Search moodle.org's
Developer Documentation

See Release Notes

  • Bug fixes for general core bugs in 3.11.x will end 14 Nov 2022 (12 months plus 6 months extension).
  • Bug fixes for security issues in 3.11.x will end 13 Nov 2023 (18 months plus 12 months extension).
  • PHP version: minimum PHP 7.3.0 Note: minimum PHP version has increased since Moodle 3.10. PHP 7.4.x is supported too.

Differences Between: [Versions 311 and 400] [Versions 311 and 401] [Versions 311 and 402] [Versions 311 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 integer 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 $qubaids \qubaid_condition
 131       * @return calculated The statistics for overall attempt scores or false if not cached.
 132       */
 133      public function get_cached($qubaids) {
 134          global $DB;
 135  
 136          $timemodified = time() - self::TIME_TO_CACHE;
 137          $fromdb = $DB->get_record_select('quiz_statistics', 'hashcode = ? AND timemodified > ?',
 138                                           array($qubaids->get_hash_code(), $timemodified));
 139          $stats = new calculated();
 140          $stats->populate_from_record($fromdb);
 141          return $stats;
 142      }
 143  
 144      /**
 145       * Find time of non-expired statistics in the database.
 146       *
 147       * @param $qubaids \qubaid_condition
 148       * @return integer|boolean Time of cached record that matches this qubaid_condition or false is non found.
 149       */
 150      public function get_last_calculated_time($qubaids) {
 151          global $DB;
 152  
 153          $timemodified = time() - self::TIME_TO_CACHE;
 154          return $DB->get_field_select('quiz_statistics', 'timemodified', 'hashcode = ? AND timemodified > ?',
 155                                           array($qubaids->get_hash_code(), $timemodified));
 156      }
 157  
 158      /**
 159       * Given a particular quiz grading method return a lang string describing which attempts contribute to grade.
 160       *
 161       * Note internally we use the grading method constants to represent which attempts we are calculating statistics for, each
 162       * grading method corresponds to different attempts for each user.
 163       *
 164       * @param  int $whichattempts which attempts to use, represented internally as one of the constants as used in
 165       *                                   $quiz->grademethod ie.
 166       *                                   QUIZ_GRADEAVERAGE, QUIZ_GRADEHIGHEST, QUIZ_ATTEMPTLAST or QUIZ_ATTEMPTFIRST
 167       *                                   we calculate stats based on which attempts would affect the grade for each student.
 168       * @return string the appropriate lang string to describe this option.
 169       */
 170      public static function using_attempts_lang_string($whichattempts) {
 171           return get_string(static::using_attempts_string_id($whichattempts), 'quiz_statistics');
 172      }
 173  
 174      /**
 175       * Given a particular quiz grading method return a string id for use as a field name prefix in mdl_quiz_statistics or to
 176       * fetch the appropriate language string describing which attempts contribute to grade.
 177       *
 178       * Note internally we use the grading method constants to represent which attempts we are calculating statistics for, each
 179       * grading method corresponds to different attempts for each user.
 180       *
 181       * @param  int $whichattempts which attempts to use, represented internally as one of the constants as used in
 182       *                                   $quiz->grademethod ie.
 183       *                                   QUIZ_GRADEAVERAGE, QUIZ_GRADEHIGHEST, QUIZ_ATTEMPTLAST or QUIZ_ATTEMPTFIRST
 184       *                                   we calculate stats based on which attempts would affect the grade for each student.
 185       * @return string the string id for this option.
 186       */
 187      public static function using_attempts_string_id($whichattempts) {
 188          switch ($whichattempts) {
 189              case QUIZ_ATTEMPTFIRST :
 190                  return 'firstattempts';
 191              case QUIZ_GRADEHIGHEST :
 192                  return 'highestattempts';
 193              case QUIZ_ATTEMPTLAST :
 194                  return 'lastattempts';
 195              case QUIZ_GRADEAVERAGE :
 196                  return 'allattempts';
 197          }
 198      }
 199  
 200      /**
 201       * Calculating count and mean of marks for first and ALL attempts by students.
 202       *
 203       * See : http://docs.moodle.org/dev/Quiz_item_analysis_calculations_in_practise
 204       *                                      #Calculating_MEAN_of_grades_for_all_attempts_by_students
 205       * @param int $quizid
 206       * @param \core\dml\sql_join $groupstudentsjoins Contains joins, wheres, params for students in this group.
 207       * @return \stdClass with properties with count and avg with prefixes firstattempts, highestattempts, etc.
 208       */
 209      protected function attempt_counts_and_averages($quizid, \core\dml\sql_join $groupstudentsjoins) {
 210          global $DB;
 211  
 212          $attempttotals = new \stdClass();
 213          foreach (array_keys(quiz_get_grading_options()) as $which) {
 214  
 215              list($fromqa, $whereqa, $qaparams) = quiz_statistics_attempts_sql($quizid, $groupstudentsjoins, $which);
 216  
 217              $fromdb = $DB->get_record_sql("SELECT COUNT(*) AS rcount, AVG(sumgrades) AS average FROM $fromqa WHERE $whereqa",
 218                                              $qaparams);
 219              $fieldprefix = static::using_attempts_string_id($which);
 220              $attempttotals->{$fieldprefix.'avg'} = $fromdb->average;
 221              $attempttotals->{$fieldprefix.'count'} = $fromdb->rcount;
 222          }
 223          return $attempttotals;
 224      }
 225  
 226      /**
 227       * Median mark.
 228       *
 229       * http://docs.moodle.org/dev/Quiz_statistics_calculations#Median_Score
 230       *
 231       * @param $s integer count of attempts
 232       * @param $fromqa string
 233       * @param $whereqa string
 234       * @param $qaparams string
 235       * @return float
 236       */
 237      protected function median($s, $fromqa, $whereqa, $qaparams) {
 238          global $DB;
 239  
 240          if ($s % 2 == 0) {
 241              // An even number of attempts.
 242              $limitoffset = $s / 2 - 1;
 243              $limit = 2;
 244          } else {
 245              $limitoffset = floor($s / 2);
 246              $limit = 1;
 247          }
 248          $sql = "SELECT quiza.id, quiza.sumgrades
 249                    FROM $fromqa
 250                   WHERE $whereqa
 251                ORDER BY sumgrades";
 252  
 253          $medianmarks = $DB->get_records_sql_menu($sql, $qaparams, $limitoffset, $limit);
 254  
 255          return array_sum($medianmarks) / count($medianmarks);
 256      }
 257  
 258      /**
 259       * Fetch the sum of squared, cubed and to the power 4 differences between sumgrade and it's mean.
 260       *
 261       * Explanation here : http://docs.moodle.org/dev/Quiz_item_analysis_calculations_in_practise
 262       *              #Calculating_Standard_Deviation.2C_Skewness_and_Kurtosis_of_grades_for_all_attempts_by_students
 263       *
 264       * @param $mean
 265       * @param $fromqa
 266       * @param $whereqa
 267       * @param $qaparams
 268       * @return object with properties power2, power3, power4
 269       */
 270      protected function sum_of_powers_of_difference_to_mean($mean, $fromqa, $whereqa, $qaparams) {
 271          global $DB;
 272  
 273          $sql = "SELECT
 274                      SUM(POWER((quiza.sumgrades - $mean), 2)) AS power2,
 275                      SUM(POWER((quiza.sumgrades - $mean), 3)) AS power3,
 276                      SUM(POWER((quiza.sumgrades - $mean), 4)) AS power4
 277                    FROM $fromqa
 278                   WHERE $whereqa";
 279          $params = array('mean1' => $mean, 'mean2' => $mean, 'mean3' => $mean) + $qaparams;
 280  
 281          return $DB->get_record_sql($sql, $params, MUST_EXIST);
 282      }
 283  
 284  }