forked from moodle/moodle
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathmodel.php
2034 lines (1670 loc) · 71.2 KB
/
model.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
<?php
// This file is part of Moodle - http://moodle.org/
//
// Moodle is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// Moodle is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with Moodle. If not, see <http://www.gnu.org/licenses/>.
/**
* Prediction model representation.
*
* @package core_analytics
* @copyright 2016 David Monllao {@link http://www.davidmonllao.com}
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
namespace core_analytics;
defined('MOODLE_INTERNAL') || die();
/**
* Prediction model representation.
*
* @package core_analytics
* @copyright 2016 David Monllao {@link http://www.davidmonllao.com}
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
class model {
/**
* All as expected.
*/
const OK = 0;
/**
* There was a problem.
*/
const GENERAL_ERROR = 1;
/**
* No dataset to analyse.
*/
const NO_DATASET = 2;
/**
* Model with low prediction accuracy.
*/
const LOW_SCORE = 4;
/**
* Not enough data to evaluate the model properly.
*/
const NOT_ENOUGH_DATA = 8;
/**
* Invalid analysable for the time splitting method.
*/
const ANALYSABLE_REJECTED_TIME_SPLITTING_METHOD = 4;
/**
* Invalid analysable for all time splitting methods.
*/
const ANALYSABLE_STATUS_INVALID_FOR_RANGEPROCESSORS = 8;
/**
* Invalid analysable for the target
*/
const ANALYSABLE_STATUS_INVALID_FOR_TARGET = 16;
/**
* Minimum score to consider a non-static prediction model as good.
*/
const MIN_SCORE = 0.7;
/**
* Minimum prediction confidence (from 0 to 1) to accept a prediction as reliable enough.
*/
const PREDICTION_MIN_SCORE = 0.6;
/**
* Maximum standard deviation between different evaluation repetitions to consider that evaluation results are stable.
*/
const ACCEPTED_DEVIATION = 0.05;
/**
* Number of evaluation repetitions.
*/
const EVALUATION_ITERATIONS = 10;
/**
* @var \stdClass
*/
protected $model = null;
/**
* @var \core_analytics\local\analyser\base
*/
protected $analyser = null;
/**
* @var \core_analytics\local\target\base
*/
protected $target = null;
/**
* @var \core_analytics\predictor
*/
protected $predictionsprocessor = null;
/**
* @var \core_analytics\local\indicator\base[]
*/
protected $indicators = null;
/**
* @var \context[]
*/
protected $contexts = null;
/**
* Unique Model id created from site info and last model modification.
*
* @var string
*/
protected $uniqueid = null;
/**
* Constructor.
*
* @param int|\stdClass $model
* @return void
*/
public function __construct($model) {
global $DB;
if (is_scalar($model)) {
$model = $DB->get_record('analytics_models', array('id' => $model), '*', MUST_EXIST);
if (!$model) {
throw new \moodle_exception('errorunexistingmodel', 'analytics', '', $model);
}
}
$this->model = $model;
}
/**
* Quick safety check to discard site models which required components are not available anymore.
*
* @return bool
*/
public function is_available() {
$target = $this->get_target();
if (!$target) {
return false;
}
$classname = $target->get_analyser_class();
if (!class_exists($classname)) {
return false;
}
return true;
}
/**
* Returns the model id.
*
* @return int
*/
public function get_id() {
return $this->model->id;
}
/**
* Returns a plain \stdClass with the model data.
*
* @return \stdClass
*/
public function get_model_obj() {
return $this->model;
}
/**
* Returns the model target.
*
* @return \core_analytics\local\target\base
*/
public function get_target() {
if ($this->target !== null) {
return $this->target;
}
$instance = \core_analytics\manager::get_target($this->model->target);
$this->target = $instance;
return $this->target;
}
/**
* Returns the model indicators.
*
* @return \core_analytics\local\indicator\base[]
*/
public function get_indicators() {
if ($this->indicators !== null) {
return $this->indicators;
}
$fullclassnames = json_decode($this->model->indicators);
if (!is_array($fullclassnames)) {
throw new \coding_exception('Model ' . $this->model->id . ' indicators can not be read');
}
$this->indicators = array();
foreach ($fullclassnames as $fullclassname) {
$instance = \core_analytics\manager::get_indicator($fullclassname);
if ($instance) {
$this->indicators[$fullclassname] = $instance;
} else {
debugging('Can\'t load ' . $fullclassname . ' indicator', DEBUG_DEVELOPER);
}
}
return $this->indicators;
}
/**
* Returns the list of indicators that could potentially be used by the model target.
*
* It includes the indicators that are part of the model.
*
* @return \core_analytics\local\indicator\base[]
*/
public function get_potential_indicators() {
$indicators = \core_analytics\manager::get_all_indicators();
if (empty($this->analyser)) {
$this->init_analyser(array('notimesplitting' => true));
}
foreach ($indicators as $classname => $indicator) {
if ($this->analyser->check_indicator_requirements($indicator) !== true) {
unset($indicators[$classname]);
}
}
return $indicators;
}
/**
* Returns the model analyser (defined by the model target).
*
* @param array $options Default initialisation with no options.
* @return \core_analytics\local\analyser\base
*/
public function get_analyser($options = array()) {
if ($this->analyser !== null) {
return $this->analyser;
}
$this->init_analyser($options);
return $this->analyser;
}
/**
* Initialises the model analyser.
*
* @throws \coding_exception
* @param array $options
* @return void
*/
protected function init_analyser($options = array()) {
$target = $this->get_target();
$indicators = $this->get_indicators();
if (empty($target)) {
throw new \moodle_exception('errornotarget', 'analytics');
}
$potentialtimesplittings = $this->get_potential_timesplittings();
$timesplittings = array();
if (empty($options['notimesplitting'])) {
if (!empty($options['evaluation'])) {
// The evaluation process will run using all available time splitting methods unless one is specified.
if (!empty($options['timesplitting'])) {
$timesplitting = \core_analytics\manager::get_time_splitting($options['timesplitting']);
if (empty($potentialtimesplittings[$timesplitting->get_id()])) {
throw new \moodle_exception('errorcannotusetimesplitting', 'analytics');
}
$timesplittings = array($timesplitting->get_id() => $timesplitting);
} else {
$timesplittingsforevaluation = \core_analytics\manager::get_time_splitting_methods_for_evaluation();
// They both have the same objects, using $potentialtimesplittings as its items are sorted.
$timesplittings = array_intersect_key($potentialtimesplittings, $timesplittingsforevaluation);
}
} else {
if (empty($this->model->timesplitting)) {
throw new \moodle_exception('invalidtimesplitting', 'analytics', '', $this->model->id);
}
// Returned as an array as all actions (evaluation, training and prediction) go through the same process.
$timesplittings = array($this->model->timesplitting => $this->get_time_splitting());
}
if (empty($timesplittings)) {
throw new \moodle_exception('errornotimesplittings', 'analytics');
}
}
$classname = $target->get_analyser_class();
if (!class_exists($classname)) {
throw new \coding_exception($classname . ' class does not exists');
}
// Returns a \core_analytics\local\analyser\base class.
$this->analyser = new $classname($this->model->id, $target, $indicators, $timesplittings, $options);
}
/**
* Returns the model time splitting method.
*
* @return \core_analytics\local\time_splitting\base|false Returns false if no time splitting.
*/
public function get_time_splitting() {
if (empty($this->model->timesplitting)) {
return false;
}
return \core_analytics\manager::get_time_splitting($this->model->timesplitting);
}
/**
* Returns the time-splitting methods that can be used by this model.
*
* @return \core_analytics\local\time_splitting\base[]
*/
public function get_potential_timesplittings() {
$timesplittings = \core_analytics\manager::get_all_time_splittings();
uasort($timesplittings, function($a, $b) {
return strcasecmp($a->get_name(), $b->get_name());
});
foreach ($timesplittings as $key => $timesplitting) {
if (!$this->get_target()->can_use_timesplitting($timesplitting)) {
unset($timesplittings[$key]);
continue;
}
}
return $timesplittings;
}
/**
* Creates a new model. Enables it if $timesplittingid is specified.
*
* @param \core_analytics\local\target\base $target
* @param \core_analytics\local\indicator\base[] $indicators
* @param string|false $timesplittingid The time splitting method id (its fully qualified class name)
* @param string|null $processor The machine learning backend this model will use.
* @return \core_analytics\model
*/
public static function create(\core_analytics\local\target\base $target, array $indicators,
$timesplittingid = false, $processor = null) {
global $USER, $DB;
$indicatorclasses = self::indicator_classes($indicators);
$now = time();
$modelobj = new \stdClass();
$modelobj->target = $target->get_id();
$modelobj->indicators = json_encode($indicatorclasses);
$modelobj->version = $now;
$modelobj->timecreated = $now;
$modelobj->timemodified = $now;
$modelobj->usermodified = $USER->id;
if ($target->based_on_assumptions()) {
$modelobj->trained = 1;
}
if ($timesplittingid) {
if (!\core_analytics\manager::is_valid($timesplittingid, '\core_analytics\local\time_splitting\base')) {
throw new \moodle_exception('errorinvalidtimesplitting', 'analytics');
}
if (substr($timesplittingid, 0, 1) !== '\\') {
throw new \moodle_exception('errorinvalidtimesplitting', 'analytics');
}
$modelobj->timesplitting = $timesplittingid;
}
if ($processor &&
!manager::is_valid($processor, '\core_analytics\classifier') &&
!manager::is_valid($processor, '\core_analytics\regressor')) {
throw new \coding_exception('The provided predictions processor \\' . $processor . '\processor is not valid');
} else {
$modelobj->predictionsprocessor = $processor;
}
$id = $DB->insert_record('analytics_models', $modelobj);
// Get db defaults.
$modelobj = $DB->get_record('analytics_models', array('id' => $id), '*', MUST_EXIST);
$model = new static($modelobj);
return $model;
}
/**
* Does this model exist?
*
* If no indicators are provided it considers any model with the provided
* target a match.
*
* @param \core_analytics\local\target\base $target
* @param \core_analytics\local\indicator\base[]|false $indicators
* @return bool
*/
public static function exists(\core_analytics\local\target\base $target, $indicators = false) {
global $DB;
$existingmodels = $DB->get_records('analytics_models', array('target' => $target->get_id()));
if (!$existingmodels) {
return false;
}
if (!$indicators && $existingmodels) {
return true;
}
$indicatorids = array_keys($indicators);
sort($indicatorids);
foreach ($existingmodels as $modelobj) {
$model = new \core_analytics\model($modelobj);
$modelindicatorids = array_keys($model->get_indicators());
sort($modelindicatorids);
if ($indicatorids === $modelindicatorids) {
return true;
}
}
return false;
}
/**
* Updates the model.
*
* @param int|bool $enabled
* @param \core_analytics\local\indicator\base[]|false $indicators False to respect current indicators
* @param string|false $timesplittingid False to respect current time splitting method
* @param string|false $predictionsprocessor False to respect current predictors processor value
* @param int[]|false $contextids List of context ids for this model. False to respect the current list of contexts.
* @return void
*/
public function update($enabled, $indicators = false, $timesplittingid = '', $predictionsprocessor = false,
$contextids = false) {
global $USER, $DB;
\core_analytics\manager::check_can_manage_models();
$now = time();
if ($indicators !== false) {
$indicatorclasses = self::indicator_classes($indicators);
$indicatorsstr = json_encode($indicatorclasses);
} else {
// Respect current value.
$indicatorsstr = $this->model->indicators;
}
if ($timesplittingid === false) {
// Respect current value.
$timesplittingid = $this->model->timesplitting;
}
if ($predictionsprocessor === false) {
// Respect current value.
$predictionsprocessor = $this->model->predictionsprocessor;
}
if ($contextids === false) {
$contextsstr = $this->model->contextids;
} else if (!$contextids) {
$contextsstr = null;
} else {
$contextsstr = json_encode($contextids);
// Reset the internal cache.
$this->contexts = null;
}
if ($this->model->timesplitting !== $timesplittingid ||
$this->model->indicators !== $indicatorsstr ||
$this->model->predictionsprocessor !== $predictionsprocessor) {
// Delete generated predictions before changing the model version.
$this->clear();
// It needs to be reset as the version changes.
$this->uniqueid = null;
$this->indicators = null;
// We update the version of the model so different time splittings are not mixed up.
$this->model->version = $now;
// Reset trained flag.
if (!$this->is_static()) {
$this->model->trained = 0;
}
} else if ($this->model->enabled != $enabled) {
// We purge the cached contexts with insights as some will not be visible anymore.
$this->purge_insights_cache();
}
$this->model->enabled = intval($enabled);
$this->model->indicators = $indicatorsstr;
$this->model->timesplitting = $timesplittingid;
$this->model->predictionsprocessor = $predictionsprocessor;
$this->model->contextids = $contextsstr;
$this->model->timemodified = $now;
$this->model->usermodified = $USER->id;
$DB->update_record('analytics_models', $this->model);
}
/**
* Removes the model.
*
* @return void
*/
public function delete() {
global $DB;
\core_analytics\manager::check_can_manage_models();
$this->clear();
// Method self::clear is already clearing the current model version.
$predictor = $this->get_predictions_processor(false);
if ($predictor->is_ready() !== true) {
$predictorname = \core_analytics\manager::get_predictions_processor_name($predictor);
debugging('Prediction processor ' . $predictorname . ' is not ready to be used. Model ' .
$this->model->id . ' could not be deleted.');
} else {
$predictor->delete_output_dir($this->get_output_dir(array(), true), $this->get_unique_id());
}
$DB->delete_records('analytics_models', array('id' => $this->model->id));
$DB->delete_records('analytics_models_log', array('modelid' => $this->model->id));
}
/**
* Evaluates the model.
*
* This method gets the site contents (through the analyser) creates a .csv dataset
* with them and evaluates the model prediction accuracy multiple times using the
* machine learning backend. It returns an object where the model score is the average
* prediction accuracy of all executed evaluations.
*
* @param array $options
* @return \stdClass[]
*/
public function evaluate($options = array()) {
\core_analytics\manager::check_can_manage_models();
if ($this->is_static()) {
$this->get_analyser()->add_log(get_string('noevaluationbasedassumptions', 'analytics'));
$result = new \stdClass();
$result->status = self::NO_DATASET;
return array($result);
}
$options['evaluation'] = true;
if (empty($options['mode'])) {
$options['mode'] = 'configuration';
}
switch ($options['mode']) {
case 'trainedmodel':
// We are only interested on the time splitting method used by the trained model.
$options['timesplitting'] = $this->model->timesplitting;
// Provide the trained model directory to the ML backend if that is what we want to evaluate.
$trainedmodeldir = $this->get_output_dir(['execution']);
break;
case 'configuration':
$trainedmodeldir = false;
break;
default:
throw new \moodle_exception('errorunknownaction', 'analytics');
}
$this->init_analyser($options);
if (empty($this->get_indicators())) {
throw new \moodle_exception('errornoindicators', 'analytics');
}
$this->heavy_duty_mode();
// Before get_labelled_data call so we get an early exception if it is not ready.
$predictor = $this->get_predictions_processor();
$datasets = $this->get_analyser()->get_labelled_data($this->get_contexts());
// No datasets generated.
if (empty($datasets)) {
$result = new \stdClass();
$result->status = self::NO_DATASET;
$result->info = $this->get_analyser()->get_logs();
return array($result);
}
if (!PHPUNIT_TEST && CLI_SCRIPT) {
echo PHP_EOL . get_string('processingsitecontents', 'analytics') . PHP_EOL;
}
$results = array();
foreach ($datasets as $timesplittingid => $dataset) {
$timesplitting = \core_analytics\manager::get_time_splitting($timesplittingid);
$result = new \stdClass();
$dashestimesplittingid = str_replace('\\', '', $timesplittingid);
$outputdir = $this->get_output_dir(array('evaluation', $dashestimesplittingid));
// Evaluate the dataset, the deviation we accept in the results depends on the amount of iterations.
if ($this->get_target()->is_linear()) {
$predictorresult = $predictor->evaluate_regression($this->get_unique_id(), self::ACCEPTED_DEVIATION,
self::EVALUATION_ITERATIONS, $dataset, $outputdir, $trainedmodeldir);
} else {
$predictorresult = $predictor->evaluate_classification($this->get_unique_id(), self::ACCEPTED_DEVIATION,
self::EVALUATION_ITERATIONS, $dataset, $outputdir, $trainedmodeldir);
}
$result->status = $predictorresult->status;
$result->info = $predictorresult->info;
if (isset($predictorresult->score)) {
$result->score = $predictorresult->score;
} else {
// Prediction processors may return an error, default to 0 score in that case.
$result->score = 0;
}
$dir = false;
if (!empty($predictorresult->dir)) {
$dir = $predictorresult->dir;
}
$result->logid = $this->log_result($timesplitting->get_id(), $result->score, $dir, $result->info, $options['mode']);
$results[$timesplitting->get_id()] = $result;
}
return $results;
}
/**
* Trains the model using the site contents.
*
* This method prepares a dataset from the site contents (through the analyser)
* and passes it to the machine learning backends. Static models are skipped as
* they do not require training.
*
* @return \stdClass
*/
public function train() {
\core_analytics\manager::check_can_manage_models();
if ($this->is_static()) {
$this->get_analyser()->add_log(get_string('notrainingbasedassumptions', 'analytics'));
$result = new \stdClass();
$result->status = self::OK;
return $result;
}
if (!$this->is_enabled() || empty($this->model->timesplitting)) {
throw new \moodle_exception('invalidtimesplitting', 'analytics', '', $this->model->id);
}
if (empty($this->get_indicators())) {
throw new \moodle_exception('errornoindicators', 'analytics');
}
$this->heavy_duty_mode();
// Before get_labelled_data call so we get an early exception if it is not writable.
$outputdir = $this->get_output_dir(array('execution'));
// Before get_labelled_data call so we get an early exception if it is not ready.
$predictor = $this->get_predictions_processor();
$datasets = $this->get_analyser()->get_labelled_data($this->get_contexts());
// No training if no files have been provided.
if (empty($datasets) || empty($datasets[$this->model->timesplitting])) {
$result = new \stdClass();
$result->status = self::NO_DATASET;
$result->info = $this->get_analyser()->get_logs();
return $result;
}
$samplesfile = $datasets[$this->model->timesplitting];
// Train using the dataset.
if ($this->get_target()->is_linear()) {
$predictorresult = $predictor->train_regression($this->get_unique_id(), $samplesfile, $outputdir);
} else {
$predictorresult = $predictor->train_classification($this->get_unique_id(), $samplesfile, $outputdir);
}
$result = new \stdClass();
$result->status = $predictorresult->status;
$result->info = $predictorresult->info;
if ($result->status !== self::OK) {
return $result;
}
$this->flag_file_as_used($samplesfile, 'trained');
// Mark the model as trained if it wasn't.
if ($this->model->trained == false) {
$this->mark_as_trained();
}
return $result;
}
/**
* Get predictions from the site contents.
*
* It analyses the site contents (through analyser classes) looking for samples
* ready to receive predictions. It generates a dataset with all samples ready to
* get predictions and it passes it to the machine learning backends or to the
* targets based on assumptions to get the predictions.
*
* @return \stdClass
*/
public function predict() {
global $DB;
\core_analytics\manager::check_can_manage_models();
if (!$this->is_enabled() || empty($this->model->timesplitting)) {
throw new \moodle_exception('invalidtimesplitting', 'analytics', '', $this->model->id);
}
if (empty($this->get_indicators())) {
throw new \moodle_exception('errornoindicators', 'analytics');
}
$this->heavy_duty_mode();
// Before get_unlabelled_data call so we get an early exception if it is not writable.
$outputdir = $this->get_output_dir(array('execution'));
if (!$this->is_static()) {
// Predictions using a machine learning backend.
// Before get_unlabelled_data call so we get an early exception if it is not ready.
$predictor = $this->get_predictions_processor();
$samplesdata = $this->get_analyser()->get_unlabelled_data($this->get_contexts());
// Get the prediction samples file.
if (empty($samplesdata) || empty($samplesdata[$this->model->timesplitting])) {
$result = new \stdClass();
$result->status = self::NO_DATASET;
$result->info = $this->get_analyser()->get_logs();
return $result;
}
$samplesfile = $samplesdata[$this->model->timesplitting];
// We need to throw an exception if we are trying to predict stuff that was already predicted.
$params = array('modelid' => $this->model->id, 'action' => 'predicted', 'fileid' => $samplesfile->get_id());
if ($predicted = $DB->get_record('analytics_used_files', $params)) {
throw new \moodle_exception('erroralreadypredict', 'analytics', '', $samplesfile->get_id());
}
$indicatorcalculations = \core_analytics\dataset_manager::get_structured_data($samplesfile);
// Estimation and classification processes run on the machine learning backend side.
if ($this->get_target()->is_linear()) {
$predictorresult = $predictor->estimate($this->get_unique_id(), $samplesfile, $outputdir);
} else {
$predictorresult = $predictor->classify($this->get_unique_id(), $samplesfile, $outputdir);
}
// Prepare the results object.
$result = new \stdClass();
$result->status = $predictorresult->status;
$result->info = $predictorresult->info;
$result->predictions = $this->format_predictor_predictions($predictorresult);
} else {
// Predictions based on assumptions.
$indicatorcalculations = $this->get_analyser()->get_static_data($this->get_contexts());
// Get the prediction samples file.
if (empty($indicatorcalculations) || empty($indicatorcalculations[$this->model->timesplitting])) {
$result = new \stdClass();
$result->status = self::NO_DATASET;
$result->info = $this->get_analyser()->get_logs();
return $result;
}
// Same as reset($indicatorcalculations) as models based on assumptions only analyse 1 single
// time-splitting method.
$indicatorcalculations = $indicatorcalculations[$this->model->timesplitting];
// Prepare the results object.
$result = new \stdClass();
$result->status = self::OK;
$result->info = [];
$result->predictions = $this->get_static_predictions($indicatorcalculations);
}
if ($result->status !== self::OK) {
return $result;
}
if ($result->predictions) {
list($samplecontexts, $predictionrecords) = $this->execute_prediction_callbacks($result->predictions,
$indicatorcalculations);
}
if (!empty($samplecontexts) && $this->uses_insights()) {
$this->trigger_insights($samplecontexts, $predictionrecords);
}
if (!$this->is_static()) {
$this->flag_file_as_used($samplesfile, 'predicted');
}
return $result;
}
/**
* Returns the model predictions processor.
*
* @param bool $checkisready
* @return \core_analytics\predictor
*/
public function get_predictions_processor($checkisready = true) {
return manager::get_predictions_processor($this->model->predictionsprocessor, $checkisready);
}
/**
* Formats the predictor results.
*
* @param array $predictorresult
* @return array
*/
private function format_predictor_predictions($predictorresult) {
$predictions = array();
if (!empty($predictorresult->predictions)) {
foreach ($predictorresult->predictions as $sampleinfo) {
// We parse each prediction.
switch (count($sampleinfo)) {
case 1:
// For whatever reason the predictions processor could not process this sample, we
// skip it and do nothing with it.
debugging($this->model->id . ' model predictions processor could not process the sample with id ' .
$sampleinfo[0], DEBUG_DEVELOPER);
continue 2;
case 2:
// Prediction processors that do not return a prediction score will have the maximum prediction
// score.
list($uniquesampleid, $prediction) = $sampleinfo;
$predictionscore = 1;
break;
case 3:
list($uniquesampleid, $prediction, $predictionscore) = $sampleinfo;
break;
default:
break;
}
$predictiondata = (object)['prediction' => $prediction, 'predictionscore' => $predictionscore];
$predictions[$uniquesampleid] = $predictiondata;
}
}
return $predictions;
}
/**
* Execute the prediction callbacks defined by the target.
*
* @param \stdClass[] $predictions
* @param array $indicatorcalculations
* @return array
*/
protected function execute_prediction_callbacks(&$predictions, $indicatorcalculations) {
// Here we will store all predictions' contexts, this will be used to limit which users will see those predictions.
$samplecontexts = array();
$records = array();
foreach ($predictions as $uniquesampleid => $prediction) {
// The unique sample id contains both the sampleid and the rangeindex.
list($sampleid, $rangeindex) = $this->get_time_splitting()->infer_sample_info($uniquesampleid);
if ($this->get_target()->triggers_callback($prediction->prediction, $prediction->predictionscore)) {
// Prepare the record to store the predicted values.
list($record, $samplecontext) = $this->prepare_prediction_record($sampleid, $rangeindex, $prediction->prediction,
$prediction->predictionscore, json_encode($indicatorcalculations[$uniquesampleid]));
// We will later bulk-insert them all.
$records[$uniquesampleid] = $record;
// Also store all samples context to later generate insights or whatever action the target wants to perform.
$samplecontexts[$samplecontext->id] = $samplecontext;
$this->get_target()->prediction_callback($this->model->id, $sampleid, $rangeindex, $samplecontext,
$prediction->prediction, $prediction->predictionscore);
}
}
if (!empty($records)) {
$this->save_predictions($records);
}
return [$samplecontexts, $records];
}
/**
* Generates insights and updates the cache.
*
* @param \context[] $samplecontexts
* @param \stdClass[] $predictionrecords
* @return void
*/
protected function trigger_insights($samplecontexts, $predictionrecords) {
// Notify the target that all predictions have been processed.
if ($this->get_analyser()::one_sample_per_analysable()) {
// We need to do something unusual here. self::save_predictions uses the bulk-insert function (insert_records()) for
// performance reasons and that function does not return us the inserted ids. We need to retrieve them from
// the database, and we need to do it using one single database query (for performance reasons as well).
$predictionrecords = $this->add_prediction_ids($predictionrecords);
$samplesdata = $this->predictions_sample_data($predictionrecords);
$samplesdata = $this->append_calculations_info($predictionrecords, $samplesdata);
$predictions = array_map(function($predictionobj) use ($samplesdata) {
$prediction = new \core_analytics\prediction($predictionobj, $samplesdata[$predictionobj->sampleid]);
return $prediction;
}, $predictionrecords);
} else {
$predictions = [];
}
$this->get_target()->generate_insight_notifications($this->model->id, $samplecontexts, $predictions);
if ($this->get_target()->link_insights_report()) {
// Update cache.
foreach ($samplecontexts as $context) {
\core_analytics\manager::cached_models_with_insights($context, $this->get_id());
}
}
}
/**
* Get predictions from a static model.
*
* @param array $indicatorcalculations
* @return \stdClass[]
*/
protected function get_static_predictions(&$indicatorcalculations) {