a717cabc428fdb76c858e8e8fd81778a5142409a
[moodle.git] / admin / tool / analytics / classes / output / models_list.php
1 <?php
2 // This file is part of Moodle - http://moodle.org/
3 //
4 // Moodle is free software: you can redistribute it and/or modify
5 // it under the terms of the GNU General Public License as published by
6 // the Free Software Foundation, either version 3 of the License, or
7 // (at your option) any later version.
8 //
9 // Moodle is distributed in the hope that it will be useful,
10 // but WITHOUT ANY WARRANTY; without even the implied warranty of
11 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12 // GNU General Public License for more details.
13 //
14 // You should have received a copy of the GNU General Public License
15 // along with Moodle.  If not, see <http://www.gnu.org/licenses/>.
17 /**
18  * Prediction models list page.
19  *
20  * @package    tool_analytics
21  * @copyright  2016 David Monllao {@link http://www.davidmonllao.com}
22  * @license    http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
23  */
25 namespace tool_analytics\output;
27 defined('MOODLE_INTERNAL') || die();
29 /**
30  * Shows tool_analytics models list.
31  *
32  * @package    tool_analytics
33  * @copyright  2016 David Monllao {@link http://www.davidmonllao.com}
34  * @license    http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
35  */
36 class models_list implements \renderable, \templatable {
38     /**
39      * models
40      *
41      * @var \core_analytics\model[]
42      */
43     protected $models = array();
45     /**
46      * __construct
47      *
48      * @param \core_analytics\model[] $models
49      * @return void
50      */
51     public function __construct($models) {
52         $this->models = $models;
53     }
55     /**
56      * Exports the data.
57      *
58      * @param \renderer_base $output
59      * @return \stdClass
60      */
61     public function export_for_template(\renderer_base $output) {
62         global $PAGE;
64         $data = new \stdClass();
65         $data->importmodelurl = new \moodle_url('/admin/tool/analytics/importmodel.php');
66         $data->createmodelurl = new \moodle_url('/admin/tool/analytics/createmodel.php');
68         $onlycli = get_config('analytics', 'onlycli');
69         if ($onlycli === false) {
70             // Default applied if no config found.
71             $onlycli = 1;
72         }
74         // Evaluation options.
75         $timesplittingmethods = [
76             ['id' => 'all', 'text' => get_string('alltimesplittingmethods', 'tool_analytics')],
77         ];
78         foreach (\core_analytics\manager::get_time_splitting_methods_for_evaluation(true) as $timesplitting) {
79             $timesplittingmethods[] = [
80                 'id' => \tool_analytics\output\helper::class_to_option($timesplitting->get_id()),
81                 'text' => $timesplitting->get_name()->out(),
82             ];
83         }
85         $data->models = array();
86         foreach ($this->models as $model) {
87             $modeldata = $model->export($output);
89             // Check if there is a help icon for the target to show.
90             $identifier = $modeldata->target->get_identifier();
91             $component = $modeldata->target->get_component();
92             if (get_string_manager()->string_exists($identifier . '_help', $component)) {
93                 $helpicon = new \help_icon($identifier, $component);
94                 $modeldata->targethelp = $helpicon->export_for_template($output);
95             } else {
96                 // We really want to encourage developers to add help to their targets.
97                 debugging("The target '{$modeldata->target}' should include a '{$identifier}_help' string to
98                     describe its purpose.", DEBUG_DEVELOPER);
99             }
101             // Check if there is a help icon for the indicators to show.
102             if (!empty($modeldata->indicators)) {
103                 $indicators = array();
104                 foreach ($modeldata->indicators as $ind) {
105                     // Create the indicator with the details we want for the context.
106                     $indicator = new \stdClass();
107                     $indicator->name = $ind->out();
108                     $identifier = $ind->get_identifier();
109                     $component = $ind->get_component();
110                     if (get_string_manager()->string_exists($identifier . '_help', $component)) {
111                         $helpicon = new \help_icon($identifier, $component);
112                         $indicator->help = $helpicon->export_for_template($output);
113                     } else {
114                         // We really want to encourage developers to add help to their indicators.
115                         debugging("The indicator '{$ind}' should include a '{$identifier}_help' string to
116                             describe its purpose.", DEBUG_DEVELOPER);
117                     }
118                     $indicators[] = $indicator;
119                 }
120                 $modeldata->indicators = $indicators;
121             }
123             // Check if there is a help icon for the time splitting method.
124             if (!empty($modeldata->timesplitting)) {
125                 $identifier = $modeldata->timesplitting->get_identifier();
126                 $component = $modeldata->timesplitting->get_component();
127                 if (get_string_manager()->string_exists($identifier . '_help', $component)) {
128                     $helpicon = new \help_icon($identifier, $component);
129                     $modeldata->timesplittinghelp = $helpicon->export_for_template($output);
130                 } else {
131                     // We really want to encourage developers to add help to their time splitting methods.
132                     debugging("The time splitting method '{$modeldata->timesplitting}' should include a '{$identifier}_help'
133                         string to describe its purpose.", DEBUG_DEVELOPER);
134                 }
135             } else {
136                 $helpicon = new \help_icon('timesplittingnotdefined', 'tool_analytics');
137                 $modeldata->timesplittinghelp = $helpicon->export_for_template($output);
138             }
140             // Has this model generated predictions?.
141             $predictioncontexts = $model->get_predictions_contexts();
143             // Model predictions list.
144             if (!$model->is_enabled()) {
145                 $modeldata->noinsights = get_string('disabledmodel', 'analytics');
146             } else if ($model->uses_insights()) {
147                 if ($predictioncontexts) {
149                     foreach ($predictioncontexts as $contextid => $unused) {
150                         // We prepare this to be used as single_select template options.
151                         $context = \context::instance_by_id($contextid);
153                         // Special name for system level predictions as showing "System is not visually nice".
154                         if ($contextid == SYSCONTEXTID) {
155                             $contextname = get_string('allpredictions', 'tool_analytics');
156                         } else {
157                             $contextname = shorten_text($context->get_context_name(true, true), 90);
158                         }
159                         $predictioncontexts[$contextid] = $contextname;
160                     }
161                     \core_collator::asort($predictioncontexts);
163                     if (!empty($predictioncontexts)) {
164                         $url = new \moodle_url('/report/insights/insights.php', array('modelid' => $model->get_id()));
165                         $singleselect = new \single_select($url, 'contextid', $predictioncontexts);
166                         $modeldata->insights = $singleselect->export_for_template($output);
167                     }
168                 }
170                 if (empty($modeldata->insights)) {
171                     if ($model->any_prediction_obtained()) {
172                         $modeldata->noinsights = get_string('noinsights', 'analytics');
173                     } else {
174                         $modeldata->noinsights = get_string('nopredictionsyet', 'analytics');
175                     }
176                 }
178             } else {
179                 $modeldata->noinsights = get_string('noinsightsmodel', 'analytics');
180             }
182             // Actions.
183             $actionsmenu = new \action_menu();
184             $actionsmenu->set_menu_trigger(get_string('actions'));
185             $actionsmenu->set_owner_selector('model-actions-' . $model->get_id());
186             $actionsmenu->set_alignment(\action_menu::TL, \action_menu::BL);
188             $urlparams = ['id' => $model->get_id(), 'sesskey' => sesskey()];
190             // Get predictions.
191             if (!$onlycli && $modeldata->enabled && !empty($modeldata->timesplitting)) {
192                 $urlparams['action'] = 'getpredictions';
193                 $url = new \moodle_url('model.php', $urlparams);
194                 $icon = new \action_menu_link_secondary($url, new \pix_icon('i/notifications',
195                     get_string('getpredictions', 'tool_analytics')), get_string('getpredictions', 'tool_analytics'));
196                 $actionsmenu->add($icon);
197             }
199             // Evaluate machine-learning-based models.
200             if (!$onlycli && $model->get_indicators() && !$model->is_static()) {
202                 // Extra is_trained call as trained_locally returns false if the model has not been trained yet.
203                 $trainedonlyexternally = !$model->trained_locally() && $model->is_trained();
205                 $actionid = 'evaluate-' . $model->get_id();
207                 $modeltimesplittingmethods = $timesplittingmethods;
208                 // Include the current time-splitting method as the default selection method the model already have one.
209                 if ($model->get_model_obj()->timesplitting) {
210                     $currenttimesplitting = ['id' => 'current', 'text' => get_string('currenttimesplitting', 'tool_analytics')];
211                     array_unshift($modeltimesplittingmethods, $currenttimesplitting);
212                 }
214                 $evaluateparams = [$actionid, $trainedonlyexternally, $modeltimesplittingmethods];
215                 $PAGE->requires->js_call_amd('tool_analytics/model', 'selectEvaluationOptions', $evaluateparams);
216                 $urlparams['action'] = 'evaluate';
217                 $url = new \moodle_url('model.php', $urlparams);
218                 $icon = new \action_menu_link_secondary($url, new \pix_icon('i/calc', get_string('evaluate', 'tool_analytics')),
219                     get_string('evaluate', 'tool_analytics'), ['data-action-id' => $actionid]);
220                 $actionsmenu->add($icon);
221             }
223             // Machine-learning-based models evaluation log.
224             if (!$model->is_static() && $model->get_logs()) {
225                 $urlparams['action'] = 'log';
226                 $url = new \moodle_url('model.php', $urlparams);
227                 $icon = new \action_menu_link_secondary($url, new \pix_icon('i/report', get_string('viewlog', 'tool_analytics')),
228                     get_string('viewlog', 'tool_analytics'));
229                 $actionsmenu->add($icon);
230             }
232             // Edit model.
233             $urlparams['action'] = 'edit';
234             $url = new \moodle_url('model.php', $urlparams);
235             $icon = new \action_menu_link_secondary($url, new \pix_icon('t/edit', get_string('edit')), get_string('edit'));
236             $actionsmenu->add($icon);
238             // Enable / disable.
239             if ($model->is_enabled() || !empty($modeldata->timesplitting)) {
240                 // If there is no timesplitting method set, the model can not be enabled.
241                 if ($model->is_enabled()) {
242                     $action = 'disable';
243                     $text = get_string('disable');
244                     $icontype = 't/block';
245                 } else {
246                     $action = 'enable';
247                     $text = get_string('enable');
248                     $icontype = 'i/checked';
249                 }
250                 $urlparams['action'] = $action;
251                 $url = new \moodle_url('model.php', $urlparams);
252                 $icon = new \action_menu_link_secondary($url, new \pix_icon($icontype, $text), $text);
253                 $actionsmenu->add($icon);
254             }
256             // Export.
257             if (!$model->is_static()) {
259                 $fullysetup = $model->get_indicators() && !empty($modeldata->timesplitting);
260                 $istrained = $model->is_trained();
262                 if ($fullysetup || $istrained) {
264                     $url = new \moodle_url('model.php', $urlparams);
265                     // Clear the previous action param from the URL, we will set it in JS.
266                     $url->remove_params('action');
268                     $actionid = 'export-' . $model->get_id();
269                     $PAGE->requires->js_call_amd('tool_analytics/model', 'selectExportOptions',
270                         [$actionid, $istrained]);
272                     $icon = new \action_menu_link_secondary($url, new \pix_icon('i/export',
273                         get_string('export', 'tool_analytics')), get_string('export', 'tool_analytics'),
274                         ['data-action-id' => $actionid]);
275                     $actionsmenu->add($icon);
276                 }
277             }
279             // Invalid analysables.
280             $analyser = $model->get_analyser(['notimesplitting' => true]);
281             if (!$analyser instanceof \core_analytics\local\analyser\sitewide) {
282                 $urlparams['action'] = 'invalidanalysables';
283                 $url = new \moodle_url('model.php', $urlparams);
284                 $pix = new \pix_icon('i/report', get_string('invalidanalysables', 'tool_analytics'));
285                 $icon = new \action_menu_link_secondary($url, $pix, get_string('invalidanalysables', 'tool_analytics'));
286                 $actionsmenu->add($icon);
287             }
289             // Clear model.
290             if (!empty($predictioncontexts) || $model->is_trained()) {
291                 $actionid = 'clear-' . $model->get_id();
292                 $PAGE->requires->js_call_amd('tool_analytics/model', 'confirmAction', [$actionid, 'clear']);
293                 $urlparams['action'] = 'clear';
294                 $url = new \moodle_url('model.php', $urlparams);
295                 $icon = new \action_menu_link_secondary($url, new \pix_icon('e/cleanup_messy_code',
296                     get_string('clearpredictions', 'tool_analytics')), get_string('clearpredictions', 'tool_analytics'),
297                     ['data-action-id' => $actionid]);
298                 $actionsmenu->add($icon);
299             }
301             // Delete model.
302             if (!$model->is_static()) {
303                 $actionid = 'delete-' . $model->get_id();
304                 $PAGE->requires->js_call_amd('tool_analytics/model', 'confirmAction', [$actionid, 'delete']);
305                 $urlparams['action'] = 'delete';
306                 $url = new \moodle_url('model.php', $urlparams);
307                 $icon = new \action_menu_link_secondary($url, new \pix_icon('t/delete',
308                     get_string('delete', 'tool_analytics')), get_string('delete', 'tool_analytics'),
309                     ['data-action-id' => $actionid]);
310                 $actionsmenu->add($icon);
311             }
313             $modeldata->actions = $actionsmenu->export_for_template($output);
315             $data->models[] = $modeldata;
316         }
318         if (!$onlycli) {
319             $data->warnings = array(
320                 (object)array('message' => get_string('bettercli', 'tool_analytics'), 'closebutton' => true)
321             );
322         } else {
323             $url = new \moodle_url('/admin/settings.php', array('section' => 'analyticssettings'),
324                 'id_s_analytics_onlycli');
326             $langstrid = 'clievaluationandpredictionsnoadmin';
327             if (is_siteadmin()) {
328                 $langstrid = 'clievaluationandpredictions';
329             }
330             $data->infos = array(
331                 (object)array('message' => get_string($langstrid, 'tool_analytics', $url->out()),
332                     'closebutton' => true)
333             );
334         }
336         return $data;
337     }