-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathMathFunction.js
More file actions
executable file
·1433 lines (1263 loc) · 39.3 KB
/
MathFunction.js
File metadata and controls
executable file
·1433 lines (1263 loc) · 39.3 KB
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
/**
* scripts/wrapper/MathFunction_header.js
*/
/**
* Mathematical function object.
*/
(function loadMathParser(window, document, console, MathJax, isNaN, pow) {
/**
* scripts/MathFunction/dependencies/FunctionTree.js
*/
var FunctionTree = function() {};
FunctionTree.prototype = {
left: false,
right: false,
// check for right/left children
hasRight: function() {
return this.right!==false;
},
hasLeft: function() {
return this.left!==false;
},
// set the child nodes.
setLeaves: function(l, r) {
this.left = l;
this.right = r;
},
// check whether this tree has its leaved instantiated.
hasLeaves: function() {
return (this.left && this.right);
},
/**
* Evaluate the mathematical expression modelled
* by this tree, by substituting all variables
* in the [var_names] array with the corresponding
* values in the [values] array.
*/
evaluate: function(var_names, values) {
return false;
},
/**
* Returns the list of free parameters used in this function
*/
getParameters: function() {
var free = [];
this.addParametersFromChild(free, this.left);
this.addParametersFromChild(free, this.right);
return free;
},
// helper method
addParametersFromChild: function(list, child) {
if(child) {
var free = child.getParameters();
free.forEach(function(s){
if(list.indexOf(s)>-1) {
return;
}
list.push(s);
});
}
},
/**
* generate plot data.
* clamps: [{label:<str>,value:<num>},...]
*/
plot: function(varname, start, end, step, clamps) {
var data = [],
values = [],
var_names = [varname],
v;
clamps = clamps || [];
clamps.forEach(function(clamp){
var_names.push(clamp.label);
values.push(clamp.value);
});
for(var i=start; i<=end; i+=step) {
v = this.evaluate(var_names, [i].concat(values));
data.push([i, v]);
}
return data;
},
/**
* replace a variable with name [varname] with [replacement]
*/
replace: function(varname, replacement) {
var left = this.left, right = this.right;
if(left && left instanceof SimpleNode && left.label===varname) {
this.left = replacement;
}
if(right && right instanceof SimpleNode && right.label===varname) {
this.right = replacement;
}
}
};
/**
* scripts/MathFunction/dependencies/SimpleNodes.js
*/
/**
*
*/
var NumberNode = function(value) { this.value = parseFloat(value); };
NumberNode.prototype = new FunctionTree();
NumberNode.prototype.nf = function(val) {
var cap = (""+val).length-1-(""+(val|0)).length;
if(cap<0) cap=0;
return val.toFixed(cap);
};
NumberNode.prototype.evaluate = function() { return this.value; };
NumberNode.prototype.toString = function() { return /*"num:" +*/ this.nf(this.value); };
NumberNode.prototype.toLaTeX = function() { return "{" + this.nf(this.value) + "}"; };
NumberNode.prototype.getParameters = function() { return []; };
NumberNode.prototype.derive = function(varname) { return this; };
/**
*
*/
var SimpleNode = function(label) { this.label = label; };
SimpleNode.prototype = new FunctionTree();
SimpleNode.prototype.evaluate = function() {
if(arguments.length==1) return this.evaluate$1(arguments[0]);
if(arguments.length==2) return this.evaluate$2(arguments[0], arguments[1]);
return false; };
SimpleNode.prototype.evaluate$1 = function(v) { return v; };
SimpleNode.prototype.evaluate$2 = function(var_names, values) {
for(var i=0, last=var_names.length; i<last; i++) {
if(var_names[i] == this.label) {
return values[i]; }}
return false; };
SimpleNode.prototype.getParameters = function() { return [this.label]; };
SimpleNode.prototype.toString = function() { return /*"var:"+*/ this.label; };
SimpleNode.prototype.toLaTeX = function() { return this.label; };
/**
*
*/
var ConstantNode = function(label, value) { this.label = label; this.value = value; };
ConstantNode.prototype = new NumberNode();
/**
*
*/
var ConstantNode_pi = function() {};
ConstantNode_pi.prototype = new ConstantNode("π", Math.PI);
ConstantNode_pi.prototype.toLaTeX = function() { return "π"; };
/**
*
*/
var ConstantNode_e = function() {};
ConstantNode_e.prototype = new ConstantNode("e", Math.E);
ConstantNode_e.prototype.toLaTeX = function() { return "e"; };
// builder functions
var isNumber = function (n) { return n == parseFloat(n); };
var getSimpleNode = function(term) {
if(term == "π") return new ConstantNode_pi();
if(term == "pi") return new ConstantNode_pi();
if(term == "e") return new ConstantNode_e();
if(isNumber(term)) return new NumberNode(term);
return new SimpleNode(term);
};
/**
* scripts/MathFunction/dependencies/OperatorNodes.js
*/
/**
* Operator prototype
*/
var OperatorNode = function(op, str){
this.operator = op;
this.strength = str;
};
OperatorNode.prototype = new FunctionTree();
OperatorNode.prototype.getStrength = function() { return this.strength; };
OperatorNode.prototype.toString = function() {
var left = this.left, right = this.right;
return (left ? left.toString() : "") + this.operator + (right ? right.toString() : "");
};
OperatorNode.prototype.toLaTeX = function() {
return this.left.toLaTeX() + this.operator + this.right.toLaTeX();
};
/**
* Operator type lookup
*/
var operatorNodes = {},
unaryOperatorNodes = {};
/**
* ...
*/
var AdditionNode = function(){};
AdditionNode.prototype = new OperatorNode("+", 1);
AdditionNode.prototype.evaluate = function(var_names, values) {
var left = this.left, right = this.right;
return left.evaluate(var_names, values) + right.evaluate(var_names, values);
};
operatorNodes["+"] = AdditionNode;
/**
* ...
*/
var SubtractionNode = function(){};
SubtractionNode.prototype = new OperatorNode("-", 1);
SubtractionNode.prototype.evaluate = function(var_names, values) {
var left = this.left, right = this.right;
return left.evaluate(var_names, values) - right.evaluate(var_names, values);
};
operatorNodes["-"] = SubtractionNode;
/**
* ...
*/
var MultiplicationNode = function(){};
MultiplicationNode.prototype = new OperatorNode("*", 2);
MultiplicationNode.prototype.evaluate = function(var_names, values) {
var left = this.left, right = this.right;
return left.evaluate(var_names, values) * right.evaluate(var_names, values);
};
MultiplicationNode.prototype.toLaTeX = function() {
return this.left.toLaTeX() + " \\cdot " + this.right.toLaTeX();
};
operatorNodes["*"] = MultiplicationNode;
/**
* ...
*/
var DivisionNode = function(){};
DivisionNode.prototype = new OperatorNode("/", 2);
DivisionNode.prototype.evaluate = function(var_names, values) {
var left = this.left, right = this.right;
return left.evaluate(var_names, values) / right.evaluate(var_names, values);
};
DivisionNode.prototype.toLaTeX = function() {
return "\\frac{" + this.left.toLaTeX() + "}{" + this.right.toLaTeX() + "}";
};
operatorNodes["/"] = DivisionNode;
/**
* ...
*/
var PowerNode = function(){};
PowerNode.prototype = new OperatorNode("^", 4);
PowerNode.prototype.evaluate = function(var_names, values) {
var left = this.left, right = this.right;
return Math.pow(left.evaluate(var_names, values), right.evaluate(var_names, values));
};
operatorNodes["^"] = PowerNode;
// builder function
var getOperatorNode = function(op) {
if(operatorNodes[op]) {
return new operatorNodes[op]();
}
return false;
};
/**
* ...
*/
var NegativeNode = function(){};
NegativeNode.prototype = new OperatorNode("-", 3);
NegativeNode.prototype.hasLeft = function() { return false; };
NegativeNode.prototype.hasLeaves = function() { return this.right!==false; };
NegativeNode.prototype.setLeaves = function(l, r) { this.right = r; };
NegativeNode.prototype.evaluate = function(var_names, values) {
return - this.right.evaluate(var_names, values);
};
NegativeNode.prototype.toLaTeX = function() { return "-" + this.right.toLaTeX(); };
unaryOperatorNodes["-"] = NegativeNode;
/**
* ...
*/
var FactorialNode = function(){};
FactorialNode.prototype = new OperatorNode("!", 5);
FactorialNode.prototype.hasLeft = function() { return false; };
FactorialNode.prototype.hasLeaves = function() { return this.left!==false; };
FactorialNode.prototype.setLeaves = function(l, r) { this.left = l; };
FactorialNode.prototype.factorial = function(n) {
// TODO: add in LUT-speedup
if(n<=1) return 1;
return n * this.factorial(n-1);
};
FactorialNode.prototype.evaluate = function(var_names, values) {
var v = this.left.evaluate(var_names, values) | 0;
return this.factorial(v);
};
FactorialNode.prototype.toLaTeX = function() { return this.left.toLaTeX()+"!"; };
unaryOperatorNodes["!"] = FactorialNode;
// builder function
var getUnaryOperatorNode = function(op) {
if(unaryOperatorNodes[op]) {
return new unaryOperatorNodes[op]();
}
return false;
};
/**
* scripts/MathFunction/dependencies/FunctionNodes.js
*/
/**
*
*/
var FunctionNode = function(label) { this.label = label; };
FunctionNode.prototype = new FunctionTree();
FunctionNode.prototype.setContent = function(content) {
this.setLeaves(false,content);
this.content = content;
};
FunctionNode.prototype.replace = function(varname, replacement) {
if(this.content instanceof SimpleNode && this.content.label===varname) {
var mf = new MathFunction(replacement.toString());
this.setContent(mf.functionTree);
} else { this.content.replace(varname, replacement); }
};
FunctionNode.prototype.toString = function() { return /*"f:" +*/ this.label + "(" + this.content.toString() + ")"; };
FunctionNode.prototype.toLaTeX= function() { return this.label + "\\left ( " + this.content.toLaTeX() + " \\right ) "; };
/**
*
*/
var WrapperNode = function(content) { this.setContent(content); };
WrapperNode.prototype = new FunctionNode("wrapper");
WrapperNode.prototype.toString = function() { return "(" + this.content.toString() + ")"; };
WrapperNode.prototype.toLaTeX = function() { return " \\left ( " + this.content.toLaTeX() + " \\right ) "; };
WrapperNode.prototype.evaluate = function(var_names, values) {
return this.content.evaluate(var_names, values);
};
/**
*
*/
var functionNodes = {};
/**
*
*/
var FunctionNode_sin = function(content) { this.setContent(content); };
FunctionNode_sin.prototype = new FunctionNode("sin");
FunctionNode_sin.prototype.evaluate = function(var_names, values) {
return Math.sin(this.content.evaluate(var_names, values));
};
functionNodes.sin = FunctionNode_sin;
/**
*
*/
var FunctionNode_cos = function(content) { this.setContent(content); };
FunctionNode_cos.prototype = new FunctionNode("cos");
FunctionNode_cos.prototype.evaluate = function(var_names, values) {
return Math.cos(this.content.evaluate(var_names, values));
};
functionNodes.cos = FunctionNode_cos;
/**
*
*/
var FunctionNode_tan = function(content) { this.setContent(content); };
FunctionNode_tan.prototype = new FunctionNode("tan");
FunctionNode_tan.prototype.evaluate = function(var_names, values) {
return Math.tan(this.content.evaluate(var_names, values));
};
functionNodes.tan = FunctionNode_tan;
/**
*
*/
var FunctionNode_asin = function(content) { this.setContent(content); };
FunctionNode_asin.prototype = new FunctionNode("asin");
FunctionNode_asin.prototype.evaluate = function(var_names, values) {
return Math.asin(this.content.evaluate(var_names, values));
};
functionNodes.asin = FunctionNode_asin;
/**
*
*/
var FunctionNode_acos = function(content) { this.setContent(content); };
FunctionNode_acos.prototype = new FunctionNode("acos");
FunctionNode_acos.prototype.evaluate = function(var_names, values) {
return Math.acos(this.content.evaluate(var_names, values));
};
functionNodes.acos = FunctionNode_acos;
/**
*
*/
var FunctionNode_atan = function(content) { this.setContent(content); };
FunctionNode_atan.prototype = new FunctionNode("atan");
FunctionNode_atan.prototype.evaluate = function(var_names, values) {
return Math.atan(this.content.evaluate(var_names, values));
};
functionNodes.atan = FunctionNode_atan;
/**
*
*/
var FunctionNode_sinh = function(content) { this.setContent(content); };
FunctionNode_sinh.prototype = new FunctionNode("sinh");
FunctionNode_sinh.prototype.evaluate = function(var_names, values) {
return Math.sinh(this.content.evaluate(var_names, values));
};
functionNodes.sinh = FunctionNode_sinh;
/**
*
*/
var FunctionNode_cosh = function(content) { this.setContent(content); };
FunctionNode_cosh.prototype = new FunctionNode("cosh");
FunctionNode_cosh.prototype.evaluate = function(var_names, values) {
return Math.cosh(this.content.evaluate(var_names, values));
};
functionNodes.cosh = FunctionNode_cosh;
/**
*
*/
var FunctionNode_tanh = function(content) { this.setContent(content); };
FunctionNode_tanh.prototype = new FunctionNode("tanh");
FunctionNode_tanh.prototype.evaluate = function(var_names, values) {
return Math.tanh(this.content.evaluate(var_names, values));
};
functionNodes.tanh = FunctionNode_tanh;
/**
*
*/
var FunctionNode_ln = function(content) { this.setContent(content); };
FunctionNode_ln.prototype = new FunctionNode("ln");
FunctionNode_ln.prototype.evaluate = function(var_names, values) {
var v = this.content.evaluate(var_names, values);
return Math.log(v) / Math.log(Math.E);
};
functionNodes.ln = FunctionNode_ln;
/**
*
*/
var FunctionNode_log = function(content) { this.setContent(content); };
FunctionNode_log.prototype = new FunctionNode("log");
FunctionNode_log.prototype.evaluate = function(var_names, values) {
var v = this.content.evaluate(var_names, values);
return Math.log(v) / Math.log(10);
};
functionNodes.log = FunctionNode_log;
/**
*
*/
var FunctionNode_sqrt = function(content) { this.setContent(content); };
FunctionNode_sqrt.prototype = new FunctionNode("sqrt");
FunctionNode_sqrt.prototype.evaluate = function(var_names, values) {
return Math.sqrt(this.content.evaluate(var_names, values));
};
FunctionNode_sqrt.prototype.toLaTeX = function() { return "\\sqrt{" + this.content.toLaTeX() + "}"; };
functionNodes.sqrt = FunctionNode_sqrt;
/**
*
*/
var FunctionNode_abs = function(content) { this.setContent(content); };
FunctionNode_abs.prototype = new FunctionNode("abs");
FunctionNode_abs.prototype.evaluate = function(var_names, values) {
return Math.abs(this.content.evaluate(var_names, values));
};
FunctionNode_abs.prototype.toLaTeX = function() { return "|" + this.content.toLaTeX() + "|"; };
functionNodes.abs = FunctionNode_abs;
// builder function
var getFunctionNode = function(functor, content) {
if(functionNodes[functor]) {
return new functionNodes[functor](content);
}
return false;
};
/**
* scripts/MathFunction/dependencies/AggregatorNodes.js
*/
/**
* Very special function node.
*/
var AggregateNode = function(label) { this.label = label; };
AggregateNode.prototype = new FunctionNode();
AggregateNode.prototype.getParameters = function() { return this.content.getParameters(); };
AggregateNode.prototype.bindAll = function(parameters, content, startValue) {
this.startValue = startValue;
this.setContent(content);
params = [];
parameters.forEach(function(param) {
params.push(getSimpleNode(param));
});
this.parameters = params;
};
AggregateNode.prototype.evaluate = function(var_names, values) {
// augment variable names to include the special var "n"
var pos, last = var_names.length;
pos = var_names.indexOf("n");
if(pos===-1) { pos = var_names.length; var_names.push("n"); }
// calculate the start/end integer values
var s = this.parameters[0].evaluate(var_names,values),
e = this.parameters[1].evaluate(var_names,values);
// and compute aggregate
return this.computeAggregate(s,e,pos,var_names,values);
};
/**
* parameters:
* 0 = n_start value
* 1 = n_end value
*/
var FunctionNode_sum = function(parameters, content) { this.bindAll(parameters, content, 0); };
FunctionNode_sum.prototype = new AggregateNode("sum");
FunctionNode_sum.prototype.computeAggregate = function(start, end, pos, var_names, values) {
var value = this.startValue,
s = Math.round(start)|0,
e = Math.round(end)|0,
i;
for(i=s; i<=e; i++) {
values[pos] = i;
value += this.content.evaluate(var_names, values);
}
return value;
};
FunctionNode_sum.prototype.toLaTeX = function() {
var params = this.parameters;
return "\\sum_{n="+params[0].toLaTeX()+"}^{"+params[1].toLaTeX()+"} " + this.content.toLaTeX();
};
/**
* parameters:
* 0 = n_start value
* 1 = n_end value
*/
var FunctionNode_prod = function(parameters, content) { this.bindAll(parameters, content, 1); };
FunctionNode_prod.prototype = new AggregateNode("prod");
FunctionNode_prod.prototype.computeAggregate = function(start, end, pos, var_names, values) {
var value = this.startValue,
s = Math.round(start)|0,
e = Math.round(end)|0,
i;
for(i=s; i<=e; i++) {
values[pos] = i;
value *= this.content.evaluate(var_names, values);
}
return value;
};
FunctionNode_prod.prototype.toLaTeX = function() {
var params = this.parameters;
return "\\prod_{n="+params[0].toLaTeX()+"}^{"+params[1].toLaTeX()+"} " + this.content.toLaTeX();
};
/**
* A Newtonian take on computing a definite integral:
* compute the area under a function by adding rectangular areas.
*
* parameters:
* 0 = interval start value
* 1 = interval end value
* 2 = number of slices in this interval
* 3 = variable name (string) for which to evaluate the interval
*/
var FunctionNode_area = function(parameters, content) { this.bindAll(parameters, content, 0); };
FunctionNode_area.prototype = new AggregateNode("area");
FunctionNode_area.prototype.computeAggregate = function (s, e, pos, var_names, values) {
var params = this.parameters,
start = s,
end = e,
step = params[2].evaluate(),
slen = (end-start)/step,
varName = params[3].getParameters()[0],
area = this.startValue,
slice,
v;
for(pos=0; pos<var_names.length; pos++) {
if(var_names[pos] == varName) break;
}
// compute area by strip-rect-addition
for(v=start+slen/2; v<end; v+=slen) {
values[pos] = v;
slice = this.content.evaluate(var_names, values);
area += slen * Math.abs(slice);
}
return area;
};
FunctionNode_area.prototype.toLaTeX = function() {
var params = this.parameters;
return "\\int_{"+params[0].toLaTeX()+"}^{"+params[1].toLaTeX()+"} " + this.content.toLaTeX() + " d"+params[3].label;
};
// builder functions
var isAggregateNode = function(functor) {
if (functor == "sum") return true;
if (functor == "prod") return true;
if (functor == "area") return true;
return false; };
var getAggregateNode = function(functor, args, content) {
if (functor == "sum") return new FunctionNode_sum(args, content);
if (functor == "prod") return new FunctionNode_prod(args, content);
if (functor == "area") return new FunctionNode_area(args, content);
return false; };
/**
* scripts/MathFunction/dependencies/Tape.js
*/
/**
* Create a new tape based on a data string.
* In order to ensure we don't screw up Unicode
* strings, this splits the data into an array
* of String, emphatically NOT a char array.
*
* If stripWhitespace is true, all whitespace
* in the data will be removed. This can be
* useful for things like math functions.
*/
var Tape = function(data, stripWhiteSpace) {
stripWhiteSpace = stripWhiteSpace || false;
if(stripWhiteSpace) {
data = data.replace(/[ \t\n\s]/g,'');
}
this.data = data.split("");
this.length = data.length;
this.position = 0;
};
Tape.prototype = {
/**
* read the current character on the tape.
*/
read: function() {
return this.data[this.position];
},
/**
* checks whether there are more characters that can be read.
*/
more: function() {
return this.position<this.length;
},
/**
* advance the tape by one spot
*/
advance: function() {
if(this.position<this.length-1) {
this.position++;
}
},
/**
* read the next unread character on the tape.
*/
next: function() {
return this.data[this.position++];
},
/**
* look at the next character without forwarding the read head.
*/
peek: function() {
return this.data[this.position+1];
},
/**
* Recursively skip over a grouped expression.
* This is important for skipping over bracketed
* strings such as '', "", (), {}, [] and <> groups
*/
skipGroup: function(opener, closer) {
var buffer = "",
_tmp;
while(this.position<this.length) {
_tmp = this.data[this.position++];
if(_tmp == opener) {
buffer += this.skipGroup(opener, closer);
}
else if(_tmp == closer) {
break;
}
else {
buffer += _tmp;
}
}
return opener + buffer + closer;
},
/**
* Generate the String representation of this tape.
*/
toString: function() {
var s = join(this.data, '');
s = s.substring(0,this.position) + " " + this.data[this.position] + " " + s.substring(this.position+1);
return s;
}
};
/**
* scripts/MathFunction/dependencies/ArithmeticFragment.js
*/
/**
* An arithmetic fragment models a piece of a function.
*/
var ArithmeticFragment = function(fragment) {
this.setup(fragment);
};
// uid counter
ArithmeticFragment.afCount = 1;
// prototype
ArithmeticFragment.prototype = {
setup: function(fragment) {
this.uid = ArithmeticFragment.afCount++;
// only used for summation
this.sumarguments = [],
// As an object, there is either a simple string
// descriptor for this fragment, or a set of
// children describing the fragment as a compound.
this.fragment = fragment,
// array of ArithmeticFragment:
this.children = [],
// If this fragment represents a function,
// it will have a functor and a set of
// children.
this.functor = "";
// tells us whether to wrap our fragment
this.wrapped = false;
// tells us whether we're already expanded
this.expanded = false;
},
/**
* balanced parentheses?
*/
getBalance: function() {
var toks = this.fragment.split(""),
pCount =0,
i, last;
for(i=0, last=toks.length; i<last; i++) {
if(toks[i] == "(") pCount++;
if(toks[i] == ")") pCount--; }
return pCount;
},
// functor(...) fragment?
isFunctionWrapped: function(fragment) {
if(!fragment.match(/^\w+\(.+\)/)) return false;
fragment = fragment.replace(/^\w+/g,'');
return this.isParensWrapped(fragment);
},
// (...) fragment?
isParensWrapped: function(fragment) {
if(!fragment.match(/^\(.*\)$/)) return false;
var tokens = fragment.split(""),
groupCount = 0,
last, i;
for(i=0, last=tokens.length; i<last; i++) {
if(tokens[i] === "") continue;
if(tokens[i] === "(") groupCount++;
if(tokens[i] === ")") groupCount--;
if(groupCount===0 && i<last-1) return false;
}
return groupCount===0;
},
// does a char represent a mathematical operator?
isArithmeticOperator: function(t) {
return t=="+" || t=="-" || t=="*" || t=="/" || t=="^" || t=="!";
},
/**
* Expand this fragment, if possible
*/
expand: function() {
if(this.expanded) return;
var compound = false,
unwrapped = false;
// WAY TOO MANY [this.] ENTRIES HERE:
// is this a function? if so, unwrap it
if (this.isFunctionWrapped(this.fragment)) {
unwrapped = true;
this.functor = this.fragment.substring(0,this.fragment.indexOf("("));
this.fragment = this.fragment.replace(new RegExp("^"+this.functor),'');
}
if (this.isParensWrapped(this.fragment)) {
if(!unwrapped) { this.wrapped = true; }
unwrapped = true;
this.fragment = this.fragment.substring(1,this.fragment.length-1);
}
// is this a summation?
if(isAggregateNode(this.functor) && this.fragment.trim()!=="") {
var pos = this.fragment.indexOf(","),
capPos = this.fragment.indexOf("(");
if(capPos===-1) { capPos = this.fragment.length(); }
var arg = "";
while(pos>-1 && pos<capPos) {
arg = this.fragment.substring(0,pos);
this.fragment = this.fragment.replace(new RegExp("^"+arg+",",'g'),'');
capPos--;
this.sumarguments.push(arg);
pos = this.fragment.indexOf(",");
}
}
// expand the fragment
var tape = new Tape(this.fragment, true),
buffer = "",
token,
just_inserted = false;
while(tape.more()) {
token = tape.next();
// If we encounter an arithmetic operator, split up the fragment
if(this.isArithmeticOperator(token)) {
compound = true;
if (buffer.trim() !== "" || just_inserted) {
// content
if(buffer.trim() !== "") {
this.fragment = "";
this.children.push(new ArithmeticFragment(buffer)); }
// operator
if(token == "!") { this.children.push(new UnaryOperator(token)); }
else { this.children.push(new Operator(token)); }
buffer = "";
} else if(token === "-") {
this.children.push(new UnaryOperator("-"));
}
just_inserted = true;
}
// If we encounter a grouping token,
// skip over the group content.
else if (token === "(") {
buffer += tape.skipGroup("(",")");
}
// Otherwise, move token to buffer
else {
just_inserted = false;
buffer += token;
}
}
// If we have a non-empty buffer after expanding
// we need to create a "final" fragment.
if ((compound || unwrapped) && buffer!=="") {
this.children.push(new ArithmeticFragment(buffer));
compound = true;
}
// If we went from plain fragment to compound,
// make sure to expand all children.
if (compound) {
this.children.forEach(function(c) {
c.expand();
});
}
this.expanded = true;
},
/**
* form the function tree that maps to this fragment
*/
formFunctionTree: function() {
var finalNode,
nodes = [];
if(!this.expanded) { this.expand(); }
if(this.children.length>0) {
var i,
last = this.children.length;
// bottom-up conversion
for(i=0; i<last; i++) {
var af = this.children[i];
if(af instanceof UnaryOperator) {
nodes.push(getUnaryOperatorNode(af.operator));
}
else if(af instanceof Operator) {
nodes.push(getOperatorNode(af.operator));
}
else { nodes.push(af.formFunctionTree()); }
}
// assemble these nodes into a tree.
var rhs = false, lhs = false,
tn, right, left;
for(var s=6; s>=0; s--) {
for(i=nodes.length-1; i>=0; i--) {
tn = nodes[i];
if(tn.getStrength) {
if(tn.getStrength()==s) {
if (!tn.hasLeaves()) {
// right sibling
rhs = tn.hasRight();
right = (rhs ? false: nodes.splice(i+1,1)[0]);
// left sibling
lhs = tn.hasLeft();
left = (lhs ? false : nodes.splice(i-1,1)[0]);
// set node content
tn.setLeaves(left, right);
}
}
}
}
}
finalNode = (nodes.length>0 ? nodes[0] : tn);
}
// no children: simple content
else { finalNode = getSimpleNode(this.fragment); }
// if this is function-wrapped, wrap it.
if(this.functor) {
var aggregator = getAggregateNode(this.functor, this.sumarguments, finalNode);
finalNode = (aggregator ? aggregator : getFunctionNode(this.functor, finalNode));
}
// do we need to wrap?
if(this.wrapped) { finalNode = new WrapperNode(finalNode); }
return finalNode;
},
/**
* toString - always useful
*/
toString: function(pad) {
if(!pad) return this.toString(" ");
var s = "["+this.uid+"] ";
s = (this.functor ? this.functor+"[" : '');
if(this.children.length>0) {
var cstrings = [];
for(var i=0, last=this.children.length; i<last; i++) {
cstrings[i] = this.children[i].toString(pad+" ");
}
s += cstrings.join('');
}
else { s += this.fragment; }