-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathconstrain.js
7148 lines (6819 loc) · 246 KB
/
constrain.js
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
"use strict"
// Constrain: A package for creating animated figures in JavaScript canvases,
// similar to the sort of animated figure you would put into a slide
// presentation, or for web-based course notes.
//
// Author: Andrew Myers, 2019-2023
// github.com/andrewcmyers/constrain
var Constrain = function() {
// There is a set of Figure objects recorded in the array Figures. Each one
// is attached to a separate canvas.
//
const Figures = []
// Various switches and constants control the default appearance of figures.
const USE_BACKPROPAGATION = true,
CACHE_ALL_EVALUATIONS = true,
PROFILE_EVALUATIONS = false,
REPORT_EVALUATED_EXPRESSIONS = false,
COMPARE_GRADIENTS = false,
TINY = 1e-17
const DEBUG = false, DEBUG_GROUPS = false, DEBUG_CONSTRAINTS = false, REPORT_UNSOLVED_CONSTRAINTS = false,
CHECK_NAN = false, DEBUG_TWEENING = false
const REPORT_PERFORMANCE = false
const NUMBER = "number", FUNCTION = "function", OBJECT_STR = "object", STRING_STR = "string"
const Figure_defaults = {
ARROW_SIZE : 12,
FONT_SIZE : 12,
LINEWIDTH : 1,
TRIANGLE_SIZE : 10,
FRAMERATE : 60,
FONT_NAME : "sans-serif",
FONT_STYLE : "",
LINE_SPACING : 1.3,
SUPERSCRIPT_OFFSET : 0.44,
SUBSCRIPT_OFFSET : -0.16,
LINELABEL_INSET : null,
SCRIPTSIZE : 0.80,
LARGE_SPAN : 10000.0,
HYPHEN_COST : 100000,
CONNECTION_STYLE : 'magnet'
}
const UNCMIN_GRADIENT = 0, UNCMIN_BFGS = 1, UNCMIN_DFP = 2, UNCMIN_ADAM = 3, UNCMIN_LBFGS = 4
let algorithm = UNCMIN_BFGS
const CALLBACK_RETURNED_TRUE = "Callback returned true",
BAD_SEARCH_DIRECTION = "Search direction has Infinity or NaN",
BAD_GRADIENT = "Gradient has Infinity or NaN"
const ADAM_BETA1 = 0.9, ADAM_BETA2 = 0.999, ADAM_EPSILON = 1e-8
const RANDOM_GRADIENT_SCALING = 0.001
const SOLVE_TIME_ALPHA = 0.3
const TARGET_TWEEN_FRAMES = 4
const defaultMinimizationOptions = {
maxIterations : 1000,
overshoot : 0.1,
stepSize : 1,
LBFGS_M : 10,
}
const {gradient, dot, sub, add, tensor, div, sqrt, mul, transpose, all, isFinite, neg} = numeric
function wrongSizedInvHessian(nvars, invHessian) {
switch (algorithm) {
case UNCMIN_BFGS:
case UNCMIN_DFP: return nvars != invHessian.length
case UNCMIN_LBFGS: return nvars != invHessian.y_hist[0].length
default: return false
}
}
function seconds(T) {
return ((T / 1000) % 100).toLocaleString(undefined, {minimumFractionDigits:3, maximumFractionDigits:3})
}
// A Figure represents a possibly animated figure containing graphical objects
// whose position is solved for. A Figure is attached to a canvas and knows
// how to render itself. It has a set of associated Frames which can be stepped
// through.
//
// A Figure can have multiple frames that correspond to the state of the
// animation. Frames can have a positive duration, allowing smooth animation
// during the frame if constraints are phrased in terms of the time within the
// frame.
//
// A Figure has a set of Variables that can be adjusted to minimize an
// objective function generated by summing costs from various constraints.
//
// Expressions can be built out of Variables. Constraints are built using expressions.
// They have a cost that is supposed to be as small as possible (zero, if the constraint
// is fully satisfiable). The solver tries to minimize the total cost of all constraints.
//
// Associated with each figure is a set of Graphics that know how to
// render themselves based on associated Variables. When new graphical objects
// are created, their style is set to their figure's style by default, but can
// be changed later.
//
// Depending on which frame a figure is on, different variables are active and
// solved for. A figure can also have multiple stages, which are orthogonal to
// frames. Variables are solved for in stages, and the same stages are solved
// for each frame.
//
class Figure {
// Create a figure appearing in a canvas. 'canvas' should be either the
// canvas HTML element or, for convenience, its id attribute as a string
constructor(canvas) {
this.figure = this
if (typeof canvas == OBJECT_STR && canvas instanceof HTMLCanvasElement) {
this.canvas = canvas
this.name = canvas.id
} else if (typeof canvas == STRING_STR) {
const c = document.getElementById(canvas)
if (c) {
this.canvas = canvas = c
this.name = c.id
} else {
console.error('Could not find any canvas with id "' + canvas + '"')
return
}
} else if (typeof canvas == 'undefined' &&
document.getElementsByTagName('canvas').length == 1) {
this.canvas = canvas = document.getElementsByTagName('canvas')[0]
this.name = 'canvas'
} else {
console.error("new Figure() expects a canvas or a canvas id")
return
}
this.ctx = canvas.getContext("2d")
this.is_ready = true // whether figure content is marked as ready for rendering
this.is_started = false // whether a request for rendering has occurred
this.setupListeners()
this.initObjects()
this.time = 0
this.zoom = 1 // figure units per HTML pixel
this.zoomCheckInterval = 200 // how many ms between testing browser zoom
this.currentFrame = undefined // current frame object
this.frameRate = Figure_defaults.FRAMERATE
this.Frames = []
this.wrapFrames = false // does advancing from last frame go back to first
this.currentStage = 0
this.numStages = 1
this.substitutionEnabled = true
// default styles
this.style = new Context()
this.setFillStyle("white")
this.setStrokeStyle("black")
this.setTextStyle("black")
this.setFontName(Figure_defaults.FONT_NAME)
this.setFontStyle(Figure_defaults.FONT_STYLE)
this.setFontSize(Figure_defaults.FONT_SIZE)
this.setLineWidth(Figure_defaults.LINEWIDTH)
this.setLineSpacing(Figure_defaults.LINE_SPACING)
this.setLineLabelInset(Figure_defaults.LINELABEL_INSET)
this.setArrowSize(Figure_defaults.ARROW_SIZE)
this.setConnectionStyle(Figure_defaults.CONNECTION_STYLE)
this.setLineDash(null)
this.repeat = false
this.animatedSolving = false
this.solverCallbacks = []
this.minimizationOptions = {...defaultMinimizationOptions}
this.fadeColor = this.findFadeColor(canvas)
this.timeVar = new Variable(this, "time") // variable representing the current frame time
Figures.push(this)
if (canvas.style.padding && canvas.style.padding != "0px")
console.error("Canvas input will not work correctly with padding")
}
setupCanvas() {
const canvas = this.canvas, br = canvas.getBoundingClientRect(),
_width = br.width, _height = br.height
let scale
if (window.innerWidth && window.visualViewport) {
this.browserZoom = (window.innerWidth/window.visualViewport.width)
} else {
scale = 1
}
scale = this.browserZoom * (window.devicePixelRatio || 1) // canvas pixels per HTML "pixel"
this.scale = scale
this.width = _width
this.height = _height
this.canvas.width = _width * scale
this.canvas.height = _height * scale
this.ctx.setTransform(scale * this.zoom, 0, 0, scale * this.zoom, 0, 0)
if (this.browserZoom) {
setInterval(() => {
const newZoom = (window.innerWidth/window.visualViewport.width)
if (newZoom != this.browserZoom) {
this.browserZoom = newZoom
this.renderNeeded = true
this.delayedRender()
}
}, this.zoomCheckInterval)
}
}
findFadeColor(canvas) {
let elt = canvas, c
while (elt) {
c = window.getComputedStyle(canvas).backgroundColor
if (c != "rgba(0, 0, 0, 0)") break
elt = elt.parentNode
}
if (c == "rgba(0, 0, 0, 0)") return "#fff"
return c
}
toString() {
return "Figure"
}
// Return this figure. Useful in combination with `with`.
thisFigure() {
return this
}
setZoom(z) {
this.zoom = z || 1
}
setupListeners() {
const canvas = this.canvas
this.canvas.addEventListener('mousedown', e => {
const x = e.offsetX, y = e.offsetY
// alternatively: could use clientX/clientY with getBoundingClientRect
this.interactives.forEach(i => {
if (!i.mousedown(x, y, e)) return false
})
e.preventDefault()
e.stopPropagation()
return false
})
this.canvas.addEventListener('mouseup', e => {
const x = e.offsetX, y = e.offsetY
this.interactives.forEach(i => {
if (!i.mouseup(e)) return false
})
e.preventDefault()
e.stopPropagation()
return false
})
this.canvas.addEventListener('mousemove', e => {
if (!this.focused) return false
const x = e.offsetX, y = e.offsetY
return this.focused.mousemove(x, y, e)
})
this.canvas.addEventListener('dblclick', e => {
e.preventDefault()
e.stopPropagation()
return false
})
this.canvas.addEventListener('click', e => {
e.preventDefault()
e.stopPropagation()
return false
})
}
initObjects() {
this.Graphics = []
this.Constraints = []
this.Graphs = []
this.Variables = []
this.numVariables = 0
this.interactives = []
this.events = []
this.focused = null
this.renderNeeded = false
}
// Return the valuation to be used for solving
initialValuation(incremental) {
if (this.Variables.length != this.numVariables) {
console.error("oops " + this.numVariables + " " + this.Variables.length)
}
const result = new Array(this.activeVariables.length)
for (let i = 0; i < this.activeVariables.length; i++) {
const v = this.activeVariables[i]
if (v.hasOwnProperty('solutionValue')) {
if (!incremental && v.prevValue !== undefined) {
// predict next solution based on linear motion assumption
const motion = numeric.sub(v.solutionValue, v.prevValue)
if (isFinite(motion) && Math.abs(motion) < 10) {
result[i] = numeric.add(v.solutionValue, motion)
} else {
result[i] = v.solutionValue
}
} else {
result[i] = v.solutionValue
}
v.prevValue = v.solutionValue
} else if (v.hint != null) {
result[i] = v.hint
} else {
result[i] = 100
}
v.solutionValue = result[i]
}
return result
}
// Create a map from each variable to the set of constraints that mention it.
constraintsByVar() {
const constraintsByVar = new Map()
this.Constraints.forEach(c => {
if (c.active()) {
for (const v of c.variables()) {
const cons = constraintsByVar.get(v) || new Set()
cons.add(c)
constraintsByVar.set(v, cons)
}
}
})
return constraintsByVar
}
// Control whether substitution is used to solve for variables. It usually
// speeds up solving but by overconstraining related variables can make it
// harder to escape local minima.
enableSubstitution(b) {
if (b === undefined) b = true
this.substitutionEnabled = b
}
// Variables are solved either by minimization or by direct solution after
// minimization is complete. This function identifies which variables need
// to be solved to support the currently visible graphical objects in this
// stage (and component, if provided), and decides which way to solve them.
// It also determines which constraints need to be evaluated during
// minimization.
// Variables solved by minimization are assigned indices in the valuation
// array to each of the variables that are active in this stage (and
// component, if provided).
// Variables are solved directly when they are only used in a single
// constraint whose form admits direct solution. Closures that directly
// solve these variables are appended to this.postMinActions; these closures
// are ordered so that variables have already been solved.
// If the component is not specified, only computes this.stageVariables
// to be the variables that need to be solved across all components in the
// stage.
numberVariables(stage, component) {
let i = 0
const frame = this.currentFrame
if (DEBUG && DEBUG_CONSTRAINTS) {
console.log("-- Setting up solving for " + this.name +
", frame " + (frame ? frame.index : "none") + ", stage " + stage
+ (component ? (", component " + component) : " (all components)") + " --")
}
this.Variables.forEach(v => v.removeIndex())
this.Constraints.forEach(c => { delete c.directSolved })
const constraintsByVar = this.constraintsByVar()
const solvedVariables = new Set() // all variables to solve currently
const enabledConstraints = new Set() // relevant to current solve
const activeVariables = [] // to solve via minimization
const postMinActions = [] // solving actions to run after minimization
const directSolvedConstraints = new Set() // solved directly or by substitution
let substitutable = 0, directlySolved = 0
// Add this constraint, if not there already, to the
// set of enabled constraints, and check if each of its variables need
// to be solved, which may lead to enabling more constraints.
function enableConstraint(c) {
if (!enabledConstraints.has(c)) {
enabledConstraints.add(c)
c.variables().forEach(checkIfNeeded)
delete c.directSolved
}
}
// Check whether v needs to be solved for, and activate any
// constraints that mention it.
function checkIfNeeded(v) {
if (v.stage != stage) return
if (v.index !== undefined) return
if (v === v.figure.timeVar) return
if (component && v.component != component) return
if (solvedVariables.has(v)) return
solvedVariables.add(v)
const cons = constraintsByVar.get(v)
if (cons) cons.forEach(enableConstraint)
}
this.Graphics.forEach(g => {
if (g.active() && g.visible()) {
g.variables().forEach(v => {
checkIfNeeded(v)
})
}
})
if (!component) {
this.stageVariables = solvedVariables
if (DEBUG && DEBUG_CONSTRAINTS) {
console.log("Stage variables = ", this.stageVariables)
}
return solvedVariables
}
// Return a function that solves the equation e = e2 for the variable v,
// given two arguments: the value of e2, and a current valuation array.
function solveFor(v, e) {
if (e == v) {
return (v2, valuation) => v2
}
if (e instanceof Plus) {
const [e1, e2] = [e.e1, e.e2]
const solve1 = solveFor(v, e1)
if (solve1 && !exprVariables(e2).has(v)) { // e1 + e2 = sum <=> e1 = sum - e2
return (sum, valuation) => solve1(sum - evaluate(e2, valuation), valuation)
}
const solve2 = solveFor(v, e2)
if (solve2 && !exprVariables(e1).has(v)) { // e1 + e2 = sum <=> e2 = sum - e1
return (sum, valuation) => solve2(sum - evaluate(e1, valuation), valuation)
}
return null
} else if (e instanceof Minus) {
const [e1, e2] = [e.e1, e.e2]
const solve1 = solveFor(v, e1)
if (solve1 && !exprVariables(e2).has(v)) { // e1 - e2 = diff <=> e1 = diff + e2
return (diff, valuation) => solve1(diff + evaluate(e2, valuation), valuation)
}
const solve2 = solveFor(v, e2)
if (solve2 && !exprVariables(e1).has(v)) { // e1 - e2 = diff <=> e2 = e1 - diff
return (diff, valuation) => solve2(evaluate(e1, valuation) - diff, valuation)
}
return null
} else {
return null // can't solve
}
}
// If variable v is only in one constraint and can
// be solved from it, append solving code to postMinActions
// for v and (before that) for any directly solvable variables
// it depends on and return true. If we can't solve v directly,
// return false.
//
function tryDirectSolve(v) {
if (v.hasOwnProperty('directSolved')) return v.directSolved
if (v.solvePending) return false // prevent cycles in solution strategy
const s = constraintsByVar.get(v)
if (!s || s.size == 0) {
postMinActions.push(valuation => {
v.solutionValue = v.hasOwnProperty('hint') ? v.hint : 100
if (DEBUG_CONSTRAINTS) console.log("Trivially solving " + v + " <- " + v.solutionValue)
})
directlySolved++
v.directSolved = true // unconstrained: any value works!
return
}
if (s.size > 1) return false
v.solvePending = true
for (const c of s.keys()) {
if (c instanceof NearZero && c.expr instanceof Sq && c.expr.expr instanceof Minus && !c.directSolved) {
let e1 = c.expr.expr.e1, e2 = c.expr.expr.e2
let solve1 = solveFor(v, e1),
e2v = exprVariables(e2)
if (!solve1 || e2v.has(v)) { // try it the other way round
[e1, e2] = [e2, e1]
solve1 = solveFor(v, e1)
e2v = exprVariables(e2)
}
if (solve1 && !e2v.has(v)) {
for (const v2 of e2v) tryDirectSolve(v2)
if (c.directSolved) { // oops, used it up already
v.directSolved = false
v.solvePending = false
return false
}
postMinActions.push(valuation => {
v.solutionValue = 0
v.solutionValue = solve1(evaluate(e2, valuation), valuation)
if (DEBUG_CONSTRAINTS) console.log("Directly solving " + v + " <- " + v.solutionValue)
})
directlySolved++
v.directSolved = c
v.solvePending = false
directSolvedConstraints.add(c)
c.directSolved = v
return true
}
}
v.directSolved = false // can't solve directly
v.solvePending = false
return false
}
console.error("can't get here")
}
for (const v of solvedVariables) {
tryDirectSolve(v)
}
function simpleExpr(e) {
return (e instanceof Variable) || (typeof e == NUMBER) || (e instanceof Global)
}
function trySubstitution(v) {
const s = constraintsByVar.get(v)
for (const c of s.keys()) {
if (c instanceof NearZero && c.expr instanceof Sq && c.expr.expr instanceof Minus && c.cost >= 1) {
let e1 = c.expr.expr.e1, e2 = c.expr.expr.e2
const e1_simple = simpleExpr(e1),
e2_simple = simpleExpr(e2)
if (e1 == v && e2_simple || e2 == v && e1_simple) {
const substitution = (v == e1) ? e2 : e1
if (substitution instanceof Variable) {
if (substitution.directSolved) continue
if (v.toString() >= substitution.toString()) continue
}
v.substitution = substitution
directSolvedConstraints.add(c)
postMinActions.push(valuation => {
v.solutionValue = evaluate(substitution, valuation)
if (DEBUG_CONSTRAINTS) console.log("Solving by substitution " + v + " <- " + v.solutionValue)
})
substitutable++
if (DEBUG_CONSTRAINTS) console.log("Substitution: " + v + " <- " + v.substitution)
return
}
}
}
}
if (this.substitutionEnabled) {
for (const v of solvedVariables) {
if (!v.directSolved) trySubstitution(v)
}
}
// Assign a fresh index to variable v if it is not to be solved directly
function assignIndex(v) {
if (v.substitution && v.substitution.directSolved) {
console.error("Oops, using a direct solved variable")
}
if (v.directSolved || v.substitution) return
if (component && v.variableComponent() !== component) return
v.setIndex(i)
activeVariables.push(v)
i++
}
// assign indices to all variables that need to be solved and cannot be
// solved directly
for (const v of solvedVariables) {
assignIndex(v)
}
const activeConstraints = new Set() // to use in minimization
// create the set of constraints that minimization should try to minimize
for (const c of enabledConstraints) {
if (!directSolvedConstraints.has(c)) activeConstraints.add(c)
}
this.activeConstraints = activeConstraints
if (DEBUG) {
this.solvedVariables = solvedVariables
this.enabledConstraints = enabledConstraints
}
this.activeVariables = activeVariables
this.postMinActions = postMinActions
if (DEBUG) {
console.log("Stage " + stage + ", component " + component)
console.log(" Constraints solved by minimization: ", activeConstraints.size)
console.log(" Variables solved by minimization: ", activeVariables.length)
console.log(" Directly solved variables: ", directlySolved)
console.log(" Substituted variables: ", substitutable)
}
}
unnumberVariables() {
const vars = this.Variables, n = vars.length
for (let i = 0; i < n; i++) {
vars[i].removeIndex()
}
}
// Add one or more constraints that should be satisfied
// If an array is passed as an argument, each element is added
// as a constraint.
// A constraint should return a nonnegative cost
// Normally, constraints call this method themselves
addConstraints(...constraints) {
constraints.flat().forEach(c => {
if (!this.Constraints.includes(c)) this.Constraints.push(c)
})
delete this.components
}
removeConstraints(...constraints) {
constraints = constraints.flat()
this.Constraints = this.Constraints.filter(c => !constraints.includes(c))
delete this.components
}
totalCost(valuation) {
return this.costGrad(valuation, false)
}
// compute the gradient of the output cost at value 'valuation' with
// respect to all active expressions, including variables, using
// backpropagation. Two different backprop evaluations cannot happen
// at the same time, because partial results are stored in the expression
// objects themselves, in their bpDiff field.
//
// Requires that all variables have been numbered appropriately.
bpGrad(valuation, task) {
const n = valuation.length,
val = this.totalCost(valuation) // initalize node values
task.run(valuation)
const grad = new Array(n)
for (let i = 0; i < n; i++) {
const v = this.activeVariables[i]
if (v.bpTask !== task) {
// console.log("Variable did not have its gradient computed: " + v)
grad[i] = 0
} else {
grad[i] = v.bpDiff
if (CHECK_NAN) checkNaNResult(v.bpDiff)
}
}
if (COMPARE_GRADIENTS) {
let [cgVal, cgGrad] = this.costGrad(valuation, true)
for (let i = 0; i < valuation.length; i++) {
if (exceedsError(cgVal, val)) {
console.error("Difference between computed values exceeds error")
}
if (exceedsError(cgGrad[i], grad[i])) {
console.error("Difference between computed gradients exceeds error")
}
}
}
return [val, grad]
}
isActiveConstraint(con) {
if (!con.active()) return false
if (con.parent !== undefined) return this.isActiveConstraint(con.parent)
return true
}
setupBackPropagation(task) {
let n = 0
this.activeConstraints.forEach(con => {
n++
// console.log(" active constraint: " + con)
con.addToTask(task)
})
// console.log(`Created backpropagation task with ${task.exprs.length} expressions from ${n} active constraints`)
}
// Compute the total cost of the constraints, and the gradient of
// the cost wrt the currently active variables. This is done by
// symbolic differentiation.
costGrad(valuation, doGrad) {
let n = valuation.length, cost = 0, dcost = new Array(n).fill(0)
this.activeConstraints.forEach(con => {
if (con.directSolved) {
console.error("direct-solved constraint appearing in cost minimization", con)
}
const result = con.getCost(valuation, doGrad)
if (CHECK_NAN && checkNaNResult(result)) return
let c, dc
if (doGrad) {
[c, dc] = result
dcost = numeric.add(dcost, dc)
} else {
c = result
}
cost += c
})
if (!doGrad) {
return cost
} else {
return [cost, dcost]
}
}
// Recompute the components for a given figure stage
// Requires: this.stageVariables contains all the variables that need to be solved in
// this stage.
computeComponents(stage) {
if (DEBUG) console.log("Computing components for stage " + stage)
delete this.activeComponent
for (const v of this.stageVariables) {
if (v.stage != stage) {
console.error("Variable is in wrong stage")
}
delete v.component
}
this.Constraints.forEach(c => {
if (c.active())
c.variables().forEach(v1 => {
if (v1.stage != stage) return
const v1c = v1.variableComponent()
c.variables().forEach(v2 => {
if (v2.stage != stage) return
const v2c = v2.variableComponent()
if (v1c !== v2c) {
v1c.component = v2c
}
})
})
})
const components = []
for (const v of this.stageVariables) {
const c = v.variableComponent()
c.component = c
if (!components.includes(c)) components.push(c)
}
if (DEBUG_CONSTRAINTS) {
console.log(this.name +
(this.currentFrame ? " frame " + this.currentFrame.index : "") +
": stage " + stage + " contains " + this.stageVariables.size + " variables and " + components.length + " components: [" + components.join(", ") + "]")
for (const c of components) {
let s = "component " + c + ": "
for (const v of this.stageVariables) {
if (v.variableComponent() == c) s += (v + ' ')
}
console.log(s)
}
}
return components
}
// compute a valuation to solve constraints within tolerance tol
updateValuation(tol, incremental) {
let solution, figure = this
if (PROFILE_EVALUATIONS) evaluations = 0
if (!this.components) this.components = []
figure.timeVar.currentValue = figure.currentTime
this.invalidateCachedExprs([this.timeVar])
for (let stage = 0; stage < this.numStages; stage++) {
this.activeStage = stage
this.numberVariables(stage)
let components = this.components[stage]
if (!components) {
components = this.computeComponents(stage)
this.components[stage] = components
} // otherwise, reuse previously computed components
solution = [[], "No minimization needed"]
// console.log(`Stage ${stage}: ${components.length} components`)
for (const component of components) {
this.activeComponent = component
this.numberVariables(stage, component)
this.invalidateCachedExprs(this.stageVariables)
this.currentValuation = this.initialValuation(incremental)
if (DEBUG_CONSTRAINTS) {
console.log(`Solving component in stage ${stage}: ${this.activeVariables.length} minimized variables, ${this.activeConstraints.size} constraints, ${this.postMinActions.length} post-min actions`)
}
if (component.invHessian && wrongSizedInvHessian(this.currentValuation.length, component.invHessian)) {
delete component.invHessian
if (DEBUG) console.log("Discarding wrong-sized inverse Hessian")
}
solution = this.minimizeConstraintLoss(this.currentValuation, tol, component.invHessian)
if (solution[3]) this.totalIterations += solution[3]
if (!solution[1]) return false
component.invHessian = solution[2]
this.postMinActions.forEach(solver => solver(solution[0]))
if (PROFILE_EVALUATIONS) console.log(" evaluations = " + evaluations)
if (DEBUG_CONSTRAINTS || REPORT_UNSOLVED_CONSTRAINTS) {
for (const c of this.activeConstraints) {
if (c instanceof Loss) {
const loss = evaluate(c.expr, solution[0])
if (Math.abs(loss > 0.01)) {
if (c.cost >= 1) {
console.log("** Badly solved constraint " + c + ": loss = " + loss)
} else {
console.log(" Weak constraint " + c + ": loss = " + loss)
}
}
} else {
// console.error("huh?" + c)
}
}
}
}
}
if (PROFILE_EVALUATIONS) {
console.log("Total evaluations: " + evaluations)
if (REPORT_EVALUATED_EXPRESSIONS) {
const entries = []
for (const e of evaluationCounts.entries()) {
entries.push(e)
}
const sorted = entries.sort((a, b) => b[1] - a[1])
for (let i = 0; i < sorted.length; i++) {
console.log(" expr: " + sorted[i][0] + ", evaluations: " + sorted[i][1])
}
}
}
return true
}
recordUpdatedValuation(accuracy) {
this.totalIterations = 0
const solved = this.updateValuation(accuracy)
if (DEBUG_TWEENING) console.log("total iterations: " + this.totalIterations)
if (!solved) {
console.error("not solved??")
}
this.unnumberVariables()
return this.recordValuation(true)
}
// Create a new array holding the current values of all variables. If
// valuation is provided as an argument, it's the solver's current value;
// otherwise, the renderer's.
recordValuation(valuation) {
const vars = this.Variables,
n = vars.length,
result = new Array(n)
for (let i = 0; i < n; i++) {
if (valuation) {
result[i] = vars[i].solutionValue
} else {
result[i] = vars[i].renderValue
}
}
// console.log("recorded " + count + " variable values")
return result
}
// Set the render values of all variables using the valuation array
applyValuation(valuation) {
const vars = this.Variables
const n = vars.length
if (n != valuation.length) {
console.error("length mismatch")
}
for (let i = 0; i < n; i++) {
const v = valuation[i], variable = vars[i]
variable.removeIndex()
if (v !== undefined) {
if (variable.renderValue !== v) {
variable.renderValue = v
// console.log("invalidating cached exprs from renderValue " + variable)
this.invalidateCachedExprs([variable])
}
} else {
delete variable.renderValue
// console.log("invalidating cached exprs from undefined " + variable)
this.invalidateCachedExprs([variable])
}
}
}
invalidateCachedExprs(vars) {
for (const v of vars) {
for (const expr of v.dependents) {
if (expr.cachedResult) {
// console.log(" forgetting cached value of " + expr + " because of " + v)
expr.clearCache()
}
}
}
}
// Register a callback to be invoked at every solver step
registerCallback(cb) {
for (let i = 0; i < this.solverCallbacks.length; i++) {
if (this.solverCallbacks[i] == cb) return
}
this.solverCallbacks.push(cb)
}
// Unregister a callback. Either the callback object itself or
// its name may be supplied as an argument.
unregisterCallback(name) {
for (let i = 0; i < this.solverCallbacks.length; i++) {
if (this.solverCallbacks[i].name == name ||
this.solverCallbacks[i] === name) {
this.solverCallbacks = this.solverCallbacks.slice(0, i)
.concat(this.solverCallbacks.slice(i+1))
}
}
}
// Run the minimization-based solver. The parameter invHessian is optional, useful
// for incrementally solving from a previous solution.
minimizeConstraintLoss(valuation, tol, invHessian) {
let doGrad = true, fig = this
if (valuation === undefined) {
console.error("Need initial valuation")
}
if (valuation.length == 0) {
if (DEBUG) console.log(" No minimization needed")
return [valuation, "No minimization needed"]
}
const task = USE_BACKPROPAGATION ? new BackPropagation(this.activeVariables) : undefined
if (USE_BACKPROPAGATION) {
this.setupBackPropagation(task)
}
let result, callback, maxit = 1000
if (this.solverCallbacks.length > 0) {
callback = (it, x0, f0, g0, H1) => {
for (let i = 0; i < this.solverCallbacks.length; i++) {
if (this.solverCallbacks[i].call(it, x0, f0, g0, H1)) return true
}
return false
}
}
const minimizationOptions = this.minimizationOptions
const uncmin_options = {tol, maxit}
for (const key in minimizationOptions) uncmin_options[key] = minimizationOptions[key]
uncmin_options.Hinv = invHessian
if (doGrad) {
if (USE_BACKPROPAGATION) {
result = uncmin((v,d) => { return d ? fig.bpGrad(v, task) : fig.totalCost(v) },
valuation, callback, uncmin_options)
} else {
result = uncmin((v,d) => fig.costGrad(v,d), valuation, callback, uncmin_options)
}
} else {
result = numeric.uncmin(this.totalCost, valuation, undefined, uncmin_options)
}
if (DEBUG && result.message != CALLBACK_RETURNED_TRUE) console.log(result.iterations + " iterations, ", result.message)
return [result.solution, result.message != CALLBACK_RETURNED_TRUE, result.invHessian, result.iterations]
}
// Rendering
renderIfDirty(animating) {
if (this.currentFrame === undefined) {
console.log("current frame not defined yet, skipping render")
return
}
if (this.renderNeeded) {
this.renderFrame(animating)
this.renderNeeded = false
}
}
// Cause a render to happen (but not right away, so multiple render requests are
// collapsed into one.)
delayedRender() {
this.figure.renderNeeded = true
setTimeout(() => this.figure.renderIfDirty(false), 0)
}
// Render this figure for time this.renderTime (whic is a fraction in [0,1]
// measuring completion of current frame) Parameter animating is whether
// this is just an intermediate animation frame.
//
// Implementation notes:
// The figure maintains up to 3 valuations for solvable variables,
// in this.valuations.
// this.prevValuation : the solved valuation for a time before the current time
// this.nextValuation : the solved valuation for a time after the current time
// this.pendingValuation : the solved valuation for a time after the time for valuations[1].
// Once the current time goes beyond the time for nextValuation, that valuation becomes
// the prevValuation and pendingValuation becomes nextValuation.
// the properties this.prevTime, this.nextTime, and this.pendingTime are the values of time
// for each of these valuations. In addition, the property this.renderTime is the time
// at which rendering is supposed to happen, and what is rendering is an interpolation between
// prevValuation and nextValuation, which is in v.renderValue for all variables v
//
// cases:
// 1. no existing valuations: compute the valuation for current time and render it,
// and also start a solving job for the next time.
// 2. have previous valuation but not next valuation.
// solve in foreground for the valuation for the next time and render an interpolated value, and
// also start a solving job for the pending valuation, aborting any existing solving job.
// 3. have previous and next valuation but not pending valuation
// render an interpolated valuation and possibly start a solving job for the pending valuation
// 3a. No useful pending background solve, so start one, aborting any existing background solve.
// 3b. Pending background solve for a time in the future. Just interpolate and render.
// 4. have previous, next, and (good) pending valuation.
// Simply render interpolated frame.
renderFrame(animating, frameInterval, frameLength) {
const figure = this,
rT = figure.realTime,
t = figure.renderTime,
vars = this.Variables
function updateSolveTime() {
const dT = (new Date().getTime() - figure.startRealTime) - figure.realTime
figure.avgSolveTime = figure.avgSolveTime * (1 - SOLVE_TIME_ALPHA) + dT * SOLVE_TIME_ALPHA
if (DEBUG_TWEENING) {
console.log("Actual solve time = " + dT/1000)
console.log("New avg solve time = " + figure.avgSolveTime/1000)
}
}
function nextSolveTime(t) {
const result = Math.min(1, t + TARGET_TWEEN_FRAMES * figure.avgSolveTime/frameLength)
const eof = figure.startRealTime + frameLength
if (result > eof - frameInterval) result = 1
// console.log("next solve time for " + t + " is " + result)
return result
}
function interpolate(v0, v1, f) {
const n = v0.length,
result = new Array(n)
for (let i = 0; i < n; i++) {
const a = v0[i], b = v1[i]
result[i] = (a === undefined ? b :
b === undefined ? a :
a + (b - a) * f)
}
return result
}
function sameValuation(a, b) {
const n = a.length
for (let i = 0; i < n; i++) {
if (a[i] != b[i]) return false
}
return true
}
if (!animating) {