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