forked from 3b1b/manim
-
Notifications
You must be signed in to change notification settings - Fork 0
/
WindingNumber.py
2885 lines (2332 loc) · 100 KB
/
WindingNumber.py
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
from manimlib.imports import *
import warnings
warnings.warn("""
Warning: This file makes use of
ContinualAnimation, which has since
been deprecated
""")
import time
import mpmath
mpmath.mp.dps = 7
# Warning, this file uses ContinualChangingDecimal,
# which has since been been deprecated. Use a mobject
# updater instead
# Useful constants to play around with
UL = UP + LEFT
UR = UP + RIGHT
DL = DOWN + LEFT
DR = DOWN + RIGHT
standard_rect = np.array([UL, UR, DR, DL])
# Used in EquationSolver2d, and a few other places
border_stroke_width = 10
# Used for clockwise circling in some scenes
cw_circle = Circle(color = WHITE).stretch(-1, 0)
# Used when walker animations are on black backgrounds, in EquationSolver2d and PiWalker
WALKER_LIGHT_COLOR = DARK_GREY
ODOMETER_RADIUS = 1.5
ODOMETER_STROKE_WIDTH = 20
# TODO/WARNING: There's a lot of refactoring and cleanup to be done in this code,
# (and it will be done, but first I'll figure out what I'm doing with all this...)
# -SR
# This turns counterclockwise revs into their color. Beware, we use CCW angles
# in all display code, but generally think in this video's script in terms of
# CW angles
def rev_to_rgba(alpha):
alpha = (0.5 - alpha) % 1 # For convenience, to go CW from red on left instead of CCW from right
# 0 is red, 1/6 is yellow, 1/3 is green, 2/3 is blue
hue_list = [0, 0.5/6.0, 1/6.0, 1.1/6.0, 2/6.0, 3/6.0, 4/6.0, 5/6.0]
num_hues = len(hue_list)
start_index = int(np.floor(num_hues * alpha)) % num_hues
end_index = (start_index + 1) % num_hues
beta = (alpha % (1.0/num_hues)) * num_hues
start_hue = hue_list[start_index]
end_hue = hue_list[end_index]
if end_hue < start_hue:
end_hue = end_hue + 1
hue = interpolate(start_hue, end_hue, beta)
return color_to_rgba(Color(hue = hue, saturation = 1, luminance = 0.5))
# alpha = alpha % 1
# colors = colorslist
# num_colors = len(colors)
# beta = (alpha % (1.0/num_colors)) * num_colors
# start_index = int(np.floor(num_colors * alpha)) % num_colors
# end_index = (start_index + 1) % num_colors
# return interpolate(colors[start_index], colors[end_index], beta)
def rev_to_color(alpha):
return rgba_to_color(rev_to_rgba(alpha))
def point_to_rev(xxx_todo_changeme6, allow_origin = False):
# Warning: np.arctan2 would happily discontinuously returns the value 0 for (0, 0), due to
# design choices in the underlying atan2 library call, but for our purposes, this is
# illegitimate, and all winding number calculations must be set up to avoid this
(x, y) = xxx_todo_changeme6
if not(allow_origin) and (x, y) == (0, 0):
print("Error! Angle of (0, 0) computed!")
return
return fdiv(np.arctan2(y, x), TAU)
def point_to_size(xxx_todo_changeme7):
(x, y) = xxx_todo_changeme7
return np.sqrt(x**2 + y**2)
# rescaled_size goes from 0 to 1 as size goes from 0 to infinity
# The exact method is arbitrarily chosen to make pleasing color map
# brightness levels
def point_to_rescaled_size(p):
base_size = point_to_size(p)
return np.sqrt(fdiv(base_size, base_size + 1))
def point_to_rgba(point):
rev = point_to_rev(point, allow_origin = True)
rgba = rev_to_rgba(rev)
rescaled_size = point_to_rescaled_size(point)
return rgba * [rescaled_size, rescaled_size, rescaled_size, 1] # Preserve alpha
positive_color = rev_to_color(0)
negative_color = rev_to_color(0.5)
neutral_color = rev_to_color(0.25)
class EquationSolver1d(GraphScene, ZoomedScene):
CONFIG = {
"camera_config" :
{
"use_z_coordinate_for_display_order": True,
},
"func" : lambda x : x,
"targetX" : 0,
"targetY" : 0,
"initial_lower_x" : 0,
"initial_upper_x" : 10,
"num_iterations" : 10,
"iteration_at_which_to_start_zoom" : None,
"graph_label" : None,
"show_target_line" : True,
"base_line_y" : 0, # The y coordinate at which to draw our x guesses
"show_y_as_deviation" : False, # Displays y-values as deviations from target,
}
def drawGraph(self):
self.setup_axes()
self.graph = self.get_graph(self.func)
self.add(self.graph)
if self.graph_label != None:
curve_label = self.get_graph_label(self.graph, self.graph_label,
x_val = 4, direction = LEFT)
curve_label.shift(LEFT)
self.add(curve_label)
if self.show_target_line:
target_line_object = DashedLine(
self.coords_to_point(self.x_min, self.targetY),
self.coords_to_point(self.x_max, self.targetY),
dash_length = 0.1)
self.add(target_line_object)
target_label_num = 0 if self.show_y_as_deviation else self.targetY
target_line_label = TexMobject("y = " + str(target_label_num))
target_line_label.next_to(target_line_object.get_left(), UP + RIGHT)
self.add(target_line_label)
self.wait() # Give us time to appreciate the graph
if self.show_target_line:
self.play(FadeOut(target_line_label)) # Reduce clutter
print("For reference, graphOrigin: ", self.coords_to_point(0, 0))
print("targetYPoint: ", self.coords_to_point(0, self.targetY))
# This is a mess right now (first major animation coded),
# but it works; can be refactored later or never
def solveEquation(self):
# Under special conditions, used in GuaranteedZeroScene, we let the
# "lower" guesses actually be too high, or vice versa, and color
# everything accordingly
def color_by_comparison(val, ref):
if val > ref:
return positive_color
elif val < ref:
return negative_color
else:
return neutral_color
lower_color = color_by_comparison(self.func(self.initial_lower_x), self.targetY)
upper_color = color_by_comparison(self.func(self.initial_upper_x), self.targetY)
if self.show_y_as_deviation:
y_bias = -self.targetY
else:
y_bias = 0
startBrace = TexMobject("|", stroke_width = 10) #TexMobject("[") # Not using [ and ] because they end up crossing over
startBrace.set_color(lower_color)
endBrace = startBrace.copy().stretch(-1, 0)
endBrace.set_color(upper_color)
genericBraces = Group(startBrace, endBrace)
#genericBraces.scale(1.5)
leftBrace = startBrace.copy()
rightBrace = endBrace.copy()
xBraces = Group(leftBrace, rightBrace)
downBrace = startBrace.copy()
upBrace = endBrace.copy()
yBraces = Group(downBrace, upBrace)
yBraces.rotate(TAU/4)
lowerX = self.initial_lower_x
lowerY = self.func(lowerX)
upperX = self.initial_upper_x
upperY = self.func(upperX)
leftBrace.move_to(self.coords_to_point(lowerX, self.base_line_y)) #, aligned_edge = RIGHT)
leftBraceLabel = DecimalNumber(lowerX)
leftBraceLabel.next_to(leftBrace, DOWN + LEFT, buff = SMALL_BUFF)
leftBraceLabelAnimation = ContinualChangingDecimal(leftBraceLabel,
lambda alpha : self.point_to_coords(leftBrace.get_center())[0],
tracked_mobject = leftBrace)
rightBrace.move_to(self.coords_to_point(upperX, self.base_line_y)) #, aligned_edge = LEFT)
rightBraceLabel = DecimalNumber(upperX)
rightBraceLabel.next_to(rightBrace, DOWN + RIGHT, buff = SMALL_BUFF)
rightBraceLabelAnimation = ContinualChangingDecimal(rightBraceLabel,
lambda alpha : self.point_to_coords(rightBrace.get_center())[0],
tracked_mobject = rightBrace)
downBrace.move_to(self.coords_to_point(0, lowerY)) #, aligned_edge = UP)
downBraceLabel = DecimalNumber(lowerY)
downBraceLabel.next_to(downBrace, LEFT + DOWN, buff = SMALL_BUFF)
downBraceLabelAnimation = ContinualChangingDecimal(downBraceLabel,
lambda alpha : self.point_to_coords(downBrace.get_center())[1] + y_bias,
tracked_mobject = downBrace)
upBrace.move_to(self.coords_to_point(0, upperY)) #, aligned_edge = DOWN)
upBraceLabel = DecimalNumber(upperY)
upBraceLabel.next_to(upBrace, LEFT + UP, buff = SMALL_BUFF)
upBraceLabelAnimation = ContinualChangingDecimal(upBraceLabel,
lambda alpha : self.point_to_coords(upBrace.get_center())[1] + y_bias,
tracked_mobject = upBrace)
lowerDotPoint = self.input_to_graph_point(lowerX, self.graph)
lowerDotXPoint = self.coords_to_point(lowerX, self.base_line_y)
lowerDotYPoint = self.coords_to_point(0, self.func(lowerX))
lowerDot = Dot(lowerDotPoint + OUT, color = lower_color)
upperDotPoint = self.input_to_graph_point(upperX, self.graph)
upperDot = Dot(upperDotPoint + OUT, color = upper_color)
upperDotXPoint = self.coords_to_point(upperX, self.base_line_y)
upperDotYPoint = self.coords_to_point(0, self.func(upperX))
lowerXLine = Line(lowerDotXPoint, lowerDotPoint, color = lower_color)
upperXLine = Line(upperDotXPoint, upperDotPoint, color = upper_color)
lowerYLine = Line(lowerDotPoint, lowerDotYPoint, color = lower_color)
upperYLine = Line(upperDotPoint, upperDotYPoint, color = upper_color)
x_guess_line = Line(lowerDotXPoint, upperDotXPoint, color = WHITE, stroke_width = 10)
lowerGroup = Group(
lowerDot,
leftBrace, downBrace,
lowerXLine, lowerYLine,
x_guess_line
)
upperGroup = Group(
upperDot,
rightBrace, upBrace,
upperXLine, upperYLine,
x_guess_line
)
initialLowerXDot = Dot(lowerDotXPoint + OUT, color = lower_color)
initialUpperXDot = Dot(upperDotXPoint + OUT, color = upper_color)
initialLowerYDot = Dot(lowerDotYPoint + OUT, color = lower_color)
initialUpperYDot = Dot(upperDotYPoint + OUT, color = upper_color)
# All the initial adds and ShowCreations are here now:
self.play(FadeIn(initialLowerXDot), FadeIn(leftBrace), FadeIn(leftBraceLabel))
self.add_foreground_mobjects(initialLowerXDot, leftBrace)
self.add(leftBraceLabelAnimation)
self.play(ShowCreation(lowerXLine))
self.add_foreground_mobject(lowerDot)
self.play(ShowCreation(lowerYLine))
self.play(FadeIn(initialLowerYDot), FadeIn(downBrace), FadeIn(downBraceLabel))
self.add_foreground_mobjects(initialLowerYDot, downBrace)
self.add(downBraceLabelAnimation)
self.wait()
self.play(FadeIn(initialUpperXDot), FadeIn(rightBrace), FadeIn(rightBraceLabel))
self.add_foreground_mobjects(initialUpperXDot, rightBrace)
self.add(rightBraceLabelAnimation)
self.play(ShowCreation(upperXLine))
self.add_foreground_mobject(upperDot)
self.play(ShowCreation(upperYLine))
self.play(FadeIn(initialUpperYDot), FadeIn(upBrace), FadeIn(upBraceLabel))
self.add_foreground_mobjects(initialUpperYDot, upBrace)
self.add(upBraceLabelAnimation)
self.wait()
self.play(FadeIn(x_guess_line))
self.wait()
for i in range(self.num_iterations):
if i == self.iteration_at_which_to_start_zoom:
self.activate_zooming()
self.little_rectangle.move_to(
self.coords_to_point(self.targetX, self.targetY))
inverseZoomFactor = 1/float(self.zoom_factor)
self.play(
lowerDot.scale_in_place, inverseZoomFactor,
upperDot.scale_in_place, inverseZoomFactor)
def makeUpdater(xAtStart, fixed_guess_x):
def updater(group, alpha):
dot, xBrace, yBrace, xLine, yLine, guess_line = group
newX = interpolate(xAtStart, midX, alpha)
newY = self.func(newX)
graphPoint = self.input_to_graph_point(newX,
self.graph)
dot.move_to(graphPoint)
xAxisPoint = self.coords_to_point(newX, self.base_line_y)
xBrace.move_to(xAxisPoint)
yAxisPoint = self.coords_to_point(0, newY)
yBrace.move_to(yAxisPoint)
xLine.put_start_and_end_on(xAxisPoint, graphPoint)
yLine.put_start_and_end_on(yAxisPoint, graphPoint)
fixed_guess_point = self.coords_to_point(fixed_guess_x, self.base_line_y)
guess_line.put_start_and_end_on(xAxisPoint, fixed_guess_point)
return group
return updater
midX = (lowerX + upperX)/float(2)
midY = self.func(midX)
# If we run with an interval whose endpoints start off with same sign,
# then nothing after this branching can be trusted to do anything reasonable
# in terms of picking branches or assigning colors
in_negative_branch = midY < self.targetY
sign_color = negative_color if in_negative_branch else positive_color
midCoords = self.coords_to_point(midX, midY)
midColor = neutral_color
# Hm... even the z buffer isn't helping keep this above x_guess_line
midXBrace = startBrace.copy() # Had start and endBrace been asymmetric, we'd do something different here
midXBrace.set_color(midColor)
midXBrace.move_to(self.coords_to_point(midX, self.base_line_y) + OUT)
# We only actually add this much later
midXPoint = Dot(self.coords_to_point(midX, self.base_line_y) + OUT, color = sign_color)
x_guess_label_caption = TextMobject("New guess: x = ", fill_color = midColor)
x_guess_label_num = DecimalNumber(midX, fill_color = midColor)
x_guess_label_num.move_to(0.9 * FRAME_Y_RADIUS * DOWN)
x_guess_label_caption.next_to(x_guess_label_num, LEFT)
x_guess_label = Group(x_guess_label_caption, x_guess_label_num)
y_guess_label_caption = TextMobject(", y = ", fill_color = midColor)
y_guess_label_num = DecimalNumber(midY, fill_color = sign_color)
y_guess_label_caption.next_to(x_guess_label_num, RIGHT)
y_guess_label_num.next_to(y_guess_label_caption, RIGHT)
y_guess_label = Group(y_guess_label_caption, y_guess_label_num)
guess_labels = Group(x_guess_label, y_guess_label)
self.play(
ReplacementTransform(leftBrace.copy(), midXBrace),
ReplacementTransform(rightBrace.copy(), midXBrace),
FadeIn(x_guess_label))
self.add_foreground_mobject(midXBrace)
midXLine = DashedLine(
self.coords_to_point(midX, self.base_line_y),
midCoords,
color = midColor
)
self.play(ShowCreation(midXLine))
midDot = Dot(midCoords, color = sign_color)
if(self.iteration_at_which_to_start_zoom != None and
i >= self.iteration_at_which_to_start_zoom):
midDot.scale_in_place(inverseZoomFactor)
self.add(midDot)
midYLine = DashedLine(midCoords, self.coords_to_point(0, midY), color = sign_color)
self.play(
ShowCreation(midYLine),
FadeIn(y_guess_label),
ApplyMethod(midXBrace.set_color, sign_color),
ApplyMethod(midXLine.set_color, sign_color),
run_time = 0.25
)
midYPoint = Dot(self.coords_to_point(0, midY), color = sign_color)
self.add(midXPoint, midYPoint)
if in_negative_branch:
self.play(
UpdateFromAlphaFunc(lowerGroup,
makeUpdater(lowerX,
fixed_guess_x = upperX
)
),
FadeOut(guess_labels),
)
lowerX = midX
lowerY = midY
else:
self.play(
UpdateFromAlphaFunc(upperGroup,
makeUpdater(upperX,
fixed_guess_x = lowerX
)
),
FadeOut(guess_labels),
)
upperX = midX
upperY = midY
#mid_group = Group(midXLine, midDot, midYLine) Removing groups doesn't flatten as expected?
self.remove(midXLine, midDot, midYLine, midXBrace)
self.wait()
def construct(self):
self.drawGraph()
self.solveEquation()
# Returns the value with the same fractional component as x, closest to m
def resit_near(x, m):
frac_diff = (x - m) % 1
if frac_diff > 0.5:
frac_diff -= 1
return m + frac_diff
# TODO?: Perhaps use modulus of (uniform) continuity instead of num_checkpoints, calculating
# latter as needed from former?
#
# "cheap" argument only used for diagnostic testing right now
def make_alpha_winder(func, start, end, num_checkpoints, cheap = False):
check_points = [None for i in range(num_checkpoints)]
check_points[0] = func(start)
step_size = fdiv(end - start, num_checkpoints)
for i in range(num_checkpoints - 1):
check_points[i + 1] = \
resit_near(
func(start + (i + 1) * step_size),
check_points[i])
def return_func(alpha):
if cheap:
return alpha # A test to see if this func is responsible for slowdown
index = np.clip(0, num_checkpoints - 1, int(alpha * num_checkpoints))
x = interpolate(start, end, alpha)
if cheap:
return check_points[index] # A more principled test that at least returns a reasonable answer
else:
return resit_near(func(x), check_points[index])
return return_func
# The various inconsistent choices of what datatype to use where are a bit of a mess,
# but I'm more keen to rush this video out now than to sort this out.
def complex_to_pair(c):
return np.array((c.real, c.imag))
def plane_func_from_complex_func(f):
return lambda x_y4 : complex_to_pair(f(complex(x_y4[0],x_y4[1])))
def point3d_func_from_plane_func(f):
def g(xxx_todo_changeme):
(x, y, z) = xxx_todo_changeme
f_val = f((x, y))
return np.array((f_val[0], f_val[1], 0))
return g
def point3d_func_from_complex_func(f):
return point3d_func_from_plane_func(plane_func_from_complex_func(f))
def plane_zeta(xxx_todo_changeme8):
(x, y) = xxx_todo_changeme8
CLAMP_SIZE = 1000
z = complex(x, y)
try:
answer = mpmath.zeta(z)
except ValueError:
return (CLAMP_SIZE, 0)
if abs(answer) > CLAMP_SIZE:
answer = answer/abs(answer) * CLAMP_SIZE
return (float(answer.real), float(answer.imag))
def rescaled_plane_zeta(xxx_todo_changeme9):
(x, y) = xxx_todo_changeme9
return plane_zeta((x/FRAME_X_RADIUS, 8*y))
# Returns a function from 2-ples to 2-ples
# This function is specified by a list of (x, y, z) tuples,
# and has winding number z (or total of all specified z) around each (x, y)
#
# Can also pass in (x, y) tuples, interpreted as (x, y, 1)
def plane_func_by_wind_spec(*specs):
def embiggen(p):
if len(p) == 3:
return p
elif len(p) == 2:
return (p[0], p[1], 1)
else:
print("Error in plane_func_by_wind_spec embiggen!")
specs = list(map(embiggen, specs))
pos_specs = [x_y_z for x_y_z in specs if x_y_z[2] > 0]
neg_specs = [x_y_z1 for x_y_z1 in specs if x_y_z1[2] < 0]
neg_specs_made_pos = [(x_y_z2[0], x_y_z2[1], -x_y_z2[2]) for x_y_z2 in neg_specs]
def poly(c, root_specs):
return np.prod([(c - complex(x, y))**z for (x, y, z) in root_specs])
def complex_func(c):
return poly(c, pos_specs) * np.conjugate(poly(c, neg_specs_made_pos))
return plane_func_from_complex_func(complex_func)
def scale_func(func, scale_factor):
return lambda x : func(x) * scale_factor
# Used in Initial2dFunc scenes, VectorField scene, and ExamplePlaneFunc
example_plane_func_spec = [(-3, -1.3, 2), (0.1, 0.2, 1), (2.8, -2, -1)]
example_plane_func = plane_func_by_wind_spec(*example_plane_func_spec)
empty_animation = EmptyAnimation()
class WalkerAnimation(Animation):
CONFIG = {
"walk_func" : None, # Must be initialized to use
"remover" : True,
"rate_func" : None,
"coords_to_point" : None
}
def __init__(self, walk_func, val_func, coords_to_point,
show_arrows = True, scale_arrows = False,
**kwargs):
self.walk_func = walk_func
self.val_func = val_func
self.coords_to_point = coords_to_point
self.compound_walker = VGroup()
self.show_arrows = show_arrows
self.scale_arrows = scale_arrows
if "walker_stroke_color" in kwargs:
walker_stroke_color = kwargs["walker_stroke_color"]
else:
walker_stroke_color = BLACK
base_walker = Dot().scale(5 * 0.35).set_stroke(walker_stroke_color, 2) # PiCreature().scale(0.8 * 0.35)
self.compound_walker.walker = base_walker
if show_arrows:
self.compound_walker.arrow = Arrow(ORIGIN, 0.5 * RIGHT, buff = 0)
self.compound_walker.arrow.match_style(self.compound_walker.walker)
self.compound_walker.digest_mobject_attrs()
Animation.__init__(self, self.compound_walker, **kwargs)
# Perhaps abstract this out into an "Animation updating from original object" class
def interpolate_submobject(self, submobject, starting_submobject, alpha):
submobject.points = np.array(starting_submobject.points)
def interpolate_mobject(self, alpha):
Animation.interpolate_mobject(self, alpha)
cur_x, cur_y = cur_coords = self.walk_func(alpha)
cur_point = self.coords_to_point(cur_x, cur_y)
self.mobject.shift(cur_point - self.mobject.walker.get_center())
val = self.val_func(cur_coords)
rev = point_to_rev(val)
self.mobject.walker.set_fill(rev_to_color(rev))
if self.show_arrows:
self.mobject.arrow.set_fill(rev_to_color(rev))
self.mobject.arrow.rotate(
rev * TAU,
about_point = self.mobject.arrow.get_start()
)
if self.scale_arrows:
size = point_to_rescaled_size(val)
self.mobject.arrow.scale(
size * 0.3, # Hack constant; we barely use this feature right now
about_point = self.mobject.arrow.get_start()
)
def walker_animation_with_display(
walk_func,
val_func,
coords_to_point,
number_update_func = None,
show_arrows = True,
scale_arrows = False,
num_decimal_places = 1,
include_background_rectangle = True,
**kwargs
):
walker_anim = WalkerAnimation(
walk_func = walk_func,
val_func = val_func,
coords_to_point = coords_to_point,
show_arrows = show_arrows,
scale_arrows = scale_arrows,
**kwargs)
walker = walker_anim.compound_walker.walker
if number_update_func != None:
display = DecimalNumber(0,
num_decimal_places = num_decimal_places,
fill_color = WHITE if include_background_rectangle else BLACK,
include_background_rectangle = include_background_rectangle)
if include_background_rectangle:
display.background_rectangle.fill_opacity = 0.5
display.background_rectangle.fill_color = GREY
display.background_rectangle.scale(1.2)
displaycement = 0.5 * DOWN # How about that pun, eh?
# display.move_to(walker.get_center() + displaycement)
display.next_to(walker, DOWN+RIGHT, SMALL_BUFF)
display_anim = ChangingDecimal(display,
number_update_func,
tracked_mobject = walker_anim.compound_walker.walker,
**kwargs)
anim_group = AnimationGroup(walker_anim, display_anim, rate_func=linear)
return anim_group
else:
return walker_anim
def LinearWalker(
start_coords,
end_coords,
coords_to_point,
val_func,
number_update_func = None,
show_arrows = True,
scale_arrows = False,
include_background_rectangle = True,
**kwargs
):
walk_func = lambda alpha : interpolate(start_coords, end_coords, alpha)
return walker_animation_with_display(
walk_func = walk_func,
coords_to_point = coords_to_point,
val_func = val_func,
number_update_func = number_update_func,
show_arrows = show_arrows,
scale_arrows = scale_arrows,
include_background_rectangle = include_background_rectangle,
**kwargs)
class ColorMappedByFuncScene(Scene):
CONFIG = {
"func" : lambda p : p,
"num_plane" : NumberPlane(),
"show_num_plane" : True,
"show_output" : False,
"hide_background" : False #Background used for color mapped objects, not as background
}
def short_path_to_long_path(self, filename_with_ext):
return self.get_image_file_path(filename_with_ext)
def setup(self):
# The composition of input_to_pos and pos_to_color
# is to be equal to func (which turns inputs into colors)
# However, depending on whether we are showing input or output (via a MappingCamera),
# we color the background using either func or the identity map
if self.show_output:
self.input_to_pos_func = self.func
self.pos_to_color_func = lambda p : p
else:
self.input_to_pos_func = lambda p : p
self.pos_to_color_func = self.func
self.pixel_pos_to_color_func = lambda x_y3 : self.pos_to_color_func(
self.num_plane.point_to_coords_cheap(np.array([x_y3[0], x_y3[1], 0]))
)
jitter_val = 0.1
line_coords = np.linspace(-10, 10) + jitter_val
func_hash_points = it.product(line_coords, line_coords)
def mini_hasher(p):
rgba = point_to_rgba(self.pixel_pos_to_color_func(p))
if rgba[3] != 1.0:
print("Warning! point_to_rgba assigns fractional alpha", rgba[3])
return tuple(rgba)
to_hash = tuple(mini_hasher(p) for p in func_hash_points)
func_hash = hash(to_hash)
# We hash just based on output image
# Thus, multiple scenes with same output image can re-use it
# without recomputation
full_hash = hash((func_hash, self.camera.get_pixel_width()))
self.background_image_file = self.short_path_to_long_path(
"color_mapped_bg_hash_" + str(full_hash) + ".png"
)
self.in_background_pass = not os.path.exists(self.background_image_file)
print("Background file: " + self.background_image_file)
if self.in_background_pass:
print("The background file does not exist yet; this will be a background creation + video pass")
else:
print("The background file already exists; this will only be a video pass")
def construct(self):
if self.in_background_pass:
self.camera.set_background_from_func(
lambda x_y: point_to_rgba(
self.pixel_pos_to_color_func(
(x_y[0], x_y[1])
)
)
)
self.save_image(self.background_image_file, mode="RGBA")
if self.hide_background:
# Clearing background
self.camera.background_image = None
else:
# Even if we just computed the background, we switch to the file now
self.camera.background_image = self.background_image_file
self.camera.init_background()
if self.show_num_plane:
self.num_plane.fade()
self.add(self.num_plane)
class PureColorMap(ColorMappedByFuncScene):
CONFIG = {
"show_num_plane" : False
}
def construct(self):
ColorMappedByFuncScene.construct(self)
self.wait()
# This sets self.background_image_file, but does not display it as the background
class ColorMappedObjectsScene(ColorMappedByFuncScene):
CONFIG = {
"show_num_plane" : False,
"hide_background" : True,
}
class PiWalker(ColorMappedByFuncScene):
CONFIG = {
"walk_coords" : [],
"step_run_time" : 1,
"scale_arrows" : False,
"display_wind" : True,
"wind_reset_indices" : [],
"display_size" : False,
"display_odometer" : False,
"color_foreground_not_background" : False,
"show_num_plane" : False,
"draw_lines" : True,
"num_checkpoints" : 10,
"num_decimal_places" : 1,
"include_background_rectangle" : False,
}
def construct(self):
ColorMappedByFuncScene.construct(self)
if self.color_foreground_not_background or self.display_odometer:
# Clear background
self.camera.background_image = None
self.camera.init_background()
num_plane = self.num_plane
walk_coords = self.walk_coords
points = [num_plane.coords_to_point(x, y) for x, y in walk_coords]
polygon = Polygon(*points, color = WHITE)
if self.color_foreground_not_background:
polygon.stroke_width = border_stroke_width
polygon.color_using_background_image(self.background_image_file)
total_run_time = len(points) * self.step_run_time
polygon_anim = ShowCreation(polygon, run_time = total_run_time, rate_func=linear)
walker_anim = empty_animation
start_wind = 0
for i in range(len(walk_coords)):
start_coords = walk_coords[i]
end_coords = walk_coords[(i + 1) % len(walk_coords)]
# We need to do this roundabout default argument thing to get the closure we want,
# so the next iteration changing start_coords, end_coords doesn't change this closure
val_alpha_func = lambda a, start_coords = start_coords, end_coords = end_coords : self.func(interpolate(start_coords, end_coords, a))
if self.display_wind:
clockwise_val_func = lambda p : -point_to_rev(self.func(p))
alpha_winder = make_alpha_winder(clockwise_val_func, start_coords, end_coords, self.num_checkpoints)
number_update_func = lambda alpha, alpha_winder = alpha_winder, start_wind = start_wind: alpha_winder(alpha) - alpha_winder(0) + start_wind
start_wind = 0 if i + 1 in self.wind_reset_indices else number_update_func(1)
elif self.display_size:
# We need to do this roundabout default argument thing to get the closure we want,
# so the next iteration changing val_alpha_func doesn't change this closure
number_update_func = lambda a, val_alpha_func = val_alpha_func : point_to_rescaled_size(val_alpha_func(a)) # We only use this for diagnostics
else:
number_update_func = None
new_anim = LinearWalker(
start_coords = start_coords,
end_coords = end_coords,
coords_to_point = num_plane.coords_to_point,
val_func = self.func,
remover = (i < len(walk_coords) - 1),
show_arrows = not self.show_output,
scale_arrows = self.scale_arrows,
number_update_func = number_update_func,
run_time = self.step_run_time,
walker_stroke_color = WALKER_LIGHT_COLOR if self.color_foreground_not_background else BLACK,
num_decimal_places = self.num_decimal_places,
include_background_rectangle = self.include_background_rectangle,
)
if self.display_odometer:
# Discard above animation and show an odometer instead
# We need to do this roundabout default argument thing to get the closure we want,
# so the next iteration changing val_alpha_func doesn't change this closure
rev_func = lambda a, val_alpha_func = val_alpha_func : point_to_rev(val_alpha_func(a))
base_arrow = Arrow(ORIGIN, RIGHT, buff = 0)
new_anim = FuncRotater(base_arrow,
rev_func = rev_func,
run_time = self.step_run_time,
rate_func=linear,
remover = i < len(walk_coords) - 1,
)
walker_anim = Succession(walker_anim, new_anim)
# TODO: Allow smooth paths instead of breaking them up into lines, and
# use point_from_proportion to get points along the way
if self.display_odometer:
color_wheel = Circle(radius = ODOMETER_RADIUS)
color_wheel.stroke_width = ODOMETER_STROKE_WIDTH
color_wheel.color_using_background_image(self.short_path_to_long_path("pure_color_map.png")) # Manually inserted here; this is unclean
self.add(color_wheel)
self.play(walker_anim)
else:
if self.draw_lines:
self.play(polygon_anim, walker_anim)
else:
# (Note: Turns out, play is unhappy playing empty_animation, as had been
# previous approach to this toggle; should fix that)
self.play(walker_anim)
self.wait()
class PiWalkerRect(PiWalker):
CONFIG = {
"start_x" : -1,
"start_y" : 1,
"walk_width" : 2,
"walk_height" : 2,
"func" : plane_func_from_complex_func(lambda c: c**2),
"double_up" : False,
# New default for the scenes using this:
"display_wind" : True
}
def setup(self):
TL = np.array((self.start_x, self.start_y))
TR = TL + (self.walk_width, 0)
BR = TR + (0, -self.walk_height)
BL = BR + (-self.walk_width, 0)
self.walk_coords = [TL, TR, BR, BL]
if self.double_up:
self.walk_coords = self.walk_coords + self.walk_coords
PiWalker.setup(self)
class PiWalkerCircle(PiWalker):
CONFIG = {
"radius" : 1,
"num_steps" : 100,
"step_run_time" : 0.01
}
def setup(self):
r = self.radius
N = self.num_steps
self.walk_coords = [r * np.array((np.cos(i * TAU/N), np.sin(i * TAU/N))) for i in range(N)]
PiWalker.setup(self)
def split_interval(xxx_todo_changeme10):
(a, b) = xxx_todo_changeme10
mid = (a + b)/2.0
return ((a, mid), (mid, b))
# I am surely reinventing some wheel here, but what's done is done...
class RectangleData():
def __init__(self, x_interval, y_interval):
self.rect = (x_interval, y_interval)
def get_top_left(self):
return np.array((self.rect[0][0], self.rect[1][1]))
def get_top_right(self):
return np.array((self.rect[0][1], self.rect[1][1]))
def get_bottom_right(self):
return np.array((self.rect[0][1], self.rect[1][0]))
def get_bottom_left(self):
return np.array((self.rect[0][0], self.rect[1][0]))
def get_top(self):
return (self.get_top_left(), self.get_top_right())
def get_right(self):
return (self.get_top_right(), self.get_bottom_right())
def get_bottom(self):
return (self.get_bottom_right(), self.get_bottom_left())
def get_left(self):
return (self.get_bottom_left(), self.get_top_left())
def get_center(self):
return interpolate(self.get_top_left(), self.get_bottom_right(), 0.5)
def get_width(self):
return self.rect[0][1] - self.rect[0][0]
def get_height(self):
return self.rect[1][1] - self.rect[1][0]
def splits_on_dim(self, dim):
x_interval = self.rect[0]
y_interval = self.rect[1]
# TODO: Can refactor the following; will do later
if dim == 0:
return_data = [RectangleData(new_interval, y_interval) for new_interval in split_interval(x_interval)]
elif dim == 1:
return_data = [RectangleData(x_interval, new_interval) for new_interval in split_interval(y_interval)[::-1]]
else:
print("RectangleData.splits_on_dim passed illegitimate dimension!")
return tuple(return_data)
def split_line_on_dim(self, dim):
x_interval = self.rect[0]
y_interval = self.rect[1]
if dim == 0:
sides = (self.get_top(), self.get_bottom())
elif dim == 1:
sides = (self.get_left(), self.get_right())
else:
print("RectangleData.split_line_on_dim passed illegitimate dimension!")
return tuple([mid(x, y) for (x, y) in sides])
class EquationSolver2dNode(object):
def __init__(self, first_anim, children = []):
self.first_anim = first_anim
self.children = children
def depth(self):
if len(self.children) == 0:
return 0
return 1 + max([n.depth() for n in self.children])
def nodes_at_depth(self, n):
if n == 0:
return [self]
# Not the efficient way to flatten lists, because Python + is linear in list size,
# but we have at most two children, so no big deal here
return sum([c.nodes_at_depth(n - 1) for c in self.children], [])
# This is definitely NOT the efficient way to do BFS, but I'm just trying to write something
# quick without thinking that gets the job done on small instances for now
def hacky_bfs(self):
depth = self.depth()
# Not the efficient way to flatten lists, because Python + is linear in list size,
# but this IS hacky_bfs...
return sum([self.nodes_at_depth(i) for i in range(depth + 1)], [])
def display_in_series(self):
return Succession(self.first_anim, *[n.display_in_series() for n in self.children])
def display_in_parallel(self):
return Succession(self.first_anim, AnimationGroup(*[n.display_in_parallel() for n in self.children]))
def display_in_bfs(self):
bfs_nodes = self.hacky_bfs()
return Succession(*[n.first_anim for n in bfs_nodes])
def play_in_bfs(self, scene, border_anim):
bfs_nodes = self.hacky_bfs()
print("Number of nodes: ", len(bfs_nodes))
if len(bfs_nodes) < 1:
print("Less than 1 node! Aborting!")
return
scene.play(bfs_nodes[0].first_anim, border_anim)