-
Notifications
You must be signed in to change notification settings - Fork 13
/
Copy pathcalculatorbase.php
465 lines (411 loc) · 17.2 KB
/
calculatorbase.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
<?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/>.
defined('MOODLE_INTERNAL') || die();
require_once($CFG->libdir . '/evalmath/evalmath.class.php');
/**
* Class for evaluating variants for varnumericset question type.
*
* @package qtype_varnumericset
* @copyright 2011 The Open University
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
abstract class qtype_varnumeric_calculator_base {
/**
* @var boolean whether assignments to variables should be evaluated on each
* question load.
*/
protected $recalculateeverytime = false;
/**
* @var string used to randomize random functions. The variant no and variable
* name will be appended to this.
*/
protected $randomseed;
/** @var EvalMath $ev evaluation class instance to use. **/
protected $ev;
/**
* @var array two dimensional array first key is varno,
* 2nd is variant no, contents is value of variant.
*/
protected $predefinedvariants = [];
/**
* @var array two dimensional array first key is varno,
* 2nd is variant no, contents is value of variant
*/
protected $calculatedvariants = [];
/** @var array one dimensional array key is varno. **/
protected $variables = [];
/** @var array one dimensional array first key is varno. **/
protected $vartypes = [];
protected $noofvariants = 0;
protected $answers = [];
protected $textswithembeddedvars = [];
protected $errors = [];
public function add_variable($varno, $variablenameorassignment) {
$this->variables[$varno] = $variablenameorassignment;
}
public function add_defined_variant($varno, $variantno, $value) {
$this->noofvariants = max($this->noofvariants, $variantno + 1);
if (!isset($this->predefinedvariants[$variantno])) {
$this->predefinedvariants[$variantno] = [];
}
$this->predefinedvariants[$variantno][$varno] = $value;
}
public function add_answer($answerno, $answer, $error) {
$answerobj = new stdClass();
$answerobj->answer = $answer;
$answerobj->error = $error;
$this->answers[$answerno] = $answerobj;
}
public function add_text_with_embedded_variables($form, $keys) {
$value = $form;
$fromformfield = '';
do {
$key = array_shift($keys);
if ($fromformfield == '') {
$fromformfield = $key;
} else {
$fromformfield .= '[' . $key . ']';
}
if (isset($value[$key])) {
$value = $value[$key];
} else {
return;
}
} while (count($keys));
if (isset($value['text'])) {
$value = $value['text'];
} else {
return;
}
$this->textswithembeddedvars[$fromformfield] = $value;
}
public function get_num_variants_in_form() {
if ($this->noofvariants == 0) {
// If there are no predefined variables at all then have a set
// amount of 5 variants.
return 5;
}
return $this->noofvariants;
}
public function get_errors() {
return $this->errors;
}
public function get_calculated_variants() {
return $this->calculatedvariants;
}
protected function get_defined_variant($varno, $variantno) {
if (!isset($this->predefinedvariants[$variantno][$varno])) {
throw new coding_exception(
"Predefined variant no {$variantno} for var no {$varno} has not been loaded!");
}
return $this->predefinedvariants[$variantno][$varno];
}
/**
* Evaluate everything loaded into caculator. Used for error checking and to calculate values
* for variables in every question variant.
* @param boolean $forcerecalculate
*/
public function evaluate_all($forcerecalculate = false) {
for ($variantno = 0; $variantno < $this->get_num_variants_in_form(); $variantno++) {
$this->evaluate_variant($variantno, $forcerecalculate);
$this->calculatedvariants[$variantno]
= $this->calculate_calculated_variant_values($variantno);
foreach ($this->answers as $answerno => $answer) {
foreach (['answer', 'error'] as $prop) {
if ($prop == 'error' && $answer->{$prop} == '') {
continue; // No error messages for blank allowed error fields in answer.
}
if (self::is_assignment($answer->{$prop})) {
// This is an assignment not legal here.
$this->errors[$prop . '[' . $answerno . ']'] =
get_string('expressionmustevaluatetoanumber', 'qtype_varnumericset');
} else {
$this->evaluate($answer->{$prop}, $prop . '[' . $answerno . ']');
}
}
}
foreach ($this->textswithembeddedvars as $wherefrom => $textwithembeddedvars) {
$this->evaluate_variables_in_text($textwithembeddedvars, $wherefrom);
}
}
}
public function evaluate($item, $placetoputanyerror = null) {
$result = $this->ev->evaluate($item);
$error = '';
if ($result === false) {
$error = get_string('errorreportedbyexpressionevaluator', 'qtype_varnumericset',
$this->ev->last_error);
}
if (is_nan($result)) {
$error = get_string('expressionevaluatesasnan', 'qtype_varnumericset');
}
if (is_infinite($result)) {
$error = get_string('expressionevaluatesasinfinite', 'qtype_varnumericset');
}
if ($error) {
$this->errors[$placetoputanyerror] = $error;
}
return $result;
}
/**
* Load all variable assignments for a given variant.
*
* @param integer $variantno
* @param boolean $forcerecalculate force recalculate calculated values
* or load calculated values as predefined values?
*/
public function evaluate_variant($variantno, $forcerecalculate = false) {
if ((!$this->recalculateeverytime) && (!$forcerecalculate)) {
$recalculatecalculated = false;
} else {
$recalculatecalculated = true;
}
$this->ev = new EvalMath(true, true);
$this->ev->suppress_errors = true;
foreach ($this->variables as $varno => $variablenameorassignment) {
if (!$recalculatecalculated || !self::is_assignment($variablenameorassignment)) {
$varname = self::var_in_assignment($variablenameorassignment);
$this->evaluate($varname.'='.$this->get_defined_variant($varno, $variantno),
'variant' . $variantno . '[' . $varno . ']');
} else {
$varname = self::var_in_assignment($variablenameorassignment);
EvalMathFuncs::set_random_seed($this->randomseed.$variantno.$varname);
$this->evaluate($variablenameorassignment, 'varname[' . $varno . ']');
}
}
}
protected function calculate_calculated_variant_values($variantno) {
$calculatedvariants = [];
foreach ($this->variables as $varno => $variablenameorassignment) {
if (self::is_assignment($variablenameorassignment)) {
$varname = self::var_in_assignment($variablenameorassignment);
$calculatedvariants[$varno]
= $this->evaluate($varname, 'variant' . $variantno . '[' . $varno . ']');
}
}
return $calculatedvariants;
}
/**
* Save internal state of calculator as question type step data.
*
* @param question_attempt_step $step
* @param integer $variantno
*/
public function save_state_as_qt_data($step) {
foreach ($this->variables as $varno => $variablenameorassignment) {
$varname = self::var_in_assignment($variablenameorassignment);
$step->set_qt_var('_var' . $varname, $this->evaluate($varname));
$step->set_qt_var('_var' . $varname, $this->evaluate($varname));
}
}
public function load_state_from_qt_data ($step) {
$this->ev = new EvalMath(true, true);
foreach ($this->variables as $varno => $variablenameorassignment) {
$varname = self::var_in_assignment($variablenameorassignment);
$this->evaluate($varname . '=' . $step->get_qt_var('_var' . $varname));
}
}
public function load_data_from_form($formdata) {
if (isset($formdata['varname'])) {
foreach ($formdata['varname'] as $varno => $varname) {
if ($varname !== '') {
$this->add_variable($varno, $varname);
}
}
}
for ($variantno = 0; $variantno < $formdata['noofvariants']; $variantno++) {
if (isset($formdata['variant'.$variantno])) {
$variants = $formdata['variant'.$variantno];
foreach ($variants as $varno => $value) {
if ($formdata['vartype'][$varno] == 1) {
if ($value !== '') {
$this->add_defined_variant($varno, $variantno, $value);
}
}
}
}
}
foreach ($formdata['answer'] as $answerno => $answer) {
if (!empty($answer) && '*' != $answer) {
$this->add_answer($answerno, $answer, $formdata['error'][$answerno]);
}
}
$this->add_text_with_embedded_variables($formdata, ['questiontext']);
$this->add_text_with_embedded_variables($formdata, ['generalfeedback']);
foreach (['feedback', 'hint'] as $itemname) {
if (isset($formdata[$itemname])) {
foreach ($formdata[$itemname] as $indexno => $item) {
$this->add_text_with_embedded_variables($formdata, [$itemname, $indexno]);
}
}
}
}
/**
*
* Set the portion of the random seed shared by all variants and variables.
* @param string $randomseed from the question creation form
* @param string $questionstamp autogenerated unique value for each question from
* question object
*/
public function set_random_seed($randomseed, $questionstamp) {
if ($randomseed !== '') {
$this->randomseed = $randomseed;
} else {
$this->randomseed = $questionstamp;
}
}
/**
* Get the portion of the random seed shared by all variants and variables.
*/
public function get_random_seed() {
return $this->randomseed;
}
public function set_recalculate_rand($recalculateeverytime) {
$this->recalculateeverytime = $recalculateeverytime;
}
public function load_data_from_database($vars, $variants) {
// Declare and load data whether or not we will use calculator.
$varidtovarno = [];
foreach ($vars as $varid => $var) {
if (self::is_assignment($var->nameorassignment)) {
$this->vartypes[$var->varno] = 0;
} else {
$this->vartypes[$var->varno] = 1;
}
$this->add_variable($var->varno, $var->nameorassignment);
$varidtovarno[$varid] = $var->varno;
}
foreach ($variants as $variant) {
$this->add_defined_variant($varidtovarno[$variant->varid],
$variant->variantno, $variant->value);
}
}
public function get_data_for_form($dataforform) {
if ($this->recalculateeverytime) {
$this->evaluate_all(true);
}
$dataforform->randomseed = $dataforform->options->randomseed;
$dataforform->vartype = array_values($this->vartypes);
$dataforform->varname = array_values($this->variables);
for ($variantno = 0; $variantno < $this->get_num_variants_in_form(); $variantno++) {
$propname = 'variant'.$variantno;
$dataforform->{$propname} = [];
if (isset($this->predefinedvariants[$variantno])) {
$dataforform->{$propname} += array_values($this->predefinedvariants[$variantno]);
}
if (isset($this->calculatedvariants[$variantno])) {
$dataforform->{$propname} += array_values($this->calculatedvariants[$variantno]);
}
}
return $dataforform;
}
public function get_var_types() {
return $this->vartypes;
}
public function get_var_names() {
return $this->variables;
}
public function get_defined_variants() {
return $this->predefinedvariants;
}
public static function is_assignment($string) {
$parts = explode('=', $string);
if (count($parts) != 2) {
return false;
}
return EvalMath::is_valid_var_or_func_name(trim($parts[0]));
}
public static function var_in_assignment($assignment) {
$parts = explode('=', $assignment);
return trim($parts[0]);
}
public function evaluate_variables_in_text($text, $wheretoputerror = null) {
$done = [];
$errors = [];
// Match anything surrounded by [[ ]].
preg_match_all('~\[\[(.+?)(\s*,\s*(.*?))?]]~', $text, $matches, PREG_SET_ORDER);
foreach ($matches as $match) {
// Since the format may, or may not, be present, append an extra empty string to $match.
[$placeholder, $variableorexpression, $hasformat, $format] = array_merge($match, ['', '']);
if (isset($done[$placeholder])) {
// The same placeholder always gets replaced by the same value.
continue;
}
if (self::is_assignment($variableorexpression)) {
// This is an assignment, not legal here.
$errors[] = get_string('expressionmustevaluatetoanumber', 'qtype_varnumericset');
continue;
} else {
$this->errors['temp'] = '';
$evaluated = $this->evaluate($variableorexpression, 'temp');
if ($this->errors['temp']) {
$errors[] = get_string('errorvalidationissue', 'qtype_varnumericset',
['placeholder' => $placeholder, 'message' => $this->errors['temp']]);
}
unset($this->errors['temp']);
}
if ($hasformat) {
if (strpos($format, ' ') !== false) {
$errors[] = get_string('errorvalidationformatnumbernonbsp', 'qtype_varnumericset', $placeholder);
continue;
} else {
try {
$numberasstring = self::format_number($evaluated, $format);
} catch (Throwable $e) {
$errors[] = get_string('errorvalidationissue', 'qtype_varnumericset',
['placeholder' => $placeholder, 'message' => s($e->getMessage())]);
continue;
}
}
} else {
$numberasstring = (string) $evaluated;
}
$numberasstring = self::htmlize_exponent($numberasstring);
$text = str_replace($placeholder, $numberasstring, $text);
$done[$placeholder] = true;
}
// Store errors, if any, and if required.
if ($wheretoputerror && $errors) {
if (count($errors) == 1) {
$message = $errors[0];
} else {
$message = html_writer::alist($errors);
}
$this->errors[$wheretoputerror] = get_string(
'errorvalidationformatnumber', 'qtype_varnumericset', $message);
}
return $text;
}
/**
* Format a number using a sprintf code.
*
* @param $number a number
* @param string $sprintfcode a printf code, without the leading '%'.
* @return string the formatted number.
*/
public static function format_number($number, string $sprintfcode): string {
return sprintf('%' . $sprintfcode, $number);
}
/**
* Typeset any scientific notation in the formatted number string.
*
* @param string|null $numberasstring the number to improve the display of.
* @return string prettier string.
*/
public static function htmlize_exponent(?string $numberasstring): string {
return preg_replace('!e([+-]?\d+)$!i', ' × 10<sup>$1</sup>', $numberasstring ?? '');
}
}