executable-engineering 0.1.53__py3-none-any.whl → 0.1.56__py3-none-any.whl

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.
@@ -0,0 +1,1828 @@
1
+ import ipywidgets as widgets
2
+ import numpy as np
3
+ import plotly.graph_objects as go
4
+ from IPython.display import display
5
+ from plotly.subplots import make_subplots
6
+ from scipy.integrate import solve_ivp
7
+ from scipy.optimize import root
8
+ from scipy.spatial.distance import cdist
9
+
10
+
11
+ def forward_euler(f, t0, y0, t_end, h):
12
+ t_points = np.arange(t0, t_end + h / 2, h)
13
+ y_points = np.zeros_like(t_points, dtype=float)
14
+ y_points[0] = y0
15
+
16
+ for i in range(len(t_points) - 1):
17
+ y_points[i + 1] = y_points[i] + h * f(t_points[i], y_points[i])
18
+
19
+ return {
20
+ "t_points": t_points,
21
+ "y_points": y_points,
22
+ "h": h,
23
+ "method": "Forward Euler",
24
+ }
25
+
26
+
27
+ def heun_method(f, t0, y0, t_end, h, iterations=1):
28
+ t_points = np.arange(t0, t_end + h / 2, h)
29
+ y_points = np.zeros_like(t_points, dtype=float)
30
+ y_points[0] = y0
31
+ cycle_history = []
32
+
33
+ for i in range(len(t_points) - 1):
34
+ t_i, y_i = t_points[i], y_points[i]
35
+ k1 = f(t_i, y_i)
36
+ y_pred = y_i + h * k1
37
+ step_cycles = [y_pred]
38
+
39
+ for _ in range(iterations):
40
+ k2 = f(t_i + h, y_pred)
41
+ y_pred = y_i + h * (k1 + k2) / 2.0
42
+ step_cycles.append(y_pred)
43
+
44
+ y_points[i + 1] = y_pred
45
+ cycle_history.append(step_cycles)
46
+
47
+ return {
48
+ "t_points": t_points,
49
+ "y_points": y_points,
50
+ "cycle_history": cycle_history,
51
+ "h": h,
52
+ "iterations": iterations,
53
+ "method": f"Heun's Method ({iterations} iter)",
54
+ }
55
+
56
+
57
+ def midpoint_ode(f, t0, y0, t_end, h):
58
+ t_points = np.arange(t0, t_end + h / 2, h)
59
+ y_points = np.zeros_like(t_points, dtype=float)
60
+ y_points[0] = y0
61
+
62
+ for i in range(len(t_points) - 1):
63
+ t_i, y_i = t_points[i], y_points[i]
64
+ k1 = f(t_i, y_i)
65
+ k2 = f(t_i + 0.5 * h, y_i + 0.5 * h * k1)
66
+ y_points[i + 1] = y_points[i] + h * k2
67
+
68
+ return {
69
+ "t_points": t_points,
70
+ "y_points": y_points,
71
+ "h": h,
72
+ "method": "Midpoint Method (RK2)",
73
+ }
74
+
75
+
76
+ def ralston_method(f, t0, y0, t_end, h):
77
+ t_points = np.arange(t0, t_end + h / 2, h)
78
+ y_points = np.zeros_like(t_points, dtype=float)
79
+ y_points[0] = y0
80
+
81
+ for i in range(len(t_points) - 1):
82
+ t_i, y_i = t_points[i], y_points[i]
83
+ k1 = f(t_i, y_i)
84
+ k2 = f(t_i + 0.75 * h, y_i + 0.75 * h * k1)
85
+ y_points[i + 1] = y_points[i] + h * (k1 + 2.0 * k2) / 3.0
86
+
87
+ return {
88
+ "t_points": t_points,
89
+ "y_points": y_points,
90
+ "h": h,
91
+ "method": "Ralston's Method (RK2)",
92
+ }
93
+
94
+
95
+ def rk3_method(f, t0, y0, t_end, h):
96
+ t_points = np.arange(t0, t_end + h / 2, h)
97
+ y_points = np.zeros_like(t_points, dtype=float)
98
+ y_points[0] = y0
99
+
100
+ for i in range(len(t_points) - 1):
101
+ t_i, y_i = t_points[i], y_points[i]
102
+ k1 = f(t_i, y_i)
103
+ k2 = f(t_i + 0.5 * h, y_i + 0.5 * h * k1)
104
+ k3 = f(t_i + h, y_i - h * k1 + 2.0 * h * k2)
105
+ y_points[i + 1] = y_points[i] + h * (k1 + 4.0 * k2 + k3) / 6.0
106
+
107
+ return {
108
+ "t_points": t_points,
109
+ "y_points": y_points,
110
+ "h": h,
111
+ "method": "Classical RK3",
112
+ }
113
+
114
+
115
+ def rk4_method(f, t0, y0, t_end, h):
116
+ t_points = np.arange(t0, t_end + h / 2, h)
117
+ y_points = np.zeros_like(t_points, dtype=float)
118
+ y_points[0] = y0
119
+
120
+ for i in range(len(t_points) - 1):
121
+ t_i, y_i = t_points[i], y_points[i]
122
+ k1 = f(t_i, y_i)
123
+ k2 = f(t_i + 0.5 * h, y_i + 0.5 * h * k1)
124
+ k3 = f(t_i + 0.5 * h, y_i + 0.5 * h * k2)
125
+ k4 = f(t_i + h, y_i + h * k3)
126
+ y_points[i + 1] = y_points[i] + h * (k1 + 2.0 * k2 + 2.0 * k3 + k4) / 6.0
127
+
128
+ return {
129
+ "t_points": t_points,
130
+ "y_points": y_points,
131
+ "h": h,
132
+ "method": "Classical RK4",
133
+ }
134
+
135
+
136
+ def plot_direction_field(
137
+ f,
138
+ t_range=(0, 4),
139
+ y_range=(0, 10),
140
+ y_true=None,
141
+ trajectories=None,
142
+ n_grid=16,
143
+ title="Direction Field & Solution Trajectories",
144
+ ):
145
+ t_grid = np.linspace(t_range[0], t_range[1], n_grid)
146
+ y_grid = np.linspace(y_range[0], y_range[1], n_grid)
147
+ T, Y = np.meshgrid(t_grid, y_grid)
148
+ slopes = f(T, Y)
149
+
150
+ dt = (t_range[1] - t_range[0]) / (n_grid * 2.6)
151
+ dy_scale = (y_range[1] - y_range[0]) / (t_range[1] - t_range[0])
152
+
153
+ seg_t = []
154
+ seg_y = []
155
+ for i in range(n_grid):
156
+ for j in range(n_grid):
157
+ ti = T[i, j]
158
+ yi = Y[i, j]
159
+ s = slopes[i, j]
160
+ norm = np.sqrt(1.0 + (s / dy_scale) ** 2)
161
+ d_t = dt / norm
162
+ d_y = s * d_t
163
+ seg_t.extend([ti - d_t, ti + d_t, None])
164
+ seg_y.extend([yi - d_y, yi + d_y, None])
165
+
166
+ fig = go.Figure()
167
+ fig.add_trace(
168
+ go.Scatter(
169
+ x=seg_t,
170
+ y=seg_y,
171
+ mode="lines",
172
+ name="Slope Field f(t, y)",
173
+ line=dict(color="rgba(148, 163, 184, 0.7)", width=1.5),
174
+ hoverinfo="skip",
175
+ )
176
+ )
177
+
178
+ t_dense = np.linspace(t_range[0], t_range[1], 300)
179
+ if y_true is not None:
180
+ fig.add_trace(
181
+ go.Scatter(
182
+ x=t_dense,
183
+ y=y_true(t_dense),
184
+ mode="lines",
185
+ name="Exact Solution y(t)",
186
+ line=dict(color="#111827", width=3, dash="dash"),
187
+ )
188
+ )
189
+
190
+ palette = ["#2563EB", "#DC2626", "#059669", "#D97706", "#7C3AED"]
191
+ if trajectories:
192
+ if isinstance(trajectories, dict) and "t_points" in trajectories:
193
+ trajectories = {trajectories.get("method", "Approximation"): trajectories}
194
+ for idx, (label, data) in enumerate(trajectories.items()):
195
+ c = palette[idx % len(palette)]
196
+ t_pts = data["t_points"] if isinstance(data, dict) else data[0]
197
+ y_pts = data["y_points"] if isinstance(data, dict) else data[1]
198
+ fig.add_trace(
199
+ go.Scatter(
200
+ x=t_pts,
201
+ y=y_pts,
202
+ mode="lines+markers",
203
+ name=label,
204
+ line=dict(color=c, width=2.2),
205
+ marker=dict(size=7, symbol="circle"),
206
+ )
207
+ )
208
+
209
+ fig.update_layout(
210
+ title=title,
211
+ xaxis_title="Time t",
212
+ yaxis_title="y(t)",
213
+ xaxis=dict(range=list(t_range)),
214
+ yaxis=dict(range=list(y_range)),
215
+ template="plotly_white",
216
+ hovermode="x unified",
217
+ height=460,
218
+ legend=dict(x=0.02, y=0.98, bgcolor="rgba(255, 255, 255, 0.85)"),
219
+ )
220
+ return fig
221
+
222
+
223
+ def plot_ode_comparison(
224
+ t_range,
225
+ y_true,
226
+ results_dict,
227
+ title="Explicit Runge-Kutta Methods vs. Exact Solution",
228
+ ):
229
+ t_dense = np.linspace(t_range[0], t_range[1], 300)
230
+ y_exact_dense = y_true(t_dense)
231
+
232
+ fig = make_subplots(
233
+ rows=2,
234
+ cols=1,
235
+ shared_xaxes=True,
236
+ vertical_spacing=0.1,
237
+ subplot_titles=("Solution Trajectories y(t)", "Global Truncation Error |y_i - y(t_i)|"),
238
+ row_heights=[0.62, 0.38],
239
+ )
240
+
241
+ fig.add_trace(
242
+ go.Scatter(
243
+ x=t_dense,
244
+ y=y_exact_dense,
245
+ mode="lines",
246
+ name="Exact Solution",
247
+ line=dict(color="#111827", width=3, dash="dash"),
248
+ ),
249
+ row=1,
250
+ col=1,
251
+ )
252
+
253
+ palette = ["#2563EB", "#D97706", "#059669", "#DC2626", "#7C3AED", "#0891B2"]
254
+ for idx, (label, res) in enumerate(results_dict.items()):
255
+ c = palette[idx % len(palette)]
256
+ t_pts = res["t_points"]
257
+ y_pts = res["y_points"]
258
+ err = np.maximum(np.abs(y_pts - y_true(t_pts)), 1e-16)
259
+
260
+ fig.add_trace(
261
+ go.Scatter(
262
+ x=t_pts,
263
+ y=y_pts,
264
+ mode="lines+markers",
265
+ name=label,
266
+ line=dict(color=c, width=2),
267
+ marker=dict(size=7),
268
+ ),
269
+ row=1,
270
+ col=1,
271
+ )
272
+ fig.add_trace(
273
+ go.Scatter(
274
+ x=t_pts[1:],
275
+ y=err[1:],
276
+ mode="lines+markers",
277
+ name=f"{label} Error",
278
+ line=dict(color=c, width=1.8),
279
+ marker=dict(size=6, symbol="diamond"),
280
+ showlegend=False,
281
+ ),
282
+ row=2,
283
+ col=1,
284
+ )
285
+
286
+ fig.update_yaxes(title_text="y(t)", row=1, col=1)
287
+ fig.update_yaxes(title_text="Absolute Error", type="log", row=2, col=1)
288
+ fig.update_xaxes(title_text="Time t", row=2, col=1)
289
+ fig.update_layout(
290
+ title=title,
291
+ template="plotly_white",
292
+ hovermode="x unified",
293
+ height=540,
294
+ legend=dict(orientation="h", yanchor="bottom", y=1.03, xanchor="right", x=1),
295
+ )
296
+ return fig
297
+
298
+
299
+ def plot_heun_iterations(
300
+ f,
301
+ y_true,
302
+ t0=0.0,
303
+ y0=2.0,
304
+ t_end=4.0,
305
+ h=1.0,
306
+ max_iter=15,
307
+ title="Heun's Predictor-Corrector: 1 vs. 15 Iterations",
308
+ ):
309
+ res_1 = heun_method(f, t0, y0, t_end, h, iterations=1)
310
+ res_m = heun_method(f, t0, y0, t_end, h, iterations=max_iter)
311
+
312
+ t_dense = np.linspace(t0, t_end, 300)
313
+ fig = make_subplots(
314
+ rows=1,
315
+ cols=2,
316
+ subplot_titles=(
317
+ "Global Trajectory Comparison",
318
+ f"Corrector Convergence at Step 1 (t = {t0 + h})",
319
+ ),
320
+ horizontal_spacing=0.12,
321
+ )
322
+
323
+ fig.add_trace(
324
+ go.Scatter(
325
+ x=t_dense,
326
+ y=y_true(t_dense),
327
+ mode="lines",
328
+ name="Exact Solution",
329
+ line=dict(color="#111827", width=3, dash="dash"),
330
+ ),
331
+ row=1,
332
+ col=1,
333
+ )
334
+ fig.add_trace(
335
+ go.Scatter(
336
+ x=res_1["t_points"],
337
+ y=res_1["y_points"],
338
+ mode="lines+markers",
339
+ name="Heun (1 iteration)",
340
+ line=dict(color="#2563EB", width=2.2),
341
+ marker=dict(size=8),
342
+ ),
343
+ row=1,
344
+ col=1,
345
+ )
346
+ fig.add_trace(
347
+ go.Scatter(
348
+ x=res_m["t_points"],
349
+ y=res_m["y_points"],
350
+ mode="lines+markers",
351
+ name=f"Heun ({max_iter} iterations)",
352
+ line=dict(color="#DC2626", width=2.2),
353
+ marker=dict(size=8, symbol="square"),
354
+ ),
355
+ row=1,
356
+ col=1,
357
+ )
358
+
359
+ step1_cycles = res_m["cycle_history"][0]
360
+ iters = list(range(len(step1_cycles)))
361
+ true_step1 = float(y_true(t0 + h))
362
+
363
+ fig.add_trace(
364
+ go.Scatter(
365
+ x=iters,
366
+ y=step1_cycles,
367
+ mode="lines+markers",
368
+ name="Corrector Sequence y_1^(k)",
369
+ line=dict(color="#7C3AED", width=2.2),
370
+ marker=dict(size=7),
371
+ ),
372
+ row=1,
373
+ col=2,
374
+ )
375
+ fig.add_trace(
376
+ go.Scatter(
377
+ x=[0, max_iter],
378
+ y=[true_step1, true_step1],
379
+ mode="lines",
380
+ name=f"Exact y({t0 + h}) = {true_step1:.4f}",
381
+ line=dict(color="#111827", width=2, dash="dot"),
382
+ ),
383
+ row=1,
384
+ col=2,
385
+ )
386
+
387
+ fig.update_xaxes(title_text="Time t", row=1, col=1)
388
+ fig.update_yaxes(title_text="y(t)", row=1, col=1)
389
+ fig.update_xaxes(title_text="Corrector Iteration k", row=1, col=2)
390
+ fig.update_yaxes(title_text="Approximation y_1", row=1, col=2)
391
+ fig.update_layout(
392
+ title=title,
393
+ template="plotly_white",
394
+ height=450,
395
+ legend=dict(orientation="h", yanchor="bottom", y=1.05, xanchor="right", x=1),
396
+ )
397
+ return fig
398
+
399
+
400
+ def plot_rk4_stages(
401
+ f,
402
+ y_true,
403
+ t0=0.0,
404
+ y0=2.0,
405
+ h=1.0,
406
+ title="Geometric Anatomy of a Single Classical RK4 Step",
407
+ ):
408
+ k1 = f(t0, y0)
409
+ t_half = t0 + 0.5 * h
410
+ y_k1 = y0 + 0.5 * h * k1
411
+ k2 = f(t_half, y_k1)
412
+ y_k2 = y0 + 0.5 * h * k2
413
+ k3 = f(t_half, y_k2)
414
+ t1 = t0 + h
415
+ y_k3 = y0 + h * k3
416
+ k4 = f(t1, y_k3)
417
+ y_rk4 = y0 + (h / 6.0) * (k1 + 2.0 * k2 + 2.0 * k3 + k4)
418
+
419
+ t_dense = np.linspace(t0, t1 + 0.15 * h, 200)
420
+ fig = go.Figure()
421
+
422
+ fig.add_trace(
423
+ go.Scatter(
424
+ x=t_dense,
425
+ y=y_true(t_dense),
426
+ mode="lines",
427
+ name="Exact Solution y(t)",
428
+ line=dict(color="#111827", width=3),
429
+ )
430
+ )
431
+
432
+ # Trial step lines from (t0, y0)
433
+ fig.add_trace(
434
+ go.Scatter(
435
+ x=[t0, t_half],
436
+ y=[y0, y_k1],
437
+ mode="lines+markers",
438
+ name=f"Stage 1 → Midpoint (k1={k1:.2f})",
439
+ line=dict(color="#2563EB", width=2, dash="dot"),
440
+ marker=dict(size=8),
441
+ )
442
+ )
443
+ fig.add_trace(
444
+ go.Scatter(
445
+ x=[t0, t_half],
446
+ y=[y0, y_k2],
447
+ mode="lines+markers",
448
+ name=f"Stage 2 → Corrected Midpoint (k2={k2:.2f})",
449
+ line=dict(color="#D97706", width=2, dash="dot"),
450
+ marker=dict(size=8),
451
+ )
452
+ )
453
+ fig.add_trace(
454
+ go.Scatter(
455
+ x=[t0, t1],
456
+ y=[y0, y_k3],
457
+ mode="lines+markers",
458
+ name=f"Stage 3 → Endpoint Trial (k3={k3:.2f})",
459
+ line=dict(color="#7C3AED", width=2, dash="dot"),
460
+ marker=dict(size=8),
461
+ )
462
+ )
463
+
464
+ # Short tangent slope segments at each stage evaluation point
465
+ seg_len = 0.18 * h
466
+ stages = [
467
+ (t0, y0, k1, "k1", "#2563EB"),
468
+ (t_half, y_k1, k2, "k2", "#D97706"),
469
+ (t_half, y_k2, k3, "k3", "#7C3AED"),
470
+ (t1, y_k3, k4, "k4", "#DC2626"),
471
+ ]
472
+ for ts, ys, ks, lbl, col in stages:
473
+ fig.add_trace(
474
+ go.Scatter(
475
+ x=[ts, ts + seg_len],
476
+ y=[ys, ys + ks * seg_len],
477
+ mode="lines",
478
+ name=f"Slope {lbl} = {ks:.2f}",
479
+ line=dict(color=col, width=3.5),
480
+ showlegend=(lbl == "k4"),
481
+ )
482
+ )
483
+
484
+ # Final weighted RK4 step
485
+ fig.add_trace(
486
+ go.Scatter(
487
+ x=[t0, t1],
488
+ y=[y0, y_rk4],
489
+ mode="lines+markers",
490
+ name=f"Final RK4 Step (y1={y_rk4:.4f})",
491
+ line=dict(color="#059669", width=3),
492
+ marker=dict(size=11, symbol="star"),
493
+ )
494
+ )
495
+
496
+ fig.add_vline(x=t_half, line_dash="dash", line_color="#9CA3AF", annotation_text="t0 + h/2")
497
+ fig.add_vline(x=t1, line_dash="dash", line_color="#9CA3AF", annotation_text="t0 + h")
498
+
499
+ fig.update_layout(
500
+ title=title,
501
+ xaxis_title="Time t",
502
+ yaxis_title="y(t)",
503
+ template="plotly_white",
504
+ hovermode="closest",
505
+ height=480,
506
+ legend=dict(x=0.02, y=0.98, bgcolor="rgba(255, 255, 255, 0.85)"),
507
+ )
508
+ return fig
509
+
510
+
511
+ def rk4_step(f, t, y, h):
512
+ k1 = h * f(t, y)
513
+ k2 = h * f(t + 0.5 * h, y + 0.5 * k1)
514
+ k3 = h * f(t + 0.5 * h, y + 0.5 * k2)
515
+ k4 = h * f(t + h, y + k3)
516
+ return y + (k1 + 2.0 * k2 + 2.0 * k3 + k4) / 6.0
517
+
518
+
519
+ def backward_euler(f, t0, y0, t_end, h):
520
+ from scipy.optimize import root
521
+
522
+ t_points = np.arange(t0, t_end + h / 2, h)
523
+ y_points = np.zeros_like(t_points, dtype=float)
524
+ y_points[0] = y0
525
+
526
+ for i in range(len(t_points) - 1):
527
+ t_next = t_points[i + 1]
528
+ y_curr = y_points[i]
529
+ sol = root(lambda y_val: y_val - (y_curr + h * f(t_next, y_val)), y_curr)
530
+ y_points[i + 1] = sol.x[0]
531
+
532
+ return {
533
+ "t_points": t_points,
534
+ "y_points": y_points,
535
+ "h": h,
536
+ "method": "Backward Euler",
537
+ }
538
+
539
+
540
+ def plot_transient_function(
541
+ t_range=(0.0, 10.0),
542
+ n_coarse=12,
543
+ title="Fast Transient vs. Slow Drift: y(t) = tanh((t - 5) / 0.1) - t",
544
+ ):
545
+ t_dense = np.linspace(t_range[0], t_range[1], 600)
546
+ y_dense = np.tanh((t_dense - 5.0) / 0.1) - t_dense
547
+
548
+ t_coarse = np.linspace(t_range[0], t_range[1], n_coarse)
549
+ y_coarse = np.tanh((t_coarse - 5.0) / 0.1) - t_coarse
550
+
551
+ fig = go.Figure()
552
+ fig.add_trace(
553
+ go.Scatter(
554
+ x=t_dense,
555
+ y=y_dense,
556
+ mode="lines",
557
+ name="Exact Curve (Fine Resolution)",
558
+ line=dict(color="#2563EB", width=3),
559
+ )
560
+ )
561
+ fig.add_trace(
562
+ go.Scatter(
563
+ x=t_coarse,
564
+ y=y_coarse,
565
+ mode="lines+markers",
566
+ name=f"Coarse Uniform Step ({n_coarse} points)",
567
+ line=dict(color="#DC2626", width=2, dash="dash"),
568
+ marker=dict(size=8, symbol="circle"),
569
+ )
570
+ )
571
+
572
+ fig.add_vrect(
573
+ x0=4.7,
574
+ x1=5.3,
575
+ fillcolor="rgba(245, 158, 11, 0.18)",
576
+ line_width=0,
577
+ annotation_text="Sharp Transient",
578
+ annotation_position="top left",
579
+ )
580
+
581
+ fig.update_layout(
582
+ title=title,
583
+ xaxis_title="Time t",
584
+ yaxis_title="y(t)",
585
+ template="plotly_white",
586
+ hovermode="x unified",
587
+ height=440,
588
+ legend=dict(x=0.02, y=0.15, bgcolor="rgba(255, 255, 255, 0.85)"),
589
+ )
590
+ return fig
591
+
592
+
593
+ def plot_rk45_adaptive(
594
+ sol,
595
+ y_true=None,
596
+ title="Adaptive Runge-Kutta-Fehlberg (RK45) Trajectory & Step Sizes",
597
+ ):
598
+ t_pts = sol.t
599
+ y_pts = sol.y[0]
600
+ step_sizes = np.diff(t_pts)
601
+
602
+ fig = make_subplots(
603
+ rows=2,
604
+ cols=1,
605
+ shared_xaxes=True,
606
+ vertical_spacing=0.12,
607
+ subplot_titles=(
608
+ "Solution Trajectory y(t) & Adaptive Nodes",
609
+ "Adaptive Step Size h_i = t_{i+1} - t_i",
610
+ ),
611
+ row_heights=[0.62, 0.38],
612
+ )
613
+
614
+ if y_true is not None:
615
+ t_dense = np.linspace(t_pts[0], t_pts[-1], 300)
616
+ fig.add_trace(
617
+ go.Scatter(
618
+ x=t_dense,
619
+ y=y_true(t_dense),
620
+ mode="lines",
621
+ name="Exact Solution",
622
+ line=dict(color="#111827", width=3, dash="dash"),
623
+ ),
624
+ row=1,
625
+ col=1,
626
+ )
627
+
628
+ fig.add_trace(
629
+ go.Scatter(
630
+ x=t_pts,
631
+ y=y_pts,
632
+ mode="lines+markers",
633
+ name=f"RK45 Nodes ({len(t_pts)} steps)",
634
+ line=dict(color="#2563EB", width=2.2),
635
+ marker=dict(size=9, symbol="circle"),
636
+ ),
637
+ row=1,
638
+ col=1,
639
+ )
640
+
641
+ fig.add_trace(
642
+ go.Scatter(
643
+ x=t_pts[:-1],
644
+ y=step_sizes,
645
+ mode="lines+markers",
646
+ name="Step Size h",
647
+ line=dict(color="#059669", width=2.2, shape="hv"),
648
+ marker=dict(size=8, symbol="diamond"),
649
+ ),
650
+ row=2,
651
+ col=1,
652
+ )
653
+
654
+ fig.update_yaxes(title_text="y(t)", row=1, col=1)
655
+ fig.update_yaxes(title_text="Step Size h", row=2, col=1)
656
+ fig.update_xaxes(title_text="Time t", row=2, col=1)
657
+ fig.update_layout(
658
+ title=title,
659
+ template="plotly_white",
660
+ hovermode="x unified",
661
+ height=520,
662
+ legend=dict(orientation="h", yanchor="bottom", y=1.03, xanchor="right", x=1),
663
+ )
664
+ return fig
665
+
666
+
667
+ def plot_euler_stability(
668
+ t_end=20.0,
669
+ y0=2.0,
670
+ title="Numerical Stability on dy/dt = -y: Explicit vs. Implicit Euler",
671
+ ):
672
+ h_values = [0.2, 0.5, 0.8, 1.2, 1.8, 2.0, 2.15, 2.3]
673
+ default_idx = 2 # h = 0.8
674
+
675
+ t_dense = np.linspace(0.0, t_end, 400)
676
+ y_exact = y0 * np.exp(-t_dense)
677
+
678
+ fig = go.Figure()
679
+
680
+ # Trace 0: Exact solution (always visible)
681
+ fig.add_trace(
682
+ go.Scatter(
683
+ x=t_dense,
684
+ y=y_exact,
685
+ mode="lines",
686
+ name="Exact Solution y(t) = 2e^(-t)",
687
+ line=dict(color="#111827", width=3, dash="dash"),
688
+ visible=True,
689
+ )
690
+ )
691
+
692
+ for idx, h in enumerate(h_values):
693
+ t_pts = np.arange(0.0, t_end + h / 2, h)
694
+ y_exp = np.zeros_like(t_pts)
695
+ y_imp = np.zeros_like(t_pts)
696
+ y_exp[0] = y0
697
+ y_imp[0] = y0
698
+ for i in range(1, len(t_pts)):
699
+ y_exp[i] = y_exp[i - 1] * (1.0 - h)
700
+ y_imp[i] = y_imp[i - 1] / (1.0 + h)
701
+
702
+ is_vis = idx == default_idx
703
+ fig.add_trace(
704
+ go.Scatter(
705
+ x=t_pts,
706
+ y=y_exp,
707
+ mode="lines+markers",
708
+ name=f"Forward Euler (h = {h})",
709
+ line=dict(color="#2563EB", width=2.2),
710
+ marker=dict(size=7, symbol="circle"),
711
+ visible=is_vis,
712
+ )
713
+ )
714
+ fig.add_trace(
715
+ go.Scatter(
716
+ x=t_pts,
717
+ y=y_imp,
718
+ mode="lines+markers",
719
+ name=f"Backward Euler (h = {h})",
720
+ line=dict(color="#DC2626", width=2.2),
721
+ marker=dict(size=7, symbol="x"),
722
+ visible=is_vis,
723
+ )
724
+ )
725
+
726
+ steps = []
727
+ for idx, h in enumerate(h_values):
728
+ vis = [True] + [False] * (2 * len(h_values))
729
+ vis[1 + 2 * idx] = True
730
+ vis[1 + 2 * idx + 1] = True
731
+ regime = (
732
+ "Monotonic decay"
733
+ if h < 1.0
734
+ else ("Damped oscillation" if h < 2.0 else ("Neutral oscillation" if h == 2.0 else "Unstable divergence!"))
735
+ )
736
+ steps.append(
737
+ dict(
738
+ method="update",
739
+ args=[
740
+ {"visible": vis},
741
+ {"title": f"{title} — Step Size h = {h} ({regime})"},
742
+ ],
743
+ label=f"{h}",
744
+ )
745
+ )
746
+
747
+ fig.update_layout(
748
+ title=f"{title} — Step Size h = {h_values[default_idx]} (Monotonic decay)",
749
+ xaxis_title="Time t",
750
+ yaxis_title="y(t)",
751
+ xaxis=dict(range=[0, t_end]),
752
+ template="plotly_white",
753
+ hovermode="x unified",
754
+ height=520,
755
+ legend=dict(x=0.58, y=0.98, bgcolor="rgba(255, 255, 255, 0.85)"),
756
+ sliders=[
757
+ dict(
758
+ active=default_idx,
759
+ currentvalue={"prefix": "Step size h = "},
760
+ pad={"t": 45},
761
+ steps=steps,
762
+ )
763
+ ],
764
+ )
765
+ return fig
766
+
767
+
768
+ def plot_stiff_ode(
769
+ title="Analytical Solution of Stiff ODE: y(t) = 3 - 0.998e^(-1000t) - 2.002e^(-t)",
770
+ ):
771
+ limits = [0.005, 0.02, 0.1, 0.5, 1.5, 3.0, 5.0]
772
+ default_idx = 5 # limit = 3.0
773
+
774
+ fig = go.Figure()
775
+ for idx, lim in enumerate(limits):
776
+ t = np.linspace(0.0, lim, 500)
777
+ y = 3.0 - 0.998 * np.exp(-1000.0 * t) - 2.002 * np.exp(-t)
778
+ fig.add_trace(
779
+ go.Scatter(
780
+ x=t,
781
+ y=y,
782
+ mode="lines",
783
+ name=f"y(t) on [0, {lim}]",
784
+ line=dict(color="#2563EB", width=3),
785
+ visible=(idx == default_idx),
786
+ )
787
+ )
788
+
789
+ steps = []
790
+ for idx, lim in enumerate(limits):
791
+ vis = [i == idx for i in range(len(limits))]
792
+ steps.append(
793
+ dict(
794
+ method="update",
795
+ args=[
796
+ {"visible": vis},
797
+ {
798
+ "title": f"{title} (t_max = {lim})",
799
+ "xaxis.range": [0, lim],
800
+ },
801
+ ],
802
+ label=f"{lim}",
803
+ )
804
+ )
805
+
806
+ fig.update_layout(
807
+ title=f"{title} (t_max = {limits[default_idx]})",
808
+ xaxis_title="Time t",
809
+ yaxis_title="y(t)",
810
+ xaxis=dict(range=[0, limits[default_idx]]),
811
+ template="plotly_white",
812
+ hovermode="x unified",
813
+ height=500,
814
+ sliders=[
815
+ dict(
816
+ active=default_idx,
817
+ currentvalue={"prefix": "Time Window t_max = "},
818
+ pad={"t": 45},
819
+ steps=steps,
820
+ )
821
+ ],
822
+ )
823
+ return fig
824
+
825
+
826
+ def plot_stiff_euler_comparison(
827
+ t0=0.01,
828
+ t_end=0.05,
829
+ title="Stiff ODE on [0.01, 0.05]: Explicit vs. Implicit Euler",
830
+ ):
831
+ h_values = [0.0002, 0.0005, 0.001, 0.0015, 0.002, 0.003, 0.004, 0.005]
832
+ default_idx = 1 # h = 0.0005
833
+
834
+ def y_true(t):
835
+ return 3.0 - 0.998 * np.exp(-1000.0 * t) - 2.002 * np.exp(-t)
836
+
837
+ def f_stiff(t, y):
838
+ return -1000.0 * y + 3000.0 - 2000.0 * np.exp(-t)
839
+
840
+ t_dense = np.linspace(t0, t_end, 400)
841
+ y0 = y_true(t0)
842
+
843
+ fig = go.Figure()
844
+ fig.add_trace(
845
+ go.Scatter(
846
+ x=t_dense,
847
+ y=y_true(t_dense),
848
+ mode="lines",
849
+ name="Analytical Solution",
850
+ line=dict(color="#111827", width=3, dash="dash"),
851
+ visible=True,
852
+ )
853
+ )
854
+
855
+ for idx, h in enumerate(h_values):
856
+ res_exp = forward_euler(f_stiff, t0, y0, t_end, h)
857
+ res_imp = backward_euler(f_stiff, t0, y0, t_end, h)
858
+
859
+ is_vis = idx == default_idx
860
+ fig.add_trace(
861
+ go.Scatter(
862
+ x=res_exp["t_points"],
863
+ y=res_exp["y_points"],
864
+ mode="lines+markers",
865
+ name=f"Explicit Euler (h = {h:.4f})",
866
+ line=dict(color="#2563EB", width=2),
867
+ marker=dict(size=6, symbol="circle"),
868
+ visible=is_vis,
869
+ )
870
+ )
871
+ fig.add_trace(
872
+ go.Scatter(
873
+ x=res_imp["t_points"],
874
+ y=res_imp["y_points"],
875
+ mode="lines+markers",
876
+ name=f"Implicit Euler (h = {h:.4f})",
877
+ line=dict(color="#DC2626", width=2),
878
+ marker=dict(size=6, symbol="x"),
879
+ visible=is_vis,
880
+ )
881
+ )
882
+
883
+ steps = []
884
+ for idx, h in enumerate(h_values):
885
+ vis = [True] + [False] * (2 * len(h_values))
886
+ vis[1 + 2 * idx] = True
887
+ vis[1 + 2 * idx + 1] = True
888
+ status = "Stable" if h < 0.002 else "Unstable (h > 2/1000)!"
889
+ steps.append(
890
+ dict(
891
+ method="update",
892
+ args=[
893
+ {"visible": vis},
894
+ {"title": f"{title} — h = {h:.4f} ({status})"},
895
+ ],
896
+ label=f"{h:.4f}",
897
+ )
898
+ )
899
+
900
+ fig.update_layout(
901
+ title=f"{title} — h = {h_values[default_idx]:.4f} (Stable)",
902
+ xaxis_title="Time t",
903
+ yaxis_title="y(t)",
904
+ xaxis=dict(range=[t0, t_end]),
905
+ template="plotly_white",
906
+ hovermode="x unified",
907
+ height=520,
908
+ legend=dict(x=0.02, y=0.98, bgcolor="rgba(255, 255, 255, 0.85)"),
909
+ sliders=[
910
+ dict(
911
+ active=default_idx,
912
+ currentvalue={"prefix": "Step size h = "},
913
+ pad={"t": 45},
914
+ steps=steps,
915
+ )
916
+ ],
917
+ )
918
+ return fig
919
+
920
+
921
+ def plot_pendulum_system(
922
+ t,
923
+ theta,
924
+ theta_dot,
925
+ title="Nonlinear Pendulum Motion via Reduction of Order (RK45)",
926
+ ):
927
+ fig = make_subplots(
928
+ rows=1,
929
+ cols=2,
930
+ subplot_titles=(
931
+ "Time Evolution: Angle & Angular Velocity",
932
+ "Phase Portrait: θ'(t) vs. θ(t)",
933
+ ),
934
+ horizontal_spacing=0.12,
935
+ )
936
+
937
+ fig.add_trace(
938
+ go.Scatter(
939
+ x=t,
940
+ y=theta,
941
+ mode="lines+markers",
942
+ name="Angle Θ(t) [rad]",
943
+ line=dict(color="#2563EB", width=2.5),
944
+ marker=dict(size=5),
945
+ ),
946
+ row=1,
947
+ col=1,
948
+ )
949
+ fig.add_trace(
950
+ go.Scatter(
951
+ x=t,
952
+ y=theta_dot,
953
+ mode="lines",
954
+ name="Angular Velocity dΘ/dt [rad/s]",
955
+ line=dict(color="#D97706", width=2, dash="dot"),
956
+ ),
957
+ row=1,
958
+ col=1,
959
+ )
960
+
961
+ fig.add_trace(
962
+ go.Scatter(
963
+ x=theta,
964
+ y=theta_dot,
965
+ mode="lines+markers",
966
+ name="Phase Trajectory",
967
+ line=dict(color="#059669", width=2.2),
968
+ marker=dict(size=5),
969
+ ),
970
+ row=1,
971
+ col=2,
972
+ )
973
+
974
+ fig.update_xaxes(title_text="Time t (s)", row=1, col=1)
975
+ fig.update_yaxes(title_text="State Variables", row=1, col=1)
976
+ fig.update_xaxes(title_text="Angle Θ (rad)", row=1, col=2)
977
+ fig.update_yaxes(title_text="Angular Velocity dΘ/dt (rad/s)", row=1, col=2)
978
+ fig.update_layout(
979
+ title=title,
980
+ template="plotly_white",
981
+ hovermode="closest",
982
+ height=460,
983
+ legend=dict(orientation="h", yanchor="bottom", y=1.05, xanchor="right", x=1),
984
+ )
985
+ return fig
986
+
987
+
988
+ # =====================================================================
989
+ # 3. Pedagogical PDE Solvers (1D Heat Equation)
990
+ # Exposed in notebooks via {literalinclude} and exe.display_source()
991
+ # =====================================================================
992
+
993
+
994
+ def forward_euler_heat(T0, alpha, dx, dt, num_steps):
995
+ T = T0.copy()
996
+ T_history = [T.copy()]
997
+ r = alpha * dt / dx**2
998
+ for _ in range(num_steps):
999
+ T[1:-1] = T[1:-1] + r * (T[:-2] - 2.0 * T[1:-1] + T[2:])
1000
+ T_history.append(T.copy())
1001
+ return np.array(T_history)
1002
+
1003
+
1004
+ def backward_euler_heat(T0, alpha, dx, dt, num_steps):
1005
+ T = T0.copy()
1006
+ T_history = [T.copy()]
1007
+ n = len(T)
1008
+ r = alpha * dt / dx**2
1009
+ A = (
1010
+ np.diag((1.0 + 2.0 * r) * np.ones(n), 0)
1011
+ + np.diag(-r * np.ones(n - 1), -1)
1012
+ + np.diag(-r * np.ones(n - 1), 1)
1013
+ )
1014
+ A[0, :] = 0.0
1015
+ A[0, 0] = 1.0
1016
+ A[-1, :] = 0.0
1017
+ A[-1, -1] = 1.0
1018
+ for _ in range(num_steps):
1019
+ b = T.copy()
1020
+ T = np.linalg.solve(A, b)
1021
+ T_history.append(T.copy())
1022
+ return np.array(T_history)
1023
+
1024
+
1025
+ def crank_nicolson_heat(T0, alpha, dx, dt, num_steps):
1026
+ T = T0.copy()
1027
+ T_history = [T.copy()]
1028
+ n = len(T)
1029
+ r = alpha * dt / (2.0 * dx**2)
1030
+ A = (
1031
+ np.diag((1.0 + 2.0 * r) * np.ones(n), 0)
1032
+ + np.diag(-r * np.ones(n - 1), -1)
1033
+ + np.diag(-r * np.ones(n - 1), 1)
1034
+ )
1035
+ B = (
1036
+ np.diag((1.0 - 2.0 * r) * np.ones(n), 0)
1037
+ + np.diag(r * np.ones(n - 1), -1)
1038
+ + np.diag(r * np.ones(n - 1), 1)
1039
+ )
1040
+ A[0, :] = 0.0
1041
+ A[0, 0] = 1.0
1042
+ A[-1, :] = 0.0
1043
+ A[-1, -1] = 1.0
1044
+ for _ in range(num_steps):
1045
+ b = B @ T
1046
+ b[0] = T[0]
1047
+ b[-1] = T[-1]
1048
+ T = np.linalg.solve(A, b)
1049
+ T_history.append(T.copy())
1050
+ return np.array(T_history)
1051
+
1052
+
1053
+ crank_nicholson_heat = crank_nicolson_heat
1054
+
1055
+
1056
+ def _interactive_heat_widget(method, alpha=1.0, dx=0.05, dt=0.0010, steps=20, max_steps=50):
1057
+ """Display interactive 3-slider (dx, dt, step) Plotly UI for a 1D heat solver."""
1058
+ x_fine = np.linspace(0.0, 1.0, 301)
1059
+ T0_fine = 1.0 - np.abs(2.0 * x_fine - 1.0)
1060
+ modes = np.arange(1, 50, 2)[:, None]
1061
+ coeffs = 8.0 * ((-1.0) ** ((modes - 1) // 2)) / (np.pi * modes) ** 2
1062
+ sin_fine = np.sin(modes * np.pi * x_fine)
1063
+
1064
+ style = {"description_width": "initial"}
1065
+ dx_slider = widgets.FloatSlider(
1066
+ value=dx,
1067
+ min=0.02,
1068
+ max=0.10,
1069
+ step=0.01,
1070
+ description="Step size Δx:",
1071
+ readout_format=".2f",
1072
+ continuous_update=False,
1073
+ style=style,
1074
+ layout=widgets.Layout(width="270px"),
1075
+ )
1076
+ dt_slider = widgets.FloatSlider(
1077
+ value=dt,
1078
+ min=0.0005,
1079
+ max=0.0100,
1080
+ step=0.0005,
1081
+ description="Time step Δt:",
1082
+ readout_format=".4f",
1083
+ continuous_update=False,
1084
+ style=style,
1085
+ layout=widgets.Layout(width="290px"),
1086
+ )
1087
+ step_slider = widgets.IntSlider(
1088
+ value=steps,
1089
+ min=0,
1090
+ max=max_steps,
1091
+ step=1,
1092
+ description="Step number:",
1093
+ continuous_update=False,
1094
+ style=style,
1095
+ layout=widgets.Layout(width="270px"),
1096
+ )
1097
+
1098
+ def render(dx_val, dt_val, step_val):
1099
+ n = int(round(1.0 / dx_val)) + 1
1100
+ x = np.linspace(0.0, 1.0, n)
1101
+ dx_actual = x[1] - x[0]
1102
+ T0 = 1.0 - np.abs(2.0 * x - 1.0)
1103
+ t_val = step_val * dt_val
1104
+ r_euler = alpha * dt_val / dx_actual**2
1105
+ T_exact = (
1106
+ T0_fine
1107
+ if step_val == 0
1108
+ else np.sum(
1109
+ coeffs * np.exp(-alpha * (modes * np.pi) ** 2 * t_val) * sin_fine,
1110
+ axis=0,
1111
+ )
1112
+ )
1113
+
1114
+ fig = go.Figure()
1115
+
1116
+ fig.add_trace(
1117
+ go.Scatter(
1118
+ x=x_fine,
1119
+ y=T0_fine,
1120
+ mode="lines",
1121
+ name="Initial T(x, 0) = 1 - |2x - 1|",
1122
+ line=dict(color="#6B7280", width=2, dash="dash"),
1123
+ )
1124
+ )
1125
+ fig.add_trace(
1126
+ go.Scatter(
1127
+ x=x_fine,
1128
+ y=T_exact,
1129
+ mode="lines",
1130
+ name=f"Exact Solution (t = {t_val:.4f})",
1131
+ line=dict(color="#1F2937", width=2.5),
1132
+ )
1133
+ )
1134
+
1135
+ if method == "forward_euler":
1136
+ T_num = forward_euler_heat(T0, alpha, dx_actual, dt_val, step_val)[-1]
1137
+ # Cap extreme blow-up values so Plotly SVG coordinates stay responsive
1138
+ T_plot = np.clip(np.nan_to_num(T_num, posinf=1e4, neginf=-1e4), -1e4, 1e4)
1139
+ status = "Stable (r ≤ 0.5)" if r_euler <= 0.5001 else "Unstable (r > 0.5)!"
1140
+ fig.add_trace(
1141
+ go.Scatter(
1142
+ x=x,
1143
+ y=T_plot,
1144
+ mode="lines+markers",
1145
+ name=f"Forward Euler (step {step_val})",
1146
+ line=dict(color="#DC2626", width=2.5),
1147
+ marker=dict(size=6),
1148
+ )
1149
+ )
1150
+ title = (
1151
+ f"1D Heat Equation via Forward Euler "
1152
+ f"(Δx = {dx_actual:.3f}, Δt = {dt_val:.4f}, step = {step_val}, "
1153
+ f"t = {t_val:.4f}, r = {r_euler:.2f} — {status})"
1154
+ )
1155
+ fig.update_xaxes(title_text="Position x")
1156
+ fig.update_yaxes(title_text="Temperature T(x, t)", range=[-0.6, 1.6])
1157
+ elif method == "backward_euler":
1158
+ T_num = backward_euler_heat(T0, alpha, dx_actual, dt_val, step_val)[-1]
1159
+ fig.add_trace(
1160
+ go.Scatter(
1161
+ x=x,
1162
+ y=T_num,
1163
+ mode="lines+markers",
1164
+ name=f"Backward Euler (step {step_val})",
1165
+ line=dict(color="#2563EB", width=2.5),
1166
+ marker=dict(size=6),
1167
+ )
1168
+ )
1169
+ title = (
1170
+ f"1D Heat Equation via Backward Euler "
1171
+ f"(Δx = {dx_actual:.3f}, Δt = {dt_val:.4f}, step = {step_val}, "
1172
+ f"t = {t_val:.4f}, r = {r_euler:.2f} — Unconditionally Stable)"
1173
+ )
1174
+ fig.update_xaxes(title_text="Position x")
1175
+ fig.update_yaxes(title_text="Temperature T(x, t)", range=[-0.1, 1.1])
1176
+ elif method == "crank_nicolson":
1177
+ T_cn = crank_nicolson_heat(T0, alpha, dx_actual, dt_val, step_val)[-1]
1178
+ T_be = backward_euler_heat(T0, alpha, dx_actual, dt_val, step_val)[-1]
1179
+ r_cn = alpha * dt_val / (2.0 * dx_actual**2)
1180
+ fig.add_trace(
1181
+ go.Scatter(
1182
+ x=x,
1183
+ y=T_be,
1184
+ mode="lines+markers",
1185
+ name=f"Backward Euler (1st-order, step {step_val})",
1186
+ line=dict(color="#2563EB", width=2, dash="dot"),
1187
+ marker=dict(size=5, symbol="square"),
1188
+ )
1189
+ )
1190
+ fig.add_trace(
1191
+ go.Scatter(
1192
+ x=x,
1193
+ y=T_cn,
1194
+ mode="lines+markers",
1195
+ name=f"Crank-Nicolson (2nd-order, step {step_val})",
1196
+ line=dict(color="#059669", width=2.5),
1197
+ marker=dict(size=6, symbol="diamond"),
1198
+ )
1199
+ )
1200
+ title = (
1201
+ f"1D Heat Equation via Crank-Nicolson "
1202
+ f"(Δx = {dx_actual:.3f}, Δt = {dt_val:.4f}, step = {step_val}, "
1203
+ f"t = {t_val:.4f}, r = {r_cn:.2f} — Unconditionally Stable)"
1204
+ )
1205
+ fig.update_xaxes(title_text="Position x")
1206
+ fig.update_yaxes(title_text="Temperature T(x, t)", range=[-0.1, 1.1])
1207
+ else:
1208
+ raise ValueError(f"Unknown heat solver method: {method}")
1209
+
1210
+ fig.update_layout(
1211
+ title=title,
1212
+ template="plotly_white",
1213
+ hovermode="x unified",
1214
+ height=480,
1215
+ margin=dict(t=85, b=50, l=60, r=30),
1216
+ legend=dict(x=0.01, y=0.98, bgcolor="rgba(255, 255, 255, 0.85)"),
1217
+ )
1218
+ display(fig)
1219
+
1220
+ out = widgets.interactive_output(
1221
+ render,
1222
+ {"dx_val": dx_slider, "dt_val": dt_slider, "step_val": step_slider},
1223
+ )
1224
+ controls = widgets.HBox(
1225
+ [dx_slider, dt_slider, step_slider],
1226
+ layout=widgets.Layout(flex_flow="row wrap", gap="12px"),
1227
+ )
1228
+ display(widgets.VBox([controls, out]))
1229
+
1230
+
1231
+ def plot_forward_euler_heat(alpha=1.0, dx=0.05, dt=0.0010, steps=20, max_steps=50):
1232
+ """Display interactive 3-slider Forward Euler 1D heat equation visualizer."""
1233
+ _interactive_heat_widget("forward_euler", alpha=alpha, dx=dx, dt=dt, steps=steps, max_steps=max_steps)
1234
+
1235
+
1236
+ def plot_backward_euler_heat(alpha=1.0, dx=0.05, dt=0.0025, steps=10, max_steps=50):
1237
+ """Display interactive 3-slider Backward Euler 1D heat equation visualizer."""
1238
+ _interactive_heat_widget("backward_euler", alpha=alpha, dx=dx, dt=dt, steps=steps, max_steps=max_steps)
1239
+
1240
+
1241
+ def plot_crank_nicolson_heat(alpha=1.0, dx=0.05, dt=0.0050, steps=10, max_steps=50):
1242
+ """Display interactive 3-slider Crank-Nicolson 1D heat equation visualizer."""
1243
+ _interactive_heat_widget("crank_nicolson", alpha=alpha, dx=dx, dt=dt, steps=steps, max_steps=max_steps)
1244
+
1245
+
1246
+ plot_crank_nicholson_heat = plot_crank_nicolson_heat
1247
+
1248
+
1249
+ def plot_pde_method_comparison(alpha=0.1, dx=0.1, dt=0.02, num_steps=6):
1250
+ x = np.linspace(0.0, 1.0, int(round(1.0 / dx)) + 1)
1251
+ dx_actual = x[1] - x[0]
1252
+ T0 = np.zeros_like(x)
1253
+ T0[len(x) // 2] = 1.0
1254
+
1255
+ fe_sol = forward_euler_heat(T0, alpha, dx_actual, dt, num_steps)
1256
+ be_sol = backward_euler_heat(T0, alpha, dx_actual, dt, num_steps)
1257
+ cn_sol = crank_nicolson_heat(T0, alpha, dx_actual, dt, num_steps)
1258
+
1259
+ fig = go.Figure()
1260
+ default_step = 1
1261
+ traces_per_step = 3
1262
+
1263
+ for step_idx in range(num_steps + 1):
1264
+ vis = step_idx == default_step
1265
+ fig.add_trace(
1266
+ go.Scatter(
1267
+ x=x,
1268
+ y=fe_sol[step_idx],
1269
+ mode="lines+markers",
1270
+ name="Forward Euler (1st-order time, explicit)",
1271
+ line=dict(color="#DC2626", width=2.2, dash="dot"),
1272
+ marker=dict(size=6, symbol="circle"),
1273
+ visible=vis,
1274
+ )
1275
+ )
1276
+ fig.add_trace(
1277
+ go.Scatter(
1278
+ x=x,
1279
+ y=be_sol[step_idx],
1280
+ mode="lines+markers",
1281
+ name="Backward Euler (1st-order time, implicit)",
1282
+ line=dict(color="#2563EB", width=2.2, dash="dash"),
1283
+ marker=dict(size=6, symbol="square"),
1284
+ visible=vis,
1285
+ )
1286
+ )
1287
+ fig.add_trace(
1288
+ go.Scatter(
1289
+ x=x,
1290
+ y=cn_sol[step_idx],
1291
+ mode="lines+markers",
1292
+ name="Crank-Nicolson (2nd-order time, implicit)",
1293
+ line=dict(color="#059669", width=2.6),
1294
+ marker=dict(size=7, symbol="diamond"),
1295
+ visible=vis,
1296
+ )
1297
+ )
1298
+
1299
+ steps = []
1300
+ for step_idx in range(num_steps + 1):
1301
+ vis_mask = [False] * (traces_per_step * (num_steps + 1))
1302
+ for k in range(traces_per_step):
1303
+ vis_mask[step_idx * traces_per_step + k] = True
1304
+ t_val = step_idx * dt
1305
+ steps.append(
1306
+ dict(
1307
+ method="update",
1308
+ args=[
1309
+ {"visible": vis_mask},
1310
+ {
1311
+ "title": (
1312
+ f"Comparison of PDE Time-Stepping Schemes at Step {step_idx} "
1313
+ f"(t = {t_val:.3f} s, r = {alpha * dt / dx_actual**2:.2f})"
1314
+ )
1315
+ },
1316
+ ],
1317
+ label=f"Step {step_idx} (t={t_val:.2f})",
1318
+ )
1319
+ )
1320
+
1321
+ r_val = alpha * dt / dx_actual**2
1322
+ fig.update_layout(
1323
+ title=(
1324
+ f"Comparison of PDE Time-Stepping Schemes at Step {default_step} "
1325
+ f"(t = {default_step * dt:.3f} s, r = {r_val:.2f})"
1326
+ ),
1327
+ xaxis_title="Position x",
1328
+ yaxis_title="Temperature T(x, t)",
1329
+ yaxis=dict(range=[-0.1, 1.05]),
1330
+ template="plotly_white",
1331
+ hovermode="x unified",
1332
+ height=500,
1333
+ legend=dict(x=0.02, y=0.98, bgcolor="rgba(255, 255, 255, 0.85)"),
1334
+ sliders=[
1335
+ dict(
1336
+ active=default_step,
1337
+ currentvalue={"prefix": "Time index: "},
1338
+ pad={"t": 45},
1339
+ steps=steps,
1340
+ )
1341
+ ],
1342
+ )
1343
+ return fig
1344
+
1345
+
1346
+ def shooting_ballistics(y_target=50.0, t_end=5.0, v0_guess=1.0):
1347
+ def model(t, state):
1348
+ return [state[1], -9.8]
1349
+
1350
+ def residual(v0):
1351
+ sol = solve_ivp(model, [0.0, t_end], [0.0, float(v0[0])])
1352
+ return sol.y[0, -1] - y_target
1353
+
1354
+ res = root(residual, [v0_guess])
1355
+ v0_star = float(res.x[0])
1356
+ t_eval = np.linspace(0.0, t_end, 100)
1357
+ sol = solve_ivp(model, [0.0, t_end], [0.0, v0_star], t_eval=t_eval)
1358
+ return sol.t, sol.y[0], sol.y[1], v0_star
1359
+
1360
+
1361
+ def rbf_poisson_2d(N=20):
1362
+ epsilon = N / np.sqrt(2.0)
1363
+ x = np.linspace(0.0, 1.0, N)
1364
+ X, Y = np.meshgrid(x, x)
1365
+ points = np.column_stack([X.ravel(), Y.ravel()])
1366
+ r = cdist(points, points)
1367
+ exp_term = np.exp(-(epsilon * r) ** 2)
1368
+ A = exp_term
1369
+ L = (4.0 * epsilon**2 - 4.0 * epsilon**4 * r**2) * exp_term
1370
+ rhs = np.full(points.shape[0], 4.0)
1371
+ boundary = (
1372
+ (points[:, 0] == 0.0)
1373
+ | (points[:, 0] == 1.0)
1374
+ | (points[:, 1] == 0.0)
1375
+ | (points[:, 1] == 1.0)
1376
+ )
1377
+ L[boundary, :] = A[boundary, :]
1378
+ rhs[boundary] = 0.0
1379
+ weights = np.linalg.solve(L, rhs)
1380
+ U = (A @ weights).reshape(N, N)
1381
+ return X, Y, U
1382
+
1383
+
1384
+ def fdm_rocket_bvp(n=10):
1385
+ h = 5.0 / n
1386
+ A = np.zeros((n + 1, n + 1))
1387
+ b = np.zeros(n + 1)
1388
+ A[0, 0] = 1.0
1389
+ A[n, n] = 1.0
1390
+ b[n] = 50.0
1391
+ for i in range(1, n):
1392
+ A[i, i - 1] = 1.0
1393
+ A[i, i] = -2.0
1394
+ A[i, i + 1] = 1.0
1395
+ b[i] = -9.8 * h**2
1396
+ t = np.linspace(0.0, 5.0, n + 1)
1397
+ y = np.linalg.solve(A, b)
1398
+ return t, y, A, b
1399
+
1400
+
1401
+ def fdm_neumann_bvp(n=10, ghost_node=False):
1402
+ h = (np.pi / 2.0) / n
1403
+ A = np.zeros((n + 1, n + 1))
1404
+ b = np.zeros(n + 1)
1405
+ A[0, 0] = 1.0
1406
+ for i in range(1, n):
1407
+ A[i, i - 1] = 1.0
1408
+ A[i, i] = -2.0 + 4.0 * h**2
1409
+ A[i, i + 1] = 1.0
1410
+ b[i] = 4.0 * h**2 * (i * h)
1411
+ if ghost_node:
1412
+ A[n, n - 1] = 2.0
1413
+ A[n, n] = -2.0 + 4.0 * h**2
1414
+ b[n] = 4.0 * h**2 * (n * h)
1415
+ else:
1416
+ A[n, n - 1] = -1.0
1417
+ A[n, n] = 1.0
1418
+ x = np.linspace(0.0, np.pi / 2.0, n + 1)
1419
+ return x, np.linalg.solve(A, b)
1420
+
1421
+
1422
+ def fdm_nonlinear_bvp(n=10):
1423
+ h = 2.0 / n
1424
+
1425
+ def residual(y):
1426
+ r = np.zeros(n + 1)
1427
+ r[0] = y[0]
1428
+ r[1:n] = (
1429
+ y[:-2] - 2.0 * y[1:-1] + y[2:]
1430
+ + 1.5 * h * y[1:-1] * (y[2:] - y[:-2])
1431
+ )
1432
+ r[n] = y[n] - 1.0
1433
+ return r
1434
+
1435
+ y0 = np.linspace(0.0, 1.0, n + 1)
1436
+ sol = root(residual, y0)
1437
+ x = np.linspace(0.0, 2.0, n + 1)
1438
+ return x, sol.x, sol
1439
+
1440
+
1441
+ def fdm_poisson_2d(n=10):
1442
+ h = 1.0 / n
1443
+ size = (n + 1) ** 2
1444
+ A = np.zeros((size, size))
1445
+ b = np.zeros(size)
1446
+ for i in range(n + 1):
1447
+ for j in range(n + 1):
1448
+ idx = i * (n + 1) + j
1449
+ if i == 0 or i == n or j == 0 or j == n:
1450
+ A[idx, idx] = 1.0
1451
+ else:
1452
+ A[idx, idx] = -4.0
1453
+ A[idx, (i - 1) * (n + 1) + j] = 1.0
1454
+ A[idx, (i + 1) * (n + 1) + j] = 1.0
1455
+ A[idx, i * (n + 1) + (j - 1)] = 1.0
1456
+ A[idx, i * (n + 1) + (j + 1)] = 1.0
1457
+ b[idx] = -h**2
1458
+ U = np.linalg.solve(A, b).reshape((n + 1, n + 1))
1459
+ return U, A, b
1460
+
1461
+
1462
+ def plot_shooting_ballistics(t_end=5.0, y_target=50.0, v0_guess=1.0):
1463
+ """Plot the converged shooting trajectory and velocity profile."""
1464
+ t, y, v, v0_star = shooting_ballistics(
1465
+ y_target=y_target, t_end=t_end, v0_guess=v0_guess
1466
+ )
1467
+ fig = make_subplots(
1468
+ rows=1,
1469
+ cols=2,
1470
+ subplot_titles=(
1471
+ f"Altitude y(t) (v0* = {v0_star:.2f} m/s)",
1472
+ "Vertical Velocity v(t)",
1473
+ ),
1474
+ )
1475
+ fig.add_trace(
1476
+ go.Scatter(
1477
+ x=t, y=y, mode="lines", name="Shooting y(t)",
1478
+ line=dict(color="#2563EB", width=3),
1479
+ ),
1480
+ row=1, col=1,
1481
+ )
1482
+ fig.add_trace(
1483
+ go.Scatter(
1484
+ x=[0.0, t_end], y=[0.0, y_target], mode="markers",
1485
+ name="Boundary conditions",
1486
+ marker=dict(color="#DC2626", size=10, symbol="diamond"),
1487
+ ),
1488
+ row=1, col=1,
1489
+ )
1490
+ fig.add_trace(
1491
+ go.Scatter(
1492
+ x=t, y=v, mode="lines", name="Velocity v(t)",
1493
+ line=dict(color="#059669", width=3),
1494
+ ),
1495
+ row=1, col=2,
1496
+ )
1497
+ fig.update_xaxes(title_text="Time t (s)", row=1, col=1)
1498
+ fig.update_xaxes(title_text="Time t (s)", row=1, col=2)
1499
+ fig.update_yaxes(title_text="Altitude y (m)", row=1, col=1)
1500
+ fig.update_yaxes(title_text="Velocity v (m/s)", row=1, col=2)
1501
+ fig.update_layout(
1502
+ template="plotly_white",
1503
+ title="Shooting Method Solution for Ballistics BVP",
1504
+ height=440,
1505
+ )
1506
+ return fig
1507
+
1508
+
1509
+ def plot_shooting_trial_trajectories(t_end=5.0, y_target=50.0):
1510
+ """Plot interactive trial ballistics trajectories across initial velocities."""
1511
+ t = np.linspace(0.0, t_end, 100)
1512
+ v0_star = y_target / t_end + 0.5 * 9.8 * t_end
1513
+ v0_trials = [10.0, 20.0, 28.0, v0_star, 40.0, 50.0, 60.0]
1514
+ default_idx = 3
1515
+
1516
+ fig = go.Figure()
1517
+ for v0 in v0_trials:
1518
+ y = v0 * t - 0.5 * 9.8 * t**2
1519
+ fig.add_trace(
1520
+ go.Scatter(
1521
+ x=t, y=y, mode="lines", name=f"v0 = {v0:.1f} m/s",
1522
+ line=dict(color="#9CA3AF", width=1.5), opacity=0.45,
1523
+ showlegend=False,
1524
+ )
1525
+ )
1526
+
1527
+ n_bg = len(v0_trials)
1528
+ for idx, v0 in enumerate(v0_trials):
1529
+ y = v0 * t - 0.5 * 9.8 * t**2
1530
+ fig.add_trace(
1531
+ go.Scatter(
1532
+ x=t, y=y, mode="lines",
1533
+ name=f"Selected v0 = {v0:.2f} m/s (y({t_end:g}) = {y[-1]:.1f} m)",
1534
+ line=dict(color="#2563EB", width=3.5),
1535
+ visible=(idx == default_idx),
1536
+ )
1537
+ )
1538
+ fig.add_trace(
1539
+ go.Scatter(
1540
+ x=[t_end], y=[y[-1]], mode="markers",
1541
+ name=f"Endpoint ({t_end:g}, {y[-1]:.1f})",
1542
+ marker=dict(color="#2563EB", size=11),
1543
+ visible=(idx == default_idx),
1544
+ )
1545
+ )
1546
+
1547
+ fig.add_trace(
1548
+ go.Scatter(
1549
+ x=[t_end], y=[y_target], mode="markers",
1550
+ name=f"Target y({t_end:g}) = {y_target:g} m",
1551
+ marker=dict(color="#DC2626", size=14, symbol="star"),
1552
+ )
1553
+ )
1554
+
1555
+ steps = []
1556
+ total_traces = len(fig.data)
1557
+ for idx, v0 in enumerate(v0_trials):
1558
+ vis = [True] * n_bg + [False] * (2 * len(v0_trials)) + [True]
1559
+ vis[n_bg + 2 * idx] = True
1560
+ vis[n_bg + 2 * idx + 1] = True
1561
+ steps.append(
1562
+ dict(
1563
+ method="update",
1564
+ args=[{"visible": vis[:total_traces]}],
1565
+ label=f"{v0:.1f}",
1566
+ )
1567
+ )
1568
+
1569
+ fig.update_layout(
1570
+ template="plotly_white",
1571
+ title="Trial Ballistics Trajectories vs Target Boundary Condition",
1572
+ xaxis_title="Time t (s)",
1573
+ yaxis_title="Altitude y (m)",
1574
+ yaxis=dict(range=[0.0, 125.0]),
1575
+ height=500,
1576
+ sliders=[
1577
+ dict(
1578
+ active=default_idx,
1579
+ currentvalue={"prefix": "Initial velocity v0 (m/s): "},
1580
+ pad={"t": 50},
1581
+ steps=steps,
1582
+ )
1583
+ ],
1584
+ )
1585
+ return fig
1586
+
1587
+
1588
+ def plot_bvp_spline_collocation(sol, y_target=50.0):
1589
+ """Plot a SciPy solve_bvp cubic spline solution and its collocation mesh."""
1590
+ t_dense = np.linspace(sol.x[0], sol.x[-1], 200)
1591
+ y_dense = sol.sol(t_dense)
1592
+
1593
+ fig = make_subplots(
1594
+ rows=1,
1595
+ cols=2,
1596
+ subplot_titles=(
1597
+ f"Altitude y(t) (v0 = {sol.y[1, 0]:.2f} m/s)",
1598
+ "Velocity v(t)",
1599
+ ),
1600
+ )
1601
+ fig.add_trace(
1602
+ go.Scatter(
1603
+ x=t_dense, y=y_dense[0], mode="lines", name="Spline y(t)",
1604
+ line=dict(color="#2563EB", width=3),
1605
+ ),
1606
+ row=1, col=1,
1607
+ )
1608
+ fig.add_trace(
1609
+ go.Scatter(
1610
+ x=sol.x, y=sol.y[0], mode="markers", name="Collocation nodes",
1611
+ marker=dict(color="#DC2626", size=8),
1612
+ ),
1613
+ row=1, col=1,
1614
+ )
1615
+ fig.add_trace(
1616
+ go.Scatter(
1617
+ x=[sol.x[0], sol.x[-1]], y=[0.0, y_target], mode="markers",
1618
+ name="Boundary conditions",
1619
+ marker=dict(color="#059669", size=10, symbol="diamond"),
1620
+ ),
1621
+ row=1, col=1,
1622
+ )
1623
+ fig.add_trace(
1624
+ go.Scatter(
1625
+ x=t_dense, y=y_dense[1], mode="lines", name="Spline v(t)",
1626
+ line=dict(color="#D97706", width=3),
1627
+ ),
1628
+ row=1, col=2,
1629
+ )
1630
+ fig.update_xaxes(title_text="Time t (s)", row=1, col=1)
1631
+ fig.update_xaxes(title_text="Time t (s)", row=1, col=2)
1632
+ fig.update_yaxes(title_text="Altitude y (m)", row=1, col=1)
1633
+ fig.update_yaxes(title_text="Velocity v (m/s)", row=1, col=2)
1634
+ fig.update_layout(
1635
+ template="plotly_white",
1636
+ title="Cubic Spline Collocation Solution via solve_bvp",
1637
+ height=440,
1638
+ )
1639
+ return fig
1640
+
1641
+
1642
+ def plot_rbf_poisson_3d(X, Y, U):
1643
+ """Plot a 3D interactive surface for the RBF Poisson collocation solution."""
1644
+ fig = go.Figure(
1645
+ data=[
1646
+ go.Surface(
1647
+ x=X, y=Y, z=U, colorscale="Viridis",
1648
+ colorbar=dict(title="u(x, y)"), name="RBF surface",
1649
+ ),
1650
+ go.Scatter3d(
1651
+ x=X.ravel(), y=Y.ravel(), z=U.ravel(),
1652
+ mode="markers", name="Collocation nodes",
1653
+ marker=dict(size=2.5, color="#1F2937", opacity=0.65),
1654
+ ),
1655
+ ]
1656
+ )
1657
+ fig.update_layout(
1658
+ template="plotly_white",
1659
+ title="2D Poisson Solution using Gaussian RBF Collocation",
1660
+ scene=dict(xaxis_title="x", yaxis_title="y", zaxis_title="u(x, y)"),
1661
+ height=550,
1662
+ )
1663
+ return fig
1664
+
1665
+
1666
+ def plot_fdm_rocket(n=10):
1667
+ """Plot the finite-difference rocket trajectory against the exact solution."""
1668
+ t, y, _, _ = fdm_rocket_bvp(n=n)
1669
+ t_fine = np.linspace(0.0, 5.0, 200)
1670
+ y_exact = 34.5 * t_fine - 0.5 * 9.8 * t_fine**2
1671
+
1672
+ fig = go.Figure()
1673
+ fig.add_trace(
1674
+ go.Scatter(
1675
+ x=t_fine, y=y_exact, mode="lines", name="Analytical y(t)",
1676
+ line=dict(color="#1F2937", width=2.5, dash="dash"),
1677
+ )
1678
+ )
1679
+ fig.add_trace(
1680
+ go.Scatter(
1681
+ x=t, y=y, mode="lines+markers", name=f"FDM (n={n})",
1682
+ line=dict(color="#2563EB", width=2.5), marker=dict(size=8),
1683
+ )
1684
+ )
1685
+ fig.update_layout(
1686
+ template="plotly_white",
1687
+ title=f"Rocket Trajectory BVP via Finite Differences (n = {n})",
1688
+ xaxis_title="Time t (s)",
1689
+ yaxis_title="Altitude y (m)",
1690
+ height=440,
1691
+ )
1692
+ return fig
1693
+
1694
+
1695
+ def plot_fdm_neumann(n=10):
1696
+ """Plot the Neumann BVP finite-difference solution alongside exact curve."""
1697
+ x, y = fdm_neumann_bvp(n=n, ghost_node=False)
1698
+ x_fine = np.linspace(0.0, np.pi / 2.0, 200)
1699
+ y_exact = x_fine + 0.5 * np.sin(2.0 * x_fine)
1700
+
1701
+ fig = go.Figure()
1702
+ fig.add_trace(
1703
+ go.Scatter(
1704
+ x=x_fine, y=y_exact, mode="lines", name="Exact: x + 0.5 sin(2x)",
1705
+ line=dict(color="#1F2937", width=2.5, dash="dash"),
1706
+ )
1707
+ )
1708
+ fig.add_trace(
1709
+ go.Scatter(
1710
+ x=x, y=y, mode="lines+markers", name=f"FDM Backward BC (n={n})",
1711
+ line=dict(color="#2563EB", width=2.5), marker=dict(size=8),
1712
+ )
1713
+ )
1714
+ fig.update_layout(
1715
+ template="plotly_white",
1716
+ title=f"Neumann BVP Solution on [0, pi/2] (n = {n})",
1717
+ xaxis_title="x",
1718
+ yaxis_title="y(x)",
1719
+ height=440,
1720
+ )
1721
+ return fig
1722
+
1723
+
1724
+ def plot_fdm_neumann_convergence(n_values=(10, 15, 20, 25, 40, 80)):
1725
+ """Compare right-boundary error between backward difference and ghost node."""
1726
+ y_exact_end = np.pi / 2.0
1727
+ hs = [(np.pi / 2.0) / n for n in n_values]
1728
+ err_backward = [
1729
+ abs(fdm_neumann_bvp(n=n, ghost_node=False)[1][-1] - y_exact_end)
1730
+ for n in n_values
1731
+ ]
1732
+ err_ghost = [
1733
+ abs(fdm_neumann_bvp(n=n, ghost_node=True)[1][-1] - y_exact_end)
1734
+ for n in n_values
1735
+ ]
1736
+
1737
+ fig = go.Figure()
1738
+ fig.add_trace(
1739
+ go.Scatter(
1740
+ x=hs, y=err_backward, mode="lines+markers",
1741
+ name="Backward difference BC",
1742
+ line=dict(color="#2563EB", width=2.5), marker=dict(size=8),
1743
+ )
1744
+ )
1745
+ fig.add_trace(
1746
+ go.Scatter(
1747
+ x=hs, y=err_ghost, mode="lines+markers",
1748
+ name="Ghost-node central BC",
1749
+ line=dict(color="#DC2626", width=2.5, dash="dot"),
1750
+ marker=dict(size=8, symbol="square"),
1751
+ )
1752
+ )
1753
+ fig.update_layout(
1754
+ template="plotly_white",
1755
+ title="Right-Boundary Error |y_n - pi/2| vs Grid Spacing h",
1756
+ xaxis_title="Grid spacing h",
1757
+ yaxis_title="Absolute error at x = pi/2",
1758
+ xaxis_type="log",
1759
+ yaxis_type="log",
1760
+ height=440,
1761
+ )
1762
+ return fig
1763
+
1764
+
1765
+ def plot_fdm_nonlinear(n=10):
1766
+ """Plot the solution of the nonlinear BVP y'' = -3 y y'."""
1767
+ x, y, _ = fdm_nonlinear_bvp(n=n)
1768
+ fig = go.Figure()
1769
+ fig.add_trace(
1770
+ go.Scatter(
1771
+ x=x, y=y, mode="lines+markers", name=f"Nonlinear FDM (n={n})",
1772
+ line=dict(color="#059669", width=2.5), marker=dict(size=8),
1773
+ )
1774
+ )
1775
+ fig.update_layout(
1776
+ template="plotly_white",
1777
+ title=f"Solution of Nonlinear BVP y'' = -3 y y' (n = {n})",
1778
+ xaxis_title="x",
1779
+ yaxis_title="y(x)",
1780
+ height=440,
1781
+ )
1782
+ return fig
1783
+
1784
+
1785
+ def plot_fdm_poisson_2d(U, A):
1786
+ """Plot the 2D Poisson solution heatmap and matrix sparsity pattern."""
1787
+ n = U.shape[0] - 1
1788
+ coords = np.linspace(0.0, 1.0, n + 1)
1789
+ rows, cols = np.nonzero(A)
1790
+
1791
+ fig = make_subplots(
1792
+ rows=1,
1793
+ cols=2,
1794
+ subplot_titles=(
1795
+ f"Solution u(x, y) ({n + 1}x{n + 1} grid)",
1796
+ f"Sparsity Pattern of A ({A.shape[0]}x{A.shape[1]})",
1797
+ ),
1798
+ )
1799
+ fig.add_trace(
1800
+ go.Heatmap(
1801
+ x=coords, y=coords, z=U, colorscale="Viridis",
1802
+ colorbar=dict(title="u(x, y)", x=0.45),
1803
+ ),
1804
+ row=1, col=1,
1805
+ )
1806
+ fig.add_trace(
1807
+ go.Scatter(
1808
+ x=cols, y=rows, mode="markers", name="Nonzero entries",
1809
+ marker=dict(color="#1F2937", size=4, symbol="square"),
1810
+ showlegend=False,
1811
+ ),
1812
+ row=1, col=2,
1813
+ )
1814
+ fig.update_xaxes(title_text="x", row=1, col=1)
1815
+ fig.update_yaxes(title_text="y", row=1, col=1)
1816
+ fig.update_xaxes(title_text="Column index", row=1, col=2)
1817
+ fig.update_yaxes(
1818
+ title_text="Row index", autorange="reversed", row=1, col=2
1819
+ )
1820
+ fig.update_layout(
1821
+ template="plotly_white",
1822
+ title="2D Poisson BVP Solution and Stencil Matrix Sparsity",
1823
+ height=460,
1824
+ )
1825
+ return fig
1826
+
1827
+
1828
+