@beff/aula 0.0.0-stage → 0.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +8 -2
- package/dist/animations.d.ts +634 -0
- package/dist/animations.js +1793 -0
- package/dist/braces.d.ts +84 -0
- package/dist/braces.js +253 -0
- package/dist/card.d.ts +17 -0
- package/dist/card.js +90 -0
- package/dist/colors-palette.d.ts +2242 -0
- package/dist/colors-palette.js +2241 -0
- package/dist/colors.d.ts +120 -0
- package/dist/colors.js +403 -0
- package/dist/curves.d.ts +10 -0
- package/dist/curves.js +128 -0
- package/dist/engine.d.ts +1595 -0
- package/dist/engine.js +3364 -0
- package/dist/errors.d.ts +19 -0
- package/dist/errors.js +25 -0
- package/dist/generated/aula.conditional-suspending-3-i32-to-void.wasm +0 -0
- package/dist/generated/aula.core.wasm +0 -0
- package/dist/generated/aula.core2.wasm +0 -0
- package/dist/generated/aula.core3.wasm +0 -0
- package/dist/generated/aula.core4.wasm +0 -0
- package/dist/generated/aula.core5.wasm +0 -0
- package/dist/generated/aula.core6.wasm +0 -0
- package/dist/generated/aula.core7.wasm +0 -0
- package/dist/generated/aula.core8.wasm +0 -0
- package/dist/generated/aula.d.ts +80 -0
- package/dist/generated/aula.js +54639 -0
- package/dist/generated/interfaces/aula-engine-engine.d.ts +983 -0
- package/dist/generated/interfaces/aula-engine-host.d.ts +10 -0
- package/dist/generated/interfaces/aula-engine-tts.d.ts +43 -0
- package/dist/generated/interfaces/aula-engine-types.d.ts +60 -0
- package/dist/geometry.d.ts +551 -0
- package/dist/geometry.js +1821 -0
- package/dist/graph.d.ts +117 -0
- package/dist/graph.js +526 -0
- package/dist/graphing.d.ts +597 -0
- package/dist/graphing.js +1504 -0
- package/dist/host.d.ts +19 -0
- package/dist/host.js +85 -0
- package/dist/index.d.ts +5 -0
- package/dist/index.js +11 -0
- package/dist/licenses/aula-g2p-NOTICE.txt +13 -0
- package/dist/licenses/espeak-ng-COPYING.txt +674 -0
- package/dist/licenses/fonts-OFL-JetBrainsMono.txt +93 -0
- package/dist/licenses/fonts-OFL-NunitoSans.txt +93 -0
- package/dist/load.d.ts +16 -0
- package/dist/load.js +69 -0
- package/dist/logo.d.ts +30 -0
- package/dist/logo.js +186 -0
- package/dist/manim.d.ts +22 -0
- package/dist/manim.js +19 -0
- package/dist/mobjects.d.ts +127 -0
- package/dist/mobjects.js +316 -0
- package/dist/pointcloud.d.ts +144 -0
- package/dist/pointcloud.js +400 -0
- package/dist/rates.d.ts +19 -0
- package/dist/rates.js +54 -0
- package/dist/run.d.ts +82 -0
- package/dist/run.js +245 -0
- package/dist/tables.d.ts +179 -0
- package/dist/tables.js +403 -0
- package/dist/tex.d.ts +8 -0
- package/dist/tex.js +257 -0
- package/dist/text-layouts.d.ts +64 -0
- package/dist/text-layouts.js +225 -0
- package/dist/text.d.ts +35 -0
- package/dist/text.js +52 -0
- package/dist/theme.d.ts +25 -0
- package/dist/theme.js +12 -0
- package/dist/user-code.d.ts +5 -0
- package/dist/user-code.js +20 -0
- package/dist/utils.d.ts +152 -0
- package/dist/utils.js +517 -0
- package/dist/vector-field.d.ts +132 -0
- package/dist/vector-field.js +361 -0
- package/package.json +45 -3
package/dist/graphing.js
ADDED
|
@@ -0,0 +1,1504 @@
|
|
|
1
|
+
// Manim CE's graphing mobjects: the scales (LinearBase, LogBase), NumberLine, UnitInterval,
|
|
2
|
+
// CoordinateSystem, Axes, NumberPlane, PolarPlane, ComplexPlane, BarChart and SampleSpace.
|
|
3
|
+
// The engine draws a number line (its line, ticks, numbers and tip); the rest is built here
|
|
4
|
+
// from engine shapes.
|
|
5
|
+
import { BLACK, DL, DOWN, DR, DecimalNumber, FRAME_HEIGHT, FRAME_WIDTH, LEFT, MED_SMALL_BUFF, MathTex, Mobject, ORIGIN, PI, Polyline, RIGHT, SMALL_BUFF, TAU, Tex, UP, UR, VGroup, WHITE, add, gradientColors, lerp, mul, norm, raw, sub, wrap, wrong, styled, YELLOW, PURE_YELLOW, } from "./engine.js";
|
|
6
|
+
import { BLUE, BLUE_D, BLUE_E, GREEN, GREEN_E, MAROON_B, DARK_GREY, LIGHT_GREY } from "./colors-palette.js";
|
|
7
|
+
import { Brace } from "./braces.js";
|
|
8
|
+
import { Arrow, Circle, DashedLine, Dot, Line, Polygon, Rectangle, Triangle } from "./geometry.js";
|
|
9
|
+
import { invertColor, interpolateColor } from "./colors.js";
|
|
10
|
+
import { insertCurves } from "./curves.js";
|
|
11
|
+
import { engine } from "./load.js";
|
|
12
|
+
import { VDict } from "./mobjects.js";
|
|
13
|
+
/** A linear scale (Manim `LinearBase`): the value is `scaleFactor` times the position. */
|
|
14
|
+
export class LinearBaseScale {
|
|
15
|
+
scaleFactor;
|
|
16
|
+
customLabels = false;
|
|
17
|
+
constructor(scaleFactor) {
|
|
18
|
+
this.scaleFactor = scaleFactor;
|
|
19
|
+
}
|
|
20
|
+
function(value) {
|
|
21
|
+
return this.scaleFactor * value;
|
|
22
|
+
}
|
|
23
|
+
inverseFunction(value) {
|
|
24
|
+
return value / this.scaleFactor;
|
|
25
|
+
}
|
|
26
|
+
}
|
|
27
|
+
/** Manim's `LinearBase(scaleFactor)`. */
|
|
28
|
+
export function LinearBase(scaleFactor = 1) {
|
|
29
|
+
return new LinearBaseScale(scaleFactor);
|
|
30
|
+
}
|
|
31
|
+
/** A logarithmic scale (Manim `LogBase`): the value is `base` to the power of the position. */
|
|
32
|
+
export class LogBaseScale {
|
|
33
|
+
base;
|
|
34
|
+
customLabels;
|
|
35
|
+
constructor(base, customLabels) {
|
|
36
|
+
this.base = base;
|
|
37
|
+
this.customLabels = customLabels;
|
|
38
|
+
}
|
|
39
|
+
function(value) {
|
|
40
|
+
return this.base ** value;
|
|
41
|
+
}
|
|
42
|
+
inverseFunction(value) {
|
|
43
|
+
if (value <= 0)
|
|
44
|
+
wrong("LogBase", "log(0) is undefined", "give values greater than 0");
|
|
45
|
+
return Math.log(value) / Math.log(this.base);
|
|
46
|
+
}
|
|
47
|
+
/** A `base^{exponent}` label for each value (Manim `get_custom_labels`). */
|
|
48
|
+
getCustomLabels(valRange, unitDecimalPlaces = 0, baseConfig = {}) {
|
|
49
|
+
return valRange.map((v) => MathTex(`${String(this.base)}^{${this.inverseFunction(v).toFixed(unitDecimalPlaces)}}`, baseConfig));
|
|
50
|
+
}
|
|
51
|
+
}
|
|
52
|
+
/** Manim's `LogBase(base, customLabels)`. */
|
|
53
|
+
export function LogBase(base = 10, customLabels = true) {
|
|
54
|
+
return new LogBaseScale(base, customLabels);
|
|
55
|
+
}
|
|
56
|
+
function fullRange(r) {
|
|
57
|
+
return [r[0], r[1], r[2] ?? 1];
|
|
58
|
+
}
|
|
59
|
+
/** Manim's `_decimal_places_from_step`: the digits after the point of the step. */
|
|
60
|
+
function placesOf(step) {
|
|
61
|
+
const s = String(step);
|
|
62
|
+
return s.includes(".") ? (s.split(".")[1]?.length ?? 0) : 0;
|
|
63
|
+
}
|
|
64
|
+
/** NumPy's `arange(start, stop, step)`. */
|
|
65
|
+
function arange(start, stop, step) {
|
|
66
|
+
const n = step > 0 ? Math.ceil((stop - start) / step) : step < 0 ? Math.ceil((start - stop) / -step) : 0;
|
|
67
|
+
return Array.from({ length: Math.max(0, n) }, (_, i) => start + i * step);
|
|
68
|
+
}
|
|
69
|
+
const defaultLabel = (t) => MathTex(t);
|
|
70
|
+
/** A number line: Manim's `NumberLine`. Its own path is the line; its submobjects are the
|
|
71
|
+
* tip (with `includeTip`), the ticks, the numbers and the labels of `addLabels`. As in Manim,
|
|
72
|
+
* the line stops at the base of the tip, and `getEnd()` is the tip point. */
|
|
73
|
+
export class NumberLineMobject extends Mobject {
|
|
74
|
+
#s;
|
|
75
|
+
#labels;
|
|
76
|
+
constructor(handle, settings) {
|
|
77
|
+
super(handle);
|
|
78
|
+
this.#s = settings;
|
|
79
|
+
}
|
|
80
|
+
copy() {
|
|
81
|
+
const c = new NumberLineMobject(raw(this).copy(), this.#s);
|
|
82
|
+
if (this.#labels !== undefined)
|
|
83
|
+
c.#labels = c.submobjects.at(-1);
|
|
84
|
+
return c;
|
|
85
|
+
}
|
|
86
|
+
/** `[min, max, step]` (Manim `x_range`). */
|
|
87
|
+
get xRange() {
|
|
88
|
+
return this.#s.xRange;
|
|
89
|
+
}
|
|
90
|
+
get scaling() {
|
|
91
|
+
return this.#s.scaling;
|
|
92
|
+
}
|
|
93
|
+
get fontSize() {
|
|
94
|
+
return this.#s.fontSize;
|
|
95
|
+
}
|
|
96
|
+
get labelConstructor() {
|
|
97
|
+
return this.#s.labelConstructor;
|
|
98
|
+
}
|
|
99
|
+
get labelDirection() {
|
|
100
|
+
return this.#s.labelDirection;
|
|
101
|
+
}
|
|
102
|
+
get lineToNumberBuff() {
|
|
103
|
+
return this.#s.lineToNumberBuff;
|
|
104
|
+
}
|
|
105
|
+
/** The point of `number` on the line (Manim `number_to_point`). */
|
|
106
|
+
numberToPoint(number) {
|
|
107
|
+
const [min, max] = this.#s.xRange;
|
|
108
|
+
return lerp(this.getStart(), this.getEnd(), (this.#s.scaling.inverseFunction(number) - min) / (max - min));
|
|
109
|
+
}
|
|
110
|
+
n2p(number) {
|
|
111
|
+
return this.numberToPoint(number);
|
|
112
|
+
}
|
|
113
|
+
/** The number at `point`, projected on the line (Manim `point_to_number`). */
|
|
114
|
+
pointToNumber(point) {
|
|
115
|
+
const [min, max] = this.#s.xRange;
|
|
116
|
+
const start = this.getStart();
|
|
117
|
+
const v = sub(this.getEnd(), start);
|
|
118
|
+
const d = sub(point, start);
|
|
119
|
+
const proportion = (d[0] * v[0] + d[1] * v[1]) / (v[0] * v[0] + v[1] * v[1]);
|
|
120
|
+
return this.#s.scaling.function(min + proportion * (max - min));
|
|
121
|
+
}
|
|
122
|
+
p2n(point) {
|
|
123
|
+
return this.pointToNumber(point);
|
|
124
|
+
}
|
|
125
|
+
/** Frame units for one unit of the line. */
|
|
126
|
+
getUnitSize() {
|
|
127
|
+
return this.getLength() / (this.#s.xRange[1] - this.#s.xRange[0]);
|
|
128
|
+
}
|
|
129
|
+
/** Rotates the line by `angle` about the point of 0 (Manim `rotate_about_zero`). */
|
|
130
|
+
rotateAboutZero(angle) {
|
|
131
|
+
return this.rotateAboutNumber(0, angle);
|
|
132
|
+
}
|
|
133
|
+
/** Rotates the line by `angle` about the point of `number` (Manim `rotate_about_number`). */
|
|
134
|
+
rotateAboutNumber(number, angle) {
|
|
135
|
+
return this.rotate(angle, { aboutPoint: this.n2p(number) });
|
|
136
|
+
}
|
|
137
|
+
/** The ticks (Manim `ticks`). */
|
|
138
|
+
get ticks() {
|
|
139
|
+
return this.#child(this.#s.includeTip ? 1 : 0);
|
|
140
|
+
}
|
|
141
|
+
/** The numbers (Manim `numbers`); empty without numbers. */
|
|
142
|
+
get numbers() {
|
|
143
|
+
return this.#child(this.#s.includeTip ? 2 : 1);
|
|
144
|
+
}
|
|
145
|
+
/** The tip, or undefined without `includeTip`. */
|
|
146
|
+
get tip() {
|
|
147
|
+
return this.#s.includeTip ? this.submobjects[0] : undefined;
|
|
148
|
+
}
|
|
149
|
+
/** The labels of `addLabels`, or undefined. */
|
|
150
|
+
get labels() {
|
|
151
|
+
return this.#labels;
|
|
152
|
+
}
|
|
153
|
+
#child(i) {
|
|
154
|
+
return this.submobjects[i] ?? wrong("NumberLine", "the number line has lost its parts");
|
|
155
|
+
}
|
|
156
|
+
/** The values of the ticks (Manim `get_tick_range`), through the scale. */
|
|
157
|
+
getTickRange() {
|
|
158
|
+
const [xMin, x, step] = this.#s.xRange;
|
|
159
|
+
const xMax = this.#s.includeTip ? x : x + 1e-6;
|
|
160
|
+
let range;
|
|
161
|
+
if ((xMin < xMax && xMax < 0) || (xMax > xMin && xMin > 0))
|
|
162
|
+
range = arange(xMin, xMax, step);
|
|
163
|
+
else {
|
|
164
|
+
const start = this.#s.excludeOriginTick ? step : 0;
|
|
165
|
+
const low = arange(start, Math.abs(xMin) + 1e-6, step).map((v) => -v);
|
|
166
|
+
const high = arange(start, xMax, step);
|
|
167
|
+
range = [...new Set([...low, ...high].map((v) => (Object.is(v, -0) ? 0 : v)))].toSorted((a, b) => a - b);
|
|
168
|
+
}
|
|
169
|
+
return range.map((v) => this.#s.scaling.function(v));
|
|
170
|
+
}
|
|
171
|
+
/** A tick at `x`, `size` above and below the line (Manim `get_tick`). */
|
|
172
|
+
getTick(x, size = this.#s.tickSize) {
|
|
173
|
+
const tick = Line(mul(DOWN, size), mul(UP, size));
|
|
174
|
+
tick.rotate(this.getAngle()).moveTo(this.numberToPoint(x));
|
|
175
|
+
return tick.setStroke(this.getStrokeColor(), { width: this.getStrokeWidth(), opacity: this.getStrokeOpacity() });
|
|
176
|
+
}
|
|
177
|
+
/** Draws the ticks again (Manim `add_ticks`). */
|
|
178
|
+
addTicks() {
|
|
179
|
+
const ticks = this.ticks;
|
|
180
|
+
ticks.remove(...ticks.submobjects);
|
|
181
|
+
const long = this.#s.numbersWithElongatedTicks.map((n) => n - this.#s.xRange[0]);
|
|
182
|
+
for (const x of this.getTickRange()) {
|
|
183
|
+
const elongated = long.some((o) => Math.abs(x - this.#s.xRange[0] - o) < 1e-8);
|
|
184
|
+
ticks.add(this.getTick(x, elongated ? this.#s.tickSize * this.#s.longerTickMultiple : this.#s.tickSize));
|
|
185
|
+
}
|
|
186
|
+
return this;
|
|
187
|
+
}
|
|
188
|
+
getTickMarks() {
|
|
189
|
+
return this.ticks;
|
|
190
|
+
}
|
|
191
|
+
/** A DecimalNumber of `x`, next to its point (Manim `get_number_mobject`). */
|
|
192
|
+
getNumberMobject(x, opts = {}) {
|
|
193
|
+
const { direction = this.#s.labelDirection, buff = this.#s.lineToNumberBuff, labelConstructor: _, ...config } = opts;
|
|
194
|
+
const number = DecimalNumber(x, { fontSize: this.#s.fontSize, ...this.#s.numberConfig, ...config });
|
|
195
|
+
number.nextTo(this.numberToPoint(x), direction, { buff });
|
|
196
|
+
if (x < 0 && this.#s.labelDirection[0] === 0)
|
|
197
|
+
number.shift(mul(LEFT, (number.submobjects[0]?.width ?? 0) / 2));
|
|
198
|
+
return number;
|
|
199
|
+
}
|
|
200
|
+
/** A number at each value, or at each tick by default (Manim `get_number_mobjects`). */
|
|
201
|
+
getNumberMobjects(...numbers) {
|
|
202
|
+
const values = numbers.filter((n) => typeof n === "number");
|
|
203
|
+
const opts = numbers.find((n) => typeof n === "object") ?? {};
|
|
204
|
+
const shown = values.length > 0 ? values : this.#defaultNumbers();
|
|
205
|
+
return VGroup(shown.map((n) => this.getNumberMobject(n, opts)));
|
|
206
|
+
}
|
|
207
|
+
#defaultNumbers() {
|
|
208
|
+
return (this.#s.numbersToInclude ?? this.getTickRange()).filter((x) => !this.#s.numbersToExclude.includes(x));
|
|
209
|
+
}
|
|
210
|
+
/** The numbers at the ticks (Manim `get_labels`). */
|
|
211
|
+
getLabels() {
|
|
212
|
+
return this.getNumberMobjects();
|
|
213
|
+
}
|
|
214
|
+
/** Draws a number at each value, or at each tick by default (Manim `add_numbers`). */
|
|
215
|
+
addNumbers(xValues, opts = {}) {
|
|
216
|
+
const { excluding = this.#s.numbersToExclude, ...rest } = opts;
|
|
217
|
+
const numbers = this.numbers;
|
|
218
|
+
numbers.remove(...numbers.submobjects);
|
|
219
|
+
for (const x of xValues ?? this.getTickRange()) {
|
|
220
|
+
if (!excluding.includes(x))
|
|
221
|
+
numbers.add(this.getNumberMobject(x, rest));
|
|
222
|
+
}
|
|
223
|
+
return this;
|
|
224
|
+
}
|
|
225
|
+
/** Puts a label at each value (Manim `add_labels`): a string with the default MathTex is a
|
|
226
|
+
* `Tex`, as in Manim. */
|
|
227
|
+
addLabels(dictValues, opts = {}) {
|
|
228
|
+
const { direction = this.#s.labelDirection, buff = this.#s.lineToNumberBuff, fontSize = this.#s.fontSize, labelConstructor = this.#s.labelConstructor, } = opts;
|
|
229
|
+
const entries = dictValues instanceof Map ? [...dictValues] : Object.entries(dictValues).map(([k, v]) => [Number(k), v]);
|
|
230
|
+
const labels = VGroup();
|
|
231
|
+
for (const [x, value] of entries) {
|
|
232
|
+
const label = value instanceof Mobject
|
|
233
|
+
? value
|
|
234
|
+
: typeof value === "string" && labelConstructor === defaultLabel
|
|
235
|
+
? Tex(value)
|
|
236
|
+
: labelConstructor(String(value), { fontSize });
|
|
237
|
+
if (label.fontSize > 0)
|
|
238
|
+
label.scale(fontSize / label.fontSize);
|
|
239
|
+
labels.add(label.nextTo(this.numberToPoint(x), direction, { buff }));
|
|
240
|
+
}
|
|
241
|
+
if (this.#labels !== undefined)
|
|
242
|
+
this.remove(this.#labels);
|
|
243
|
+
this.#labels = labels;
|
|
244
|
+
this.add(labels);
|
|
245
|
+
return this;
|
|
246
|
+
}
|
|
247
|
+
/** A label of text, a number or a mobject, made with the label constructor. */
|
|
248
|
+
createLabelTex(label) {
|
|
249
|
+
return label instanceof Mobject ? label : this.#s.labelConstructor(String(label), {});
|
|
250
|
+
}
|
|
251
|
+
}
|
|
252
|
+
/** A number line (Manim `NumberLine`): `NumberLine({ xRange: [0, 10, 2], length: 8, includeNumbers: true })`. */
|
|
253
|
+
export function NumberLine(opts = {}) {
|
|
254
|
+
const xRange = fullRange(opts.xRange ?? [-7, 7, 1]);
|
|
255
|
+
const scaling = opts.scaling ?? LinearBase();
|
|
256
|
+
const numberConfig = opts.decimalNumberConfig ?? {};
|
|
257
|
+
const places = numberConfig.numDecimalPlaces ?? placesOf(xRange[2]);
|
|
258
|
+
if (!Number.isSafeInteger(places) || places < 0 || places > 100) {
|
|
259
|
+
wrong("NumberLine", `decimalNumberConfig.numDecimalPlaces must be a whole number from 0 to 100; got ${String(places)}`);
|
|
260
|
+
}
|
|
261
|
+
const plain = scaling instanceof LinearBaseScale && scaling.scaleFactor === 1;
|
|
262
|
+
const includeNumbers = opts.includeNumbers ?? false;
|
|
263
|
+
const settings = {
|
|
264
|
+
xRange,
|
|
265
|
+
tickSize: opts.tickSize ?? 0.1,
|
|
266
|
+
longerTickMultiple: opts.longerTickMultiple ?? 2,
|
|
267
|
+
numbersWithElongatedTicks: opts.numbersWithElongatedTicks ?? [],
|
|
268
|
+
includeTip: opts.includeTip ?? false,
|
|
269
|
+
excludeOriginTick: opts.excludeOriginTick ?? false,
|
|
270
|
+
labelDirection: opts.labelDirection ?? DOWN,
|
|
271
|
+
lineToNumberBuff: opts.lineToNumberBuff ?? MED_SMALL_BUFF,
|
|
272
|
+
fontSize: opts.fontSize ?? 36,
|
|
273
|
+
numberConfig: { ...numberConfig, numDecimalPlaces: places },
|
|
274
|
+
numbersToExclude: opts.numbersToExclude ?? [],
|
|
275
|
+
numbersToInclude: opts.numbersToInclude,
|
|
276
|
+
scaling,
|
|
277
|
+
labelConstructor: opts.labelConstructor ?? defaultLabel,
|
|
278
|
+
};
|
|
279
|
+
const handle = engine.numberLine({
|
|
280
|
+
xRange,
|
|
281
|
+
...(opts.length === undefined ? {} : { length: opts.length }),
|
|
282
|
+
unitSize: opts.unitSize ?? 1,
|
|
283
|
+
includeTicks: opts.includeTicks ?? true,
|
|
284
|
+
tickSize: settings.tickSize,
|
|
285
|
+
numbersWithElongatedTicks: Float64Array.from(settings.numbersWithElongatedTicks),
|
|
286
|
+
longerTickMultiple: settings.longerTickMultiple,
|
|
287
|
+
excludeOriginTick: settings.excludeOriginTick,
|
|
288
|
+
rotation: opts.rotation ?? 0,
|
|
289
|
+
strokeWidth: opts.strokeWidth ?? 2,
|
|
290
|
+
color: opts.color ?? WHITE,
|
|
291
|
+
includeTip: settings.includeTip,
|
|
292
|
+
tipWidth: opts.tipWidth ?? 0.35,
|
|
293
|
+
tipHeight: opts.tipHeight ?? 0.35,
|
|
294
|
+
includeNumbers: includeNumbers && plain,
|
|
295
|
+
fontSize: settings.fontSize,
|
|
296
|
+
labelDirection: settings.labelDirection,
|
|
297
|
+
lineToNumberBuff: settings.lineToNumberBuff,
|
|
298
|
+
numDecimalPlaces: places,
|
|
299
|
+
numbersToExclude: Float64Array.from(settings.numbersToExclude),
|
|
300
|
+
...(opts.numbersToInclude === undefined ? {} : { numbersToInclude: Float64Array.from(opts.numbersToInclude) }),
|
|
301
|
+
});
|
|
302
|
+
const line = new NumberLineMobject(handle, settings);
|
|
303
|
+
if (opts.tipShape !== undefined && settings.includeTip) {
|
|
304
|
+
const [start, end, angle] = [line.getStart(), line.getEnd(), line.getAngle()];
|
|
305
|
+
const old = line.tip;
|
|
306
|
+
if (old !== undefined)
|
|
307
|
+
line.remove(old);
|
|
308
|
+
const tip = opts.tipShape({ length: opts.tipHeight ?? 0.35, width: opts.tipWidth ?? 0.35 });
|
|
309
|
+
tip.setColor(opts.color ?? WHITE).setStroke(opts.color ?? WHITE, { width: opts.strokeWidth ?? 2 });
|
|
310
|
+
tip.rotate(angle - tip.tipAngle).shift(sub(end, tip.tipPoint));
|
|
311
|
+
// As Manim's add_tip: the line stops at the base of the tip, which is the first child.
|
|
312
|
+
const ps = line.getPoints();
|
|
313
|
+
const k = norm(sub(tip.base, start)) / norm(sub(ps.at(-1) ?? end, start));
|
|
314
|
+
line.setPoints(ps.map((p) => add(start, mul(sub(p, start), k))));
|
|
315
|
+
line.insert(0, tip);
|
|
316
|
+
}
|
|
317
|
+
if (includeNumbers && !plain) {
|
|
318
|
+
if (scaling.customLabels && scaling.getCustomLabels !== undefined) {
|
|
319
|
+
const ticks = line.getTickRange();
|
|
320
|
+
const labels = scaling.getCustomLabels(ticks, places);
|
|
321
|
+
line.addLabels(new Map(ticks.map((t, i) => [t, labels[i] ?? String(t)])));
|
|
322
|
+
}
|
|
323
|
+
else
|
|
324
|
+
line.addNumbers(opts.numbersToInclude);
|
|
325
|
+
}
|
|
326
|
+
return line;
|
|
327
|
+
}
|
|
328
|
+
/** The interval from 0 to 1 (Manim `UnitInterval`): ticks every 0.1, 10 units long. */
|
|
329
|
+
export function UnitInterval(opts = {}) {
|
|
330
|
+
const { unitSize = 10, numbersWithElongatedTicks = [0, 1], decimalNumberConfig = { numDecimalPlaces: 1 }, ...rest } = opts;
|
|
331
|
+
return NumberLine({ xRange: [0, 1, 0.1], unitSize, numbersWithElongatedTicks, decimalNumberConfig, ...rest });
|
|
332
|
+
}
|
|
333
|
+
// --- coordinate systems ----------------------------------------------------------------------
|
|
334
|
+
/** Manim's `_origin_shift`: the number of an axis that is at the origin of the axes. */
|
|
335
|
+
function originShift(r) {
|
|
336
|
+
return r[0] > 0 ? r[0] : r[1] < 0 ? r[1] : 0;
|
|
337
|
+
}
|
|
338
|
+
/** Manim's `shift_onto_screen`: moves an edge that is out of the frame onto it. */
|
|
339
|
+
function shiftOntoScreen(mobject, buff) {
|
|
340
|
+
for (const v of [UP, DOWN, LEFT, RIGHT]) {
|
|
341
|
+
const half = (v[0] === 0 ? FRAME_HEIGHT : FRAME_WIDTH) / 2;
|
|
342
|
+
const edge = mobject.getCriticalPoint(v);
|
|
343
|
+
if (edge[0] * v[0] + edge[1] * v[1] > half - buff)
|
|
344
|
+
mobject.toEdge(v, { buff });
|
|
345
|
+
}
|
|
346
|
+
}
|
|
347
|
+
/** A function of x that `plot` drew (Manim `ParametricFunction` with `underlying_function`). */
|
|
348
|
+
export class PlotMobject extends Mobject {
|
|
349
|
+
/** The function (Manim `underlying_function`). */
|
|
350
|
+
underlyingFunction;
|
|
351
|
+
/** The point of the curve at `t` (Manim `function`). */
|
|
352
|
+
function;
|
|
353
|
+
tMin;
|
|
354
|
+
tMax;
|
|
355
|
+
constructor(handle, f, point, range) {
|
|
356
|
+
super(handle);
|
|
357
|
+
this.underlyingFunction = f;
|
|
358
|
+
this.function = point;
|
|
359
|
+
this.tMin = range[0];
|
|
360
|
+
this.tMax = range[1];
|
|
361
|
+
}
|
|
362
|
+
copy() {
|
|
363
|
+
return new PlotMobject(raw(this).copy(), this.underlyingFunction, this.function, [this.tMin, this.tMax]);
|
|
364
|
+
}
|
|
365
|
+
}
|
|
366
|
+
/** A smooth curve through `point(t)` at `t` from `range[0]` to `range[1]` every `range[2]`. */
|
|
367
|
+
function curveThrough(point, range) {
|
|
368
|
+
const ts = [...arange(range[0], range[1], range[2]), range[1]];
|
|
369
|
+
const samples = ts.map(point).filter((p) => Number.isFinite(p[0]) && Number.isFinite(p[1]));
|
|
370
|
+
if (samples.length < 2)
|
|
371
|
+
return wrong("plot", "the function has fewer than two finite points in the range");
|
|
372
|
+
return Polyline(samples).setPointsSmoothly(samples);
|
|
373
|
+
}
|
|
374
|
+
/** The common part of Axes and the planes: Manim's `CoordinateSystem`. */
|
|
375
|
+
export class CoordinateSystem extends Mobject {
|
|
376
|
+
xRange;
|
|
377
|
+
yRange;
|
|
378
|
+
xLength;
|
|
379
|
+
yLength;
|
|
380
|
+
/** The labels of `addCoordinates` (Manim `coordinate_labels`). */
|
|
381
|
+
coordinateLabels;
|
|
382
|
+
constructor(handle, opts) {
|
|
383
|
+
super(handle);
|
|
384
|
+
this.xRange = fullRange(opts.xRange ?? [-7, 7, 1]);
|
|
385
|
+
this.yRange = fullRange(opts.yRange ?? [-4, 4, 1]);
|
|
386
|
+
this.xLength = opts.xLength;
|
|
387
|
+
this.yLength = opts.yLength;
|
|
388
|
+
}
|
|
389
|
+
/** The point of the polar coordinates (Manim `polar_to_point`). */
|
|
390
|
+
polarToPoint(radius, azimuth) {
|
|
391
|
+
return this.coordsToPoint(radius * Math.cos(azimuth), radius * Math.sin(azimuth));
|
|
392
|
+
}
|
|
393
|
+
/** The polar coordinates `[radius, azimuth]` of `point` (Manim `point_to_polar`). */
|
|
394
|
+
pointToPolar(point) {
|
|
395
|
+
const [x, y] = this.pointToCoords(point);
|
|
396
|
+
return [Math.hypot(x, y), Math.atan2(y, x)];
|
|
397
|
+
}
|
|
398
|
+
c2p(x, y) {
|
|
399
|
+
return this.coordsToPoint(x, y);
|
|
400
|
+
}
|
|
401
|
+
p2c(point) {
|
|
402
|
+
return this.pointToCoords(point);
|
|
403
|
+
}
|
|
404
|
+
pr2pt(radius, azimuth) {
|
|
405
|
+
return this.polarToPoint(radius, azimuth);
|
|
406
|
+
}
|
|
407
|
+
pt2pr(point) {
|
|
408
|
+
return this.pointToPolar(point);
|
|
409
|
+
}
|
|
410
|
+
/** Axis `index`: 0 is x, 1 is y. */
|
|
411
|
+
getAxis(index) {
|
|
412
|
+
const axis = this.getAxes().submobjects[index];
|
|
413
|
+
return axis instanceof NumberLineMobject ? axis : wrong("getAxis", `there is no axis ${String(index)}`);
|
|
414
|
+
}
|
|
415
|
+
/** The point of the coordinates (0, 0). */
|
|
416
|
+
getOrigin() {
|
|
417
|
+
return this.coordsToPoint(0, 0);
|
|
418
|
+
}
|
|
419
|
+
getXAxis() {
|
|
420
|
+
return this.getAxis(0);
|
|
421
|
+
}
|
|
422
|
+
getYAxis() {
|
|
423
|
+
return this.getAxis(1);
|
|
424
|
+
}
|
|
425
|
+
getXUnitSize() {
|
|
426
|
+
return this.getXAxis().getUnitSize();
|
|
427
|
+
}
|
|
428
|
+
getYUnitSize() {
|
|
429
|
+
return this.getYAxis().getUnitSize();
|
|
430
|
+
}
|
|
431
|
+
#axisLabel(label, axis, edge, direction, buff) {
|
|
432
|
+
const mobject = this.getXAxis().createLabelTex(label);
|
|
433
|
+
mobject.nextTo(axis.getEdgeCenter(edge), direction, { buff });
|
|
434
|
+
shiftOntoScreen(mobject, MED_SMALL_BUFF);
|
|
435
|
+
return mobject;
|
|
436
|
+
}
|
|
437
|
+
/** A label at the right end of the x axis (Manim `get_x_axis_label`): a string is a `MathTex`. */
|
|
438
|
+
getXAxisLabel(label, opts = {}) {
|
|
439
|
+
return this.#axisLabel(label, this.getXAxis(), opts.edge ?? UR, opts.direction ?? UR, opts.buff ?? SMALL_BUFF);
|
|
440
|
+
}
|
|
441
|
+
/** A label at the top of the y axis (Manim `get_y_axis_label`). */
|
|
442
|
+
getYAxisLabel(label, opts = {}) {
|
|
443
|
+
return this.#axisLabel(label, this.getYAxis(), opts.edge ?? UR, opts.direction ?? [1, 0.5], opts.buff ?? SMALL_BUFF);
|
|
444
|
+
}
|
|
445
|
+
/** Both labels, as a VGroup (Manim `get_axis_labels`). */
|
|
446
|
+
getAxisLabels(xLabel = "x", yLabel = "y") {
|
|
447
|
+
return VGroup(this.getXAxisLabel(xLabel), this.getYAxisLabel(yLabel));
|
|
448
|
+
}
|
|
449
|
+
/** Numbers or labels on each axis (Manim `add_coordinates`): for each axis, a list of values,
|
|
450
|
+
* an object of value to label, or undefined for the ticks. */
|
|
451
|
+
addCoordinates(...axesNumbers) {
|
|
452
|
+
const labels = VGroup();
|
|
453
|
+
const axes = this.getAxes().submobjects.filter((a) => a instanceof NumberLineMobject);
|
|
454
|
+
axes.forEach((axis, i) => {
|
|
455
|
+
const values = axesNumbers[i];
|
|
456
|
+
if (isLabelDict(values)) {
|
|
457
|
+
axis.addLabels(values);
|
|
458
|
+
if (axis.labels !== undefined)
|
|
459
|
+
labels.add(axis.labels);
|
|
460
|
+
}
|
|
461
|
+
else if (values === undefined && axis.scaling.customLabels && axis.scaling.getCustomLabels !== undefined) {
|
|
462
|
+
const ticks = axis.getTickRange();
|
|
463
|
+
const custom = axis.scaling.getCustomLabels(ticks);
|
|
464
|
+
axis.addLabels(new Map(ticks.map((t, k) => [t, custom[k] ?? String(t)])));
|
|
465
|
+
if (axis.labels !== undefined)
|
|
466
|
+
labels.add(axis.labels);
|
|
467
|
+
}
|
|
468
|
+
else {
|
|
469
|
+
axis.addNumbers(values);
|
|
470
|
+
labels.add(axis.numbers);
|
|
471
|
+
}
|
|
472
|
+
});
|
|
473
|
+
this.coordinateLabels = labels;
|
|
474
|
+
return this;
|
|
475
|
+
}
|
|
476
|
+
/** A line from axis `index` to `point`, a DashedLine by default (Manim
|
|
477
|
+
* `get_line_from_axis_to_point`). */
|
|
478
|
+
getLineFromAxisToPoint(index, point, opts = {}) {
|
|
479
|
+
const { lineFunc = (a, b, style) => DashedLine(a, b, style), lineConfig = {}, color = WHITE, strokeWidth = 2, } = opts;
|
|
480
|
+
const axis = this.getAxis(index);
|
|
481
|
+
const start = axis.getStart();
|
|
482
|
+
const v = sub(axis.getEnd(), start);
|
|
483
|
+
const t = ((point[0] - start[0]) * v[0] + (point[1] - start[1]) * v[1]) / (v[0] * v[0] + v[1] * v[1]);
|
|
484
|
+
return lineFunc(add(start, mul(v, t)), point, { ...lineConfig, color, strokeWidth });
|
|
485
|
+
}
|
|
486
|
+
/** A line from the x axis up or down to `point` (Manim `get_vertical_line`). */
|
|
487
|
+
getVerticalLine(point, opts = {}) {
|
|
488
|
+
return this.getLineFromAxisToPoint(0, point, opts);
|
|
489
|
+
}
|
|
490
|
+
/** A line from the y axis across to `point` (Manim `get_horizontal_line`). */
|
|
491
|
+
getHorizontalLine(point, opts = {}) {
|
|
492
|
+
return this.getLineFromAxisToPoint(1, point, opts);
|
|
493
|
+
}
|
|
494
|
+
/** The horizontal and the vertical line to `point` (Manim `get_lines_to_point`). */
|
|
495
|
+
getLinesToPoint(point, opts = {}) {
|
|
496
|
+
return VGroup(this.getHorizontalLine(point, opts), this.getVerticalLine(point, opts));
|
|
497
|
+
}
|
|
498
|
+
/** The graph of `function` (Manim `plot`): a smooth curve through samples, 10 for each step
|
|
499
|
+
* of `xRange` (or every `xRange[2]` with a step). */
|
|
500
|
+
plot(fn, opts = {}) {
|
|
501
|
+
const { xRange: r, useVectorized: _, colorscale, colorscaleAxis = 1, ...style } = opts;
|
|
502
|
+
const t = [...this.xRange];
|
|
503
|
+
if (r !== undefined) {
|
|
504
|
+
t[0] = r[0];
|
|
505
|
+
t[1] = r[1];
|
|
506
|
+
if (r[2] !== undefined)
|
|
507
|
+
t[2] = r[2];
|
|
508
|
+
}
|
|
509
|
+
if (r === undefined || r.length < 3)
|
|
510
|
+
t[2] /= 10;
|
|
511
|
+
const point = (x) => this.c2p(x, fn(x));
|
|
512
|
+
const curve = styled(curveThrough(point, t), style);
|
|
513
|
+
const graph = new PlotMobject(raw(curve), fn, point, [t[0], t[1]]);
|
|
514
|
+
if (colorscale !== undefined && colorscale.length > 0)
|
|
515
|
+
this.#colorscale(graph, colorscale, colorscaleAxis, t);
|
|
516
|
+
return graph;
|
|
517
|
+
}
|
|
518
|
+
/** Manim's `colorscale` of `plot`: each curve of the graph, from one sample to the next,
|
|
519
|
+
* becomes a submobject in the colour of its first sample; the graph's own stroke is hidden. */
|
|
520
|
+
#colorscale(graph, colorscale, axis, t) {
|
|
521
|
+
const pairs = colorscale.every((c) => Array.isArray(c) && c.length === 2 && typeof c[1] === "number");
|
|
522
|
+
// oxlint-disable-next-line typescript/no-unsafe-type-assertion -- `pairs` checked the form
|
|
523
|
+
const pivoted = pairs ? colorscale : undefined;
|
|
524
|
+
// oxlint-disable-next-line typescript/no-unsafe-type-assertion -- without pairs, each item is a colour
|
|
525
|
+
const colors = pivoted?.map((p) => p[0]) ?? colorscale;
|
|
526
|
+
const range = axis === 0 ? this.xRange : this.yRange;
|
|
527
|
+
const pivots = pivoted?.map((p) => p[1]) ??
|
|
528
|
+
colors.map((_, i) => range[0] + ((range[1] - range[0]) * i) / Math.max(1, colors.length - 1));
|
|
529
|
+
const colorAt = (v) => {
|
|
530
|
+
const first = pivots[0] ?? 0;
|
|
531
|
+
if (v <= first)
|
|
532
|
+
return interpolateColor(colors[0] ?? WHITE, colors[0] ?? WHITE, 0);
|
|
533
|
+
const i = pivots.findIndex((p) => p > v);
|
|
534
|
+
if (i < 0)
|
|
535
|
+
return interpolateColor(colors.at(-1) ?? WHITE, colors.at(-1) ?? WHITE, 0);
|
|
536
|
+
const [p0, p1] = [pivots[i - 1] ?? first, pivots[i] ?? first];
|
|
537
|
+
return interpolateColor(colors[i - 1] ?? WHITE, colors[i] ?? WHITE, Math.min((v - p0) / (p1 - p0), 1));
|
|
538
|
+
};
|
|
539
|
+
const xs = [...arange(t[0], t[1], t[2]), t[1]];
|
|
540
|
+
const points = graph.getPoints();
|
|
541
|
+
const width = graph.getStrokeWidth();
|
|
542
|
+
for (let i = 0; i + 3 < points.length; i += 4) {
|
|
543
|
+
const x = xs[i / 4] ?? t[1];
|
|
544
|
+
const value = axis === 0 ? x : graph.underlyingFunction(x);
|
|
545
|
+
const piece = Polyline(ORIGIN, ORIGIN).setPoints(points.slice(i, i + 4));
|
|
546
|
+
graph.add(piece.setStroke(colorAt(value), { width }));
|
|
547
|
+
}
|
|
548
|
+
graph.setStroke({ opacity: 0 }).submobjects.forEach((p) => p.setStroke({ opacity: 1 }));
|
|
549
|
+
}
|
|
550
|
+
/** The curve where `func(x, y)` is 0 (Manim `plot_implicit_curve`), by marching squares on
|
|
551
|
+
* a grid of about `maxQuads` cells. */
|
|
552
|
+
plotImplicitCurve(func, opts = {}) {
|
|
553
|
+
const { minDepth = 5, maxQuads = 1500, ...style } = opts;
|
|
554
|
+
const side = Math.max(2 ** Math.max(1, minDepth), Math.round(Math.sqrt(maxQuads)));
|
|
555
|
+
const [x0, x1] = this.xRange;
|
|
556
|
+
const [y0, y1] = this.yRange;
|
|
557
|
+
const segments = marchingSquares(func, [x0, x1], [y0, y1], side);
|
|
558
|
+
const parts = joinSegments(segments).map((path) => {
|
|
559
|
+
const pts = path.map(([x, y]) => this.c2p(x, y));
|
|
560
|
+
return Polyline(pts);
|
|
561
|
+
});
|
|
562
|
+
return styled(VGroup(parts), style);
|
|
563
|
+
}
|
|
564
|
+
/** The curve of `function(t)` = `[x, y]` in coordinates (Manim `plot_parametric_curve`). */
|
|
565
|
+
plotParametricCurve(fn, opts = {}) {
|
|
566
|
+
const { tRange = [0, 1, 0.01], useVectorized: _, ...style } = opts;
|
|
567
|
+
const point = (t) => {
|
|
568
|
+
const [x, y] = fn(t);
|
|
569
|
+
return this.c2p(x, y);
|
|
570
|
+
};
|
|
571
|
+
return styled(curveThrough(point, fullRange(tRange)), style);
|
|
572
|
+
}
|
|
573
|
+
/** The curve of `rFunc(theta)` in polar coordinates (Manim `plot_polar_graph`). */
|
|
574
|
+
plotPolarGraph(rFunc, opts = {}) {
|
|
575
|
+
const { thetaRange = [0, TAU, 0.01], ...style } = opts;
|
|
576
|
+
const range = fullRange(thetaRange);
|
|
577
|
+
if (thetaRange.length < 3)
|
|
578
|
+
range[2] = 0.01;
|
|
579
|
+
return styled(curveThrough((th) => this.pr2pt(rFunc(th), th), range), style);
|
|
580
|
+
}
|
|
581
|
+
/** The point of `graph` at `x` (Manim `input_to_graph_point`). */
|
|
582
|
+
inputToGraphPoint(x, graph) {
|
|
583
|
+
if (graph instanceof PlotMobject)
|
|
584
|
+
return graph.function(x);
|
|
585
|
+
let [lo, hi] = [0, 1];
|
|
586
|
+
const xAt = (a) => this.pointToCoords(graph.pointFromProportion(a))[0];
|
|
587
|
+
const increasing = xAt(1) >= xAt(0);
|
|
588
|
+
for (let i = 0; i < 60; i++) {
|
|
589
|
+
const mid = (lo + hi) / 2;
|
|
590
|
+
if (xAt(mid) < x === increasing)
|
|
591
|
+
lo = mid;
|
|
592
|
+
else
|
|
593
|
+
hi = mid;
|
|
594
|
+
}
|
|
595
|
+
const p = graph.pointFromProportion((lo + hi) / 2);
|
|
596
|
+
if (Math.abs(this.pointToCoords(p)[0] - x) > 1e-3) {
|
|
597
|
+
wrong("inputToGraphPoint", `x=${String(x)} is not in the range of the graph`);
|
|
598
|
+
}
|
|
599
|
+
return p;
|
|
600
|
+
}
|
|
601
|
+
/** `[x, f(x)]` (Manim `input_to_graph_coords`). */
|
|
602
|
+
inputToGraphCoords(x, graph) {
|
|
603
|
+
return [x, graph.underlyingFunction(x)];
|
|
604
|
+
}
|
|
605
|
+
i2gc(x, graph) {
|
|
606
|
+
return this.inputToGraphCoords(x, graph);
|
|
607
|
+
}
|
|
608
|
+
i2gp(x, graph) {
|
|
609
|
+
return this.inputToGraphPoint(x, graph);
|
|
610
|
+
}
|
|
611
|
+
/** A label of `graph` (Manim `get_graph_label`): at `xVal`, or at the right end that is in
|
|
612
|
+
* the frame, in the colour of the graph. */
|
|
613
|
+
getGraphLabel(graph, label = "f(x)", opts = {}) {
|
|
614
|
+
const { xVal, direction = RIGHT, buff = MED_SMALL_BUFF, color = graph.getStrokeColor(), dot = false, dotConfig = {}, } = opts;
|
|
615
|
+
const labelMob = this.getXAxis().createLabelTex(label).setColor(color);
|
|
616
|
+
let point;
|
|
617
|
+
if (xVal === undefined) {
|
|
618
|
+
point = this.inputToGraphPoint(this.xRange[0], graph);
|
|
619
|
+
for (let k = 0; k < 100; k++) {
|
|
620
|
+
const x = this.xRange[1] + ((this.xRange[0] - this.xRange[1]) * k) / 99;
|
|
621
|
+
const p = this.inputToGraphPoint(x, graph);
|
|
622
|
+
if (p[1] < FRAME_HEIGHT / 2) {
|
|
623
|
+
point = p;
|
|
624
|
+
break;
|
|
625
|
+
}
|
|
626
|
+
}
|
|
627
|
+
}
|
|
628
|
+
else
|
|
629
|
+
point = this.inputToGraphPoint(xVal, graph);
|
|
630
|
+
labelMob.nextTo(point, direction, { buff });
|
|
631
|
+
shiftOntoScreen(labelMob, MED_SMALL_BUFF);
|
|
632
|
+
if (dot)
|
|
633
|
+
labelMob.add(Dot(point, dotConfig));
|
|
634
|
+
return labelMob;
|
|
635
|
+
}
|
|
636
|
+
/** Rectangles under `graph` from `xRange` every `dx` (Manim `get_riemann_rectangles`). */
|
|
637
|
+
getRiemannRectangles(graph, opts = {}) {
|
|
638
|
+
const { dx = 0.1, inputSampleType = "left", strokeWidth = 1, strokeColor = BLACK, fillOpacity = 1, color = [BLUE, GREEN], showSignedArea = true, boundedGraph, blend = false, widthScaleFactor = 1.001, } = opts;
|
|
639
|
+
const range = opts.xRange ??
|
|
640
|
+
(boundedGraph === undefined
|
|
641
|
+
? [graph.tMin, graph.tMax]
|
|
642
|
+
: [Math.max(graph.tMin, boundedGraph.tMin), Math.min(graph.tMax, boundedGraph.tMax)]);
|
|
643
|
+
const xs = arange(range[0], range[1], dx);
|
|
644
|
+
const colors = gradientColors(typeof color === "string" ? [color] : color, xs.length);
|
|
645
|
+
const offset = { left: 0, right: dx, center: dx / 2 }[inputSampleType];
|
|
646
|
+
const rects = xs.map((x, i) => {
|
|
647
|
+
const graphPoint = this.inputToGraphPoint(x + offset, graph);
|
|
648
|
+
const y = boundedGraph === undefined ? originShift(this.yRange) : boundedGraph.underlyingFunction(x);
|
|
649
|
+
const corners = [this.c2p(x, y), this.c2p(x + widthScaleFactor * dx, y), graphPoint];
|
|
650
|
+
const [left, right] = [Math.min(...corners.map((c) => c[0])), Math.max(...corners.map((c) => c[0]))];
|
|
651
|
+
const [bottom, top] = [Math.min(...corners.map((c) => c[1])), Math.max(...corners.map((c) => c[1]))];
|
|
652
|
+
const rect = Rectangle({ width: Math.max(right - left, 1e-9), height: Math.max(top - bottom, 1e-9) }).moveTo([
|
|
653
|
+
(left + right) / 2,
|
|
654
|
+
(bottom + top) / 2,
|
|
655
|
+
]);
|
|
656
|
+
let c = colors[i] ?? BLUE;
|
|
657
|
+
if (this.p2c(graphPoint)[1] < y && showSignedArea)
|
|
658
|
+
c = invertColor(c);
|
|
659
|
+
rect.setFill(c, { opacity: fillOpacity }).setStroke(blend ? c : strokeColor, { width: strokeWidth });
|
|
660
|
+
return rect;
|
|
661
|
+
});
|
|
662
|
+
return VGroup(rects);
|
|
663
|
+
}
|
|
664
|
+
/** The area between `graph` and the x axis, or `boundedGraph` (Manim `get_area`). A list of
|
|
665
|
+
* colours fills with the first. */
|
|
666
|
+
getArea(graph, opts = {}) {
|
|
667
|
+
const { xRange, color = [BLUE, GREEN], opacity = 0.3, boundedGraph, ...style } = opts;
|
|
668
|
+
let [a, b] = xRange ?? [graph.tMin, graph.tMax];
|
|
669
|
+
if (boundedGraph !== undefined) {
|
|
670
|
+
if (boundedGraph.tMin > b || boundedGraph.tMax < a)
|
|
671
|
+
wrong("getArea", "the ranges of the two graphs do not overlap");
|
|
672
|
+
a = Math.max(a, boundedGraph.tMin);
|
|
673
|
+
b = Math.min(b, boundedGraph.tMax);
|
|
674
|
+
}
|
|
675
|
+
const inside = (g) => [
|
|
676
|
+
g.function(a),
|
|
677
|
+
...g.getPoints().filter((p) => {
|
|
678
|
+
const x = this.p2c(p)[0];
|
|
679
|
+
return a <= x && x <= b;
|
|
680
|
+
}),
|
|
681
|
+
g.function(b),
|
|
682
|
+
];
|
|
683
|
+
const points = boundedGraph === undefined
|
|
684
|
+
? [this.c2p(a, 0), ...inside(graph), this.c2p(b, 0)]
|
|
685
|
+
: [...inside(graph), ...inside(boundedGraph).toReversed()];
|
|
686
|
+
const area = Polygon(points, style).setOpacity(opacity);
|
|
687
|
+
const first = typeof color === "string" ? color : (color[0] ?? BLUE);
|
|
688
|
+
return area.setColor(first).setFill(first, { opacity }).setStroke(first, { opacity });
|
|
689
|
+
}
|
|
690
|
+
/** The angle of the tangent of `graph` at `x`, in coordinates (Manim `angle_of_tangent`). */
|
|
691
|
+
angleOfTangent(x, graph, dx = 1e-8) {
|
|
692
|
+
const [x0, y0] = this.inputToGraphCoords(x, graph);
|
|
693
|
+
const [x1, y1] = this.inputToGraphCoords(x + dx, graph);
|
|
694
|
+
return Math.atan2(y1 - y0, x1 - x0);
|
|
695
|
+
}
|
|
696
|
+
/** The slope of the tangent of `graph` at `x` (Manim `slope_of_tangent`). */
|
|
697
|
+
slopeOfTangent(x, graph, opts = {}) {
|
|
698
|
+
return Math.tan(this.angleOfTangent(x, graph, opts.dx));
|
|
699
|
+
}
|
|
700
|
+
/** The graph of the derivative of `graph` (Manim `plot_derivative_graph`). */
|
|
701
|
+
plotDerivativeGraph(graph, opts = {}) {
|
|
702
|
+
const { color = GREEN, ...rest } = opts;
|
|
703
|
+
return this.plot((x) => this.slopeOfTangent(x, graph), { color, ...rest });
|
|
704
|
+
}
|
|
705
|
+
/** The graph of an antiderivative of `graph` through `yIntercept` at 0 (Manim
|
|
706
|
+
* `plot_antiderivative_graph`), with the trapezoid rule on `samples` points. */
|
|
707
|
+
plotAntiderivativeGraph(graph, opts = {}) {
|
|
708
|
+
const { yIntercept = 0, samples = 50, useVectorized: _, ...rest } = opts;
|
|
709
|
+
const f = graph.underlyingFunction;
|
|
710
|
+
const antiderivative = (x) => {
|
|
711
|
+
let sum = 0;
|
|
712
|
+
for (let i = 1; i < samples; i++) {
|
|
713
|
+
const [a, b] = [(x * (i - 1)) / (samples - 1), (x * i) / (samples - 1)];
|
|
714
|
+
sum += ((f(a) + f(b)) / 2) * (b - a);
|
|
715
|
+
}
|
|
716
|
+
return sum + yIntercept;
|
|
717
|
+
};
|
|
718
|
+
return this.plot(antiderivative, rest);
|
|
719
|
+
}
|
|
720
|
+
/** The lines of a secant from `x` to `x + dx` (Manim `get_secant_slope_group`): `dxLine`,
|
|
721
|
+
* `dfLine`, the labels and the secant line. */
|
|
722
|
+
getSecantSlopeGroup(x, graph, opts = {}) {
|
|
723
|
+
const { dx = (this.xRange[1] - this.xRange[0]) / 10, dxLineColor = PURE_YELLOW, dyLineColor = graph.getStrokeColor(), dxLabel, dyLabel, includeSecantLine = true, secantLineColor = GREEN, secantLineLength = 10, } = opts;
|
|
724
|
+
const p1 = this.inputToGraphPoint(x, graph);
|
|
725
|
+
const p2 = this.inputToGraphPoint(x + dx, graph);
|
|
726
|
+
const corner = [p2[0], p1[1]];
|
|
727
|
+
const dxLine = Line(p1, corner, { color: dxLineColor });
|
|
728
|
+
const dfLine = Line(corner, p2, { color: dyLineColor });
|
|
729
|
+
const group = VGroup(dxLine, dfLine);
|
|
730
|
+
const labels = [];
|
|
731
|
+
const dxMob = dxLabel === undefined ? undefined : this.getXAxis().createLabelTex(dxLabel);
|
|
732
|
+
const dyMob = dyLabel === undefined ? undefined : this.getXAxis().createLabelTex(dyLabel);
|
|
733
|
+
for (const l of [dxMob, dyMob])
|
|
734
|
+
if (l !== undefined)
|
|
735
|
+
labels.push(l);
|
|
736
|
+
if (labels.length > 0) {
|
|
737
|
+
const all = VGroup(labels);
|
|
738
|
+
if (all.width > 0.8 * dxLine.width)
|
|
739
|
+
all.width = 0.8 * dxLine.width;
|
|
740
|
+
if (all.height > 0.8 * dfLine.height)
|
|
741
|
+
all.height = 0.8 * dfLine.height;
|
|
742
|
+
}
|
|
743
|
+
if (dxMob !== undefined) {
|
|
744
|
+
dxMob.nextTo(dxLine, mul(DOWN, Math.sign(dx)), { buff: dxMob.height / 2 }).setColor(dxLineColor);
|
|
745
|
+
group.add(dxMob);
|
|
746
|
+
}
|
|
747
|
+
if (dyMob !== undefined) {
|
|
748
|
+
dyMob.nextTo(dfLine, mul(RIGHT, Math.sign(dx)), { buff: dyMob.height / 2 }).setColor(dyLineColor);
|
|
749
|
+
group.add(dyMob);
|
|
750
|
+
}
|
|
751
|
+
if (includeSecantLine) {
|
|
752
|
+
const secant = Line(p1, p2, { color: secantLineColor });
|
|
753
|
+
group.add(secant.scale(secantLineLength / secant.getLength()));
|
|
754
|
+
}
|
|
755
|
+
return group;
|
|
756
|
+
}
|
|
757
|
+
/** `numLines` vertical lines from the x axis to `graph` (Manim `get_vertical_lines_to_graph`). */
|
|
758
|
+
getVerticalLinesToGraph(graph, opts = {}) {
|
|
759
|
+
const { xRange = this.xRange, numLines = 20, ...rest } = opts;
|
|
760
|
+
const xs = Array.from({ length: numLines }, (_, i) => xRange[0] + ((xRange[1] - xRange[0]) * i) / Math.max(1, numLines - 1));
|
|
761
|
+
return VGroup(xs.map((x) => this.getVerticalLine(this.i2gp(x, graph), rest)));
|
|
762
|
+
}
|
|
763
|
+
/** A triangle under `xVal` on the x axis, a label and a vertical line to `graph` (Manim
|
|
764
|
+
* `get_T_label`). */
|
|
765
|
+
getTLabel(xVal, graph, opts = {}) {
|
|
766
|
+
const { label, labelColor, triangleSize = MED_SMALL_BUFF, triangleColor = WHITE, lineFunc = (a, b, s) => Line(a, b, s), lineColor = PURE_YELLOW, } = opts;
|
|
767
|
+
const triangle = Triangle({ strokeWidth: 0 }).setFill(triangleColor, { opacity: 1 });
|
|
768
|
+
triangle.height = triangleSize;
|
|
769
|
+
triangle.moveTo(this.coordsToPoint(xVal, 0), { alignedEdge: UP });
|
|
770
|
+
const group = VGroup();
|
|
771
|
+
if (label !== undefined) {
|
|
772
|
+
const t = this.getXAxis().createLabelTex(label);
|
|
773
|
+
if (labelColor !== undefined)
|
|
774
|
+
t.setColor(labelColor);
|
|
775
|
+
group.add(t.nextTo(triangle, DOWN));
|
|
776
|
+
}
|
|
777
|
+
group.add(triangle, this.getVerticalLine(this.i2gp(xVal, graph), { color: lineColor, lineFunc }));
|
|
778
|
+
return group;
|
|
779
|
+
}
|
|
780
|
+
}
|
|
781
|
+
function isLabelDict(v) {
|
|
782
|
+
return v !== undefined && !Array.isArray(v);
|
|
783
|
+
}
|
|
784
|
+
/** The point between `pa` and `pb` where a linear function with values `va` and `vb` is 0. */
|
|
785
|
+
function zeroCrossing(pa, va, pb, vb) {
|
|
786
|
+
return lerp(pa, pb, va / (va - vb));
|
|
787
|
+
}
|
|
788
|
+
/** The segments where `f` is 0 on a `side` × `side` grid (marching squares). */
|
|
789
|
+
function marchingSquares(f, [x0, x1], [y0, y1], side) {
|
|
790
|
+
const xs = Array.from({ length: side + 1 }, (_, i) => x0 + ((x1 - x0) * i) / side);
|
|
791
|
+
const ys = Array.from({ length: side + 1 }, (_, j) => y0 + ((y1 - y0) * j) / side);
|
|
792
|
+
const v = xs.map((x) => ys.map((y) => f(x, y)));
|
|
793
|
+
const out = [];
|
|
794
|
+
for (let i = 0; i < side; i++) {
|
|
795
|
+
for (let j = 0; j < side; j++) {
|
|
796
|
+
const corners = [
|
|
797
|
+
[[xs[i] ?? 0, ys[j] ?? 0], v[i]?.[j] ?? 0],
|
|
798
|
+
[[xs[i + 1] ?? 0, ys[j] ?? 0], v[i + 1]?.[j] ?? 0],
|
|
799
|
+
[[xs[i + 1] ?? 0, ys[j + 1] ?? 0], v[i + 1]?.[j + 1] ?? 0],
|
|
800
|
+
[[xs[i] ?? 0, ys[j + 1] ?? 0], v[i]?.[j + 1] ?? 0],
|
|
801
|
+
];
|
|
802
|
+
const hits = [];
|
|
803
|
+
for (let k = 0; k < 4; k++) {
|
|
804
|
+
const [pa, va] = corners[k] ?? [[0, 0], 0];
|
|
805
|
+
const [pb, vb] = corners[(k + 1) % 4] ?? [[0, 0], 0];
|
|
806
|
+
if (va < 0 !== vb < 0)
|
|
807
|
+
hits.push(zeroCrossing(pa, va, pb, vb));
|
|
808
|
+
}
|
|
809
|
+
if (hits.length === 2)
|
|
810
|
+
out.push([hits[0] ?? [0, 0], hits[1] ?? [0, 0]]);
|
|
811
|
+
if (hits.length === 4)
|
|
812
|
+
out.push([hits[0] ?? [0, 0], hits[1] ?? [0, 0]], [hits[2] ?? [0, 0], hits[3] ?? [0, 0]]);
|
|
813
|
+
}
|
|
814
|
+
}
|
|
815
|
+
return out;
|
|
816
|
+
}
|
|
817
|
+
/** A key of a point, for joining segments. */
|
|
818
|
+
function pointKey(p) {
|
|
819
|
+
return `${p[0].toFixed(9)},${p[1].toFixed(9)}`;
|
|
820
|
+
}
|
|
821
|
+
/** Joins segments that share ends into paths. */
|
|
822
|
+
function joinSegments(segments) {
|
|
823
|
+
const ends = new Map();
|
|
824
|
+
segments.forEach(([a, b], i) => {
|
|
825
|
+
for (const p of [a, b])
|
|
826
|
+
ends.set(pointKey(p), [...(ends.get(pointKey(p)) ?? []), i]);
|
|
827
|
+
});
|
|
828
|
+
const used = new Set();
|
|
829
|
+
const paths = [];
|
|
830
|
+
segments.forEach((seg, i) => {
|
|
831
|
+
if (used.has(i))
|
|
832
|
+
return;
|
|
833
|
+
used.add(i);
|
|
834
|
+
const path = [seg[0], seg[1]];
|
|
835
|
+
for (const forward of [true, false]) {
|
|
836
|
+
for (;;) {
|
|
837
|
+
const end = forward ? path.at(-1) : path[0];
|
|
838
|
+
if (end === undefined)
|
|
839
|
+
break;
|
|
840
|
+
const next = (ends.get(pointKey(end)) ?? []).find((k) => !used.has(k));
|
|
841
|
+
if (next === undefined)
|
|
842
|
+
break;
|
|
843
|
+
used.add(next);
|
|
844
|
+
const [a, b] = segments[next] ?? [end, end];
|
|
845
|
+
const other = pointKey(a) === pointKey(end) ? b : a;
|
|
846
|
+
if (forward)
|
|
847
|
+
path.push(other);
|
|
848
|
+
else
|
|
849
|
+
path.unshift(other);
|
|
850
|
+
}
|
|
851
|
+
}
|
|
852
|
+
paths.push(path);
|
|
853
|
+
});
|
|
854
|
+
return paths;
|
|
855
|
+
}
|
|
856
|
+
/** The two axes of `opts`, with their origins at the frame origin. */
|
|
857
|
+
function axesOf(opts, lengths) {
|
|
858
|
+
const xRange = fullRange(opts.xRange ?? [-7, 7, 1]);
|
|
859
|
+
const yRange = fullRange(opts.yRange ?? [-4, 4, 1]);
|
|
860
|
+
const common = { includeTip: opts.tips ?? true, numbersToExclude: [0], ...opts.axisConfig };
|
|
861
|
+
const axis = (range, own, length) => {
|
|
862
|
+
const line = NumberLine({
|
|
863
|
+
...common,
|
|
864
|
+
...own,
|
|
865
|
+
xRange: range,
|
|
866
|
+
...(length === undefined ? {} : { length }),
|
|
867
|
+
excludeOriginTick: true,
|
|
868
|
+
});
|
|
869
|
+
return line.shift(mul(line.n2p(originShift(range)), -1));
|
|
870
|
+
};
|
|
871
|
+
return [
|
|
872
|
+
axis(xRange, { ...opts.xAxisConfig }, lengths[0]),
|
|
873
|
+
axis(yRange, { rotation: PI / 2, labelDirection: LEFT, ...opts.yAxisConfig }, lengths[1]),
|
|
874
|
+
];
|
|
875
|
+
}
|
|
876
|
+
/** Two number lines: Manim's `Axes`. Its submobjects are the x axis and the y axis (after any
|
|
877
|
+
* background lines). */
|
|
878
|
+
export class AxesMobject extends CoordinateSystem {
|
|
879
|
+
/** The x axis (Manim `x_axis`). */
|
|
880
|
+
xAxis;
|
|
881
|
+
/** The y axis (Manim `y_axis`). */
|
|
882
|
+
yAxis;
|
|
883
|
+
constructor(handle, axes, opts) {
|
|
884
|
+
super(handle, opts);
|
|
885
|
+
[this.xAxis, this.yAxis] = axes;
|
|
886
|
+
}
|
|
887
|
+
copy() {
|
|
888
|
+
const handle = raw(this).copy();
|
|
889
|
+
return new AxesMobject(handle, copiedAxes(this, handle), this);
|
|
890
|
+
}
|
|
891
|
+
getAxes() {
|
|
892
|
+
return VGroup(this.xAxis, this.yAxis);
|
|
893
|
+
}
|
|
894
|
+
getXAxis() {
|
|
895
|
+
return this.xAxis;
|
|
896
|
+
}
|
|
897
|
+
getYAxis() {
|
|
898
|
+
return this.yAxis;
|
|
899
|
+
}
|
|
900
|
+
/** The point of the coordinates `(x, y)` (Manim `coords_to_point`). */
|
|
901
|
+
coordsToPoint(x, y) {
|
|
902
|
+
const origin = this.xAxis.n2p(this.xAxis.scaling.function(originShift(this.xRange)));
|
|
903
|
+
return add(this.xAxis.n2p(x), sub(this.yAxis.n2p(y), origin));
|
|
904
|
+
}
|
|
905
|
+
/** The coordinates of `point` (Manim `point_to_coords`). */
|
|
906
|
+
pointToCoords(point) {
|
|
907
|
+
return [this.xAxis.p2n(point), this.yAxis.p2n(point)];
|
|
908
|
+
}
|
|
909
|
+
/** A polyline through the points `(x, y)` in `lineColor`, with a dot at each (Manim
|
|
910
|
+
* `plot_line_graph`): a VDict with `line_graph` and `vertex_dots`. */
|
|
911
|
+
plotLineGraph(xValues, yValues, opts = {}) {
|
|
912
|
+
const { lineColor = PURE_YELLOW, addVertexDots = true, vertexDotRadius = 0.08, vertexDotStyle = {}, ...style } = opts;
|
|
913
|
+
if (xValues.length !== yValues.length)
|
|
914
|
+
wrong("plotLineGraph", "xValues and yValues must have the same length");
|
|
915
|
+
const vertices = xValues.map((x, i) => this.c2p(x, yValues[i] ?? 0));
|
|
916
|
+
const graph = styled(Polyline(vertices).setColor(lineColor), style);
|
|
917
|
+
const result = VDict([["line_graph", graph]]);
|
|
918
|
+
if (addVertexDots)
|
|
919
|
+
result.set("vertex_dots", VGroup(vertices.map((p) => Dot(p, { radius: vertexDotRadius, ...vertexDotStyle }))));
|
|
920
|
+
return result;
|
|
921
|
+
}
|
|
922
|
+
}
|
|
923
|
+
/** The axes of a copy: the two NumberLine children of `handle`, in the places of `of`'s axes. */
|
|
924
|
+
function copiedAxes(of, handle) {
|
|
925
|
+
const children = handle.children();
|
|
926
|
+
const at = (axis) => {
|
|
927
|
+
const i = of.submobjects.indexOf(axis);
|
|
928
|
+
const h = children[i];
|
|
929
|
+
if (h === undefined)
|
|
930
|
+
return wrong("Axes", "the axes have lost an axis");
|
|
931
|
+
const w = wrap(h);
|
|
932
|
+
return w instanceof NumberLineMobject ? w : axis.copy();
|
|
933
|
+
};
|
|
934
|
+
return [at(of.xAxis), at(of.yAxis)];
|
|
935
|
+
}
|
|
936
|
+
/** The axes, centred on the middle of the ranges. */
|
|
937
|
+
function centred(axes) {
|
|
938
|
+
const [x, y] = [axes.xRange, axes.yRange];
|
|
939
|
+
return axes.shift(mul(axes.c2p((x[0] + x[1]) / 2, (y[0] + y[1]) / 2), -1));
|
|
940
|
+
}
|
|
941
|
+
/** Two number lines that cross at the origin (Manim `Axes`): `Axes({ xRange: [0, 10, 1], yRange: [0, 100, 10] })`. */
|
|
942
|
+
export function Axes(opts = {}) {
|
|
943
|
+
const lengths = [opts.xLength ?? 12, opts.yLength ?? 6];
|
|
944
|
+
const axes = axesOf(opts, lengths);
|
|
945
|
+
return centred(new AxesMobject(engine.vGroup(axes.map(raw)), axes, { ...opts, xLength: lengths[0], yLength: lengths[1] }));
|
|
946
|
+
}
|
|
947
|
+
function lineStyle(mob, s) {
|
|
948
|
+
mob.setStroke(s.strokeColor, {
|
|
949
|
+
...(s.strokeWidth === undefined ? {} : { width: s.strokeWidth }),
|
|
950
|
+
...(s.strokeOpacity === undefined ? {} : { opacity: s.strokeOpacity }),
|
|
951
|
+
});
|
|
952
|
+
}
|
|
953
|
+
/** Manim's faded style: the numbers of the style halved. */
|
|
954
|
+
function halved(s) {
|
|
955
|
+
return {
|
|
956
|
+
...s,
|
|
957
|
+
...(s.strokeWidth === undefined ? {} : { strokeWidth: s.strokeWidth / 2 }),
|
|
958
|
+
...(s.strokeOpacity === undefined ? {} : { strokeOpacity: s.strokeOpacity / 2 }),
|
|
959
|
+
};
|
|
960
|
+
}
|
|
961
|
+
/** A grid of lines on axes: Manim's `NumberPlane`. Its first submobjects are the faded lines
|
|
962
|
+
* and the background lines. */
|
|
963
|
+
export class NumberPlaneMobject extends AxesMobject {
|
|
964
|
+
/** The background lines (Manim `background_lines`). */
|
|
965
|
+
get backgroundLines() {
|
|
966
|
+
return this.submobjects[1] ?? VGroup();
|
|
967
|
+
}
|
|
968
|
+
/** The faded lines (Manim `faded_lines`). */
|
|
969
|
+
get fadedLines() {
|
|
970
|
+
return this.submobjects[0] ?? VGroup();
|
|
971
|
+
}
|
|
972
|
+
copy() {
|
|
973
|
+
const handle = raw(this).copy();
|
|
974
|
+
const c = new NumberPlaneMobject(handle, copiedAxes(this, handle), this);
|
|
975
|
+
c.makeSmoothAfterApplyingFunctions = this.makeSmoothAfterApplyingFunctions;
|
|
976
|
+
return c;
|
|
977
|
+
}
|
|
978
|
+
getVector(coords, opts = {}) {
|
|
979
|
+
if (coords === undefined)
|
|
980
|
+
return super.getVector();
|
|
981
|
+
return Arrow(this.c2p(0, 0), this.c2p(coords[0], coords[1]), { ...opts, buff: 0 });
|
|
982
|
+
}
|
|
983
|
+
/** Splits the curves of each part to at least `numInsertedCurves`, so that a function bends
|
|
984
|
+
* the lines smoothly (Manim `prepare_for_nonlinear_transform`). */
|
|
985
|
+
prepareForNonlinearTransform(numInsertedCurves = 50) {
|
|
986
|
+
return prepareForNonlinear(this, numInsertedCurves);
|
|
987
|
+
}
|
|
988
|
+
}
|
|
989
|
+
function prepareForNonlinear(mob, numInsertedCurves) {
|
|
990
|
+
for (const part of mob.getFamily()) {
|
|
991
|
+
const points = part.getPoints();
|
|
992
|
+
const curves = points.length / 4;
|
|
993
|
+
if (curves > 0 && numInsertedCurves > curves)
|
|
994
|
+
part.setPoints(insertCurves(points, numInsertedCurves - curves));
|
|
995
|
+
}
|
|
996
|
+
return mob;
|
|
997
|
+
}
|
|
998
|
+
/** The lines of a plane parallel to `along`, every `step` of `across` (Manim
|
|
999
|
+
* `_get_lines_parallel_to_axis`): the bright lines and the faded ones. */
|
|
1000
|
+
function parallelLines(along, across, freq, ratio) {
|
|
1001
|
+
const line = Line(along.getStart(), along.getEnd());
|
|
1002
|
+
const r = ratio === 0 ? 1 : ratio;
|
|
1003
|
+
const step = freq / r;
|
|
1004
|
+
const unit = mul(across.getUnitVector(), across.getUnitSize());
|
|
1005
|
+
let [xMin, xMax] = across.xRange;
|
|
1006
|
+
if (across.xRange[0] > 0 && xMin < 0)
|
|
1007
|
+
[xMin, xMax] = [0, Math.abs(xMin) + Math.abs(xMax)];
|
|
1008
|
+
const bright = [];
|
|
1009
|
+
const faded = [];
|
|
1010
|
+
const ranges = [
|
|
1011
|
+
[0],
|
|
1012
|
+
arange(step, Math.min(xMax - xMin, xMax), step),
|
|
1013
|
+
arange(-step, Math.max(xMin - xMax, xMin), -step),
|
|
1014
|
+
];
|
|
1015
|
+
for (const inputs of ranges) {
|
|
1016
|
+
inputs.forEach((x, k) => {
|
|
1017
|
+
const l = line.copy().shift(mul(unit, x));
|
|
1018
|
+
if ((k + 1) % r === 0)
|
|
1019
|
+
bright.push(l);
|
|
1020
|
+
else
|
|
1021
|
+
faded.push(l);
|
|
1022
|
+
});
|
|
1023
|
+
}
|
|
1024
|
+
return [bright, faded];
|
|
1025
|
+
}
|
|
1026
|
+
/** Puts the background and faded lines behind the axes. */
|
|
1027
|
+
function withLines(axes, lines, bg, faded) {
|
|
1028
|
+
const background = VGroup(lines[0]);
|
|
1029
|
+
const fadedLines = VGroup(lines[1]);
|
|
1030
|
+
lineStyle(background, bg);
|
|
1031
|
+
lineStyle(fadedLines, faded ?? halved(bg));
|
|
1032
|
+
return engine.vGroup([raw(fadedLines), raw(background), ...axes.map(raw)]);
|
|
1033
|
+
}
|
|
1034
|
+
/** Manim's `NumberPlane(opts)`: the frame's grid by default, blue background lines every step. */
|
|
1035
|
+
export function NumberPlane(opts = {}) {
|
|
1036
|
+
const { backgroundLineStyle = {}, fadedLineStyle, fadedLineRatio = 1, makeSmoothAfterApplyingFunctions = true, ...axesOptions } = opts;
|
|
1037
|
+
const o = {
|
|
1038
|
+
xRange: [-FRAME_WIDTH / 2, FRAME_WIDTH / 2, 1],
|
|
1039
|
+
yRange: [-FRAME_HEIGHT / 2, FRAME_HEIGHT / 2, 1],
|
|
1040
|
+
...axesOptions,
|
|
1041
|
+
axisConfig: {
|
|
1042
|
+
strokeWidth: 2,
|
|
1043
|
+
includeTicks: false,
|
|
1044
|
+
includeTip: false,
|
|
1045
|
+
lineToNumberBuff: SMALL_BUFF,
|
|
1046
|
+
labelDirection: DR,
|
|
1047
|
+
fontSize: 24,
|
|
1048
|
+
...axesOptions.axisConfig,
|
|
1049
|
+
},
|
|
1050
|
+
yAxisConfig: { labelDirection: DR, ...axesOptions.yAxisConfig },
|
|
1051
|
+
};
|
|
1052
|
+
const axes = axesOf(o, [o.xLength, o.yLength]);
|
|
1053
|
+
const [x, y] = axes;
|
|
1054
|
+
const xLines = parallelLines(x, y, y.xRange[2], fadedLineRatio);
|
|
1055
|
+
const yLines = parallelLines(y, x, x.xRange[2], fadedLineRatio);
|
|
1056
|
+
const bg = { strokeColor: BLUE_D, strokeWidth: 2, strokeOpacity: 1, ...backgroundLineStyle };
|
|
1057
|
+
const handle = withLines(axes, [
|
|
1058
|
+
[...xLines[0], ...yLines[0]],
|
|
1059
|
+
[...xLines[1], ...yLines[1]],
|
|
1060
|
+
], bg, fadedLineStyle);
|
|
1061
|
+
const plane = new NumberPlaneMobject(handle, axes, o);
|
|
1062
|
+
plane.makeSmoothAfterApplyingFunctions = makeSmoothAfterApplyingFunctions;
|
|
1063
|
+
return centred(plane);
|
|
1064
|
+
}
|
|
1065
|
+
/** Manim's `ComplexPlane`: a NumberPlane whose points are complex numbers `[re, im]`. */
|
|
1066
|
+
export class ComplexPlaneMobject extends NumberPlaneMobject {
|
|
1067
|
+
/** The point of `number` (Manim `number_to_point`). */
|
|
1068
|
+
numberToPoint(number) {
|
|
1069
|
+
const [re, im] = typeof number === "number" ? [number, 0] : number;
|
|
1070
|
+
return this.coordsToPoint(re, im);
|
|
1071
|
+
}
|
|
1072
|
+
n2p(number) {
|
|
1073
|
+
return this.numberToPoint(number);
|
|
1074
|
+
}
|
|
1075
|
+
/** The complex number `[re, im]` at `point` (Manim `point_to_number`). */
|
|
1076
|
+
pointToNumber(point) {
|
|
1077
|
+
return this.pointToCoords(point);
|
|
1078
|
+
}
|
|
1079
|
+
p2n(point) {
|
|
1080
|
+
return this.pointToNumber(point);
|
|
1081
|
+
}
|
|
1082
|
+
/** A number at each value: on the x axis for a real value, on the y axis with `i` for an
|
|
1083
|
+
* imaginary one (Manim `get_coordinate_labels`). By default, at each tick. */
|
|
1084
|
+
getCoordinateLabels(...numbers) {
|
|
1085
|
+
const values = numbers.filter((n) => typeof n === "number" || Array.isArray(n));
|
|
1086
|
+
const opts = numbers.find((n) => typeof n === "object" && !Array.isArray(n)) ?? {};
|
|
1087
|
+
const shown = values.length > 0
|
|
1088
|
+
? values
|
|
1089
|
+
: [
|
|
1090
|
+
...this.getXAxis().getTickRange(),
|
|
1091
|
+
...this.getYAxis()
|
|
1092
|
+
.getTickRange()
|
|
1093
|
+
.filter((y) => y !== 0)
|
|
1094
|
+
.map((y) => [0, y]),
|
|
1095
|
+
];
|
|
1096
|
+
const labels = VGroup(shown.map((z) => {
|
|
1097
|
+
const [re, im] = typeof z === "number" ? [z, 0] : z;
|
|
1098
|
+
return Math.abs(im) > Math.abs(re)
|
|
1099
|
+
? this.getYAxis().getNumberMobject(im, { ...opts, unit: "i" })
|
|
1100
|
+
: this.getXAxis().getNumberMobject(re, opts);
|
|
1101
|
+
}));
|
|
1102
|
+
this.coordinateLabels = labels;
|
|
1103
|
+
return labels;
|
|
1104
|
+
}
|
|
1105
|
+
/** Adds `getCoordinateLabels(...numbers)` (Manim `add_coordinates`). */
|
|
1106
|
+
addCoordinates(...numbers) {
|
|
1107
|
+
const parts = numbers.flatMap((n) => {
|
|
1108
|
+
if (n === undefined)
|
|
1109
|
+
return [];
|
|
1110
|
+
if (typeof n === "number")
|
|
1111
|
+
return [n];
|
|
1112
|
+
if (Array.isArray(n))
|
|
1113
|
+
return [[n[0] ?? 0, n[1] ?? 0]];
|
|
1114
|
+
// oxlint-disable-next-line typescript/no-unsafe-type-assertion -- an object that is not an array is the options
|
|
1115
|
+
return [n];
|
|
1116
|
+
});
|
|
1117
|
+
return this.add(this.getCoordinateLabels(...parts));
|
|
1118
|
+
}
|
|
1119
|
+
copy() {
|
|
1120
|
+
const handle = raw(this).copy();
|
|
1121
|
+
const c = new ComplexPlaneMobject(handle, copiedAxes(this, handle), this);
|
|
1122
|
+
c.makeSmoothAfterApplyingFunctions = this.makeSmoothAfterApplyingFunctions;
|
|
1123
|
+
return c;
|
|
1124
|
+
}
|
|
1125
|
+
}
|
|
1126
|
+
/** Manim's `ComplexPlane(opts)`: the options of NumberPlane. */
|
|
1127
|
+
export function ComplexPlane(opts = {}) {
|
|
1128
|
+
const plane = NumberPlane(opts);
|
|
1129
|
+
const handle = raw(plane).copy();
|
|
1130
|
+
const c = new ComplexPlaneMobject(handle, copiedAxes(plane, handle), plane);
|
|
1131
|
+
c.makeSmoothAfterApplyingFunctions = plane.makeSmoothAfterApplyingFunctions;
|
|
1132
|
+
return c;
|
|
1133
|
+
}
|
|
1134
|
+
/** The fraction nearest to `x` with a denominator up to `max` (Python's `limit_denominator`). */
|
|
1135
|
+
function fraction(x, max) {
|
|
1136
|
+
let best = [Math.round(x), 1];
|
|
1137
|
+
for (let d = 1; d <= max; d++) {
|
|
1138
|
+
const n = Math.round(x * d);
|
|
1139
|
+
if (Math.abs(n / d - x) < Math.abs(best[0] / best[1] - x) - 1e-12)
|
|
1140
|
+
best = [n, d];
|
|
1141
|
+
}
|
|
1142
|
+
const g = (a, b) => (b === 0 ? Math.abs(a) : g(b, a % b));
|
|
1143
|
+
const k = g(best[0], best[1]) || 1;
|
|
1144
|
+
return [best[0] / k, best[1] / k];
|
|
1145
|
+
}
|
|
1146
|
+
/** Circles and rays on axes: Manim's `PolarPlane`. */
|
|
1147
|
+
export class PolarPlaneMobject extends AxesMobject {
|
|
1148
|
+
#p;
|
|
1149
|
+
constructor(handle, axes, opts, polar) {
|
|
1150
|
+
super(handle, axes, opts);
|
|
1151
|
+
this.#p = polar;
|
|
1152
|
+
}
|
|
1153
|
+
copy() {
|
|
1154
|
+
const handle = raw(this).copy();
|
|
1155
|
+
const c = new PolarPlaneMobject(handle, copiedAxes(this, handle), this, this.#p);
|
|
1156
|
+
c.makeSmoothAfterApplyingFunctions = this.makeSmoothAfterApplyingFunctions;
|
|
1157
|
+
return c;
|
|
1158
|
+
}
|
|
1159
|
+
getVector(coords, opts = {}) {
|
|
1160
|
+
if (coords === undefined)
|
|
1161
|
+
return super.getVector();
|
|
1162
|
+
return Arrow(this.c2p(0, 0), this.c2p(coords[0], coords[1]), { ...opts, buff: 0 });
|
|
1163
|
+
}
|
|
1164
|
+
prepareForNonlinearTransform(numInsertedCurves = 50) {
|
|
1165
|
+
return prepareForNonlinear(this, numInsertedCurves);
|
|
1166
|
+
}
|
|
1167
|
+
/** The label of the angle `number` (a fraction of a turn) in π or τ (Manim `get_radian_label`). */
|
|
1168
|
+
getRadianLabel(number, opts = {}) {
|
|
1169
|
+
const { fontSize = 24, ...rest } = opts;
|
|
1170
|
+
const unit = this.#p.azimuthUnits === "TAU radians" ? "\\tau" : "\\pi";
|
|
1171
|
+
const [n, d] = fraction(number * (this.#p.azimuthUnits === "TAU radians" ? 1 : 2), 100);
|
|
1172
|
+
const compact = this.#p.azimuthCompactFraction;
|
|
1173
|
+
const s = n === 0
|
|
1174
|
+
? "0"
|
|
1175
|
+
: n === 1 && d === 1
|
|
1176
|
+
? unit
|
|
1177
|
+
: n === 1
|
|
1178
|
+
? compact
|
|
1179
|
+
? `\\tfrac{${unit}}{${String(d)}}`
|
|
1180
|
+
: `\\tfrac{1}{${String(d)}}${unit}`
|
|
1181
|
+
: d === 1
|
|
1182
|
+
? `${String(n)}${unit}`
|
|
1183
|
+
: compact
|
|
1184
|
+
? `\\tfrac{${String(n)}${unit}}{${String(d)}}`
|
|
1185
|
+
: `\\tfrac{${String(n)}}{${String(d)}}${unit}`;
|
|
1186
|
+
return MathTex(s, { fontSize, ...rest });
|
|
1187
|
+
}
|
|
1188
|
+
/** The radius numbers and the azimuth labels (Manim `get_coordinate_labels`). */
|
|
1189
|
+
getCoordinateLabels(rValues, aValues) {
|
|
1190
|
+
const radii = rValues ??
|
|
1191
|
+
this.getXAxis()
|
|
1192
|
+
.getTickRange()
|
|
1193
|
+
.filter((r) => r >= 0);
|
|
1194
|
+
const turns = aValues ?? arange(0, 1, 1 / this.#p.azimuthStep);
|
|
1195
|
+
const rMobs = this.getXAxis().addNumbers(radii).numbers;
|
|
1196
|
+
const d = this.#p.azimuthDirection === "CW" ? -1 : 1;
|
|
1197
|
+
const r = this.getRight()[0];
|
|
1198
|
+
const fs = this.#p.azimuthLabelFontSize;
|
|
1199
|
+
const labels = turns.map((i) => {
|
|
1200
|
+
const angle = d * i * TAU + this.#p.azimuthOffset;
|
|
1201
|
+
const point = [r * Math.cos(angle), r * Math.sin(angle)];
|
|
1202
|
+
const units = this.#p.azimuthUnits;
|
|
1203
|
+
const text = units === "PI radians" || units === "TAU radians"
|
|
1204
|
+
? this.getRadianLabel(i, { fontSize: fs })
|
|
1205
|
+
: units === "degrees"
|
|
1206
|
+
? MathTex(`${String(Number((360 * i).toPrecision(6)))}^{\\circ}`, { fontSize: fs })
|
|
1207
|
+
: units === "gradians"
|
|
1208
|
+
? MathTex(`${String(Number((400 * i).toPrecision(6)))}^{g}`, { fontSize: fs })
|
|
1209
|
+
: MathTex(String(Number(i.toPrecision(6))), { fontSize: fs });
|
|
1210
|
+
return text.nextTo(point, point, { alignedEdge: point, buff: this.#p.azimuthLabelBuff });
|
|
1211
|
+
});
|
|
1212
|
+
const all = VGroup(rMobs, VGroup(labels));
|
|
1213
|
+
this.coordinateLabels = all;
|
|
1214
|
+
return all;
|
|
1215
|
+
}
|
|
1216
|
+
/** Adds `getCoordinateLabels(rValues, aValues)` (Manim `add_coordinates`). */
|
|
1217
|
+
/** Adds the labels of `getCoordinateLabels(rValues, aValues)` (Manim `add_coordinates`). */
|
|
1218
|
+
addCoordinates(rValues, aValues) {
|
|
1219
|
+
return this.add(this.getCoordinateLabels(rValues, aValues));
|
|
1220
|
+
}
|
|
1221
|
+
}
|
|
1222
|
+
/** Manim's `PolarPlane(opts)`: circles every `radiusStep` and `azimuthStep` rays. */
|
|
1223
|
+
export function PolarPlane(opts = {}) {
|
|
1224
|
+
const { radiusMax = FRAME_HEIGHT / 2, size, radiusStep = 1, azimuthUnits = "PI radians", azimuthCompactFraction = true, azimuthOffset = 0, azimuthDirection = "CCW", azimuthLabelBuff = SMALL_BUFF, azimuthLabelFontSize = 24, radiusConfig = {}, backgroundLineStyle = {}, fadedLineStyle, fadedLineRatio = 1, makeSmoothAfterApplyingFunctions = true, ...axesOptions } = opts;
|
|
1225
|
+
const steps = { "PI radians": 20, "TAU radians": 20, degrees: 36, gradians: 40, null: 1 };
|
|
1226
|
+
const azimuthStep = opts.azimuthStep ?? steps[String(azimuthUnits)] ?? 1;
|
|
1227
|
+
const o = {
|
|
1228
|
+
...axesOptions,
|
|
1229
|
+
xRange: [-radiusMax, radiusMax, radiusStep],
|
|
1230
|
+
yRange: [-radiusMax, radiusMax, radiusStep],
|
|
1231
|
+
...(size === undefined ? {} : { xLength: size, yLength: size }),
|
|
1232
|
+
axisConfig: {
|
|
1233
|
+
strokeWidth: 2,
|
|
1234
|
+
includeTicks: false,
|
|
1235
|
+
includeTip: false,
|
|
1236
|
+
lineToNumberBuff: SMALL_BUFF,
|
|
1237
|
+
labelDirection: DL,
|
|
1238
|
+
fontSize: 24,
|
|
1239
|
+
...radiusConfig,
|
|
1240
|
+
},
|
|
1241
|
+
};
|
|
1242
|
+
const axes = axesOf(o, [size, size]);
|
|
1243
|
+
const [x] = axes;
|
|
1244
|
+
const r = fadedLineRatio === 0 ? 1 : fadedLineRatio;
|
|
1245
|
+
const rstep = x.xRange[2] / r;
|
|
1246
|
+
const astep = TAU / azimuthStep / r;
|
|
1247
|
+
const unit = x.getUnitSize();
|
|
1248
|
+
const bright = [];
|
|
1249
|
+
const faded = [];
|
|
1250
|
+
arange(0, x.xRange[1] + rstep, rstep).forEach((radius, k) => {
|
|
1251
|
+
(k % r === 0 ? bright : faded).push(Circle({ radius: Math.max(radius * unit, 1e-6) }));
|
|
1252
|
+
});
|
|
1253
|
+
const center = ORIGIN;
|
|
1254
|
+
const ray = Line(center, x.getEnd());
|
|
1255
|
+
const rays = [[], []];
|
|
1256
|
+
arange(0, TAU, astep).forEach((a, k) => {
|
|
1257
|
+
rays[k % r === 0 ? 0 : 1].push(ray.copy().rotate(a + azimuthOffset, { aboutPoint: center }));
|
|
1258
|
+
});
|
|
1259
|
+
const bg = { strokeColor: BLUE_D, strokeWidth: 2, strokeOpacity: 1, ...backgroundLineStyle };
|
|
1260
|
+
const handle = withLines(axes, [
|
|
1261
|
+
[...rays[0], ...bright],
|
|
1262
|
+
[...rays[1], ...faded],
|
|
1263
|
+
], bg, fadedLineStyle);
|
|
1264
|
+
const settings = {
|
|
1265
|
+
azimuthStep,
|
|
1266
|
+
azimuthUnits,
|
|
1267
|
+
azimuthCompactFraction,
|
|
1268
|
+
azimuthOffset,
|
|
1269
|
+
azimuthDirection,
|
|
1270
|
+
azimuthLabelBuff,
|
|
1271
|
+
azimuthLabelFontSize,
|
|
1272
|
+
};
|
|
1273
|
+
const plane = new PolarPlaneMobject(handle, axes, o, settings);
|
|
1274
|
+
plane.makeSmoothAfterApplyingFunctions = makeSmoothAfterApplyingFunctions;
|
|
1275
|
+
return centred(plane);
|
|
1276
|
+
}
|
|
1277
|
+
/** Bars on axes: Manim's `BarChart`. */
|
|
1278
|
+
export class BarChartMobject extends AxesMobject {
|
|
1279
|
+
/** The bars (Manim `bars`). */
|
|
1280
|
+
bars = VGroup();
|
|
1281
|
+
/** The values of the bars (Manim `values`). */
|
|
1282
|
+
values = [];
|
|
1283
|
+
barColors = [];
|
|
1284
|
+
barWidth = 0.6;
|
|
1285
|
+
barFillOpacity = 0.7;
|
|
1286
|
+
barStrokeWidth = 3;
|
|
1287
|
+
/** A label with the value over each bar, in the colour of the bar (Manim `get_bar_labels`). */
|
|
1288
|
+
getBarLabels(opts = {}) {
|
|
1289
|
+
const { color, fontSize = 24, buff = MED_SMALL_BUFF, labelConstructor = (t) => Tex(t) } = opts;
|
|
1290
|
+
return VGroup(this.bars.submobjects.map((bar, i) => {
|
|
1291
|
+
const value = this.values[i] ?? 0;
|
|
1292
|
+
const label = labelConstructor(String(value), { fontSize }).setColor(color ?? bar.getFillColor());
|
|
1293
|
+
if (label.fontSize > 0)
|
|
1294
|
+
label.scale(fontSize / label.fontSize);
|
|
1295
|
+
return label.nextTo(bar, value >= 0 ? UP : DOWN, { buff });
|
|
1296
|
+
}));
|
|
1297
|
+
}
|
|
1298
|
+
/** Stretches the bars to new values (Manim `change_bar_values`). */
|
|
1299
|
+
changeBarValues(values, updateColors = true) {
|
|
1300
|
+
values.forEach((value, i) => {
|
|
1301
|
+
const bar = this.bars.submobjects[i];
|
|
1302
|
+
const old = this.values[i];
|
|
1303
|
+
if (bar === undefined || old === undefined)
|
|
1304
|
+
return;
|
|
1305
|
+
let edge = old > 0 ? DOWN : UP;
|
|
1306
|
+
const limit = old > 0 ? bar.getBottom() : bar.getTop();
|
|
1307
|
+
if (old !== 0) {
|
|
1308
|
+
const quotient = value / old;
|
|
1309
|
+
if (quotient < 0)
|
|
1310
|
+
edge = old > 0 ? UP : DOWN;
|
|
1311
|
+
bar.stretchToFitHeight(Math.max(Math.abs(quotient) * bar.height, 1e-9));
|
|
1312
|
+
bar.moveTo(limit, { alignedEdge: edge });
|
|
1313
|
+
}
|
|
1314
|
+
else {
|
|
1315
|
+
const fresh = this.createBar(i, value);
|
|
1316
|
+
bar.become(fresh);
|
|
1317
|
+
}
|
|
1318
|
+
this.values[i] = value;
|
|
1319
|
+
});
|
|
1320
|
+
if (updateColors)
|
|
1321
|
+
this.#updateColors();
|
|
1322
|
+
return this;
|
|
1323
|
+
}
|
|
1324
|
+
/** The bar of `value` at position `barNumber` (Manim `_create_bar`). */
|
|
1325
|
+
createBar(barNumber, value) {
|
|
1326
|
+
const h = Math.abs(this.c2p(0, value)[1] - this.c2p(0, 0)[1]);
|
|
1327
|
+
const w = this.c2p(this.barWidth, 0)[0] - this.c2p(0, 0)[0];
|
|
1328
|
+
const bar = Rectangle({
|
|
1329
|
+
height: Math.max(h, 1e-9),
|
|
1330
|
+
width: w,
|
|
1331
|
+
strokeWidth: this.barStrokeWidth,
|
|
1332
|
+
fillOpacity: this.barFillOpacity,
|
|
1333
|
+
});
|
|
1334
|
+
return bar.nextTo(this.c2p(barNumber + 0.5, 0), value >= 0 ? UP : DOWN, { buff: 0 });
|
|
1335
|
+
}
|
|
1336
|
+
#updateColors() {
|
|
1337
|
+
const colors = gradientColors(this.barColors, this.bars.length);
|
|
1338
|
+
this.bars.submobjects.forEach((bar, i) => bar.setColor(colors[i] ?? WHITE));
|
|
1339
|
+
}
|
|
1340
|
+
/** Makes and colours the bars. */
|
|
1341
|
+
addBars() {
|
|
1342
|
+
this.values.forEach((v, i) => this.bars.add(this.createBar(i, v)));
|
|
1343
|
+
this.#updateColors();
|
|
1344
|
+
}
|
|
1345
|
+
}
|
|
1346
|
+
/** Manim's `BarChart(values, opts)`: a bar for each value, with the names under the x axis. */
|
|
1347
|
+
export function BarChart(values, opts = {}) {
|
|
1348
|
+
const { barNames, barColors = ["#003f5c", "#58508d", "#bc5090", "#ff6361", "#ffa600"], barWidth = 0.6, barFillOpacity = 0.7, barStrokeWidth = 3, ...axesOptions } = opts;
|
|
1349
|
+
if (values.length === 0)
|
|
1350
|
+
wrong("BarChart", "values is empty");
|
|
1351
|
+
const yLength = axesOptions.yLength ?? FRAME_HEIGHT - 4;
|
|
1352
|
+
const max = Math.max(...values);
|
|
1353
|
+
const step = Math.round((max / yLength) * 100) / 100 || 1;
|
|
1354
|
+
const yRange = axesOptions.yRange === undefined
|
|
1355
|
+
? [Math.min(0, ...values), Math.max(0, max), step]
|
|
1356
|
+
: axesOptions.yRange.length === 2
|
|
1357
|
+
? [axesOptions.yRange[0], axesOptions.yRange[1], step]
|
|
1358
|
+
: axesOptions.yRange;
|
|
1359
|
+
const xLength = axesOptions.xLength ?? Math.min(values.length, FRAME_WIDTH - 2);
|
|
1360
|
+
const o = {
|
|
1361
|
+
...axesOptions,
|
|
1362
|
+
xRange: [0, values.length, 1],
|
|
1363
|
+
yRange,
|
|
1364
|
+
xLength,
|
|
1365
|
+
yLength,
|
|
1366
|
+
tips: axesOptions.tips ?? false,
|
|
1367
|
+
xAxisConfig: { fontSize: 24, labelConstructor: (t) => Tex(t), ...axesOptions.xAxisConfig },
|
|
1368
|
+
yAxisConfig: { includeNumbers: true, ...axesOptions.yAxisConfig },
|
|
1369
|
+
};
|
|
1370
|
+
const axes = axesOf(o, [xLength, yLength]);
|
|
1371
|
+
const chart = centred(new BarChartMobject(engine.vGroup(axes.map(raw)), axes, o));
|
|
1372
|
+
chart.values = [...values];
|
|
1373
|
+
chart.barColors = barColors;
|
|
1374
|
+
chart.barWidth = barWidth;
|
|
1375
|
+
chart.barFillOpacity = barFillOpacity;
|
|
1376
|
+
chart.barStrokeWidth = barStrokeWidth;
|
|
1377
|
+
chart.addBars();
|
|
1378
|
+
const children = chart.submobjects;
|
|
1379
|
+
chart.remove(...children);
|
|
1380
|
+
chart.add(chart.bars, ...children);
|
|
1381
|
+
if (barNames !== undefined) {
|
|
1382
|
+
const x = chart.xAxis;
|
|
1383
|
+
const labels = barNames.map((name, i) => {
|
|
1384
|
+
const label = x.labelConstructor(name, { fontSize: x.fontSize });
|
|
1385
|
+
if (label.fontSize > 0)
|
|
1386
|
+
label.scale(x.fontSize / label.fontSize);
|
|
1387
|
+
return label.nextTo(x.numberToPoint(i + 0.5), (values[i] ?? 0) < 0 ? UP : DOWN, { buff: x.lineToNumberBuff });
|
|
1388
|
+
});
|
|
1389
|
+
x.add(VGroup(labels));
|
|
1390
|
+
}
|
|
1391
|
+
return chart;
|
|
1392
|
+
}
|
|
1393
|
+
/** A rectangle that divides into parts: Manim's `SampleSpace`. */
|
|
1394
|
+
export class SampleSpaceMobject extends Mobject {
|
|
1395
|
+
defaultLabelScaleVal = 1;
|
|
1396
|
+
/** The parts of `divideHorizontally` (Manim `horizontal_parts`). */
|
|
1397
|
+
horizontalParts;
|
|
1398
|
+
/** The parts of `divideVertically` (Manim `vertical_parts`). */
|
|
1399
|
+
verticalParts;
|
|
1400
|
+
/** The title of `addTitle`. */
|
|
1401
|
+
title;
|
|
1402
|
+
/** The label of `addLabel`. */
|
|
1403
|
+
label;
|
|
1404
|
+
#marks = new WeakMap();
|
|
1405
|
+
/** A `Tex` title above the space, at most as wide (Manim `add_title`). */
|
|
1406
|
+
addTitle(title = "Sample space", buff = MED_SMALL_BUFF) {
|
|
1407
|
+
const t = Tex(title);
|
|
1408
|
+
if (t.width > this.width)
|
|
1409
|
+
t.width = this.width;
|
|
1410
|
+
this.title = t.nextTo(this, UP, { buff });
|
|
1411
|
+
return this.add(t);
|
|
1412
|
+
}
|
|
1413
|
+
addLabel(label) {
|
|
1414
|
+
this.label = label;
|
|
1415
|
+
return this;
|
|
1416
|
+
}
|
|
1417
|
+
/** The probabilities with the rest of 1 at the end (Manim `complete_p_list`). */
|
|
1418
|
+
completePList(pList) {
|
|
1419
|
+
const list = typeof pList === "number" ? [pList] : [...pList];
|
|
1420
|
+
const rest = 1 - list.reduce((a, b) => a + b, 0);
|
|
1421
|
+
return Math.abs(rest) > 1e-8 ? [...list, rest] : list;
|
|
1422
|
+
}
|
|
1423
|
+
/** Parts of the space along axis `dim` (0 x, 1 y), sized by the probabilities (Manim
|
|
1424
|
+
* `get_division_along_dimension`). */
|
|
1425
|
+
getDivisionAlongDimension(pList, dim, colors, vect) {
|
|
1426
|
+
const list = this.completePList(pList);
|
|
1427
|
+
const palette = gradientColors(colors, list.length);
|
|
1428
|
+
let last = this.getEdgeCenter(mul(vect, -1));
|
|
1429
|
+
const parts = list.map((factor, i) => {
|
|
1430
|
+
const part = SampleSpace().setFill(palette[i] ?? WHITE, { opacity: 1 });
|
|
1431
|
+
part.replace(this, { stretch: true });
|
|
1432
|
+
part.stretch(factor, dim);
|
|
1433
|
+
part.moveTo(last, { alignedEdge: mul(vect, -1) });
|
|
1434
|
+
last = part.getEdgeCenter(vect);
|
|
1435
|
+
return part;
|
|
1436
|
+
});
|
|
1437
|
+
return VGroup(parts);
|
|
1438
|
+
}
|
|
1439
|
+
getHorizontalDivision(pList, colors = [GREEN_E, BLUE_E], vect = DOWN) {
|
|
1440
|
+
return this.getDivisionAlongDimension(pList, 1, colors, vect);
|
|
1441
|
+
}
|
|
1442
|
+
getVerticalDivision(pList, colors = [MAROON_B, YELLOW], vect = RIGHT) {
|
|
1443
|
+
return this.getDivisionAlongDimension(pList, 0, colors, vect);
|
|
1444
|
+
}
|
|
1445
|
+
divideHorizontally(pList, colors, vect) {
|
|
1446
|
+
this.horizontalParts = this.getHorizontalDivision(pList, colors, vect);
|
|
1447
|
+
return this.add(this.horizontalParts);
|
|
1448
|
+
}
|
|
1449
|
+
divideVertically(pList, colors, vect) {
|
|
1450
|
+
this.verticalParts = this.getVerticalDivision(pList, colors, vect);
|
|
1451
|
+
return this.add(this.verticalParts);
|
|
1452
|
+
}
|
|
1453
|
+
/** A brace and a label on each part (Manim `get_subdivision_braces_and_labels`). A string
|
|
1454
|
+
* label is a `MathTex`. */
|
|
1455
|
+
getSubdivisionBracesAndLabels(parts, labels, direction, opts = {}) {
|
|
1456
|
+
const { buff = SMALL_BUFF } = opts;
|
|
1457
|
+
const braces = VGroup();
|
|
1458
|
+
const labelMobs = VGroup();
|
|
1459
|
+
parts.submobjects.forEach((part, i) => {
|
|
1460
|
+
const label = labels[i];
|
|
1461
|
+
if (label === undefined)
|
|
1462
|
+
return;
|
|
1463
|
+
const brace = Brace(part, direction, { buff });
|
|
1464
|
+
const mob = label instanceof Mobject ? label : MathTex(label).scale(this.defaultLabelScaleVal);
|
|
1465
|
+
mob.nextTo(brace, direction, { buff });
|
|
1466
|
+
braces.add(brace);
|
|
1467
|
+
labelMobs.add(mob);
|
|
1468
|
+
});
|
|
1469
|
+
this.#marks.set(parts, { braces, labels: labelMobs });
|
|
1470
|
+
return VGroup(braces, labelMobs);
|
|
1471
|
+
}
|
|
1472
|
+
getSideBracesAndLabels(labels, direction = LEFT, opts = {}) {
|
|
1473
|
+
const parts = this.horizontalParts ??
|
|
1474
|
+
wrong("getSideBracesAndLabels", "the space has no horizontal parts", "call divideHorizontally first");
|
|
1475
|
+
return this.getSubdivisionBracesAndLabels(parts, labels, direction, opts);
|
|
1476
|
+
}
|
|
1477
|
+
getTopBracesAndLabels(labels, opts = {}) {
|
|
1478
|
+
const parts = this.verticalParts ??
|
|
1479
|
+
wrong("getTopBracesAndLabels", "the space has no vertical parts", "call divideVertically first");
|
|
1480
|
+
return this.getSubdivisionBracesAndLabels(parts, labels, UP, opts);
|
|
1481
|
+
}
|
|
1482
|
+
getBottomBracesAndLabels(labels, opts = {}) {
|
|
1483
|
+
const parts = this.verticalParts ??
|
|
1484
|
+
wrong("getBottomBracesAndLabels", "the space has no vertical parts", "call divideVertically first");
|
|
1485
|
+
return this.getSubdivisionBracesAndLabels(parts, labels, DOWN, opts);
|
|
1486
|
+
}
|
|
1487
|
+
/** Adds the braces and labels of the parts (Manim `add_braces_and_labels`). */
|
|
1488
|
+
addBracesAndLabels() {
|
|
1489
|
+
for (const parts of [this.horizontalParts, this.verticalParts]) {
|
|
1490
|
+
const marks = parts === undefined ? undefined : this.#marks.get(parts);
|
|
1491
|
+
if (marks !== undefined)
|
|
1492
|
+
this.add(marks.braces, marks.labels);
|
|
1493
|
+
}
|
|
1494
|
+
return this;
|
|
1495
|
+
}
|
|
1496
|
+
}
|
|
1497
|
+
/** Manim's `SampleSpace(opts)`: a dark grey 3 × 3 square. */
|
|
1498
|
+
export function SampleSpace(opts = {}) {
|
|
1499
|
+
const { height = 3, width = 3, fillColor = DARK_GREY, fillOpacity = 1, strokeWidth = 0.5, strokeColor = LIGHT_GREY, defaultLabelScaleVal = 1, } = opts;
|
|
1500
|
+
const rect = Rectangle({ height, width, fillColor, fillOpacity, strokeWidth, strokeColor });
|
|
1501
|
+
const space = new SampleSpaceMobject(raw(rect));
|
|
1502
|
+
space.defaultLabelScaleVal = defaultLabelScaleVal;
|
|
1503
|
+
return space;
|
|
1504
|
+
}
|