forked from 3b1b/videos
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmatrix_as_transform_2d.py
551 lines (486 loc) · 18 KB
/
matrix_as_transform_2d.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
#!/usr/bin/env python
import numpy as np
import itertools as it
from copy import deepcopy
import sys
from manim_imports_ext import *
ARROW_CONFIG = {"stroke_width" : 2*DEFAULT_STROKE_WIDTH}
LIGHT_RED = RED_E
def matrix_to_string(matrix):
return "--".join(["-".join(map(str, row)) for row in matrix])
def matrix_mobject(matrix):
return OldTexText(
"""
\\left(
\\begin{array}{%s}
%d & %d \\\\
%d & %d
\\end{array}
\\right)
"""%tuple(["c"*matrix.shape[1]] + list(matrix.flatten())),
size = "\\Huge"
)
class ShowMultiplication(NumberLineScene):
args_list = [
(2, True),
(0.5, True),
(-3, True),
(-3, True),
(2, True),
(6, True),
]
@staticmethod
def args_to_string(num, show_original_line):
end_string = "WithCopiedOriginalLine" if show_original_line else ""
return str(num) + end_string
@staticmethod
def string_to_args(string):
parts = string.split()
if len(parts) == 2:
num, original_line = parts
show_original_line = original_line == "WithCopiedOriginalLine"
return float(num), False
else:
return float(parts[0]), False
def construct(self, num, show_original_line):
config = {
"density" : max(abs(num), 1)*DEFAULT_POINT_DENSITY_1D,
"stroke_width" : 2*DEFAULT_STROKE_WIDTH
}
if abs(num) < 1:
config["numerical_radius"] = FRAME_X_RADIUS/num
NumberLineScene.construct(self, **config)
if show_original_line:
self.copy_original_line()
self.wait()
self.show_multiplication(num, run_time = 1.5)
self.wait()
def copy_original_line(self):
copied_line = deepcopy(self.number_line)
copied_num_mobs = deepcopy(self.number_mobs)
self.play(
ApplyFunction(
lambda m : m.shift(DOWN).set_color("lightgreen"),
copied_line
), *[
ApplyMethod(mob.shift, DOWN)
for mob in copied_num_mobs
]
)
self.wait()
class ExamplesOfOneDimensionalLinearTransforms(ShowMultiplication):
args_list = []
@staticmethod
def args_to_string():
return ""
def construct(self):
for num in [2, 0.5, -3]:
self.clear()
ShowMultiplication.construct(self, num, False)
class ExamplesOfNonlinearOneDimensionalTransforms(NumberLineScene):
def construct(self):
def sinx_plux_x(x_y_z):
(x, y, z) = x_y_z
return (np.sin(x) + 1.2*x, y, z)
def shift_zero(x_y_z):
(x, y, z) = x_y_z
return (2*x+4, y, z)
self.nonlinear = OldTexText("Not a Linear Transform")
self.nonlinear.set_color(LIGHT_RED).to_edge(UP, buff = 1.5)
pairs = [
(sinx_plux_x, "numbers don't remain evenly spaced"),
(shift_zero, "zero does not remain fixed")
]
for func, explanation in pairs:
self.run_function(func, explanation)
self.wait(3)
def run_function(self, function, explanation):
self.clear()
self.add(self.nonlinear)
config = {
"stroke_width" : 2*DEFAULT_STROKE_WIDTH,
"density" : 5*DEFAULT_POINT_DENSITY_1D,
}
NumberLineScene.construct(self, **config)
words = OldTexText(explanation).set_color(LIGHT_RED)
words.next_to(self.nonlinear, DOWN, buff = 0.5)
self.add(words)
self.play(
ApplyPointwiseFunction(function, self.number_line),
*[
ApplyMethod(
mob.shift,
function(mob.get_center()) - mob.get_center()
)
for mob in self.number_mobs
],
run_time = 2.0
)
class ShowTwoThenThree(ShowMultiplication):
args_list = []
@staticmethod
def args_to_string():
return ""
def construct(self):
config = {
"stroke_width" : 2*DEFAULT_STROKE_WIDTH,
"density" : 6*DEFAULT_POINT_DENSITY_1D,
}
NumberLineScene.construct(self, **config)
self.copy_original_line()
self.show_multiplication(2)
self.wait()
self.show_multiplication(3)
self.wait()
########################################################
class TransformScene2D(Scene):
def add_number_plane(self, density_factor = 1, use_faded_lines = True):
config = {
"x_radius" : FRAME_WIDTH,
"y_radius" : FRAME_WIDTH,
"density" : DEFAULT_POINT_DENSITY_1D*density_factor,
"stroke_width" : 2*DEFAULT_STROKE_WIDTH
}
if not use_faded_lines:
config["x_faded_line_frequency"] = None
config["y_faded_line_frequency"] = None
self.number_plane = NumberPlane(**config)
self.add(self.number_plane)
def add_background(self):
grey_plane = NumberPlane(color = "grey")
num_mobs = grey_plane.get_coordinate_labels()
self.paint_into_background(grey_plane, *num_mobs)
def add_x_y_arrows(self):
self.x_arrow = Arrow(
ORIGIN,
self.number_plane.num_pair_to_point((1, 0)),
color = "lightgreen",
**ARROW_CONFIG
)
self.y_arrow = Arrow(
ORIGIN,
self.number_plane.num_pair_to_point((0, 1)),
color = LIGHT_RED,
**ARROW_CONFIG
)
self.add(self.x_arrow, self.y_arrow)
self.number_plane.filter_out(
lambda x_y_z : (0 < x_y_z[0]) and (x_y_z[0] < 1) and (abs(x_y_z[1]) < 0.1)
)
self.number_plane.filter_out(
lambda x_y_z1 : (0 < x_y_z1[1]) and (x_y_z1[1] < 1) and (abs(x_y_z1[0]) < 0.1)
)
return self
class ShowMatrixTransform(TransformScene2D):
args_list = [
([[1, 3], [-2, 0]], False, False),
([[1, 3], [-2, 0]], True, False),
([[1, 0.5], [0.5, 1]], True, False),
([[2, 0], [0, 2]], True, False),
([[0.5, 0], [0, 0.5]], True, False),
([[-1, 0], [0, -1]], True, False),
([[0, 1], [1, 0]], True, False),
([[-2, 0], [-1, -1]], True, False),
([[0, -1], [1, 0]], True, False),
]
@staticmethod
def args_to_string(matrix, with_background, show_matrix):
background_string = "WithBackground" if with_background else "WithoutBackground"
show_string = "ShowingMatrix" if show_matrix else ""
return matrix_to_string(matrix) + background_string + show_string
def construct(self, matrix, with_background, show_matrix):
matrix = np.array(matrix)
number_plane_config = {
"density_factor" : self.get_density_factor(matrix)
}
if with_background:
self.add_background()
number_plane_config["use_faded_lines"] = False
self.add_number_plane(**number_plane_config)
self.add_x_y_arrows()
else:
self.add_number_plane(**number_plane_config)
if show_matrix:
self.add(matrix_mobject(matrix).to_corner(UP+LEFT))
def func(mobject):
mobject.get_points()[:, :2] = np.dot(mobject.get_points()[:, :2], np.transpose(matrix))
return mobject
self.wait()
kwargs = {
"run_time" : 2.0,
"path_func" : self.get_path_func(matrix)
}
anims = [ApplyFunction(func, self.number_plane, **kwargs)]
if hasattr(self, "x_arrow") and hasattr(self, "y_arrow"):
for arrow, index in (self.x_arrow, 0), (self.y_arrow, 1):
new_arrow = Arrow(
ORIGIN,
self.number_plane.num_pair_to_point(matrix[:,index]),
color = arrow.get_color(),
**ARROW_CONFIG
)
arrow.remove_tip()
new_arrow.remove_tip()
Mobject.align_data_and_family(arrow, new_arrow)
arrow.add_tip()
new_arrow.add_tip()
anims.append(Transform(arrow, new_arrow, **kwargs))
self.play(*anims)
self.wait()
def get_density_factor(self, matrix):
max_norm = max([
abs(get_norm(column))
for column in np.transpose(matrix)
])
return max(max_norm, 1)
def get_path_func(self, matrix):
rotational_components = np.array([
np.log(multiplier*complex(*matrix[:,i])).imag
for i, multiplier in [(0, 1), (1, complex(0, -1))]
])
rotational_components[rotational_components == -np.pi] = np.pi
return path_along_arc(np.mean(rotational_components))
class ExamplesOfTwoDimensionalLinearTransformations(ShowMatrixTransform):
args_list = []
@staticmethod
def args_to_string():
return ""
def construct(self):
matrices = [
[[1, 0.5],
[0.5, 1]],
[[0, -1],
[2, 0]],
[[1, 3],
[-2, 0]],
]
for matrix in matrices:
self.clear()
ShowMatrixTransform.construct(self, matrix, False, False)
class ExamplesOfNonlinearTwoDimensionalTransformations(Scene):
def construct(self):
Scene.construct(self)
def squiggle(x_y_z):
(x, y, z) = x_y_z
return (x+np.sin(y), y+np.cos(x), z)
def shift_zero(x_y_z):
(x, y, z) = x_y_z
return (2*x + 3*y + 4, -1*x+y+2, z)
self.nonlinear = OldTexText("Nonlinear Transform")
self.nonlinear.set_color(LIGHT_RED)
self.nonlinear.to_edge(UP, buff = 1.5)
pairs = [
(squiggle, "lines do not remain straight"),
(shift_zero, "the origin does not remain fixed")
]
self.get_blackness()
for function, explanation in pairs:
self.apply_function(function, explanation)
def apply_function(self, function, explanation):
self.clear()
config = {
"x_radius" : FRAME_WIDTH,
"y_radius" : FRAME_WIDTH,
"density" : 3*DEFAULT_POINT_DENSITY_1D,
"stroke_width" : 2*DEFAULT_STROKE_WIDTH
}
number_plane = NumberPlane(**config)
numbers = number_plane.get_coordinate_labels()
words = OldTexText(explanation)
words.set_color(LIGHT_RED)
words.next_to(self.nonlinear, DOWN, buff = 0.5)
self.add(number_plane, *numbers)
self.add(self.blackness, self.nonlinear, words)
self.wait()
self.play(
ApplyPointwiseFunction(function, number_plane),
*[
ApplyMethod(
mob.shift,
function(mob.get_center())-mob.get_center()
)
for mob in numbers
] + [
Animation(self.blackness),
Animation(words),
Animation(self.nonlinear)
],
run_time = 2.0
)
self.wait(3)
def get_blackness(self):
vertices = [
3.5*LEFT+1.05*UP,
3.5*RIGHT+1.05*UP,
3.5*RIGHT+2.75*UP,
3.5*LEFT+2.75*UP,
]
region = region_from_polygon_vertices(*vertices)
image = disp.paint_region(region, color = WHITE)
self.blackness = OldTexText("")
ImageMobject.generate_points_from_image_array(self.blackness, image)
self.blackness.set_color(BLACK)
rectangle = Rectangle(width = 7, height=1.7)
rectangle.set_color(WHITE)
rectangle.shift(self.blackness.get_center())
self.blackness.add(rectangle)
self.blackness.scale(0.95)
class TrickyExamplesOfNonlinearTwoDimensionalTransformations(Scene):
def construct(self):
config = {
"x_radius" : 0.6*FRAME_WIDTH,
"y_radius" : 0.6*FRAME_WIDTH,
"density" : 10*DEFAULT_POINT_DENSITY_1D,
"stroke_width" : 2*DEFAULT_STROKE_WIDTH
}
number_plane = NumberPlane(**config)
phrase1, phrase2 = OldTexText([
"These might look like they keep lines straight...",
"but diagonal lines get curved"
]).to_edge(UP, buff = 1.5).split()
phrase2.set_color(LIGHT_RED)
diagonal = Line(
DOWN*FRAME_Y_RADIUS+LEFT*FRAME_X_RADIUS,
UP*FRAME_Y_RADIUS+RIGHT*FRAME_X_RADIUS,
density = 10*DEFAULT_POINT_DENSITY_1D
)
def sunrise(x_y_z):
(x, y, z) = x_y_z
return ((FRAME_Y_RADIUS+y)*x, y, z)
def squished(x_y_z):
(x, y, z) = x_y_z
return (x + np.sin(x), y+np.sin(y), z)
self.get_blackness()
self.run_function(sunrise, number_plane, phrase1)
self.run_function(squished, number_plane, phrase1)
phrase1.add(phrase2)
self.add(phrase1)
self.play(ShowCreation(diagonal))
self.remove(diagonal)
number_plane.add(diagonal)
self.run_function(sunrise, number_plane, phrase1)
self.run_function(squished, number_plane, phrase1, False)
def run_function(self, function, plane, phrase, remove_plane = True):
number_plane = deepcopy(plane)
self.add(number_plane, self.blackness, phrase)
self.wait()
self.play(
ApplyPointwiseFunction(function, number_plane, run_time = 2.0),
Animation(self.blackness),
Animation(phrase),
)
self.wait(3)
if remove_plane:
self.remove(number_plane)
def get_blackness(self):
vertices = [
4.5*LEFT+1.25*UP,
4.5*RIGHT+1.25*UP,
4.5*RIGHT+2.75*UP,
4.5*LEFT+2.75*UP,
]
region = region_from_polygon_vertices(*vertices)
image = disp.paint_region(region, color = WHITE)
self.blackness = OldTexText("")
ImageMobject.generate_points_from_image_array(self.blackness, image)
self.blackness.set_color(BLACK)
rectangle = Rectangle(width = 9, height=1.5)
rectangle.set_color(WHITE)
rectangle.shift(self.blackness.get_center())
self.blackness.add(rectangle)
self.blackness.scale(0.95)
############# HORRIBLE! ##########################
class ShowMatrixTransformWithDot(TransformScene2D):
args_list = [
([[1, 3], [-2, 0]], True, False),
]
@staticmethod
def args_to_string(matrix, with_background, show_matrix):
background_string = "WithBackground" if with_background else "WithoutBackground"
show_string = "ShowingMatrix" if show_matrix else ""
return matrix_to_string(matrix) + background_string + show_string
def construct(self, matrix, with_background, show_matrix):
matrix = np.array(matrix)
number_plane_config = {
"density_factor" : self.get_density_factor(matrix),
}
if with_background:
self.add_background()
number_plane_config["use_faded_lines"] = False
self.add_number_plane(**number_plane_config)
self.add_x_y_arrows()
else:
self.add_number_plane(**number_plane_config)
if show_matrix:
self.add(matrix_mobject(matrix).to_corner(UP+LEFT))
def func(mobject):
mobject.get_points()[:, :2] = np.dot(mobject.get_points()[:, :2], np.transpose(matrix))
return mobject
dot = Dot((-1, 2, 0), color = "yellow")
self.add(dot)
x_arrow_copy = deepcopy(self.x_arrow)
y_arrow_copy = Arrow(LEFT, LEFT+2*UP, color = LIGHT_RED, **ARROW_CONFIG)
self.play(ApplyMethod(x_arrow_copy.rotate, np.pi))
self.play(ShowCreation(y_arrow_copy))
self.wait()
self.remove(x_arrow_copy, y_arrow_copy)
kwargs = {
"run_time" : 2.0,
"path_func" : self.get_path_func(matrix)
}
anims = [
ApplyFunction(func, self.number_plane, **kwargs),
ApplyMethod(dot.shift, func(deepcopy(dot)).get_center()-dot.get_center(), **kwargs),
]
if hasattr(self, "x_arrow") and hasattr(self, "y_arrow"):
for arrow, index in (self.x_arrow, 0), (self.y_arrow, 1):
new_arrow = Arrow(
ORIGIN,
self.number_plane.num_pair_to_point(matrix[:,index]),
color = arrow.get_color(),
**ARROW_CONFIG
)
arrow.remove_tip()
new_arrow.remove_tip()
Mobject.align_data_and_family(arrow, new_arrow)
arrow.add_tip()
new_arrow.add_tip()
anims.append(Transform(arrow, new_arrow, **kwargs))
self.play(*anims)
self.wait()
x_arrow_copy = deepcopy(self.x_arrow)
y_arrow_copy = Arrow(LEFT+2*UP, 5*RIGHT+2*UP, color = LIGHT_RED, **ARROW_CONFIG)
self.play(ApplyMethod(x_arrow_copy.rotate, np.pi))
self.play(ShowCreation(y_arrow_copy))
self.wait(3)
self.remove(x_arrow_copy, y_arrow_copy)
def get_density_factor(self, matrix):
max_norm = max([
abs(get_norm(column))
for column in np.transpose(matrix)
])
return max(max_norm, 1)
def get_path_func(self, matrix):
rotational_components = [
sign*np.arccos(matrix[i,i]/get_norm(matrix[:,i]))
for i in [0, 1]
for sign in [((-1)**i)*np.sign(matrix[1-i, i])]
]
average_rotation = sum(rotational_components)/2
if abs(average_rotation) < np.pi / 2:
return straight_path
elif average_rotation > 0:
return counterclockwise_path()
else:
return clockwise_path()
class Show90DegreeRotation(TransformScene2D):
def construct(self):
self.add_number_plane()
self.add_background()
self.add_x_y_arrows()
self.wait()
self.play(*[
RotationAsTransform(mob, run_time = 2.0)
for mob in (self.number_plane, self.x_arrow, self.y_arrow)
])
self.wait()