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