Merge branch 'install_master' of https://git.in.moodle.com/amosbot/moodle-install
[moodle.git] / analytics / classes / model.php
blob5385c29fc3b643ad288a0edf7c2962aff32c5662
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.
14 // You should have received a copy of the GNU General Public License
15 // along with Moodle. If not, see <http://www.gnu.org/licenses/>.
17 /**
18 * Prediction model representation.
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
25 namespace core_analytics;
27 defined('MOODLE_INTERNAL') || die();
29 /**
30 * Prediction model representation.
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
36 class model {
38 /**
39 * All as expected.
41 const OK = 0;
43 /**
44 * There was a problem.
46 const GENERAL_ERROR = 1;
48 /**
49 * No dataset to analyse.
51 const NO_DATASET = 2;
53 /**
54 * Model with low prediction accuracy.
56 const LOW_SCORE = 4;
58 /**
59 * Not enough data to evaluate the model properly.
61 const NOT_ENOUGH_DATA = 8;
63 /**
64 * Invalid analysable for the time splitting method.
66 const ANALYSABLE_REJECTED_TIME_SPLITTING_METHOD = 4;
68 /**
69 * Invalid analysable for all time splitting methods.
71 const ANALYSABLE_STATUS_INVALID_FOR_RANGEPROCESSORS = 8;
73 /**
74 * Invalid analysable for the target
76 const ANALYSABLE_STATUS_INVALID_FOR_TARGET = 16;
78 /**
79 * Minimum score to consider a non-static prediction model as good.
81 const MIN_SCORE = 0.7;
83 /**
84 * Minimum prediction confidence (from 0 to 1) to accept a prediction as reliable enough.
86 const PREDICTION_MIN_SCORE = 0.6;
88 /**
89 * Maximum standard deviation between different evaluation repetitions to consider that evaluation results are stable.
91 const ACCEPTED_DEVIATION = 0.05;
93 /**
94 * Number of evaluation repetitions.
96 const EVALUATION_ITERATIONS = 10;
98 /**
99 * @var \stdClass
101 protected $model = null;
104 * @var \core_analytics\local\analyser\base
106 protected $analyser = null;
109 * @var \core_analytics\local\target\base
111 protected $target = null;
114 * @var \core_analytics\predictor
116 protected $predictionsprocessor = null;
119 * @var \core_analytics\local\indicator\base[]
121 protected $indicators = null;
124 * @var \context[]
126 protected $contexts = null;
129 * Unique Model id created from site info and last model modification.
131 * @var string
133 protected $uniqueid = null;
136 * Constructor.
138 * @param int|\stdClass $model
139 * @return void
141 public function __construct($model) {
142 global $DB;
144 if (is_scalar($model)) {
145 $model = $DB->get_record('analytics_models', array('id' => $model), '*', MUST_EXIST);
146 if (!$model) {
147 throw new \moodle_exception('errorunexistingmodel', 'analytics', '', $model);
150 $this->model = $model;
154 * Quick safety check to discard site models which required components are not available anymore.
156 * @return bool
158 public function is_available() {
159 $target = $this->get_target();
160 if (!$target) {
161 return false;
164 $classname = $target->get_analyser_class();
165 if (!class_exists($classname)) {
166 return false;
169 return true;
173 * Returns the model id.
175 * @return int
177 public function get_id() {
178 return $this->model->id;
182 * Returns a plain \stdClass with the model data.
184 * @return \stdClass
186 public function get_model_obj() {
187 return $this->model;
191 * Returns the model target.
193 * @return \core_analytics\local\target\base
195 public function get_target() {
196 if ($this->target !== null) {
197 return $this->target;
199 $instance = \core_analytics\manager::get_target($this->model->target);
200 $this->target = $instance;
202 return $this->target;
206 * Returns the model indicators.
208 * @return \core_analytics\local\indicator\base[]
210 public function get_indicators() {
211 if ($this->indicators !== null) {
212 return $this->indicators;
215 $fullclassnames = json_decode($this->model->indicators);
217 if (!is_array($fullclassnames)) {
218 throw new \coding_exception('Model ' . $this->model->id . ' indicators can not be read');
221 $this->indicators = array();
222 foreach ($fullclassnames as $fullclassname) {
223 $instance = \core_analytics\manager::get_indicator($fullclassname);
224 if ($instance) {
225 $this->indicators[$fullclassname] = $instance;
226 } else {
227 debugging('Can\'t load ' . $fullclassname . ' indicator', DEBUG_DEVELOPER);
231 return $this->indicators;
235 * Returns the list of indicators that could potentially be used by the model target.
237 * It includes the indicators that are part of the model.
239 * @return \core_analytics\local\indicator\base[]
241 public function get_potential_indicators() {
243 $indicators = \core_analytics\manager::get_all_indicators();
245 if (empty($this->analyser)) {
246 $this->init_analyser(array('notimesplitting' => true));
249 foreach ($indicators as $classname => $indicator) {
250 if ($this->analyser->check_indicator_requirements($indicator) !== true) {
251 unset($indicators[$classname]);
254 return $indicators;
258 * Returns the model analyser (defined by the model target).
260 * @param array $options Default initialisation with no options.
261 * @return \core_analytics\local\analyser\base
263 public function get_analyser($options = array()) {
264 if ($this->analyser !== null) {
265 return $this->analyser;
268 $this->init_analyser($options);
270 return $this->analyser;
274 * Initialises the model analyser.
276 * @throws \coding_exception
277 * @param array $options
278 * @return void
280 protected function init_analyser($options = array()) {
282 $target = $this->get_target();
283 $indicators = $this->get_indicators();
285 if (empty($target)) {
286 throw new \moodle_exception('errornotarget', 'analytics');
289 $potentialtimesplittings = $this->get_potential_timesplittings();
291 $timesplittings = array();
292 if (empty($options['notimesplitting'])) {
293 if (!empty($options['evaluation'])) {
294 // The evaluation process will run using all available time splitting methods unless one is specified.
295 if (!empty($options['timesplitting'])) {
296 $timesplitting = \core_analytics\manager::get_time_splitting($options['timesplitting']);
298 if (empty($potentialtimesplittings[$timesplitting->get_id()])) {
299 throw new \moodle_exception('errorcannotusetimesplitting', 'analytics');
301 $timesplittings = array($timesplitting->get_id() => $timesplitting);
302 } else {
303 $timesplittingsforevaluation = \core_analytics\manager::get_time_splitting_methods_for_evaluation();
305 // They both have the same objects, using $potentialtimesplittings as its items are sorted.
306 $timesplittings = array_intersect_key($potentialtimesplittings, $timesplittingsforevaluation);
308 } else {
310 if (empty($this->model->timesplitting)) {
311 throw new \moodle_exception('invalidtimesplitting', 'analytics', '', $this->model->id);
314 // Returned as an array as all actions (evaluation, training and prediction) go through the same process.
315 $timesplittings = array($this->model->timesplitting => $this->get_time_splitting());
318 if (empty($timesplittings)) {
319 throw new \moodle_exception('errornotimesplittings', 'analytics');
323 $classname = $target->get_analyser_class();
324 if (!class_exists($classname)) {
325 throw new \coding_exception($classname . ' class does not exists');
328 // Returns a \core_analytics\local\analyser\base class.
329 $this->analyser = new $classname($this->model->id, $target, $indicators, $timesplittings, $options);
333 * Returns the model time splitting method.
335 * @return \core_analytics\local\time_splitting\base|false Returns false if no time splitting.
337 public function get_time_splitting() {
338 if (empty($this->model->timesplitting)) {
339 return false;
341 return \core_analytics\manager::get_time_splitting($this->model->timesplitting);
345 * Returns the time-splitting methods that can be used by this model.
347 * @return \core_analytics\local\time_splitting\base[]
349 public function get_potential_timesplittings() {
351 $timesplittings = \core_analytics\manager::get_all_time_splittings();
352 uasort($timesplittings, function($a, $b) {
353 return strcasecmp($a->get_name(), $b->get_name());
356 foreach ($timesplittings as $key => $timesplitting) {
357 if (!$this->get_target()->can_use_timesplitting($timesplitting)) {
358 unset($timesplittings[$key]);
359 continue;
362 return $timesplittings;
366 * Creates a new model. Enables it if $timesplittingid is specified.
368 * @param \core_analytics\local\target\base $target
369 * @param \core_analytics\local\indicator\base[] $indicators
370 * @param string|false $timesplittingid The time splitting method id (its fully qualified class name)
371 * @param string|null $processor The machine learning backend this model will use.
372 * @return \core_analytics\model
374 public static function create(\core_analytics\local\target\base $target, array $indicators,
375 $timesplittingid = false, $processor = null) {
376 global $USER, $DB;
378 $indicatorclasses = self::indicator_classes($indicators);
380 $now = time();
382 $modelobj = new \stdClass();
383 $modelobj->target = $target->get_id();
384 $modelobj->indicators = json_encode($indicatorclasses);
385 $modelobj->version = $now;
386 $modelobj->timecreated = $now;
387 $modelobj->timemodified = $now;
388 $modelobj->usermodified = $USER->id;
390 if ($target->based_on_assumptions()) {
391 $modelobj->trained = 1;
394 if ($timesplittingid) {
395 if (!\core_analytics\manager::is_valid($timesplittingid, '\core_analytics\local\time_splitting\base')) {
396 throw new \moodle_exception('errorinvalidtimesplitting', 'analytics');
398 if (substr($timesplittingid, 0, 1) !== '\\') {
399 throw new \moodle_exception('errorinvalidtimesplitting', 'analytics');
401 $modelobj->timesplitting = $timesplittingid;
404 if ($processor &&
405 !manager::is_valid($processor, '\core_analytics\classifier') &&
406 !manager::is_valid($processor, '\core_analytics\regressor')) {
407 throw new \coding_exception('The provided predictions processor \\' . $processor . '\processor is not valid');
408 } else {
409 $modelobj->predictionsprocessor = $processor;
412 $id = $DB->insert_record('analytics_models', $modelobj);
414 // Get db defaults.
415 $modelobj = $DB->get_record('analytics_models', array('id' => $id), '*', MUST_EXIST);
417 $model = new static($modelobj);
419 return $model;
423 * Does this model exist?
425 * If no indicators are provided it considers any model with the provided
426 * target a match.
428 * @param \core_analytics\local\target\base $target
429 * @param \core_analytics\local\indicator\base[]|false $indicators
430 * @return bool
432 public static function exists(\core_analytics\local\target\base $target, $indicators = false) {
433 global $DB;
435 $existingmodels = $DB->get_records('analytics_models', array('target' => $target->get_id()));
437 if (!$existingmodels) {
438 return false;
441 if (!$indicators && $existingmodels) {
442 return true;
445 $indicatorids = array_keys($indicators);
446 sort($indicatorids);
448 foreach ($existingmodels as $modelobj) {
449 $model = new \core_analytics\model($modelobj);
450 $modelindicatorids = array_keys($model->get_indicators());
451 sort($modelindicatorids);
453 if ($indicatorids === $modelindicatorids) {
454 return true;
457 return false;
461 * Updates the model.
463 * @param int|bool $enabled
464 * @param \core_analytics\local\indicator\base[]|false $indicators False to respect current indicators
465 * @param string|false $timesplittingid False to respect current time splitting method
466 * @param string|false $predictionsprocessor False to respect current predictors processor value
467 * @param int[]|false $contextids List of context ids for this model. False to respect the current list of contexts.
468 * @return void
470 public function update($enabled, $indicators = false, $timesplittingid = '', $predictionsprocessor = false,
471 $contextids = false) {
472 global $USER, $DB;
474 \core_analytics\manager::check_can_manage_models();
476 $now = time();
478 if ($indicators !== false) {
479 $indicatorclasses = self::indicator_classes($indicators);
480 $indicatorsstr = json_encode($indicatorclasses);
481 } else {
482 // Respect current value.
483 $indicatorsstr = $this->model->indicators;
486 if ($timesplittingid === false) {
487 // Respect current value.
488 $timesplittingid = $this->model->timesplitting;
491 if ($predictionsprocessor === false) {
492 // Respect current value.
493 $predictionsprocessor = $this->model->predictionsprocessor;
496 if ($contextids === false) {
497 $contextsstr = $this->model->contextids;
498 } else if (!$contextids) {
499 $contextsstr = null;
500 } else {
501 $contextsstr = json_encode($contextids);
503 // Reset the internal cache.
504 $this->contexts = null;
507 if ($this->model->timesplitting !== $timesplittingid ||
508 $this->model->indicators !== $indicatorsstr ||
509 $this->model->predictionsprocessor !== $predictionsprocessor) {
511 // Delete generated predictions before changing the model version.
512 $this->clear();
514 // It needs to be reset as the version changes.
515 $this->uniqueid = null;
516 $this->indicators = null;
518 // We update the version of the model so different time splittings are not mixed up.
519 $this->model->version = $now;
521 // Reset trained flag.
522 if (!$this->is_static()) {
523 $this->model->trained = 0;
526 } else if ($this->model->enabled != $enabled) {
527 // We purge the cached contexts with insights as some will not be visible anymore.
528 $this->purge_insights_cache();
531 $this->model->enabled = intval($enabled);
532 $this->model->indicators = $indicatorsstr;
533 $this->model->timesplitting = $timesplittingid;
534 $this->model->predictionsprocessor = $predictionsprocessor;
535 $this->model->contextids = $contextsstr;
536 $this->model->timemodified = $now;
537 $this->model->usermodified = $USER->id;
539 $DB->update_record('analytics_models', $this->model);
543 * Removes the model.
545 * @return void
547 public function delete() {
548 global $DB;
550 \core_analytics\manager::check_can_manage_models();
552 $this->clear();
554 // Method self::clear is already clearing the current model version.
555 $predictor = $this->get_predictions_processor(false);
556 if ($predictor->is_ready() !== true) {
557 $predictorname = \core_analytics\manager::get_predictions_processor_name($predictor);
558 debugging('Prediction processor ' . $predictorname . ' is not ready to be used. Model ' .
559 $this->model->id . ' could not be deleted.');
560 } else {
561 $predictor->delete_output_dir($this->get_output_dir(array(), true), $this->get_unique_id());
564 $DB->delete_records('analytics_models', array('id' => $this->model->id));
565 $DB->delete_records('analytics_models_log', array('modelid' => $this->model->id));
569 * Evaluates the model.
571 * This method gets the site contents (through the analyser) creates a .csv dataset
572 * with them and evaluates the model prediction accuracy multiple times using the
573 * machine learning backend. It returns an object where the model score is the average
574 * prediction accuracy of all executed evaluations.
576 * @param array $options
577 * @return \stdClass[]
579 public function evaluate($options = array()) {
581 \core_analytics\manager::check_can_manage_models();
583 if ($this->is_static()) {
584 $this->get_analyser()->add_log(get_string('noevaluationbasedassumptions', 'analytics'));
585 $result = new \stdClass();
586 $result->status = self::NO_DATASET;
587 return array($result);
590 $options['evaluation'] = true;
592 if (empty($options['mode'])) {
593 $options['mode'] = 'configuration';
596 switch ($options['mode']) {
597 case 'trainedmodel':
599 // We are only interested on the time splitting method used by the trained model.
600 $options['timesplitting'] = $this->model->timesplitting;
602 // Provide the trained model directory to the ML backend if that is what we want to evaluate.
603 $trainedmodeldir = $this->get_output_dir(['execution']);
604 break;
605 case 'configuration':
607 $trainedmodeldir = false;
608 break;
610 default:
611 throw new \moodle_exception('errorunknownaction', 'analytics');
614 $this->init_analyser($options);
616 if (empty($this->get_indicators())) {
617 throw new \moodle_exception('errornoindicators', 'analytics');
620 $this->heavy_duty_mode();
622 // Before get_labelled_data call so we get an early exception if it is not ready.
623 $predictor = $this->get_predictions_processor();
625 $datasets = $this->get_analyser()->get_labelled_data($this->get_contexts());
627 // No datasets generated.
628 if (empty($datasets)) {
629 $result = new \stdClass();
630 $result->status = self::NO_DATASET;
631 $result->info = $this->get_analyser()->get_logs();
632 return array($result);
635 if (!PHPUNIT_TEST && CLI_SCRIPT) {
636 echo PHP_EOL . get_string('processingsitecontents', 'analytics') . PHP_EOL;
639 $results = array();
640 foreach ($datasets as $timesplittingid => $dataset) {
642 $timesplitting = \core_analytics\manager::get_time_splitting($timesplittingid);
644 $result = new \stdClass();
646 $dashestimesplittingid = str_replace('\\', '', $timesplittingid);
647 $outputdir = $this->get_output_dir(array('evaluation', $dashestimesplittingid));
649 // Evaluate the dataset, the deviation we accept in the results depends on the amount of iterations.
650 if ($this->get_target()->is_linear()) {
651 $predictorresult = $predictor->evaluate_regression($this->get_unique_id(), self::ACCEPTED_DEVIATION,
652 self::EVALUATION_ITERATIONS, $dataset, $outputdir, $trainedmodeldir);
653 } else {
654 $predictorresult = $predictor->evaluate_classification($this->get_unique_id(), self::ACCEPTED_DEVIATION,
655 self::EVALUATION_ITERATIONS, $dataset, $outputdir, $trainedmodeldir);
658 $result->status = $predictorresult->status;
659 $result->info = $predictorresult->info;
661 if (isset($predictorresult->score)) {
662 $result->score = $predictorresult->score;
663 } else {
664 // Prediction processors may return an error, default to 0 score in that case.
665 $result->score = 0;
668 $dir = false;
669 if (!empty($predictorresult->dir)) {
670 $dir = $predictorresult->dir;
673 $result->logid = $this->log_result($timesplitting->get_id(), $result->score, $dir, $result->info, $options['mode']);
675 $results[$timesplitting->get_id()] = $result;
678 return $results;
682 * Trains the model using the site contents.
684 * This method prepares a dataset from the site contents (through the analyser)
685 * and passes it to the machine learning backends. Static models are skipped as
686 * they do not require training.
688 * @return \stdClass
690 public function train() {
692 \core_analytics\manager::check_can_manage_models();
694 if ($this->is_static()) {
695 $this->get_analyser()->add_log(get_string('notrainingbasedassumptions', 'analytics'));
696 $result = new \stdClass();
697 $result->status = self::OK;
698 return $result;
701 if (!$this->is_enabled() || empty($this->model->timesplitting)) {
702 throw new \moodle_exception('invalidtimesplitting', 'analytics', '', $this->model->id);
705 if (empty($this->get_indicators())) {
706 throw new \moodle_exception('errornoindicators', 'analytics');
709 $this->heavy_duty_mode();
711 // Before get_labelled_data call so we get an early exception if it is not writable.
712 $outputdir = $this->get_output_dir(array('execution'));
714 // Before get_labelled_data call so we get an early exception if it is not ready.
715 $predictor = $this->get_predictions_processor();
717 $datasets = $this->get_analyser()->get_labelled_data($this->get_contexts());
719 // No training if no files have been provided.
720 if (empty($datasets) || empty($datasets[$this->model->timesplitting])) {
722 $result = new \stdClass();
723 $result->status = self::NO_DATASET;
724 $result->info = $this->get_analyser()->get_logs();
725 return $result;
727 $samplesfile = $datasets[$this->model->timesplitting];
729 // Train using the dataset.
730 if ($this->get_target()->is_linear()) {
731 $predictorresult = $predictor->train_regression($this->get_unique_id(), $samplesfile, $outputdir);
732 } else {
733 $predictorresult = $predictor->train_classification($this->get_unique_id(), $samplesfile, $outputdir);
736 $result = new \stdClass();
737 $result->status = $predictorresult->status;
738 $result->info = $predictorresult->info;
740 if ($result->status !== self::OK) {
741 return $result;
744 $this->flag_file_as_used($samplesfile, 'trained');
746 // Mark the model as trained if it wasn't.
747 if ($this->model->trained == false) {
748 $this->mark_as_trained();
751 return $result;
755 * Get predictions from the site contents.
757 * It analyses the site contents (through analyser classes) looking for samples
758 * ready to receive predictions. It generates a dataset with all samples ready to
759 * get predictions and it passes it to the machine learning backends or to the
760 * targets based on assumptions to get the predictions.
762 * @return \stdClass
764 public function predict() {
765 global $DB;
767 \core_analytics\manager::check_can_manage_models();
769 if (!$this->is_enabled() || empty($this->model->timesplitting)) {
770 throw new \moodle_exception('invalidtimesplitting', 'analytics', '', $this->model->id);
773 if (empty($this->get_indicators())) {
774 throw new \moodle_exception('errornoindicators', 'analytics');
777 $this->heavy_duty_mode();
779 // Before get_unlabelled_data call so we get an early exception if it is not writable.
780 $outputdir = $this->get_output_dir(array('execution'));
782 if (!$this->is_static()) {
783 // Predictions using a machine learning backend.
785 // Before get_unlabelled_data call so we get an early exception if it is not ready.
786 $predictor = $this->get_predictions_processor();
788 $samplesdata = $this->get_analyser()->get_unlabelled_data($this->get_contexts());
790 // Get the prediction samples file.
791 if (empty($samplesdata) || empty($samplesdata[$this->model->timesplitting])) {
793 $result = new \stdClass();
794 $result->status = self::NO_DATASET;
795 $result->info = $this->get_analyser()->get_logs();
796 return $result;
798 $samplesfile = $samplesdata[$this->model->timesplitting];
800 // We need to throw an exception if we are trying to predict stuff that was already predicted.
801 $params = array('modelid' => $this->model->id, 'action' => 'predicted', 'fileid' => $samplesfile->get_id());
802 if ($predicted = $DB->get_record('analytics_used_files', $params)) {
803 throw new \moodle_exception('erroralreadypredict', 'analytics', '', $samplesfile->get_id());
806 $indicatorcalculations = \core_analytics\dataset_manager::get_structured_data($samplesfile);
808 // Estimation and classification processes run on the machine learning backend side.
809 if ($this->get_target()->is_linear()) {
810 $predictorresult = $predictor->estimate($this->get_unique_id(), $samplesfile, $outputdir);
811 } else {
812 $predictorresult = $predictor->classify($this->get_unique_id(), $samplesfile, $outputdir);
815 // Prepare the results object.
816 $result = new \stdClass();
817 $result->status = $predictorresult->status;
818 $result->info = $predictorresult->info;
819 $result->predictions = $this->format_predictor_predictions($predictorresult);
821 } else {
822 // Predictions based on assumptions.
824 $indicatorcalculations = $this->get_analyser()->get_static_data($this->get_contexts());
825 // Get the prediction samples file.
826 if (empty($indicatorcalculations) || empty($indicatorcalculations[$this->model->timesplitting])) {
828 $result = new \stdClass();
829 $result->status = self::NO_DATASET;
830 $result->info = $this->get_analyser()->get_logs();
831 return $result;
834 // Same as reset($indicatorcalculations) as models based on assumptions only analyse 1 single
835 // time-splitting method.
836 $indicatorcalculations = $indicatorcalculations[$this->model->timesplitting];
838 // Prepare the results object.
839 $result = new \stdClass();
840 $result->status = self::OK;
841 $result->info = [];
842 $result->predictions = $this->get_static_predictions($indicatorcalculations);
845 if ($result->status !== self::OK) {
846 return $result;
849 if ($result->predictions) {
850 list($samplecontexts, $predictionrecords) = $this->execute_prediction_callbacks($result->predictions,
851 $indicatorcalculations);
854 if (!empty($samplecontexts) && $this->uses_insights()) {
855 $this->trigger_insights($samplecontexts, $predictionrecords);
858 if (!$this->is_static()) {
859 $this->flag_file_as_used($samplesfile, 'predicted');
862 return $result;
866 * Returns the model predictions processor.
868 * @param bool $checkisready
869 * @return \core_analytics\predictor
871 public function get_predictions_processor($checkisready = true) {
872 return manager::get_predictions_processor($this->model->predictionsprocessor, $checkisready);
876 * Formats the predictor results.
878 * @param array $predictorresult
879 * @return array
881 private function format_predictor_predictions($predictorresult) {
883 $predictions = array();
884 if (!empty($predictorresult->predictions)) {
885 foreach ($predictorresult->predictions as $sampleinfo) {
887 // We parse each prediction.
888 switch (count($sampleinfo)) {
889 case 1:
890 // For whatever reason the predictions processor could not process this sample, we
891 // skip it and do nothing with it.
892 debugging($this->model->id . ' model predictions processor could not process the sample with id ' .
893 $sampleinfo[0], DEBUG_DEVELOPER);
894 continue 2;
895 case 2:
896 // Prediction processors that do not return a prediction score will have the maximum prediction
897 // score.
898 list($uniquesampleid, $prediction) = $sampleinfo;
899 $predictionscore = 1;
900 break;
901 case 3:
902 list($uniquesampleid, $prediction, $predictionscore) = $sampleinfo;
903 break;
904 default:
905 break;
907 $predictiondata = (object)['prediction' => $prediction, 'predictionscore' => $predictionscore];
908 $predictions[$uniquesampleid] = $predictiondata;
911 return $predictions;
915 * Execute the prediction callbacks defined by the target.
917 * @param \stdClass[] $predictions
918 * @param array $indicatorcalculations
919 * @return array
921 protected function execute_prediction_callbacks(&$predictions, $indicatorcalculations) {
923 // Here we will store all predictions' contexts, this will be used to limit which users will see those predictions.
924 $samplecontexts = array();
925 $records = array();
927 foreach ($predictions as $uniquesampleid => $prediction) {
929 // The unique sample id contains both the sampleid and the rangeindex.
930 list($sampleid, $rangeindex) = $this->get_time_splitting()->infer_sample_info($uniquesampleid);
931 if ($this->get_target()->triggers_callback($prediction->prediction, $prediction->predictionscore)) {
933 // Prepare the record to store the predicted values.
934 list($record, $samplecontext) = $this->prepare_prediction_record($sampleid, $rangeindex, $prediction->prediction,
935 $prediction->predictionscore, json_encode($indicatorcalculations[$uniquesampleid]));
937 // We will later bulk-insert them all.
938 $records[$uniquesampleid] = $record;
940 // Also store all samples context to later generate insights or whatever action the target wants to perform.
941 $samplecontexts[$samplecontext->id] = $samplecontext;
943 $this->get_target()->prediction_callback($this->model->id, $sampleid, $rangeindex, $samplecontext,
944 $prediction->prediction, $prediction->predictionscore);
948 if (!empty($records)) {
949 $this->save_predictions($records);
952 return [$samplecontexts, $records];
956 * Generates insights and updates the cache.
958 * @param \context[] $samplecontexts
959 * @param \stdClass[] $predictionrecords
960 * @return void
962 protected function trigger_insights($samplecontexts, $predictionrecords) {
964 // Notify the target that all predictions have been processed.
965 if ($this->get_analyser()::one_sample_per_analysable()) {
967 // We need to do something unusual here. self::save_predictions uses the bulk-insert function (insert_records()) for
968 // performance reasons and that function does not return us the inserted ids. We need to retrieve them from
969 // the database, and we need to do it using one single database query (for performance reasons as well).
970 $predictionrecords = $this->add_prediction_ids($predictionrecords);
972 $samplesdata = $this->predictions_sample_data($predictionrecords);
973 $samplesdata = $this->append_calculations_info($predictionrecords, $samplesdata);
975 $predictions = array_map(function($predictionobj) use ($samplesdata) {
976 $prediction = new \core_analytics\prediction($predictionobj, $samplesdata[$predictionobj->sampleid]);
977 return $prediction;
978 }, $predictionrecords);
979 } else {
980 $predictions = [];
983 $this->get_target()->generate_insight_notifications($this->model->id, $samplecontexts, $predictions);
985 if ($this->get_target()->link_insights_report()) {
987 // Update cache.
988 foreach ($samplecontexts as $context) {
989 \core_analytics\manager::cached_models_with_insights($context, $this->get_id());
995 * Get predictions from a static model.
997 * @param array $indicatorcalculations
998 * @return \stdClass[]
1000 protected function get_static_predictions(&$indicatorcalculations) {
1002 $headers = array_shift($indicatorcalculations);
1004 // Get rid of the sampleid header.
1005 array_shift($headers);
1007 // Group samples by analysable for \core_analytics\local\target::calculate.
1008 $analysables = array();
1009 // List all sampleids together.
1010 $sampleids = array();
1012 foreach ($indicatorcalculations as $uniquesampleid => $indicators) {
1014 // Get rid of the sampleid column.
1015 unset($indicators[0]);
1016 $indicators = array_combine($headers, $indicators);
1017 $indicatorcalculations[$uniquesampleid] = $indicators;
1019 list($sampleid, $rangeindex) = $this->get_time_splitting()->infer_sample_info($uniquesampleid);
1021 $analysable = $this->get_analyser()->get_sample_analysable($sampleid);
1022 $analysableclass = get_class($analysable);
1023 if (empty($analysables[$analysableclass])) {
1024 $analysables[$analysableclass] = array();
1026 if (empty($analysables[$analysableclass][$rangeindex])) {
1027 $analysables[$analysableclass][$rangeindex] = (object)[
1028 'analysable' => $analysable,
1029 'indicatorsdata' => array(),
1030 'sampleids' => array()
1034 // Using the sampleid as a key so we can easily merge indicators data later.
1035 $analysables[$analysableclass][$rangeindex]->indicatorsdata[$sampleid] = $indicators;
1036 // We could use indicatorsdata keys but the amount of redundant data is not that big and leaves code below cleaner.
1037 $analysables[$analysableclass][$rangeindex]->sampleids[$sampleid] = $sampleid;
1039 // Accumulate sample ids to get all their associated data in 1 single db query (analyser::get_samples).
1040 $sampleids[$sampleid] = $sampleid;
1043 // Get all samples data.
1044 list($sampleids, $samplesdata) = $this->get_samples($sampleids);
1046 // Calculate the targets.
1047 $predictions = array();
1048 foreach ($analysables as $analysableclass => $rangedata) {
1049 foreach ($rangedata as $rangeindex => $data) {
1051 // Attach samples data and calculated indicators data.
1052 $this->get_target()->clear_sample_data();
1053 $this->get_target()->add_sample_data($samplesdata);
1054 $this->get_target()->add_sample_data($data->indicatorsdata);
1056 // Append new elements (we can not get duplicates because sample-analysable relation is N-1).
1057 $timesplitting = $this->get_time_splitting();
1058 $timesplitting->set_modelid($this->get_id());
1059 $timesplitting->set_analysable($data->analysable);
1060 $range = $timesplitting->get_range_by_index($rangeindex);
1062 $this->get_target()->filter_out_invalid_samples($data->sampleids, $data->analysable, false);
1063 $calculations = $this->get_target()->calculate($data->sampleids, $data->analysable, $range['start'], $range['end']);
1065 // Missing $indicatorcalculations values in $calculations are caused by is_valid_sample. We need to remove
1066 // these $uniquesampleid from $indicatorcalculations because otherwise they will be stored as calculated
1067 // by self::save_prediction.
1068 $indicatorcalculations = array_filter($indicatorcalculations, function($indicators, $uniquesampleid)
1069 use ($calculations, $rangeindex) {
1070 list($sampleid, $indicatorsrangeindex) = $this->get_time_splitting()->infer_sample_info($uniquesampleid);
1071 if ($rangeindex == $indicatorsrangeindex && !isset($calculations[$sampleid])) {
1072 return false;
1074 return true;
1075 }, ARRAY_FILTER_USE_BOTH);
1077 foreach ($calculations as $sampleid => $value) {
1079 $uniquesampleid = $this->get_time_splitting()->append_rangeindex($sampleid, $rangeindex);
1081 // Null means that the target couldn't calculate the sample, we also remove them from $indicatorcalculations.
1082 if (is_null($calculations[$sampleid])) {
1083 unset($indicatorcalculations[$uniquesampleid]);
1084 continue;
1087 // Even if static predictions are based on assumptions we flag them as 100% because they are 100%
1088 // true according to what the developer defined.
1089 $predictions[$uniquesampleid] = (object)['prediction' => $value, 'predictionscore' => 1];
1093 return $predictions;
1097 * Stores the prediction in the database.
1099 * @param int $sampleid
1100 * @param int $rangeindex
1101 * @param int $prediction
1102 * @param float $predictionscore
1103 * @param string $calculations
1104 * @return \context
1106 protected function prepare_prediction_record($sampleid, $rangeindex, $prediction, $predictionscore, $calculations) {
1107 $context = $this->get_analyser()->sample_access_context($sampleid);
1109 $record = new \stdClass();
1110 $record->modelid = $this->model->id;
1111 $record->contextid = $context->id;
1112 $record->sampleid = $sampleid;
1113 $record->rangeindex = $rangeindex;
1114 $record->prediction = $prediction;
1115 $record->predictionscore = $predictionscore;
1116 $record->calculations = $calculations;
1117 $record->timecreated = time();
1119 $analysable = $this->get_analyser()->get_sample_analysable($sampleid);
1120 $timesplitting = $this->get_time_splitting();
1121 $timesplitting->set_modelid($this->get_id());
1122 $timesplitting->set_analysable($analysable);
1123 $range = $timesplitting->get_range_by_index($rangeindex);
1124 if ($range) {
1125 $record->timestart = $range['start'];
1126 $record->timeend = $range['end'];
1129 return array($record, $context);
1133 * Save the prediction objects.
1135 * @param \stdClass[] $records
1137 protected function save_predictions($records) {
1138 global $DB;
1139 $DB->insert_records('analytics_predictions', $records);
1143 * Enabled the model using the provided time splitting method.
1145 * @param string|false $timesplittingid False to respect the current time splitting method.
1146 * @return void
1148 public function enable($timesplittingid = false) {
1149 global $DB, $USER;
1151 $now = time();
1153 if ($timesplittingid && $timesplittingid !== $this->model->timesplitting) {
1155 if (!\core_analytics\manager::is_valid($timesplittingid, '\core_analytics\local\time_splitting\base')) {
1156 throw new \moodle_exception('errorinvalidtimesplitting', 'analytics');
1159 if (substr($timesplittingid, 0, 1) !== '\\') {
1160 throw new \moodle_exception('errorinvalidtimesplitting', 'analytics');
1163 // Delete generated predictions before changing the model version.
1164 $this->clear();
1166 // It needs to be reset as the version changes.
1167 $this->uniqueid = null;
1169 $this->model->timesplitting = $timesplittingid;
1170 $this->model->version = $now;
1172 // Reset trained flag.
1173 if (!$this->is_static()) {
1174 $this->model->trained = 0;
1176 } else if (empty($this->model->timesplitting)) {
1177 // A valid timesplitting method needs to be supplied before a model can be enabled.
1178 throw new \moodle_exception('invalidtimesplitting', 'analytics', '', $this->model->id);
1182 // Purge pages with insights as this may change things.
1183 if ($this->model->enabled != 1) {
1184 $this->purge_insights_cache();
1187 $this->model->enabled = 1;
1188 $this->model->timemodified = $now;
1189 $this->model->usermodified = $USER->id;
1191 // We don't always update timemodified intentionally as we reserve it for target, indicators or timesplitting updates.
1192 $DB->update_record('analytics_models', $this->model);
1196 * Is this a static model (as defined by the target)?.
1198 * Static models are based on assumptions instead of in machine learning
1199 * backends results.
1201 * @return bool
1203 public function is_static() {
1204 return (bool)$this->get_target()->based_on_assumptions();
1208 * Is this model enabled?
1210 * @return bool
1212 public function is_enabled() {
1213 return (bool)$this->model->enabled;
1217 * Is this model already trained?
1219 * @return bool
1221 public function is_trained() {
1222 // Models which targets are based on assumptions do not need training.
1223 return (bool)$this->model->trained || $this->is_static();
1227 * Marks the model as trained
1229 * @return void
1231 public function mark_as_trained() {
1232 global $DB;
1234 \core_analytics\manager::check_can_manage_models();
1236 $this->model->trained = 1;
1237 $DB->update_record('analytics_models', $this->model);
1241 * Get the contexts with predictions.
1243 * @param bool $skiphidden Skip hidden predictions
1244 * @return \stdClass[]
1246 public function get_predictions_contexts($skiphidden = true) {
1247 global $DB, $USER;
1249 $sql = "SELECT DISTINCT ap.contextid FROM {analytics_predictions} ap
1250 JOIN {context} ctx ON ctx.id = ap.contextid
1251 WHERE ap.modelid = :modelid";
1252 $params = array('modelid' => $this->model->id);
1254 if ($skiphidden) {
1255 $sql .= " AND NOT EXISTS (
1256 SELECT 1
1257 FROM {analytics_prediction_actions} apa
1258 WHERE apa.predictionid = ap.id AND apa.userid = :userid AND
1259 (apa.actionname = :fixed OR apa.actionname = :notuseful OR
1260 apa.actionname = :useful OR apa.actionname = :notapplicable OR
1261 apa.actionname = :incorrectlyflagged)
1263 $params['userid'] = $USER->id;
1264 $params['fixed'] = \core_analytics\prediction::ACTION_FIXED;
1265 $params['notuseful'] = \core_analytics\prediction::ACTION_NOT_USEFUL;
1266 $params['useful'] = \core_analytics\prediction::ACTION_USEFUL;
1267 $params['notapplicable'] = \core_analytics\prediction::ACTION_NOT_APPLICABLE;
1268 $params['incorrectlyflagged'] = \core_analytics\prediction::ACTION_INCORRECTLY_FLAGGED;
1271 return $DB->get_records_sql($sql, $params);
1275 * Has this model generated predictions?
1277 * We don't check analytics_predictions table because targets have the ability to
1278 * ignore some predicted values, if that is the case predictions are not even stored
1279 * in db.
1281 * @return bool
1283 public function any_prediction_obtained() {
1284 global $DB;
1285 return $DB->record_exists('analytics_predict_samples',
1286 array('modelid' => $this->model->id, 'timesplitting' => $this->model->timesplitting));
1290 * Whether this model generates insights or not (defined by the model's target).
1292 * @return bool
1294 public function uses_insights() {
1295 $target = $this->get_target();
1296 return $target::uses_insights();
1300 * Whether predictions exist for this context.
1302 * @param \context $context
1303 * @return bool
1305 public function predictions_exist(\context $context) {
1306 global $DB;
1308 // Filters out previous predictions keeping only the last time range one.
1309 $select = "modelid = :modelid AND contextid = :contextid";
1310 $params = array('modelid' => $this->model->id, 'contextid' => $context->id);
1311 return $DB->record_exists_select('analytics_predictions', $select, $params);
1315 * Gets the predictions for this context.
1317 * @param \context $context
1318 * @param bool $skiphidden Skip hidden predictions
1319 * @param int $page The page of results to fetch. False for all results.
1320 * @param int $perpage The max number of results to fetch. Ignored if $page is false.
1321 * @return array($total, \core_analytics\prediction[])
1323 public function get_predictions(\context $context, $skiphidden = true, $page = false, $perpage = 100) {
1324 global $DB, $USER;
1326 \core_analytics\manager::check_can_list_insights($context);
1328 // Filters out previous predictions keeping only the last time range one.
1329 $sql = "SELECT ap.*
1330 FROM {analytics_predictions} ap
1331 JOIN (
1332 SELECT sampleid, max(rangeindex) AS rangeindex
1333 FROM {analytics_predictions}
1334 WHERE modelid = :modelidsubap and contextid = :contextidsubap
1335 GROUP BY sampleid
1336 ) apsub
1337 ON ap.sampleid = apsub.sampleid AND ap.rangeindex = apsub.rangeindex
1338 WHERE ap.modelid = :modelid and ap.contextid = :contextid";
1340 $params = array('modelid' => $this->model->id, 'contextid' => $context->id,
1341 'modelidsubap' => $this->model->id, 'contextidsubap' => $context->id);
1343 if ($skiphidden) {
1344 $sql .= " AND NOT EXISTS (
1345 SELECT 1
1346 FROM {analytics_prediction_actions} apa
1347 WHERE apa.predictionid = ap.id AND apa.userid = :userid AND
1348 (apa.actionname = :fixed OR apa.actionname = :notuseful OR
1349 apa.actionname = :useful OR apa.actionname = :notapplicable OR
1350 apa.actionname = :incorrectlyflagged)
1352 $params['userid'] = $USER->id;
1353 $params['fixed'] = \core_analytics\prediction::ACTION_FIXED;
1354 $params['notuseful'] = \core_analytics\prediction::ACTION_NOT_USEFUL;
1355 $params['useful'] = \core_analytics\prediction::ACTION_USEFUL;
1356 $params['notapplicable'] = \core_analytics\prediction::ACTION_NOT_APPLICABLE;
1357 $params['incorrectlyflagged'] = \core_analytics\prediction::ACTION_INCORRECTLY_FLAGGED;
1360 $sql .= " ORDER BY ap.timecreated DESC";
1361 if (!$predictions = $DB->get_records_sql($sql, $params)) {
1362 return array();
1365 // Get predicted samples' ids.
1366 $sampleids = array_map(function($prediction) {
1367 return $prediction->sampleid;
1368 }, $predictions);
1370 list($unused, $samplesdata) = $this->get_samples($sampleids);
1372 $current = 0;
1374 if ($page !== false) {
1375 $offset = $page * $perpage;
1376 $limit = $offset + $perpage;
1379 foreach ($predictions as $predictionid => $predictiondata) {
1381 $sampleid = $predictiondata->sampleid;
1383 // Filter out predictions which samples are not available anymore.
1384 if (empty($samplesdata[$sampleid])) {
1385 unset($predictions[$predictionid]);
1386 continue;
1389 // Return paginated dataset - we cannot paginate in the DB because we post filter the list.
1390 if ($page === false || ($current >= $offset && $current < $limit)) {
1391 // Replace \stdClass object by \core_analytics\prediction objects.
1392 $prediction = new \core_analytics\prediction($predictiondata, $samplesdata[$sampleid]);
1393 $predictions[$predictionid] = $prediction;
1394 } else {
1395 unset($predictions[$predictionid]);
1398 $current++;
1401 if (empty($predictions)) {
1402 return array();
1405 return [$current, $predictions];
1409 * Returns the actions executed by users on the predictions.
1411 * @param \context|null $context
1412 * @return \moodle_recordset
1414 public function get_prediction_actions(?\context $context): \moodle_recordset {
1415 global $DB;
1417 $sql = "SELECT apa.id, apa.predictionid, apa.userid, apa.actionname, apa.timecreated,
1418 ap.contextid, ap.sampleid, ap.rangeindex, ap.prediction, ap.predictionscore
1419 FROM {analytics_prediction_actions} apa
1420 JOIN {analytics_predictions} ap ON ap.id = apa.predictionid
1421 WHERE ap.modelid = :modelid";
1422 $params = ['modelid' => $this->model->id];
1424 if ($context) {
1425 $sql .= " AND ap.contextid = :contextid";
1426 $params['contextid'] = $context->id;
1429 return $DB->get_recordset_sql($sql, $params);
1433 * Returns the sample data of a prediction.
1435 * @param \stdClass $predictionobj
1436 * @return array
1438 public function prediction_sample_data($predictionobj) {
1440 list($unused, $samplesdata) = $this->get_samples(array($predictionobj->sampleid));
1442 if (empty($samplesdata[$predictionobj->sampleid])) {
1443 throw new \moodle_exception('errorsamplenotavailable', 'analytics');
1446 return $samplesdata[$predictionobj->sampleid];
1450 * Returns the samples data of the provided predictions.
1452 * @param \stdClass[] $predictionrecords
1453 * @return array
1455 public function predictions_sample_data(array $predictionrecords): array {
1457 $sampleids = [];
1458 foreach ($predictionrecords as $predictionobj) {
1459 $sampleids[] = $predictionobj->sampleid;
1461 list($sampleids, $samplesdata) = $this->get_analyser()->get_samples($sampleids);
1463 return $samplesdata;
1467 * Appends the calculation info to the samples data.
1469 * @param \stdClass[] $predictionrecords
1470 * @param array $samplesdata
1471 * @return array
1473 public function append_calculations_info(array $predictionrecords, array $samplesdata): array {
1475 if ($extrainfo = calculation_info::pull_info($predictionrecords)) {
1476 foreach ($samplesdata as $sampleid => $data) {
1477 // The extra info come prefixed by extra: so we will not have overwrites here.
1478 $samplesdata[$sampleid] = $samplesdata[$sampleid] + $extrainfo[$sampleid];
1481 return $samplesdata;
1485 * Returns the description of a sample
1487 * @param \core_analytics\prediction $prediction
1488 * @return array 2 elements: list(string, \renderable)
1490 public function prediction_sample_description(\core_analytics\prediction $prediction) {
1491 return $this->get_analyser()->sample_description($prediction->get_prediction_data()->sampleid,
1492 $prediction->get_prediction_data()->contextid, $prediction->get_sample_data());
1496 * Returns the output directory for prediction processors.
1498 * Directory structure as follows:
1499 * - Evaluation runs:
1500 * models/$model->id/$model->version/evaluation/$model->timesplitting
1501 * - Training & prediction runs:
1502 * models/$model->id/$model->version/execution
1504 * @param array $subdirs
1505 * @param bool $onlymodelid Preference over $subdirs
1506 * @return string
1508 public function get_output_dir($subdirs = array(), $onlymodelid = false) {
1509 global $CFG;
1511 $subdirstr = '';
1512 foreach ($subdirs as $subdir) {
1513 $subdirstr .= DIRECTORY_SEPARATOR . $subdir;
1516 $outputdir = get_config('analytics', 'modeloutputdir');
1517 if (empty($outputdir)) {
1518 // Apply default value.
1519 $outputdir = rtrim($CFG->dataroot, '/') . DIRECTORY_SEPARATOR . 'models';
1522 // Append model id.
1523 $outputdir .= DIRECTORY_SEPARATOR . $this->model->id;
1524 if (!$onlymodelid) {
1525 // Append version + subdirs.
1526 $outputdir .= DIRECTORY_SEPARATOR . $this->model->version . $subdirstr;
1529 make_writable_directory($outputdir);
1531 return $outputdir;
1535 * Returns a unique id for this model.
1537 * This id should be unique for this site.
1539 * @return string
1541 public function get_unique_id() {
1542 global $CFG;
1544 if (!is_null($this->uniqueid)) {
1545 return $this->uniqueid;
1548 // Generate a unique id for this site, this model and this time splitting method, considering the last time
1549 // that the model target and indicators were updated.
1550 $ids = array($CFG->wwwroot, $CFG->prefix, $this->model->id, $this->model->version);
1551 $this->uniqueid = sha1(implode('$$', $ids));
1553 return $this->uniqueid;
1557 * Exports the model data for displaying it in a template.
1559 * @param \renderer_base $output The renderer to use for exporting
1560 * @return \stdClass
1562 public function export(\renderer_base $output) {
1564 \core_analytics\manager::check_can_manage_models();
1566 $data = clone $this->model;
1568 $data->modelname = format_string($this->get_name());
1569 $data->name = $this->inplace_editable_name()->export_for_template($output);
1570 $data->target = $this->get_target()->get_name();
1571 $data->targetclass = $this->get_target()->get_id();
1573 if ($timesplitting = $this->get_time_splitting()) {
1574 $data->timesplitting = $timesplitting->get_name();
1577 $data->indicators = array();
1578 foreach ($this->get_indicators() as $indicator) {
1579 $data->indicators[] = $indicator->get_name();
1581 return $data;
1585 * Exports the model data to a zip file.
1587 * @param string $zipfilename
1588 * @param bool $includeweights Include the model weights if available
1589 * @return string Zip file path
1591 public function export_model(string $zipfilename, bool $includeweights = true) : string {
1593 \core_analytics\manager::check_can_manage_models();
1595 $modelconfig = new model_config($this);
1596 return $modelconfig->export($zipfilename, $includeweights);
1600 * Imports the provided model.
1602 * Note that this method assumes that model_config::check_dependencies has already been called.
1604 * @throws \moodle_exception
1605 * @param string $zipfilepath Zip file path
1606 * @return \core_analytics\model
1608 public static function import_model(string $zipfilepath) : \core_analytics\model {
1610 \core_analytics\manager::check_can_manage_models();
1612 $modelconfig = new \core_analytics\model_config();
1613 return $modelconfig->import($zipfilepath);
1617 * Can this model be exported?
1619 * @return bool
1621 public function can_export_configuration() : bool {
1623 if (empty($this->model->timesplitting)) {
1624 return false;
1626 if (!$this->get_indicators()) {
1627 return false;
1630 if ($this->is_static()) {
1631 return false;
1634 return true;
1638 * Returns the model logs data.
1640 * @param int $limitfrom
1641 * @param int $limitnum
1642 * @return \stdClass[]
1644 public function get_logs($limitfrom = 0, $limitnum = 0) {
1645 global $DB;
1647 \core_analytics\manager::check_can_manage_models();
1649 return $DB->get_records('analytics_models_log', array('modelid' => $this->get_id()), 'timecreated DESC', '*',
1650 $limitfrom, $limitnum);
1654 * Merges all training data files into one and returns it.
1656 * @return \stored_file|false
1658 public function get_training_data() {
1660 \core_analytics\manager::check_can_manage_models();
1662 $timesplittingid = $this->get_time_splitting()->get_id();
1663 return \core_analytics\dataset_manager::export_training_data($this->get_id(), $timesplittingid);
1667 * Has the model been trained using data from this site?
1669 * This method is useful to determine if a trained model can be evaluated as
1670 * we can not use the same data for training and for evaluation.
1672 * @return bool
1674 public function trained_locally() : bool {
1675 global $DB;
1677 if (!$this->is_trained() || $this->is_static()) {
1678 // Early exit.
1679 return false;
1682 if ($DB->record_exists('analytics_train_samples', ['modelid' => $this->model->id])) {
1683 return true;
1686 return false;
1690 * Flag the provided file as used for training or prediction.
1692 * @param \stored_file $file
1693 * @param string $action
1694 * @return void
1696 protected function flag_file_as_used(\stored_file $file, $action) {
1697 global $DB;
1699 $usedfile = new \stdClass();
1700 $usedfile->modelid = $this->model->id;
1701 $usedfile->fileid = $file->get_id();
1702 $usedfile->action = $action;
1703 $usedfile->time = time();
1704 $DB->insert_record('analytics_used_files', $usedfile);
1708 * Log the evaluation results in the database.
1710 * @param string $timesplittingid
1711 * @param float $score
1712 * @param string $dir
1713 * @param array $info
1714 * @param string $evaluationmode
1715 * @return int The inserted log id
1717 protected function log_result($timesplittingid, $score, $dir = false, $info = false, $evaluationmode = 'configuration') {
1718 global $DB, $USER;
1720 $log = new \stdClass();
1721 $log->modelid = $this->get_id();
1722 $log->version = $this->model->version;
1723 $log->evaluationmode = $evaluationmode;
1724 $log->target = $this->model->target;
1725 $log->indicators = $this->model->indicators;
1726 $log->timesplitting = $timesplittingid;
1727 $log->dir = $dir;
1728 if ($info) {
1729 // Ensure it is not an associative array.
1730 $log->info = json_encode(array_values($info));
1732 $log->score = $score;
1733 $log->timecreated = time();
1734 $log->usermodified = $USER->id;
1736 return $DB->insert_record('analytics_models_log', $log);
1740 * Utility method to return indicator class names from a list of indicator objects
1742 * @param \core_analytics\local\indicator\base[] $indicators
1743 * @return string[]
1745 private static function indicator_classes($indicators) {
1747 // What we want to check and store are the indicator classes not the keys.
1748 $indicatorclasses = array();
1749 foreach ($indicators as $indicator) {
1750 if (!\core_analytics\manager::is_valid($indicator, '\core_analytics\local\indicator\base')) {
1751 if (!is_object($indicator) && !is_scalar($indicator)) {
1752 $indicator = strval($indicator);
1753 } else if (is_object($indicator)) {
1754 $indicator = '\\' . get_class($indicator);
1756 throw new \moodle_exception('errorinvalidindicator', 'analytics', '', $indicator);
1758 $indicatorclasses[] = $indicator->get_id();
1761 return $indicatorclasses;
1765 * Clears the model training and prediction data.
1767 * Executed after updating model critical elements like the time splitting method
1768 * or the indicators.
1770 * @return void
1772 public function clear() {
1773 global $DB, $USER;
1775 \core_analytics\manager::check_can_manage_models();
1777 // Delete current model version stored stuff.
1778 $predictor = $this->get_predictions_processor(false);
1779 if ($predictor->is_ready() !== true) {
1780 $predictorname = \core_analytics\manager::get_predictions_processor_name($predictor);
1781 debugging('Prediction processor ' . $predictorname . ' is not ready to be used. Model ' .
1782 $this->model->id . ' could not be cleared.');
1783 } else {
1784 $predictor->clear_model($this->get_unique_id(), $this->get_output_dir());
1787 $DB->delete_records_select('analytics_prediction_actions', "predictionid IN
1788 (SELECT id FROM {analytics_predictions} WHERE modelid = :modelid)", ['modelid' => $this->get_id()]);
1790 $DB->delete_records('analytics_predictions', array('modelid' => $this->model->id));
1791 $DB->delete_records('analytics_predict_samples', array('modelid' => $this->model->id));
1792 $DB->delete_records('analytics_train_samples', array('modelid' => $this->model->id));
1793 $DB->delete_records('analytics_used_files', array('modelid' => $this->model->id));
1794 $DB->delete_records('analytics_used_analysables', array('modelid' => $this->model->id));
1796 // Purge all generated files.
1797 \core_analytics\dataset_manager::clear_model_files($this->model->id);
1799 // We don't expect people to clear models regularly and the cost of filling the cache is
1800 // 1 db read per context.
1801 $this->purge_insights_cache();
1803 if (!$this->is_static()) {
1804 $this->model->trained = 0;
1807 $this->model->timemodified = time();
1808 $this->model->usermodified = $USER->id;
1809 $DB->update_record('analytics_models', $this->model);
1813 * Returns the name of the model.
1815 * By default, models use their target's name as their own name. They can have their explicit name, too. In which
1816 * case, the explicit name is used instead of the default one.
1818 * @return string|lang_string
1820 public function get_name() {
1822 if (trim($this->model->name) === '') {
1823 return $this->get_target()->get_name();
1825 } else {
1826 return $this->model->name;
1831 * Renames the model to the given name.
1833 * When given an empty string, the model falls back to using the associated target's name as its name.
1835 * @param string $name The new name for the model, empty string for using the default name.
1837 public function rename(string $name) {
1838 global $DB, $USER;
1840 $this->model->name = $name;
1841 $this->model->timemodified = time();
1842 $this->model->usermodified = $USER->id;
1844 $DB->update_record('analytics_models', $this->model);
1848 * Returns an inplace editable element with the model's name.
1850 * @return \core\output\inplace_editable
1852 public function inplace_editable_name() {
1854 $displayname = format_string($this->get_name());
1856 return new \core\output\inplace_editable('core_analytics', 'modelname', $this->model->id,
1857 has_capability('moodle/analytics:managemodels', \context_system::instance()), $displayname, $this->model->name);
1861 * Returns true if the time-splitting method used by this model is invalid for this model.
1862 * @return bool
1864 public function invalid_timesplitting_selected(): bool {
1865 $currenttimesplitting = $this->model->timesplitting;
1866 if (empty($currenttimesplitting)) {
1867 // Not set is different from invalid. This function is used to identify invalid
1868 // time-splittings.
1869 return false;
1872 $potentialtimesplittings = $this->get_potential_timesplittings();
1873 if ($currenttimesplitting && empty($potentialtimesplittings[$currenttimesplitting])) {
1874 return true;
1877 return false;
1881 * Adds the id from {analytics_predictions} db table to the prediction \stdClass objects.
1883 * @param \stdClass[] $predictionrecords
1884 * @return \stdClass[] The prediction records including their ids in {analytics_predictions} db table.
1886 private function add_prediction_ids($predictionrecords) {
1887 global $DB;
1889 $firstprediction = reset($predictionrecords);
1891 $contextids = array_map(function($predictionobj) {
1892 return $predictionobj->contextid;
1893 }, $predictionrecords);
1895 // Limited to 30000 records as a middle point between the ~65000 params limit in pgsql and the size limit for mysql which
1896 // can be increased if required up to a reasonable point.
1897 $chunks = array_chunk($contextids, 30000);
1898 foreach ($chunks as $contextidschunk) {
1899 list($contextsql, $contextparams) = $DB->get_in_or_equal($contextidschunk, SQL_PARAMS_NAMED);
1901 // We select the fields that will allow us to map ids to $predictionrecords. Given that we already filter by modelid
1902 // we have enough with sampleid and rangeindex. The reason is that the sampleid relation to a site is N - 1.
1903 $fields = 'id, sampleid, rangeindex';
1905 // We include the contextid and the timecreated filter to reduce the number of records in $dbpredictions. We can not
1906 // add as many OR conditions as records in $predictionrecords.
1907 $sql = "SELECT $fields
1908 FROM {analytics_predictions}
1909 WHERE modelid = :modelid
1910 AND contextid $contextsql
1911 AND timecreated >= :firsttimecreated";
1912 $params = $contextparams + ['modelid' => $this->model->id, 'firsttimecreated' => $firstprediction->timecreated];
1913 $dbpredictions = $DB->get_recordset_sql($sql, $params);
1914 foreach ($dbpredictions as $id => $dbprediction) {
1915 // The append_rangeindex implementation is the same regardless of the time splitting method in use.
1916 $uniqueid = $this->get_time_splitting()->append_rangeindex($dbprediction->sampleid, $dbprediction->rangeindex);
1917 $predictionrecords[$uniqueid]->id = $dbprediction->id;
1921 return $predictionrecords;
1925 * Wrapper around analyser's get_samples to skip DB's max-number-of-params exception.
1927 * @param array $sampleids
1928 * @return array
1930 public function get_samples(array $sampleids): array {
1932 if (empty($sampleids)) {
1933 throw new \coding_exception('No sample ids provided');
1936 $chunksize = count($sampleids);
1938 // We start with just 1 chunk, if it is too large for the db we split the list of sampleids in 2 and we
1939 // try again. We repeat this process until the chunk is small enough for the db engine to process. The
1940 // >= has been added in case there are other \dml_read_exceptions unrelated to the max number of params.
1941 while (empty($done) && $chunksize >= 1) {
1943 $chunks = array_chunk($sampleids, $chunksize);
1944 $allsampleids = [];
1945 $allsamplesdata = [];
1947 foreach ($chunks as $index => $chunk) {
1949 try {
1950 list($chunksampleids, $chunksamplesdata) = $this->get_analyser()->get_samples($chunk);
1951 } catch (\dml_read_exception $e) {
1953 // Reduce the chunksize, we use floor() so the $chunksize is always less than the previous $chunksize value.
1954 $chunksize = floor($chunksize / 2);
1955 break;
1958 // We can sum as these two arrays are indexed by sampleid and there are no collisions.
1959 $allsampleids = $allsampleids + $chunksampleids;
1960 $allsamplesdata = $allsamplesdata + $chunksamplesdata;
1962 if ($index === count($chunks) - 1) {
1963 // We successfully processed all the samples in all chunks, we are done.
1964 $done = true;
1969 if (empty($done)) {
1970 if (!empty($e)) {
1971 // Throw the last exception we caught, the \dml_read_exception we have been catching is unrelated to the max number
1972 // of param's exception.
1973 throw new \dml_read_exception($e);
1974 } else {
1975 throw new \coding_exception('We should never reach this point, there is a bug in ' .
1976 'core_analytics\\model::get_samples\'s code');
1979 return [$allsampleids, $allsamplesdata];
1983 * Contexts where this model should be active.
1985 * @return \context[] Empty array if there are no context restrictions.
1987 public function get_contexts() {
1988 if ($this->contexts !== null) {
1989 return $this->contexts;
1992 if (!$this->model->contextids) {
1993 $this->contexts = [];
1994 return $this->contexts;
1996 $contextids = json_decode($this->model->contextids);
1998 // We don't expect this list to be massive as contexts need to be selected manually using the edit model form.
1999 $this->contexts = array_map(function($contextid) {
2000 return \context::instance_by_id($contextid, IGNORE_MISSING);
2001 }, $contextids);
2003 return $this->contexts;
2007 * Purges the insights cache.
2009 private function purge_insights_cache() {
2010 $cache = \cache::make('core', 'contextwithinsights');
2011 $cache->purge();
2015 * Increases system memory and time limits.
2017 * @return void
2019 private function heavy_duty_mode() {
2020 if (ini_get('memory_limit') != -1) {
2021 raise_memory_limit(MEMORY_HUGE);
2023 \core_php_time_limit::raise();