executable-engineering 0.1.54__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.
@@ -126,7 +126,24 @@ from .differential_equations_module import (
126
126
  plot_pendulum_system,
127
127
  plot_forward_euler_heat,
128
128
  plot_backward_euler_heat,
129
+ plot_crank_nicolson_heat,
130
+ plot_crank_nicholson_heat,
129
131
  plot_pde_method_comparison,
132
+ shooting_ballistics,
133
+ rbf_poisson_2d,
134
+ fdm_rocket_bvp,
135
+ fdm_neumann_bvp,
136
+ fdm_nonlinear_bvp,
137
+ fdm_poisson_2d,
138
+ plot_shooting_ballistics,
139
+ plot_shooting_trial_trajectories,
140
+ plot_bvp_spline_collocation,
141
+ plot_rbf_poisson_3d,
142
+ plot_fdm_rocket,
143
+ plot_fdm_neumann,
144
+ plot_fdm_neumann_convergence,
145
+ plot_fdm_nonlinear,
146
+ plot_fdm_poisson_2d,
130
147
  )
131
148
 
132
149
  from .display_code_module import display_source
@@ -258,6 +275,23 @@ __all__ = [
258
275
  "plot_pendulum_system",
259
276
  "plot_forward_euler_heat",
260
277
  "plot_backward_euler_heat",
278
+ "plot_crank_nicolson_heat",
279
+ "plot_crank_nicholson_heat",
261
280
  "plot_pde_method_comparison",
281
+ "shooting_ballistics",
282
+ "rbf_poisson_2d",
283
+ "fdm_rocket_bvp",
284
+ "fdm_neumann_bvp",
285
+ "fdm_nonlinear_bvp",
286
+ "fdm_poisson_2d",
287
+ "plot_shooting_ballistics",
288
+ "plot_shooting_trial_trajectories",
289
+ "plot_bvp_spline_collocation",
290
+ "plot_rbf_poisson_3d",
291
+ "plot_fdm_rocket",
292
+ "plot_fdm_neumann",
293
+ "plot_fdm_neumann_convergence",
294
+ "plot_fdm_nonlinear",
295
+ "plot_fdm_poisson_2d",
262
296
  "display_source",
263
297
  ]
@@ -1,6 +1,11 @@
1
+ import ipywidgets as widgets
1
2
  import numpy as np
2
3
  import plotly.graph_objects as go
4
+ from IPython.display import display
3
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
4
9
 
5
10
 
6
11
  def forward_euler(f, t0, y0, t_end, h):
@@ -1048,243 +1053,197 @@ def crank_nicolson_heat(T0, alpha, dx, dt, num_steps):
1048
1053
  crank_nicholson_heat = crank_nicolson_heat
1049
1054
 
1050
1055
 
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
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
+ )
1061
1097
 
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,
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
+ )
1071
1112
  )
1072
- )
1073
1113
 
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)
1114
+ fig = go.Figure()
1081
1115
 
1082
1116
  fig.add_trace(
1083
1117
  go.Scatter(
1084
- x=x,
1085
- y=T_exact,
1118
+ x=x_fine,
1119
+ y=T0_fine,
1086
1120
  mode="lines",
1087
- name=f"Exact Solution (t = {t_final:.4f})",
1088
- line=dict(color="#1F2937", width=2.5),
1089
- visible=vis,
1121
+ name="Initial T(x, 0) = 1 - |2x - 1|",
1122
+ line=dict(color="#6B7280", width=2, dash="dash"),
1090
1123
  )
1091
1124
  )
1092
1125
  fig.add_trace(
1093
1126
  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,
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),
1112
1132
  )
1113
1133
  )
1114
1134
 
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
+ 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)"
1135
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)"),
1136
1217
  )
1218
+ display(fig)
1137
1219
 
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
- ],
1220
+ out = widgets.interactive_output(
1221
+ render,
1222
+ {"dx_val": dx_slider, "dt_val": dt_slider, "step_val": step_slider},
1159
1223
  )
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]
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]))
1166
1229
 
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
1230
 
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
- )
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)
1183
1234
 
1184
- sample_steps = [0, 2, 5, 12, num_steps]
1185
- palette = ["#6B7280", "#2563EB", "#059669", "#D97706", "#DC2626"]
1186
- default_idx = 2
1187
1235
 
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
- )
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)
1210
1239
 
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
1240
 
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
- )
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)
1233
1244
 
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
1245
 
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
1246
+ plot_crank_nicholson_heat = plot_crank_nicolson_heat
1288
1247
 
1289
1248
 
1290
1249
  def plot_pde_method_comparison(alpha=0.1, dx=0.1, dt=0.02, num_steps=6):
@@ -1384,3 +1343,486 @@ def plot_pde_method_comparison(alpha=0.1, dx=0.1, dt=0.02, num_steps=6):
1384
1343
  return fig
1385
1344
 
1386
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
+
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: executable_engineering
3
- Version: 0.1.54
3
+ Version: 0.1.56
4
4
  Summary: Demonstrative tools for the Executable Engineering textbook
5
5
  Home-page: https://github.com/themintlab/ExecutableEngineering/tree/main/executable_engineering
6
6
  Author: Michael Welland
@@ -1,8 +1,8 @@
1
- executable_engineering/__init__.py,sha256=MsCSIb93XG71oyslRSA4K2GbJwnhbIJNCFSD8NuCN50,6674
1
+ executable_engineering/__init__.py,sha256=W6im8KuL5fH-O6e1oxwTS_73lbw6m1huzbDrlOhyyXA,7558
2
2
  executable_engineering/closedoptimization_module.py,sha256=7J6espVpgjRRwQvx35QXuaaigdX9R-P2wN5JTSpi5fI,14076
3
3
  executable_engineering/closedrootfinder_module.py,sha256=hQ6iWNi16RkZTaE_WPUEwkohmrYrAyU8WWSXO2EPLJY,6000
4
4
  executable_engineering/constrainedoptimization_module.py,sha256=rNqVnwGZdFRgc653dYM9iBy0WOcMtNF5GmtXBHzXV2k,5061
5
- executable_engineering/differential_equations_module.py,sha256=JaE6pVQY4kvJIQi5zWigbecvjCQhez87g7w4L2nOzqo,40215
5
+ executable_engineering/differential_equations_module.py,sha256=g4vJph82KfmNViCpaxKbXkRrkxSU1823VACjjkjpVIU,54613
6
6
  executable_engineering/differentiation_module.py,sha256=SNzT7R56h74dgXKvu-Z9i15A0z8-FzeRuTMz8vHEm1k,22490
7
7
  executable_engineering/display_code_module.py,sha256=KOeRQwP3O7QuD6kxwzN2HKp2uY2i1pOaI05HkxgXpLo,239
8
8
  executable_engineering/functions_module.py,sha256=rmjHi2Q_KqAmcwFnB01SluLeHwlqDZSEBiYy9Pehdpc,10780
@@ -15,8 +15,8 @@ executable_engineering/numerical_integration_module.py,sha256=TMB3_Eqr4NBTjmeYML
15
15
  executable_engineering/openoptimization_module.py,sha256=FJCnrgWS5G1Rz07F_5lxXdwBMdk0O7ll8epA-Y4gCvc,13083
16
16
  executable_engineering/openrootfinder_module.py,sha256=R_lPtCQsIGLXV-j_uDpQepImOOgtgA7I6qnhUPwWLLc,5944
17
17
  executable_engineering/optimization_module.py,sha256=GZtLSWY4VaF39HYg29HU3ZdU7yF-q5s2f8QlF6E1Uqw,12097
18
- executable_engineering-0.1.54.dist-info/licenses/LICENSE,sha256=Tg4nrt8rFhgpkPbIA8SWoCR3MlGLw0NufB8AE6-TH_o,1074
19
- executable_engineering-0.1.54.dist-info/METADATA,sha256=uCzy5UjhyxaFiWtqdm1D08sYs0gI8BLTjzJEo-XeH-w,1648
20
- executable_engineering-0.1.54.dist-info/WHEEL,sha256=mOdXR9C3wMVov7cSY8PY-XCzo3SmmWCHvGQr5csJoao,91
21
- executable_engineering-0.1.54.dist-info/top_level.txt,sha256=0U5ATV5WGTLvN9rRSjQ54TyL-ztTyXaN3FzZ_QMq4HM,23
22
- executable_engineering-0.1.54.dist-info/RECORD,,
18
+ executable_engineering-0.1.56.dist-info/licenses/LICENSE,sha256=Tg4nrt8rFhgpkPbIA8SWoCR3MlGLw0NufB8AE6-TH_o,1074
19
+ executable_engineering-0.1.56.dist-info/METADATA,sha256=r0RkYTk8OXN-vRvk8yGpoFdJu15QivFaoD41k7Fe2rE,1648
20
+ executable_engineering-0.1.56.dist-info/WHEEL,sha256=mOdXR9C3wMVov7cSY8PY-XCzo3SmmWCHvGQr5csJoao,91
21
+ executable_engineering-0.1.56.dist-info/top_level.txt,sha256=0U5ATV5WGTLvN9rRSjQ54TyL-ztTyXaN3FzZ_QMq4HM,23
22
+ executable_engineering-0.1.56.dist-info/RECORD,,