-
Notifications
You must be signed in to change notification settings - Fork 0
/
vec.py
384 lines (281 loc) · 10 KB
/
vec.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
"""
Show an animation of vector cross products.
usage: python3.8 vec.py [-h] mag1 mag2
One plot shows the vectors rotating about the origin and displays their cross product.
Adjacent to that, a plot displays the cross product as a function of
theta (absolute value of each vectors' angles above/below the X-axis).
Each of the vectors' magnitudes remain constant and the only transformation is rotation.
positional arguments:
mag1 Magnitude of vector 1
mag2 Magnitude of vector 2
optional arguments:
-h, --help show this help message and exit
"""
from argparse import ArgumentParser
import math
from typing import Any, Callable, List, Optional, Tuple, TypedDict
import matplotlib as mpl
import matplotlib.pyplot as plt
import numpy as np
from matplot_fmt_pi.ticker import MultiplePi
from matplotlib.animation import FuncAnimation
from matplotlib.artist import Artist
from matplotlib.axes import Axes
from matplotlib.axis import XAxis, YAxis
from matplotlib.backends.backend_qt5 import FigureManagerQT
from matplotlib.figure import Figure
from matplotlib.lines import Line2D
from matplotlib.patches import Patch
from matplotlib.quiver import Quiver
from matplotlib.text import Text
from matplotlib.ticker import MultipleLocator
# TODO
# Command line args for vectors' magnitudes?
# Make graph sizing generated?
# Move main() initialization to init_anim()
# The components of a vector
Vector = Tuple[float, float]
# Two vectors together
VectorPair = Tuple[Vector, Vector]
class LineDict(TypedDict):
"""Dictionary with attributes about a plotted line."""
line: Line2D
x_data: List[float]
y_data: List[float]
def calc_vector_comps(theta_1: float, theta_2: float,
mag1: float, mag2: float) -> VectorPair:
"""Calculate the components of two vectors with constant magnitude.
Parameters
----------
theta_1 : `float`
The first angle
theta_2 : `float`
The second angle
Returns
-------
`VectorPair`
The components of the vectors
"""
x_1, y_1 = (mag1 *
math.cos(theta_1), mag1 *
math.sin(theta_1))
x_2, y_2 = (mag2 *
math.cos(theta_2), mag2 *
math.sin(theta_2))
return ((x_1, y_1), (x_2, y_2))
def setup_plt() -> None:
"""Adjust properties to be rendered on the plot."""
mpl.rcParams["font.family"] = "Poppins"
plt.style.use("ggplot")
def format_plt() -> None:
"""Adjust properties of the rendered plot."""
plt.tight_layout()
def format_plt_1(plt_1: Axes, mag1: float, mag2: float) -> None:
"""Format the vector plot after it has been rendered.
Parameters
----------
plt_1 : `Axes`
The Axes object describing the subplot
"""
v_patch = Patch(color="r", label=r"$\vec{v}$")
w_patch = Patch(color="g", label=r"$\vec{w}$")
plt_1.legend(handles=[v_patch, w_patch])
x_axis: XAxis = plt_1.get_xaxis()
y_axis: YAxis = plt_1.get_yaxis()
# y_min_loc: MultipleLocator = MultipleLocator(1)
# y_axis.set_minor_locator(y_min_loc)
# x_min_loc: MultipleLocator = MultipleLocator(1)
# x_axis.set_minor_locator(x_min_loc)
plt_1.grid(axis="both", which="major", lw=1.5)
plt_1.grid(axis="both", which="minor", lw=0.5)
plt_1.set(xlabel="$X$", ylabel="$Y$", title="Vectors plotted on grid")
plt_1.set_xlim([-max(mag1, mag2) - 1, max(mag1, mag2) + 1])
plt_1.set_ylim([-max(mag1, mag2) - 1, max(mag1, mag2) + 1])
def format_plt_2(plt_2: Axes, mag1: float, mag2: float) -> None:
"""Format the cross product plot after it has been rendered.
Parameters
----------
plt_2 : `Axes`
The Axes object describing the subplot
"""
x_axis: XAxis = plt_2.get_xaxis()
plt_2.set(
xlabel=r"$\theta$ (radians)",
ylabel="Cross Product",
title="Cross Product Theta Relationship")
maj_manager = MultiplePi(denominator=4)
min_manager = MultiplePi(denominator=12)
x_axis.set_major_locator(maj_manager.locator())
x_axis.set_major_formatter(maj_manager.formatter())
x_axis.set_minor_locator(min_manager.locator())
((x_1, y_1), (x_2, y_2)) = calc_vector_comps(
math.pi / 4, -math.pi / 4, mag1, mag2)
vecs: np.ndarray = np.array([[x_1, y_1], [x_2, y_2]])
# gets maximum cross product to know hot to set axes
bound = abs(np.cross(*vecs))
bound = bound + bound / 10
plt_2.set_ylim([-bound, bound])
plt_2.set_xlim([- math.pi / 8, math.pi + (math.pi / 8)])
def plot_quiver(axes: Axes, mag1: float, mag2: float) -> Tuple[Quiver, Text]:
"""Plot the vector arrows on the plot.
Parameters
----------
axes : `Axes`
The object describing the subplot
Returns
-------
`Tuple[Quiver, Text]`
The quiver objects as well as the cross product text
"""
((x_1, y_1), (x_2, y_2)) = calc_vector_comps(0, 0, mag1, mag2)
vecs: np.ndarray = np.array([[0, 0, x_1, y_1], [0, 0, x_2, y_2]])
x_origins, y_origins, x_comps, y_comps = zip(*vecs)
arrows: Quiver = axes.quiver(
x_origins,
y_origins,
x_comps,
y_comps,
angles='xy',
scale_units='xy',
scale=1,
color=("r", "g"))
info: Text = axes.text(0.1, 0.9, f"Cross Product: 0", transform=axes.transAxes)
return (arrows, info)
def plot_cross_prod_line(plt_2: Axes) -> Line2D:
"""Plot the cross product value as a function of theta.
Parameters
----------
plt_2 : `Axes`
The Axes object describing the graph
Returns
-------
`Line2D`
The object describing the plotted line
"""
artists: List[Any] = plt_2.plot(
[],
[],
lw=2,
color="#0055ffff",
label="cross v. theta")
line: Line2D = artists[0]
return line
def init_anim_factory(arrows: Quiver, info: Text,
line: Line2D) -> Callable[..., List[Artist]]:
"""Return a function that has all of the initially plotted artists on the subplots.
The blitting algorithm needs these artists for its optimizations.
This function could probably contain what is currently in main().
Parameters
----------
arrows : `Quiver`
The vector arrows
info : `Text`
The text stating the cross product
line : `Line2D`
Line plotting cross product
Returns
-------
`Callable[..., List[Artist]]`
The function called by FuncAnimation
"""
return lambda: [arrows, info, line]
def update_plt_1(arrows: Quiver,
info: Text, theta: float, mag1: float, mag2: float) -> float:
"""Update the vector plot with new angles and re-calculate cross product.
Parameters
----------
arrows : `Quiver`
The vector arrows
info : `Text`
The text stating the cross product
theta : `float`
The angle above and below the x-axis for each vector
Returns
-------
`float`
The cross product at this angle
"""
((x_1, y_1), (x_2, y_2)) = calc_vector_comps(theta, -theta, mag1, mag2)
vecs: np.ndarray = np.array([[x_1, y_1], [x_2, y_2]])
x_comps, y_comps = zip(*vecs)
cross_prod = np.cross(*vecs)
info.set_text(f"Cross product: {cross_prod:>6.2f}")
arrows.set_UVC(x_comps, y_comps)
return cross_prod
def update_plt_2(line_dict: LineDict, theta: float,
cross_prod: float) -> Line2D:
"""Update the line plotting cross product as a function of theta.
Parameters
----------
line_dict : `LineDict`
Has the line object and associated x and y data
theta : `float`
The angle above and below the x-axis for each vector
cross_prod : `float`
The calculated cross product
Returns
-------
`Line2D`
The actual line object
"""
line_dict["x_data"].append(theta)
line_dict["y_data"].append(cross_prod)
line_dict["line"].set_data(line_dict["x_data"], line_dict["y_data"])
return line_dict["line"]
def animate(theta: float, arrows: Quiver, info: Text,
line_dict: LineDict, mag1: float, mag2: float) -> List[Artist]:
"""Update all plots with new data.
Parameters
----------
theta : `float`
The angle above and below the x-axis for each vector
arrows : `Quiver`
The vector arrows
info : `Text`
The text stating the cross product
line_dict : `LineDict`
Has the line object and associated x and y data
Returns
-------
`List[Artist]`
The updated artists
"""
cross_prod = update_plt_1(arrows, info, theta, mag1, mag2)
update_plt_2(line_dict, theta, cross_prod)
return [arrows, info, line_dict["line"]]
def main() -> None:
"""Run all executable code."""
parser = ArgumentParser(
prog="python3.8 vec.py",
description="Show an animation of vector cross products.",
)
parser.add_argument("mag1", type=float, help="Magnitude of vector 1")
parser.add_argument("mag2", type=float, help="Magnitude of vector 2")
args = parser.parse_args()
setup_plt()
fig: Figure = plt.figure(figsize=(9, 4.5), dpi=140)
plt_1: Axes = fig.add_subplot(121)
plt_2: Axes = fig.add_subplot(122)
format_plt_1(plt_1, args.mag1, args.mag2)
format_plt_2(plt_2, args.mag1, args.mag2)
(arrows, info) = plot_quiver(plt_1, args.mag1, args.mag2)
line = plot_cross_prod_line(plt_2)
# Include line_dict and info under plt_x in future
# plt_dict = {"plt_1": plt_1, "plt_2": plt_2}
line_dict: LineDict = {"line": line, "x_data": [], "y_data": []}
format_plt()
anim = FuncAnimation( # pylint: disable=unused-variable
fig,
animate,
init_func=init_anim_factory(arrows, info, line),
fargs=(arrows, info, line_dict, args.mag1, args.mag2),
frames=np.linspace(0, math.pi, 128),
interval=1000 / 30,
repeat=False)
fig_manager: Optional[FigureManagerQT] = plt.get_current_fig_manager()
if fig_manager is not None:
fig_manager.set_window_title("Cross Product Animation")
plt.draw()
plt.show()
if __name__ == "__main__":
main()