executable-engineering 0.1.53__py3-none-any.whl → 0.1.54__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,1386 @@
1
+ import numpy as np
2
+ import plotly.graph_objects as go
3
+ from plotly.subplots import make_subplots
4
+
5
+
6
+ def forward_euler(f, t0, y0, t_end, h):
7
+ t_points = np.arange(t0, t_end + h / 2, h)
8
+ y_points = np.zeros_like(t_points, dtype=float)
9
+ y_points[0] = y0
10
+
11
+ for i in range(len(t_points) - 1):
12
+ y_points[i + 1] = y_points[i] + h * f(t_points[i], y_points[i])
13
+
14
+ return {
15
+ "t_points": t_points,
16
+ "y_points": y_points,
17
+ "h": h,
18
+ "method": "Forward Euler",
19
+ }
20
+
21
+
22
+ def heun_method(f, t0, y0, t_end, h, iterations=1):
23
+ t_points = np.arange(t0, t_end + h / 2, h)
24
+ y_points = np.zeros_like(t_points, dtype=float)
25
+ y_points[0] = y0
26
+ cycle_history = []
27
+
28
+ for i in range(len(t_points) - 1):
29
+ t_i, y_i = t_points[i], y_points[i]
30
+ k1 = f(t_i, y_i)
31
+ y_pred = y_i + h * k1
32
+ step_cycles = [y_pred]
33
+
34
+ for _ in range(iterations):
35
+ k2 = f(t_i + h, y_pred)
36
+ y_pred = y_i + h * (k1 + k2) / 2.0
37
+ step_cycles.append(y_pred)
38
+
39
+ y_points[i + 1] = y_pred
40
+ cycle_history.append(step_cycles)
41
+
42
+ return {
43
+ "t_points": t_points,
44
+ "y_points": y_points,
45
+ "cycle_history": cycle_history,
46
+ "h": h,
47
+ "iterations": iterations,
48
+ "method": f"Heun's Method ({iterations} iter)",
49
+ }
50
+
51
+
52
+ def midpoint_ode(f, t0, y0, t_end, h):
53
+ t_points = np.arange(t0, t_end + h / 2, h)
54
+ y_points = np.zeros_like(t_points, dtype=float)
55
+ y_points[0] = y0
56
+
57
+ for i in range(len(t_points) - 1):
58
+ t_i, y_i = t_points[i], y_points[i]
59
+ k1 = f(t_i, y_i)
60
+ k2 = f(t_i + 0.5 * h, y_i + 0.5 * h * k1)
61
+ y_points[i + 1] = y_points[i] + h * k2
62
+
63
+ return {
64
+ "t_points": t_points,
65
+ "y_points": y_points,
66
+ "h": h,
67
+ "method": "Midpoint Method (RK2)",
68
+ }
69
+
70
+
71
+ def ralston_method(f, t0, y0, t_end, h):
72
+ t_points = np.arange(t0, t_end + h / 2, h)
73
+ y_points = np.zeros_like(t_points, dtype=float)
74
+ y_points[0] = y0
75
+
76
+ for i in range(len(t_points) - 1):
77
+ t_i, y_i = t_points[i], y_points[i]
78
+ k1 = f(t_i, y_i)
79
+ k2 = f(t_i + 0.75 * h, y_i + 0.75 * h * k1)
80
+ y_points[i + 1] = y_points[i] + h * (k1 + 2.0 * k2) / 3.0
81
+
82
+ return {
83
+ "t_points": t_points,
84
+ "y_points": y_points,
85
+ "h": h,
86
+ "method": "Ralston's Method (RK2)",
87
+ }
88
+
89
+
90
+ def rk3_method(f, t0, y0, t_end, h):
91
+ t_points = np.arange(t0, t_end + h / 2, h)
92
+ y_points = np.zeros_like(t_points, dtype=float)
93
+ y_points[0] = y0
94
+
95
+ for i in range(len(t_points) - 1):
96
+ t_i, y_i = t_points[i], y_points[i]
97
+ k1 = f(t_i, y_i)
98
+ k2 = f(t_i + 0.5 * h, y_i + 0.5 * h * k1)
99
+ k3 = f(t_i + h, y_i - h * k1 + 2.0 * h * k2)
100
+ y_points[i + 1] = y_points[i] + h * (k1 + 4.0 * k2 + k3) / 6.0
101
+
102
+ return {
103
+ "t_points": t_points,
104
+ "y_points": y_points,
105
+ "h": h,
106
+ "method": "Classical RK3",
107
+ }
108
+
109
+
110
+ def rk4_method(f, t0, y0, t_end, h):
111
+ t_points = np.arange(t0, t_end + h / 2, h)
112
+ y_points = np.zeros_like(t_points, dtype=float)
113
+ y_points[0] = y0
114
+
115
+ for i in range(len(t_points) - 1):
116
+ t_i, y_i = t_points[i], y_points[i]
117
+ k1 = f(t_i, y_i)
118
+ k2 = f(t_i + 0.5 * h, y_i + 0.5 * h * k1)
119
+ k3 = f(t_i + 0.5 * h, y_i + 0.5 * h * k2)
120
+ k4 = f(t_i + h, y_i + h * k3)
121
+ y_points[i + 1] = y_points[i] + h * (k1 + 2.0 * k2 + 2.0 * k3 + k4) / 6.0
122
+
123
+ return {
124
+ "t_points": t_points,
125
+ "y_points": y_points,
126
+ "h": h,
127
+ "method": "Classical RK4",
128
+ }
129
+
130
+
131
+ def plot_direction_field(
132
+ f,
133
+ t_range=(0, 4),
134
+ y_range=(0, 10),
135
+ y_true=None,
136
+ trajectories=None,
137
+ n_grid=16,
138
+ title="Direction Field & Solution Trajectories",
139
+ ):
140
+ t_grid = np.linspace(t_range[0], t_range[1], n_grid)
141
+ y_grid = np.linspace(y_range[0], y_range[1], n_grid)
142
+ T, Y = np.meshgrid(t_grid, y_grid)
143
+ slopes = f(T, Y)
144
+
145
+ dt = (t_range[1] - t_range[0]) / (n_grid * 2.6)
146
+ dy_scale = (y_range[1] - y_range[0]) / (t_range[1] - t_range[0])
147
+
148
+ seg_t = []
149
+ seg_y = []
150
+ for i in range(n_grid):
151
+ for j in range(n_grid):
152
+ ti = T[i, j]
153
+ yi = Y[i, j]
154
+ s = slopes[i, j]
155
+ norm = np.sqrt(1.0 + (s / dy_scale) ** 2)
156
+ d_t = dt / norm
157
+ d_y = s * d_t
158
+ seg_t.extend([ti - d_t, ti + d_t, None])
159
+ seg_y.extend([yi - d_y, yi + d_y, None])
160
+
161
+ fig = go.Figure()
162
+ fig.add_trace(
163
+ go.Scatter(
164
+ x=seg_t,
165
+ y=seg_y,
166
+ mode="lines",
167
+ name="Slope Field f(t, y)",
168
+ line=dict(color="rgba(148, 163, 184, 0.7)", width=1.5),
169
+ hoverinfo="skip",
170
+ )
171
+ )
172
+
173
+ t_dense = np.linspace(t_range[0], t_range[1], 300)
174
+ if y_true is not None:
175
+ fig.add_trace(
176
+ go.Scatter(
177
+ x=t_dense,
178
+ y=y_true(t_dense),
179
+ mode="lines",
180
+ name="Exact Solution y(t)",
181
+ line=dict(color="#111827", width=3, dash="dash"),
182
+ )
183
+ )
184
+
185
+ palette = ["#2563EB", "#DC2626", "#059669", "#D97706", "#7C3AED"]
186
+ if trajectories:
187
+ if isinstance(trajectories, dict) and "t_points" in trajectories:
188
+ trajectories = {trajectories.get("method", "Approximation"): trajectories}
189
+ for idx, (label, data) in enumerate(trajectories.items()):
190
+ c = palette[idx % len(palette)]
191
+ t_pts = data["t_points"] if isinstance(data, dict) else data[0]
192
+ y_pts = data["y_points"] if isinstance(data, dict) else data[1]
193
+ fig.add_trace(
194
+ go.Scatter(
195
+ x=t_pts,
196
+ y=y_pts,
197
+ mode="lines+markers",
198
+ name=label,
199
+ line=dict(color=c, width=2.2),
200
+ marker=dict(size=7, symbol="circle"),
201
+ )
202
+ )
203
+
204
+ fig.update_layout(
205
+ title=title,
206
+ xaxis_title="Time t",
207
+ yaxis_title="y(t)",
208
+ xaxis=dict(range=list(t_range)),
209
+ yaxis=dict(range=list(y_range)),
210
+ template="plotly_white",
211
+ hovermode="x unified",
212
+ height=460,
213
+ legend=dict(x=0.02, y=0.98, bgcolor="rgba(255, 255, 255, 0.85)"),
214
+ )
215
+ return fig
216
+
217
+
218
+ def plot_ode_comparison(
219
+ t_range,
220
+ y_true,
221
+ results_dict,
222
+ title="Explicit Runge-Kutta Methods vs. Exact Solution",
223
+ ):
224
+ t_dense = np.linspace(t_range[0], t_range[1], 300)
225
+ y_exact_dense = y_true(t_dense)
226
+
227
+ fig = make_subplots(
228
+ rows=2,
229
+ cols=1,
230
+ shared_xaxes=True,
231
+ vertical_spacing=0.1,
232
+ subplot_titles=("Solution Trajectories y(t)", "Global Truncation Error |y_i - y(t_i)|"),
233
+ row_heights=[0.62, 0.38],
234
+ )
235
+
236
+ fig.add_trace(
237
+ go.Scatter(
238
+ x=t_dense,
239
+ y=y_exact_dense,
240
+ mode="lines",
241
+ name="Exact Solution",
242
+ line=dict(color="#111827", width=3, dash="dash"),
243
+ ),
244
+ row=1,
245
+ col=1,
246
+ )
247
+
248
+ palette = ["#2563EB", "#D97706", "#059669", "#DC2626", "#7C3AED", "#0891B2"]
249
+ for idx, (label, res) in enumerate(results_dict.items()):
250
+ c = palette[idx % len(palette)]
251
+ t_pts = res["t_points"]
252
+ y_pts = res["y_points"]
253
+ err = np.maximum(np.abs(y_pts - y_true(t_pts)), 1e-16)
254
+
255
+ fig.add_trace(
256
+ go.Scatter(
257
+ x=t_pts,
258
+ y=y_pts,
259
+ mode="lines+markers",
260
+ name=label,
261
+ line=dict(color=c, width=2),
262
+ marker=dict(size=7),
263
+ ),
264
+ row=1,
265
+ col=1,
266
+ )
267
+ fig.add_trace(
268
+ go.Scatter(
269
+ x=t_pts[1:],
270
+ y=err[1:],
271
+ mode="lines+markers",
272
+ name=f"{label} Error",
273
+ line=dict(color=c, width=1.8),
274
+ marker=dict(size=6, symbol="diamond"),
275
+ showlegend=False,
276
+ ),
277
+ row=2,
278
+ col=1,
279
+ )
280
+
281
+ fig.update_yaxes(title_text="y(t)", row=1, col=1)
282
+ fig.update_yaxes(title_text="Absolute Error", type="log", row=2, col=1)
283
+ fig.update_xaxes(title_text="Time t", row=2, col=1)
284
+ fig.update_layout(
285
+ title=title,
286
+ template="plotly_white",
287
+ hovermode="x unified",
288
+ height=540,
289
+ legend=dict(orientation="h", yanchor="bottom", y=1.03, xanchor="right", x=1),
290
+ )
291
+ return fig
292
+
293
+
294
+ def plot_heun_iterations(
295
+ f,
296
+ y_true,
297
+ t0=0.0,
298
+ y0=2.0,
299
+ t_end=4.0,
300
+ h=1.0,
301
+ max_iter=15,
302
+ title="Heun's Predictor-Corrector: 1 vs. 15 Iterations",
303
+ ):
304
+ res_1 = heun_method(f, t0, y0, t_end, h, iterations=1)
305
+ res_m = heun_method(f, t0, y0, t_end, h, iterations=max_iter)
306
+
307
+ t_dense = np.linspace(t0, t_end, 300)
308
+ fig = make_subplots(
309
+ rows=1,
310
+ cols=2,
311
+ subplot_titles=(
312
+ "Global Trajectory Comparison",
313
+ f"Corrector Convergence at Step 1 (t = {t0 + h})",
314
+ ),
315
+ horizontal_spacing=0.12,
316
+ )
317
+
318
+ fig.add_trace(
319
+ go.Scatter(
320
+ x=t_dense,
321
+ y=y_true(t_dense),
322
+ mode="lines",
323
+ name="Exact Solution",
324
+ line=dict(color="#111827", width=3, dash="dash"),
325
+ ),
326
+ row=1,
327
+ col=1,
328
+ )
329
+ fig.add_trace(
330
+ go.Scatter(
331
+ x=res_1["t_points"],
332
+ y=res_1["y_points"],
333
+ mode="lines+markers",
334
+ name="Heun (1 iteration)",
335
+ line=dict(color="#2563EB", width=2.2),
336
+ marker=dict(size=8),
337
+ ),
338
+ row=1,
339
+ col=1,
340
+ )
341
+ fig.add_trace(
342
+ go.Scatter(
343
+ x=res_m["t_points"],
344
+ y=res_m["y_points"],
345
+ mode="lines+markers",
346
+ name=f"Heun ({max_iter} iterations)",
347
+ line=dict(color="#DC2626", width=2.2),
348
+ marker=dict(size=8, symbol="square"),
349
+ ),
350
+ row=1,
351
+ col=1,
352
+ )
353
+
354
+ step1_cycles = res_m["cycle_history"][0]
355
+ iters = list(range(len(step1_cycles)))
356
+ true_step1 = float(y_true(t0 + h))
357
+
358
+ fig.add_trace(
359
+ go.Scatter(
360
+ x=iters,
361
+ y=step1_cycles,
362
+ mode="lines+markers",
363
+ name="Corrector Sequence y_1^(k)",
364
+ line=dict(color="#7C3AED", width=2.2),
365
+ marker=dict(size=7),
366
+ ),
367
+ row=1,
368
+ col=2,
369
+ )
370
+ fig.add_trace(
371
+ go.Scatter(
372
+ x=[0, max_iter],
373
+ y=[true_step1, true_step1],
374
+ mode="lines",
375
+ name=f"Exact y({t0 + h}) = {true_step1:.4f}",
376
+ line=dict(color="#111827", width=2, dash="dot"),
377
+ ),
378
+ row=1,
379
+ col=2,
380
+ )
381
+
382
+ fig.update_xaxes(title_text="Time t", row=1, col=1)
383
+ fig.update_yaxes(title_text="y(t)", row=1, col=1)
384
+ fig.update_xaxes(title_text="Corrector Iteration k", row=1, col=2)
385
+ fig.update_yaxes(title_text="Approximation y_1", row=1, col=2)
386
+ fig.update_layout(
387
+ title=title,
388
+ template="plotly_white",
389
+ height=450,
390
+ legend=dict(orientation="h", yanchor="bottom", y=1.05, xanchor="right", x=1),
391
+ )
392
+ return fig
393
+
394
+
395
+ def plot_rk4_stages(
396
+ f,
397
+ y_true,
398
+ t0=0.0,
399
+ y0=2.0,
400
+ h=1.0,
401
+ title="Geometric Anatomy of a Single Classical RK4 Step",
402
+ ):
403
+ k1 = f(t0, y0)
404
+ t_half = t0 + 0.5 * h
405
+ y_k1 = y0 + 0.5 * h * k1
406
+ k2 = f(t_half, y_k1)
407
+ y_k2 = y0 + 0.5 * h * k2
408
+ k3 = f(t_half, y_k2)
409
+ t1 = t0 + h
410
+ y_k3 = y0 + h * k3
411
+ k4 = f(t1, y_k3)
412
+ y_rk4 = y0 + (h / 6.0) * (k1 + 2.0 * k2 + 2.0 * k3 + k4)
413
+
414
+ t_dense = np.linspace(t0, t1 + 0.15 * h, 200)
415
+ fig = go.Figure()
416
+
417
+ fig.add_trace(
418
+ go.Scatter(
419
+ x=t_dense,
420
+ y=y_true(t_dense),
421
+ mode="lines",
422
+ name="Exact Solution y(t)",
423
+ line=dict(color="#111827", width=3),
424
+ )
425
+ )
426
+
427
+ # Trial step lines from (t0, y0)
428
+ fig.add_trace(
429
+ go.Scatter(
430
+ x=[t0, t_half],
431
+ y=[y0, y_k1],
432
+ mode="lines+markers",
433
+ name=f"Stage 1 → Midpoint (k1={k1:.2f})",
434
+ line=dict(color="#2563EB", width=2, dash="dot"),
435
+ marker=dict(size=8),
436
+ )
437
+ )
438
+ fig.add_trace(
439
+ go.Scatter(
440
+ x=[t0, t_half],
441
+ y=[y0, y_k2],
442
+ mode="lines+markers",
443
+ name=f"Stage 2 → Corrected Midpoint (k2={k2:.2f})",
444
+ line=dict(color="#D97706", width=2, dash="dot"),
445
+ marker=dict(size=8),
446
+ )
447
+ )
448
+ fig.add_trace(
449
+ go.Scatter(
450
+ x=[t0, t1],
451
+ y=[y0, y_k3],
452
+ mode="lines+markers",
453
+ name=f"Stage 3 → Endpoint Trial (k3={k3:.2f})",
454
+ line=dict(color="#7C3AED", width=2, dash="dot"),
455
+ marker=dict(size=8),
456
+ )
457
+ )
458
+
459
+ # Short tangent slope segments at each stage evaluation point
460
+ seg_len = 0.18 * h
461
+ stages = [
462
+ (t0, y0, k1, "k1", "#2563EB"),
463
+ (t_half, y_k1, k2, "k2", "#D97706"),
464
+ (t_half, y_k2, k3, "k3", "#7C3AED"),
465
+ (t1, y_k3, k4, "k4", "#DC2626"),
466
+ ]
467
+ for ts, ys, ks, lbl, col in stages:
468
+ fig.add_trace(
469
+ go.Scatter(
470
+ x=[ts, ts + seg_len],
471
+ y=[ys, ys + ks * seg_len],
472
+ mode="lines",
473
+ name=f"Slope {lbl} = {ks:.2f}",
474
+ line=dict(color=col, width=3.5),
475
+ showlegend=(lbl == "k4"),
476
+ )
477
+ )
478
+
479
+ # Final weighted RK4 step
480
+ fig.add_trace(
481
+ go.Scatter(
482
+ x=[t0, t1],
483
+ y=[y0, y_rk4],
484
+ mode="lines+markers",
485
+ name=f"Final RK4 Step (y1={y_rk4:.4f})",
486
+ line=dict(color="#059669", width=3),
487
+ marker=dict(size=11, symbol="star"),
488
+ )
489
+ )
490
+
491
+ fig.add_vline(x=t_half, line_dash="dash", line_color="#9CA3AF", annotation_text="t0 + h/2")
492
+ fig.add_vline(x=t1, line_dash="dash", line_color="#9CA3AF", annotation_text="t0 + h")
493
+
494
+ fig.update_layout(
495
+ title=title,
496
+ xaxis_title="Time t",
497
+ yaxis_title="y(t)",
498
+ template="plotly_white",
499
+ hovermode="closest",
500
+ height=480,
501
+ legend=dict(x=0.02, y=0.98, bgcolor="rgba(255, 255, 255, 0.85)"),
502
+ )
503
+ return fig
504
+
505
+
506
+ def rk4_step(f, t, y, h):
507
+ k1 = h * f(t, y)
508
+ k2 = h * f(t + 0.5 * h, y + 0.5 * k1)
509
+ k3 = h * f(t + 0.5 * h, y + 0.5 * k2)
510
+ k4 = h * f(t + h, y + k3)
511
+ return y + (k1 + 2.0 * k2 + 2.0 * k3 + k4) / 6.0
512
+
513
+
514
+ def backward_euler(f, t0, y0, t_end, h):
515
+ from scipy.optimize import root
516
+
517
+ t_points = np.arange(t0, t_end + h / 2, h)
518
+ y_points = np.zeros_like(t_points, dtype=float)
519
+ y_points[0] = y0
520
+
521
+ for i in range(len(t_points) - 1):
522
+ t_next = t_points[i + 1]
523
+ y_curr = y_points[i]
524
+ sol = root(lambda y_val: y_val - (y_curr + h * f(t_next, y_val)), y_curr)
525
+ y_points[i + 1] = sol.x[0]
526
+
527
+ return {
528
+ "t_points": t_points,
529
+ "y_points": y_points,
530
+ "h": h,
531
+ "method": "Backward Euler",
532
+ }
533
+
534
+
535
+ def plot_transient_function(
536
+ t_range=(0.0, 10.0),
537
+ n_coarse=12,
538
+ title="Fast Transient vs. Slow Drift: y(t) = tanh((t - 5) / 0.1) - t",
539
+ ):
540
+ t_dense = np.linspace(t_range[0], t_range[1], 600)
541
+ y_dense = np.tanh((t_dense - 5.0) / 0.1) - t_dense
542
+
543
+ t_coarse = np.linspace(t_range[0], t_range[1], n_coarse)
544
+ y_coarse = np.tanh((t_coarse - 5.0) / 0.1) - t_coarse
545
+
546
+ fig = go.Figure()
547
+ fig.add_trace(
548
+ go.Scatter(
549
+ x=t_dense,
550
+ y=y_dense,
551
+ mode="lines",
552
+ name="Exact Curve (Fine Resolution)",
553
+ line=dict(color="#2563EB", width=3),
554
+ )
555
+ )
556
+ fig.add_trace(
557
+ go.Scatter(
558
+ x=t_coarse,
559
+ y=y_coarse,
560
+ mode="lines+markers",
561
+ name=f"Coarse Uniform Step ({n_coarse} points)",
562
+ line=dict(color="#DC2626", width=2, dash="dash"),
563
+ marker=dict(size=8, symbol="circle"),
564
+ )
565
+ )
566
+
567
+ fig.add_vrect(
568
+ x0=4.7,
569
+ x1=5.3,
570
+ fillcolor="rgba(245, 158, 11, 0.18)",
571
+ line_width=0,
572
+ annotation_text="Sharp Transient",
573
+ annotation_position="top left",
574
+ )
575
+
576
+ fig.update_layout(
577
+ title=title,
578
+ xaxis_title="Time t",
579
+ yaxis_title="y(t)",
580
+ template="plotly_white",
581
+ hovermode="x unified",
582
+ height=440,
583
+ legend=dict(x=0.02, y=0.15, bgcolor="rgba(255, 255, 255, 0.85)"),
584
+ )
585
+ return fig
586
+
587
+
588
+ def plot_rk45_adaptive(
589
+ sol,
590
+ y_true=None,
591
+ title="Adaptive Runge-Kutta-Fehlberg (RK45) Trajectory & Step Sizes",
592
+ ):
593
+ t_pts = sol.t
594
+ y_pts = sol.y[0]
595
+ step_sizes = np.diff(t_pts)
596
+
597
+ fig = make_subplots(
598
+ rows=2,
599
+ cols=1,
600
+ shared_xaxes=True,
601
+ vertical_spacing=0.12,
602
+ subplot_titles=(
603
+ "Solution Trajectory y(t) & Adaptive Nodes",
604
+ "Adaptive Step Size h_i = t_{i+1} - t_i",
605
+ ),
606
+ row_heights=[0.62, 0.38],
607
+ )
608
+
609
+ if y_true is not None:
610
+ t_dense = np.linspace(t_pts[0], t_pts[-1], 300)
611
+ fig.add_trace(
612
+ go.Scatter(
613
+ x=t_dense,
614
+ y=y_true(t_dense),
615
+ mode="lines",
616
+ name="Exact Solution",
617
+ line=dict(color="#111827", width=3, dash="dash"),
618
+ ),
619
+ row=1,
620
+ col=1,
621
+ )
622
+
623
+ fig.add_trace(
624
+ go.Scatter(
625
+ x=t_pts,
626
+ y=y_pts,
627
+ mode="lines+markers",
628
+ name=f"RK45 Nodes ({len(t_pts)} steps)",
629
+ line=dict(color="#2563EB", width=2.2),
630
+ marker=dict(size=9, symbol="circle"),
631
+ ),
632
+ row=1,
633
+ col=1,
634
+ )
635
+
636
+ fig.add_trace(
637
+ go.Scatter(
638
+ x=t_pts[:-1],
639
+ y=step_sizes,
640
+ mode="lines+markers",
641
+ name="Step Size h",
642
+ line=dict(color="#059669", width=2.2, shape="hv"),
643
+ marker=dict(size=8, symbol="diamond"),
644
+ ),
645
+ row=2,
646
+ col=1,
647
+ )
648
+
649
+ fig.update_yaxes(title_text="y(t)", row=1, col=1)
650
+ fig.update_yaxes(title_text="Step Size h", row=2, col=1)
651
+ fig.update_xaxes(title_text="Time t", row=2, col=1)
652
+ fig.update_layout(
653
+ title=title,
654
+ template="plotly_white",
655
+ hovermode="x unified",
656
+ height=520,
657
+ legend=dict(orientation="h", yanchor="bottom", y=1.03, xanchor="right", x=1),
658
+ )
659
+ return fig
660
+
661
+
662
+ def plot_euler_stability(
663
+ t_end=20.0,
664
+ y0=2.0,
665
+ title="Numerical Stability on dy/dt = -y: Explicit vs. Implicit Euler",
666
+ ):
667
+ h_values = [0.2, 0.5, 0.8, 1.2, 1.8, 2.0, 2.15, 2.3]
668
+ default_idx = 2 # h = 0.8
669
+
670
+ t_dense = np.linspace(0.0, t_end, 400)
671
+ y_exact = y0 * np.exp(-t_dense)
672
+
673
+ fig = go.Figure()
674
+
675
+ # Trace 0: Exact solution (always visible)
676
+ fig.add_trace(
677
+ go.Scatter(
678
+ x=t_dense,
679
+ y=y_exact,
680
+ mode="lines",
681
+ name="Exact Solution y(t) = 2e^(-t)",
682
+ line=dict(color="#111827", width=3, dash="dash"),
683
+ visible=True,
684
+ )
685
+ )
686
+
687
+ for idx, h in enumerate(h_values):
688
+ t_pts = np.arange(0.0, t_end + h / 2, h)
689
+ y_exp = np.zeros_like(t_pts)
690
+ y_imp = np.zeros_like(t_pts)
691
+ y_exp[0] = y0
692
+ y_imp[0] = y0
693
+ for i in range(1, len(t_pts)):
694
+ y_exp[i] = y_exp[i - 1] * (1.0 - h)
695
+ y_imp[i] = y_imp[i - 1] / (1.0 + h)
696
+
697
+ is_vis = idx == default_idx
698
+ fig.add_trace(
699
+ go.Scatter(
700
+ x=t_pts,
701
+ y=y_exp,
702
+ mode="lines+markers",
703
+ name=f"Forward Euler (h = {h})",
704
+ line=dict(color="#2563EB", width=2.2),
705
+ marker=dict(size=7, symbol="circle"),
706
+ visible=is_vis,
707
+ )
708
+ )
709
+ fig.add_trace(
710
+ go.Scatter(
711
+ x=t_pts,
712
+ y=y_imp,
713
+ mode="lines+markers",
714
+ name=f"Backward Euler (h = {h})",
715
+ line=dict(color="#DC2626", width=2.2),
716
+ marker=dict(size=7, symbol="x"),
717
+ visible=is_vis,
718
+ )
719
+ )
720
+
721
+ steps = []
722
+ for idx, h in enumerate(h_values):
723
+ vis = [True] + [False] * (2 * len(h_values))
724
+ vis[1 + 2 * idx] = True
725
+ vis[1 + 2 * idx + 1] = True
726
+ regime = (
727
+ "Monotonic decay"
728
+ if h < 1.0
729
+ else ("Damped oscillation" if h < 2.0 else ("Neutral oscillation" if h == 2.0 else "Unstable divergence!"))
730
+ )
731
+ steps.append(
732
+ dict(
733
+ method="update",
734
+ args=[
735
+ {"visible": vis},
736
+ {"title": f"{title} — Step Size h = {h} ({regime})"},
737
+ ],
738
+ label=f"{h}",
739
+ )
740
+ )
741
+
742
+ fig.update_layout(
743
+ title=f"{title} — Step Size h = {h_values[default_idx]} (Monotonic decay)",
744
+ xaxis_title="Time t",
745
+ yaxis_title="y(t)",
746
+ xaxis=dict(range=[0, t_end]),
747
+ template="plotly_white",
748
+ hovermode="x unified",
749
+ height=520,
750
+ legend=dict(x=0.58, y=0.98, bgcolor="rgba(255, 255, 255, 0.85)"),
751
+ sliders=[
752
+ dict(
753
+ active=default_idx,
754
+ currentvalue={"prefix": "Step size h = "},
755
+ pad={"t": 45},
756
+ steps=steps,
757
+ )
758
+ ],
759
+ )
760
+ return fig
761
+
762
+
763
+ def plot_stiff_ode(
764
+ title="Analytical Solution of Stiff ODE: y(t) = 3 - 0.998e^(-1000t) - 2.002e^(-t)",
765
+ ):
766
+ limits = [0.005, 0.02, 0.1, 0.5, 1.5, 3.0, 5.0]
767
+ default_idx = 5 # limit = 3.0
768
+
769
+ fig = go.Figure()
770
+ for idx, lim in enumerate(limits):
771
+ t = np.linspace(0.0, lim, 500)
772
+ y = 3.0 - 0.998 * np.exp(-1000.0 * t) - 2.002 * np.exp(-t)
773
+ fig.add_trace(
774
+ go.Scatter(
775
+ x=t,
776
+ y=y,
777
+ mode="lines",
778
+ name=f"y(t) on [0, {lim}]",
779
+ line=dict(color="#2563EB", width=3),
780
+ visible=(idx == default_idx),
781
+ )
782
+ )
783
+
784
+ steps = []
785
+ for idx, lim in enumerate(limits):
786
+ vis = [i == idx for i in range(len(limits))]
787
+ steps.append(
788
+ dict(
789
+ method="update",
790
+ args=[
791
+ {"visible": vis},
792
+ {
793
+ "title": f"{title} (t_max = {lim})",
794
+ "xaxis.range": [0, lim],
795
+ },
796
+ ],
797
+ label=f"{lim}",
798
+ )
799
+ )
800
+
801
+ fig.update_layout(
802
+ title=f"{title} (t_max = {limits[default_idx]})",
803
+ xaxis_title="Time t",
804
+ yaxis_title="y(t)",
805
+ xaxis=dict(range=[0, limits[default_idx]]),
806
+ template="plotly_white",
807
+ hovermode="x unified",
808
+ height=500,
809
+ sliders=[
810
+ dict(
811
+ active=default_idx,
812
+ currentvalue={"prefix": "Time Window t_max = "},
813
+ pad={"t": 45},
814
+ steps=steps,
815
+ )
816
+ ],
817
+ )
818
+ return fig
819
+
820
+
821
+ def plot_stiff_euler_comparison(
822
+ t0=0.01,
823
+ t_end=0.05,
824
+ title="Stiff ODE on [0.01, 0.05]: Explicit vs. Implicit Euler",
825
+ ):
826
+ h_values = [0.0002, 0.0005, 0.001, 0.0015, 0.002, 0.003, 0.004, 0.005]
827
+ default_idx = 1 # h = 0.0005
828
+
829
+ def y_true(t):
830
+ return 3.0 - 0.998 * np.exp(-1000.0 * t) - 2.002 * np.exp(-t)
831
+
832
+ def f_stiff(t, y):
833
+ return -1000.0 * y + 3000.0 - 2000.0 * np.exp(-t)
834
+
835
+ t_dense = np.linspace(t0, t_end, 400)
836
+ y0 = y_true(t0)
837
+
838
+ fig = go.Figure()
839
+ fig.add_trace(
840
+ go.Scatter(
841
+ x=t_dense,
842
+ y=y_true(t_dense),
843
+ mode="lines",
844
+ name="Analytical Solution",
845
+ line=dict(color="#111827", width=3, dash="dash"),
846
+ visible=True,
847
+ )
848
+ )
849
+
850
+ for idx, h in enumerate(h_values):
851
+ res_exp = forward_euler(f_stiff, t0, y0, t_end, h)
852
+ res_imp = backward_euler(f_stiff, t0, y0, t_end, h)
853
+
854
+ is_vis = idx == default_idx
855
+ fig.add_trace(
856
+ go.Scatter(
857
+ x=res_exp["t_points"],
858
+ y=res_exp["y_points"],
859
+ mode="lines+markers",
860
+ name=f"Explicit Euler (h = {h:.4f})",
861
+ line=dict(color="#2563EB", width=2),
862
+ marker=dict(size=6, symbol="circle"),
863
+ visible=is_vis,
864
+ )
865
+ )
866
+ fig.add_trace(
867
+ go.Scatter(
868
+ x=res_imp["t_points"],
869
+ y=res_imp["y_points"],
870
+ mode="lines+markers",
871
+ name=f"Implicit Euler (h = {h:.4f})",
872
+ line=dict(color="#DC2626", width=2),
873
+ marker=dict(size=6, symbol="x"),
874
+ visible=is_vis,
875
+ )
876
+ )
877
+
878
+ steps = []
879
+ for idx, h in enumerate(h_values):
880
+ vis = [True] + [False] * (2 * len(h_values))
881
+ vis[1 + 2 * idx] = True
882
+ vis[1 + 2 * idx + 1] = True
883
+ status = "Stable" if h < 0.002 else "Unstable (h > 2/1000)!"
884
+ steps.append(
885
+ dict(
886
+ method="update",
887
+ args=[
888
+ {"visible": vis},
889
+ {"title": f"{title} — h = {h:.4f} ({status})"},
890
+ ],
891
+ label=f"{h:.4f}",
892
+ )
893
+ )
894
+
895
+ fig.update_layout(
896
+ title=f"{title} — h = {h_values[default_idx]:.4f} (Stable)",
897
+ xaxis_title="Time t",
898
+ yaxis_title="y(t)",
899
+ xaxis=dict(range=[t0, t_end]),
900
+ template="plotly_white",
901
+ hovermode="x unified",
902
+ height=520,
903
+ legend=dict(x=0.02, y=0.98, bgcolor="rgba(255, 255, 255, 0.85)"),
904
+ sliders=[
905
+ dict(
906
+ active=default_idx,
907
+ currentvalue={"prefix": "Step size h = "},
908
+ pad={"t": 45},
909
+ steps=steps,
910
+ )
911
+ ],
912
+ )
913
+ return fig
914
+
915
+
916
+ def plot_pendulum_system(
917
+ t,
918
+ theta,
919
+ theta_dot,
920
+ title="Nonlinear Pendulum Motion via Reduction of Order (RK45)",
921
+ ):
922
+ fig = make_subplots(
923
+ rows=1,
924
+ cols=2,
925
+ subplot_titles=(
926
+ "Time Evolution: Angle & Angular Velocity",
927
+ "Phase Portrait: θ'(t) vs. θ(t)",
928
+ ),
929
+ horizontal_spacing=0.12,
930
+ )
931
+
932
+ fig.add_trace(
933
+ go.Scatter(
934
+ x=t,
935
+ y=theta,
936
+ mode="lines+markers",
937
+ name="Angle Θ(t) [rad]",
938
+ line=dict(color="#2563EB", width=2.5),
939
+ marker=dict(size=5),
940
+ ),
941
+ row=1,
942
+ col=1,
943
+ )
944
+ fig.add_trace(
945
+ go.Scatter(
946
+ x=t,
947
+ y=theta_dot,
948
+ mode="lines",
949
+ name="Angular Velocity dΘ/dt [rad/s]",
950
+ line=dict(color="#D97706", width=2, dash="dot"),
951
+ ),
952
+ row=1,
953
+ col=1,
954
+ )
955
+
956
+ fig.add_trace(
957
+ go.Scatter(
958
+ x=theta,
959
+ y=theta_dot,
960
+ mode="lines+markers",
961
+ name="Phase Trajectory",
962
+ line=dict(color="#059669", width=2.2),
963
+ marker=dict(size=5),
964
+ ),
965
+ row=1,
966
+ col=2,
967
+ )
968
+
969
+ fig.update_xaxes(title_text="Time t (s)", row=1, col=1)
970
+ fig.update_yaxes(title_text="State Variables", row=1, col=1)
971
+ fig.update_xaxes(title_text="Angle Θ (rad)", row=1, col=2)
972
+ fig.update_yaxes(title_text="Angular Velocity dΘ/dt (rad/s)", row=1, col=2)
973
+ fig.update_layout(
974
+ title=title,
975
+ template="plotly_white",
976
+ hovermode="closest",
977
+ height=460,
978
+ legend=dict(orientation="h", yanchor="bottom", y=1.05, xanchor="right", x=1),
979
+ )
980
+ return fig
981
+
982
+
983
+ # =====================================================================
984
+ # 3. Pedagogical PDE Solvers (1D Heat Equation)
985
+ # Exposed in notebooks via {literalinclude} and exe.display_source()
986
+ # =====================================================================
987
+
988
+
989
+ def forward_euler_heat(T0, alpha, dx, dt, num_steps):
990
+ T = T0.copy()
991
+ T_history = [T.copy()]
992
+ r = alpha * dt / dx**2
993
+ for _ in range(num_steps):
994
+ T[1:-1] = T[1:-1] + r * (T[:-2] - 2.0 * T[1:-1] + T[2:])
995
+ T_history.append(T.copy())
996
+ return np.array(T_history)
997
+
998
+
999
+ def backward_euler_heat(T0, alpha, dx, dt, num_steps):
1000
+ T = T0.copy()
1001
+ T_history = [T.copy()]
1002
+ n = len(T)
1003
+ r = alpha * dt / dx**2
1004
+ A = (
1005
+ np.diag((1.0 + 2.0 * r) * np.ones(n), 0)
1006
+ + np.diag(-r * np.ones(n - 1), -1)
1007
+ + np.diag(-r * np.ones(n - 1), 1)
1008
+ )
1009
+ A[0, :] = 0.0
1010
+ A[0, 0] = 1.0
1011
+ A[-1, :] = 0.0
1012
+ A[-1, -1] = 1.0
1013
+ for _ in range(num_steps):
1014
+ b = T.copy()
1015
+ T = np.linalg.solve(A, b)
1016
+ T_history.append(T.copy())
1017
+ return np.array(T_history)
1018
+
1019
+
1020
+ def crank_nicolson_heat(T0, alpha, dx, dt, num_steps):
1021
+ T = T0.copy()
1022
+ T_history = [T.copy()]
1023
+ n = len(T)
1024
+ r = alpha * dt / (2.0 * dx**2)
1025
+ A = (
1026
+ np.diag((1.0 + 2.0 * r) * np.ones(n), 0)
1027
+ + np.diag(-r * np.ones(n - 1), -1)
1028
+ + np.diag(-r * np.ones(n - 1), 1)
1029
+ )
1030
+ B = (
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
+ A[0, :] = 0.0
1036
+ A[0, 0] = 1.0
1037
+ A[-1, :] = 0.0
1038
+ A[-1, -1] = 1.0
1039
+ for _ in range(num_steps):
1040
+ b = B @ T
1041
+ b[0] = T[0]
1042
+ b[-1] = T[-1]
1043
+ T = np.linalg.solve(A, b)
1044
+ T_history.append(T.copy())
1045
+ return np.array(T_history)
1046
+
1047
+
1048
+ crank_nicholson_heat = crank_nicolson_heat
1049
+
1050
+
1051
+ def plot_forward_euler_heat(alpha=1.0, dx=0.05, dt_values=None, num_steps=30):
1052
+ if dt_values is None:
1053
+ dt_values = [0.0005, 0.0010, 0.00125, 0.00135, 0.0015]
1054
+
1055
+ x = np.linspace(0.0, 1.0, int(round(1.0 / dx)) + 1)
1056
+ dx_actual = x[1] - x[0]
1057
+ T0 = np.sin(np.pi * x)
1058
+
1059
+ fig = go.Figure()
1060
+ default_idx = 1
1061
+
1062
+ # Add initial condition trace (always visible)
1063
+ fig.add_trace(
1064
+ go.Scatter(
1065
+ x=x,
1066
+ y=T0,
1067
+ mode="lines",
1068
+ name="Initial T(x, 0) = sin(πx)",
1069
+ line=dict(color="#6B7280", width=2, dash="dash"),
1070
+ visible=True,
1071
+ )
1072
+ )
1073
+
1074
+ traces_per_step = 3
1075
+ for idx, dt in enumerate(dt_values):
1076
+ vis = idx == default_idx
1077
+ T_hist = forward_euler_heat(T0, alpha, dx_actual, dt, num_steps)
1078
+ t_mid = (num_steps // 2) * dt
1079
+ t_final = num_steps * dt
1080
+ T_exact = np.exp(-alpha * (np.pi**2) * t_final) * np.sin(np.pi * x)
1081
+
1082
+ fig.add_trace(
1083
+ go.Scatter(
1084
+ x=x,
1085
+ y=T_exact,
1086
+ mode="lines",
1087
+ name=f"Exact Solution (t = {t_final:.4f})",
1088
+ line=dict(color="#1F2937", width=2.5),
1089
+ visible=vis,
1090
+ )
1091
+ )
1092
+ fig.add_trace(
1093
+ go.Scatter(
1094
+ x=x,
1095
+ y=T_hist[num_steps // 2],
1096
+ mode="lines+markers",
1097
+ name=f"Forward Euler (step {num_steps // 2}, t = {t_mid:.4f})",
1098
+ line=dict(color="#3B82F6", width=2, dash="dot"),
1099
+ marker=dict(size=5),
1100
+ visible=vis,
1101
+ )
1102
+ )
1103
+ fig.add_trace(
1104
+ go.Scatter(
1105
+ x=x,
1106
+ y=T_hist[-1],
1107
+ mode="lines+markers",
1108
+ name=f"Forward Euler (step {num_steps}, t = {t_final:.4f})",
1109
+ line=dict(color="#DC2626", width=2.5),
1110
+ marker=dict(size=6),
1111
+ visible=vis,
1112
+ )
1113
+ )
1114
+
1115
+ steps = []
1116
+ for idx, dt in enumerate(dt_values):
1117
+ r_val = alpha * dt / (dx_actual**2)
1118
+ status = "Stable (r ≤ 0.5)" if r_val <= 0.5001 else "Unstable (r > 0.5)"
1119
+ vis_mask = [True] + [False] * (traces_per_step * len(dt_values))
1120
+ for k in range(traces_per_step):
1121
+ vis_mask[1 + idx * traces_per_step + k] = True
1122
+ steps.append(
1123
+ dict(
1124
+ method="update",
1125
+ args=[
1126
+ {"visible": vis_mask},
1127
+ {
1128
+ "title": (
1129
+ f"1D Heat Equation via Forward Euler "
1130
+ f"(Δx = {dx_actual:.3f}, Δt = {dt:.5f}, r = {r_val:.2f} — {status})"
1131
+ )
1132
+ },
1133
+ ],
1134
+ label=f"{dt:.5f} (r={r_val:.2f})",
1135
+ )
1136
+ )
1137
+
1138
+ r_def = alpha * dt_values[default_idx] / (dx_actual**2)
1139
+ fig.update_layout(
1140
+ title=(
1141
+ f"1D Heat Equation via Forward Euler "
1142
+ f"(Δx = {dx_actual:.3f}, Δt = {dt_values[default_idx]:.5f}, r = {r_def:.2f} — Stable (r ≤ 0.5))"
1143
+ ),
1144
+ xaxis_title="Position x",
1145
+ yaxis_title="Temperature T(x, t)",
1146
+ yaxis=dict(range=[-0.6, 1.4]),
1147
+ template="plotly_white",
1148
+ hovermode="x unified",
1149
+ height=520,
1150
+ legend=dict(x=0.02, y=0.98, bgcolor="rgba(255, 255, 255, 0.85)"),
1151
+ sliders=[
1152
+ dict(
1153
+ active=default_idx,
1154
+ currentvalue={"prefix": "Time step Δt = "},
1155
+ pad={"t": 45},
1156
+ steps=steps,
1157
+ )
1158
+ ],
1159
+ )
1160
+ return fig
1161
+
1162
+
1163
+ def plot_backward_euler_heat(alpha=0.1, dx=0.05, dt_values=None, num_steps=25):
1164
+ if dt_values is None:
1165
+ dt_values = [0.005, 0.01, 0.025, 0.05, 0.1]
1166
+
1167
+ x = np.linspace(0.0, 1.0, int(round(1.0 / dx)) + 1)
1168
+ dx_actual = x[1] - x[0]
1169
+ n = len(x)
1170
+ T0 = np.zeros_like(x)
1171
+ T0[n // 2] = 1.0
1172
+
1173
+ fig = make_subplots(
1174
+ rows=1,
1175
+ cols=2,
1176
+ column_widths=[0.65, 0.35],
1177
+ subplot_titles=(
1178
+ "Backward Euler Temperature Profiles T(x, t)",
1179
+ "Tridiagonal Sparsity Pattern of Matrix A",
1180
+ ),
1181
+ horizontal_spacing=0.12,
1182
+ )
1183
+
1184
+ sample_steps = [0, 2, 5, 12, num_steps]
1185
+ palette = ["#6B7280", "#2563EB", "#059669", "#D97706", "#DC2626"]
1186
+ default_idx = 2
1187
+
1188
+ traces_per_dt = len(sample_steps)
1189
+ for idx, dt in enumerate(dt_values):
1190
+ vis = idx == default_idx
1191
+ T_hist = backward_euler_heat(T0, alpha, dx_actual, dt, num_steps)
1192
+ for s_idx, step_num in enumerate(sample_steps):
1193
+ fig.add_trace(
1194
+ go.Scatter(
1195
+ x=x,
1196
+ y=T_hist[step_num],
1197
+ mode="lines+markers" if step_num > 0 else "lines",
1198
+ name=f"Step {step_num} (t = {step_num * dt:.3f})",
1199
+ line=dict(
1200
+ color=palette[s_idx],
1201
+ width=2.2,
1202
+ dash="dash" if step_num == 0 else "solid",
1203
+ ),
1204
+ marker=dict(size=5),
1205
+ visible=vis,
1206
+ ),
1207
+ row=1,
1208
+ col=1,
1209
+ )
1210
+
1211
+ # Sparsity pattern trace on col=2 (always visible)
1212
+ rows_idx, cols_idx = [], []
1213
+ for i in range(n):
1214
+ rows_idx.append(i)
1215
+ cols_idx.append(i)
1216
+ if i > 0 and i < n - 1:
1217
+ rows_idx.extend([i, i])
1218
+ cols_idx.extend([i - 1, i + 1])
1219
+
1220
+ fig.add_trace(
1221
+ go.Scatter(
1222
+ x=cols_idx,
1223
+ y=rows_idx,
1224
+ mode="markers",
1225
+ name="Non-zero entries of A",
1226
+ marker=dict(symbol="square", size=7, color="#1E3A8A"),
1227
+ showlegend=False,
1228
+ visible=True,
1229
+ ),
1230
+ row=1,
1231
+ col=2,
1232
+ )
1233
+
1234
+ steps = []
1235
+ total_temp_traces = traces_per_dt * len(dt_values)
1236
+ for idx, dt in enumerate(dt_values):
1237
+ r_val = alpha * dt / (dx_actual**2)
1238
+ vis_mask = [False] * total_temp_traces + [True]
1239
+ for k in range(traces_per_dt):
1240
+ vis_mask[idx * traces_per_dt + k] = True
1241
+ steps.append(
1242
+ dict(
1243
+ method="update",
1244
+ args=[
1245
+ {"visible": vis_mask},
1246
+ {
1247
+ "title": (
1248
+ f"Backward Euler 1D Heat Diffusion "
1249
+ f"(Δt = {dt:.3f}, r = {r_val:.2f} — Unconditionally Stable)"
1250
+ )
1251
+ },
1252
+ ],
1253
+ label=f"Δt={dt:.3f} (r={r_val:.1f})",
1254
+ )
1255
+ )
1256
+
1257
+ r_def = alpha * dt_values[default_idx] / (dx_actual**2)
1258
+ fig.update_xaxes(title_text="Position x", row=1, col=1)
1259
+ fig.update_yaxes(title_text="Temperature T(x, t)", range=[-0.05, 1.05], row=1, col=1)
1260
+ fig.update_xaxes(title_text="Column Index j", range=[-1, n], row=1, col=2)
1261
+ fig.update_yaxes(
1262
+ title_text="Row Index i",
1263
+ range=[n, -1],
1264
+ scaleanchor="x2",
1265
+ scaleratio=1,
1266
+ row=1,
1267
+ col=2,
1268
+ )
1269
+ fig.update_layout(
1270
+ title=(
1271
+ f"Backward Euler 1D Heat Diffusion "
1272
+ f"(Δt = {dt_values[default_idx]:.3f}, r = {r_def:.2f} — Unconditionally Stable)"
1273
+ ),
1274
+ template="plotly_white",
1275
+ hovermode="closest",
1276
+ height=520,
1277
+ legend=dict(x=0.01, y=0.98, bgcolor="rgba(255, 255, 255, 0.85)"),
1278
+ sliders=[
1279
+ dict(
1280
+ active=default_idx,
1281
+ currentvalue={"prefix": "Selected step: "},
1282
+ pad={"t": 45},
1283
+ steps=steps,
1284
+ )
1285
+ ],
1286
+ )
1287
+ return fig
1288
+
1289
+
1290
+ def plot_pde_method_comparison(alpha=0.1, dx=0.1, dt=0.02, num_steps=6):
1291
+ x = np.linspace(0.0, 1.0, int(round(1.0 / dx)) + 1)
1292
+ dx_actual = x[1] - x[0]
1293
+ T0 = np.zeros_like(x)
1294
+ T0[len(x) // 2] = 1.0
1295
+
1296
+ fe_sol = forward_euler_heat(T0, alpha, dx_actual, dt, num_steps)
1297
+ be_sol = backward_euler_heat(T0, alpha, dx_actual, dt, num_steps)
1298
+ cn_sol = crank_nicolson_heat(T0, alpha, dx_actual, dt, num_steps)
1299
+
1300
+ fig = go.Figure()
1301
+ default_step = 1
1302
+ traces_per_step = 3
1303
+
1304
+ for step_idx in range(num_steps + 1):
1305
+ vis = step_idx == default_step
1306
+ fig.add_trace(
1307
+ go.Scatter(
1308
+ x=x,
1309
+ y=fe_sol[step_idx],
1310
+ mode="lines+markers",
1311
+ name="Forward Euler (1st-order time, explicit)",
1312
+ line=dict(color="#DC2626", width=2.2, dash="dot"),
1313
+ marker=dict(size=6, symbol="circle"),
1314
+ visible=vis,
1315
+ )
1316
+ )
1317
+ fig.add_trace(
1318
+ go.Scatter(
1319
+ x=x,
1320
+ y=be_sol[step_idx],
1321
+ mode="lines+markers",
1322
+ name="Backward Euler (1st-order time, implicit)",
1323
+ line=dict(color="#2563EB", width=2.2, dash="dash"),
1324
+ marker=dict(size=6, symbol="square"),
1325
+ visible=vis,
1326
+ )
1327
+ )
1328
+ fig.add_trace(
1329
+ go.Scatter(
1330
+ x=x,
1331
+ y=cn_sol[step_idx],
1332
+ mode="lines+markers",
1333
+ name="Crank-Nicolson (2nd-order time, implicit)",
1334
+ line=dict(color="#059669", width=2.6),
1335
+ marker=dict(size=7, symbol="diamond"),
1336
+ visible=vis,
1337
+ )
1338
+ )
1339
+
1340
+ steps = []
1341
+ for step_idx in range(num_steps + 1):
1342
+ vis_mask = [False] * (traces_per_step * (num_steps + 1))
1343
+ for k in range(traces_per_step):
1344
+ vis_mask[step_idx * traces_per_step + k] = True
1345
+ t_val = step_idx * dt
1346
+ steps.append(
1347
+ dict(
1348
+ method="update",
1349
+ args=[
1350
+ {"visible": vis_mask},
1351
+ {
1352
+ "title": (
1353
+ f"Comparison of PDE Time-Stepping Schemes at Step {step_idx} "
1354
+ f"(t = {t_val:.3f} s, r = {alpha * dt / dx_actual**2:.2f})"
1355
+ )
1356
+ },
1357
+ ],
1358
+ label=f"Step {step_idx} (t={t_val:.2f})",
1359
+ )
1360
+ )
1361
+
1362
+ r_val = alpha * dt / dx_actual**2
1363
+ fig.update_layout(
1364
+ title=(
1365
+ f"Comparison of PDE Time-Stepping Schemes at Step {default_step} "
1366
+ f"(t = {default_step * dt:.3f} s, r = {r_val:.2f})"
1367
+ ),
1368
+ xaxis_title="Position x",
1369
+ yaxis_title="Temperature T(x, t)",
1370
+ yaxis=dict(range=[-0.1, 1.05]),
1371
+ template="plotly_white",
1372
+ hovermode="x unified",
1373
+ height=500,
1374
+ legend=dict(x=0.02, y=0.98, bgcolor="rgba(255, 255, 255, 0.85)"),
1375
+ sliders=[
1376
+ dict(
1377
+ active=default_step,
1378
+ currentvalue={"prefix": "Time index: "},
1379
+ pad={"t": 45},
1380
+ steps=steps,
1381
+ )
1382
+ ],
1383
+ )
1384
+ return fig
1385
+
1386
+