Search moodle.org's
Developer Documentation

See Release Notes
Long Term Support Release

  • Bug fixes for general core bugs in 4.1.x will end 13 November 2023 (12 months).
  • Bug fixes for security issues in 4.1.x will end 10 November 2025 (36 months).
  • PHP version: minimum PHP 7.4.0 Note: minimum PHP version has increased since Moodle 4.0. PHP 8.0.x is supported too.

Differences Between: [Versions 310 and 401] [Versions 311 and 401] [Versions 39 and 401] [Versions 401 and 402] [Versions 401 and 403]

   1  <?php
   2  // This file is part of Moodle - http://moodle.org/
   3  //
   4  // Moodle is free software: you can redistribute it and/or modify
   5  // it under the terms of the GNU General Public License as published by
   6  // the Free Software Foundation, either version 3 of the License, or
   7  // (at your option) any later version.
   8  //
   9  // Moodle is distributed in the hope that it will be useful,
  10  // but WITHOUT ANY WARRANTY; without even the implied warranty of
  11  // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
  12  // GNU General Public License for more details.
  13  //
  14  // You should have received a copy of the GNU General Public License
  15  // along with Moodle.  If not, see <http://www.gnu.org/licenses/>.
  16  
  17  namespace quiz_statistics;
  18  defined('MOODLE_INTERNAL') || die();
  19  
  20  /**
  21   * Class to calculate and also manage caching of quiz statistics.
  22   *
  23   * These quiz statistics calculations are described here :
  24   *
  25   * http://docs.moodle.org/dev/Quiz_statistics_calculations#Test_statistics
  26   *
  27   * @package    quiz_statistics
  28   * @copyright  2013 The Open University
  29   * @author     James Pratt me@jamiep.org
  30   * @license    http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
  31   */
  32  class calculator {
  33  
  34      /**
  35       * @var \core\progress\base
  36       */
  37      protected $progress;
  38  
  39      public function __construct(\core\progress\base $progress = null) {
  40          if ($progress === null) {
  41              $progress = new \core\progress\none();
  42          }
  43          $this->progress = $progress;
  44      }
  45  
  46      /**
  47       * Compute the quiz statistics.
  48       *
  49       * @param int   $quizid            the quiz id.
  50       * @param int $whichattempts which attempts to use, represented internally as one of the constants as used in
  51       *                                   $quiz->grademethod ie.
  52       *                                   QUIZ_GRADEAVERAGE, QUIZ_GRADEHIGHEST, QUIZ_ATTEMPTLAST or QUIZ_ATTEMPTFIRST
  53       *                                   we calculate stats based on which attempts would affect the grade for each student.
  54       * @param \core\dml\sql_join $groupstudentsjoins Contains joins, wheres, params for students in this group.
  55       * @param int   $p                 number of positions (slots).
  56       * @param float $sumofmarkvariance sum of mark variance, calculated as part of question statistics
  57       * @return calculated $quizstats The statistics for overall attempt scores.
  58       */
  59      public function calculate($quizid, $whichattempts, \core\dml\sql_join $groupstudentsjoins, $p, $sumofmarkvariance) {
  60  
  61          $this->progress->start_progress('', 3);
  62  
  63          $quizstats = new calculated($whichattempts);
  64  
  65          $countsandaverages = $this->attempt_counts_and_averages($quizid, $groupstudentsjoins);
  66          $this->progress->progress(1);
  67  
  68          foreach ($countsandaverages as $propertyname => $value) {
  69              $quizstats->{$propertyname} = $value;
  70          }
  71  
  72          $s = $quizstats->s();
  73          if ($s != 0) {
  74  
  75              // Recalculate sql again this time possibly including test for first attempt.
  76              list($fromqa, $whereqa, $qaparams) =
  77                  quiz_statistics_attempts_sql($quizid, $groupstudentsjoins, $whichattempts);
  78  
  79              $quizstats->median = $this->median($s, $fromqa, $whereqa, $qaparams);
  80              $this->progress->progress(2);
  81  
  82              if ($s > 1) {
  83  
  84                  $powers = $this->sum_of_powers_of_difference_to_mean($quizstats->avg(), $fromqa, $whereqa, $qaparams);
  85                  $this->progress->progress(3);
  86  
  87                  $quizstats->standarddeviation = sqrt($powers->power2 / ($s - 1));
  88  
  89                  // Skewness.
  90                  if ($s > 2) {
  91                      // See http://docs.moodle.org/dev/Quiz_item_analysis_calculations_in_practise#Skewness_and_Kurtosis.
  92                      $m2 = $powers->power2 / $s;
  93                      $m3 = $powers->power3 / $s;
  94                      $m4 = $powers->power4 / $s;
  95  
  96                      $k2 = $s * $m2 / ($s - 1);
  97                      $k3 = $s * $s * $m3 / (($s - 1) * ($s - 2));
  98                      if ($k2 != 0) {
  99                          $quizstats->skewness = $k3 / (pow($k2, 3 / 2));
 100  
 101                          // Kurtosis.
 102                          if ($s > 3) {
 103                              $k4 = $s * $s * ((($s + 1) * $m4) - (3 * ($s - 1) * $m2 * $m2)) / (($s - 1) * ($s - 2) * ($s - 3));
 104                              $quizstats->kurtosis = $k4 / ($k2 * $k2);
 105                          }
 106  
 107                          if ($p > 1) {
 108                              $quizstats->cic = (100 * $p / ($p - 1)) * (1 - ($sumofmarkvariance / $k2));
 109                              $quizstats->errorratio = 100 * sqrt(1 - ($quizstats->cic / 100));
 110                              $quizstats->standarderror = $quizstats->errorratio *
 111                                  $quizstats->standarddeviation / 100;
 112                          }
 113                      }
 114  
 115                  }
 116              }
 117  
 118              $quizstats->cache(quiz_statistics_qubaids_condition($quizid, $groupstudentsjoins, $whichattempts));
 119          }
 120          $this->progress->end_progress();
 121          return $quizstats;
 122      }
 123  
 124      /** @var int No longer used. Previously the time after which statistics are automatically recomputed. */
 125      const TIME_TO_CACHE = 900; // 15 minutes.
 126  
 127      /**
 128       * Load cached statistics from the database.
 129       *
 130       * @param \qubaid_condition $qubaids
 131       * @return calculated|false The statistics for overall attempt scores or false if not cached.
 132       */
 133      public function get_cached($qubaids) {
 134          global $DB;
 135  
 136          $lastcalculatedtime = $this->get_last_calculated_time($qubaids);
 137          if (!$lastcalculatedtime) {
 138              return false;
 139          }
 140          $fromdb = $DB->get_record('quiz_statistics', ['hashcode' => $qubaids->get_hash_code(),
 141                  'timemodified' => $lastcalculatedtime]);
 142          $stats = new calculated();
 143          $stats->populate_from_record($fromdb);
 144          return $stats;
 145      }
 146  
 147      /**
 148       * Find time of non-expired statistics in the database.
 149       *
 150       * @param $qubaids \qubaid_condition
 151       * @return int|bool Time of cached record that matches this qubaid_condition or false is non found.
 152       */
 153      public function get_last_calculated_time($qubaids) {
 154          global $DB;
 155          $lastcalculatedtime = $DB->get_field('quiz_statistics', 'COALESCE(MAX(timemodified), 0)',
 156                  ['hashcode' => $qubaids->get_hash_code()]);
 157          if ($lastcalculatedtime) {
 158              return $lastcalculatedtime;
 159          } else {
 160              return false;
 161          }
 162      }
 163  
 164      /**
 165       * Given a particular quiz grading method return a lang string describing which attempts contribute to grade.
 166       *
 167       * Note internally we use the grading method constants to represent which attempts we are calculating statistics for, each
 168       * grading method corresponds to different attempts for each user.
 169       *
 170       * @param  int $whichattempts which attempts to use, represented internally as one of the constants as used in
 171       *                                   $quiz->grademethod ie.
 172       *                                   QUIZ_GRADEAVERAGE, QUIZ_GRADEHIGHEST, QUIZ_ATTEMPTLAST or QUIZ_ATTEMPTFIRST
 173       *                                   we calculate stats based on which attempts would affect the grade for each student.
 174       * @return string the appropriate lang string to describe this option.
 175       */
 176      public static function using_attempts_lang_string($whichattempts) {
 177           return get_string(static::using_attempts_string_id($whichattempts), 'quiz_statistics');
 178      }
 179  
 180      /**
 181       * Given a particular quiz grading method return a string id for use as a field name prefix in mdl_quiz_statistics or to
 182       * fetch the appropriate language string describing which attempts contribute to grade.
 183       *
 184       * Note internally we use the grading method constants to represent which attempts we are calculating statistics for, each
 185       * grading method corresponds to different attempts for each user.
 186       *
 187       * @param  int $whichattempts which attempts to use, represented internally as one of the constants as used in
 188       *                                   $quiz->grademethod ie.
 189       *                                   QUIZ_GRADEAVERAGE, QUIZ_GRADEHIGHEST, QUIZ_ATTEMPTLAST or QUIZ_ATTEMPTFIRST
 190       *                                   we calculate stats based on which attempts would affect the grade for each student.
 191       * @return string the string id for this option.
 192       */
 193      public static function using_attempts_string_id($whichattempts) {
 194          switch ($whichattempts) {
 195              case QUIZ_ATTEMPTFIRST :
 196                  return 'firstattempts';
 197              case QUIZ_GRADEHIGHEST :
 198                  return 'highestattempts';
 199              case QUIZ_ATTEMPTLAST :
 200                  return 'lastattempts';
 201              case QUIZ_GRADEAVERAGE :
 202                  return 'allattempts';
 203          }
 204      }
 205  
 206      /**
 207       * Calculating count and mean of marks for first and ALL attempts by students.
 208       *
 209       * See : http://docs.moodle.org/dev/Quiz_item_analysis_calculations_in_practise
 210       *                                      #Calculating_MEAN_of_grades_for_all_attempts_by_students
 211       * @param int $quizid
 212       * @param \core\dml\sql_join $groupstudentsjoins Contains joins, wheres, params for students in this group.
 213       * @return \stdClass with properties with count and avg with prefixes firstattempts, highestattempts, etc.
 214       */
 215      protected function attempt_counts_and_averages($quizid, \core\dml\sql_join $groupstudentsjoins) {
 216          global $DB;
 217  
 218          $attempttotals = new \stdClass();
 219          foreach (array_keys(quiz_get_grading_options()) as $which) {
 220  
 221              list($fromqa, $whereqa, $qaparams) = quiz_statistics_attempts_sql($quizid, $groupstudentsjoins, $which);
 222  
 223              $fromdb = $DB->get_record_sql("SELECT COUNT(*) AS rcount, AVG(sumgrades) AS average FROM $fromqa WHERE $whereqa",
 224                                              $qaparams);
 225              $fieldprefix = static::using_attempts_string_id($which);
 226              $attempttotals->{$fieldprefix.'avg'} = $fromdb->average;
 227              $attempttotals->{$fieldprefix.'count'} = $fromdb->rcount;
 228          }
 229          return $attempttotals;
 230      }
 231  
 232      /**
 233       * Median mark.
 234       *
 235       * http://docs.moodle.org/dev/Quiz_statistics_calculations#Median_Score
 236       *
 237       * @param $s integer count of attempts
 238       * @param $fromqa string
 239       * @param $whereqa string
 240       * @param $qaparams string
 241       * @return float
 242       */
 243      protected function median($s, $fromqa, $whereqa, $qaparams) {
 244          global $DB;
 245  
 246          if ($s % 2 == 0) {
 247              // An even number of attempts.
 248              $limitoffset = $s / 2 - 1;
 249              $limit = 2;
 250          } else {
 251              $limitoffset = floor($s / 2);
 252              $limit = 1;
 253          }
 254          $sql = "SELECT quiza.id, quiza.sumgrades
 255                    FROM $fromqa
 256                   WHERE $whereqa
 257                ORDER BY sumgrades";
 258  
 259          $medianmarks = $DB->get_records_sql_menu($sql, $qaparams, $limitoffset, $limit);
 260  
 261          return array_sum($medianmarks) / count($medianmarks);
 262      }
 263  
 264      /**
 265       * Fetch the sum of squared, cubed and to the power 4 differences between sumgrade and it's mean.
 266       *
 267       * Explanation here : http://docs.moodle.org/dev/Quiz_item_analysis_calculations_in_practise
 268       *              #Calculating_Standard_Deviation.2C_Skewness_and_Kurtosis_of_grades_for_all_attempts_by_students
 269       *
 270       * @param $mean
 271       * @param $fromqa
 272       * @param $whereqa
 273       * @param $qaparams
 274       * @return object with properties power2, power3, power4
 275       */
 276      protected function sum_of_powers_of_difference_to_mean($mean, $fromqa, $whereqa, $qaparams) {
 277          global $DB;
 278  
 279          $sql = "SELECT
 280                      SUM(POWER((quiza.sumgrades - $mean), 2)) AS power2,
 281                      SUM(POWER((quiza.sumgrades - $mean), 3)) AS power3,
 282                      SUM(POWER((quiza.sumgrades - $mean), 4)) AS power4
 283                    FROM $fromqa
 284                   WHERE $whereqa";
 285          $params = array('mean1' => $mean, 'mean2' => $mean, 'mean3' => $mean) + $qaparams;
 286  
 287          return $DB->get_record_sql($sql, $params, MUST_EXIST);
 288      }
 289  
 290  }