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