forked from jmvedrine/moodle-qtype_algebra
-
Notifications
You must be signed in to change notification settings - Fork 0
/
parser.php
1858 lines (1755 loc) · 77.2 KB
/
parser.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/>.
/**
* Parser code for the Moodle Algebra question type Moodle algebra question type class
*
* @package qtype_algebra
* @copyright Roger Moore <rwmoore 'at' ualberta.ca>
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
defined('MOODLE_INTERNAL') || die();
/**
* Helper function which will compare two strings using their length only.
*
* This function is intended for use in sorting arrays of strings by their string
* length. This is used to order arrays for regular expressions so that the longest
* expressions are checked first.
* In this version, if both strings have equal length, string order is used. So this
* version of the sort is stable.
*
*
* @package qtype_algebra
* @author Roger Moore <rwmoore 'at' ualberta.ca>
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
* @param string $a first string to compare
* @param string $b second string to compare
* @return numeric -1 if $a is longer than $b, and +1 if $a is shorter
*/
function qtype_algebra_parser_strlen_sort($a, $b) {
// Get the two string lengths once so we don't have to repeat the function call.
$alen = strlen($a);
$blen = strlen($b);
// If the two lengths are equal use strings order.
if ($alen == $blen) {
return ($a > $b) ? -1 : +1;
}
// Otherwise return +1 if a is shorter or -1 if longer.
return ($alen > $blen) ? -1 : +1;
}
/**
* Base class for all the types of exception we throw.
*
* @package qtype_algebra
* @author Roger Moore <rwmoore 'at' ualberta.ca>
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
class parser_exception extends moodle_exception {
/**
* The constructor
*
* @param object $error
*/
public function __construct($error) {
parent::__construct('exceptionmessage', 'qtype_algebra', '', $error);
}
}
/**
* Class which represents a single term in an algebraic expression.
*
* A single algebraic term is considered to be either an operation, for example addition,
* subtraction, raising to a power etc. or something operated on, such as a number or
* variable. Each type of term implements a subclass of this base class.
*
* @package qtype_algebra
* @author Roger Moore <rwmoore 'at' ualberta.ca>
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
class qtype_algebra_parser_term {
// Member variables.
/** @var string */
public $_value; // String of the actual term itself.
/** @var array */
public $_arguments = array(); // Array of arguments in class form.
/** @var array */
public $_formats; // Array of format strings.
/** @var int */
public $_nargs; // Number of arguments for this term.
/**
* Constructor for the generic parser term.
*
* This method is called by all subclasses to initialize the base class for use.
* It initializes the number of arguments required, the format strings to use
* when converting the term in various strng formats, the parser text associated
* with the term and whether the term is one which commutes.
*
* @param int $nargs number of arguments which this type of term requires
* @param array $formats an array of the format strings for this term keyed by type
* @param string $text the text from the expression associated with the array
* @param bool $commutes if set to true then this term commutes (only for 2 argument terms)
*/
public function __construct($nargs, $formats, $text = '', $commutes = false) {
$this->_value = $text;
$this->_nargs = $nargs;
$this->_formats = $formats;
$this->_commutes = $commutes;
}
/**
* Generates the list of arguments needed when converting the term into a string.
*
* This method returns an array with the arguments needed when converting the term
* into a string. The arrys can then be used with a format string to generate the
* string representation. The method is recursive because it needs to convert the
* arguments of the term into strings and so it will walk down the parse tree.
*
* @param object $method name of method to call to convert arguments into strings
* @return array of the arguments that, with a format string, can be passed to sprintf
*/
public function print_args($method) {
// Create an empty array to store the arguments in.
$args = array();
// Handle zero argument terms differently by making the
// first 'argument' the value of the term itself.
if ($this->_nargs == 0) {
$args[] = $this->_value;
} else {
foreach ($this->_arguments as $arg) {
$args[] = $arg->$method();
}
}
// Return the array of arguments.
return $args;
}
/**
* Produces a 'prettified' string of the expression using the standard input syntax.
*
* This method will use the print_args() method to convert the term and all its
* arguments into a string.
*
* @return string input syntax format string of the expression
* @throws parser_exception
*/
public function str() {
// First check to see if the class has been given all the arguments.
$this->check_arguments();
// Get an array of all the arguments except for the format string.
$args = $this->print_args('str');
// Insert the format string at the front of the argument array.
array_unshift($args, $this->_formats['str']);
// Call sprintf using the argument array as the arguments.
return call_user_func_array('sprintf', $args);
}
/**
* Produces a LaTeX formatted string of the expression.
*
* This method will use the print_args() method to convert the term and all its
* arguments into a LaTeX formatted string. This can then be given to the main Moodle
* engine, with TeX filter enabled, to produce a graphical representation of the
* expression.
*
* @return string LaTeX format string of the expression
* @throws parser_exception
*/
public function tex() {
// First check to see if the class has been given all the arguments.
$this->check_arguments();
// Get an array of all the arguments except for the format string.
$args = $this->print_args('tex');
// Insert the format string at the front of the argument array.
array_unshift($args, $this->_formats['tex']);
// Call sprintf using the argument array as the arguments.
return call_user_func_array('sprintf', $args);
}
/**
* Produces a SAGE formatted string of the expression.
*
* This method will use the print_args() method to convert the term and all its
* arguments into a SAGE formatted string. This can then be passed to SAGE via XML-RPC
* for symbolic comparisons. The format is very similar to the str() method but
* has all multiplications made explicit with an asterix.
*
* @return object SAGE format string of the expression
* @throws parser_exception
*/
public function sage() {
// First check to see if the class has been given all the arguments.
$this->check_arguments();
// Get an array of all the arguments except for the format string.
$args = $this->print_args('sage');
// Insert the format string at the front of the argument array. First we
// check to see if there is a format element called 'sage' if not then we
// default to the standard string format.
if (array_key_exists('sage', $this->_formats)) {
// Insert the sage format string at the front of the argument array.
array_unshift($args, $this->_formats['sage']);
} else {
// Insert the normal format string at the front of the argument array.
array_unshift($args, $this->_formats['str']);
}
// Call sprintf using the argument array as the arguments.
return call_user_func_array('sprintf', $args);
}
/**
* Returns the list of arguments for the term.
*
* This method provides access to the arguments of the term. Although this should
* ideally be private information it is needed in certain cases to determine
* how neighbouring terms should display themselves.
*
* @return array of arguments for this term
*/
public function arguments() {
return $this->_arguments;
}
/**
* Sets the arguments of the term to the values in the given array.
*
* The code here overrides the base class's method. The code uses this method to actually
* set the arguments in the given array but a second stage to choose the format of the
* multiplication operator is required. This is because a 'x' symbol is required when
* multiplying two numbers. However this can be omitted when multiplying two variables,
* a variable and a function etc.
*
* @param array $args array to set the arguments of the term to
* @return void
* @throws coding_exception
* @throws parser_exception
*/
public function set_arguments($args) {
if (count($args) != $this->_nargs) {
throw new parser_exception(get_string('nargswrong', 'qtype_algebra', $this->_value));
}
$this->_arguments = $args;
}
/**
* Checks to ensure that the correct number of arguments are defined.
*
* Note that this method just checks for the number or arguments it does not check
* whether they are valid arguments. If the parameter passed is true (default value)
* an exception will be thrown if the correct number of arguments are not present. Otherwise
* the function returns false.
*
* @param object $exc if true then an exception will be thrown if the number of arguments is incorrect
* @return bool true if the correct number of arguments are present, false otherwise
*/
public function check_arguments($exc = true) {
$retval = (count($this->_arguments) == $this->_nargs);
if ($exc && !$retval) {
throw new parser_exception(get_string('nargswrong', 'qtype_algebra', $this->_value));
} else {
return $retval;
}
}
/**
* Returns a list of all the variable names found in the expression.
*
* This method uses the collect() method to walk down the parse tree and collect
* a list of all the variables which the parser has found in the expression. The names
* of the variables are then returned.
*
* @return array an array containing all the variables names in the expression
*/
public function get_variables() {
$list = array();
$this->collect($list, 'qtype_algebra_parser_variable');
return array_keys($list);
}
/**
* Returns a list of all the function names found in the expression.
*
* This method uses the collect() method to walk down the parse tree and collect
* a list of all the functions which the parser has found in the expression. The names
* of the functions are then returned.
*
* @return array an array containing all the function names used in the expression
*/
public function get_functions() {
$list = array();
$this->collect($list, 'qtype_algebra_parser_function');
return array_keys($list);
}
/**
* Collects all the terms of a given type with unique values in the parse tree
*
* This method walks recursively down the parse tree by calling itself for the arguments
* of the current term. The method simply adds the current term to the given imput array
* using a key set to the value of the term but only if the term matches the selected type.
* In this way terms only a single entry per term value is return which is the functionality
* required for the get_variables() and get_functions() methods.
*
* @param array $list the array to add the term to if it matches the type
* @param object $type the name of the type of term to collect.
* @return array an array containing all the terms of the selected type keyed by their value
*/
public function collect(&$list, $type) {
// Add this class to the list if of the correct type.
if (is_a($this, $type)) {
// Add a key to the array with the value of the term, this means
// that multiple terms with the same value will overwrite each
// other so only one will remain.
$list[$this->_value] = 0;
}
// Now loop over all the argument for this term (if any) and check them.
foreach ($this->_arguments as $arg) {
// Collect terms from the arguments as well.
$arg->collect($list, $type);
}
}
/**
* Checks to see if this term is equal to another term ignoring arguments.
*
* This method compares the current term to another term. The default method simply compares
* the class of each term. Terms which require more than this, for example comparing values
* too, override this method in theor own classes.
*
* @param object $term the term to compare to the current one
* @return bool true if the terms match, false otherwise
*/
public function equals($term) {
// Default method just checks to ensure that the Terms are both of the same type.
return is_a($term, get_class($this));
}
/**
* Compares this term, including any arguments, with another term.
*
* This method uses the equals() method to see if the current and given term match.
* It then looks at any arguments which the two terms have and, recursively, calls their
* compare methods to determine if they also match. For terms with two arguments which
* also commute the reverse ordering of the arguments is also tried if the first order
* fails to match.
*
* @param object $expr top level term of an expression to compare against
* @return bool true if the expressions match, false otherwise
*/
public function equivalent($expr) {
// Check that the argument is also a term.
if (!is_a($expr, 'qtype_algebra_parser_term')) {
throw new parser_exception(get_string('badequivtype', 'qtype_algebra'));
}
// Now check that this term is the same as the given term.
if (!$this->equals($expr)) {
// Terms are not equal immediately return false since the two do not match.
return false;
}
// Now compare the arguments recursively...
switch($this->_nargs) {
case 0:
// For zero arguments we already compared this class and found it the same so
// because there are no arguments to check we are equivalent!
return true;
case 1:
// For one argument we also need to compare the argument of each term.
return $this->_arguments[0]->equivalent($expr->_arguments[0]);
case 2:
// Now it gets interesting. First we compare the two arguments in the same
// order and see what we get...
if ($this->_arguments[0]->equivalent($expr->_arguments[0]) &&
$this->_arguments[1]->equivalent($expr->_arguments[1])) {
// Both arguments are equivalent so we have a match.
return true;
} else if ($this->_commutes && $this->_arguments[0]->equivalent($expr->_arguments[1]) &&
$this->_arguments[1]->equivalent($expr->_arguments[0])) {
// Otherwise if the operator commutes we can see if the first argument matches
// the second argument and vice versa.
return true;
} else {
return false;
}
default:
throw new parser_exception(get_string('morethantwoargs', 'qtype_algebra'));
}
}
/**
* Returns the number of arguments required by the term.
*
* @return int the number of arguments required by the term
*/
public function n_args() {
return $this->_nargs;
}
/**
* Evaluates the term numerically using the given variable values.
*
* The given parameter array is keyed by the name of the variable and the numerical
* value to assign it is stored in the array value. This method is an abstract one
* which must be implemented by all subclasses. Failure to do so will generate an
* exception when the method is called.
*
* @param array $params array of values keyed by variable name
* @return numeric the numerical value of the term given the provided values for the variables
*/
public function evaluate($params) {
throw new parser_exception(get_string('noevaluate', 'qtype_algebra', $this->_value));
}
/**
* Dumps the term and its arguments to standard out.
*
* This method will recursively call the entire parse tree attached to it and produce
* a nicely formatted dump of the term structure. This is mainly useful for debugging
* purposes.
*
* @param object $params variable values to use if an evaluation is also desired
* @param string $indent string containing the indentation to use
* @return void a string indicating the type of the term
* @throws parser_exception
*/
public function dump(&$params = array(), $indent = '') {
echo "$indent<Term type '".get_class($this).'\' with value \''.$this->_value;
if (!empty($params)) {
echo ' eval = \''.$this->evaluate($params)."'>\n";
} else {
echo "'>\n";
}
foreach ($this->_arguments as $arg) {
$arg->dump($params, $indent.' ');
}
}
/**
* Special casting operator method to convert the term object to a string.
*
* This is primarily a debug method. It is called when the term object is cast into a
* string, such as happens when echoing or printing it. It simply returns a string
* indicating the type of the parser term.
*
* @return string a string indicating the type of the term
*/
public function __toString() {
return '<Algebraic parser term of type \''.get_class($this).'\'>';
}
}
/**
* Class representing a null, or empty, term.
*
* This is the type of term returned when the parser is given an empty string to parse.
* It takes no arguments and will never be found in a parser tree. This term is solely
* to give a valid return type for an empty string condition and so avoids the need to
* throw an exception in such cases.
*
* @package qtype_algebra
* @author Roger Moore <rwmoore 'at' ualberta.ca>
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
class qtype_algebra_parser_nullterm extends qtype_algebra_parser_term {
/** @var The TeX multiply operator. */
public $id;
/**
* Constructs an instance of a null term.
*
* Initializes a null term class. Since this class represents nothing no special
* initialization is required and no arguments are needed.
*/
public function __construct() {
parent::__construct(self::NARGS, self::$formats, '');
}
/**
* Returns the array of arguments needed to convert this class into a string.
*
* Since this class is represented by an empty string which has no formatting fields
* we override the base class method to return an empty array.
*
* @param object $method name of method to call to convert arguments into strings
* @return array of the arguments that, with a format string, can be passed to sprintf
*/
public function print_args($method) {
return array();
}
/**
* Evaluates the term numerically.
*
* Since this is an empty term we define the evaluation as zero regardless of the parameters.
*
* @param array $params array of the variable values to use
* @return float|int|string
*/
public function evaluate($params) {
// Return something which is not a number.
return acos(2.0);
}
// Static class properties.
/** Number of arguments */
const NARGS = 0;
/** @var array */
private static $formats = array('str' => '',
'tex' => '');
}
/**
* Class representing a number.
*
* All purely numerical quantities will be represented by this type of class. There are
* two basic types of numbers: non-exponential and exponential. Both types are handled by
* this single class.
*
* @package qtype_algebra
* @author Roger Moore <rwmoore 'at' ualberta.ca>
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
class qtype_algebra_parser_number extends qtype_algebra_parser_term {
/**
* Constructs an instance of a number term.
*
* This function initializes an instance of a number term using the string which
* matches the number's regular expression.
*
* @param string $text string matching the number regular expression
* @throws dml_exception
*/
public function __construct($text = '') {
// Unfortunately PHP maths will only support a '.' as a decimal point and will not support
// ',' as used in Danish, French etc. To allow for this we always convert any commas into
// decimal points before we parse the string.
$text = str_replace(',', '.', $text);
$this->_sign = '';
// Now determine whether this is in exponent form or just a plain number.
if (preg_match('/([\.0-9]+)E([-+]?\d+)/', $text, $m)) {
$this->_base = $m[1];
$this->_exp = $m[2];
$eformats = array('str' => '%sE%s',
'tex' => '%s \\' . get_config('qtype_algebra', 'multiplyoperator') . '10^{%s}');
parent::__construct(self::NARGS, $eformats, $text);
} else {
$this->_base = $text;
$this->_exp = '';
parent::__construct(self::NARGS, self::$formats, $text);
}
}
/**
* Sets this number to be negative.
*
* This method will convert the number into a nagetive one. It is called when
* the parser finds a subtraction operator in front of the number which does
* not have a variable or another number preceding it.
*
* @return void
*/
public function set_negative() {
// Prepend a minus sign to both the base and total value strings.
$this->_base = '-'.$this->_base;
$this->_value = '-'.$this->_value;
$this->_sign = '-';
}
/**
* Checks to see if this number is equal to another number.
*
* This is a two step process. First we use the base class equals method to ensure
* that we are comparing two numbers. Then we check that the two have the same value.
*
* @param object $expr the term to compare to the current one
* @return bool true if the terms match, false otherwise
*/
public function equals($expr) {
// Call the default method first to check type.
if (parent::equals($expr)) {
return (float)$this->_value == (float)$expr->_value;
} else {
return false;
}
}
/**
* Generates the list of arguments needed when converting the term into a string.
*
* For number terms there are two possible formats: those with an exponent and those
* without an exponent. This method determines which to use and then pushes the correct
* arguments into the array which is returned.
*
* @param object $method name of method to call to convert arguments into strings
* @return array of the arguments that, with a format string, can be passed to sprintf
*/
public function print_args($method) {
// When displaying the number we need to worry about whether to use a decimal point
// or a comma depending on the language currently selected/ Do this by replacing the
// decimal point (which we have to use internally because of the PHP math standard)
// with the correct string from the language pack.
$base = str_replace('.', get_string('decimal', 'qtype_algebra'), $this->_base);
// Put the base part of the number into the argument array.
$args = array($base);
// Check to see if we have an exponent...
if ($this->_exp) {
// We do so add it to the argument array as well.
$args[] = $this->_exp;
}
// Return the list of arguments.
return $args;
}
/**
* Evaluates the term numerically.
*
* All this method does is return the string representing the number cast as a double
* precision floating point variable.
*
* @param array $params array of the variable values to use
*/
public function evaluate($params) {
return doubleval($this->_value);
}
// Static class properties.
/** Number of arguments */
const NARGS = 0;
/** @var array */
private static $formats = array('str' => '%s',
'tex' => '%s ');
}
/**
* Class representing a variable term in an algebraic expression.
*
* When the parser finds a text string which does not correspond to a function it creates
* this type of term and puts the contents of that text into it. Variables with names
* corresponding to the names of the greek letters are replaced by those letters when
* rendering the term in LaTeX. Other variables display their first letter with all
* subsequent letters being lowercase. This reduces confusion when rendering expressions
* consisting of multiplication of two variables.
*
* @package qtype_algebra
* @author Roger Moore <rwmoore 'at' ualberta.ca>
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
class qtype_algebra_parser_variable extends qtype_algebra_parser_term {
// Define the list of variable names which will be replaced by greek letters.
/** @var array */
public static $greek = array (
'alpha',
'beta',
'gamma',
'delta',
'epsilon',
'zeta',
'eta',
'theta',
'iota',
'kappa',
'lambda',
'mu',
'nu',
'xi',
'omicron',
'pi',
'rho',
'sigma',
'tau',
'upsilon',
'phi',
'chi',
'psi',
'omega'
);
/**
* Constructor for an algebraic term cass representing a variable.
*
* Initializes an instance of the variable term subclass. The method is given the text
* in the expression corresponding to the variable name. This is then parsed to get the
* variable name which is split into a base and subscript. If the start of the string
* matches the name of a greek letter this is taken as the base and the remainder as the
* subscript. Failing that either the subscript must be explicitly specified using an
* underscore character or the first character is taken as the base.
*
* @param string $text text matching the variable name
*/
public function __construct($text) {
// Create the array to store the regular expression matches in.
$m = array();
// Set the sign of the variable to be empty.
$this->_sign = '';
// Try to match the text to a greek letter.
if (preg_match('/('.implode('|', self::$greek).')/A', $text, $m)) {
// Take the base name of the variable to be the greek letter.
$this->_base = $m[1];
// Extract the remaining characters for use as the subscript.
$this->_subscript = substr($text, strlen($m[1]));
// If the first letter of the subscript is an underscore then remove it.
if (strlen($this->_subscript) != 0 && $this->_subscript[0] == '_') {
$this->_subscript = substr($this->_subscript, 1);
}
// Call the base class constructor with the variable text set to the combination of the
// base name and the subscript without an underscore between them.
parent::__construct(self::NARGS, self::$formats['greek'],
$this->_base.$this->_subscript);
} else {
// Otherwise we have a simple multi-letter variable name. Treat the fist letter as the base
// name and the rest as the subscript.
// Get the variable's base name.
$this->_base = substr($text, 0, 1);
// Now set the subscript to the remaining letters.
$this->_subscript = substr($text, 1);
// If the first letter of the subscript is an underscore then remove it.
if (strlen($this->_subscript) != 0 && $this->_subscript[0] == '_') {
$this->_subscript = substr($this->_subscript, 1);
}
// Call the base class constructor with the variable text set to the combination of the
// base name and the subscript without an underscore between them.
parent::__construct(self::NARGS, self::$formats['std'],
$this->_base.$this->_subscript);
}
}
/**
* Sets this variable to be negative.
*
* This method will convert the number into a nagetive one. It is called when
* the parser finds a subtraction operator in front of the number which does
* not have a variable or another number preceding it.
*
* @return void
*/
public function set_negative() {
// Set the sign to be a '-'.
$this->_sign = '-';
}
/**
* Generates the list of arguments needed when converting the term into a string.
*
* The string of the variable depends solely on the name and subscript and hence these
* are the only two arguments returned in the array.
*
* @param object $method name of method to call to convert arguments into strings
* @return array of the arguments that, with a format string, can be passed to sprintf
*/
public function print_args($method) {
return array($this->_sign, $this->_base, $this->_subscript);
}
/**
* Evaluates the number numerically.
*
* Overrides the base class method to simply return the numerical value of the number the
* class represents.
*
* @param array $params array of values keyed by variable name
* @return numeric the numerical value of the term given the provided values for the variables
*/
public function evaluate($params) {
if ($this->_sign == '-') {
$mult = -1;
} else {
$mult = 1;
}
if (array_key_exists($this->_value, $params)) {
return $mult * doubleval($params[$this->_value]);
} else {
// Found an indefined variable. Cannot evaluate numerically so throw exception.
throw new parser_exception(get_string('undefinedvariable', 'qtype_algebra', $this->_value));
}
}
/**
* Checks to see if this variable is equal to another variable.
*
* This is a two step process. First we use the base class equals method to ensure
* that we are comparing two variables. Then we check that the two are the same variable.
*
* @param object $expr the term to compare to the current one
* @return bool true if the terms match, false otherwise
*/
public function equals($expr) {
// Call the default method first to check type.
if (parent::equals($expr)) {
return $this->_value == $expr->_value && $this->_sign == $expr->_sign;
} else {
return false;
}
}
// Static class properties.
/** Number of arguments */
const NARGS = 0;
/** @var array */
private static $formats = array(
'greek' => array('str' => '%s%s%s',
'tex' => '%s\%s_{%s}'),
'std' => array('str' => '%s%s%s',
'tex' => '%s%s_{%s}')
);
}
/**
* Class representing a power operation in an algebraic expression.
*
* The parser creates an instance of this term when it finds a string matching the power
* operator's syntax. The string which corresponds to the term is passed to the constructor
* of this subclass.
*
* @package qtype_algebra
* @author Roger Moore <rwmoore 'at' ualberta.ca>
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
class qtype_algebra_parser_power extends qtype_algebra_parser_term {
/**
* Constructs an instance of a power operator term.
*
* This function initializes an instance of a power operator term using the string which
* matches the power operator expression. Since this is simply the character representing
* the operator it is not used except when producing a string representation of the term.
*
* @param string $text string matching the term's regular expression
*/
public function __construct($text) {
parent::__construct(self::NARGS, self::$formats, $text);
}
/**
* Evaluates the power operation numerically.
*
* Overrides the base class method to simply return the numerical value of the power
* operation. The method evaluates the two arguments of the term and then passes them to
* the 'pow' function from the maths library.
*
* @param array $params array of values keyed by variable name
* @return numeric the numerical value of the term given the provided values for the variables
*/
public function evaluate($params) {
$this->check_arguments();
return pow(doubleval($this->_arguments[0]->evaluate($params)),
doubleval($this->_arguments[1]->evaluate($params)));
}
// Static class properties.
/** Number of arguments */
const NARGS = 2;
/** @var array */
private static $formats = array(
'str' => '%s^%s',
'tex' => '%s^{%s}'
);
}
/**
* Class representing a divide operation in an algebraic expression.
*
* The parser creates an instance of this term when it finds a string matching the divide
* operator's syntax. The string which corresponds to the term is passed to the constructor
* of this subclass.
*
* @package qtype_algebra
* @author Roger Moore <rwmoore 'at' ualberta.ca>
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
class qtype_algebra_parser_divide extends qtype_algebra_parser_term {
/**
* Constructs an instance of a divide operator term.
*
* This function initializes an instance of a divide operator term using the string which
* matches the divide operator expression. Since this is simply the character representing
* the operator it is not used except when producing a string representation of the term.
*
* @param string $text string matching the term's regular expression
*/
public function __construct($text) {
parent::__construct(self::NARGS, self::$formats, $text);
}
/**
* Evaluates the divide operation numerically.
*
* Overrides the base class method to simply return the numerical value of the divide
* operation. The method evaluates the two arguments of the term and then simply divides
* them to get the return value.
*
* @param array $params array of values keyed by variable name
* @return numeric the numerical value of the term given the provided values for the variables
*/
public function evaluate($params) {
$this->check_arguments();
// Get the value we are trying to divide by.
$divby = $this->_arguments[1]->evaluate($params);
// Check to see if this is zero.
if ($divby == 0) {
// Check the sign of the other argument and use to determine whether we return
// plus or minus infinity.
return INF * $this->_arguments[0]->evaluate($params);
} else {
return $this->_arguments[0]->evaluate($params) / $divby;
}
}
// Static class properties.
/** Number of arguments */
const NARGS = 2;
/** @var array */
private static $formats = array(
'str' => '%s/%s',
'tex' => '\\frac{%s}{%s}'
);
}
/**
* Class representing a multiplication operation in an algebraic expression.
*
* The parser creates an instance of this term when it finds a string matching the multiplication
* operator's syntax. The string which corresponds to the term is passed to the constructor
* of this subclass.
*
* @package qtype_algebra
* @author Roger Moore <rwmoore 'at' ualberta.ca>
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
class qtype_algebra_parser_multiply extends qtype_algebra_parser_term {
/**
* Constructs an instance of a multiplication operator term.
*
* This function initializes an instance of a multiplication operator term using the string which
* matches the multiplication operator expression. Since this is simply the character representing
* the operator it is not used except when producing a string representation of the term.
*
* @param string $text string matching the term's regular expression
*/
public function __construct($text) {
$this->mformats = array('*' => array('str' => '%s*%s',
'tex' => '%s \\' . get_config('qtype_algebra', 'multiplyoperator') . ' %s'),
'.' => array('str' => '%s %s',
'tex' => '%s %s',
'sage' => '%s*%s')
);
parent::__construct(self::NARGS, $this->mformats['*'], $text, true);
}
/**
* Sets the arguments of the term to the values in the given array.
*
* This method sets the term's arguments to those in the given array.
*
* @param array $args array to set the arguments of the term to
*/
public function set_arguments($args) {
// First perform default argument setting method. This will generate
// an error if there is a problem with the number of arguments.
parent::set_arguments($args);
// Set the default explicit format.
$this->_formats = $this->mformats['*'];
// Only allow the implicit multiplication if the second argument is either a
// special, variable, function or bracket and not negative. In all other cases the operator must be
// explicitly written.
if (is_a($args[1], 'qtype_algebra_parser_bracket') ||
is_a($args[1], 'qtype_algebra_parser_variable') ||
is_a($args[1], 'qtype_algebra_parser_special') ||
is_a($args[1], 'qtype_algebra_parser_function')) {
if (!method_exists($args[1], 'set_negative') || $args[1]->_sign == '') {
$this->_formats = $this->mformats['.'];
}
}
// Check for one more special exemption: if the second argument is a power expression
// then we use the same criteria on the first argument of it.
if (is_a($args[1], 'qtype_algebra_parser_power')) {
// Get the arguments from the power term. Note we do not check these since
// power terms are parsed before multiplication ones and are required to
// have two arguments.
$powargs = $args[1]->arguments();
// Allow the implicit multiplication if the power's first argument is either a
// special, variable, function or bracket and not negative.
if (is_a($powargs[0], 'qtype_algebra_parser_bracket') ||
is_a($powargs[0], 'qtype_algebra_parser_variable') ||
is_a($powargs[0], 'qtype_algebra_parser_special') ||
is_a($powargs[0], 'qtype_algebra_parser_function')) {
if (!method_exists($powargs[0], 'set_negative') || $powargs[0]->_sign == '') {
$this->_formats = $this->mformats['.'];
}
}
}