-
Notifications
You must be signed in to change notification settings - Fork 10
/
Calculators.ecs
274 lines (254 loc) · 14.2 KB
/
Calculators.ecs
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
#ecs; // enable support for @@symbols and :: operator
using System(, .Collections.Generic, .Linq, .Text);
using Loyc(, .Syntax, .Collections);
namespace LesGraphingCalc
{
using number = System.Double; // Change this line to make a calculator for a different data type
class CalcRange
{
// Generate a constructor and three public fields
public this(public number Lo, public number Hi, public int PxCount)
{
StepSize = (Hi - Lo) / Math.Max(PxCount - 1, 1);
}
public number StepSize;
public number ValueToPx(number value) => (value - Lo) / (Hi - Lo) * PxCount;
public number PxToValue(int px) => (number)px / PxCount * (Hi - Lo) + Lo;
public number PxToDelta(int px) => (number)px / PxCount * (Hi - Lo);
public CalcRange DraggedBy(int dPx) =>
new CalcRange(Lo - PxToDelta(dPx), Hi - PxToDelta(dPx), PxCount);
public CalcRange ZoomedBy(number ratio)
{
double mid = (Hi + Lo) / 2, halfSpan = (Hi - Lo) * ratio / 2;
return new CalcRange(mid - halfSpan, mid + halfSpan, PxCount);
}
}
// "alt class" generates an entire class hierarchy with base class CalculatorCore and
// read-only fields. Each "alternative" (derived class) is marked with the word "alt".
abstract alt class CalculatorCore
{
// Base class constructor and fields
alt this(LNode Expr, Dictionary<Symbol, LNode> Vars, CalcRange XRange);
public object Results { get; protected set; }
// Derived class for 2D graphing calculator
alt Calculator2D()
{
public override object Run()
{
var results = new number[XRange.PxCount];
number x = XRange.Lo;
Func<Symbol, number> lookup = null;
lookup = name => (name == @@x ? x : Eval(Vars[name], lookup));
for (int i = 0; i < results.Length; i++) {
results[i] = Eval(Expr, lookup);
x += XRange.StepSize;
}
return Results = results;
}
public override number? GetValueAt(int x, int _) =>
(uint)x < (uint)((number[])Results)::r.Length ? r[x] : (number?)null;
}
// Derived class for pseudo-3D and "equation" calculator
alt Calculator3D(CalcRange YRange)
{
public bool EquationMode { get; private set; }
public override object Run()
{
matchCode(Expr) {
// If we're given an equation like "x**2 = y**2", change it to
// "x**2 - y**2" and plot transitions in sign
case $L = $R, $L == $R:
EquationMode = true;
number[,] results = RunCore(quote($L - $R), true);
number[,] results2 = new number[results.GetLength(0) - 1, results.GetLength(1) - 1];
for (int i = 0; i < results.GetLength(0)-1; i++) {
for (int j = 0; j < results.GetLength(1)-1; j++) {
int sign = Math.Sign(results[i, j]);
if (sign == 0 || sign != Math.Sign(results[i+1, j]) ||
sign != Math.Sign(results[i, j+1]) ||
sign != Math.Sign(results[i+1, j+1]))
results2[i, j] = (number)1;
else
results2[i, j] = (number)0;
}
}
return Results = results2;
default:
EquationMode = Expr.ArgCount == 2 && Expr.Name.IsOneOf(
CodeSymbols.GT, CodeSymbols.LT, CodeSymbols.GE, CodeSymbols.LE, CodeSymbols.Neq, CodeSymbols.And, CodeSymbols.Or);
return Results = RunCore(Expr, false);
}
}
public number[,] RunCore(LNode expr, bool difMode)
{
var results = new number[YRange.PxCount + (difMode?1:0),
XRange.PxCount + (difMode?1:0)];
number x = XRange.Lo, startx = x;
number y = YRange.Lo;
if (difMode) {
x -= XRange.StepSize / 2;
y -= YRange.StepSize / 2;
}
Func<Symbol, number> lookup = null;
lookup = name => (name == @@x ? x : name == @@y ? y : Eval(Vars[name], lookup));
for (int yi = 0; yi < results.GetLength(0); yi++, x = startx) {
for (int xi = 0; xi < results.GetLength(1); xi++) {
results[yi, xi] = Eval(expr, lookup);
x += XRange.StepSize;
}
y += YRange.StepSize;
}
return results;
}
public override number? GetValueAt(int x, int y) =>
(uint)x < (uint)((number[,])Results)::r.GetLength(1) &&
(uint)y < (uint)r.GetLength(0) ? r[y, x] : (number?)null;
}
public abstract object Run();
public abstract number? GetValueAt(int x, int y);
public static CalculatorCore New(LNode expr, Dictionary<Symbol, LNode> vars, CalcRange xRange, CalcRange yRange)
{
// Find out if the expression uses the variable "y" (or is an equation with '=' or '==')
// As an (unnecessary) side effect, this throws if an unreferenced var is used
bool isEquation = expr.Calls(CodeSymbols.Assign, 2) || expr.Calls(CodeSymbols.Eq, 2), usesY = false;
if (!isEquation) {
LNode zero = LNode.Literal((double) 0);
Func<Symbol, double> lookup = null;
lookup = name => name == @@x || (usesY |= name == @@y) ? 0 : Eval(vars[name], lookup);
Eval(expr, lookup);
}
if (isEquation || usesY)
return new Calculator3D(expr, vars, xRange, yRange);
else
return new Calculator2D(expr, vars, xRange);
}
// Parse the list of variables provided in the GUI
public static Dictionary<Symbol, LNode> ParseVarList(IEnumerable<LNode> varList)
{
var vars = new Dictionary<Symbol, LNode>();
foreach (LNode assignment in varList) {
matchCode (assignment) {
case $var = $expr:
if (!var.IsId)
throw new ArgumentException("Left-hand side of '=' must be a variable name: {0}".Localized(var));
// For efficiency, try to evaluate the expression in advance
try { expr = LNode.Literal(Eval(expr, vars)); }
catch { } // it won't work if expression uses X or Y
vars.Add(var.Name, expr);
default:
throw new ArgumentException("Expected assignment expression: {0}".Localized(assignment));
};
}
return vars;
}
public static number Eval(LNode expr, Dictionary<Symbol, LNode> vars)
{
Func<Symbol, number> lookup = null;
lookup = name => Eval(vars[name], lookup);
return Eval(expr, lookup);
}
// Evaluates an expression
public static number Eval(LNode expr, Func<Symbol, number> lookup)
{
if (expr.IsLiteral) {
if (expr.Value is number)
return (number)expr.Value;
else
return (number)Convert.ToDouble(expr.Value);
}
if (expr.IsId)
return lookup(expr.Name);
// expr must be a function or operator
if (expr.ArgCount == 2) {
// Binary operators are the most common...
matchCode (expr) {
case $a + $b: return Eval(a, lookup) + Eval(b, lookup);
case $a * $b: return Eval(a, lookup) * Eval(b, lookup);
case $a - $b: return Eval(a, lookup) - Eval(b, lookup);
case $a / $b: return Eval(a, lookup) / Eval(b, lookup);
case $a % $b: return Eval(a, lookup) % Eval(b, lookup);
case $a ** $b: return (number) Math.Pow(Eval(a, lookup), Eval(b, lookup));
case $a >> $b: return (number) G.ShiftRight(Eval(a, lookup), (int)Eval(b, lookup));
case $a << $b: return (number) G.ShiftLeft(Eval(a, lookup), (int)Eval(b, lookup));
case $a > $b: return Eval(a, lookup) > Eval(b, lookup) ? (number)1 : (number)0;
case $a < $b: return Eval(a, lookup) < Eval(b, lookup) ? (number)1 : (number)0;
case $a >= $b: return Eval(a, lookup) >= Eval(b, lookup) ? (number)1 : (number)0;
case $a <= $b: return Eval(a, lookup) <= Eval(b, lookup) ? (number)1 : (number)0;
case $a == $b: return Eval(a, lookup) == Eval(b, lookup) ? (number)1 : (number)0;
case $a != $b: return Eval(a, lookup) != Eval(b, lookup) ? (number)1 : (number)0;
case $a & $b: return (number)((long)Eval(a, lookup) & (long)Eval(b, lookup));
case $a | $b: return (number)((long)Eval(a, lookup) | (long)Eval(b, lookup));
case $a ?? $b: return double.IsNaN(Eval(a, lookup)::a2) | double.IsInfinity(a2) ? Eval(b, lookup) : a2;
case $a && $b, @`'and`($a, $b): return Eval(a, lookup) != (number)0 ? Eval(b, lookup) : (number)0;
case $a || $b, @`'or`($a, $b): return Eval(a, lookup) == (number)0 ? Eval(b, lookup) : (number)1;
case @`'xor`($a, $b): return (Eval(a, lookup) != 0) != (Eval(b, lookup) != 0) ? (number)1 : (number)0;
case xor($a, $b): return (number)((long)Eval(a, lookup) ^ (long)Eval(b, lookup));
case min($a, $b): return Math.Min(Eval(a, lookup), Eval(b, lookup));
case max($a, $b): return Math.Max(Eval(a, lookup), Eval(b, lookup));
case mod($a, $b), @`'MOD`($a, $b): return Mod(Eval(a, lookup), Eval(b, lookup));
case atan($a, $b): return Math.Atan2(Eval(a, lookup), Eval(b, lookup));
case log($a, $b): return Math.Log(Eval(a, lookup), Eval(b, lookup));
case @`'in`($a, ($lo, $hi)): return G.IsInRange(Eval(a, lookup), Eval(lo, lookup), Eval(hi, lookup)) ? (number)1 : (number)0;
case @`'clamp`($a, ($lo, $hi)), clamp($a, $lo, $hi): return G.PutInRange(Eval(a, lookup), Eval(lo, lookup), Eval(hi, lookup));
case @`'P`($a, $b), P($a, $b): return P((int)Math.Round(Eval(a, lookup)), (int)Math.Round(Eval(b, lookup)));
case @`'C`($a, $b), C($a, $b): return C((ulong)Math.Round(Eval(a, lookup)), (ulong)Math.Round(Eval(b, lookup)));
}
}
// Other stuff
matchCode (expr) {
case -$a: return -Eval(a, lookup);
case +$a: return Math.Abs(Eval(a, lookup));
case !$a: return Eval(a, lookup) == 0 ? (number)1 : (number)0;
case ~$a: return (number)~(long)Eval(a, lookup);
// In LES, the conditional operator a?b:c is actually two separate binary
// operators named '? and ': ... so if we use C# syntax $c ? $a : $b here,
// it will NOT work. Note: @`'?` represents the identifier called '? in EC#
case @`'?`($c, @`':`($a, $b)):
return Eval(c, lookup) != (number)0 ? Eval(a, lookup) : Eval(b, lookup);
case square($a): return Eval(a, lookup)::n * n;
case sqrt($a): return Math.Sqrt(Eval(a, lookup));
case sin($a): return Math.Sin(Eval(a, lookup));
case cos($a): return Math.Cos(Eval(a, lookup));
case tan($a): return Math.Tan(Eval(a, lookup));
case asin($a): return Math.Asin(Eval(a, lookup));
case acos($a): return Math.Acos(Eval(a, lookup));
case atan($a): return Math.Atan(Eval(a, lookup));
case sec($a): return 1/Math.Cos(Eval(a, lookup));
case csc($a): return 1/Math.Sin(Eval(a, lookup));
case cot($a): return 1/Math.Tan(Eval(a, lookup));
case exp($a): return Math.Exp(Eval(a, lookup));
case ln($a): return Math.Log(Eval(a, lookup));
case log($a): return Math.Log10(Eval(a, lookup));
case ceil($a): return Math.Ceiling(Eval(a, lookup));
case floor($a): return Math.Floor(Eval(a, lookup));
case sign($a): return Math.Sign(Eval(a, lookup));
case abs($a): return Math.Abs(Eval(a, lookup));
case rnd(): return (number)_r.NextDouble();
case rnd($a): return (number)_r.Next((int)Eval(a, lookup));
case rnd($a, $b): return (number)_r.Next((int)Eval(a, lookup), (int)Eval(b, lookup));
case fact($a): return Factorial(Eval(a, lookup));
}
throw new ArgumentException("Expression not understood: {0}".Localized(expr));
}
static double Mod(double x, double y)
{
double m = x % y;
return m + (m < 0 ? y : 0);
}
static double Factorial(double n) =>
n <= 1 ? 1 : n * Factorial(n - 1);
static double P(int n, int k) =>
k <= 0 ? 1 : k > n ? 0 : n * P(n - 1, k - 1);
static double C(ulong n, ulong k) {
if (k > n) return 0;
k = Math.Min(k, n - k);
double result = 1;
for (ulong d = 1; d <= k; ++d) {
result *= n--;
result /= d;
}
return result;
}
static Random _r = new Random();
}
}