tvboptim 0.2.0__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.
Files changed (70) hide show
  1. tvboptim/__init__.py +9 -0
  2. tvboptim/data/__init__.py +12 -0
  3. tvboptim/data/loaders.py +99 -0
  4. tvboptim/execution.py +268 -0
  5. tvboptim/experimental/__init__.py +15 -0
  6. tvboptim/experimental/network_dynamics/__init__.py +28 -0
  7. tvboptim/experimental/network_dynamics/core/__init__.py +6 -0
  8. tvboptim/experimental/network_dynamics/core/bunch.py +67 -0
  9. tvboptim/experimental/network_dynamics/core/network.py +686 -0
  10. tvboptim/experimental/network_dynamics/coupling/__init__.py +22 -0
  11. tvboptim/experimental/network_dynamics/coupling/base.py +1005 -0
  12. tvboptim/experimental/network_dynamics/coupling/linear.py +466 -0
  13. tvboptim/experimental/network_dynamics/coupling/subspace.py +509 -0
  14. tvboptim/experimental/network_dynamics/coupling/tvb.py +202 -0
  15. tvboptim/experimental/network_dynamics/dynamics/__init__.py +7 -0
  16. tvboptim/experimental/network_dynamics/dynamics/base.py +541 -0
  17. tvboptim/experimental/network_dynamics/dynamics/lorenz.py +207 -0
  18. tvboptim/experimental/network_dynamics/dynamics/tvb/__init__.py +29 -0
  19. tvboptim/experimental/network_dynamics/dynamics/tvb/coombes_byrne.py +154 -0
  20. tvboptim/experimental/network_dynamics/dynamics/tvb/epileptor.py +200 -0
  21. tvboptim/experimental/network_dynamics/dynamics/tvb/generic_2d_oscillator.py +149 -0
  22. tvboptim/experimental/network_dynamics/dynamics/tvb/jansen_rit.py +158 -0
  23. tvboptim/experimental/network_dynamics/dynamics/tvb/kuramoto.py +120 -0
  24. tvboptim/experimental/network_dynamics/dynamics/tvb/larter_breakspear.py +221 -0
  25. tvboptim/experimental/network_dynamics/dynamics/tvb/linear.py +111 -0
  26. tvboptim/experimental/network_dynamics/dynamics/tvb/montbrio_pazo_roxin.py +137 -0
  27. tvboptim/experimental/network_dynamics/dynamics/tvb/sup_hopf.py +131 -0
  28. tvboptim/experimental/network_dynamics/dynamics/tvb/wilson_cowan.py +210 -0
  29. tvboptim/experimental/network_dynamics/dynamics/tvb/wong_wang.py +124 -0
  30. tvboptim/experimental/network_dynamics/dynamics/tvb/wong_wang_exc_inh.py +177 -0
  31. tvboptim/experimental/network_dynamics/external_input/__init__.py +20 -0
  32. tvboptim/experimental/network_dynamics/external_input/base.py +152 -0
  33. tvboptim/experimental/network_dynamics/external_input/data.py +203 -0
  34. tvboptim/experimental/network_dynamics/external_input/parametric.py +270 -0
  35. tvboptim/experimental/network_dynamics/graph/__init__.py +14 -0
  36. tvboptim/experimental/network_dynamics/graph/base.py +706 -0
  37. tvboptim/experimental/network_dynamics/graph/sparse.py +885 -0
  38. tvboptim/experimental/network_dynamics/graph/utils.py +0 -0
  39. tvboptim/experimental/network_dynamics/noise/__init__.py +6 -0
  40. tvboptim/experimental/network_dynamics/noise/base.py +162 -0
  41. tvboptim/experimental/network_dynamics/noise/gaussian.py +71 -0
  42. tvboptim/experimental/network_dynamics/result.py +78 -0
  43. tvboptim/experimental/network_dynamics/solve.py +721 -0
  44. tvboptim/experimental/network_dynamics/solvers/__init__.py +15 -0
  45. tvboptim/experimental/network_dynamics/solvers/base.py +46 -0
  46. tvboptim/experimental/network_dynamics/solvers/diffrax.py +63 -0
  47. tvboptim/experimental/network_dynamics/solvers/native.py +308 -0
  48. tvboptim/experimental/network_dynamics/utils/__init__.py +3 -0
  49. tvboptim/experimental/network_dynamics/utils/printer.py +555 -0
  50. tvboptim/model.py +111 -0
  51. tvboptim/observations/__init__.py +3 -0
  52. tvboptim/observations/observation.py +32 -0
  53. tvboptim/observations/tvb_monitors/__init__.py +11 -0
  54. tvboptim/observations/tvb_monitors/bold.py +290 -0
  55. tvboptim/observations/tvb_monitors/downsampling.py +185 -0
  56. tvboptim/optim/__init__.py +4 -0
  57. tvboptim/optim/callbacks.py +333 -0
  58. tvboptim/optim/optax.py +379 -0
  59. tvboptim/types/__init__.py +35 -0
  60. tvboptim/types/parameter.py +769 -0
  61. tvboptim/types/spaces.py +943 -0
  62. tvboptim/types/stateutils.py +109 -0
  63. tvboptim/utils/__init__.py +16 -0
  64. tvboptim/utils/caching.py +82 -0
  65. tvboptim/utils/utils.py +265 -0
  66. tvboptim-0.2.0.dist-info/METADATA +157 -0
  67. tvboptim-0.2.0.dist-info/RECORD +70 -0
  68. tvboptim-0.2.0.dist-info/WHEEL +5 -0
  69. tvboptim-0.2.0.dist-info/licenses/LICENSE +278 -0
  70. tvboptim-0.2.0.dist-info/top_level.txt +1 -0
@@ -0,0 +1,555 @@
1
+ """Pretty-printing utilities for Network Dynamics networks."""
2
+
3
+ import ast
4
+ import inspect
5
+ import textwrap
6
+ from typing import Any, Dict, List
7
+
8
+
9
+ def format_network(network) -> str:
10
+ """Generate pretty-printed description of a network system.
11
+
12
+ Args:
13
+ network: Network instance
14
+
15
+ Returns:
16
+ Formatted string describing the complete dynamical system
17
+ """
18
+ return NetworkPrinter(network).format()
19
+
20
+
21
+ def print_network(network) -> None:
22
+ """Print a pretty-printed description of a network system.
23
+
24
+ Args:
25
+ network: Network instance
26
+ """
27
+ print(format_network(network))
28
+
29
+
30
+ class NetworkPrinter:
31
+ """Pretty-print Network as a mathematical system."""
32
+
33
+ def __init__(self, network):
34
+ self.network = network
35
+ self.coupling_descriptions = self._build_coupling_descriptions()
36
+
37
+ def _build_coupling_descriptions(self) -> Dict[str, Dict[str, Any]]:
38
+ """Generate descriptions for each coupling."""
39
+ descriptions = {}
40
+ for name, coupling in self.network.couplings.items():
41
+ desc = CouplingDescriptor(coupling, self.network).describe()
42
+ descriptions[name] = desc
43
+ return descriptions
44
+
45
+ def format(self) -> str:
46
+ """Generate complete system description."""
47
+ sections = [
48
+ self._format_header(),
49
+ self._format_graph(),
50
+ self._format_noise(),
51
+ self._format_couplings(),
52
+ self._format_dynamics(),
53
+ self._format_parameters(),
54
+ ]
55
+ return "\n\n".join(s for s in sections if s)
56
+
57
+ def _format_header(self) -> str:
58
+ """Format network header."""
59
+ lines = [
60
+ " Network Dynamics Network System",
61
+ "=" * 50,
62
+ "",
63
+ f"Dynamics: {self.network.dynamics.__class__.__name__}",
64
+ f" States: {', '.join(self.network.dynamics.STATE_NAMES)}",
65
+ ]
66
+
67
+ # Show initial state if available
68
+ if (
69
+ hasattr(self.network, "initial_state")
70
+ and self.network.initial_state is not None
71
+ ):
72
+ initial_str = ", ".join(
73
+ [
74
+ f"{name}={val:.3g}"
75
+ for name, val in zip(
76
+ self.network.dynamics.STATE_NAMES,
77
+ self.network.initial_state[:, 0], # First node
78
+ )
79
+ ]
80
+ )
81
+ lines.append(f" Initial: {initial_str}")
82
+
83
+ return "\n".join(lines)
84
+
85
+ def _format_graph(self) -> str:
86
+ """Format graph information."""
87
+ graph = self.network.graph
88
+ lines = [
89
+ f"Graph: {graph.__class__.__name__}",
90
+ f" Nodes: {graph.n_nodes}",
91
+ ]
92
+
93
+ # Add density for sparse graphs
94
+ if hasattr(graph, "nnz"):
95
+ density = graph.nnz / (graph.n_nodes**2) * 100
96
+ lines.append(f" Density: {density:.3f}%")
97
+
98
+ # Add max delay for delay graphs
99
+ if hasattr(graph, "max_delay"):
100
+ lines.append(f" Max delay: {graph.max_delay} ms")
101
+
102
+ return "\n".join(lines)
103
+
104
+ def _format_noise(self) -> str:
105
+ """Format noise information."""
106
+ if not hasattr(self.network, "noise") or self.network.noise is None:
107
+ return ""
108
+
109
+ noise = self.network.noise
110
+ lines = [
111
+ f"Noise: {noise.__class__.__name__}",
112
+ ]
113
+
114
+ # Show which states receive noise
115
+ if noise.apply_to is None:
116
+ apply_str = "all states"
117
+ elif isinstance(noise.apply_to, str):
118
+ apply_str = noise.apply_to
119
+ elif isinstance(noise.apply_to, list):
120
+ if len(noise.apply_to) > 0 and isinstance(noise.apply_to[0], str):
121
+ # List of state names
122
+ apply_str = f"({', '.join(noise.apply_to)})"
123
+ else:
124
+ # List of indices
125
+ apply_str = f"indices {noise.apply_to}"
126
+ else:
127
+ apply_str = str(noise.apply_to)
128
+
129
+ lines.append(f" Apply to: {apply_str}")
130
+
131
+ # Show parameters
132
+ if hasattr(noise, "params") and len(noise.params) > 0:
133
+ param_items = []
134
+ for key, value in noise.params.items():
135
+ if isinstance(value, (int, float)):
136
+ param_items.append(f"{key}={value:.3g}")
137
+ else:
138
+ param_items.append(f"{key}={value}")
139
+ lines.append(f" Params: {', '.join(param_items)}")
140
+
141
+ return "\n".join(lines)
142
+
143
+ def _format_couplings(self) -> str:
144
+ """Format all couplings."""
145
+ if not self.coupling_descriptions:
146
+ return ""
147
+
148
+ lines = ["Couplings", "-" * 50]
149
+
150
+ for i, (name, desc) in enumerate(self.coupling_descriptions.items(), 1):
151
+ lines.append(f"{i}. {name} ({desc['class_name']})")
152
+ lines.append(f" Type: {desc['type']}")
153
+
154
+ # Subspace-specific information (if present)
155
+ if "n_regions" in desc:
156
+ lines.append(f" Regions: {desc['n_regions']}")
157
+ lines.append(f" Aggregation: {desc['aggregation']}")
158
+ lines.append(f" Distribution: {desc['distribution']}")
159
+
160
+ # State information
161
+ state_info = []
162
+ if desc["incoming_states"]:
163
+ state_info.append(
164
+ f"incoming={self._format_state_list(desc['incoming_states'])}"
165
+ )
166
+ if desc["local_states"]:
167
+ state_info.append(
168
+ f"local={self._format_state_list(desc['local_states'])}"
169
+ )
170
+ if state_info:
171
+ lines.append(f" States: {', '.join(state_info)}")
172
+
173
+ # Network form (always show)
174
+ if desc["network_form"]:
175
+ lines.append(f" Form: {desc['network_form']}")
176
+
177
+ # Show pre/post if they exist
178
+ if desc.get("pre_form"):
179
+ lines.append(f" pre: {desc['pre_form']}")
180
+ if desc.get("post_form"):
181
+ lines.append(f" post: {desc['post_form']}")
182
+
183
+ # Parameters (only if present)
184
+ if desc["params"]:
185
+ param_str = ", ".join([f"{k}={v}" for k, v in desc["params"].items()])
186
+ lines.append(f" params: {param_str}")
187
+
188
+ # Delay information
189
+ if desc["type"] == "delayed" and "max_delay" in desc:
190
+ lines.append(f" Max delay: {desc['max_delay']} ms")
191
+
192
+ lines.append("") # Blank line between couplings
193
+
194
+ return "\n".join(lines)
195
+
196
+ def _format_dynamics(self) -> str:
197
+ """Format dynamics equations."""
198
+ formatter = DynamicsFormatter(self.network.dynamics, self.coupling_descriptions)
199
+ return formatter.format()
200
+
201
+ def _format_parameters(self) -> str:
202
+ """Format parameter values."""
203
+ if not hasattr(self.network.dynamics, "params"):
204
+ return ""
205
+
206
+ params = self.network.dynamics.params
207
+ param_items = []
208
+ for key, value in params.items():
209
+ if isinstance(value, (int, float)):
210
+ param_items.append(f"{key}={value:.3g}")
211
+ else:
212
+ param_items.append(f"{key}={value}")
213
+
214
+ lines = ["Parameters", "-" * 50, " " + ", ".join(param_items)]
215
+
216
+ return "\n".join(lines)
217
+
218
+ def _format_state_list(self, states) -> str:
219
+ """Format state names."""
220
+ if isinstance(states, str):
221
+ return states
222
+ elif isinstance(states, (list, tuple)):
223
+ if len(states) == 0:
224
+ return ""
225
+ elif len(states) == 1:
226
+ return states[0]
227
+ else:
228
+ return f"({', '.join(states)})"
229
+ return str(states)
230
+
231
+
232
+ class CouplingDescriptor:
233
+ """Extract mathematical form of a coupling."""
234
+
235
+ def __init__(self, coupling, network):
236
+ self.coupling = coupling
237
+ self.network = network
238
+
239
+ def describe(self) -> Dict[str, Any]:
240
+ """Return coupling description with mathematical form.
241
+
242
+ Returns:
243
+ Dictionary with keys: type, incoming_states, local_states,
244
+ params, math_form, network_form, class_name
245
+ """
246
+ from tvboptim.experimental.network_dynamics.coupling.base import DelayedCoupling
247
+
248
+ # Try to get description from coupling's describe() method first
249
+ if hasattr(self.coupling, "describe"):
250
+ # Use coupling's describe() as the base - it has all the info we need
251
+ result = self.coupling.describe()
252
+
253
+ # Only add fallback fields if not already provided
254
+ if "class_name" not in result:
255
+ result["class_name"] = self.coupling.__class__.__name__
256
+ if "type" not in result:
257
+ result["type"] = (
258
+ "delayed"
259
+ if isinstance(self.coupling, DelayedCoupling)
260
+ else "instantaneous"
261
+ )
262
+ if "incoming_states" not in result:
263
+ result["incoming_states"] = self._normalize_states(
264
+ self.coupling.INCOMING_STATE_NAMES
265
+ )
266
+ if "local_states" not in result:
267
+ result["local_states"] = self._normalize_states(
268
+ self.coupling.LOCAL_STATE_NAMES
269
+ )
270
+ if "params" not in result:
271
+ result["params"] = self._extract_params()
272
+ else:
273
+ # Fallback: build description from inspection
274
+ result = {
275
+ "class_name": self.coupling.__class__.__name__,
276
+ "type": (
277
+ "delayed"
278
+ if isinstance(self.coupling, DelayedCoupling)
279
+ else "instantaneous"
280
+ ),
281
+ "incoming_states": self._normalize_states(
282
+ self.coupling.INCOMING_STATE_NAMES
283
+ ),
284
+ "local_states": self._normalize_states(self.coupling.LOCAL_STATE_NAMES),
285
+ "params": self._extract_params(),
286
+ "math_form": self._infer_from_source(),
287
+ "network_form": self._default_network_form(),
288
+ }
289
+
290
+ # Add delay info if applicable (only if not already provided by coupling)
291
+ if result["type"] == "delayed" and "max_delay" not in result:
292
+ if hasattr(self.network, "max_delay"):
293
+ result["max_delay"] = self.network.max_delay
294
+
295
+ return result
296
+
297
+ def _normalize_states(self, states) -> List[str]:
298
+ """Normalize state names to list."""
299
+ if states is None:
300
+ return []
301
+ elif isinstance(states, str):
302
+ return [states]
303
+ elif isinstance(states, (list, tuple)):
304
+ return list(states)
305
+ return []
306
+
307
+ def _extract_params(self) -> Dict[str, Any]:
308
+ """Extract coupling parameters."""
309
+ if not hasattr(self.coupling, "params"):
310
+ return {}
311
+
312
+ params = {}
313
+ for key, value in self.coupling.params.items():
314
+ if isinstance(value, (int, float, str)):
315
+ params[key] = value
316
+
317
+ return params
318
+
319
+ def _infer_from_source(self) -> str:
320
+ """Fallback: try to infer math form from source inspection."""
321
+ # This is a simple fallback - the describe() method should provide better info
322
+ return f"{self.coupling.__class__.__name__}"
323
+
324
+ def _default_network_form(self) -> str:
325
+ """Default network form based on coupling type."""
326
+ from tvboptim.experimental.network_dynamics.coupling.base import DelayedCoupling
327
+
328
+ if isinstance(self.coupling, DelayedCoupling):
329
+ return "Σⱼ w_ij * f(state_j(t - τ_ij))"
330
+ else:
331
+ return "Σⱼ w_ij * f(state_j(t))"
332
+
333
+
334
+ class DynamicsFormatter:
335
+ """Parse and annotate dynamics source code."""
336
+
337
+ def __init__(self, dynamics, coupling_descriptions):
338
+ self.dynamics = dynamics
339
+ self.coupling_descriptions = coupling_descriptions
340
+
341
+ def format(self) -> str:
342
+ """Extract and beautify dynamics equations."""
343
+ try:
344
+ source = inspect.getsource(self.dynamics.dynamics)
345
+
346
+ # Remove docstring
347
+ source = self._remove_docstring(source)
348
+
349
+ # Collapse multi-line function signature
350
+ source = self._collapse_function_signature(source)
351
+
352
+ # Parse AST to find coupling usage
353
+ coupling_usage = self._find_coupling_usage(source)
354
+
355
+ # Annotate source with coupling descriptions
356
+ annotated = self._annotate_source(source, coupling_usage)
357
+
358
+ lines = ["Dynamics Equations", "-" * 50, annotated]
359
+
360
+ return "\n".join(lines)
361
+
362
+ except Exception as e:
363
+ return f"Dynamics Equations\n{'-' * 50}\n# Could not parse source: {e}"
364
+
365
+ def _remove_docstring(self, source: str) -> str:
366
+ """Remove docstring from function source code."""
367
+ try:
368
+ # Dedent for parsing
369
+ dedented = textwrap.dedent(source)
370
+ tree = ast.parse(dedented)
371
+
372
+ # Find the function definition
373
+ func_def = None
374
+ for node in ast.walk(tree):
375
+ if isinstance(node, ast.FunctionDef):
376
+ func_def = node
377
+ break
378
+
379
+ if func_def is None:
380
+ return source
381
+
382
+ # Check if first statement is a docstring
383
+ if (
384
+ func_def.body
385
+ and isinstance(func_def.body[0], ast.Expr)
386
+ and isinstance(func_def.body[0].value, (ast.Str, ast.Constant))
387
+ ):
388
+ # Get the docstring node
389
+ docstring_node = func_def.body[0]
390
+
391
+ # Remove lines containing the docstring
392
+ lines = source.split("\n")
393
+
394
+ # Find docstring start and end lines
395
+ # The first body statement starts after the function def line
396
+ start_line = docstring_node.lineno - 1 # 0-indexed
397
+ end_line = (
398
+ docstring_node.end_lineno - 1
399
+ if hasattr(docstring_node, "end_lineno")
400
+ else start_line
401
+ )
402
+
403
+ # Remove docstring lines
404
+ new_lines = lines[:start_line] + lines[end_line + 1 :]
405
+
406
+ return "\n".join(new_lines)
407
+
408
+ return source
409
+
410
+ except (AttributeError, ValueError, IndexError):
411
+ # If anything fails, return original source
412
+ return source
413
+
414
+ def _collapse_function_signature(self, source: str) -> str:
415
+ """Collapse multi-line function signature into single line."""
416
+ lines = source.split("\n")
417
+
418
+ # Find the function definition (starts with 'def ')
419
+ func_start = None
420
+ func_end = None
421
+
422
+ for i, line in enumerate(lines):
423
+ stripped = line.strip()
424
+ if stripped.startswith("def "):
425
+ func_start = i
426
+ # Find where the signature ends (line ending with ':')
427
+ for j in range(i, len(lines)):
428
+ if lines[j].rstrip().endswith(":"):
429
+ func_end = j
430
+ break
431
+ break
432
+
433
+ if func_start is None or func_end is None or func_start == func_end:
434
+ return source
435
+
436
+ # Extract indent from first line
437
+ indent = lines[func_start][
438
+ : len(lines[func_start]) - len(lines[func_start].lstrip())
439
+ ]
440
+
441
+ # Collect signature parts, stripping each line
442
+ sig_parts = []
443
+ for i in range(func_start, func_end + 1):
444
+ part = lines[i].strip()
445
+ if part: # Only add non-empty parts
446
+ sig_parts.append(part)
447
+
448
+ # Join into single line with single spaces
449
+ collapsed = " ".join(sig_parts)
450
+
451
+ # Clean up spacing around parentheses and commas
452
+ import re
453
+
454
+ collapsed = re.sub(r"\s+", " ", collapsed) # Multiple spaces to single
455
+ collapsed = re.sub(r"\s*\(\s*", "(", collapsed) # Remove spaces around (
456
+ collapsed = re.sub(r"\s*\)\s*", ")", collapsed) # Remove spaces around )
457
+ collapsed = re.sub(r"\s*,\s*", ", ", collapsed) # Normalize comma spacing
458
+ collapsed = re.sub(r"\s*->\s*", " -> ", collapsed) # Normalize arrow spacing
459
+
460
+ # Reconstruct with collapsed signature
461
+ new_lines = lines[:func_start] + [indent + collapsed] + lines[func_end + 1 :]
462
+
463
+ return "\n".join(new_lines)
464
+
465
+ def _find_coupling_usage(self, source: str) -> List[Dict[str, Any]]:
466
+ """Find all coupling.X[Y] access patterns.
467
+
468
+ Returns:
469
+ List of dicts with keys: name, index, lineno, col_offset
470
+ """
471
+ try:
472
+ # Dedent source to avoid indentation errors
473
+ dedented = textwrap.dedent(source)
474
+ tree = ast.parse(dedented)
475
+ except (SyntaxError, ValueError):
476
+ return []
477
+
478
+ class CouplingVisitor(ast.NodeVisitor):
479
+ def __init__(self):
480
+ self.usages = []
481
+
482
+ def visit_Subscript(self, node):
483
+ # Check if it's coupling.X[Y]
484
+ if (
485
+ isinstance(node.value, ast.Attribute)
486
+ and isinstance(node.value.value, ast.Name)
487
+ and node.value.value.id == "coupling"
488
+ ):
489
+ coupling_name = node.value.attr
490
+ if isinstance(node.slice, (ast.Constant, ast.Index)):
491
+ if isinstance(node.slice, ast.Index):
492
+ index = (
493
+ node.slice.value.value
494
+ if isinstance(node.slice.value, ast.Constant)
495
+ else 0
496
+ )
497
+ else:
498
+ index = node.slice.value
499
+
500
+ self.usages.append(
501
+ {
502
+ "name": coupling_name,
503
+ "index": index,
504
+ "lineno": node.lineno,
505
+ "col_offset": node.col_offset,
506
+ }
507
+ )
508
+
509
+ self.generic_visit(node)
510
+
511
+ visitor = CouplingVisitor()
512
+ visitor.visit(tree)
513
+ return visitor.usages
514
+
515
+ def _annotate_source(
516
+ self, source: str, coupling_usage: List[Dict[str, Any]]
517
+ ) -> str:
518
+ """Add inline annotations for coupling usage."""
519
+ lines = source.split("\n")
520
+
521
+ # Group usages by line number
522
+ usages_by_line = {}
523
+ for usage in coupling_usage:
524
+ lineno = usage["lineno"]
525
+ if lineno not in usages_by_line:
526
+ usages_by_line[lineno] = []
527
+ usages_by_line[lineno].append(usage)
528
+
529
+ # Insert annotations (in reverse order to maintain line numbers)
530
+ for lineno in sorted(usages_by_line.keys(), reverse=True):
531
+ usages = usages_by_line[lineno]
532
+
533
+ # Build annotation
534
+ annotations = []
535
+ for usage in usages:
536
+ coupling_name = usage["name"]
537
+ desc = self.coupling_descriptions.get(coupling_name, {})
538
+
539
+ if "network_form" in desc and desc["network_form"]:
540
+ annotations.append(f"{coupling_name}: {desc['network_form']}")
541
+ else:
542
+ # Coupling referenced but not provided - defaults to 0
543
+ annotations.append(f"{coupling_name}: 0 (not provided)")
544
+
545
+ if annotations:
546
+ indent = self._get_indent(lines[lineno - 1])
547
+ # Add annotation on the NEXT line (after the line with coupling usage)
548
+ annotation_line = f"{indent}# ↳ {', '.join(annotations)}"
549
+ lines.insert(lineno, annotation_line)
550
+
551
+ return "\n".join(lines)
552
+
553
+ def _get_indent(self, line: str) -> str:
554
+ """Extract indentation from a line."""
555
+ return line[: len(line) - len(line.lstrip())]
tvboptim/model.py ADDED
@@ -0,0 +1,111 @@
1
+ # %%
2
+ import jax
3
+ import jax.numpy as jnp
4
+
5
+
6
+ def jaxify(
7
+ experiment,
8
+ enable_x64: bool = True,
9
+ replace_temporal_averaging: bool = False,
10
+ return_new_ics: bool = False,
11
+ scalar_pre: bool = False,
12
+ bold_fft_convolve: bool = True,
13
+ small_dt: bool = False,
14
+ **kwargs,
15
+ ):
16
+ """Convert TVBO SimulationExperiment to JAX-compatible model function and state.
17
+
18
+ This function transforms a TVBO simulation experiment into a JAX-compiled
19
+ model function and corresponding state object for efficient brain simulation.
20
+ The resulting model supports automatic differentiation and parallel execution.
21
+
22
+ Parameters
23
+ ----------
24
+ experiment : tvbo.export.experiment.SimulationExperiment
25
+ TVBO SimulationExperiment containing model, connectivity, coupling,
26
+ integration, and monitor specifications.
27
+ enable_x64 : bool, optional
28
+ If True, use float64 precision; otherwise float32. Transforms all arrays
29
+ in state to correct precision and sets JAX config 'jax_enable_x64'.
30
+ Default is True.
31
+ replace_temporal_averaging : bool, optional
32
+ If False, BOLD uses TemporalAverage monitor as TVB does. If True,
33
+ uses faster SubSample monitor with similar results. Default is False.
34
+ return_new_ics : bool, optional
35
+ If True, model returns updated initial conditions TimeSeries along
36
+ with simulation output for continuing simulations. Changes output
37
+ from result to [result, initial_conditions]. Default is False.
38
+ scalar_pre : bool, optional
39
+ If True, applies performance optimization replacing dot product with
40
+ matmul in coupling term. Only works with scalar-only pre expressions,
41
+ no delays, and when pre expression has single x_j occurrence.
42
+ Default is False.
43
+ bold_fft_convolve : bool, optional
44
+ If True, BOLD monitor uses FFT convolution instead of dot product.
45
+ Faster for most cases, time doesn't scale with BOLD period. Dot
46
+ product can be faster for large period values. Default is True.
47
+ small_dt : bool, optional
48
+ Uses full history storage for faster simulations at small dt. Can
49
+ cause memory explosion under jax.grad transformation. Default is False.
50
+ **kwargs : dict
51
+ Additional keyword arguments passed to experiment.execute().
52
+
53
+ Returns
54
+ -------
55
+ tuple[Callable, Any]
56
+ A tuple containing (model_function, state) where:
57
+
58
+ - model_function : Callable that takes state and returns simulation results
59
+ - state : JAX PyTree containing all simulation parameters and initial conditions
60
+
61
+ Examples
62
+ --------
63
+ >>> from tvbo.export.experiment import SimulationExperiment
64
+ >>> from tvboptim import jaxify
65
+ >>>
66
+ >>> # Create TVBO experiment
67
+ >>> experiment = SimulationExperiment(...)
68
+ >>>
69
+ >>> # Convert to JAX
70
+ >>> model, state = jaxify(experiment, enable_x64=True, scalar_pre=True)
71
+ >>>
72
+ >>> # Run simulation
73
+ >>> result = model(state)
74
+ >>> raw_data, bold_data = result
75
+ >>>
76
+ >>> # Use with JAX transformations
77
+ >>> grad_fn = jax.grad(lambda s: model(s)[0].data.sum())
78
+ >>> gradients = grad_fn(state)
79
+
80
+ Notes
81
+ -----
82
+ The returned model function is JAX-compiled and supports:
83
+
84
+ - Automatic differentiation with jax.grad, jax.jacobian
85
+ - Parallel execution with jax.vmap, jax.pmap
86
+ - Just-in-time compilation for optimal performance
87
+ - Integration with JAX ecosystem (optax, equinox, etc.)
88
+
89
+ The state object is a JAX PyTree that can be used with all JAX transformations
90
+ and contains Parameter objects for optimization workflows.
91
+ """
92
+ state = experiment.collect_state()
93
+ jax.config.update("jax_enable_x64", enable_x64)
94
+
95
+ if enable_x64:
96
+ state = state.convert_dtype(target_dtype=jnp.float64)
97
+ else:
98
+ state = state.convert_dtype(target_dtype=jnp.float32)
99
+
100
+ _module = experiment.execute(
101
+ format="jax",
102
+ replace_temporal_averaging=replace_temporal_averaging,
103
+ return_new_ics=return_new_ics,
104
+ scalar_pre=scalar_pre,
105
+ bold_fft_convolve=bold_fft_convolve,
106
+ small_dt=small_dt,
107
+ **kwargs,
108
+ )
109
+ simulator = _module["kernel"]
110
+
111
+ return simulator, state
@@ -0,0 +1,3 @@
1
+ from .observation import compute_fc, fc_corr, rmse
2
+
3
+ __all__ = ["compute_fc", "fc_corr", "rmse"]