d0bd87c7607a7444238c788c4f95d3fcfdc5c7f3
[moodle.git] / mod / quiz / report / statistics / tests / stats_from_steps_walkthrough_test.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  * Quiz attempt walk through using data from csv file.
19  *
20  * @package    quiz_statistics
21  * @category   phpunit
22  * @copyright  2013 The Open University
23  * @author     Jamie Pratt <me@jamiep.org>
24  * @license    http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
25  */
27 defined('MOODLE_INTERNAL') || die();
29 global $CFG;
30 require_once($CFG->dirroot . '/mod/quiz/tests/attempt_walkthrough_from_csv_test.php');
31 require_once($CFG->dirroot . '/mod/quiz/report/default.php');
32 require_once($CFG->dirroot . '/mod/quiz/report/statistics/report.php');
33 require_once($CFG->dirroot . '/mod/quiz/report/reportlib.php');
35 /**
36  * Quiz attempt walk through using data from csv file.
37  *
38  * @package    quiz_statistics
39  * @category   phpunit
40  * @copyright  2013 The Open University
41  * @author     Jamie Pratt <me@jamiep.org>
42  * @license    http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
43  */
44 class quiz_report_statistics_from_steps_testcase extends mod_quiz_attempt_walkthrough_from_csv_testcase {
46     /**
47      * @var quiz_statistics_report object to do stats calculations.
48      */
49     protected $report;
51     protected function get_full_path_of_csv_file($setname, $test) {
52         // Overridden here so that __DIR__ points to the path of this file.
53         return  __DIR__."/fixtures/{$setname}{$test}.csv";
54     }
56     protected $files = array('questions', 'steps', 'results', 'qstats', 'responsecounts');
58     /**
59      * Create a quiz add questions to it, walk through quiz attempts and then check results.
60      *
61      * @param PHPUnit_Extensions_Database_DataSet_ITable[] of data read from csv file "questionsXX.csv",
62      *                                                                                  "stepsXX.csv" and "resultsXX.csv".
63      * @dataProvider get_data_for_walkthrough
64      */
65     public function test_walkthrough_from_csv($quizsettings, $csvdata) {
67         // CSV data files for these tests were generated using :
68         // https://github.com/jamiepratt/moodle-quiz-tools/tree/master/responsegenerator
70         $this->resetAfterTest(true);
71         question_bank::get_qtype('random')->clear_caches_before_testing();
73         $this->create_quiz($quizsettings, $csvdata['questions']);
75         $attemptids = $this->walkthrough_attempts($csvdata['steps']);
77         $this->check_attempts_results($csvdata['results'], $attemptids);
79         $this->report = new quiz_statistics_report();
80         $whichattempts = QUIZ_GRADEAVERAGE;
81         $groupstudents = array();
82         $questions = $this->report->load_and_initialise_questions_for_calculations($this->quiz);
83         list($quizstats, $questionstats) =
84                         $this->report->get_all_stats_and_analysis($this->quiz, $whichattempts, $groupstudents, $questions);
86         $qubaids = quiz_statistics_qubaids_condition($this->quiz->id, $groupstudents, $whichattempts);
88         // We will create some quiz and question stat calculator instances and some response analyser instances, just in order
89         // to check the last analysed time then returned.
90         $quizcalc = new \quiz_statistics\calculator();
91         // Should not be a delay of more than one second between the calculation of stats above and here.
92         $this->assertTimeCurrent($quizcalc->get_last_calculated_time($qubaids));
94         $qcalc = new \core_question\statistics\questions\calculator($questions);
95         $this->assertTimeCurrent($qcalc->get_last_calculated_time($qubaids));
97         foreach ($questions as $question) {
98             $qtypeobj = question_bank::get_qtype($question->qtype, false);
99             if (!$qtypeobj->can_analyse_responses()) {
100                 continue;
101             }
102             $responesstats = new \core_question\statistics\responses\analyser($question);
103             $this->assertTimeCurrent($responesstats->get_last_analysed_time($qubaids));
104         }
106         for ($rowno = 0; $rowno < $csvdata['responsecounts']->getRowCount(); $rowno++) {
107             $responsecount = $csvdata['responsecounts']->getRow($rowno);
108             if ($responsecount['randq'] == '') {
109                 $question = $questions[$responsecount['slot']];
110             } else {
111                 $qid = $this->randqids[$responsecount['slot']][$responsecount['randq']];
112                 $question = question_finder::get_instance()->load_question_data($qid);
113             }
114             $this->assert_response_count_equals($question, $qubaids, $responsecount);
115         }
117             // These quiz stats and the question stats found in qstats00.csv were calculated independently in spreadsheet which is
118         // available in open document or excel format here :
119         // https://github.com/jamiepratt/moodle-quiz-tools/tree/master/statsspreadsheet
120         $quizstatsexpected = array(
121             'median' => 4.5,
122             'firstattemptsavg' => 4.617333332,
123             'allattemptsavg' => 4.617333332,
124             'firstattemptscount' => 25,
125             'allattemptscount' => 25,
126             'standarddeviation' => 0.8117265554,
127             'skewness' => -0.092502502,
128             'kurtosis' => -0.7073968557,
129             'cic' => -87.2230935542,
130             'errorratio' => 136.8294900795,
131             'standarderror' => 1.1106813066
132         );
134         foreach ($quizstatsexpected as $statname => $statvalue) {
135             $this->assertEquals($statvalue, $quizstats->$statname, $quizstats->$statname, abs($statvalue) * 1.5e-5);
136         }
138         for ($rowno = 0; $rowno < $csvdata['qstats']->getRowCount(); $rowno++) {
139             $slotqstats = $csvdata['qstats']->getRow($rowno);
140             foreach ($slotqstats as $statname => $slotqstat) {
141                 if ($statname !== 'slot') {
142                     $this->assert_stat_equals($questionstats, $slotqstats['slot'], null, null, $statname, (float)$slotqstat);
143                 }
144             }
145         }
147         $itemstats = array('s' => 12,
148                           'effectiveweight' => null,
149                           'discriminationindex' => 35.803933,
150                           'discriminativeefficiency' => 39.39393939,
151                           'sd' => 0.514928651,
152                           'facility' => 0.583333333,
153                           'maxmark' => 1,
154                           'positions' => '1',
155                           'slot' => null,
156                           'subquestion' => true);
157         foreach ($itemstats as $statname => $expected) {
158             $this->assert_stat_equals($questionstats, 1, null, 'numerical', $statname, $expected);
159         }
161         // These variant's stats are calculated in stats_for_variant_1.xls and stats_for_variant_8.xls
162         // The calculations in the spreadsheets are the same but applied just to the attempts where the variants appeared.
164         $statsforslot2variants = array(1 => array('s' => 6,
165                                                     'effectiveweight' => null,
166                                                     'discriminationindex' => -10.5999788,
167                                                     'discriminativeefficiency' => -14.28571429,
168                                                     'sd' => 0.5477225575,
169                                                     'facility' => 0.50,
170                                                     'maxmark' => 1,
171                                                     'variant' => 1,
172                                                     'slot' => 2,
173                                                     'subquestion' => false),
174                                       8 => array('s' => 5,
175                                                     'effectiveweight' => null,
176                                                     'discriminationindex' => -57.77466679,
177                                                     'discriminativeefficiency' => -71.05263241,
178                                                     'sd' => 0.547722558,
179                                                     'facility' => 0.40,
180                                                     'maxmark' => 1,
181                                                     'variant' => 8,
182                                                     'slot' => 2,
183                                                     'subquestion' => false));
184         foreach ($statsforslot2variants as $variant => $stats) {
185             foreach ($stats as $statname => $expected) {
186                 $this->assert_stat_equals($questionstats, 2, $variant, null, $statname, $expected);
187             }
188         }
189     }
191     protected function assert_response_count_equals($question, $qubaids, $responsecount) {
192         $responesstats = new \core_question\statistics\responses\analyser($question);
193         $analysis = $responesstats->load_cached($qubaids);
194         if (!isset($responsecount['subpart'])) {
195             $subpart = 1;
196         } else {
197             $subpart = $responsecount['subpart'];
198         }
199         list($subpartid, $responseclassid) = $this->get_response_subpart_and_class_id($question,
200                                                                                       $subpart,
201                                                                                       $responsecount['modelresponse']);
203         $subpartanalysis = $analysis->get_analysis_for_subpart($responsecount['variant'], $subpartid);
204         $responseclassanalysis = $subpartanalysis->get_response_class($responseclassid);
205         $actualresponsecounts = $responseclassanalysis->data_for_question_response_table('', '');
206         if ($responsecount['modelresponse'] !== '[NO RESPONSE]') {
207             foreach ($actualresponsecounts as $actualresponsecount) {
208                 if ($actualresponsecount->response == $responsecount['actualresponse']) {
209                     $this->assertEquals($responsecount['count'], $actualresponsecount->count);
210                     return;
211                 }
212             }
213             throw new coding_exception("Actual response '{$responsecount['actualresponse']}' not found.");
214         } else {
215             $actualresponsecount = array_pop($actualresponsecounts);
216             $this->assertEquals($responsecount['count'], $actualresponsecount->count);
217         }
218     }
220     protected function get_response_subpart_and_class_id($question, $subpart, $modelresponse) {
221         $qtypeobj = question_bank::get_qtype($question->qtype, false);
222         $possibleresponses = $qtypeobj->get_possible_responses($question);
223         $possibleresponsesubpartids = array_keys($possibleresponses);
224         if (!isset($possibleresponsesubpartids[$subpart - 1])) {
225             throw new coding_exception("Subpart '{$subpart}' not found.");
226         }
227         $subpartid = $possibleresponsesubpartids[$subpart - 1];
229         if ($modelresponse == '[NO RESPONSE]') {
230             return array($subpartid, null);
232         } else if ($modelresponse == '[NO MATCH]') {
233             return array($subpartid, 0);
234         }
236         $modelresponses = array();
237         foreach ($possibleresponses[$subpartid] as $responseclassid => $subpartpossibleresponse) {
238             $modelresponses[$responseclassid] = $subpartpossibleresponse->responseclass;
239         }
240         $this->assertContains($modelresponse, $modelresponses);
241         $responseclassid = array_search($modelresponse, $modelresponses);
242         return array($subpartid, $responseclassid);
243     }
245     /**
246      * Check that the stat is as expected within a reasonable tolerance.
247      *
248      * @param \core_question\statistics\questions\all_calculated_for_qubaid_condition $questionstats
249      * @param int                                              $slot
250      * @param int|null                                         $variant if null then not a variant stat.
251      * @param string|null                                      $subqname if null then not an item stat.
252      * @param string                                           $statname
253      * @param float                                            $expected
254      */
255     protected function assert_stat_equals($questionstats, $slot, $variant, $subqname, $statname, $expected) {
257         if ($variant === null && $subqname === null) {
258             $actual = $questionstats->for_slot($slot)->{$statname};
259         } else if ($subqname !== null) {
260             $actual = $questionstats->for_subq($this->randqids[$slot][$subqname])->{$statname};
261         } else {
262             $actual = $questionstats->for_slot($slot, $variant)->{$statname};
263         }
264         if (is_bool($expected) || is_string($expected)) {
265             $this->assertEquals($expected, $actual, "$statname for slot $slot");
266         } else {
267             switch ($statname) {
268                 case 'covariance' :
269                 case 'discriminationindex' :
270                 case 'discriminativeefficiency' :
271                 case 'effectiveweight' :
272                     $precision = 1e-5;
273                     break;
274                 default :
275                     $precision = 1e-6;
276             }
277             $delta = abs($expected) * $precision;
278             $this->assertEquals(floatval($expected), $actual, "$statname for slot $slot", $delta);
279         }
280     }