3 // This file is part of Moodle - http://moodle.org/
5 // Moodle is free software: you can redistribute it and/or modify
6 // it under the terms of the GNU General Public License as published by
7 // the Free Software Foundation, either version 3 of the License, or
8 // (at your option) any later version.
10 // Moodle is distributed in the hope that it will be useful,
11 // but WITHOUT ANY WARRANTY; without even the implied warranty of
12 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 // GNU General Public License for more details.
15 // You should have received a copy of the GNU General Public License
16 // along with Moodle. If not, see <http://www.gnu.org/licenses/>.
19 * Contains logic class and interface for the grading evaluation plugin "Comparison
20 * with the best assessment".
22 * @package workshopeval
24 * @copyright 2009 David Mudrak <david.mudrak@gmail.com>
25 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
28 defined('MOODLE_INTERNAL') || die();
30 require_once(dirname(dirname(__FILE__)) . '/lib.php'); // interface definition
31 require_once($CFG->libdir . '/gradelib.php');
34 * Defines the computation login of the grading evaluation subplugin
36 class workshop_best_evaluation extends workshop_evaluation {
38 /** @var workshop the parent workshop instance */
41 /** @var the recently used settings in this workshop */
47 * @param workshop $workshop The workshop api instance
50 public function __construct(workshop $workshop) {
52 $this->workshop = $workshop;
53 $this->settings = $DB->get_record('workshopeval_best_settings', array('workshopid' => $this->workshop->id));
57 * Calculates the grades for assessment and updates 'gradinggrade' fields in 'workshop_assessments' table
59 * This function relies on the grading strategy subplugin providing get_assessments_recordset() method.
60 * {@see self::process_assessments()} for the required structure of the recordset.
62 * @param stdClass $settings The settings for this round of evaluation
63 * @param null|int|array $restrict If null, update all reviewers, otherwise update just grades for the given reviewers(s)
67 public function update_grading_grades(stdclass $settings, $restrict=null) {
70 // Remember the recently used settings for this workshop.
71 if (empty($this->settings)) {
72 $record = new stdclass();
73 $record->workshopid = $this->workshop->id;
74 $record->comparison = $settings->comparison;
75 $DB->insert_record('workshopeval_best_settings', $record);
76 } elseif ($this->settings->comparison != $settings->comparison) {
77 $DB->set_field('workshopeval_best_settings', 'comparison', $settings->comparison,
78 array('workshopid' => $this->workshop->id));
81 // Get the grading strategy instance.
82 $grader = $this->workshop->grading_strategy_instance();
84 // get the information about the assessment dimensions
85 $diminfo = $grader->get_dimensions_info();
87 // fetch a recordset with all assessments to process
88 $rs = $grader->get_assessments_recordset($restrict);
89 $batch = array(); // will contain a set of all assessments of a single submission
90 $previous = null; // a previous record in the recordset
91 foreach ($rs as $current) {
92 if (is_null($previous)) {
93 // we are processing the very first record in the recordset
96 if ($current->submissionid == $previous->submissionid) {
99 // process all the assessments of a single submission
100 $this->process_assessments($batch, $diminfo, $settings);
101 // start with a new batch to be processed
102 $batch = array($current);
103 $previous = $current;
106 // do not forget to process the last batch!
107 $this->process_assessments($batch, $diminfo, $settings);
112 * Returns an instance of the form to provide evaluation settings.
114 * @return workshop_best_evaluation_settings_form
116 public function get_settings_form(moodle_url $actionurl=null) {
118 $customdata['workshop'] = $this->workshop;
119 $customdata['current'] = $this->settings;
120 $attributes = array('class' => 'evalsettingsform best');
122 return new workshop_best_evaluation_settings_form($actionurl, $customdata, 'post', '', $attributes);
126 * Delete all data related to a given workshop module instance
128 * @see workshop_delete_instance()
129 * @param int $workshopid id of the workshop module instance being deleted
132 public static function delete_instance($workshopid) {
135 $DB->delete_records('workshopeval_best_settings', array('workshopid' => $workshopid));
138 ////////////////////////////////////////////////////////////////////////////////
139 // Internal methods //
140 ////////////////////////////////////////////////////////////////////////////////
143 * Given a list of all assessments of a single submission, updates the grading grades in database
145 * @param array $assessments of stdclass (->assessmentid ->assessmentweight ->reviewerid ->gradinggrade ->submissionid ->dimensionid ->grade)
146 * @param array $diminfo of stdclass (->id ->weight ->max ->min)
147 * @param stdClass grading evaluation settings
150 protected function process_assessments(array $assessments, array $diminfo, stdclass $settings) {
153 if (empty($assessments)) {
157 // reindex the passed flat structure to be indexed by assessmentid
158 $assessments = $this->prepare_data_from_recordset($assessments);
160 // normalize the dimension grades to the interval 0 - 100
161 $assessments = $this->normalize_grades($assessments, $diminfo);
163 // get a hypothetical average assessment
164 $average = $this->average_assessment($assessments);
166 // calculate variance of dimension grades
167 $variances = $this->weighted_variance($assessments);
168 foreach ($variances as $dimid => $variance) {
169 $diminfo[$dimid]->variance = $variance;
172 // for every assessment, calculate its distance from the average one
173 $distances = array();
174 foreach ($assessments as $asid => $assessment) {
175 $distances[$asid] = $this->assessments_distance($assessment, $average, $diminfo, $settings);
178 // identify the best assessments - that is those with the shortest distance from the best assessment
179 $bestids = array_keys($distances, min($distances));
181 // for every assessment, calculate its distance from the nearest best assessment
182 $distances = array();
183 foreach ($bestids as $bestid) {
184 $best = $assessments[$bestid];
185 foreach ($assessments as $asid => $assessment) {
186 $d = $this->assessments_distance($assessment, $best, $diminfo, $settings);
187 if (!is_null($d) and (!isset($distances[$asid]) or $d < $distances[$asid])) {
188 $distances[$asid] = $d;
193 // calculate the grading grade
194 foreach ($distances as $asid => $distance) {
195 $gradinggrade = (100 - $distance);
196 if ($gradinggrade < 0) {
199 if ($gradinggrade > 100) {
202 $grades[$asid] = grade_floatval($gradinggrade);
205 // if the new grading grade differs from the one stored in database, update it
206 // we do not use set_field() here because we want to pass $bulk param
207 foreach ($grades as $assessmentid => $grade) {
208 if (grade_floats_different($grade, $assessments[$assessmentid]->gradinggrade)) {
209 // the value has changed
210 $record = new stdclass();
211 $record->id = $assessmentid;
212 $record->gradinggrade = grade_floatval($grade);
213 // do not set timemodified here, it contains the timestamp of when the form was
214 // saved by the peer reviewer, not when it was aggregated
215 $DB->update_record('workshop_assessments', $record, true); // bulk operations expected
219 // done. easy, heh? ;-)
223 * Prepares a structure of assessments and given grades
225 * @param array $assessments batch of recordset items as returned by the grading strategy
228 protected function prepare_data_from_recordset($assessments) {
229 $data = array(); // to be returned
230 foreach ($assessments as $a) {
231 $id = $a->assessmentid; // just an abbreviation
232 if (!isset($data[$id])) {
233 $data[$id] = new stdclass();
234 $data[$id]->assessmentid = $a->assessmentid;
235 $data[$id]->weight = $a->assessmentweight;
236 $data[$id]->reviewerid = $a->reviewerid;
237 $data[$id]->gradinggrade = $a->gradinggrade;
238 $data[$id]->submissionid = $a->submissionid;
239 $data[$id]->dimgrades = array();
241 $data[$id]->dimgrades[$a->dimensionid] = $a->grade;
247 * Normalizes the dimension grades to the interval 0.00000 - 100.00000
249 * Note: this heavily relies on PHP5 way of handling references in array of stdclasses. Hopefully
250 * it will not change again soon.
252 * @param array $assessments of stdclass as returned by {@see self::prepare_data_from_recordset()}
253 * @param array $diminfo of stdclass
254 * @return array of stdclass with the same structure as $assessments
256 protected function normalize_grades(array $assessments, array $diminfo) {
257 foreach ($assessments as $asid => $assessment) {
258 foreach ($assessment->dimgrades as $dimid => $dimgrade) {
259 $dimmin = $diminfo[$dimid]->min;
260 $dimmax = $diminfo[$dimid]->max;
261 if ($dimmin == $dimmax) {
262 $assessment->dimgrades[$dimid] = grade_floatval($dimmax);
264 $assessment->dimgrades[$dimid] = grade_floatval(($dimgrade - $dimmin) / ($dimmax - $dimmin) * 100);
272 * Given a set of a submission's assessments, returns a hypothetical average assessment
274 * The passed structure must be array of assessments objects with ->weight and ->dimgrades properties.
276 * @param array $assessments as prepared by {@link self::prepare_data_from_recordset()}
277 * @return null|stdClass
279 protected function average_assessment(array $assessments) {
280 $sumdimgrades = array();
281 foreach ($assessments as $a) {
282 foreach ($a->dimgrades as $dimid => $dimgrade) {
283 if (!isset($sumdimgrades[$dimid])) {
284 $sumdimgrades[$dimid] = 0;
286 $sumdimgrades[$dimid] += $dimgrade * $a->weight;
291 foreach ($assessments as $a) {
292 $sumweights += $a->weight;
294 if ($sumweights == 0) {
295 // unable to calculate average assessment
299 $average = new stdclass();
300 $average->dimgrades = array();
301 foreach ($sumdimgrades as $dimid => $sumdimgrade) {
302 $average->dimgrades[$dimid] = grade_floatval($sumdimgrade / $sumweights);
308 * Given a set of a submission's assessments, returns standard deviations of all their dimensions
310 * The passed structure must be array of assessments objects with at least ->weight
311 * and ->dimgrades properties. This implementation uses weighted incremental algorithm as
312 * suggested in "D. H. D. West (1979). Communications of the ACM, 22, 9, 532-535:
313 * Updating Mean and Variance Estimates: An Improved Method"
314 * {@link http://en.wikipedia.org/wiki/Algorithms_for_calculating_variance#Weighted_incremental_algorithm}
316 * @param array $assessments as prepared by {@link self::prepare_data_from_recordset()}
317 * @return null|array indexed by dimension id
319 protected function weighted_variance(array $assessments) {
320 $first = reset($assessments);
324 $dimids = array_keys($first->dimgrades);
325 $asids = array_keys($assessments);
326 $vars = array(); // to be returned
327 foreach ($dimids as $dimid) {
331 foreach ($asids as $asid) {
332 $x = $assessments[$asid]->dimgrades[$dimid]; // value (data point)
333 $weight = $assessments[$asid]->weight; // the values' weight
341 $sumweight = $weight;
344 $temp = $weight + $sumweight;
346 $r = $q * $weight / $temp;
347 $s = $s + $sumweight * $q * $r;
352 if ($sumweight > 0 and $n > 1) {
353 // for the sample: $vars[$dimid] = ($s * $n) / (($n - 1) * $sumweight);
354 // for the population:
355 $vars[$dimid] = $s / $sumweight;
357 $vars[$dimid] = null;
364 * Measures the distance of the assessment from a referential one
366 * The passed data structures must contain ->dimgrades property. The referential
367 * assessment is supposed to be close to the average assessment. All dimension grades are supposed to be
368 * normalized to the interval 0 - 100.
369 * Returned value is rounded to 4 valid decimals to prevent some rounding issues - see the unit test
372 * @param stdClass $assessment the assessment being measured
373 * @param stdClass $referential assessment
374 * @param array $diminfo of stdclass(->weight ->min ->max ->variance) indexed by dimension id
375 * @param stdClass $settings
376 * @return float|null rounded to 4 valid decimals
378 protected function assessments_distance(stdclass $assessment, stdclass $referential, array $diminfo, stdclass $settings) {
381 foreach (array_keys($assessment->dimgrades) as $dimid) {
382 $agrade = $assessment->dimgrades[$dimid];
383 $rgrade = $referential->dimgrades[$dimid];
384 $var = $diminfo[$dimid]->variance;
385 $weight = $diminfo[$dimid]->weight;
388 // variations very close to zero are too sensitive to a small change of data values
389 if ($var > 0.01 and $agrade != $rgrade) {
390 $absdelta = abs($agrade - $rgrade);
391 $reldelta = pow($agrade - $rgrade, 2) / ($settings->comparison * $var);
392 $distance += $absdelta * $reldelta * $weight;
396 // average distance across all dimensions
397 return round($distance / $n, 4);
406 * Represents the settings form for this plugin.
408 class workshop_best_evaluation_settings_form extends workshop_evaluation_settings_form {
411 * Defines specific fields for this evaluation method.
413 protected function definition_sub() {
414 $mform = $this->_form;
416 $plugindefaults = get_config('workshopeval_best');
417 $current = $this->_customdata['current'];
420 for ($i = 9; $i >= 1; $i = $i-2) {
421 $options[$i] = get_string('comparisonlevel' . $i, 'workshopeval_best');
423 $mform->addElement('select', 'comparison', get_string('comparison', 'workshopeval_best'), $options);
424 $mform->addHelpButton('comparison', 'comparison', 'workshopeval_best');
425 $mform->setDefault('comparison', $plugindefaults->comparison);
427 $this->set_data($current);