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.
- tvboptim/__init__.py +9 -0
- tvboptim/data/__init__.py +12 -0
- tvboptim/data/loaders.py +99 -0
- tvboptim/execution.py +268 -0
- tvboptim/experimental/__init__.py +15 -0
- tvboptim/experimental/network_dynamics/__init__.py +28 -0
- tvboptim/experimental/network_dynamics/core/__init__.py +6 -0
- tvboptim/experimental/network_dynamics/core/bunch.py +67 -0
- tvboptim/experimental/network_dynamics/core/network.py +686 -0
- tvboptim/experimental/network_dynamics/coupling/__init__.py +22 -0
- tvboptim/experimental/network_dynamics/coupling/base.py +1005 -0
- tvboptim/experimental/network_dynamics/coupling/linear.py +466 -0
- tvboptim/experimental/network_dynamics/coupling/subspace.py +509 -0
- tvboptim/experimental/network_dynamics/coupling/tvb.py +202 -0
- tvboptim/experimental/network_dynamics/dynamics/__init__.py +7 -0
- tvboptim/experimental/network_dynamics/dynamics/base.py +541 -0
- tvboptim/experimental/network_dynamics/dynamics/lorenz.py +207 -0
- tvboptim/experimental/network_dynamics/dynamics/tvb/__init__.py +29 -0
- tvboptim/experimental/network_dynamics/dynamics/tvb/coombes_byrne.py +154 -0
- tvboptim/experimental/network_dynamics/dynamics/tvb/epileptor.py +200 -0
- tvboptim/experimental/network_dynamics/dynamics/tvb/generic_2d_oscillator.py +149 -0
- tvboptim/experimental/network_dynamics/dynamics/tvb/jansen_rit.py +158 -0
- tvboptim/experimental/network_dynamics/dynamics/tvb/kuramoto.py +120 -0
- tvboptim/experimental/network_dynamics/dynamics/tvb/larter_breakspear.py +221 -0
- tvboptim/experimental/network_dynamics/dynamics/tvb/linear.py +111 -0
- tvboptim/experimental/network_dynamics/dynamics/tvb/montbrio_pazo_roxin.py +137 -0
- tvboptim/experimental/network_dynamics/dynamics/tvb/sup_hopf.py +131 -0
- tvboptim/experimental/network_dynamics/dynamics/tvb/wilson_cowan.py +210 -0
- tvboptim/experimental/network_dynamics/dynamics/tvb/wong_wang.py +124 -0
- tvboptim/experimental/network_dynamics/dynamics/tvb/wong_wang_exc_inh.py +177 -0
- tvboptim/experimental/network_dynamics/external_input/__init__.py +20 -0
- tvboptim/experimental/network_dynamics/external_input/base.py +152 -0
- tvboptim/experimental/network_dynamics/external_input/data.py +203 -0
- tvboptim/experimental/network_dynamics/external_input/parametric.py +270 -0
- tvboptim/experimental/network_dynamics/graph/__init__.py +14 -0
- tvboptim/experimental/network_dynamics/graph/base.py +706 -0
- tvboptim/experimental/network_dynamics/graph/sparse.py +885 -0
- tvboptim/experimental/network_dynamics/graph/utils.py +0 -0
- tvboptim/experimental/network_dynamics/noise/__init__.py +6 -0
- tvboptim/experimental/network_dynamics/noise/base.py +162 -0
- tvboptim/experimental/network_dynamics/noise/gaussian.py +71 -0
- tvboptim/experimental/network_dynamics/result.py +78 -0
- tvboptim/experimental/network_dynamics/solve.py +721 -0
- tvboptim/experimental/network_dynamics/solvers/__init__.py +15 -0
- tvboptim/experimental/network_dynamics/solvers/base.py +46 -0
- tvboptim/experimental/network_dynamics/solvers/diffrax.py +63 -0
- tvboptim/experimental/network_dynamics/solvers/native.py +308 -0
- tvboptim/experimental/network_dynamics/utils/__init__.py +3 -0
- tvboptim/experimental/network_dynamics/utils/printer.py +555 -0
- tvboptim/model.py +111 -0
- tvboptim/observations/__init__.py +3 -0
- tvboptim/observations/observation.py +32 -0
- tvboptim/observations/tvb_monitors/__init__.py +11 -0
- tvboptim/observations/tvb_monitors/bold.py +290 -0
- tvboptim/observations/tvb_monitors/downsampling.py +185 -0
- tvboptim/optim/__init__.py +4 -0
- tvboptim/optim/callbacks.py +333 -0
- tvboptim/optim/optax.py +379 -0
- tvboptim/types/__init__.py +35 -0
- tvboptim/types/parameter.py +769 -0
- tvboptim/types/spaces.py +943 -0
- tvboptim/types/stateutils.py +109 -0
- tvboptim/utils/__init__.py +16 -0
- tvboptim/utils/caching.py +82 -0
- tvboptim/utils/utils.py +265 -0
- tvboptim-0.2.0.dist-info/METADATA +157 -0
- tvboptim-0.2.0.dist-info/RECORD +70 -0
- tvboptim-0.2.0.dist-info/WHEEL +5 -0
- tvboptim-0.2.0.dist-info/licenses/LICENSE +278 -0
- tvboptim-0.2.0.dist-info/top_level.txt +1 -0
|
@@ -0,0 +1,109 @@
|
|
|
1
|
+
# %%
|
|
2
|
+
import equinox as eqx
|
|
3
|
+
import jax
|
|
4
|
+
|
|
5
|
+
from tvboptim.types.parameter import Parameter
|
|
6
|
+
from tvboptim.utils import format_pytree_as_string
|
|
7
|
+
|
|
8
|
+
|
|
9
|
+
def collect_parameters(state):
|
|
10
|
+
"""Extract values from Parameter objects in a state tree.
|
|
11
|
+
|
|
12
|
+
This function traverses a JAX PyTree state and extracts the underlying
|
|
13
|
+
values from Parameter objects while leaving other values unchanged.
|
|
14
|
+
|
|
15
|
+
Parameters
|
|
16
|
+
----------
|
|
17
|
+
state : Any
|
|
18
|
+
JAX PyTree containing Parameter objects and other values.
|
|
19
|
+
|
|
20
|
+
Returns
|
|
21
|
+
-------
|
|
22
|
+
Any
|
|
23
|
+
JAX PyTree with same structure as input, but Parameter objects
|
|
24
|
+
replaced by their underlying values.
|
|
25
|
+
|
|
26
|
+
Examples
|
|
27
|
+
--------
|
|
28
|
+
>>> from tvboptim.types import Parameter
|
|
29
|
+
>>> import jax.numpy as jnp
|
|
30
|
+
>>>
|
|
31
|
+
>>> # Create state with Parameter objects
|
|
32
|
+
>>> state = {
|
|
33
|
+
... 'param1': Parameter(jnp.array(1.5)),
|
|
34
|
+
... 'param2': jnp.array(2.0),
|
|
35
|
+
... 'nested': {'param3': Parameter(jnp.array([1, 2, 3]))}
|
|
36
|
+
... }
|
|
37
|
+
>>>
|
|
38
|
+
>>> # Extract values
|
|
39
|
+
>>> values = collect_parameters(state)
|
|
40
|
+
>>> print(values['param1']) # jnp.array(1.5)
|
|
41
|
+
>>> print(values['param2']) # jnp.array(2.0)
|
|
42
|
+
|
|
43
|
+
Notes
|
|
44
|
+
-----
|
|
45
|
+
This function is useful when you need to extract raw JAX arrays from
|
|
46
|
+
a state tree for operations that don't require Parameter metadata.
|
|
47
|
+
With the new Parameter system, this function may become less necessary
|
|
48
|
+
as Parameters support the JAX array protocol directly.
|
|
49
|
+
"""
|
|
50
|
+
|
|
51
|
+
def _collect_parameters(leaf):
|
|
52
|
+
if isinstance(leaf, Parameter):
|
|
53
|
+
return leaf.__jax_array__()
|
|
54
|
+
else:
|
|
55
|
+
return leaf
|
|
56
|
+
|
|
57
|
+
return jax.tree.map(
|
|
58
|
+
lambda x: _collect_parameters(x),
|
|
59
|
+
state,
|
|
60
|
+
is_leaf=lambda x: isinstance(x, Parameter),
|
|
61
|
+
)
|
|
62
|
+
|
|
63
|
+
|
|
64
|
+
# %%
|
|
65
|
+
def mark_parameters(state):
|
|
66
|
+
"""Mark Parameter objects for partitioning."""
|
|
67
|
+
|
|
68
|
+
def is_parameter(leaf):
|
|
69
|
+
return isinstance(leaf, Parameter)
|
|
70
|
+
|
|
71
|
+
return jax.tree.map(
|
|
72
|
+
lambda x: is_parameter(x), state, is_leaf=lambda x: isinstance(x, Parameter)
|
|
73
|
+
)
|
|
74
|
+
|
|
75
|
+
|
|
76
|
+
# %%
|
|
77
|
+
def partition_state(state):
|
|
78
|
+
"""Separate Parameter objects from static values for optimization."""
|
|
79
|
+
param_mask = mark_parameters(state)
|
|
80
|
+
diff_state, static_state = eqx.partition(
|
|
81
|
+
state, param_mask, is_leaf=lambda x: isinstance(x, Parameter)
|
|
82
|
+
)
|
|
83
|
+
return diff_state, static_state
|
|
84
|
+
|
|
85
|
+
|
|
86
|
+
def combine_state(diff_state, static_state):
|
|
87
|
+
"""Recombine optimized parameters with static values."""
|
|
88
|
+
return eqx.combine(
|
|
89
|
+
diff_state, static_state, is_leaf=lambda x: isinstance(x, Parameter)
|
|
90
|
+
)
|
|
91
|
+
|
|
92
|
+
|
|
93
|
+
# def show_free(tree):
|
|
94
|
+
# def _show_free(leaf):
|
|
95
|
+
# if isinstance(leaf, Value) and leaf.free:
|
|
96
|
+
# print(leaf)
|
|
97
|
+
# jax.tree.map(_show_free, tree, is_leaf=lambda x: isinstance(x, Value))
|
|
98
|
+
def show_parameters(tree):
|
|
99
|
+
"""Show Parameter objects in the tree."""
|
|
100
|
+
param_mask = mark_parameters(tree)
|
|
101
|
+
diff_model, _ = eqx.partition(
|
|
102
|
+
tree, param_mask, is_leaf=lambda x: isinstance(x, Parameter)
|
|
103
|
+
)
|
|
104
|
+
print(
|
|
105
|
+
format_pytree_as_string(
|
|
106
|
+
diff_model, hide_none=True, name="Parameters", show_array_values=True
|
|
107
|
+
)
|
|
108
|
+
)
|
|
109
|
+
return None
|
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
from .caching import cache, set_cache_path
|
|
2
|
+
from .utils import (
|
|
3
|
+
broadcast_1d_array,
|
|
4
|
+
format_pytree_as_string,
|
|
5
|
+
pretty_print_pytree,
|
|
6
|
+
safe_reshape,
|
|
7
|
+
)
|
|
8
|
+
|
|
9
|
+
__all__ = [
|
|
10
|
+
"cache",
|
|
11
|
+
"set_cache_path",
|
|
12
|
+
"broadcast_1d_array",
|
|
13
|
+
"format_pytree_as_string",
|
|
14
|
+
"pretty_print_pytree",
|
|
15
|
+
"safe_reshape",
|
|
16
|
+
]
|
|
@@ -0,0 +1,82 @@
|
|
|
1
|
+
# config and helpers for manually caching long computations to make the rendering of .qmds/.ipynbs faster
|
|
2
|
+
import os
|
|
3
|
+
import shutil
|
|
4
|
+
from datetime import datetime
|
|
5
|
+
|
|
6
|
+
import dill as pickle
|
|
7
|
+
|
|
8
|
+
cache_root = os.path.join(os.path.abspath(""), "cache")
|
|
9
|
+
cache_path = None
|
|
10
|
+
caching = True
|
|
11
|
+
|
|
12
|
+
|
|
13
|
+
def set_cache_path(experiment=""):
|
|
14
|
+
"""
|
|
15
|
+
Set the path where the cache is stored, relative to the cache root which lies next to this file in /cache.
|
|
16
|
+
|
|
17
|
+
* `experiment`: name of the experiment / notebook -> becomes a subdirectory in the cache root
|
|
18
|
+
"""
|
|
19
|
+
global cache_path
|
|
20
|
+
cache_path = os.path.join(cache_root, experiment)
|
|
21
|
+
print(f"Cache stored here: {cache_path}")
|
|
22
|
+
return cache_path
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
def clear_all_cache():
|
|
26
|
+
"""
|
|
27
|
+
Clear all caches in the current cache root.
|
|
28
|
+
"""
|
|
29
|
+
if os.path.exists(cache_root):
|
|
30
|
+
shutil.rmtree(cache_root)
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
def clear_experiment_cache():
|
|
34
|
+
"""
|
|
35
|
+
Clear the cache for the current experiment / notebook.
|
|
36
|
+
"""
|
|
37
|
+
if os.path.exists(cache_path):
|
|
38
|
+
shutil.rmtree(cache_path)
|
|
39
|
+
|
|
40
|
+
|
|
41
|
+
def cache(fname="", redo=False):
|
|
42
|
+
"""
|
|
43
|
+
Caching decorator - use with care!
|
|
44
|
+
|
|
45
|
+
Brings variable in global scope and assigns it either a cached version or the result of decorated function.
|
|
46
|
+
|
|
47
|
+
* `fname`: name of the file where the computation is stored under `cache_path`
|
|
48
|
+
* `redo`: if True, the computation is run even if the file already exists
|
|
49
|
+
"""
|
|
50
|
+
|
|
51
|
+
def decorator(func):
|
|
52
|
+
def wrapper(*args, **kwargs):
|
|
53
|
+
global cache_path
|
|
54
|
+
if cache_path is None:
|
|
55
|
+
raise ValueError(
|
|
56
|
+
"No cache path set. Use `set_cache_path` to set the path to the cache."
|
|
57
|
+
)
|
|
58
|
+
cache_file = os.path.join(cache_path, f"{fname}.pkl")
|
|
59
|
+
|
|
60
|
+
if not redo and os.path.exists(cache_file):
|
|
61
|
+
print(
|
|
62
|
+
f"Loading {fname} from cache, last modified {datetime.fromtimestamp(os.path.getmtime(cache_file))}"
|
|
63
|
+
)
|
|
64
|
+
with open(cache_file, "rb") as f:
|
|
65
|
+
# exec(f"global {variable}\n{variable} = pickle.load(f)")
|
|
66
|
+
comp = pickle.load(f)
|
|
67
|
+
else:
|
|
68
|
+
print(f"Running computations for {fname}")
|
|
69
|
+
comp = func(*args, **kwargs)
|
|
70
|
+
if caching:
|
|
71
|
+
if not os.path.exists(cache_path):
|
|
72
|
+
os.makedirs(cache_path)
|
|
73
|
+
with open(cache_file, "wb") as f:
|
|
74
|
+
# Use protocol 4 for Python 3.4+ compatibility
|
|
75
|
+
# Avoid HIGHEST_PROTOCOL which changes between versions
|
|
76
|
+
pickle.dump(comp, f, protocol=4)
|
|
77
|
+
# exec(f"global {fname}\n{fname} = comp")
|
|
78
|
+
return comp
|
|
79
|
+
|
|
80
|
+
return wrapper
|
|
81
|
+
|
|
82
|
+
return decorator
|
tvboptim/utils/utils.py
ADDED
|
@@ -0,0 +1,265 @@
|
|
|
1
|
+
import equinox as eqx
|
|
2
|
+
import jax
|
|
3
|
+
import jax.numpy as jnp
|
|
4
|
+
import numpy as np
|
|
5
|
+
|
|
6
|
+
|
|
7
|
+
def format_pytree_as_string(
|
|
8
|
+
pytree,
|
|
9
|
+
name: str = "root",
|
|
10
|
+
prefix: str = "",
|
|
11
|
+
is_last: bool = False,
|
|
12
|
+
show_numerical_only: bool = False,
|
|
13
|
+
is_root: bool = True,
|
|
14
|
+
hide_none: bool = False,
|
|
15
|
+
show_array_values: bool = False,
|
|
16
|
+
):
|
|
17
|
+
"""
|
|
18
|
+
Recursively formats a JAX pytree structure as a string with Unicode box-drawing characters.
|
|
19
|
+
|
|
20
|
+
Args:
|
|
21
|
+
pytree: The pytree to format
|
|
22
|
+
name: The name of the current node
|
|
23
|
+
prefix: Current line prefix
|
|
24
|
+
is_last: Whether the current node is the last child of its parent
|
|
25
|
+
show_numerical_only: If True, only show arrays and numerical types (float, int, etc.)
|
|
26
|
+
is_root: Whether this node is the root of the tree
|
|
27
|
+
hide_none: If True, fields with None values will be hidden
|
|
28
|
+
|
|
29
|
+
Returns:
|
|
30
|
+
str: The formatted string representation of the pytree
|
|
31
|
+
"""
|
|
32
|
+
# Unicode box-drawing characters for the tree structure
|
|
33
|
+
space = " "
|
|
34
|
+
branch = "│ "
|
|
35
|
+
tee = "├── "
|
|
36
|
+
last = "└── "
|
|
37
|
+
|
|
38
|
+
# Initialize the result string
|
|
39
|
+
result = []
|
|
40
|
+
|
|
41
|
+
# Special handling for root element
|
|
42
|
+
if is_root:
|
|
43
|
+
current_prefix = "" # Root has no prefix
|
|
44
|
+
next_prefix = "" # Children of root start without vertical bars
|
|
45
|
+
else:
|
|
46
|
+
# Determine the current line prefix
|
|
47
|
+
current_prefix = prefix + (last if is_last else tee)
|
|
48
|
+
# Determine the prefix for children
|
|
49
|
+
next_prefix = prefix + (space if is_last else branch)
|
|
50
|
+
|
|
51
|
+
# Check if the object is a string
|
|
52
|
+
if isinstance(pytree, str):
|
|
53
|
+
if not show_numerical_only:
|
|
54
|
+
result.append(f'{current_prefix}{name}: "{pytree}"')
|
|
55
|
+
return "\n".join(result)
|
|
56
|
+
|
|
57
|
+
# Check if the object is None
|
|
58
|
+
if pytree is None:
|
|
59
|
+
if not hide_none and not show_numerical_only:
|
|
60
|
+
result.append(f"{current_prefix}{name}: NoneType")
|
|
61
|
+
return "\n".join(result)
|
|
62
|
+
|
|
63
|
+
# Check if the object is a JAX array
|
|
64
|
+
if isinstance(pytree, (jnp.ndarray, np.ndarray)):
|
|
65
|
+
# result.append(f"{current_prefix}{name}: Array(shape={pytree.shape}, dtype={pytree.dtype})")
|
|
66
|
+
if show_array_values:
|
|
67
|
+
# result.append(f"{current_prefix}{name}: Array({shape_str}, {dtype_str})")
|
|
68
|
+
# result.append(f"{current_prefix}{name}: No({shape_str}, {dtype_str})")
|
|
69
|
+
result.append(f"{current_prefix}{name}: {pytree}")
|
|
70
|
+
else:
|
|
71
|
+
result.append(f"{current_prefix}{name}: {eqx.tree_pformat(pytree)}")
|
|
72
|
+
return "\n".join(result)
|
|
73
|
+
|
|
74
|
+
# Try to flatten the pytree
|
|
75
|
+
try:
|
|
76
|
+
leaves, _ = jax.tree_util.tree_flatten(pytree)
|
|
77
|
+
# If it's a leaf (i.e., it has no children), format its type
|
|
78
|
+
if not leaves or (len(leaves) == 1 and pytree is leaves[0]):
|
|
79
|
+
# For numerical types, always display the value
|
|
80
|
+
if isinstance(pytree, (int, float, bool, complex)):
|
|
81
|
+
result.append(f"{current_prefix}{name}: {pytree}")
|
|
82
|
+
# For other types, check filter setting
|
|
83
|
+
elif not show_numerical_only:
|
|
84
|
+
result.append(f"{current_prefix}{name}: {type(pytree).__name__}")
|
|
85
|
+
return "\n".join(result)
|
|
86
|
+
|
|
87
|
+
# Otherwise, format it as a container and process its children
|
|
88
|
+
result.append(f"{current_prefix}{name}")
|
|
89
|
+
|
|
90
|
+
# If it's a dictionary, iterate through its key-value pairs
|
|
91
|
+
if isinstance(pytree, dict):
|
|
92
|
+
items = list(pytree.items())
|
|
93
|
+
for i, (key, value) in enumerate(items):
|
|
94
|
+
child_result = format_pytree_as_string(
|
|
95
|
+
value,
|
|
96
|
+
str(key),
|
|
97
|
+
next_prefix,
|
|
98
|
+
i == len(items) - 1,
|
|
99
|
+
show_numerical_only,
|
|
100
|
+
False,
|
|
101
|
+
hide_none,
|
|
102
|
+
show_array_values,
|
|
103
|
+
)
|
|
104
|
+
if child_result: # Only append if there's content (might be empty with show_numerical_only)
|
|
105
|
+
result.append(child_result)
|
|
106
|
+
|
|
107
|
+
# If it's a dataclass or a custom class with __dict__ attribute
|
|
108
|
+
elif hasattr(pytree, "__dict__"):
|
|
109
|
+
items = list(pytree.__dict__.items())
|
|
110
|
+
for i, (key, value) in enumerate(items):
|
|
111
|
+
child_result = format_pytree_as_string(
|
|
112
|
+
value,
|
|
113
|
+
key,
|
|
114
|
+
next_prefix,
|
|
115
|
+
i == len(items) - 1,
|
|
116
|
+
show_numerical_only,
|
|
117
|
+
False,
|
|
118
|
+
hide_none,
|
|
119
|
+
show_array_values,
|
|
120
|
+
)
|
|
121
|
+
if child_result:
|
|
122
|
+
result.append(child_result)
|
|
123
|
+
|
|
124
|
+
# If it's a sequence (like list or tuple)
|
|
125
|
+
elif hasattr(pytree, "__len__") and not isinstance(
|
|
126
|
+
pytree, (str, bytes, bytearray)
|
|
127
|
+
):
|
|
128
|
+
for i, item in enumerate(pytree):
|
|
129
|
+
child_result = format_pytree_as_string(
|
|
130
|
+
item,
|
|
131
|
+
f"[{i}]",
|
|
132
|
+
next_prefix,
|
|
133
|
+
i == len(pytree) - 1,
|
|
134
|
+
show_numerical_only,
|
|
135
|
+
False,
|
|
136
|
+
hide_none,
|
|
137
|
+
show_array_values,
|
|
138
|
+
)
|
|
139
|
+
if child_result:
|
|
140
|
+
result.append(child_result)
|
|
141
|
+
|
|
142
|
+
# For other types of containers
|
|
143
|
+
else:
|
|
144
|
+
result.append(
|
|
145
|
+
f"{current_prefix}{name}: {type(pytree).__name__} (unknown structure)"
|
|
146
|
+
)
|
|
147
|
+
|
|
148
|
+
except Exception:
|
|
149
|
+
# If we can't flatten it as a pytree, treat it as a leaf
|
|
150
|
+
# For strings, display the string value if not filtering
|
|
151
|
+
if isinstance(pytree, str):
|
|
152
|
+
if not show_numerical_only:
|
|
153
|
+
result.append(f'{current_prefix}{name}: "{pytree}"')
|
|
154
|
+
# For numerical types, always display the value
|
|
155
|
+
elif isinstance(pytree, (int, float, bool, complex)):
|
|
156
|
+
result.append(f"{current_prefix}{name}: {pytree}")
|
|
157
|
+
# For other types, check filter setting
|
|
158
|
+
elif not show_numerical_only:
|
|
159
|
+
result.append(f"{current_prefix}{name}: {type(pytree).__name__}")
|
|
160
|
+
|
|
161
|
+
return "\n".join(result)
|
|
162
|
+
|
|
163
|
+
|
|
164
|
+
def pretty_print_pytree(
|
|
165
|
+
pytree,
|
|
166
|
+
name: str = "root",
|
|
167
|
+
prefix: str = "",
|
|
168
|
+
show_numerical_only: bool = False,
|
|
169
|
+
hide_none: bool = False,
|
|
170
|
+
):
|
|
171
|
+
"""
|
|
172
|
+
Prints a pretty formatted representation of a JAX pytree structure.
|
|
173
|
+
|
|
174
|
+
Args:
|
|
175
|
+
pytree: The pytree to print
|
|
176
|
+
name: The name of the current node
|
|
177
|
+
prefix: Current line prefix
|
|
178
|
+
show_numerical_only: If True, only show arrays and numerical types (float, int, etc.)
|
|
179
|
+
hide_none: If True, fields with None values will be hidden
|
|
180
|
+
"""
|
|
181
|
+
formatted_string = format_pytree_as_string(
|
|
182
|
+
pytree, name, prefix, False, show_numerical_only, True, hide_none
|
|
183
|
+
)
|
|
184
|
+
print(formatted_string)
|
|
185
|
+
|
|
186
|
+
|
|
187
|
+
def safe_reshape(arr, new_shape, fill_value=jnp.nan):
|
|
188
|
+
"""
|
|
189
|
+
A safe reshaping function with the following properties:
|
|
190
|
+
- If new_shape has fewer elements than arr, raises an error
|
|
191
|
+
- If new_shape has equal elements to arr, performs standard reshape
|
|
192
|
+
- If new_shape requires more elements than arr, fills extra space with fill_value
|
|
193
|
+
|
|
194
|
+
Args:
|
|
195
|
+
arr: JAX array to reshape
|
|
196
|
+
new_shape: Tuple of integers specifying the new shape
|
|
197
|
+
fill_value: Value to use for filling extra elements (default: jnp.nan)
|
|
198
|
+
|
|
199
|
+
Returns:
|
|
200
|
+
Reshaped JAX array
|
|
201
|
+
"""
|
|
202
|
+
# Calculate current and new sizes
|
|
203
|
+
old_size = arr.size
|
|
204
|
+
new_size = jnp.prod(jnp.abs(jnp.array(new_shape)))
|
|
205
|
+
|
|
206
|
+
# Case 1: New shape has fewer elements than the original array
|
|
207
|
+
if new_size < old_size:
|
|
208
|
+
raise ValueError(
|
|
209
|
+
f"New shape {new_shape} has fewer elements ({new_size}) "
|
|
210
|
+
f"than original array ({old_size} elements)"
|
|
211
|
+
)
|
|
212
|
+
|
|
213
|
+
# Case 2: New shape has equal elements to the original array
|
|
214
|
+
elif new_size == old_size:
|
|
215
|
+
return arr.reshape(new_shape)
|
|
216
|
+
|
|
217
|
+
# Case 3: New shape requires more elements than the original array
|
|
218
|
+
else:
|
|
219
|
+
# Create a new array filled with the fill_value
|
|
220
|
+
result = jnp.full(new_shape, fill_value, dtype=arr.dtype)
|
|
221
|
+
|
|
222
|
+
# Create a flattened view of the result array
|
|
223
|
+
result_flat = result.reshape(-1)
|
|
224
|
+
|
|
225
|
+
# For newer JAX versions:
|
|
226
|
+
result_flat = result_flat.at[:old_size].set(arr.reshape(-1))
|
|
227
|
+
|
|
228
|
+
return result_flat.reshape(new_shape)
|
|
229
|
+
|
|
230
|
+
|
|
231
|
+
def broadcast_1d_array(arr_1d, additional_dims=()):
|
|
232
|
+
"""
|
|
233
|
+
Broadcast a 1D array of shape (N,) to shape (N, *additional_dims)
|
|
234
|
+
with a single reshape operation.
|
|
235
|
+
|
|
236
|
+
Parameters:
|
|
237
|
+
-----------
|
|
238
|
+
arr_1d : numpy.ndarray or jax.numpy.ndarray
|
|
239
|
+
1D input array of shape (N,)
|
|
240
|
+
additional_dims : tuple
|
|
241
|
+
Additional dimensions to broadcast to. Can be empty tuple () for no additional dimensions.
|
|
242
|
+
|
|
243
|
+
Returns:
|
|
244
|
+
--------
|
|
245
|
+
numpy.ndarray or jax.numpy.ndarray
|
|
246
|
+
Broadcasted array of shape (N, *additional_dims)
|
|
247
|
+
"""
|
|
248
|
+
# Handle the case of no additional dimensions
|
|
249
|
+
if not additional_dims:
|
|
250
|
+
return arr_1d
|
|
251
|
+
|
|
252
|
+
N_shape = jnp.shape(arr_1d)
|
|
253
|
+
# N = arr_1d.shape[0]
|
|
254
|
+
|
|
255
|
+
# Create a target shape with ones for the new dimensions
|
|
256
|
+
reshape_dims = N_shape + (1,) * len(additional_dims)
|
|
257
|
+
|
|
258
|
+
# Reshape in a single operation
|
|
259
|
+
reshaped = arr_1d.reshape(reshape_dims)
|
|
260
|
+
|
|
261
|
+
# Create the final target shape
|
|
262
|
+
target_shape = N_shape + additional_dims
|
|
263
|
+
|
|
264
|
+
# Use broadcast_to for memory efficiency
|
|
265
|
+
return jnp.broadcast_to(reshaped, target_shape)
|
|
@@ -0,0 +1,157 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: tvboptim
|
|
3
|
+
Version: 0.2.0
|
|
4
|
+
Summary: Optimization tools for The Virtual Brain
|
|
5
|
+
Author-email: Marius Pille <marius.pille@bih-charite.de>
|
|
6
|
+
License-Expression: EUPL-1.2
|
|
7
|
+
Project-URL: Homepage, https://github.com/virtual-twin/tvboptim
|
|
8
|
+
Project-URL: Bug Tracker, https://github.com/virtual-twin/tvboptim/issues
|
|
9
|
+
Keywords: tvb,optimization,neuroscience,brain,virtual-brain,jax,neural-simulation
|
|
10
|
+
Classifier: Development Status :: 3 - Alpha
|
|
11
|
+
Classifier: Intended Audience :: Science/Research
|
|
12
|
+
Classifier: Topic :: Scientific/Engineering :: Medical Science Apps.
|
|
13
|
+
Classifier: Topic :: Scientific/Engineering :: Bio-Informatics
|
|
14
|
+
Classifier: Programming Language :: Python :: 3
|
|
15
|
+
Classifier: Programming Language :: Python :: 3.11
|
|
16
|
+
Classifier: Programming Language :: Python :: 3.12
|
|
17
|
+
Classifier: Operating System :: OS Independent
|
|
18
|
+
Requires-Python: >=3.11
|
|
19
|
+
Description-Content-Type: text/markdown
|
|
20
|
+
License-File: LICENSE
|
|
21
|
+
Requires-Dist: optax
|
|
22
|
+
Requires-Dist: optimistix
|
|
23
|
+
Requires-Dist: matplotlib
|
|
24
|
+
Requires-Dist: numpy
|
|
25
|
+
Requires-Dist: pandas
|
|
26
|
+
Requires-Dist: jax<0.8
|
|
27
|
+
Requires-Dist: equinox
|
|
28
|
+
Requires-Dist: dill
|
|
29
|
+
Requires-Dist: tqdm
|
|
30
|
+
Requires-Dist: numpyro>=0.19.0
|
|
31
|
+
Requires-Dist: diffrax
|
|
32
|
+
Requires-Dist: plum-dispatch
|
|
33
|
+
Provides-Extra: dev
|
|
34
|
+
Requires-Dist: pytest>=7.0.0; extra == "dev"
|
|
35
|
+
Requires-Dist: pytest-cov>=4.0.0; extra == "dev"
|
|
36
|
+
Requires-Dist: ruff>=0.8.0; extra == "dev"
|
|
37
|
+
Requires-Dist: quartodoc>=0.6.0; extra == "dev"
|
|
38
|
+
Requires-Dist: jupyter>=1.0.0; extra == "dev"
|
|
39
|
+
Requires-Dist: ipykernel; extra == "dev"
|
|
40
|
+
Provides-Extra: docs
|
|
41
|
+
Requires-Dist: jupyter-cache>=1.0.1; extra == "docs"
|
|
42
|
+
Dynamic: license-file
|
|
43
|
+
|
|
44
|
+
<p align="center">
|
|
45
|
+
<img src="./docs/images/tvboptim.png" width="60%">
|
|
46
|
+
</p>
|
|
47
|
+
|
|
48
|
+
# TVB-Optim
|
|
49
|
+
|
|
50
|
+
[](https://github.com/virtual-twin/tvboptim/actions/workflows/python-package.yml)
|
|
51
|
+
[](https://codecov.io/gh/virtual-twin/tvboptim)
|
|
52
|
+
[](https://www.python.org/downloads/)
|
|
53
|
+
|
|
54
|
+
[JAX](https://jax.readthedocs.io/en/latest/)-based framework for brain network simulation and gradient-based optimization.
|
|
55
|
+
|
|
56
|
+
**[Documentation](https://virtual-twin.github.io/tvboptim)** | **[Get Started](https://virtual-twin.github.io/tvboptim/get_started.html)** | **[Examples](https://virtual-twin.github.io/tvboptim/network_dynamics/network_dynamics.html)**
|
|
57
|
+
|
|
58
|
+
## Key Features
|
|
59
|
+
|
|
60
|
+
- **Gradient-based optimization** - Fit thousands of parameters using automatic differentiation through the entire simulation pipeline
|
|
61
|
+
- **Performance** - JAX-powered with seamless GPU/TPU scaling
|
|
62
|
+
- **Flexible & extensible** - Build models with [Network Dynamics](https://virtual-twin.github.io/tvboptim/network_dynamics/network_dynamics.html), a composable framework for whole-brain modeling. Existing TVB workflows supported via [TVB-O](https://github.com/virtual-twin/tvbo).
|
|
63
|
+
- **Intuitive parameter control** - Mark values for optimization with [Parameter()](https://virtual-twin.github.io/tvboptim/parameters_and_optimization.html). Define exploration spaces with [Axes](https://virtual-twin.github.io/tvboptim/axes_and_spaces.html) for automatic parallel evaluation via JAX vmap/pmap.
|
|
64
|
+
|
|
65
|
+
## Installation
|
|
66
|
+
|
|
67
|
+
**Requires Python 3.11 or above**
|
|
68
|
+
|
|
69
|
+
```bash
|
|
70
|
+
# Using uv (recommended)
|
|
71
|
+
uv pip install tvboptim
|
|
72
|
+
|
|
73
|
+
# Using pip
|
|
74
|
+
pip install tvboptim
|
|
75
|
+
```
|
|
76
|
+
|
|
77
|
+
## Quick Example
|
|
78
|
+
|
|
79
|
+
```python
|
|
80
|
+
import jax.numpy as jnp
|
|
81
|
+
from tvboptim.experimental.network_dynamics import Network, solve, prepare
|
|
82
|
+
from tvboptim.experimental.network_dynamics.dynamics.tvb import ReducedWongWang
|
|
83
|
+
from tvboptim.experimental.network_dynamics.coupling import LinearCoupling
|
|
84
|
+
from tvboptim.experimental.network_dynamics.graph import DenseDelayGraph
|
|
85
|
+
from tvboptim.observations.tvb_monitors import Bold
|
|
86
|
+
from tvboptim.observations import compute_fc, rmse
|
|
87
|
+
from tvboptim.optim import OptaxOptimizer
|
|
88
|
+
import optax
|
|
89
|
+
|
|
90
|
+
# Build brain network model
|
|
91
|
+
network = Network(
|
|
92
|
+
dynamics=ReducedWongWang(),
|
|
93
|
+
coupling={'delayed': LinearCoupling(incoming_states="S", G=0.5)},
|
|
94
|
+
graph=DenseDelayGraph(weights, delays)
|
|
95
|
+
)
|
|
96
|
+
|
|
97
|
+
# Run simulation
|
|
98
|
+
result = solve(network, Heun(), t0=0.0, t1=60_000.0, dt=1.0)
|
|
99
|
+
|
|
100
|
+
# Optimize coupling strength to match empirical functional connectivity
|
|
101
|
+
simulator, params = prepare(network, Heun(), t0=0.0, t1=60_000.0, dt=1.0)
|
|
102
|
+
bold_monitor = Bold(history=result, period=720.0)
|
|
103
|
+
|
|
104
|
+
def loss(params):
|
|
105
|
+
predicted_fc = compute_fc(bold_monitor(simulator(params)))
|
|
106
|
+
return rmse(predicted_fc, target_fc)
|
|
107
|
+
|
|
108
|
+
opt = OptaxOptimizer(loss, optax.adam(learning_rate=0.03))
|
|
109
|
+
final_params, history = opt.run(params, max_steps=50)
|
|
110
|
+
```
|
|
111
|
+
|
|
112
|
+
See the [full example with visualization](https://virtual-twin.github.io/tvboptim/) in the documentation.
|
|
113
|
+
|
|
114
|
+
## Documentation
|
|
115
|
+
|
|
116
|
+
- **[Get Started](https://virtual-twin.github.io/tvboptim/get_started.html)** - Introduction and basic workflows
|
|
117
|
+
- **[Network Dynamics](https://virtual-twin.github.io/tvboptim/network_dynamics/network_dynamics.html)** - Build differentiable brain network models
|
|
118
|
+
- **[Parameters & Optimization](https://virtual-twin.github.io/tvboptim/parameters_and_optimization.html)** - Gradient-based parameter inference
|
|
119
|
+
- **[API Reference](https://virtual-twin.github.io/tvboptim/reference/index.html)** - Complete API documentation
|
|
120
|
+
|
|
121
|
+
## How It Works
|
|
122
|
+
|
|
123
|
+
**Functional Composition** - Models are composable functions that can be inspected, modified, and extended. Build complexity incrementally by wrapping functions.
|
|
124
|
+
|
|
125
|
+
**End-to-End Differentiability** - Compute gradients through the full pipeline: neural dynamics → hemodynamic models → empirical observables.
|
|
126
|
+
|
|
127
|
+
**Interoperability** - Convert existing TVB simulations to JAX-compatible functions via the TVB-O framework.
|
|
128
|
+
|
|
129
|
+
## Contributing
|
|
130
|
+
|
|
131
|
+
We welcome contributions and questions from the community!
|
|
132
|
+
|
|
133
|
+
- **Report Issues**: [Open an issue](https://github.com/virtual-twin/tvboptim/issues)
|
|
134
|
+
- **Ask Questions**: [Start a discussion](https://github.com/virtual-twin/tvboptim/discussions)
|
|
135
|
+
- **Contribute Code**: [Open a pull request](https://github.com/virtual-twin/tvboptim/pulls)
|
|
136
|
+
|
|
137
|
+
## Contact
|
|
138
|
+
|
|
139
|
+
Questions or want to collaborate? Reach out:
|
|
140
|
+
|
|
141
|
+
* marius.pille[at]bih-charite.de
|
|
142
|
+
|
|
143
|
+
## Citation
|
|
144
|
+
|
|
145
|
+
If you use TVB-Optim in your research, please cite:
|
|
146
|
+
|
|
147
|
+
```bibtex
|
|
148
|
+
@article{2025tvboptim,
|
|
149
|
+
title={Fast and Easy Whole-Brain Network Model Parameter Estimation with Automatic Differentiation},
|
|
150
|
+
author={Pille, Marius and Martin, Leon and Richter, Emilius and Perdikis, Dionysios and Schirner, Michael and Ritter, Petra},
|
|
151
|
+
journal={bioRxiv},
|
|
152
|
+
year={2025},
|
|
153
|
+
doi={10.1101/2025.11.18.689003}
|
|
154
|
+
}
|
|
155
|
+
```
|
|
156
|
+
|
|
157
|
+
Copyright © 2025 Charité Universitätsmedizin Berlin
|