4dca155d66d914239c1df37530da0bc3d8dd1d00
[moodle.git] / question / classes / statistics / questions / all_calculated_for_qubaid_condition.php
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/>.
17 /**
18  * A collection of all the question statistics calculated for an activity instance ie. the stats calculated for slots and
19  * sub-questions and variants of those questions.
20  *
21  * @package    core_question
22  * @copyright  2013 The Open University
23  * @author     James Pratt me@jamiep.org
24  * @license    http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
25  */
27 namespace core_question\statistics\questions;
29 /**
30  * A collection of all the question statistics calculated for an activity instance.
31  *
32  * @package core_question
33  */
34 class all_calculated_for_qubaid_condition {
36     /**
37      * The limit of rows of sub-question and variants rows to display on main page of report before switching to showing min,
38      * median and max variants.
39      */
40     const SUBQ_AND_VARIANT_ROW_LIMIT = 10;
42     /**
43      * @var object[]
44      */
45     public $subquestions;
47     /**
48      * Holds slot (position) stats and stats for variants of questions in slots.
49      *
50      * @var calculated[]
51      */
52     public $questionstats = array();
54     /**
55      * Holds sub-question stats and stats for variants of subqs.
56      *
57      * @var calculated_for_subquestion[]
58      */
59     public $subquestionstats = array();
61     /**
62      * Set up a calculated_for_subquestion instance ready to store a randomly selected question's stats.
63      *
64      * @param object     $step
65      * @param int|null   $variant Is this to keep track of a variant's stats? If so what is the variant, if not null.
66      */
67     public function initialise_for_subq($step, $variant = null) {
68         $newsubqstat =  new calculated_for_subquestion($step, $variant);
69         if ($variant === null) {
70             $this->subquestionstats[$step->questionid] = $newsubqstat;
71         } else {
72             $this->subquestionstats[$step->questionid]->variantstats[$variant] = $newsubqstat;
73         }
74     }
76     /**
77      * Set up a calculated instance ready to store a slot question's stats.
78      *
79      * @param int      $slot
80      * @param object   $question
81      * @param int|null $variant Is this to keep track of a variant's stats? If so what is the variant, if not null.
82      */
83     public function initialise_for_slot($slot, $question, $variant = null) {
84         $newqstat = new calculated($question, $slot, $variant);
85         if ($variant === null) {
86             $this->questionstats[$slot] = $newqstat;
87         } else {
88             $this->questionstats[$slot]->variantstats[$variant] = $newqstat;
89         }
90     }
92     /**
93      * Reference for a item stats instance for a questionid and optional variant no.
94      *
95      * @param      $questionid
96      * @param int|null $variant if not null then we want the object to store a variant of a sub-question's stats.
97      * @return calculated_for_subquestion|null null if the stats object does not yet exist.
98      */
99     public function for_subq($questionid, $variant = null) {
100         if ($variant === null) {
101             if (!isset($this->subquestionstats[$questionid])) {
102                 return null;
103             } else {
104                 return $this->subquestionstats[$questionid];
105             }
106         } else {
107             if (!isset($this->subquestionstats[$questionid]->variantstats[$variant])) {
108                 return null;
109             } else {
110                 return $this->subquestionstats[$questionid]->variantstats[$variant];
111             }
112         }
113     }
115     /**
116      * ids of all randomly selected question for all slots.
117      *
118      * @return int[] An array of all sub-question ids.
119      */
120     public function get_all_subq_ids() {
121         return array_keys($this->subquestionstats);
122     }
124     /**
125      * All slots nos that stats have been calculated for.
126      *
127      * @return int[] An array of all slot nos.
128      */
129     public function get_all_slots() {
130         return array_keys($this->questionstats);
131     }
133     /**
134      * Array of variants of one randomly selected question that have appeared in the attempt data.
135      *
136      * @param $questionid
137      * @return int[]
138      */
139     public function get_variants_for_subq($questionid) {
140         if (count($this->subquestionstats[$questionid]->variantstats) > 1) {
141             return array_keys($this->subquestionstats[$questionid]->variantstats);
142         } else {
143             return false;
144         }
145     }
147     /**
148      * Array of variants that have appeared in the attempt data for a question in one slot.
149      *
150      * @param $slot
151      * @return int[]
152      */
153     public function get_variants_for_slot($slot) {
154         if (count($this->questionstats[$slot]->variantstats) > 1) {
155             return array_keys($this->questionstats[$slot]->variantstats);
156         } else {
157             return false;
158         }
159     }
161     /**
162      * Reference to position stats instance for a slot and optional variant no.
163      *
164      * @param      $slot
165      * @param null $variant if provided then we want the object which stores a variant of a position's stats.
166      * @return calculated|null
167      */
168     public function for_slot($slot, $variant = null) {
169         if ($variant === null) {
170             if (!isset($this->questionstats[$slot])) {
171                 return null;
172             } else {
173                 return $this->questionstats[$slot];
174             }
175         } else {
176             if (!isset($this->questionstats[$slot]->variantstats[$variant])) {
177                 return null;
178             } else {
179                 return $this->questionstats[$slot]->variantstats[$variant];
180             }
181         }
182     }
184     /**
185      * Load cached statistics from the database.
186      *
187      * @param $qubaids \qubaid_condition
188      */
189     public function get_cached($qubaids) {
190         global $DB;
192         $timemodified = time() - self::TIME_TO_CACHE;
193         $questionstatrecs = $DB->get_records_select('question_statistics', 'hashcode = ? AND timemodified > ?',
194                                                     array($qubaids->get_hash_code(), $timemodified));
196         $questionids = array();
197         foreach ($questionstatrecs as $fromdb) {
198             if (is_null($fromdb->variant) && !$fromdb->slot) {
199                 $questionids[] = $fromdb->questionid;
200             }
201         }
202         $this->subquestions = question_load_questions($questionids);
203         foreach ($questionstatrecs as $fromdb) {
204             if (is_null($fromdb->variant)) {
205                 if ($fromdb->slot) {
206                     $this->questionstats[$fromdb->slot]->populate_from_record($fromdb);
207                     // Array created in constructor and populated from question.
208                 } else {
209                     $this->subquestionstats[$fromdb->questionid] = new calculated_for_subquestion();
210                     $this->subquestionstats[$fromdb->questionid]->populate_from_record($fromdb);
211                     $this->subquestionstats[$fromdb->questionid]->question = $this->subquestions[$fromdb->questionid];
212                 }
213             }
214         }
215         // Add cached variant stats to data structure.
216         foreach ($questionstatrecs as $fromdb) {
217             if (!is_null($fromdb->variant)) {
218                 if ($fromdb->slot) {
219                     $newcalcinstance = new calculated();
220                     $this->questionstats[$fromdb->slot]->variantstats[$fromdb->variant] = $newcalcinstance;
221                     $newcalcinstance->question = $this->questionstats[$fromdb->slot]->question;
222                 } else {
223                     $newcalcinstance = new calculated_for_subquestion();
224                     $this->subquestionstats[$fromdb->questionid]->variantstats[$fromdb->variant] = $newcalcinstance;
225                     $newcalcinstance->question = $this->subquestions[$fromdb->questionid];
226                 }
227                 $newcalcinstance->populate_from_record($fromdb);
228             }
229         }
230     }
232     /**
233      * Find time of non-expired statistics in the database.
234      *
235      * @param $qubaids \qubaid_condition
236      * @return int|bool Time of cached record that matches this qubaid_condition or false is non found.
237      */
238     public function get_last_calculated_time($qubaids) {
239         global $DB;
241         $timemodified = time() - self::TIME_TO_CACHE;
242         return $DB->get_field_select('question_statistics', 'timemodified', 'hashcode = ? AND timemodified > ?',
243                                      array($qubaids->get_hash_code(), $timemodified), IGNORE_MULTIPLE);
244     }
246     /** @var integer Time after which statistics are automatically recomputed. */
247     const TIME_TO_CACHE = 900; // 15 minutes.
249     /**
250      * Save stats to db.
251      *
252      * @param $qubaids \qubaid_condition
253      */
254     public function cache($qubaids) {
255         foreach ($this->get_all_slots() as $slot) {
256             $this->for_slot($slot)->cache($qubaids);
257         }
259         foreach ($this->get_all_subq_ids() as $subqid) {
260             $this->for_subq($subqid)->cache($qubaids);
261         }
262     }
264     /**
265      * Return all sub-questions used.
266      *
267      * @return \object[] array of questions.
268      */
269     public function get_sub_questions() {
270         return $this->subquestions;
271     }
273     /**
274      * Are there too many rows of sub-questions and / or variant rows.
275      *
276      * @param array $rows the rows we intend to add.
277      * @return bool
278      */
279     protected function too_many_subq_and_or_variant_rows($rows) {
280         return (count($rows) > static::SUBQ_AND_VARIANT_ROW_LIMIT);
281     }
283     /**
284      * From a number of calculated instances find the three instances with min, median and maximum facility index values.
285      *
286      * @param calculated[] $questionstats
287      * @return calculated[] 3 stat objects with minimum, median and maximum facility index.
288      */
289     protected function find_min_median_and_max_facility_stats_objects($questionstats) {
290         $facilities = array();
291         foreach ($questionstats as $key => $questionstat) {
292             $facilities[$key] = (float)$questionstat->facility;
293         }
294         asort($facilities);
295         $facilitykeys = array_keys($facilities);
296         $keyformin = $facilitykeys[0];
297         $keyformedian = $facilitykeys[(int)(round(count($facilitykeys) / 2)-1)];
298         $keyformax = $facilitykeys[count($facilitykeys) - 1];
299         $toreturn = array();
300         foreach (array($keyformin => 'minimumfacility',
301                        $keyformedian => 'medianfacility',
302                        $keyformax => 'maximumfacility') as $key => $stringid) {
303             $questionstats[$key]->minmedianmaxnotice = $stringid;
304             $toreturn[] = $questionstats[$key];
305         }
306         return $toreturn;
307     }
309     /**
310      * Return all stats for variants of question in slot $slot.
311      *
312      * @param int $slot
313      * @return calculated[]
314      */
315     protected function all_variant_stats_for_one_slot($slot) {
316         $toreturn = array();
317         if ($variants = $this->get_variants_for_slot($slot)){
318             foreach ($variants as $variant) {
319                 $toreturn[] = $this->for_slot($slot, $variant);
320             }
321         }
322         return $toreturn;
323     }
325     /**
326      * Return all stats for variants of randomly selected questions for one slot $slot.
327      *
328      * @param int $slot
329      * @return calculated[]
330      */
331     protected function all_subq_variants_for_one_slot($slot) {
332         $toreturn = array();
333         $displayorder = 1;
334         foreach ($this->for_slot($slot)->get_sub_question_ids() as $subqid) {
335             if ($variants = $this->get_variants_for_subq($subqid)) {
336                 foreach ($variants as $variant) {
337                     $toreturn[] = $this->make_new_subq_stat_for($displayorder, $slot, $subqid, $variant);
338                 }
339             }
340             $displayorder++;
341         }
342         return $toreturn;
343     }
345     /**
346      * Return all stats for randomly selected questions for one slot $slot.
347      *
348      * @param int $slot
349      * @return calculated[]
350      */
351     protected function all_subqs_for_one_slot($slot) {
352         $displayorder = 1;
353         $toreturn = array();
354         foreach ($this->for_slot($slot)->get_sub_question_ids() as $subqid) {
355             $toreturn[] = $this->make_new_subq_stat_for($displayorder, $slot, $subqid);
356             $displayorder++;
357         }
358         return $toreturn;
359     }
361     /**
362      * Return all variant or 'sub-question' stats one slot, either :
363      *  - variants of question
364      *  - variants of randomly selected questions
365      *  - randomly selected questions
366      *
367      * @param int $slot
368      * @param bool $limited
369      * @return calculated[]
370      */
371     public function all_subq_and_variant_stats_for_slot($slot, $limited) {
372         // Random question in this slot?
373         if ($this->for_slot($slot)->get_sub_question_ids()) {
374             if ($limited) {
375                 $subqvariantstats = $this->all_subq_variants_for_one_slot($slot);
376                 if ($this->too_many_subq_and_or_variant_rows($subqvariantstats)) {
377                     // Too many variants from randomly selected questions.
378                     return $this->find_min_median_and_max_facility_stats_objects($subqvariantstats);
379                 }
380                 $subqstats = $this->all_subqs_for_one_slot($slot);
381                 if ($this->too_many_subq_and_or_variant_rows($subqstats)) {
382                     // Too many randomly selected questions.
383                     return $this->find_min_median_and_max_facility_stats_objects($subqstats);
384                 }
385             }
386             $toreturn = array();
387             $displaynumber = 1;
388             foreach ($this->for_slot($slot)->get_sub_question_ids() as $subqid) {
389                 $toreturn[] = $this->make_new_subq_stat_for($displaynumber, $slot, $subqid);
390                 if ($variants = $this->get_variants_for_subq($subqid)) {
391                     foreach ($variants as $variant) {
392                         $toreturn[] = $this->make_new_subq_stat_for($displaynumber, $slot, $subqid, $variant);
393                     }
394                 }
395                 $displaynumber++;
396             }
397             return $toreturn;
398         } else {
399             $variantstats = $this->all_variant_stats_for_one_slot($slot);
400             if ($limited && $this->too_many_subq_and_or_variant_rows($variantstats)) {
401                 return $this->find_min_median_and_max_facility_stats_objects($variantstats);
402             } else {
403                 return $variantstats;
404             }
405         }
407     }
409     /**
410      * We need a new object for display. Sub-question stats can appear more than once in different slots.
411      * So we create a clone of the object and then we can set properties on the object that are per slot.
412      *
413      * @param      $displaynumber
414      * @param      $slot
415      * @param      $subqid
416      * @param null $variant
417      * @return calculated_for_subquestion|null
418      */
419     protected function make_new_subq_stat_for($displaynumber, $slot, $subqid, $variant = null) {
420         $slotstat = fullclone($this->for_subq($subqid, $variant));
421         $slotstat->question->number = $this->for_slot($slot)->question->number;
422         $slotstat->subqdisplayorder = $displaynumber;
423         return $slotstat;
424     }
426     /**
427      * Call after calculations to output any error messages.
428      *
429      * @return string[] Array of strings describing error messages found during stats calculation.
430      */
431     public function any_error_messages() {
432         $errors = array();
433         foreach ($this->get_all_slots() as $slot) {
434             foreach ($this->for_slot($slot)->get_sub_question_ids() as $subqid) {
435                 if ($this->for_subq($subqid)->differentweights) {
436                     $name = $this->for_subq($subqid)->question->name;
437                     $errors[] = get_string('erroritemappearsmorethanoncewithdifferentweight', 'quiz_statistics', $name);
438                 }
439             }
440         }
441         return $errors;
443     }