-
Notifications
You must be signed in to change notification settings - Fork 30
/
Copy pathvariables.php
2220 lines (2103 loc) · 97.4 KB
/
variables.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/>.
/**
* The qtype_formulas_variables class is used to parse and evaluate variables.
*
* @copyright © 2010-2011 Hon Wai, Lau
* @author Hon Wai, Lau <lau65536@gmail.com>
* @license http://www.gnu.org/copyleft/gpl.html GNU Public License version 3
*/
namespace qtype_formulas;
use Exception, Throwable;
defined('MOODLE_INTERNAL') || die();
/**
* Helper function to emulate the behaviour of the count() function with PHP <7.2
* Until then, count() returned 1 for e.g. a string. Since 8.0, it throws TypeError in such cases
*
* @author Jean-Michel Védrine
* @param mixed $a
* @return integer
*/
function mycount($a) {
if ($a === null) {
return 0;
} else {
if ($a instanceof \Countable || is_array($a)) {
return count($a);
} else {
return 1;
}
}
}
function fact($n) {
$n = (int) $n;
if ($n < 2) {
return 1;
}
$return = 1;
for ($i = $n; $i > 1; $i--) {
$return *= $i;
}
return $return;
}
/**
* Return the plugin's version number.
*
* @return integer
*/
function fqversionnumber() {
return get_config('qtype_formulas')->version;
}
/**
* calculate standard normal probability density
*
* @author Philipp Imhof
* @param float $z value
* @return float standard normal density of $z
*/
function stdnormpdf($z) {
return 1 / (sqrt(2) * M_SQRTPI) * exp(-.5 * $z ** 2);
}
/**
* calculate standard normal cumulative distribution by approximation
* using Simpson's rule, accurate to ~5 decimal places
*
* @param float $z value
*
* @author Philipp Imhof
* @return float probability for a value of $z or less under standard normal distribution
*/
function stdnormcdf($z) {
if ($z < 0) {
return 1 - stdnormcdf(-$z);
}
$n = max(10, floor(10 * $z));
$h = $z / $n;
$res = stdnormpdf(0) + stdnormpdf($z);
for ($i = 1; $i < $n; $i++) {
$res += 2 * stdnormpdf($i * $h);
$res += 4 * stdnormpdf(($i - 0.5) * $h);
}
$res += 4 * stdnormpdf(($n - 0.5) * $h);
$res *= $h / 6;
return $res + 0.5;
}
/**
* calculate normal cumulative distribution by approximation
* using Simpson's rule, accurate to ~5 decimal places
*
* @param float $x value
* @param float $mu mean
* @param float $sigma standard deviation
*
* @author Philipp Imhof
* @return float probability for a value of $x or less
*/
function normcdf($x, $mu, $sigma) {
return stdnormcdf(($x - $mu) / $sigma);
}
/**
* raise $a to the $b-th power modulo $m using efficient
* square and multiply
*
* @author Philipp Imhof
* @param integer $a base
* @param integer $b exponent
* @param integer $m modulus
* @return integer the result
*/
function modpow($a, $b, $m) {
$bin = decbin($b);
$res = $a;
if ($b == 0) {
return 1;
}
for ($i = 1; $i < strlen($bin); $i++) {
if ($bin[$i] == "0") {
$res = ($res * $res) % $m;
} else {
$res = ($res * $res) % $m;
$res = ($res * $a) % $m;
}
}
return $res;
}
/**
* calculate the multiplicative inverse of $a modulo $m using the
* extended euclidean algorithm
*
* @author Philipp Imhof
* @param integer $a the number whose inverse is to be found
* @param integer $m the modulus
* @return integer the result or 0 if the inverse does not exist
*/
function modinv($a, $m) {
$orig_m = $m;
if (gcd($a, $m) != 1) {
// Inverse does not exist.
return 0;
}
list($s, $t, $last_s, $last_t) = [1, 0, 0, 1];
while ($m != 0) {
$q = floor($a/$m);
list($a, $m) = [$m, $a - $q * $m];
list($s, $last_s) = [$last_s, $s - $q * $last_s];
list($t, $last_t) = [$last_t, $t - $q * $last_t];
}
return ($s < 0) ? $s + $orig_m : $s;
}
/**
* Calculate the floating point remainder of the division of
* the arguments, i. e. x - m * floor(x / m). There is no
* canonical definition for this function; some calculators
* use flooring (round down to nearest integer) and others
* use truncation (round to nearest integer, but towards zero).
* This implementation gives the same results as e. g. Wolfram Alpha.
*
* @author Philipp Imhof
* @param float $x the dividend
* @param float $m the modulus
* @return float remainder of $x modulo $m
*/
function fmod($x, $m) {
if ($m === 0) {
throw new Exception(get_string('error_eval_numerical', 'qtype_formulas'));
}
return $x - $m * floor($x / $m);
}
/**
* Calculate the probability of exactly $x successful outcomes for
* $n trials under a binomial distribution with a probability of success
* of $p.
*
* @param int $n number of trials
* @param float $p probability of success for each trial
* @param int $x number of successful outcomes
*
* @return float probability for exactly $x successful outcomes
* @throws Exception
*/
function binomialpdf($n, $p, $x) {
// Probability must be 0 <= p <= 1.
if ($p < 0 || $p > 1) {
throw new Exception(get_string('error_eval_numerical', 'qtype_formulas'));
}
// Number of successful outcomes must be at least 0 and at most number of trials.
if ($x < 0 || $x > $n) {
throw new Exception(get_string('error_eval_numerical', 'qtype_formulas'));
}
return ncr($n, $x) * $p ** $x * (1 - $p) ** ($n - $x);
}
/**
* Calculate the probability of up to $x successful outcomes for
* $n trials under a binomial distribution with a probability of success
* of $p, known as the cumulative distribution function.
*
* @param int $n number of trials
* @param float $p probability of success for each trial
* @param int $x number of successful outcomes
*
* @return float probability for up to $x successful outcomes
* @throws Exception
*/
function binomialcdf($n, $p, $x) {
// Probability must be 0 <= p <= 1.
if ($p < 0 || $p > 1) {
throw new Exception(get_string('error_eval_numerical', 'qtype_formulas'));
}
// Number of successful outcomes must be at least 0 and at most number of trials.
if ($x < 0 || $x > $n) {
throw new Exception(get_string('error_eval_numerical', 'qtype_formulas'));
}
$res = 0;
for ($i = 0; $i <= $x; $i++) {
$res += binomialpdf($n, $p, $i);
}
return $res;
}
function npr($n, $r) {
$n = (int)$n;
$r = (int)$r;
if ($r == 0 && $n == 0) {
return 0;
}
return ncr($n, $r) * fact($r);
}
function ncr($n, $r) {
$n = (int)$n;
$r = (int)$r;
if ($r > $n) {
return 0;
}
if (($n - $r) < $r) {
return ncr($n, ($n - $r));
}
$numerator = 1;
$denominator = 1;
for ($i = 1; $i <= $r; $i++) {
$numerator *= ($n - $i + 1);
$denominator *= $i;
}
return intdiv($numerator, $denominator);
}
function gcd($a, $b) {
if ($a < 0) {
$a = abs($a);
}
if ($b < 0) {
$b = abs($b);
}
if ($a == 0 && $b == 0) {
return 0;
}
if ($a == 0 || $b == 0) {
return $a + $b;
}
if ($a == $b) {
return $a;
}
do {
$rest = (int) $a % $b;
$a = $b;
$b = $rest;
} while ($rest > 0);
return $a;
}
function lcm($a, $b) {
if ($a == 0 || $b == 0) {
return 0;
}
return $a * $b / gcd($a, $b);
}
function sigfig($number, $precision) {
if ($number == 0) {
$decimalplaces = $precision - 1;
} else if ($number < 0) {
$decimalplaces = $precision - floor(log10($number * -1)) - 1;
} else {
$decimalplaces = $precision - floor(log10($number)) - 1;
}
$answer = ($decimalplaces > 0) ?
number_format($number, $decimalplaces, '.', '') : number_format(round($number, $decimalplaces), 0, '.', '');
return $answer;
}
/**
* format a polynomial to be display with LaTeX / MathJax
* can also be used to force the plus sign for a single number
* can also be used for arbitrary linear combinations
*
* @author Philipp Imhof
* @param mixed $variables one variable (as a string) or a list of variables (array of strings)
* @param mixed $coefficients one number or an array of numbers to be used as coefficients
* @param string $forceplus symbol to be used for the normally invisible leading plus, optional
* @param string $additionalseparator symbol to be used as separator between the terms, optional
* @return string the formatted string
*/
function poly($variables, $coefficients = null, $forceplus = '', $additionalseparator = '') {
// If no variable is given and there is just one single number, simply force the plus sign
// on positive numbers.
if ($variables === '' && is_numeric($coefficients)) {
if ($coefficients > 0) {
return $forceplus . $coefficients;
}
return $coefficients;
}
$numberofterms = count($coefficients);
// By default, we think that a final coefficient == 1 is not to be shown, because it is a true coefficient
// and not a constant term. Also, terms with coefficient == zero should generally be completely omitted.
$constantone = false;
$omitzero = true;
// If the variable is left empty, but there is a list of coefficients, we build an empty array
// of the same size as the number of coefficients. This can be used to pretty-print matrix rows.
// In that case, the numbers 1 and 0 should never be omitted.
if ($variables === '') {
$variables = array_fill(0, $numberofterms, '');
$constantone = true;
$omitzero = false;
}
// If there is just one variable, we blow it up to an array of the correct size and descending exponents.
if (gettype($variables) === 'string' && $variables !== '') {
// As we have just one variable, we are building a standard polynomial where the last coefficient
// is not a real coefficient, but a constant term that has to be printed.
$constantone = true;
$tmp = $variables;
$variables = array();
for ($i = 0; $i < $numberofterms; $i++) {
if ($i == $numberofterms - 2) {
$variables[$i] = $tmp;
} else if ($i == $numberofterms - 1) {
$variables[$i] = '';
} else {
$variables[$i] = $tmp . '^{' . ($numberofterms - 1 - $i) . '}';
}
}
}
// If the list of variables is shorter than the list of coefficients, just start over again.
if (count($variables) < $numberofterms) {
$numberofvars = count($variables);
for ($i = count($variables); $i < $numberofterms; $i++) {
$variables[$i] = $variables[$i % $numberofvars];
}
}
// If the separator is "doubled", e.g. &&, we put one half before and one half after the
// operator. By default, we have the entire separator before the operator. Also, we do not
// change anything if we are building a matrix row, because there are no operators. (They are signs.)
$separatorlength = strlen($additionalseparator);
$separatorbefore = $additionalseparator;
$separatorafter = '';
if ($separatorlength > 0 && $separatorlength % 2 === 0 && $omitzero) {
$tmpbefore = substr($additionalseparator, 0, $separatorlength / 2);
$tmpafter = substr($additionalseparator, $separatorlength / 2);
// If the separator just has even length, but is not "doubled", we don't touch it.
if ($tmpbefore === $tmpafter) {
$separatorbefore = $tmpbefore;
$separatorafter = $tmpafter;
}
}
$result = '';
// First term should not have a leading plus sign, unless user wants to force it.
foreach ($coefficients as $i => $coef) {
$thisseparatorbefore = ($i == 0 ? '' : $separatorbefore);
$thisseparatorafter = ($i == 0 ? '' : $separatorafter);
// Terms with coefficient == 0 are generally not shown. But if we use a separator, it must be printed anyway.
if ($coef == 0) {
if ($i > 0) {
$result .= $thisseparatorbefore . $thisseparatorafter;
}
if ($omitzero) {
continue;
}
}
// Put a + or - sign according to value of coefficient and replace the coefficient
// by its absolute value, as we don't need the sign anymore after this step.
// If the coefficient is 0 and we force its output, do it now. However, do not put a sign,
// as the only documented usage of this is for matrix rows and the like.
if ($coef < 0) {
$result .= $thisseparatorbefore . '-' . $thisseparatorafter;
$coef = abs($coef);
} else if ($coef > 0) {
// If $omitzero is false, we are building a matrix row, so we don't put plus signs.
$result .= $thisseparatorbefore . ($omitzero ? '+' : '') . $thisseparatorafter;
}
// Put the coefficient. If the coefficient is +1 or -1, we don't put the number,
// unless we're at the last term. The sign is already there, so we use the absolute value.
// Never omit 1's if building a matrix row.
if ($coef == 1) {
$coef = (!$omitzero || ($i == $numberofterms - 1 && $constantone) ? '1' : '');
}
$result .= $coef . $variables[$i];
}
// If the resulting string is empty (or empty with just alignment separators), add a zero at the end.
if ($result === '' || $result === str_repeat($additionalseparator, $numberofterms - 1)) {
$result .= '0';
}
// Strip leading + and replace by $forceplus (which will be '' or '+' most of the time).
if ($result[0] == '+') {
$result = $forceplus . substr($result, 1);
}
// If we have nothing but separators before the leading +, replace that + by $forceplus.
if ($separatorbefore !== '' && preg_match("/^($separatorbefore+)\+/", $result)) {
$result = preg_replace("/^($separatorbefore+)\+/", "\\1$forceplus", $result);
}
return $result;
}
/**
* Class contains methods to parse variables text and evaluate variables. Results are stored in the $vstack
* The functions can be roughly classified into 5 categories:
*
* - handle variable stack
* - substitute number, string, function and variable name by placeholder, and the reverse functino
* - parse and instantiate random variable
* - evaluate assignments, general expression and numerical expression.
* - evaluate algebraic formula
*/
class variables {
private static $maxdataset = 2e9; // It is the upper limit for the exhaustive enumeration.
private static $listmaxsize = 1000;
/* Defining legacy properties here for compatibility with PHP 8.2 */
private $func_const = [];
private $func_unary = [];
private $func_binary = [];
private $func_special = [];
private $func_all = [];
private $binary_op_map = [];
private $func_algebraic = [];
private $constlist = ['pi' => '3.14159265358979323846'];
private $evalreplacelist = ['ln' => 'log', 'log10' => '(1./log(10.))*log'];
private function initialize_function_list() {
$this->func_const = array_flip( array('pi', 'fqversionnumber'));
$this->func_unary = array_flip( array('abs', 'acos', 'acosh', 'asin', 'asinh', 'atan', 'atanh', 'ceil',
'cos', 'cosh' , 'deg2rad', 'exp', 'expm1', 'floor', 'is_finite', 'is_infinite', 'is_nan',
'log10', 'log1p', 'rad2deg', 'sin', 'sinh', 'sqrt', 'tan', 'tanh', 'log', 'round', 'fact',
'stdnormpdf', 'stdnormcdf', 'decbin', 'decoct', 'octdec', 'bindec') );
$this->func_binary = array_flip(
array('log', 'round', 'atan2', 'fmod', 'pow', 'min', 'max', 'ncr', 'npr', 'gcd', 'lcm', 'sigfig', 'modinv')
);
$this->func_special = array_flip(
array('fill', 'len', 'pick', 'sort', 'sublist', 'inv', 'map', 'sum', 'concat', 'join', 'str', 'diff', 'poly', 'normcdf',
'modpow', 'binomialpdf', 'binomialcdf')
);
$this->func_all = array_merge($this->func_const, $this->func_unary, $this->func_binary, $this->func_special);
$this->binary_op_map = array_flip(
array('+', '-', '*', '/', '%', '>', '<', '==', '!=', '&&', '||', '&', '|', '<<', '>>', '^')
);
// $this->binary_op_reduce = array_flip( array('||', '&&', '==', '+', '*') );
// Note that the implementation is exactly the same as the client so the behaviour should be the same.
$this->func_algebraic = array_flip( array('sin', 'cos', 'tan', 'asin', 'acos', 'atan',
'exp', 'log10', 'ln', 'sqrt', 'abs', 'ceil', 'floor', 'fact'));
// Natural log and log with base 10, no log allowed to avoid ambiguity.
}
public function __construct() {
$this->initialize_function_list();
}
/**
* Data structure of the variables stack object, containing:
* - all is an array with name (key) => data (value),
* - data is and object contains the type information and variable value.
* - idcounter stores the largest id of temporary variables
*
* Note the basic type of the variables are:
* n: number, s: string, ln: list of number, ls: list of string, a: algebraic variable
*
* Note also that the type used internally are:
* f: function that can be used for algebraic formula, F: functions that will be used internally only
* z(n, s, ln, ls): set of (number, string, list of number, list of string),
* zh(ln, ls): shuffle (list of number, list of string)
* Note the type number 'n' has a "constantness" associated to it. The value is of type string if it is constant
*/
// This function must be called to initial a variable stack, and the returned variable is required by most function.
public function vstack_create() {
return (object)array('idcounter' => 0, 'all' => array());
}
// Return a serialized string of vstack with type n, s, ln, ls. It can be reconstructed by calling evaluate_assignments().
public function vstack_get_serialization(&$vstack) {
$ctype = array_flip(explode(',', 'n,s,ln,ls'));
$vstr = '';
foreach ($vstack->all as $name => $data) {
if (array_key_exists($data->type, $ctype)) {
// Convert all into arrays for homogeneous treatment.
$values = $data->type[0] == 'l' ? $data->value : array($data->value);
if ($data->type == 's' || $data->type == 'ls') {
for ($i = 0; $i < mycount($values); $i++) {
// String has a quotation.
$values[$i] = '"'.$values[$i].'"';
}
}
$vstr .= $name . '=' . ($data->type[0] == 'l' ? ('['.implode(',', $values).']') : $values[0]) . ';';
}
}
return $vstr;
}
// Return the size of sample space, or null if it is too large. The purpose of this number is to instantiate all random dataset.
public function vstack_get_number_of_dataset(&$vstack) {
$numdataset = 1;
foreach ($vstack->all as $name => $data) {
if ($data->type[0] == 'z' && $data->type[1] != 'h') {
// The 'shuffle' is not counted, as it always have large number of permutation...
$numdataset *= $data->value->numelement;
if ($numdataset > self::$maxdataset) {
return null;
}
}
}
return $numdataset;
}
// Return the size of sample space, or null if it is too large. The purpose of this number is to instantiate all random dataset.
public function vstack_get_number_of_dataset_with_shuffle(&$vstack) {
$numdataset = 1;
foreach ($vstack->all as $name => $data) {
if ($data->type[0] == 'z') {
$numdataset *= $data->value->numelement;
if ($numdataset > self::$maxdataset) {
return null;
}
}
}
return $numdataset;
}
// Return whether there is shuffled data.
public function vstack_get_has_shuffle(&$vstack) {
foreach ($vstack->all as $name => $data) {
if ($data->type[0] == 'zh') {
return true;
}
}
return false;
}
// Return the list of variables stored in the vstack.
public function vstack_get_names(&$vstack) {
return array_keys($vstack->all);
}
public function vstack_get_variable(&$vstack, $name) {
return array_key_exists($name, $vstack->all) ? $vstack->all[$name] : null;
}
public function vstack_update_variable(&$vstack, $name, $index, $type, $value) {
if ($index === null) {
if ($type[0] == 'l') { // Error check for list.
if (!is_array($value)) {
throw new Exception('Unknown error. vstack_update_variable()');
}
if (mycount($value) < 1 || mycount($value) > self::$listmaxsize) {
throw new Exception(get_string('error_vars_array_size', 'qtype_formulas'));
}
if (!is_numeric($value[0]) && !is_string($value[0])) {
throw new Exception(get_string('error_vars_array_type', 'qtype_formulas'));
}
if ($type[1] == 'n') {
for ($i = 0; $i < mycount($value); $i++) {
if (!is_numeric($value[$i])) {
throw new Exception(get_string('error_vars_array_type', 'qtype_formulas'));
}
$value[$i] = floatval($value[$i]);
}
} else {
for ($i = 0; $i < mycount($value); $i++) {
if (!is_string($value[$i])) {
throw new Exception(get_string('error_vars_array_type', 'qtype_formulas'));
}
}
}
}
$vstack->all[$name] = (object)array('type' => $type, 'value' => $value);
} else {
$list = &$vstack->all[$name];
if ($list->type[0] != 'l') {
throw new Exception(get_string('error_vars_array_unsubscriptable', 'qtype_formulas'));
}
$index = intval($index);
if ($index < 0 || $index >= mycount($list->value)) {
throw new Exception(get_string('error_vars_array_index_out_of_range', 'qtype_formulas'));
}
if ($list->type[1] != $type) {
throw new Exception(get_string('error_vars_array_type', 'qtype_formulas'));
}
$list->value[$index] = $type == 'n' ? floatval($value) : $value;
}
}
private function vstack_mark_current_top(&$vstack) {
return (object)array('idcounter' => $vstack->idcounter, 'sz' => mycount($vstack->all));
}
private function vstack_restore_previous_top(&$vstack, $previoustop) {
$vstack->all = array_slice($vstack->all, 0, $previoustop->sz);
$vstack->idcounter = $previoustop->idcounter;
}
private function vstack_add_temporary_variable(&$vstack, $type, $value) {
$name = '@' . $vstack->idcounter;
$this->vstack_update_variable($vstack, $name, null, $type, $value);
$vstack->idcounter++;
return $name;
}
private function vstack_clean_temporary(&$vstack) {
$tmp = $this->vstack_create();
foreach ($vstack->all as $name => $data) {
if ($name[0] != '@') {
$tmp->all[$name] = $data;
}
}
return $tmp;
}
/**
* These functions replace the string, number, fixed range, function and variable name by placeholder (start with @)
* Also, the reverse substitution function also available for different situation.
* Note that string and fixed range are not treated as placeholder, so text with them cannot be fully recovered.
*/
// Return the text with the variables, or evaluable expressions, substituted by their values.
public function substitute_variables_in_text(&$vstack, $text) {
$funcpattern = '/(\{=[^{}]+\}|\{([A-Za-z][A-Za-z0-9_]*)(\[([0-9]+)\])?\})/';
$results = [];
if (is_string($text)) {
// @codingStandardsIgnoreLine
$ts = explode("\n`", $text); // The ` is the separator, so split it first.
} else {
$ts = [];
}
foreach ($ts as $text) {
// @codingStandardsIgnoreLine
$splitted = explode("\n`", preg_replace($funcpattern, "\n`$1\n`", $text));
for ($i = 1; $i < mycount($splitted); $i += 2) {
try {
$expr = substr($splitted[$i], $splitted[$i][1] == '=' ? 2 : 1 , -1);
$res = $this->evaluate_general_expression($vstack, $expr);
// Skip for other type.
if ($res->type != 'n' && $res->type != 's') {
throw new Exception();
}
$splitted[$i] = $res->value;
} catch (Exception $e) { // @codingStandardsIgnoreLine
// Note that the expression will not be replaced if error occurs. Also, no error throw in any cases.
}
}
$results[] = implode('', $splitted);
}
// @codingStandardsIgnoreLine
return implode("\n`", $results);
}
// Return the original string by substituting back the placeholders (given by variables in $vstack) in the input $text.
private function substitute_placeholders_in_text(&$vstack, $text) {
// @codingStandardsIgnoreLine
$splitted = explode('`', preg_replace('/(@[0-9]+)/', '`$1`', $text));
// The length will always be odd, and the placeholder is stored in odd index.
for ($i = 1; $i < mycount($splitted); $i += 2) {
// Substitute back the strings.
$splitted[$i] = $this->vstack_get_variable($vstack, $splitted[$i])->value;
}
return implode('', $splitted);
}
// If substitute_variables_by_placeholders() was used for $text,
// then this function forward the value of type 'v' to the actual variable value.
private function substitute_vname_by_variables(&$vstack, $text) {
// @codingStandardsIgnoreLine
$splitted = explode('`', preg_replace('/(@[0-9]+)/', '`$1`', $text));
$appearedvars = array(); // Reuse the temporary variable if possible.
// The length will always be odd, and the numbers are stored in odd index.
for ($i = 1; $i < mycount($splitted); $i += 2) {
$data = $this->vstack_get_variable($vstack, $splitted[$i]);
if ($data->type == 'v') {
$tmp = $this->vstack_get_variable($vstack, $data->value);
if ($tmp === null) {
throw new Exception(
get_string('error_vars_undefined', 'qtype_formulas', $data->value) . ' in substitute_vname_by_variables'
);
}
if (!array_key_exists($data->value, $appearedvars)) {
$appearedvars[$data->value] = $this->vstack_add_temporary_variable($vstack, $tmp->type, $tmp->value);
}
$splitted[$i] = $appearedvars[$data->value];
}
}
return implode('', $splitted);
}
// Replace the strings in the $text.
private function substitute_strings_by_placholders(&$vstack, $text) {
if (is_string($text)) {
$text = stripcslashes($text);
} else {
$text = '';
}
$splitted = explode("\"", $text);
if (mycount($splitted) % 2 == 0) {
throw new Exception(get_string('error_vars_string', 'qtype_formulas'));
}
foreach ($splitted as $i => &$s) {
if ($i % 2 == 1) {
if (strpos($s, '\'') !== false || strpos($s, "\n") !== false) {
throw new Exception(get_string('error_vars_string', 'qtype_formulas'));
}
$s = $this->vstack_add_temporary_variable($vstack, 's', $s);
}
// Characters @ and ` can't be used in the main text.
// @codingStandardsIgnoreLine
else if (strpos($s, '@') !== false || strpos($s, '`') !== false) {
throw new Exception(get_string('error_forbid_char', 'qtype_formulas'));
}
}
return implode('', $splitted);
}
// Replace the fixed range of the form [a:b] in the $text by variables with new names in $tmpnames, and add it to the $vars.
private function substitute_fixed_ranges_by_placeholders(&$vstack, $text) {
$rangepattern = '/(\[[^\]]+:[^\]]+\])/';
// @codingStandardsIgnoreLine
$splitted = explode('`', preg_replace($rangepattern, '`$1`', $text));
// The length will always be odd, and the numbers are stored in odd index.
for ($i = 1; $i < mycount($splitted); $i += 2) {
$res = $this->parse_fixed_range($vstack, substr($splitted[$i], 1, -1));
if ($res === null) {
throw new Exception(get_string('error_fixed_range', 'qtype_formulas'));
}
$data = array();
for ($z = $res->element[0]; $z < $res->element[1]; $z += $res->element[2]) {
$data[] = $z;
if (mycount($data) > self::$listmaxsize) {
throw new Exception(get_string('error_vars_array_size', 'qtype_formulas'));
}
}
if (mycount($data) < 1) {
throw new Exception(get_string('error_vars_array_size', 'qtype_formulas'));
}
$splitted[$i] = $this->vstack_add_temporary_variable($vstack, 'ln', $data);
}
return implode('', $splitted);
}
// Return a string with all (positive) numbers substituted by placeholders. The information of placeholders is stored in v.
private function substitute_numbers_by_placeholders(&$vstack, $text) {
$numpattern = '/(^|[\]\[)(}{, ?:><=~!|&%^\/*+-])(([0-9]+\.?[0-9]*|[0-9]*\.?[0-9]+)([eE][-+]?[0-9]+)?)/';
// @codingStandardsIgnoreLine
$splitted = explode('`', preg_replace($numpattern, '$1`$2`', $text));
// The length will always be odd, and the numbers are stored in odd index.
for ($i = 1; $i < mycount($splitted); $i += 2) {
$splitted[$i] = $this->vstack_add_temporary_variable($vstack, 'n', $splitted[$i]);
}
return implode('', $splitted);
}
// Return a string with all functions substituted by placeholders. The information of placeholders is stored in v.
private function substitute_functions_by_placeholders(&$vstack, $text, $internal=false) {
$funcpattern = '/([a-z][a-z0-9_]*)(\s*\()/';
$funclists = $internal ? $this->func_all : $this->func_algebraic;
$type = $internal ? 'F' : 'f';
// @codingStandardsIgnoreLine
$splitted = explode('`', preg_replace($funcpattern, '`$1`$2', $text));
// The length will always be odd, and the variables are stored in odd index.
for ($i = 1; $i < mycount($splitted); $i += 2) {
if (!array_key_exists($splitted[$i], $funclists)) {
continue;
}
$splitted[$i] = $this->vstack_add_temporary_variable($vstack, $type, $splitted[$i]);
}
return implode('', $splitted);
}
// Return a string with all variables substituted by placeholders. The information of placeholders is stored in v.
private function substitute_constants_by_placeholders(&$vstack, $text, $preserve) {
$varpattern = '/([A-Za-z][A-Za-z0-9_]*)/';
// @codingStandardsIgnoreLine
$splitted = explode('`', preg_replace($varpattern, '`$1`', $text));
// The length will always be odd, and the variables are stored in odd index.
for ($i = 1; $i < mycount($splitted); $i += 2) {
if (!array_key_exists($splitted[$i], $this->constlist)) {
continue;
}
$constnumber = $preserve ? $splitted[$i] : $this->constlist[$splitted[$i]];
$splitted[$i] = $this->vstack_add_temporary_variable($vstack, 'n', $constnumber);
}
return implode('', $splitted);
}
// Return a string with all variables substituted by placeholders. The information of placeholders is stored in v.
private function substitute_variables_by_placeholders(&$vstack, $text, $internal=false) {
$varpattern = $internal ? '/([A-Za-z_][A-Za-z0-9_]*)/' : '/([A-Za-z][A-Za-z0-9_]*)/';
$funclists = $internal ? $this->func_all : $this->func_algebraic;
// @codingStandardsIgnoreLine
$splitted = explode('`', preg_replace($varpattern, '`$1`', $text));
// The length will always be odd, and the variables are stored in odd index.
for ($i = 1; $i < mycount($splitted); $i += 2) {
if (array_key_exists($splitted[$i], $funclists)) {
throw new Exception(get_string('error_vars_reserved', 'qtype_formulas', $splitted[$i]));
}
$splitted[$i] = $this->vstack_add_temporary_variable($vstack, 'v', $splitted[$i]);
}
return implode('', $splitted);
}
// Parse the number or range in the format of start(:stop(:interval)). return null if error.
private function parse_fixed_range(&$vstack, $expression) {
$ex = explode(':', $expression);
if (mycount($ex) > 3) {
return null;
}
$numpart = mycount($ex);
for ($i = 0; $i < $numpart; $i++) {
$ex[$i] = trim($ex[$i]);
if (mycount($ex[$i]) == 0) {
return null;
}
$v = $ex[$i][0] == '-' ? trim(substr($ex[$i], 1)) : $ex[$i]; // Get the sign of the number.
$num = $this->vstack_get_variable($vstack, $v); // Num must be a constant number.
if ($num === null || $num->type != 'n' || !is_string($num->value)) {
return null;
}
$ex[$i] = strlen($ex[$i]) == strlen($v) ? floatval($num->value) : -floatval($num->value); // Multiply the sign back.
}
if (mycount($ex) == 1) {
$ex = array($ex[0], $ex[0] + 0.5, 1.);
}
if (mycount($ex) == 2) {
$ex = array($ex[0], $ex[1], 1.);
}
if ($ex[0] > $ex[1] || $ex[2] <= 0) {
return null;
}
return (object)array('numelement' => ceil( ($ex[1] - $ex[0]) / $ex[2] ), 'element' => $ex, 'numpart' => $numpart);
}
/**
* There are two main forms of random variables, specified in the form 'variable = expression;'
* The first form is declared as a set of either number, string, list of number and list of string.
* One element will be drawn from the set when instantiating. Note that it allow a range format of numbers
* Another one is the shuffling of a list of number or string.
* e.g. A={1,2,3}; B={1, 3:5, 8:9:.1}; C={"A","B"}; D={[1,4],[1,9]}; F=shuffle([0:10]);
*/
// Parse the random variables $assignments for later instantiation of a dataset. Throw on parsing error.
public function parse_random_variables($text) {
$vstack = $this->vstack_create();
$text = $this->substitute_strings_by_placholders($vstack, $text);
$text = $this->trim_comments($text);
$text = $this->substitute_numbers_by_placeholders($vstack, $text);
// Check whether variables or some reserved variables are used, throw on error.
$tmpvars = clone $vstack;
$tmptext = $text;
$tmptext = $this->substitute_functions_by_placeholders($tmpvars, $tmptext, true);
$tmptext = $this->substitute_variables_by_placeholders($tmpvars, $tmptext, true);
$assignments = explode(';', $text);
foreach ($assignments as $acounter => $assignment) {
try {
// Split into variable name and expression.
$ex = explode('=', $assignment, 2);
$name = trim($ex[0]);
if (mycount($ex) == 1 && strlen($name) == 0) {
continue; // If empty assignment.
}
if (mycount($ex) != 2) {
throw new Exception(get_string('error_syntax', 'qtype_formulas'));
}
if (!preg_match('/^[A-Za-z0-9_]+$/', $name)) {
throw new Exception(get_string('error_vars_name', 'qtype_formulas'));
}
$expression = trim($ex[1]);
$expression = $this->substitute_fixed_ranges_by_placeholders($vstack, $expression);
if (strlen($expression) == 0) {
throw new Exception(get_string('error_syntax', 'qtype_formulas'));
}
// Check whether the expression contains only the valid character set.
$var = (object)array('numelement' => 0, 'elements' => array());
if ($expression[0] == '{') {
$allowableoperatorchar = '-+*/:@0-9,\s}{\]\['; // Restricted set, prevent too many calculations.
// The result expression should only contains simple characters.
if (!preg_match('~^['.$allowableoperatorchar.']*$~', $expression)) {
throw new Exception(get_string('error_forbid_char', 'qtype_formulas'));
}
$bracket = $this->get_expressions_in_bracket($expression, 0, '{');
if ($bracket === null) {
throw new Exception(get_string('error_vars_bracket_mismatch', 'qtype_formulas'));
}
if (!($bracket->openloc == 0 && $bracket->closeloc == strlen($expression) - 1)) {
throw new Exception(get_string('error_syntax', 'qtype_formulas'));
}
$type = null;
foreach ($bracket->expressions as $i => $ele) {
if ($i == 0 && strpos($ele, ':') !== false) {
$type = 'n';
}
if ($type != 'n') {
$result = $this->evaluate_general_expression_substituted_recursively($vstack, $ele);
if ($i == 0) {
$type = $result->type;
}
if ($i > 0 && $result->type != $type) {
throw new Exception(get_string('error_randvars_type', 'qtype_formulas'));
}
$element = $result->value;
$numelement = 1;
}
if ($type == 'n') { // Special handle for number, because it can be specified as a range.
$result = $this->parse_fixed_range($vstack, $ele);
if ($result === null) {
throw new Exception(get_string('error_syntax', 'qtype_formulas'));
}
$element = $result->element;
$numelement = $result->numelement;
}
if ($i == 0) {
$listsize = $type[0] == 'l' ? mycount($element) : 1;
}
if ($i > 0) {
if (($type[0] == 'l' ? mycount($element) : 1) != $listsize) {
throw new Exception(get_string('error_randvars_type', 'qtype_formulas'));
}
}
$var->elements[] = $element;
$var->numelement += $numelement;
}
$type = 'z'.$type;
} else if ( preg_match('~^shuffle\s*\(([-+*/@0-9,\s\[\]]+)\)$~', $expression, $matches) ) {
$result = $this->evaluate_general_expression_substituted_recursively($vstack, $matches[1]);
if ($result === null || $result->type[0] != 'l') {
throw new Exception(get_string('error_syntax', 'qtype_formulas'));
}
$type = 'zh'.$result->type;
// Factorials can get pretty big, so it is worth limiting the true count to
// some reasonable number, e.g. 1000.
$var->numelement = min(1000, fact(mycount($result->value)));
$var->elements = $result->value;
} else {
throw new Exception(get_string('error_syntax', 'qtype_formulas'));
}
// There must be at least two elements to draw from, otherwise it is not a random variable.
if ($var->numelement < 2) {
throw new Exception(get_string('error_randvars_set_size', 'qtype_formulas'));
}
$this->vstack_update_variable($vstack, $name, null, $type, $var);
} catch (Exception $e) { // Append the error message by the line info.
throw new Exception(($acounter + 1).': '.$name.': '.$e->getMessage());
}
}
return $this->vstack_clean_temporary($vstack);
}
// Instantiate a particular variables set given by datasetid (-1 for random). Another vstack of will be returned.
public function instantiate_random_variables(&$vstack, $datasetid = -1) {
$numdataset = $this->vstack_get_number_of_dataset($vstack);
$datasetid = ($datasetid >= 0 && $datasetid < self::$maxdataset) ? $datasetid % $numdataset : -1;