-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathJSDiffTest.java
More file actions
596 lines (510 loc) · 19 KB
/
Copy pathJSDiffTest.java
File metadata and controls
596 lines (510 loc) · 19 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
import javax.script.ScriptEngine;
import javax.script.ScriptEngineManager;
import javax.script.ScriptException;
import java.io.*;
import java.util.*;
import java.util.ArrayDeque;
public class JSDiffTest {
public static class IO {
public String stringResult;
public double[][][] table = new double[10][10][10];
public void print(String message) {
System.out.print(message);
}
public void println(String message) {
System.out.println(message);
}
}
private final ScriptEngineManager factory = new ScriptEngineManager();
public static void main(String[] args) throws ScriptException, IOException {
checkAssert();
System.out.println("Options:\n -easy -- easy version\n -verbose -- verbose output");
boolean verbose = false;
boolean easy = false;
for (String arg : args) {
switch (arg) {
case "-verbose":
verbose = true;
break;
case "-easy":
easy = true;
break;
default:
throw new AssertionError("Unknown option " + arg);
}
}
new JSDiffTest(verbose, easy).run();
}
private boolean verbose;
private boolean easy;
public JSDiffTest(boolean verbose, boolean easy) {
this.verbose = verbose;
this.easy = easy;
}
private void run() {
test("x");
test("y");
test("z");
test("10");
test("x y +");
test("x y -");
test("x y *");
test("x 5 /");
test("x sin");
test("x cos");
test("2 x * 3 -");
test("x x 2 - * x * 1 +");
int base = test;
while (test < TOTAL_TESTS) {
test(polish(randomExpression((test - base + 1) * 3)));
}
}
private final Random random = new Random(8924702402404781470L);
private DiffExpression randomExpression(int size) {
if (size <= 0) {
if (random.nextBoolean()) {
return new Const(random.nextInt(1000));
} else {
return VARIABLES[random.nextInt(VARIABLES.length)];
}
}
switch (random.nextInt(6)) {
case 0: return new Add(randomExpression(size / 2 - 1), randomExpression(size / 2));
case 1: return new Subtract(randomExpression(size / 2 - 1), randomExpression(size / 2));
case 2: return new Multiply(randomExpression(size / 2 - 1), randomExpression(size / 2));
case 3: return new Divide(randomExpression(size / 2 - 1), randomExpression(size / 2));
case 4: return new Sin(randomExpression(size - 1));
case 5: return new Cos(randomExpression(size - 1));
default: throw new AssertionError("");
}
}
private int test = 0;
private int TOTAL_TESTS = 30;
private void test(String s) {
test++;
if (easy) {
s = s.replaceAll("y|z", "x");
}
System.out.format("Test %d of %d: %s\n", test, TOTAL_TESTS, s);
final DiffExpression expression = parse(s);
testToPolish(expression);
if (!easy) {
testParseTabulate(expression);
}
testTabulate(expression);
testDiff(expression);
testDiff2(expression);
}
private void testTabulate(DiffExpression expression) {
part(" Testing evaluate(...)");
String script =
"var expr = " + expression(expression) + ";" +
"for (var x = 0; x < 10; x++) for (var y = 0; y < 10; y++) for (var z = 0; z < 10; z++)" +
"io.table[x][y][z] = expr.evaluate(x, y, z);";
checkEquals(expression, run(script).table);
}
private void testParseTabulate(DiffExpression expression) {
part(" Testing parse(expr).evaluate(...)");
String script =
"var expr = parse('" + polish(expression) + "');" +
"for (var x = 0; x < 10; x++) for (var y = 0; y < 10; y++) for (var z = 0; z < 10; z++)" +
"io.table[x][y][z] = expr.evaluate(x, y, z);";
checkEquals(expression, run(script).table);
}
private void part(String message) {
if (verbose) {
System.out.println(message);
}
}
private static void checkEquals(DiffExpression expected, double[][][] actual) {
for (int x = 0; x < 10; x++) {
for (int y = 0; y < 10; y++) {
for (int z = 0; z < 10; z++) {
double e = expected.evaluate(x, y, z);
double a = actual[x][y][z];
if (!isEqual(e, a)) {
throw new AssertionError(String.format("x = %d, y = %d, z = %d: expected %f, actual %f", x, y, z, e, a));
}
}
}
}
}
private void testToPolish(DiffExpression expression) {
part(" Testing toString()");
String script = "io.stringResult = (" + expression(expression) + ").toString()";
checkEquals(expression, parse(run(script).stringResult));
}
private void testDiff(DiffExpression expression) {
for (String var : VARS) {
DiffExpression diff = expression.diff(var);
part(" Testing diff('" + var + "').toString()");
String toStringScript = "io.stringResult = (" + expression(expression) + ").diff('" + var + "').toString()";
checkEquals(diff, parse(run(toStringScript).stringResult));
part(" Testing diff('" + var + "').evaluate(...)");
String script =
"var expr = " + expression(expression) + ".diff('" + var + "');" +
"for (var x = 0; x < 10; x++) for (var y = 0; y < 10; y++) for (var z = 0; z < 10; z++)" +
"io.table[x][y][z] = expr.evaluate(x, y, z);";
checkEquals(diff, run(script).table);
if (easy) {
break;
}
}
}
private void testDiff2(DiffExpression expression) {
for (String var1 : VARS) {
for (String var2 : VARS) {
DiffExpression diff = expression.diff(var1).diff(var2);
part(" Testing diff('" + var1 + "').diff('" + var2 + "').toString()");
String toStringScript = "io.stringResult = (" + expression(expression) + ").diff('" + var1 + "').diff('" + var2 + "').toString()";
checkEquals(diff, parse(run(toStringScript).stringResult));
if (easy) {
break;
}
}
if (easy) {
break;
}
}
}
private IO run(String script) {
ScriptEngine engine = factory.getEngineByName("JavaScript");
final IO io = new IO();
engine.put("io", io);
try {
engine.eval(
"println = function(message) { io.println(message); };" +
"print = function(message) { io.print (message); };"
);
engine.eval(new InputStreamReader(new FileInputStream("jsdiff.js"), "UTF-8"));
engine.eval(script);
} catch (Exception e) {
throw new AssertionError(e);
}
return io;
}
private static void checkEquals(DiffExpression expected, DiffExpression actual) {
for (int x = 0; x < 10; x++) {
for (int y = 0; y < 10; y++) {
for (int z = 0; z < 10; z++) {
double e = expected.evaluate(x, y, z);
double a = actual.evaluate(x, y, z);
if (!isEqual(e, a)) {
throw new AssertionError(String.format("x = %d, y = %d, z = %d: expected %f, actual %f", x, y, z, e, a));
}
}
}
}
}
private static final double EPS = 1e-5;
private static boolean isEqual(double expected, double actual) {
return Double.isNaN(expected) && Double.isNaN(actual)
|| expected == actual
|| Math.abs(expected - actual) < EPS
|| Math.abs(expected) >= 1 && Math.abs(expected - actual) / expected < EPS;
}
private static void checkAssert() {
boolean assertsEnabled = false;
assert assertsEnabled = true;
if (!assertsEnabled) {
throw new AssertionError("You should enable assertions by running 'java -ea JSDiffTest'");
}
}
private static String polish(DiffExpression expression) {
return expression.polish(new StringBuilder()).toString().trim();
}
private static String expression(DiffExpression expression) {
return expression.expression(new StringBuilder()).toString().trim();
}
private final static Variable X = new Variable("x");
private final static Variable Y = new Variable("y");
private final static Variable Z = new Variable("z");
private final static String[] VARS = {"x", "y", "z"};
private final static Variable[] VARIABLES = {X, Y, Z};
private static DiffExpression parse(String s) {
StringTokenizer tokenizer = new StringTokenizer(s);
final Deque<DiffExpression> stack = new ArrayDeque<>();
try {
while (tokenizer.hasMoreTokens()) {
final String token = tokenizer.nextToken();
if ('0' <= token.charAt(0) && token.charAt(0) <= '9') {
try {
stack.addLast(new Const(Double.valueOf(token)));
} catch (NumberFormatException e) {
throw new AssertionError("Invalid number " + token);
}
} else {
DiffExpression p;
switch (token) {
case "x":
stack.addLast(X);
break;
case "y":
stack.addLast(Y);
break;
case "z":
stack.addLast(Z);
break;
case "+":
p = stack.removeLast();
stack.addLast(new Add(stack.removeLast(), p));
break;
case "-":
p = stack.removeLast();
stack.addLast(new Subtract(stack.removeLast(), p));
break;
case "*":
p = stack.removeLast();
stack.addLast(new Multiply(stack.removeLast(), p));
break;
case "/":
p = stack.removeLast();
stack.addLast(new Divide(stack.removeLast(), p));
break;
case "sin":
stack.addLast(new Sin(stack.removeLast()));
break;
case "cos":
stack.addLast(new Cos(stack.removeLast()));
break;
default:
throw new AssertionError("Invalid token " + token);
}
}
}
} catch (NoSuchElementException e) {
throw new AssertionError("Invalid expression " + s);
}
assert stack.size() == 1 : "Invalid expression " + s;
return stack.getFirst();
}
interface DiffExpression {
String name();
String symbol();
double evaluate(double x, double y, double z);
DiffExpression diff(String variable);
StringBuilder polish(StringBuilder sb);
StringBuilder expression(StringBuilder sb);
}
static final Const ZERO = new Const(0);
static final Const ONE = new Const(1);
static abstract class NullaryOperation implements DiffExpression {
@Override
public StringBuilder polish(StringBuilder sb) {
return sb.append(symbol()).append(" ");
}
@Override
public StringBuilder expression(StringBuilder sb) {
return sb.append(name());
}
}
static class Const extends NullaryOperation {
private final double value;
Const(double value) {
this.value = value;
}
@Override
public double evaluate(double x, double y, double z) {
return value;
}
@Override
public DiffExpression diff(String variable) {
return ZERO;
}
@Override
public String name() {
return "new Const(" + value + ")";
}
@Override
public String symbol() {
return String.valueOf(value);
}
}
static class Variable extends NullaryOperation {
private final String name;
Variable(String name) {
this.name = name;
evaluate(0, 0, 0);
}
@Override
public double evaluate(double x, double y, double z) {
switch (name) {
case "x": return x;
case "y": return y;
case "z": return z;
default: throw new AssertionError("Unknown variable " + name);
}
}
@Override
public DiffExpression diff(String variable) {
return name.equals(variable) ? ONE : ZERO;
}
@Override
public String name() {
return "new Variable('" + name + "')";
}
@Override
public String symbol() {
return name;
}
}
static abstract class BinaryOperation implements DiffExpression {
private final DiffExpression op1;
private final DiffExpression op2;
protected BinaryOperation(DiffExpression op1, DiffExpression op2) {
this.op1 = op1;
this.op2 = op2;
}
@Override
public double evaluate(double x, double y, double z) {
return evaluate(op1.evaluate(x, y, z), op2.evaluate(x, y, z));
}
protected abstract double evaluate(double a, double b);
@Override
public DiffExpression diff(String variable) {
return diff(op1, op1.diff(variable), op2, op2.diff(variable));
}
protected abstract DiffExpression diff(DiffExpression a, DiffExpression da, DiffExpression b, DiffExpression db);
@Override
public final String name() {
return getClass().getSimpleName();
}
@Override
public StringBuilder polish(StringBuilder sb) {
return op2.polish(op1.polish(sb)).append(symbol()).append(" ");
}
@Override
public StringBuilder expression(StringBuilder sb) {
return op2.expression(op1.expression(sb.append("new ").append(name()).append("(")).append(", ")).append(")");
}
}
static class Add extends BinaryOperation {
public Add(DiffExpression op1, DiffExpression op2) {
super(op1, op2);
}
@Override
protected double evaluate(double a, double b) {
return a + b;
}
@Override
protected DiffExpression diff(DiffExpression a, DiffExpression da, DiffExpression b, DiffExpression db) {
return new Add(da, db);
}
@Override
public String symbol() {
return "+";
}
}
static class Subtract extends BinaryOperation {
Subtract(DiffExpression op1, DiffExpression op2) {
super(op1, op2);
}
@Override
protected double evaluate(double a, double b) {
return a - b;
}
@Override
protected DiffExpression diff(DiffExpression a, DiffExpression da, DiffExpression b, DiffExpression db) {
return new Subtract(da, db);
}
@Override
public String symbol() {
return "-";
}
}
static class Multiply extends BinaryOperation {
Multiply(DiffExpression op1, DiffExpression op2) {
super(op1, op2);
}
@Override
protected double evaluate(double a, double b) {
return a * b;
}
@Override
protected DiffExpression diff(DiffExpression a, DiffExpression da, DiffExpression b, DiffExpression db) {
return new Add(new Multiply(a, db), new Multiply(b, da));
}
@Override
public String symbol() {
return "*";
}
}
static class Divide extends BinaryOperation {
Divide(DiffExpression op1, DiffExpression op2) {
super(op1, op2);
}
@Override
protected double evaluate(double a, double b) {
return a / b;
}
@Override
protected DiffExpression diff(DiffExpression a, DiffExpression da, DiffExpression b, DiffExpression db) {
return new Divide(
new Subtract(new Multiply(da, b), new Multiply(a, db)),
new Multiply(b, b)
);
}
@Override
public String symbol() {
return "/";
}
}
static abstract class UnaryOperation implements DiffExpression {
private final DiffExpression op;
protected UnaryOperation(DiffExpression op) {
this.op = op;
}
@Override
public double evaluate(double x, double y, double z) {
return evaluate(op.evaluate(x, y, z));
}
protected abstract double evaluate(double a);
@Override
public DiffExpression diff(String variable) {
return diff(op, op.diff(variable));
}
protected abstract DiffExpression diff(DiffExpression a, DiffExpression da);
@Override
public String name() {
return getClass().getSimpleName();
}
@Override
public String symbol() {
return name().toLowerCase();
}
@Override
public StringBuilder polish(StringBuilder sb) {
return op.polish(sb).append(symbol()).append(" ");
}
@Override
public StringBuilder expression(StringBuilder sb) {
return op.expression(sb.append("new ").append(name()).append("(")).append(")");
}
}
static class Sin extends UnaryOperation {
Sin(DiffExpression op) {
super(op);
}
@Override
protected double evaluate(double a) {
return Math.sin(a);
}
@Override
protected DiffExpression diff(DiffExpression a, DiffExpression da) {
return new Multiply(new Cos(a), da);
}
}
static class Cos extends UnaryOperation {
Cos(DiffExpression op) {
super(op);
}
@Override
protected double evaluate(double a) {
return Math.cos(a);
}
@Override
protected DiffExpression diff(DiffExpression a, DiffExpression da) {
return new Subtract(ZERO, new Multiply(new Sin(a), da));
}
}
}