componavt commited on
Commit
2e27876
·
1 Parent(s): 792a6fc

fix of step 1

Browse files
Files changed (3) hide show
  1. app.py +118 -50
  2. differ_hug/compute.py +11 -9
  3. differ_hug/plotting.py +100 -45
app.py CHANGED
@@ -12,7 +12,7 @@ import pandas as pd
12
  import matplotlib.pyplot as plt
13
  import io
14
  import sys
15
- from typing import Tuple, Dict, Any
16
 
17
  from differ_hug.compute import (
18
  build_angles,
@@ -28,7 +28,6 @@ from differ_hug.plotting import (
28
  make_phase_portrait_figure,
29
  make_time_series_figure,
30
  make_shadowing_figure,
31
- make_metrics_table_figure,
32
  )
33
  from differ_hug.params import parameters_to_text, text_to_parameters
34
  from differ_hug.docs import documentation_markdown, system_latex, get_system_description
@@ -75,10 +74,20 @@ def run_simulation(
75
  show_connections: bool,
76
  connection_stride: int,
77
  selected_indices: list,
78
- ) -> Tuple[Any, Any, Any, Any, str, str, str, str]:
79
  """
80
  Run the ODE simulation and generate all outputs.
81
  """
 
 
 
 
 
 
 
 
 
 
82
  diagnostics = []
83
  diagnostics.append("Starting simulation...")
84
 
@@ -109,12 +118,11 @@ def run_simulation(
109
  if not solutions:
110
  diagnostics.append(" ERROR: No trajectories solved successfully")
111
  return (
112
- None, None, None, None,
113
  "\n".join(diagnostics),
114
  DEFAULT_PARAMS_TEXT,
115
  system_latex(),
116
- "ERROR: No trajectories solved successfully",
117
- ""
118
  )
119
 
120
  diagnostics.append("Step 5: Computing local z-score...")
@@ -126,8 +134,8 @@ def run_simulation(
126
  df_metrics = pd.DataFrame(metrics)
127
  df_metrics["anomaly_score"] = compute_anomaly_score(df_metrics)
128
 
129
- diagnostics.append("Step 7: Sorting by anomaly score...")
130
- df_metrics = df_metrics.sort_values(by="anomaly_score", ascending=False, na_position="last")
131
 
132
  diagnostics.append("Step 8: Creating figures...")
133
 
@@ -146,7 +154,7 @@ def run_simulation(
146
  if show_connections:
147
  shadowing_fig = make_shadowing_figure(
148
  solutions, selected_indices, solver_type,
149
- t_train_end, t_full_end, t_number
150
  )
151
 
152
  diagnostics.append("Step 9: Creating metrics table...")
@@ -160,10 +168,21 @@ def run_simulation(
160
  'curv_count_finite': 'curv_ct_fin'
161
  }
162
  df_to_display = df_to_display.rename(columns=column_rename_map)
163
- metrics_html = df_to_display.style.format("{:.3f}")._repr_html_()
 
 
 
 
 
164
 
165
  diagnostics.append("Step 10: Preparing outputs...")
166
- params_text = parameters_to_text(locals())
 
 
 
 
 
 
167
 
168
  status = f"Simulation completed. Solved {len(solutions)} trajectories."
169
  diagnostics.append(status)
@@ -174,24 +193,23 @@ def run_simulation(
174
  phase_fig,
175
  time_fig,
176
  shadowing_fig,
177
- metrics_html,
 
178
  diagnostics_text,
179
  params_text,
180
  system_latex(),
181
- status,
182
- ""
183
  )
184
 
185
  except Exception as e:
186
  error_msg = f"ERROR: {str(e)}"
187
  diagnostics.append(error_msg)
188
  return (
189
- None, None, None, None,
190
  "\n".join(diagnostics),
191
  DEFAULT_PARAMS_TEXT,
192
  system_latex(),
193
- error_msg,
194
- ""
195
  )
196
 
197
 
@@ -212,22 +230,26 @@ def apply_text_to_controls(
212
  center_x: float,
213
  center_y: float,
214
  solver_type: str,
215
- ) -> dict:
216
  """
217
  Parse text parameters and update control values.
218
  """
219
  parsed = text_to_parameters(params_text)
220
  if not parsed:
221
- return {
222
- t_number: t_number, t_train_end: t_train_end, t_full_end: t_full_end,
223
- alpha: alpha, K: K, b: b, gamma1: gamma1, gamma2: gamma2,
224
- initial_radius: initial_radius, num_points: num_points,
225
- circle_start: circle_start, circle_end: circle_end,
226
- center_x: center_x, center_y: center_y, solver_type: solver_type,
227
- params_text: DEFAULT_PARAMS_TEXT
228
- }
229
-
230
- updates = {}
 
 
 
 
231
 
232
  int_keys = {"t_number", "num_points", "circle_start", "circle_end"}
233
  float_keys = {
@@ -235,36 +257,55 @@ def apply_text_to_controls(
235
  "gamma1", "gamma2", "initial_radius", "center_x", "center_y"
236
  }
237
 
 
 
 
 
 
 
 
 
238
  for key, val in parsed.items():
239
  if key in int_keys:
240
  try:
241
- updates[key] = int(val)
242
- except Exception:
243
  pass
244
  elif key in float_keys:
245
  try:
246
- updates[key] = float(val)
247
- except Exception:
248
  pass
249
  elif key == "solver_type":
250
- updates["solver_type"] = val
251
  elif key == "circle_start_end":
252
  cs, ce = val
253
- updates["circle_start"] = cs
254
- updates["circle_end"] = ce
255
 
256
  if "circle_start" in parsed and "circle_end" in parsed:
257
  cs = int(parsed["circle_start"])
258
  ce = int(parsed["circle_end"])
259
- updates["circle_start"] = cs
260
- updates["circle_end"] = ce
261
 
 
262
  if "num_points" in parsed:
263
- updates["selected_indices"] = list(range(min(5, int(parsed["num_points"]))))
 
 
 
264
 
265
- updates["params_text"] = parameters_to_text({**parsed, **updates})
266
 
267
- return updates
 
 
 
 
 
 
 
268
 
269
 
270
  def read_controls_to_text(
@@ -307,10 +348,38 @@ def read_controls_to_text(
307
  return parameters_to_text(params)
308
 
309
 
310
- def update_selected_indices(num_points: int, solutions_len: int) -> list:
311
  """Update selected indices based on num_points."""
312
- n = min(num_points, 50)
313
- return list(range(min(5, n)))
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
314
 
315
 
316
  with gr.Blocks(title="Differ Hug: ODE Research Platform") as demo:
@@ -359,7 +428,7 @@ with gr.Blocks(title="Differ Hug: ODE Research Platform") as demo:
359
  value=DEFAULTS["solver_type"]
360
  )
361
  show_connections = gr.Checkbox(
362
- label="Show connections (DOP853 ↔ NN)",
363
  value=False
364
  )
365
  connection_stride = gr.Slider(
@@ -387,8 +456,6 @@ with gr.Blocks(title="Differ Hug: ODE Research Platform") as demo:
387
  apply_text_btn = gr.Button("Apply text → controls")
388
  read_text_btn = gr.Button("Read controls → text")
389
 
390
- status_text = gr.Textbox(label="Status", lines=2)
391
-
392
  with gr.Column(scale=2):
393
  gr.Markdown("### Outputs")
394
 
@@ -400,7 +467,8 @@ with gr.Blocks(title="Differ Hug: ODE Research Platform") as demo:
400
  with gr.TabItem("Shadowing"):
401
  shadowing_fig = gr.Plot(label="Shadowing Analysis")
402
  with gr.TabItem("Metrics"):
403
- metrics_df = gr.HTML(label="Metrics Table")
 
404
  with gr.TabItem("Documentation"):
405
  documentation = gr.Markdown(documentation_markdown())
406
  with gr.TabItem("System Equation"):
@@ -422,8 +490,8 @@ with gr.Blocks(title="Differ Hug: ODE Research Platform") as demo:
422
  selected_indices
423
  ],
424
  outputs=[
425
- phase_fig, time_fig, shadowing_fig, metrics_df,
426
- diagnostics_text, params_text, latex_eq, status_text, selected_indices
427
  ]
428
  )
429
 
@@ -454,7 +522,7 @@ with gr.Blocks(title="Differ Hug: ODE Research Platform") as demo:
454
 
455
  num_points.change(
456
  fn=update_selected_indices,
457
- inputs=[num_points, gr.Number(value=0, visible=False)],
458
  outputs=selected_indices
459
  )
460
 
 
12
  import matplotlib.pyplot as plt
13
  import io
14
  import sys
15
+ from typing import Tuple, Dict, Any, Optional
16
 
17
  from differ_hug.compute import (
18
  build_angles,
 
28
  make_phase_portrait_figure,
29
  make_time_series_figure,
30
  make_shadowing_figure,
 
31
  )
32
  from differ_hug.params import parameters_to_text, text_to_parameters
33
  from differ_hug.docs import documentation_markdown, system_latex, get_system_description
 
74
  show_connections: bool,
75
  connection_stride: int,
76
  selected_indices: list,
77
+ ) -> Tuple[Any, Any, Any, Any, Any, str, str, str, Any]:
78
  """
79
  Run the ODE simulation and generate all outputs.
80
  """
81
+ error = validate_parameters(t_number, t_train_end, t_full_end, alpha, num_points)
82
+ if error:
83
+ return (
84
+ None, None, None, None, None,
85
+ f"ERROR: {error}",
86
+ DEFAULT_PARAMS_TEXT,
87
+ system_latex(),
88
+ gr.update(choices=[], value=[])
89
+ )
90
+
91
  diagnostics = []
92
  diagnostics.append("Starting simulation...")
93
 
 
118
  if not solutions:
119
  diagnostics.append(" ERROR: No trajectories solved successfully")
120
  return (
121
+ None, None, None, None, None,
122
  "\n".join(diagnostics),
123
  DEFAULT_PARAMS_TEXT,
124
  system_latex(),
125
+ gr.update(choices=[], value=[])
 
126
  )
127
 
128
  diagnostics.append("Step 5: Computing local z-score...")
 
134
  df_metrics = pd.DataFrame(metrics)
135
  df_metrics["anomaly_score"] = compute_anomaly_score(df_metrics)
136
 
137
+ diagnostics.append("Step 7: Building trajectory choices...")
138
+ trajectory_update = build_trajectory_choices(df_metrics)
139
 
140
  diagnostics.append("Step 8: Creating figures...")
141
 
 
154
  if show_connections:
155
  shadowing_fig = make_shadowing_figure(
156
  solutions, selected_indices, solver_type,
157
+ t_train_end, t_full_end, t_number, rhs_func
158
  )
159
 
160
  diagnostics.append("Step 9: Creating metrics table...")
 
168
  'curv_count_finite': 'curv_ct_fin'
169
  }
170
  df_to_display = df_to_display.rename(columns=column_rename_map)
171
+
172
+ df_rounded = df_metrics.round(3)
173
+ csv_path = "export_metrics_rounded.csv"
174
+ df_rounded.to_csv(csv_path, index=False, float_format="%.3f")
175
+
176
+ metrics_table_value = df_to_display
177
 
178
  diagnostics.append("Step 10: Preparing outputs...")
179
+ params_text = parameters_to_text({
180
+ "t_number": t_number, "t_train_end": t_train_end, "t_full_end": t_full_end,
181
+ "alpha": alpha, "K": K, "b": b, "gamma1": gamma1, "gamma2": gamma2,
182
+ "initial_radius": initial_radius, "num_points": num_points,
183
+ "circle_start": circle_start, "circle_end": circle_end,
184
+ "center_x": center_x, "center_y": center_y, "solver_type": solver_type,
185
+ })
186
 
187
  status = f"Simulation completed. Solved {len(solutions)} trajectories."
188
  diagnostics.append(status)
 
193
  phase_fig,
194
  time_fig,
195
  shadowing_fig,
196
+ metrics_table_value,
197
+ csv_path,
198
  diagnostics_text,
199
  params_text,
200
  system_latex(),
201
+ trajectory_update
 
202
  )
203
 
204
  except Exception as e:
205
  error_msg = f"ERROR: {str(e)}"
206
  diagnostics.append(error_msg)
207
  return (
208
+ None, None, None, None, None,
209
  "\n".join(diagnostics),
210
  DEFAULT_PARAMS_TEXT,
211
  system_latex(),
212
+ gr.update(choices=[], value=[])
 
213
  )
214
 
215
 
 
230
  center_x: float,
231
  center_y: float,
232
  solver_type: str,
233
+ ) -> Tuple:
234
  """
235
  Parse text parameters and update control values.
236
  """
237
  parsed = text_to_parameters(params_text)
238
  if not parsed:
239
+ normalized_text = parameters_to_text({
240
+ "t_number": t_number, "t_train_end": t_train_end, "t_full_end": t_full_end,
241
+ "alpha": alpha, "K": K, "b": b, "gamma1": gamma1, "gamma2": gamma2,
242
+ "initial_radius": initial_radius, "num_points": num_points,
243
+ "circle_start": circle_start, "circle_end": circle_end,
244
+ "center_x": center_x, "center_y": center_y, "solver_type": solver_type,
245
+ })
246
+ selected_update = gr.update()
247
+ return (
248
+ t_number, t_train_end, t_full_end, alpha, K, b,
249
+ gamma1, gamma2, initial_radius, num_points,
250
+ circle_start, circle_end, center_x, center_y, solver_type,
251
+ normalized_text, selected_update
252
+ )
253
 
254
  int_keys = {"t_number", "num_points", "circle_start", "circle_end"}
255
  float_keys = {
 
257
  "gamma1", "gamma2", "initial_radius", "center_x", "center_y"
258
  }
259
 
260
+ result = {
261
+ "t_number": t_number, "t_train_end": t_train_end, "t_full_end": t_full_end,
262
+ "alpha": alpha, "K": K, "b": b, "gamma1": gamma1, "gamma2": gamma2,
263
+ "initial_radius": initial_radius, "num_points": num_points,
264
+ "circle_start": circle_start, "circle_end": circle_end,
265
+ "center_x": center_x, "center_y": center_y, "solver_type": solver_type,
266
+ }
267
+
268
  for key, val in parsed.items():
269
  if key in int_keys:
270
  try:
271
+ result[key] = int(val)
272
+ except (TypeError, ValueError):
273
  pass
274
  elif key in float_keys:
275
  try:
276
+ result[key] = float(val)
277
+ except (TypeError, ValueError):
278
  pass
279
  elif key == "solver_type":
280
+ result["solver_type"] = val
281
  elif key == "circle_start_end":
282
  cs, ce = val
283
+ result["circle_start"] = cs
284
+ result["circle_end"] = ce
285
 
286
  if "circle_start" in parsed and "circle_end" in parsed:
287
  cs = int(parsed["circle_start"])
288
  ce = int(parsed["circle_end"])
289
+ result["circle_start"] = cs
290
+ result["circle_end"] = ce
291
 
292
+ selected_update = gr.update()
293
  if "num_points" in parsed:
294
+ selected_update = gr.update(
295
+ choices=list(range(result["num_points"])),
296
+ value=list(range(min(5, result["num_points"])))
297
+ )
298
 
299
+ normalized_text = parameters_to_text(result)
300
 
301
+ return (
302
+ result["t_number"], result["t_train_end"], result["t_full_end"],
303
+ result["alpha"], result["K"], result["b"], result["gamma1"], result["gamma2"],
304
+ result["initial_radius"], result["num_points"],
305
+ result["circle_start"], result["circle_end"],
306
+ result["center_x"], result["center_y"], result["solver_type"],
307
+ normalized_text, selected_update
308
+ )
309
 
310
 
311
  def read_controls_to_text(
 
348
  return parameters_to_text(params)
349
 
350
 
351
+ def update_selected_indices(num_points: int) -> "gr.update":
352
  """Update selected indices based on num_points."""
353
+ n = min(int(num_points), 50)
354
+ default_ids = list(range(min(5, n)))
355
+ return gr.update(choices=list(range(n)), value=default_ids)
356
+
357
+
358
+ def validate_parameters(t_number, t_train_end, t_full_end, alpha, num_points) -> Optional[str]:
359
+ """Return an error message if parameters are invalid, otherwise None."""
360
+ if alpha <= 0:
361
+ return "alpha must be strictly positive."
362
+ if t_number < 10:
363
+ return "t_number must be at least 10."
364
+ if num_points < 1:
365
+ return "num_points must be at least 1."
366
+ if t_full_end <= t_train_end:
367
+ return "t_full_end must be greater than t_train_end."
368
+ return None
369
+
370
+
371
+ def build_trajectory_choices(df_metrics: pd.DataFrame, top_n: int = 5):
372
+ """Build (choices, default_value) for the trajectory CheckboxGroup, sorted by anomaly_score desc."""
373
+ if df_metrics.empty:
374
+ return gr.update(choices=[], value=[])
375
+ df_sorted = df_metrics.sort_values(by="anomaly_score", ascending=False, na_position="last")
376
+ choices = []
377
+ for _, row in df_sorted.iterrows():
378
+ idx = int(row["idx"])
379
+ label = f"{idx}: H={row.get('hurst', float('nan')):.3g} | score={row.get('anomaly_score', float('nan')):.3g}"
380
+ choices.append((label, idx))
381
+ default_value = [c[1] for c in choices[:top_n]]
382
+ return gr.update(choices=choices, value=default_value)
383
 
384
 
385
  with gr.Blocks(title="Differ Hug: ODE Research Platform") as demo:
 
428
  value=DEFAULTS["solver_type"]
429
  )
430
  show_connections = gr.Checkbox(
431
+ label="Show shadowing analysis (trajectory vs. perturbed trajectory)",
432
  value=False
433
  )
434
  connection_stride = gr.Slider(
 
456
  apply_text_btn = gr.Button("Apply text → controls")
457
  read_text_btn = gr.Button("Read controls → text")
458
 
 
 
459
  with gr.Column(scale=2):
460
  gr.Markdown("### Outputs")
461
 
 
467
  with gr.TabItem("Shadowing"):
468
  shadowing_fig = gr.Plot(label="Shadowing Analysis")
469
  with gr.TabItem("Metrics"):
470
+ metrics_table = gr.Dataframe(label="Metrics Table", interactive=False)
471
+ metrics_csv_file = gr.File(label="Download metrics CSV (rounded)")
472
  with gr.TabItem("Documentation"):
473
  documentation = gr.Markdown(documentation_markdown())
474
  with gr.TabItem("System Equation"):
 
490
  selected_indices
491
  ],
492
  outputs=[
493
+ phase_fig, time_fig, shadowing_fig, metrics_table, metrics_csv_file,
494
+ diagnostics_text, params_text, latex_eq, selected_indices
495
  ]
496
  )
497
 
 
522
 
523
  num_points.change(
524
  fn=update_selected_indices,
525
+ inputs=[num_points],
526
  outputs=selected_indices
527
  )
528
 
differ_hug/compute.py CHANGED
@@ -530,6 +530,7 @@ def compute_anomaly_score(df) -> np.ndarray:
530
 
531
  def compute_shadowing_diagnostics(
532
  solutions: List[Dict],
 
533
  epsilon_threshold: float = 1e-3
534
  ) -> Dict[str, Any]:
535
  """
@@ -537,6 +538,7 @@ def compute_shadowing_diagnostics(
537
 
538
  Args:
539
  solutions: List of solution dictionaries (each with 'x', 'y', 't_full')
 
540
  epsilon_threshold: Threshold for shadowing breakdown
541
 
542
  Returns:
@@ -544,20 +546,20 @@ def compute_shadowing_diagnostics(
544
  """
545
  epsilon_t_list = []
546
  shadowing_times = []
547
-
548
  for sol in solutions:
549
  x = sol['x']
550
  y = sol['y']
551
  t_full = sol['t_full']
552
-
553
  eps = 1e-6 * (1.0 + abs(x[0]) + abs(y[0]))
554
  xp0, yp0 = x[0] + eps, y[0] + 0.5 * eps
555
  try:
556
  sol_p = solve_ivp(
557
- lambda t, s: [0, 0],
558
- (t_full[0], t_full[-1]),
559
- (xp0, yp0),
560
- method='DOP853',
561
  t_eval=t_full
562
  )
563
  if sol_p.success:
@@ -565,7 +567,7 @@ def compute_shadowing_diagnostics(
565
  dist = np.sqrt((x - xp) ** 2 + (y - yp) ** 2)
566
  epsilon_t = np.maximum.accumulate(dist)
567
  epsilon_t_list.append(epsilon_t)
568
-
569
  exceed_indices = np.where(epsilon_t > epsilon_threshold)[0]
570
  if len(exceed_indices) > 0:
571
  first_exceed_idx = exceed_indices[0]
@@ -573,8 +575,8 @@ def compute_shadowing_diagnostics(
573
  else:
574
  shadowing_times.append(None)
575
  except Exception:
576
- pass
577
-
578
  return {
579
  'epsilon_t_list': epsilon_t_list,
580
  'shadowing_times': shadowing_times,
 
530
 
531
  def compute_shadowing_diagnostics(
532
  solutions: List[Dict],
533
+ rhs_func,
534
  epsilon_threshold: float = 1e-3
535
  ) -> Dict[str, Any]:
536
  """
 
538
 
539
  Args:
540
  solutions: List of solution dictionaries (each with 'x', 'y', 't_full')
541
+ rhs_func: Right-hand side function for the ODE system
542
  epsilon_threshold: Threshold for shadowing breakdown
543
 
544
  Returns:
 
546
  """
547
  epsilon_t_list = []
548
  shadowing_times = []
549
+
550
  for sol in solutions:
551
  x = sol['x']
552
  y = sol['y']
553
  t_full = sol['t_full']
554
+
555
  eps = 1e-6 * (1.0 + abs(x[0]) + abs(y[0]))
556
  xp0, yp0 = x[0] + eps, y[0] + 0.5 * eps
557
  try:
558
  sol_p = solve_ivp(
559
+ rhs_func,
560
+ (t_full[0], t_full[-1]),
561
+ (xp0, yp0),
562
+ method='DOP853',
563
  t_eval=t_full
564
  )
565
  if sol_p.success:
 
567
  dist = np.sqrt((x - xp) ** 2 + (y - yp) ** 2)
568
  epsilon_t = np.maximum.accumulate(dist)
569
  epsilon_t_list.append(epsilon_t)
570
+
571
  exceed_indices = np.where(epsilon_t > epsilon_threshold)[0]
572
  if len(exceed_indices) > 0:
573
  first_exceed_idx = exceed_indices[0]
 
575
  else:
576
  shadowing_times.append(None)
577
  except Exception:
578
+ continue
579
+
580
  return {
581
  'epsilon_t_list': epsilon_t_list,
582
  'shadowing_times': shadowing_times,
differ_hug/plotting.py CHANGED
@@ -36,23 +36,32 @@ def make_phase_portrait_figure(
36
  Returns:
37
  matplotlib Figure object
38
  """
 
 
 
 
 
 
 
 
39
  fig, ax = plt.subplots(figsize=(8, 6))
40
  styles = ['-', '--', '-.', ':']
41
  colors = plt.cm.tab20.colors
42
 
43
- for m, solution_data in enumerate(solutions):
44
- if m not in selected_indices:
 
45
  continue
46
- color = colors[m % len(colors)]
47
 
48
  x_dop = solution_data["x"]
49
  y_dop = solution_data["y"]
50
  ax.plot(x_dop, y_dop, linestyle='-', color=color, linewidth=1.2,
51
- label=f'DOP853 traj {m}' if m == selected_indices[0] else "")
52
 
53
  ax.plot(x_dop[0], y_dop[0], 'o', color=color, markersize=4)
54
  ax.plot(x_dop[-1], y_dop[-1], 'x', color=color, markersize=6)
55
- ax.text(x_dop[-1] + 0.01, y_dop[-1] + 0.01, f"{m}", fontsize=8, color=color)
56
 
57
  if "x_nn" in solution_data and solution_data["x_nn"] is not None:
58
  x_nn = solution_data["x_nn"]
@@ -60,7 +69,7 @@ def make_phase_portrait_figure(
60
  t_full = solution_data["t_full"]
61
 
62
  ax.plot(x_nn, y_nn, linestyle='--', color=color, linewidth=1.0, alpha=0.7,
63
- label=f'NN traj {m}' if m == selected_indices[0] else "")
64
 
65
  ax.plot(x_dop[0], y_dop[0], '^', color=color, markersize=8, markeredgecolor='black')
66
 
@@ -79,11 +88,11 @@ def make_phase_portrait_figure(
79
  ax.plot([x_dop[i], x_nn[i]], [y_dop[i], y_nn[i]],
80
  color=color, linewidth=0.5, alpha=0.3, linestyle='-')
81
 
82
- ax.text(x_dop[-1] + 0.01, y_dop[-1] + 0.01, f"{m}", fontsize=8, color=color)
83
  if "x_nn" in solution_data and solution_data["x_nn"] is not None:
84
  if solution_data["x_nn"] is not None:
85
  ax.text(solution_data["x_nn"][-1] + 0.01, solution_data["y_nn"][-1] + 0.01,
86
- f"{m}", fontsize=8, color=color)
87
 
88
  ax.set_title(f"Gene regulatory trajectories ({solver_type}) "
89
  f"— t_train_end={t_train_end:.2f}, t_full_end={t_full_end:.2f}, t_points={t_number}")
@@ -126,22 +135,31 @@ def make_time_series_figure(
126
  Returns:
127
  matplotlib Figure object
128
  """
 
 
 
 
 
 
 
 
129
  fig, ax_ts = plt.subplots(figsize=(8, 6))
130
  colors = plt.cm.tab20.colors
131
 
132
- for m, solution_data in enumerate(solutions):
133
- if m not in selected_indices:
 
134
  continue
135
- color = colors[m % len(colors)]
136
 
137
  t_full = solution_data["t_full"]
138
  x_dop = solution_data["x"]
139
  y_dop = solution_data["y"]
140
 
141
  ax_ts.plot(t_full, x_dop, linestyle='-', color=color, linewidth=1.2,
142
- label=f'x(t) traj {m}' if m == selected_indices[0] else "")
143
  ax_ts.plot(t_full, y_dop, linestyle='--', color=color, linewidth=1.2,
144
- label=f'y(t) traj {m}' if m == selected_indices[0] else "")
145
 
146
  ax_ts.set_title(f"Time series ({solver_type}) — x(t) and y(t) — "
147
  f"t_train_end={t_train_end:.2f}, t_full_end={t_full_end:.2f}, t_points={t_number}")
@@ -161,6 +179,7 @@ def make_shadowing_figure(
161
  t_full_end: float = 3.0,
162
  t_number: int = 100,
163
  epsilon_threshold: float = 1e-3,
 
164
  ) -> Optional[plt.Figure]:
165
  """
166
  Create shadowing figure showing epsilon(t) vs time.
@@ -173,21 +192,28 @@ def make_shadowing_figure(
173
  t_full_end: Full integration end time
174
  t_number: Number of time points
175
  epsilon_threshold: Threshold for shadowing breakdown
 
176
 
177
  Returns:
178
  matplotlib Figure object or None if no shadowing data available
179
  """
 
 
180
  if not selected_indices:
181
- return None
 
 
 
182
 
183
  fig, ax_shad = plt.subplots(figsize=(8, 6))
184
  colors = plt.cm.tab20.colors
185
 
186
  annotated = False
187
- for m, solution_data in enumerate(solutions):
188
- if m not in selected_indices:
 
189
  continue
190
- color = colors[m % len(colors)]
191
 
192
  t_full = solution_data["t_full"]
193
  x_dop = solution_data["x"]
@@ -195,37 +221,66 @@ def make_shadowing_figure(
195
 
196
  eps = 1e-6 * (1.0 + abs(x_dop[0]) + abs(y_dop[0]))
197
  xp0, yp0 = x_dop[0] + eps, y_dop[0] + 0.5 * eps
198
- try:
199
- from scipy.integrate import solve_ivp
200
- sol_p = solve_ivp(
201
- lambda t, s: [0, 0],
202
- (t_full[0], t_full[-1]),
203
- (xp0, yp0),
204
- method='DOP853',
205
- t_eval=t_full
206
- )
207
- if sol_p.success:
208
- xp, yp = sol_p.y
209
- dist = np.sqrt((x_dop - xp)**2 + (y_dop - yp)**2)
210
- epsilon_t = np.maximum.accumulate(dist)
211
-
212
- ax_shad.plot(epsilon_t, t_full, color=color, linewidth=1.2,
213
- label=f'ε(t) traj {m}' if m == selected_indices[0] else "")
214
-
215
- exceed_indices = np.where(epsilon_t > epsilon_threshold)[0]
216
- if len(exceed_indices) > 0:
217
- first_exceed_idx = exceed_indices[0]
218
- shadowing_time = t_full[first_exceed_idx]
219
- ax_shad.axhline(y=shadowing_time, color=color, linestyle=':', alpha=0.7,
220
- label=f't*={shadowing_time:.2f}' if not annotated else "")
221
- annotated = True
222
- except Exception:
223
- pass
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
224
 
225
  ax_shad.axhline(y=t_train_end, color='red', linestyle='--', alpha=0.7,
226
  label=f't_train_end={t_train_end}')
227
 
228
- ax_shad.set_title(f"Shadowing ({solver_type}) — ε(t) vs t — "
229
  f"t_train_end={t_train_end:.2f}, t_full_end={t_full_end:.2f}, t_points={t_number}")
230
  ax_shad.set_xlabel("ε(t)")
231
  ax_shad.set_ylabel("t")
@@ -237,7 +292,7 @@ def make_shadowing_figure(
237
  from matplotlib.lines import Line2D
238
  legend_elements = [
239
  Line2D([0], [0], color='gray', lw=2, linestyle='-', label='ε(t)'),
240
- Line2D([0], [0], color='red', lw=1, linestyle='--', label=f'train/extrap boundary')
241
  ]
242
  ax_shad.legend(handles=legend_elements)
243
 
 
36
  Returns:
37
  matplotlib Figure object
38
  """
39
+ selected_indices = [int(i) for i in selected_indices] if selected_indices else []
40
+
41
+ if not selected_indices:
42
+ fig, ax = plt.subplots(figsize=(8, 6))
43
+ ax.text(0.5, 0.5, "No trajectories selected", ha="center", va="center", transform=ax.transAxes)
44
+ ax.set_axis_off()
45
+ return fig
46
+
47
  fig, ax = plt.subplots(figsize=(8, 6))
48
  styles = ['-', '--', '-.', ':']
49
  colors = plt.cm.tab20.colors
50
 
51
+ for solution_data in solutions:
52
+ traj_idx = solution_data["idx"]
53
+ if traj_idx not in selected_indices:
54
  continue
55
+ color = colors[traj_idx % len(colors)]
56
 
57
  x_dop = solution_data["x"]
58
  y_dop = solution_data["y"]
59
  ax.plot(x_dop, y_dop, linestyle='-', color=color, linewidth=1.2,
60
+ label=f'DOP853 traj {traj_idx}' if traj_idx == selected_indices[0] else "")
61
 
62
  ax.plot(x_dop[0], y_dop[0], 'o', color=color, markersize=4)
63
  ax.plot(x_dop[-1], y_dop[-1], 'x', color=color, markersize=6)
64
+ ax.text(x_dop[-1] + 0.01, y_dop[-1] + 0.01, f"{traj_idx}", fontsize=8, color=color)
65
 
66
  if "x_nn" in solution_data and solution_data["x_nn"] is not None:
67
  x_nn = solution_data["x_nn"]
 
69
  t_full = solution_data["t_full"]
70
 
71
  ax.plot(x_nn, y_nn, linestyle='--', color=color, linewidth=1.0, alpha=0.7,
72
+ label=f'NN traj {traj_idx}' if traj_idx == selected_indices[0] else "")
73
 
74
  ax.plot(x_dop[0], y_dop[0], '^', color=color, markersize=8, markeredgecolor='black')
75
 
 
88
  ax.plot([x_dop[i], x_nn[i]], [y_dop[i], y_nn[i]],
89
  color=color, linewidth=0.5, alpha=0.3, linestyle='-')
90
 
91
+ ax.text(x_dop[-1] + 0.01, y_dop[-1] + 0.01, f"{traj_idx}", fontsize=8, color=color)
92
  if "x_nn" in solution_data and solution_data["x_nn"] is not None:
93
  if solution_data["x_nn"] is not None:
94
  ax.text(solution_data["x_nn"][-1] + 0.01, solution_data["y_nn"][-1] + 0.01,
95
+ f"{traj_idx}", fontsize=8, color=color)
96
 
97
  ax.set_title(f"Gene regulatory trajectories ({solver_type}) "
98
  f"— t_train_end={t_train_end:.2f}, t_full_end={t_full_end:.2f}, t_points={t_number}")
 
135
  Returns:
136
  matplotlib Figure object
137
  """
138
+ selected_indices = [int(i) for i in selected_indices] if selected_indices else []
139
+
140
+ if not selected_indices:
141
+ fig, ax = plt.subplots(figsize=(8, 6))
142
+ ax.text(0.5, 0.5, "No trajectories selected", ha="center", va="center", transform=ax.transAxes)
143
+ ax.set_axis_off()
144
+ return fig
145
+
146
  fig, ax_ts = plt.subplots(figsize=(8, 6))
147
  colors = plt.cm.tab20.colors
148
 
149
+ for solution_data in solutions:
150
+ traj_idx = solution_data["idx"]
151
+ if traj_idx not in selected_indices:
152
  continue
153
+ color = colors[traj_idx % len(colors)]
154
 
155
  t_full = solution_data["t_full"]
156
  x_dop = solution_data["x"]
157
  y_dop = solution_data["y"]
158
 
159
  ax_ts.plot(t_full, x_dop, linestyle='-', color=color, linewidth=1.2,
160
+ label=f'x(t) traj {traj_idx}' if traj_idx == selected_indices[0] else "")
161
  ax_ts.plot(t_full, y_dop, linestyle='--', color=color, linewidth=1.2,
162
+ label=f'y(t) traj {traj_idx}' if traj_idx == selected_indices[0] else "")
163
 
164
  ax_ts.set_title(f"Time series ({solver_type}) — x(t) and y(t) — "
165
  f"t_train_end={t_train_end:.2f}, t_full_end={t_full_end:.2f}, t_points={t_number}")
 
179
  t_full_end: float = 3.0,
180
  t_number: int = 100,
181
  epsilon_threshold: float = 1e-3,
182
+ rhs_func=None,
183
  ) -> Optional[plt.Figure]:
184
  """
185
  Create shadowing figure showing epsilon(t) vs time.
 
192
  t_full_end: Full integration end time
193
  t_number: Number of time points
194
  epsilon_threshold: Threshold for shadowing breakdown
195
+ rhs_func: Right-hand side function for ODE system (for correct shadowing)
196
 
197
  Returns:
198
  matplotlib Figure object or None if no shadowing data available
199
  """
200
+ selected_indices = [int(i) for i in selected_indices] if selected_indices else []
201
+
202
  if not selected_indices:
203
+ fig, ax = plt.subplots(figsize=(8, 6))
204
+ ax.text(0.5, 0.5, "No trajectories selected", ha="center", va="center", transform=ax.transAxes)
205
+ ax.set_axis_off()
206
+ return fig
207
 
208
  fig, ax_shad = plt.subplots(figsize=(8, 6))
209
  colors = plt.cm.tab20.colors
210
 
211
  annotated = False
212
+ for solution_data in solutions:
213
+ traj_idx = solution_data["idx"]
214
+ if traj_idx not in selected_indices:
215
  continue
216
+ color = colors[traj_idx % len(colors)]
217
 
218
  t_full = solution_data["t_full"]
219
  x_dop = solution_data["x"]
 
221
 
222
  eps = 1e-6 * (1.0 + abs(x_dop[0]) + abs(y_dop[0]))
223
  xp0, yp0 = x_dop[0] + eps, y_dop[0] + 0.5 * eps
224
+
225
+ if rhs_func is not None:
226
+ try:
227
+ sol_p = solve_ivp(
228
+ rhs_func,
229
+ (t_full[0], t_full[-1]),
230
+ (xp0, yp0),
231
+ method='DOP853',
232
+ t_eval=t_full
233
+ )
234
+ if sol_p.success:
235
+ xp, yp = sol_p.y
236
+ dist = np.sqrt((x_dop - xp)**2 + (y_dop - yp)**2)
237
+ epsilon_t = np.maximum.accumulate(dist)
238
+
239
+ ax_shad.plot(epsilon_t, t_full, color=color, linewidth=1.2,
240
+ label=f'ε(t) traj {traj_idx}' if traj_idx == selected_indices[0] else "")
241
+
242
+ exceed_indices = np.where(epsilon_t > epsilon_threshold)[0]
243
+ if len(exceed_indices) > 0:
244
+ first_exceed_idx = exceed_indices[0]
245
+ shadowing_time = t_full[first_exceed_idx]
246
+ ax_shad.axhline(y=shadowing_time, color=color, linestyle=':', alpha=0.7,
247
+ label=f't*={shadowing_time:.2f}' if not annotated else "")
248
+ annotated = True
249
+ except Exception:
250
+ pass
251
+ else:
252
+ xp0, yp0 = x_dop[0] + eps, y_dop[0] + 0.5 * eps
253
+ try:
254
+ from scipy.integrate import solve_ivp
255
+ sol_p = solve_ivp(
256
+ lambda t, s: [0, 0],
257
+ (t_full[0], t_full[-1]),
258
+ (xp0, yp0),
259
+ method='DOP853',
260
+ t_eval=t_full
261
+ )
262
+ if sol_p.success:
263
+ xp, yp = sol_p.y
264
+ dist = np.sqrt((x_dop - xp)**2 + (y_dop - yp)**2)
265
+ epsilon_t = np.maximum.accumulate(dist)
266
+
267
+ ax_shad.plot(epsilon_t, t_full, color=color, linewidth=1.2,
268
+ label=f'ε(t) traj {traj_idx}' if traj_idx == selected_indices[0] else "")
269
+
270
+ exceed_indices = np.where(epsilon_t > epsilon_threshold)[0]
271
+ if len(exceed_indices) > 0:
272
+ first_exceed_idx = exceed_indices[0]
273
+ shadowing_time = t_full[first_exceed_idx]
274
+ ax_shad.axhline(y=shadowing_time, color=color, linestyle=':', alpha=0.7,
275
+ label=f't*={shadowing_time:.2f}' if not annotated else "")
276
+ annotated = True
277
+ except Exception:
278
+ pass
279
 
280
  ax_shad.axhline(y=t_train_end, color='red', linestyle='--', alpha=0.7,
281
  label=f't_train_end={t_train_end}')
282
 
283
+ ax_shad.set_title(f"Shadowing analysis ({solver_type}) — ε(t) vs t — Perturbed trajectory vs primary trajectory — "
284
  f"t_train_end={t_train_end:.2f}, t_full_end={t_full_end:.2f}, t_points={t_number}")
285
  ax_shad.set_xlabel("ε(t)")
286
  ax_shad.set_ylabel("t")
 
292
  from matplotlib.lines import Line2D
293
  legend_elements = [
294
  Line2D([0], [0], color='gray', lw=2, linestyle='-', label='ε(t)'),
295
+ Line2D([0], [0], color='red', lw=1, linestyle='--', label='train/extrap boundary')
296
  ]
297
  ax_shad.legend(handles=legend_elements)
298