MDL-64787 mlbackend: Evaluate trained models
[moodle.git] / analytics / classes / model.php
CommitLineData
369389c9
DM
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/**
b94dbb55 18 * Prediction model representation.
369389c9
DM
19 *
20 * @package core_analytics
21 * @copyright 2016 David Monllao {@link http://www.davidmonllao.com}
22 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
23 */
24
25namespace core_analytics;
26
27defined('MOODLE_INTERNAL') || die();
28
29/**
b94dbb55 30 * Prediction model representation.
369389c9
DM
31 *
32 * @package core_analytics
33 * @copyright 2016 David Monllao {@link http://www.davidmonllao.com}
34 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
35 */
36class model {
37
413f19bc
DM
38 /**
39 * All as expected.
40 */
369389c9 41 const OK = 0;
413f19bc
DM
42
43 /**
44 * There was a problem.
45 */
369389c9 46 const GENERAL_ERROR = 1;
413f19bc
DM
47
48 /**
49 * No dataset to analyse.
50 */
369389c9
DM
51 const NO_DATASET = 2;
52
413f19bc
DM
53 /**
54 * Model with low prediction accuracy.
55 */
325b3bdd 56 const LOW_SCORE = 4;
413f19bc
DM
57
58 /**
59 * Not enough data to evaluate the model properly.
60 */
325b3bdd 61 const NOT_ENOUGH_DATA = 8;
369389c9 62
413f19bc
DM
63 /**
64 * Invalid analysable for the time splitting method.
65 */
66 const ANALYSABLE_REJECTED_TIME_SPLITTING_METHOD = 4;
67
68 /**
69 * Invalid analysable for all time splitting methods.
70 */
369389c9 71 const ANALYSABLE_STATUS_INVALID_FOR_RANGEPROCESSORS = 8;
413f19bc
DM
72
73 /**
74 * Invalid analysable for the target
75 */
369389c9
DM
76 const ANALYSABLE_STATUS_INVALID_FOR_TARGET = 16;
77
413f19bc
DM
78 /**
79 * Minimum score to consider a non-static prediction model as good.
80 */
369389c9 81 const MIN_SCORE = 0.7;
413f19bc 82
5c5cb3ee
DM
83 /**
84 * Minimum prediction confidence (from 0 to 1) to accept a prediction as reliable enough.
85 */
86 const PREDICTION_MIN_SCORE = 0.6;
87
413f19bc
DM
88 /**
89 * Maximum standard deviation between different evaluation repetitions to consider that evaluation results are stable.
90 */
369389c9 91 const ACCEPTED_DEVIATION = 0.05;
413f19bc
DM
92
93 /**
94 * Number of evaluation repetitions.
95 */
369389c9
DM
96 const EVALUATION_ITERATIONS = 10;
97
98 /**
99 * @var \stdClass
100 */
101 protected $model = null;
102
103 /**
104 * @var \core_analytics\local\analyser\base
105 */
106 protected $analyser = null;
107
108 /**
109 * @var \core_analytics\local\target\base
110 */
111 protected $target = null;
112
ed12ba6b
DM
113 /**
114 * @var \core_analytics\predictor
115 */
116 protected $predictionsprocessor = null;
117
369389c9
DM
118 /**
119 * @var \core_analytics\local\indicator\base[]
120 */
121 protected $indicators = null;
122
123 /**
124 * Unique Model id created from site info and last model modification.
125 *
126 * @var string
127 */
128 protected $uniqueid = null;
129
130 /**
1cc2b4ba 131 * Constructor.
369389c9 132 *
1cc2b4ba 133 * @param int|\stdClass $model
369389c9
DM
134 * @return void
135 */
136 public function __construct($model) {
137 global $DB;
138
139 if (is_scalar($model)) {
1611308b 140 $model = $DB->get_record('analytics_models', array('id' => $model), '*', MUST_EXIST);
f9e7447f
DM
141 if (!$model) {
142 throw new \moodle_exception('errorunexistingmodel', 'analytics', '', $model);
143 }
369389c9
DM
144 }
145 $this->model = $model;
146 }
147
3a396286
DM
148 /**
149 * Quick safety check to discard site models which required components are not available anymore.
150 *
151 * @return bool
152 */
153 public function is_available() {
154 $target = $this->get_target();
155 if (!$target) {
156 return false;
157 }
3a396286
DM
158
159 $classname = $target->get_analyser_class();
160 if (!class_exists($classname)) {
161 return false;
162 }
163
164 return true;
165 }
166
369389c9 167 /**
1cc2b4ba 168 * Returns the model id.
369389c9
DM
169 *
170 * @return int
171 */
172 public function get_id() {
173 return $this->model->id;
174 }
175
176 /**
1cc2b4ba 177 * Returns a plain \stdClass with the model data.
369389c9
DM
178 *
179 * @return \stdClass
180 */
181 public function get_model_obj() {
182 return $this->model;
183 }
184
185 /**
1cc2b4ba 186 * Returns the model target.
369389c9
DM
187 *
188 * @return \core_analytics\local\target\base
189 */
190 public function get_target() {
191 if ($this->target !== null) {
192 return $this->target;
193 }
194 $instance = \core_analytics\manager::get_target($this->model->target);
195 $this->target = $instance;
196
197 return $this->target;
198 }
199
200 /**
1cc2b4ba 201 * Returns the model indicators.
369389c9
DM
202 *
203 * @return \core_analytics\local\indicator\base[]
204 */
205 public function get_indicators() {
206 if ($this->indicators !== null) {
207 return $this->indicators;
208 }
209
210 $fullclassnames = json_decode($this->model->indicators);
211
212 if (!is_array($fullclassnames)) {
213 throw new \coding_exception('Model ' . $this->model->id . ' indicators can not be read');
214 }
215
216 $this->indicators = array();
217 foreach ($fullclassnames as $fullclassname) {
218 $instance = \core_analytics\manager::get_indicator($fullclassname);
219 if ($instance) {
220 $this->indicators[$fullclassname] = $instance;
221 } else {
222 debugging('Can\'t load ' . $fullclassname . ' indicator', DEBUG_DEVELOPER);
223 }
224 }
225
226 return $this->indicators;
227 }
228
229 /**
230 * Returns the list of indicators that could potentially be used by the model target.
231 *
232 * It includes the indicators that are part of the model.
233 *
a40952d3 234 * @return \core_analytics\local\indicator\base[]
369389c9
DM
235 */
236 public function get_potential_indicators() {
237
238 $indicators = \core_analytics\manager::get_all_indicators();
239
240 if (empty($this->analyser)) {
241 $this->init_analyser(array('evaluation' => true));
242 }
243
244 foreach ($indicators as $classname => $indicator) {
245 if ($this->analyser->check_indicator_requirements($indicator) !== true) {
246 unset($indicators[$classname]);
247 }
248 }
249 return $indicators;
250 }
251
252 /**
1cc2b4ba 253 * Returns the model analyser (defined by the model target).
369389c9 254 *
a8ccc5f2 255 * @param array $options Default initialisation with no options.
369389c9
DM
256 * @return \core_analytics\local\analyser\base
257 */
a8ccc5f2 258 public function get_analyser($options = array()) {
369389c9
DM
259 if ($this->analyser !== null) {
260 return $this->analyser;
261 }
262
a8ccc5f2 263 $this->init_analyser($options);
369389c9
DM
264
265 return $this->analyser;
266 }
267
268 /**
1cc2b4ba 269 * Initialises the model analyser.
369389c9 270 *
1cc2b4ba 271 * @throws \coding_exception
369389c9
DM
272 * @param array $options
273 * @return void
274 */
275 protected function init_analyser($options = array()) {
276
277 $target = $this->get_target();
278 $indicators = $this->get_indicators();
279
280 if (empty($target)) {
281 throw new \moodle_exception('errornotarget', 'analytics');
282 }
283
a8ccc5f2
DM
284 $timesplittings = array();
285 if (empty($options['notimesplitting'])) {
286 if (!empty($options['evaluation'])) {
287 // The evaluation process will run using all available time splitting methods unless one is specified.
288 if (!empty($options['timesplitting'])) {
289 $timesplitting = \core_analytics\manager::get_time_splitting($options['timesplitting']);
290 $timesplittings = array($timesplitting->get_id() => $timesplitting);
291 } else {
292 $timesplittings = \core_analytics\manager::get_enabled_time_splitting_methods();
293 }
369389c9 294 } else {
369389c9 295
a8ccc5f2
DM
296 if (empty($this->model->timesplitting)) {
297 throw new \moodle_exception('invalidtimesplitting', 'analytics', '', $this->model->id);
298 }
369389c9 299
a8ccc5f2
DM
300 // Returned as an array as all actions (evaluation, training and prediction) go through the same process.
301 $timesplittings = array($this->model->timesplitting => $this->get_time_splitting());
302 }
369389c9 303
a8ccc5f2
DM
304 if (empty($timesplittings)) {
305 throw new \moodle_exception('errornotimesplittings', 'analytics');
306 }
369389c9
DM
307 }
308
0690a271
DM
309 if (!empty($options['evaluation'])) {
310 foreach ($timesplittings as $timesplitting) {
311 $timesplitting->set_evaluating(true);
312 }
313 }
314
369389c9
DM
315 $classname = $target->get_analyser_class();
316 if (!class_exists($classname)) {
08015e18 317 throw new \coding_exception($classname . ' class does not exists');
369389c9
DM
318 }
319
320 // Returns a \core_analytics\local\analyser\base class.
321 $this->analyser = new $classname($this->model->id, $target, $indicators, $timesplittings, $options);
322 }
323
324 /**
1cc2b4ba 325 * Returns the model time splitting method.
369389c9 326 *
1cc2b4ba 327 * @return \core_analytics\local\time_splitting\base|false Returns false if no time splitting.
369389c9
DM
328 */
329 public function get_time_splitting() {
330 if (empty($this->model->timesplitting)) {
331 return false;
332 }
333 return \core_analytics\manager::get_time_splitting($this->model->timesplitting);
334 }
335
336 /**
a40952d3 337 * Creates a new model. Enables it if $timesplittingid is specified.
369389c9
DM
338 *
339 * @param \core_analytics\local\target\base $target
340 * @param \core_analytics\local\indicator\base[] $indicators
c70a7194
DM
341 * @param string|false $timesplittingid The time splitting method id (its fully qualified class name)
342 * @param string|null $processor The machine learning backend this model will use.
369389c9
DM
343 * @return \core_analytics\model
344 */
ed12ba6b 345 public static function create(\core_analytics\local\target\base $target, array $indicators,
c70a7194 346 $timesplittingid = false, $processor = null) {
369389c9
DM
347 global $USER, $DB;
348
1611308b
DM
349 \core_analytics\manager::check_can_manage_models();
350
369389c9
DM
351 $indicatorclasses = self::indicator_classes($indicators);
352
353 $now = time();
354
355 $modelobj = new \stdClass();
b0c24929 356 $modelobj->target = $target->get_id();
369389c9
DM
357 $modelobj->indicators = json_encode($indicatorclasses);
358 $modelobj->version = $now;
359 $modelobj->timecreated = $now;
360 $modelobj->timemodified = $now;
361 $modelobj->usermodified = $USER->id;
362
ed12ba6b 363 if ($processor &&
e4453adc
DM
364 !manager::is_valid($processor, '\core_analytics\classifier') &&
365 !manager::is_valid($processor, '\core_analytics\regressor')) {
ed12ba6b
DM
366 throw new \coding_exception('The provided predictions processor \\' . $processor . '\processor is not valid');
367 } else {
368 $modelobj->predictionsprocessor = $processor;
369 }
370
369389c9
DM
371 $id = $DB->insert_record('analytics_models', $modelobj);
372
373 // Get db defaults.
374 $modelobj = $DB->get_record('analytics_models', array('id' => $id), '*', MUST_EXIST);
375
a40952d3
DM
376 $model = new static($modelobj);
377
378 if ($timesplittingid) {
379 $model->enable($timesplittingid);
380 }
381
382 if ($model->is_static()) {
383 $model->mark_as_trained();
384 }
385
386 return $model;
369389c9
DM
387 }
388
e709e544
DM
389 /**
390 * Does this model exist?
391 *
392 * If no indicators are provided it considers any model with the provided
393 * target a match.
394 *
395 * @param \core_analytics\local\target\base $target
396 * @param \core_analytics\local\indicator\base[]|false $indicators
397 * @return bool
398 */
399 public static function exists(\core_analytics\local\target\base $target, $indicators = false) {
400 global $DB;
401
402 $existingmodels = $DB->get_records('analytics_models', array('target' => $target->get_id()));
403
404 if (!$indicators && $existingmodels) {
405 return true;
406 }
407
408 $indicatorids = array_keys($indicators);
409 sort($indicatorids);
410
411 foreach ($existingmodels as $modelobj) {
412 $model = new \core_analytics\model($modelobj);
413 $modelindicatorids = array_keys($model->get_indicators());
414 sort($modelindicatorids);
415
416 if ($indicatorids === $modelindicatorids) {
417 return true;
418 }
419 }
420 return false;
421 }
422
a40952d3 423 /**
1cc2b4ba 424 * Updates the model.
a40952d3
DM
425 *
426 * @param int|bool $enabled
5c140ac4
DM
427 * @param \core_analytics\local\indicator\base[]|false $indicators False to respect current indicators
428 * @param string|false $timesplittingid False to respect current time splitting method
ed12ba6b 429 * @param string|false $predictionsprocessor False to respect current predictors processor value
a40952d3
DM
430 * @return void
431 */
ed12ba6b 432 public function update($enabled, $indicators = false, $timesplittingid = '', $predictionsprocessor = false) {
369389c9
DM
433 global $USER, $DB;
434
1611308b
DM
435 \core_analytics\manager::check_can_manage_models();
436
369389c9
DM
437 $now = time();
438
5c140ac4
DM
439 if ($indicators !== false) {
440 $indicatorclasses = self::indicator_classes($indicators);
441 $indicatorsstr = json_encode($indicatorclasses);
442 } else {
443 // Respect current value.
444 $indicatorsstr = $this->model->indicators;
445 }
446
447 if ($timesplittingid === false) {
448 // Respect current value.
449 $timesplittingid = $this->model->timesplitting;
450 }
369389c9 451
ed12ba6b
DM
452 if ($predictionsprocessor === false) {
453 // Respect current value.
454 $predictionsprocessor = $this->model->predictionsprocessor;
455 }
456
a40952d3 457 if ($this->model->timesplitting !== $timesplittingid ||
ed12ba6b
DM
458 $this->model->indicators !== $indicatorsstr ||
459 $this->model->predictionsprocessor !== $predictionsprocessor) {
369389c9 460
abafbc84 461 // Delete generated predictions before changing the model version.
325b3bdd 462 $this->clear();
369389c9 463
abafbc84
DM
464 // It needs to be reset as the version changes.
465 $this->uniqueid = null;
e4453adc 466 $this->indicators = null;
abafbc84
DM
467
468 // We update the version of the model so different time splittings are not mixed up.
469 $this->model->version = $now;
470
369389c9 471 // Reset trained flag.
abafbc84
DM
472 if (!$this->is_static()) {
473 $this->model->trained = 0;
474 }
3e0f33aa
DM
475
476 } else if ($this->model->enabled != $enabled) {
477 // We purge the cached contexts with insights as some will not be visible anymore.
478 $this->purge_insights_cache();
369389c9 479 }
3e0f33aa 480
a40952d3 481 $this->model->enabled = intval($enabled);
369389c9 482 $this->model->indicators = $indicatorsstr;
a40952d3 483 $this->model->timesplitting = $timesplittingid;
ed12ba6b 484 $this->model->predictionsprocessor = $predictionsprocessor;
369389c9
DM
485 $this->model->timemodified = $now;
486 $this->model->usermodified = $USER->id;
487
488 $DB->update_record('analytics_models', $this->model);
369389c9
DM
489 }
490
d16cf374
DM
491 /**
492 * Removes the model.
493 *
494 * @return void
495 */
d8327b60 496 public function delete() {
d16cf374 497 global $DB;
1611308b
DM
498
499 \core_analytics\manager::check_can_manage_models();
500
325b3bdd 501 $this->clear();
abafbc84 502
325b3bdd 503 // Method self::clear is already clearing the current model version.
d44ce97f
DM
504 $predictor = $this->get_predictions_processor(false);
505 if ($predictor->is_ready() !== true) {
506 $predictorname = \core_analytics\manager::get_predictions_processor_name($predictor);
507 debugging('Prediction processor ' . $predictorname . ' is not ready to be used. Model ' .
508 $this->model->id . ' could not be deleted.');
509 } else {
510 $predictor->delete_output_dir($this->get_output_dir(array(), true));
511 }
abafbc84 512
d8327b60 513 $DB->delete_records('analytics_models', array('id' => $this->model->id));
99b84a26 514 $DB->delete_records('analytics_models_log', array('modelid' => $this->model->id));
d16cf374
DM
515 }
516
369389c9 517 /**
1cc2b4ba 518 * Evaluates the model.
369389c9 519 *
1cc2b4ba
DM
520 * This method gets the site contents (through the analyser) creates a .csv dataset
521 * with them and evaluates the model prediction accuracy multiple times using the
522 * machine learning backend. It returns an object where the model score is the average
523 * prediction accuracy of all executed evaluations.
369389c9
DM
524 *
525 * @param array $options
526 * @return \stdClass[]
527 */
528 public function evaluate($options = array()) {
529
1611308b
DM
530 \core_analytics\manager::check_can_manage_models();
531
a40952d3
DM
532 if ($this->is_static()) {
533 $this->get_analyser()->add_log(get_string('noevaluationbasedassumptions', 'analytics'));
534 $result = new \stdClass();
cbf4c391
DM
535 $result->status = self::NO_DATASET;
536 return array($this->get_time_splitting()->get_id() => $result);
a40952d3
DM
537 }
538
369389c9 539 $options['evaluation'] = true;
bc82b895
DM
540
541 if (empty($options['mode'])) {
542 $options['mode'] = 'configuration';
543 }
544
545 if ($options['mode'] == 'trainedmodel') {
546
547 // We are only interested on the time splitting method used by the trained model.
548 $options['timesplitting'] = $this->model->timesplitting;
549
550 // Provide the trained model directory to the ML backend if that is what we want to evaluate.
551 $trainedmodeldir = $this->get_output_dir(['execution']);
552 } else {
553 $trainedmodeldir = false;
554 }
555
369389c9
DM
556 $this->init_analyser($options);
557
558 if (empty($this->get_indicators())) {
559 throw new \moodle_exception('errornoindicators', 'analytics');
560 }
561
1611308b
DM
562 $this->heavy_duty_mode();
563
369389c9 564 // Before get_labelled_data call so we get an early exception if it is not ready.
ed12ba6b 565 $predictor = $this->get_predictions_processor();
369389c9
DM
566
567 $datasets = $this->get_analyser()->get_labelled_data();
568
569 // No datasets generated.
570 if (empty($datasets)) {
571 $result = new \stdClass();
572 $result->status = self::NO_DATASET;
573 $result->info = $this->get_analyser()->get_logs();
574 return array($result);
575 }
576
577 if (!PHPUNIT_TEST && CLI_SCRIPT) {
578 echo PHP_EOL . get_string('processingsitecontents', 'analytics') . PHP_EOL;
579 }
580
581 $results = array();
582 foreach ($datasets as $timesplittingid => $dataset) {
583
584 $timesplitting = \core_analytics\manager::get_time_splitting($timesplittingid);
585
586 $result = new \stdClass();
587
588 $dashestimesplittingid = str_replace('\\', '', $timesplittingid);
589 $outputdir = $this->get_output_dir(array('evaluation', $dashestimesplittingid));
590
591 // Evaluate the dataset, the deviation we accept in the results depends on the amount of iterations.
5c5cb3ee
DM
592 if ($this->get_target()->is_linear()) {
593 $predictorresult = $predictor->evaluate_regression($this->get_unique_id(), self::ACCEPTED_DEVIATION,
bc82b895 594 self::EVALUATION_ITERATIONS, $dataset, $outputdir, $trainedmodeldir);
5c5cb3ee
DM
595 } else {
596 $predictorresult = $predictor->evaluate_classification($this->get_unique_id(), self::ACCEPTED_DEVIATION,
bc82b895 597 self::EVALUATION_ITERATIONS, $dataset, $outputdir, $trainedmodeldir);
5c5cb3ee 598 }
369389c9
DM
599
600 $result->status = $predictorresult->status;
601 $result->info = $predictorresult->info;
602
603 if (isset($predictorresult->score)) {
604 $result->score = $predictorresult->score;
605 } else {
606 // Prediction processors may return an error, default to 0 score in that case.
607 $result->score = 0;
608 }
609
610 $dir = false;
611 if (!empty($predictorresult->dir)) {
612 $dir = $predictorresult->dir;
613 }
614
615 $result->logid = $this->log_result($timesplitting->get_id(), $result->score, $dir, $result->info);
616
617 $results[$timesplitting->get_id()] = $result;
618 }
619
620 return $results;
621 }
622
623 /**
1cc2b4ba
DM
624 * Trains the model using the site contents.
625 *
626 * This method prepares a dataset from the site contents (through the analyser)
627 * and passes it to the machine learning backends. Static models are skipped as
628 * they do not require training.
369389c9
DM
629 *
630 * @return \stdClass
631 */
632 public function train() {
369389c9 633
1611308b
DM
634 \core_analytics\manager::check_can_manage_models();
635
a40952d3
DM
636 if ($this->is_static()) {
637 $this->get_analyser()->add_log(get_string('notrainingbasedassumptions', 'analytics'));
638 $result = new \stdClass();
639 $result->status = self::OK;
640 return $result;
641 }
642
a40952d3 643 if (!$this->is_enabled() || empty($this->model->timesplitting)) {
369389c9
DM
644 throw new \moodle_exception('invalidtimesplitting', 'analytics', '', $this->model->id);
645 }
646
647 if (empty($this->get_indicators())) {
648 throw new \moodle_exception('errornoindicators', 'analytics');
649 }
650
1611308b
DM
651 $this->heavy_duty_mode();
652
369389c9
DM
653 // Before get_labelled_data call so we get an early exception if it is not writable.
654 $outputdir = $this->get_output_dir(array('execution'));
655
656 // Before get_labelled_data call so we get an early exception if it is not ready.
ed12ba6b 657 $predictor = $this->get_predictions_processor();
369389c9
DM
658
659 $datasets = $this->get_analyser()->get_labelled_data();
660
661 // No training if no files have been provided.
662 if (empty($datasets) || empty($datasets[$this->model->timesplitting])) {
663
664 $result = new \stdClass();
665 $result->status = self::NO_DATASET;
666 $result->info = $this->get_analyser()->get_logs();
667 return $result;
668 }
669 $samplesfile = $datasets[$this->model->timesplitting];
670
671 // Train using the dataset.
5c5cb3ee
DM
672 if ($this->get_target()->is_linear()) {
673 $predictorresult = $predictor->train_regression($this->get_unique_id(), $samplesfile, $outputdir);
674 } else {
675 $predictorresult = $predictor->train_classification($this->get_unique_id(), $samplesfile, $outputdir);
676 }
369389c9
DM
677
678 $result = new \stdClass();
679 $result->status = $predictorresult->status;
680 $result->info = $predictorresult->info;
681
325b3bdd
DM
682 if ($result->status !== self::OK) {
683 return $result;
684 }
685
369389c9
DM
686 $this->flag_file_as_used($samplesfile, 'trained');
687
688 // Mark the model as trained if it wasn't.
689 if ($this->model->trained == false) {
690 $this->mark_as_trained();
691 }
692
693 return $result;
694 }
695
696 /**
1cc2b4ba
DM
697 * Get predictions from the site contents.
698 *
699 * It analyses the site contents (through analyser classes) looking for samples
700 * ready to receive predictions. It generates a dataset with all samples ready to
701 * get predictions and it passes it to the machine learning backends or to the
702 * targets based on assumptions to get the predictions.
369389c9
DM
703 *
704 * @return \stdClass
705 */
706 public function predict() {
707 global $DB;
708
1611308b 709 \core_analytics\manager::check_can_manage_models();
369389c9 710
a40952d3 711 if (!$this->is_enabled() || empty($this->model->timesplitting)) {
369389c9
DM
712 throw new \moodle_exception('invalidtimesplitting', 'analytics', '', $this->model->id);
713 }
714
715 if (empty($this->get_indicators())) {
716 throw new \moodle_exception('errornoindicators', 'analytics');
717 }
718
1611308b
DM
719 $this->heavy_duty_mode();
720
369389c9
DM
721 // Before get_unlabelled_data call so we get an early exception if it is not writable.
722 $outputdir = $this->get_output_dir(array('execution'));
723
724 // Before get_unlabelled_data call so we get an early exception if it is not ready.
a40952d3 725 if (!$this->is_static()) {
ed12ba6b 726 $predictor = $this->get_predictions_processor();
a40952d3 727 }
369389c9
DM
728
729 $samplesdata = $this->get_analyser()->get_unlabelled_data();
730
731 // Get the prediction samples file.
732 if (empty($samplesdata) || empty($samplesdata[$this->model->timesplitting])) {
733
734 $result = new \stdClass();
735 $result->status = self::NO_DATASET;
736 $result->info = $this->get_analyser()->get_logs();
737 return $result;
738 }
739 $samplesfile = $samplesdata[$this->model->timesplitting];
740
741 // We need to throw an exception if we are trying to predict stuff that was already predicted.
2dca1339 742 $params = array('modelid' => $this->model->id, 'action' => 'predicted', 'fileid' => $samplesfile->get_id());
369389c9
DM
743 if ($predicted = $DB->get_record('analytics_used_files', $params)) {
744 throw new \moodle_exception('erroralreadypredict', 'analytics', '', $samplesfile->get_id());
745 }
746
a40952d3 747 $indicatorcalculations = \core_analytics\dataset_manager::get_structured_data($samplesfile);
369389c9 748
a40952d3 749 // Prepare the results object.
369389c9 750 $result = new \stdClass();
369389c9 751
a40952d3
DM
752 if ($this->is_static()) {
753 // Prediction based on assumptions.
413f19bc 754 $result->status = self::OK;
a40952d3
DM
755 $result->info = [];
756 $result->predictions = $this->get_static_predictions($indicatorcalculations);
757
758 } else {
5c5cb3ee
DM
759 // Estimation and classification processes run on the machine learning backend side.
760 if ($this->get_target()->is_linear()) {
761 $predictorresult = $predictor->estimate($this->get_unique_id(), $samplesfile, $outputdir);
762 } else {
763 $predictorresult = $predictor->classify($this->get_unique_id(), $samplesfile, $outputdir);
764 }
a40952d3
DM
765 $result->status = $predictorresult->status;
766 $result->info = $predictorresult->info;
1611308b
DM
767 $result->predictions = $this->format_predictor_predictions($predictorresult);
768 }
769
325b3bdd
DM
770 if ($result->status !== self::OK) {
771 return $result;
772 }
773
1611308b
DM
774 if ($result->predictions) {
775 $samplecontexts = $this->execute_prediction_callbacks($result->predictions, $indicatorcalculations);
776 }
777
778 if (!empty($samplecontexts) && $this->uses_insights()) {
779 $this->trigger_insights($samplecontexts);
780 }
781
782 $this->flag_file_as_used($samplesfile, 'predicted');
783
784 return $result;
785 }
786
ed12ba6b
DM
787 /**
788 * Returns the model predictions processor.
789 *
d44ce97f 790 * @param bool $checkisready
ed12ba6b
DM
791 * @return \core_analytics\predictor
792 */
d44ce97f
DM
793 public function get_predictions_processor($checkisready = true) {
794 return manager::get_predictions_processor($this->model->predictionsprocessor, $checkisready);
ed12ba6b
DM
795 }
796
1611308b
DM
797 /**
798 * Formats the predictor results.
799 *
800 * @param array $predictorresult
801 * @return array
802 */
803 private function format_predictor_predictions($predictorresult) {
804
805 $predictions = array();
0af2421a 806 if (!empty($predictorresult->predictions)) {
1611308b
DM
807 foreach ($predictorresult->predictions as $sampleinfo) {
808
413f19bc 809 // We parse each prediction.
1611308b
DM
810 switch (count($sampleinfo)) {
811 case 1:
812 // For whatever reason the predictions processor could not process this sample, we
813 // skip it and do nothing with it.
814 debugging($this->model->id . ' model predictions processor could not process the sample with id ' .
815 $sampleinfo[0], DEBUG_DEVELOPER);
bd5fdcfc 816 continue 2;
1611308b
DM
817 case 2:
818 // Prediction processors that do not return a prediction score will have the maximum prediction
819 // score.
820 list($uniquesampleid, $prediction) = $sampleinfo;
821 $predictionscore = 1;
822 break;
823 case 3:
824 list($uniquesampleid, $prediction, $predictionscore) = $sampleinfo;
825 break;
826 default:
827 break;
a40952d3 828 }
1611308b
DM
829 $predictiondata = (object)['prediction' => $prediction, 'predictionscore' => $predictionscore];
830 $predictions[$uniquesampleid] = $predictiondata;
a40952d3
DM
831 }
832 }
1611308b
DM
833 return $predictions;
834 }
835
836 /**
837 * Execute the prediction callbacks defined by the target.
838 *
839 * @param \stdClass[] $predictions
413f19bc 840 * @param array $indicatorcalculations
1611308b
DM
841 * @return array
842 */
843 protected function execute_prediction_callbacks($predictions, $indicatorcalculations) {
369389c9
DM
844
845 // Here we will store all predictions' contexts, this will be used to limit which users will see those predictions.
846 $samplecontexts = array();
325b3bdd 847 $records = array();
369389c9 848
1611308b 849 foreach ($predictions as $uniquesampleid => $prediction) {
369389c9 850
325b3bdd
DM
851 // The unique sample id contains both the sampleid and the rangeindex.
852 list($sampleid, $rangeindex) = $this->get_time_splitting()->infer_sample_info($uniquesampleid);
369389c9 853
325b3bdd 854 if ($this->get_target()->triggers_callback($prediction->prediction, $prediction->predictionscore)) {
369389c9 855
325b3bdd 856 // Prepare the record to store the predicted values.
cab7abec 857 list($record, $samplecontext) = $this->prepare_prediction_record($sampleid, $rangeindex, $prediction->prediction,
413f19bc 858 $prediction->predictionscore, json_encode($indicatorcalculations[$uniquesampleid]));
369389c9 859
cab7abec
DM
860 // We will later bulk-insert them all.
861 $records[$uniquesampleid] = $record;
862
1611308b
DM
863 // Also store all samples context to later generate insights or whatever action the target wants to perform.
864 $samplecontexts[$samplecontext->id] = $samplecontext;
369389c9 865
1611308b
DM
866 $this->get_target()->prediction_callback($this->model->id, $sampleid, $rangeindex, $samplecontext,
867 $prediction->prediction, $prediction->predictionscore);
369389c9
DM
868 }
869 }
870
0927604f
DM
871 if (!empty($records)) {
872 $this->save_predictions($records);
873 }
cab7abec 874
1611308b
DM
875 return $samplecontexts;
876 }
369389c9 877
1611308b
DM
878 /**
879 * Generates insights and updates the cache.
880 *
881 * @param \context[] $samplecontexts
882 * @return void
883 */
884 protected function trigger_insights($samplecontexts) {
885
886 // Notify the target that all predictions have been processed.
887 $this->get_target()->generate_insight_notifications($this->model->id, $samplecontexts);
888
889 // Update cache.
890 $cache = \cache::make('core', 'contextwithinsights');
891 foreach ($samplecontexts as $context) {
892 $modelids = $cache->get($context->id);
893 if (!$modelids) {
894 // The cache is empty, but we don't know if it is empty because there are no insights
895 // in this context or because cache/s have been purged, we need to be conservative and
896 // "pay" 1 db read to fill up the cache.
897 $models = \core_analytics\manager::get_models_with_insights($context);
898 $cache->set($context->id, array_keys($models));
899 } else if (!in_array($this->get_id(), $modelids)) {
900 array_push($modelids, $this->get_id());
901 $cache->set($context->id, $modelids);
369389c9
DM
902 }
903 }
369389c9
DM
904 }
905
a40952d3 906 /**
1611308b 907 * Get predictions from a static model.
a40952d3
DM
908 *
909 * @param array $indicatorcalculations
910 * @return \stdClass[]
911 */
912 protected function get_static_predictions(&$indicatorcalculations) {
913
914 // Group samples by analysable for \core_analytics\local\target::calculate.
915 $analysables = array();
916 // List all sampleids together.
917 $sampleids = array();
918
919 foreach ($indicatorcalculations as $uniquesampleid => $indicators) {
920 list($sampleid, $rangeindex) = $this->get_time_splitting()->infer_sample_info($uniquesampleid);
921
922 $analysable = $this->get_analyser()->get_sample_analysable($sampleid);
923 $analysableclass = get_class($analysable);
924 if (empty($analysables[$analysableclass])) {
925 $analysables[$analysableclass] = array();
926 }
927 if (empty($analysables[$analysableclass][$rangeindex])) {
928 $analysables[$analysableclass][$rangeindex] = (object)[
929 'analysable' => $analysable,
930 'indicatorsdata' => array(),
931 'sampleids' => array()
932 ];
933 }
934 // Using the sampleid as a key so we can easily merge indicators data later.
935 $analysables[$analysableclass][$rangeindex]->indicatorsdata[$sampleid] = $indicators;
936 // We could use indicatorsdata keys but the amount of redundant data is not that big and leaves code below cleaner.
937 $analysables[$analysableclass][$rangeindex]->sampleids[$sampleid] = $sampleid;
938
939 // Accumulate sample ids to get all their associated data in 1 single db query (analyser::get_samples).
940 $sampleids[$sampleid] = $sampleid;
941 }
942
943 // Get all samples data.
944 list($sampleids, $samplesdata) = $this->get_analyser()->get_samples($sampleids);
945
946 // Calculate the targets.
1cc2b4ba 947 $predictions = array();
a40952d3
DM
948 foreach ($analysables as $analysableclass => $rangedata) {
949 foreach ($rangedata as $rangeindex => $data) {
950
951 // Attach samples data and calculated indicators data.
952 $this->get_target()->clear_sample_data();
953 $this->get_target()->add_sample_data($samplesdata);
954 $this->get_target()->add_sample_data($data->indicatorsdata);
955
1611308b 956 // Append new elements (we can not get duplicates because sample-analysable relation is N-1).
a40952d3 957 $range = $this->get_time_splitting()->get_range_by_index($rangeindex);
1611308b 958 $this->get_target()->filter_out_invalid_samples($data->sampleids, $data->analysable, false);
a40952d3
DM
959 $calculations = $this->get_target()->calculate($data->sampleids, $data->analysable, $range['start'], $range['end']);
960
961 // Missing $indicatorcalculations values in $calculations are caused by is_valid_sample. We need to remove
962 // these $uniquesampleid from $indicatorcalculations because otherwise they will be stored as calculated
963 // by self::save_prediction.
964 $indicatorcalculations = array_filter($indicatorcalculations, function($indicators, $uniquesampleid) use ($calculations) {
965 list($sampleid, $rangeindex) = $this->get_time_splitting()->infer_sample_info($uniquesampleid);
966 if (!isset($calculations[$sampleid])) {
a40952d3
DM
967 return false;
968 }
969 return true;
970 }, ARRAY_FILTER_USE_BOTH);
971
972 foreach ($calculations as $sampleid => $value) {
973
974 $uniquesampleid = $this->get_time_splitting()->append_rangeindex($sampleid, $rangeindex);
975
976 // Null means that the target couldn't calculate the sample, we also remove them from $indicatorcalculations.
977 if (is_null($calculations[$sampleid])) {
a40952d3
DM
978 unset($indicatorcalculations[$uniquesampleid]);
979 continue;
980 }
981
982 // Even if static predictions are based on assumptions we flag them as 100% because they are 100%
983 // true according to what the developer defined.
984 $predictions[$uniquesampleid] = (object)['prediction' => $value, 'predictionscore' => 1];
985 }
986 }
987 }
988 return $predictions;
989 }
990
369389c9 991 /**
1cc2b4ba 992 * Stores the prediction in the database.
369389c9
DM
993 *
994 * @param int $sampleid
995 * @param int $rangeindex
996 * @param int $prediction
997 * @param float $predictionscore
998 * @param string $calculations
999 * @return \context
1000 */
cab7abec 1001 protected function prepare_prediction_record($sampleid, $rangeindex, $prediction, $predictionscore, $calculations) {
369389c9
DM
1002 $context = $this->get_analyser()->sample_access_context($sampleid);
1003
1004 $record = new \stdClass();
1005 $record->modelid = $this->model->id;
1006 $record->contextid = $context->id;
1007 $record->sampleid = $sampleid;
1008 $record->rangeindex = $rangeindex;
1009 $record->prediction = $prediction;
1010 $record->predictionscore = $predictionscore;
1011 $record->calculations = $calculations;
1012 $record->timecreated = time();
369389c9 1013
f87174dc
MN
1014 $analysable = $this->get_analyser()->get_sample_analysable($sampleid);
1015 $timesplitting = $this->get_time_splitting();
1016 $timesplitting->set_analysable($analysable);
1017 $range = $timesplitting->get_range_by_index($rangeindex);
1018 if ($range) {
1019 $record->timestart = $range['start'];
1020 $record->timeend = $range['end'];
1021 }
1022
cab7abec
DM
1023 return array($record, $context);
1024 }
1025
1026 /**
1027 * Save the prediction objects.
1028 *
1029 * @param \stdClass[] $records
1030 */
1031 protected function save_predictions($records) {
1032 global $DB;
1033 $DB->insert_records('analytics_predictions', $records);
369389c9
DM
1034 }
1035
1036 /**
1cc2b4ba 1037 * Enabled the model using the provided time splitting method.
369389c9 1038 *
5c140ac4 1039 * @param string|false $timesplittingid False to respect the current time splitting method.
369389c9
DM
1040 * @return void
1041 */
1042 public function enable($timesplittingid = false) {
0af2421a 1043 global $DB, $USER;
369389c9 1044
1611308b
DM
1045 \core_analytics\manager::check_can_manage_models();
1046
369389c9
DM
1047 $now = time();
1048
1049 if ($timesplittingid && $timesplittingid !== $this->model->timesplitting) {
1050
1051 if (!\core_analytics\manager::is_valid($timesplittingid, '\core_analytics\local\time_splitting\base')) {
1052 throw new \moodle_exception('errorinvalidtimesplitting', 'analytics');
1053 }
1054
1055 if (substr($timesplittingid, 0, 1) !== '\\') {
1056 throw new \moodle_exception('errorinvalidtimesplitting', 'analytics');
1057 }
1058
abafbc84 1059 // Delete generated predictions before changing the model version.
325b3bdd 1060 $this->clear();
abafbc84
DM
1061
1062 // It needs to be reset as the version changes.
1063 $this->uniqueid = null;
1064
369389c9
DM
1065 $this->model->timesplitting = $timesplittingid;
1066 $this->model->version = $now;
abafbc84
DM
1067
1068 // Reset trained flag.
1069 if (!$this->is_static()) {
1070 $this->model->trained = 0;
1071 }
fabe98ac
AA
1072 } else if (empty($this->model->timesplitting)) {
1073 // A valid timesplitting method needs to be supplied before a model can be enabled.
1074 throw new \moodle_exception('invalidtimesplitting', 'analytics', '', $this->model->id);
1075
369389c9 1076 }
3e0f33aa
DM
1077
1078 // Purge pages with insights as this may change things.
abafbc84 1079 if ($this->model->enabled != 1) {
3e0f33aa
DM
1080 $this->purge_insights_cache();
1081 }
1082
369389c9
DM
1083 $this->model->enabled = 1;
1084 $this->model->timemodified = $now;
0af2421a 1085 $this->model->usermodified = $USER->id;
369389c9
DM
1086
1087 // We don't always update timemodified intentionally as we reserve it for target, indicators or timesplitting updates.
1088 $DB->update_record('analytics_models', $this->model);
369389c9
DM
1089 }
1090
a40952d3 1091 /**
1cc2b4ba
DM
1092 * Is this a static model (as defined by the target)?.
1093 *
1094 * Static models are based on assumptions instead of in machine learning
1095 * backends results.
a40952d3
DM
1096 *
1097 * @return bool
1098 */
1099 public function is_static() {
1100 return (bool)$this->get_target()->based_on_assumptions();
1101 }
1102
369389c9 1103 /**
1cc2b4ba 1104 * Is this model enabled?
369389c9
DM
1105 *
1106 * @return bool
1107 */
1108 public function is_enabled() {
1109 return (bool)$this->model->enabled;
1110 }
1111
1112 /**
1cc2b4ba 1113 * Is this model already trained?
369389c9
DM
1114 *
1115 * @return bool
1116 */
1117 public function is_trained() {
a40952d3
DM
1118 // Models which targets are based on assumptions do not need training.
1119 return (bool)$this->model->trained || $this->is_static();
369389c9
DM
1120 }
1121
1122 /**
1cc2b4ba 1123 * Marks the model as trained
369389c9
DM
1124 *
1125 * @return void
1126 */
1127 public function mark_as_trained() {
1128 global $DB;
1129
1611308b
DM
1130 \core_analytics\manager::check_can_manage_models();
1131
369389c9
DM
1132 $this->model->trained = 1;
1133 $DB->update_record('analytics_models', $this->model);
1134 }
1135
1136 /**
1cc2b4ba 1137 * Get the contexts with predictions.
369389c9 1138 *
2e151c3c 1139 * @param bool $skiphidden Skip hidden predictions
369389c9
DM
1140 * @return \stdClass[]
1141 */
2e151c3c
DM
1142 public function get_predictions_contexts($skiphidden = true) {
1143 global $DB, $USER;
369389c9 1144
4a210b06
DM
1145 $sql = "SELECT DISTINCT ap.contextid FROM {analytics_predictions} ap
1146 JOIN {context} ctx ON ctx.id = ap.contextid
2e151c3c
DM
1147 WHERE ap.modelid = :modelid";
1148 $params = array('modelid' => $this->model->id);
1149
1150 if ($skiphidden) {
1151 $sql .= " AND NOT EXISTS (
1152 SELECT 1
1153 FROM {analytics_prediction_actions} apa
1154 WHERE apa.predictionid = ap.id AND apa.userid = :userid AND (apa.actionname = :fixed OR apa.actionname = :notuseful)
1155 )";
1156 $params['userid'] = $USER->id;
1157 $params['fixed'] = \core_analytics\prediction::ACTION_FIXED;
1158 $params['notuseful'] = \core_analytics\prediction::ACTION_NOT_USEFUL;
1159 }
1160
1161 return $DB->get_records_sql($sql, $params);
369389c9
DM
1162 }
1163
f9e7447f
DM
1164 /**
1165 * Has this model generated predictions?
1166 *
1167 * We don't check analytics_predictions table because targets have the ability to
1168 * ignore some predicted values, if that is the case predictions are not even stored
1169 * in db.
1170 *
1171 * @return bool
1172 */
1173 public function any_prediction_obtained() {
1174 global $DB;
00da1e60 1175 return $DB->record_exists('analytics_predict_samples',
f9e7447f
DM
1176 array('modelid' => $this->model->id, 'timesplitting' => $this->model->timesplitting));
1177 }
1178
1179 /**
1180 * Whether this model generates insights or not (defined by the model's target).
1181 *
1182 * @return bool
1183 */
1184 public function uses_insights() {
1185 $target = $this->get_target();
1186 return $target::uses_insights();
1187 }
1188
369389c9
DM
1189 /**
1190 * Whether predictions exist for this context.
1191 *
1192 * @param \context $context
1193 * @return bool
1194 */
1195 public function predictions_exist(\context $context) {
1196 global $DB;
1197
1198 // Filters out previous predictions keeping only the last time range one.
1199 $select = "modelid = :modelid AND contextid = :contextid";
6ec2ae0f 1200 $params = array('modelid' => $this->model->id, 'contextid' => $context->id);
369389c9
DM
1201 return $DB->record_exists_select('analytics_predictions', $select, $params);
1202 }
1203
1204 /**
1205 * Gets the predictions for this context.
1206 *
1207 * @param \context $context
2e151c3c 1208 * @param bool $skiphidden Skip hidden predictions
21d4ae93
DM
1209 * @param int $page The page of results to fetch. False for all results.
1210 * @param int $perpage The max number of results to fetch. Ignored if $page is false.
68bfe1de 1211 * @return array($total, \core_analytics\prediction[])
369389c9 1212 */
025363d1
DM
1213 public function get_predictions(\context $context, $skiphidden = true, $page = false, $perpage = 100) {
1214 global $DB, $USER;
369389c9 1215
1611308b
DM
1216 \core_analytics\manager::check_can_list_insights($context);
1217
369389c9 1218 // Filters out previous predictions keeping only the last time range one.
4a210b06
DM
1219 $sql = "SELECT ap.*
1220 FROM {analytics_predictions} ap
369389c9
DM
1221 JOIN (
1222 SELECT sampleid, max(rangeindex) AS rangeindex
1223 FROM {analytics_predictions}
025363d1 1224 WHERE modelid = :modelidsubap and contextid = :contextidsubap
369389c9 1225 GROUP BY sampleid
4a210b06
DM
1226 ) apsub
1227 ON ap.sampleid = apsub.sampleid AND ap.rangeindex = apsub.rangeindex
025363d1
DM
1228 WHERE ap.modelid = :modelid and ap.contextid = :contextid";
1229
1230 $params = array('modelid' => $this->model->id, 'contextid' => $context->id,
1231 'modelidsubap' => $this->model->id, 'contextidsubap' => $context->id);
1232
1233 if ($skiphidden) {
1234 $sql .= " AND NOT EXISTS (
1235 SELECT 1
1236 FROM {analytics_prediction_actions} apa
1237 WHERE apa.predictionid = ap.id AND apa.userid = :userid AND (apa.actionname = :fixed OR apa.actionname = :notuseful)
1238 )";
1239 $params['userid'] = $USER->id;
1240 $params['fixed'] = \core_analytics\prediction::ACTION_FIXED;
1241 $params['notuseful'] = \core_analytics\prediction::ACTION_NOT_USEFUL;
1242 }
1243
1244 $sql .= " ORDER BY ap.timecreated DESC";
369389c9
DM
1245 if (!$predictions = $DB->get_records_sql($sql, $params)) {
1246 return array();
1247 }
1248
1249 // Get predicted samples' ids.
1250 $sampleids = array_map(function($prediction) {
1251 return $prediction->sampleid;
1252 }, $predictions);
1253
1254 list($unused, $samplesdata) = $this->get_analyser()->get_samples($sampleids);
1255
68bfe1de 1256 $current = 0;
21d4ae93
DM
1257
1258 if ($page !== false) {
1259 $offset = $page * $perpage;
1260 $limit = $offset + $perpage;
1261 }
68bfe1de 1262
369389c9
DM
1263 foreach ($predictions as $predictionid => $predictiondata) {
1264
1265 $sampleid = $predictiondata->sampleid;
1266
1267 // Filter out predictions which samples are not available anymore.
1268 if (empty($samplesdata[$sampleid])) {
1269 unset($predictions[$predictionid]);
1270 continue;
1271 }
1272
68bfe1de 1273 // Return paginated dataset - we cannot paginate in the DB because we post filter the list.
21d4ae93 1274 if ($page === false || ($current >= $offset && $current < $limit)) {
68bfe1de
DW
1275 // Replace \stdClass object by \core_analytics\prediction objects.
1276 $prediction = new \core_analytics\prediction($predictiondata, $samplesdata[$sampleid]);
1277 $predictions[$predictionid] = $prediction;
1278 } else {
1279 unset($predictions[$predictionid]);
1280 }
369389c9 1281
68bfe1de 1282 $current++;
369389c9
DM
1283 }
1284
68bfe1de 1285 return [$current, $predictions];
369389c9
DM
1286 }
1287
1288 /**
1611308b 1289 * Returns the sample data of a prediction.
369389c9
DM
1290 *
1291 * @param \stdClass $predictionobj
1292 * @return array
1293 */
1294 public function prediction_sample_data($predictionobj) {
1295
1296 list($unused, $samplesdata) = $this->get_analyser()->get_samples(array($predictionobj->sampleid));
1297
1298 if (empty($samplesdata[$predictionobj->sampleid])) {
1299 throw new \moodle_exception('errorsamplenotavailable', 'analytics');
1300 }
1301
1302 return $samplesdata[$predictionobj->sampleid];
1303 }
1304
1305 /**
1611308b 1306 * Returns the description of a sample
369389c9
DM
1307 *
1308 * @param \core_analytics\prediction $prediction
1309 * @return array 2 elements: list(string, \renderable)
1310 */
1311 public function prediction_sample_description(\core_analytics\prediction $prediction) {
1312 return $this->get_analyser()->sample_description($prediction->get_prediction_data()->sampleid,
1313 $prediction->get_prediction_data()->contextid, $prediction->get_sample_data());
1314 }
1315
1316 /**
1317 * Returns the output directory for prediction processors.
1318 *
1319 * Directory structure as follows:
1320 * - Evaluation runs:
1321 * models/$model->id/$model->version/evaluation/$model->timesplitting
1322 * - Training & prediction runs:
1323 * models/$model->id/$model->version/execution
1324 *
1325 * @param array $subdirs
abafbc84 1326 * @param bool $onlymodelid Preference over $subdirs
369389c9
DM
1327 * @return string
1328 */
c70a7194 1329 public function get_output_dir($subdirs = array(), $onlymodelid = false) {
369389c9
DM
1330 global $CFG;
1331
1332 $subdirstr = '';
1333 foreach ($subdirs as $subdir) {
1334 $subdirstr .= DIRECTORY_SEPARATOR . $subdir;
1335 }
1336
1337 $outputdir = get_config('analytics', 'modeloutputdir');
1338 if (empty($outputdir)) {
1339 // Apply default value.
1340 $outputdir = rtrim($CFG->dataroot, '/') . DIRECTORY_SEPARATOR . 'models';
1341 }
1342
325b3bdd 1343 // Append model id.
abafbc84
DM
1344 $outputdir .= DIRECTORY_SEPARATOR . $this->model->id;
1345 if (!$onlymodelid) {
1346 // Append version + subdirs.
1347 $outputdir .= DIRECTORY_SEPARATOR . $this->model->version . $subdirstr;
1348 }
369389c9
DM
1349
1350 make_writable_directory($outputdir);
1351
1352 return $outputdir;
1353 }
1354
1355 /**
1cc2b4ba
DM
1356 * Returns a unique id for this model.
1357 *
1358 * This id should be unique for this site.
369389c9
DM
1359 *
1360 * @return string
1361 */
1362 public function get_unique_id() {
1363 global $CFG;
1364
1365 if (!is_null($this->uniqueid)) {
1366 return $this->uniqueid;
1367 }
1368
1369 // Generate a unique id for this site, this model and this time splitting method, considering the last time
1370 // that the model target and indicators were updated.
b8fe16cd 1371 $ids = array($CFG->wwwroot, $CFG->prefix, $this->model->id, $this->model->version);
369389c9
DM
1372 $this->uniqueid = sha1(implode('$$', $ids));
1373
1374 return $this->uniqueid;
1375 }
1376
1377 /**
c70a7194 1378 * Exports the model data for displaying it in a template.
369389c9
DM
1379 *
1380 * @return \stdClass
1381 */
1382 public function export() {
1611308b
DM
1383
1384 \core_analytics\manager::check_can_manage_models();
1385
369389c9
DM
1386 $data = clone $this->model;
1387 $data->target = $this->get_target()->get_name();
1388
1389 if ($timesplitting = $this->get_time_splitting()) {
1390 $data->timesplitting = $timesplitting->get_name();
1391 }
1392
1393 $data->indicators = array();
1394 foreach ($this->get_indicators() as $indicator) {
1395 $data->indicators[] = $indicator->get_name();
1396 }
1397 return $data;
1398 }
1399
349c4412 1400 /**
c70a7194 1401 * Exports the model data to a zip file.
349c4412 1402 *
c70a7194
DM
1403 * @param string $zipfilename
1404 * @return string Zip file path
349c4412 1405 */
c70a7194 1406 public function export_model(string $zipfilename) : string {
349c4412 1407
e4453adc 1408 \core_analytics\manager::check_can_manage_models();
349c4412 1409
e4453adc 1410 $modelconfig = new model_config($this);
c70a7194
DM
1411 return $modelconfig->export($zipfilename);
1412 }
1413
1414 /**
1415 * Imports the provided model.
1416 *
1417 * Note that this method assumes that model_config::check_dependencies has already been called.
1418 *
1419 * @throws \moodle_exception
1420 * @param string $zipfilepath Zip file path
1421 * @return \core_analytics\model
1422 */
1423 public static function import_model(string $zipfilepath) : \core_analytics\model {
1424
1425 \core_analytics\manager::check_can_manage_models();
1426
1427 $modelconfig = new \core_analytics\model_config();
1428 return $modelconfig->import($zipfilepath);
e4453adc 1429 }
349c4412 1430
e4453adc
DM
1431 /**
1432 * Can this model be exported?
1433 *
1434 * @return bool
1435 */
1436 public function can_export_configuration() : bool {
1437
1438 if (empty($this->model->timesplitting)) {
1439 return false;
1440 }
1441 if (!$this->get_indicators()) {
1442 return false;
349c4412
AA
1443 }
1444
e4453adc
DM
1445 if ($this->is_static()) {
1446 return false;
349c4412 1447 }
e4453adc
DM
1448
1449 return true;
349c4412
AA
1450 }
1451
584ffa4f
DM
1452 /**
1453 * Returns the model logs data.
1454 *
1455 * @param int $limitfrom
1456 * @param int $limitnum
1457 * @return \stdClass[]
1458 */
1459 public function get_logs($limitfrom = 0, $limitnum = 0) {
1460 global $DB;
1611308b
DM
1461
1462 \core_analytics\manager::check_can_manage_models();
1463
584ffa4f
DM
1464 return $DB->get_records('analytics_models_log', array('modelid' => $this->get_id()), 'timecreated DESC', '*',
1465 $limitfrom, $limitnum);
1466 }
1467
d126f838
DM
1468 /**
1469 * Merges all training data files into one and returns it.
1470 *
1471 * @return \stored_file|false
1472 */
1473 public function get_training_data() {
1474
1475 \core_analytics\manager::check_can_manage_models();
1476
1477 $timesplittingid = $this->get_time_splitting()->get_id();
1478 return \core_analytics\dataset_manager::export_training_data($this->get_id(), $timesplittingid);
1479 }
1480
74823933
DM
1481 /**
1482 * Has the model been trained using data from this site?
1483 *
1484 * This method is useful to determine if a trained model can be evaluated as
1485 * we can not use the same data for training and for evaluation.
1486 *
1487 * @return bool
1488 */
bc82b895 1489 public function trained_locally() : bool {
74823933
DM
1490 global $DB;
1491
1492 if (!$this->is_trained() || $this->is_static()) {
1493 // Early exit.
1494 return false;
1495 }
1496
1497 if ($DB->record_exists('analytics_train_samples', ['modelid' => $this->model->id])) {
1498 return true;
1499 }
1500
1501 return false;
1502 }
1503
369389c9 1504 /**
1cc2b4ba 1505 * Flag the provided file as used for training or prediction.
369389c9
DM
1506 *
1507 * @param \stored_file $file
1508 * @param string $action
1509 * @return void
1510 */
1511 protected function flag_file_as_used(\stored_file $file, $action) {
1512 global $DB;
1513
1514 $usedfile = new \stdClass();
1515 $usedfile->modelid = $this->model->id;
1516 $usedfile->fileid = $file->get_id();
1517 $usedfile->action = $action;
1518 $usedfile->time = time();
1519 $DB->insert_record('analytics_used_files', $usedfile);
1520 }
1521
1522 /**
1cc2b4ba 1523 * Log the evaluation results in the database.
369389c9
DM
1524 *
1525 * @param string $timesplittingid
1526 * @param float $score
1527 * @param string $dir
1528 * @param array $info
1529 * @return int The inserted log id
1530 */
1531 protected function log_result($timesplittingid, $score, $dir = false, $info = false) {
1532 global $DB, $USER;
1533
1534 $log = new \stdClass();
1535 $log->modelid = $this->get_id();
1536 $log->version = $this->model->version;
1537 $log->target = $this->model->target;
1538 $log->indicators = $this->model->indicators;
1539 $log->timesplitting = $timesplittingid;
1540 $log->dir = $dir;
1541 if ($info) {
1542 // Ensure it is not an associative array.
1543 $log->info = json_encode(array_values($info));
1544 }
1545 $log->score = $score;
1546 $log->timecreated = time();
1547 $log->usermodified = $USER->id;
1548
1549 return $DB->insert_record('analytics_models_log', $log);
1550 }
1551
1552 /**
1553 * Utility method to return indicator class names from a list of indicator objects
1554 *
1555 * @param \core_analytics\local\indicator\base[] $indicators
1556 * @return string[]
1557 */
1558 private static function indicator_classes($indicators) {
1559
1560 // What we want to check and store are the indicator classes not the keys.
1561 $indicatorclasses = array();
1562 foreach ($indicators as $indicator) {
1563 if (!\core_analytics\manager::is_valid($indicator, '\core_analytics\local\indicator\base')) {
1564 if (!is_object($indicator) && !is_scalar($indicator)) {
1565 $indicator = strval($indicator);
1566 } else if (is_object($indicator)) {
3a396286 1567 $indicator = '\\' . get_class($indicator);
369389c9
DM
1568 }
1569 throw new \moodle_exception('errorinvalidindicator', 'analytics', '', $indicator);
1570 }
b0c24929 1571 $indicatorclasses[] = $indicator->get_id();
369389c9
DM
1572 }
1573
1574 return $indicatorclasses;
1575 }
1576
1577 /**
1578 * Clears the model training and prediction data.
1579 *
1580 * Executed after updating model critical elements like the time splitting method
1581 * or the indicators.
1582 *
1583 * @return void
1584 */
325b3bdd 1585 public function clear() {
0af2421a 1586 global $DB, $USER;
369389c9 1587
325b3bdd
DM
1588 \core_analytics\manager::check_can_manage_models();
1589
abafbc84 1590 // Delete current model version stored stuff.
d44ce97f
DM
1591 $predictor = $this->get_predictions_processor(false);
1592 if ($predictor->is_ready() !== true) {
1593 $predictorname = \core_analytics\manager::get_predictions_processor_name($predictor);
1594 debugging('Prediction processor ' . $predictorname . ' is not ready to be used. Model ' .
1595 $this->model->id . ' could not be cleared.');
1596 } else {
1597 $predictor->clear_model($this->get_unique_id(), $this->get_output_dir());
1598 }
abafbc84 1599
99b84a26
DM
1600 $predictionids = $DB->get_fieldset_select('analytics_predictions', 'id', 'modelid = :modelid',
1601 array('modelid' => $this->get_id()));
1602 if ($predictionids) {
1603 list($sql, $params) = $DB->get_in_or_equal($predictionids);
1604 $DB->delete_records_select('analytics_prediction_actions', "predictionid $sql", $params);
1605 }
1606
369389c9 1607 $DB->delete_records('analytics_predictions', array('modelid' => $this->model->id));
00da1e60 1608 $DB->delete_records('analytics_predict_samples', array('modelid' => $this->model->id));
369389c9
DM
1609 $DB->delete_records('analytics_train_samples', array('modelid' => $this->model->id));
1610 $DB->delete_records('analytics_used_files', array('modelid' => $this->model->id));
dd13fc22 1611 $DB->delete_records('analytics_used_analysables', array('modelid' => $this->model->id));
369389c9 1612
99b84a26
DM
1613 // Purge all generated files.
1614 \core_analytics\dataset_manager::clear_model_files($this->model->id);
1615
1611308b
DM
1616 // We don't expect people to clear models regularly and the cost of filling the cache is
1617 // 1 db read per context.
3e0f33aa 1618 $this->purge_insights_cache();
0af2421a
DM
1619
1620 $this->model->trained = 0;
1621 $this->model->timemodified = time();
1622 $this->model->usermodified = $USER->id;
1623 $DB->update_record('analytics_models', $this->model);
3e0f33aa
DM
1624 }
1625
1626 /**
1627 * Purges the insights cache.
1628 */
1629 private function purge_insights_cache() {
1611308b 1630 $cache = \cache::make('core', 'contextwithinsights');
1cc2b4ba 1631 $cache->purge();
369389c9
DM
1632 }
1633
1611308b
DM
1634 /**
1635 * Increases system memory and time limits.
1636 *
1637 * @return void
1638 */
1639 private function heavy_duty_mode() {
369389c9
DM
1640 if (ini_get('memory_limit') != -1) {
1641 raise_memory_limit(MEMORY_HUGE);
1642 }
1611308b 1643 \core_php_time_limit::raise();
369389c9 1644 }
369389c9 1645}