Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Optimal Control extension #247

Merged
merged 284 commits into from
Dec 22, 2023
Merged
Show file tree
Hide file tree
Changes from 250 commits
Commits
Show all changes
284 commits
Select commit Hold shift + click to select a range
ac9a4f3
implemented first method for noisy systems
lenasal Jul 28, 2022
ebcf68b
example folder
lenasal Jul 28, 2022
4d3a5a5
added comments and description
lenasal Jul 29, 2022
f147526
start readme
lenasal Jul 29, 2022
9a3b235
Update README.md
lenasal Jul 29, 2022
fd72110
added contributing file
lenasal Jul 29, 2022
6240ada
Update README.md
lenasal Jul 29, 2022
9221dff
Update README.md
lenasal Jul 29, 2022
f8bea7a
Update CONTRIBUTING.md
lenasal Jul 29, 2022
cf04b74
Update CONTRIBUTING.md
lenasal Jul 29, 2022
ee3cf2d
Update CONTRIBUTING.md
lenasal Jul 29, 2022
378c0fa
Update CONTRIBUTING.md
lenasal Jul 29, 2022
d482e7d
Update README.md
lenasal Jul 29, 2022
66a57f5
Update README.md
lenasal Jul 29, 2022
141bef7
update with code formatter
lenasal Jul 29, 2022
e195044
Merge branch 'documentation' of github.com:lenasal/neurolib into docu…
lenasal Jul 29, 2022
930f614
- edited docstring of __init__
martinptm Aug 2, 2022
8f730bf
added warning and info print for unreasonable parameter choices
lenasal Aug 4, 2022
5ff99bf
revised code
lenasal Aug 4, 2022
fce5151
- docstrings according to Sphinx docstring format
martinptm Aug 5, 2022
91a7550
Update CONTRIBUTING.md
lenasal Aug 9, 2022
92f2768
Merge branch 'documentation' into OCdev
martinptm Aug 9, 2022
48f3c4b
- code formatting with --line-length=120
martinptm Aug 9, 2022
99d7382
- code formatting with --line-length=120
martinptm Aug 9, 2022
d744ea8
adjusted shapes of arrays, no network yet
lenasal Aug 10, 2022
a28b921
implemented control matrix and precision matrix
lenasal Aug 10, 2022
f915aa8
starting testing
lenasal Aug 11, 2022
69eeaac
first functioning version without delay
lenasal Aug 11, 2022
51c450a
functional tested version of network OC for fhn
lenasal Aug 12, 2022
2e6b50d
cleaned up
lenasal Aug 12, 2022
248522c
stochastic method
lenasal Aug 12, 2022
51555cf
- fix dimensions and slices according to network-compatible dimension…
martinptm Aug 16, 2022
8d0d2e6
- noisy network example
martinptm Aug 17, 2022
c4f7c01
check cmat diagonal entries
lenasal Aug 17, 2022
d558a85
- added some description for noisy network example and made the setti…
martinptm Aug 17, 2022
dacde71
Merge remote-tracking branch 'origin/fhn_network' into fhn_network
martinptm Aug 17, 2022
b33f7f7
adjusted test setting, updated example files for noise case
lenasal Aug 17, 2022
3dfb6e2
adjusted test setting, updated example files for noise case
lenasal Aug 17, 2022
99b72f0
added tests in test_fhn_noisy and test_fhn
lenasal Aug 18, 2022
c530522
speed up solve_adjoint method
lenasal Aug 18, 2022
da65dcd
- removed unused matplotlib import in test_fhn.py
martinptm Aug 19, 2022
fec3c85
adjust parameters in test_fhn
lenasal Aug 22, 2022
c7d4f06
- baseclass for OC
martinptm Aug 24, 2022
82c7aaf
- skeleton for OC for Hopf model
martinptm Aug 24, 2022
e9e6580
- optimal control for Hopf model with quick visual evaluation of the …
martinptm Aug 26, 2022
772df28
- fix overwriting attributes of the neurolib-model that is passed to …
martinptm Sep 2, 2022
114c4b4
- add check for passed model in model specific OC
martinptm Sep 13, 2022
8606c21
- add test_twonode_oc for deterministic hopf
martinptm Sep 13, 2022
2693619
- remove fhn example, is replaced by combined example
martinptm Sep 13, 2022
1049207
refactoring stochastic OC
lenasal Sep 14, 2022
9be6743
refactored stochastic control
lenasal Sep 15, 2022
61be4a9
fixed bugs
lenasal Sep 15, 2022
17f35ec
implemented wc model
lenasal Sep 19, 2022
cb245e6
oc wc implemented and partially tested
lenasal Sep 29, 2022
ed9f12c
- improved performance of cost functions and derivatives (derivative_…
martinptm Oct 15, 2022
bba7e5d
merged OCdev
lenasal Oct 18, 2022
cedf431
functional version wc optimal control
lenasal Oct 18, 2022
0d7b7e2
Merge branch 'cost_functions_numba' into wc_model
lenasal Oct 18, 2022
ce4c284
remove file
lenasal Oct 18, 2022
fc46878
Merge remote-tracking branch 'origin/stochastic_systems' into cost_fu…
martinptm Oct 18, 2022
f03684f
- remove explicit passing of parameter "N" to precision_cost function
martinptm Oct 18, 2022
0e6cda1
- simplified function, passes tests
martinptm Oct 19, 2022
16abe8d
- fix: adjoint_state[t=0] was never computed
martinptm Oct 20, 2022
fea4f0a
Merge branch 'cost_functions_numba' into wc_model
lenasal Oct 20, 2022
ec9f506
- added function 'update_control_with_limit' to limit the absolute va…
martinptm Oct 20, 2022
097fb02
- fix: added missing 'maximum_control_strength' as parameter in the d…
martinptm Oct 20, 2022
31d47b0
Merge branch 'cost_functions_numba' into wc_model
lenasal Oct 21, 2022
299a57c
- fix: added scaling by time step of precision- and energy cost, adde…
martinptm Oct 21, 2022
f100df5
corrected background missing
lenasal Oct 25, 2022
edf17f5
- interval in which precision cost is now positional argument to avoi…
martinptm Oct 25, 2022
5f24c59
- added: apply maximal-absolute-control-strength constraint even befo…
martinptm Oct 26, 2022
ff880f1
- additional assertions for interval specification
martinptm Oct 28, 2022
e4245cb
merged cost_functions_numba branch
lenasal Oct 28, 2022
7ebc2e8
merged cost_functions_numba branch
lenasal Oct 28, 2022
01b0b73
Merge branch 'master' into OCdev
lenasal Nov 3, 2022
ff8f9ee
- adjusted to naming 'Duh' for Jacobian
martinptm Nov 3, 2022
fbb0ff1
removed unnecessary line of code
lenasal Nov 7, 2022
352b437
Merge branch 'wc_model' of github.com:lenasal/neurolib into wc_model
lenasal Nov 7, 2022
bddcda2
merged OCdev
lenasal Nov 7, 2022
9bbb626
remove background from oc.py
lenasal Nov 11, 2022
8dd9e85
- adaptive step size computation:
martinptm Dec 3, 2022
91174ea
- add counter=0 in case of zero gradient
martinptm Dec 7, 2022
b847597
- combine the step-size combination for the noisy and the noise free …
martinptm Dec 7, 2022
6f32912
- shared "factor_down" for noisy and deterministic case
martinptm Dec 8, 2022
643f21a
- revision of documentation
martinptm Dec 16, 2022
be79994
- revision of docstrings for clean documentation build
martinptm Dec 19, 2022
678f725
- fix mistake in equation
martinptm Dec 22, 2022
873d77e
implemented network delays for fhn, hopf, wc/ added tests for all thr…
lenasal Jan 12, 2023
17b043f
update notebooks, fixed typo in oc.py
lenasal Jan 12, 2023
77491c5
removed commented debug code
lenasal Jan 12, 2023
41e7c79
Merge branch 'master' into OCdev
lenasal Feb 1, 2023
0543c8a
removed file accidentially imported from other branch
lenasal Feb 1, 2023
bf1676b
Revert "removed file accidentially imported from other branch"
lenasal Feb 1, 2023
9b68c1a
Merge branch 'improve_docs' into OCdev
lenasal Feb 2, 2023
2d61d5c
- add comments
martinptm Feb 3, 2023
2535475
merge OCdev into nw delay branch
lenasal Feb 6, 2023
7aff8e9
corrected small mistake in delay test
lenasal Feb 6, 2023
f87fb64
delay test cases
lenasal Feb 6, 2023
e2cef1e
cleaned branch, remove files from experiments
lenasal Feb 6, 2023
36974ce
- restructure project
martinptm Feb 7, 2023
9812581
- move example file
martinptm Feb 7, 2023
6802e4b
- adjust imports in example to new project structure
martinptm Feb 7, 2023
6a482e6
corrected failing test
lenasal Feb 7, 2023
6a939ef
corrected failing test
lenasal Feb 7, 2023
87330fc
- move the calculation of Jacobian matrices to neurolib core modules …
martinptm Feb 7, 2023
1f25a9a
- create subfolders for oc-tests and -examples and adjust naming
martinptm Feb 8, 2023
80227c4
fixed issue in step size reduction
lenasal Feb 13, 2023
687d10a
fixed issue in step size reduction
lenasal Feb 13, 2023
7b5a722
- restore documentation-updates:
martinptm Feb 22, 2023
7fd4980
fixed bug in time delay
lenasal Mar 10, 2023
1d2e461
delete check zero in cmat/ run model once at initilaization/ revise e…
lenasal Mar 10, 2023
8b32959
revise test files
lenasal Mar 13, 2023
1f1be3a
correct typo in jacobian
lenasal Mar 13, 2023
e8a1dd0
correct typo in jacobian
lenasal Mar 13, 2023
b91e2cd
Merge remote-tracking branch 'origin/OCdev' into OCdev
martinptm Mar 14, 2023
31475bb
Merge branch 'proj_restructure_bugfixes' into OCdev
martinptm Mar 15, 2023
faa6c16
Merge branch 'restore_improved_docs' into OCdev
martinptm Mar 17, 2023
9a852c9
cost functional restructure
lenasal Apr 13, 2023
61718f0
update test wc
lenasal Apr 17, 2023
ce82e15
update test wc
lenasal Apr 17, 2023
087a4da
update test wc
lenasal Apr 17, 2023
4a1a033
update test wc
lenasal Apr 17, 2023
6c64546
changed chdir in control examples
lenasal Apr 17, 2023
56629bf
revision
lenasal Apr 18, 2023
f36a9c7
added test for weights dictionary
lenasal Apr 18, 2023
de5555f
Merge remote-tracking branch 'origin/cost_functionals_as_dict' into O…
martinptm Apr 18, 2023
3229b40
Update README.md
lenasal Apr 20, 2023
e979422
Update README.md
lenasal Apr 20, 2023
224cdbb
Update README.md
lenasal Apr 20, 2023
58aba52
Delete CONTRIBUTING.md
lenasal Apr 20, 2023
4c13b11
Delete README.md
lenasal Apr 20, 2023
8174405
start implementation oc aln
lenasal Apr 24, 2023
efba13b
implemeted bug fixes: aln delayed exc feedback, wc noise, wc&fhn&hopf…
lenasal Apr 24, 2023
66016c9
merge
lenasal Apr 24, 2023
b99e363
time seires variables
lenasal Apr 24, 2023
173cbd9
fixed bug in aln implementation
lenasal Apr 24, 2023
a1aa476
merge
lenasal Apr 24, 2023
1966231
time dependent variables
lenasal Apr 24, 2023
f07cbaf
fixed mistake
lenasal Apr 24, 2023
d067488
Merge branch 'aln_wc_bugfix' into aln
lenasal Apr 24, 2023
8bc6488
Update README.md
lenasal Apr 24, 2023
b98fa08
Update README.md
lenasal Apr 24, 2023
b790043
time dependend variables and init
lenasal Apr 24, 2023
ae6df20
notebook description
lenasal Apr 24, 2023
60b3e33
Merge branch 'readme_update' into OCdev
lenasal Apr 24, 2023
0be0109
Merge branch 'OCdev' into aln
lenasal Apr 24, 2023
75e0eb9
implementation
lenasal Apr 24, 2023
e6981d7
aln implementation
lenasal Apr 24, 2023
f307df2
added gradient as self.gradient
lenasal Apr 24, 2023
3874589
Merge branch 'OCdev' into aln
lenasal Apr 24, 2023
c78e312
aln imp
lenasal Apr 24, 2023
2b71c5d
implementation without params.Dmat_ndt
lenasal Apr 24, 2023
3257f04
merge
lenasal Apr 24, 2023
cce0d9e
functioning implementation except for sigmas, adaptation
lenasal Apr 27, 2023
6623270
functioning implementation except for sigmas, adaptation
lenasal Apr 27, 2023
4caa519
sigma implementation, IA missing
lenasal Apr 27, 2023
b8141c3
apparently works with adaptation
lenasal Apr 28, 2023
26ba056
minimal version of adaptation control
lenasal Apr 28, 2023
6e9f8aa
finish aln implementation including adaptation current
lenasal May 2, 2023
89b181d
finish aln implementation including adaptation current
lenasal May 2, 2023
82bca36
refactoring
lenasal May 2, 2023
e6b28b1
Merge branch 'master' into OCdev
lenasal May 2, 2023
bf401ef
Merge branch 'OCdev' into aln
lenasal May 2, 2023
8b8dbbb
merge neurolib updates
lenasal May 2, 2023
118e5cf
network implementation
lenasal May 3, 2023
8afed0f
finalize(?) aln
lenasal May 5, 2023
bd4c497
remove files
lenasal May 5, 2023
fb04a94
refactor implementation and finish example notebook
lenasal May 8, 2023
f68c2e5
finalize tests
lenasal May 8, 2023
8a3dc40
replace Vmean with analytical function
lenasal May 9, 2023
695df42
finish test cases
lenasal May 9, 2023
f131eea
finalize aln implmentation
lenasal May 12, 2023
2a80ddc
added Dxdoth in hopf and fhn
lenasal May 12, 2023
60dfe60
adjust fhn, hopf, wc model_params as in aln
lenasal May 12, 2023
2ae390e
pass N, V, T for iterations
lenasal May 12, 2023
72c40b8
refactor compute_gradient function
lenasal May 12, 2023
f95c2b3
update comments
lenasal May 12, 2023
ae57e74
fix bug in network input aln
lenasal May 12, 2023
4407038
revise example notebooks
lenasal May 12, 2023
7f27a3d
initialize. for implementation, wait for aln
lenasal May 16, 2023
3fcd573
Merge branch 'neurolib-dev:master' into OCdev
lenasal Jul 13, 2023
cb79678
Merge branch 'neurolib-dev:master' into OCdev
lenasal Jul 13, 2023
d781eb1
merge aln into OCdev
lenasal Aug 2, 2023
7a26884
merging
lenasal Aug 2, 2023
f046606
cleaned up repository
lenasal Aug 2, 2023
936057d
clean up
lenasal Aug 2, 2023
ff36942
Delete workflow.txt
lenasal Aug 2, 2023
fd0c01e
move zero_ste_encountered in deterministic computation
lenasal Aug 2, 2023
9c39319
Merge branch 'OCdev' of github.com:lenasal/neurolib into OCdev
lenasal Aug 2, 2023
e53866c
Merge branch 'OCdev' into control_interval
lenasal Aug 2, 2023
3a0729c
implemented cost interval and added test
lenasal Aug 2, 2023
fca3312
Merge branch 'neurolib-dev:master' into OCdev
lenasal Aug 2, 2023
a2863fe
checkout files from master
lenasal Aug 28, 2023
990c45e
fixed solve_adjoint
lenasal Aug 30, 2023
618d88b
differentiate static and time-dependent inputs
lenasal Aug 30, 2023
ceedfae
update example
lenasal Aug 30, 2023
e8a3a96
revert example change
lenasal Aug 30, 2023
6cae278
Merge branch 'neurolib-dev:master' into master
lenasal Aug 30, 2023
fd0c814
mergw wc time integration
lenasal Aug 30, 2023
d6e4bbd
update wc for baseline and dynamical inputs
lenasal Aug 30, 2023
351ed33
revise test wc
lenasal Aug 31, 2023
0fb1a71
revise test wc
lenasal Aug 31, 2023
752ffdc
revised cost functional tests
lenasal Aug 31, 2023
5d42a86
revised remaining test files
lenasal Aug 31, 2023
aa7ce1f
moved get_xs, get_xs_delay and update_input to oc.py
lenasal Sep 1, 2023
602be41
refactoring tests
lenasal Sep 4, 2023
7cd6e32
state vars as dict
lenasal Sep 5, 2023
02f1b26
remove test notebook
lenasal Sep 5, 2023
1ae3e1b
update aln model with correct input_vars
lenasal Sep 5, 2023
76e433f
merging
lenasal Sep 5, 2023
cd8c975
merging
lenasal Sep 5, 2023
c0fcdea
finish test revision
lenasal Sep 5, 2023
34438b3
indexing in time_integration file via dictionary in all models
lenasal Sep 6, 2023
fa536d5
remove comments
lenasal Sep 6, 2023
bced3fc
add adjust shape method for inputs, refactoring
lenasal Sep 7, 2023
208729d
Merge branch 'neurolib-dev:master' into master
lenasal Sep 7, 2023
5a65c2c
Merge branch 'neurolib-dev:master' into OCdev
lenasal Sep 7, 2023
f244de4
moved example files to main folder
lenasal Sep 7, 2023
d7b596b
refactor aln oc test
lenasal Sep 7, 2023
1a20eb9
refactor etst cases
lenasal Sep 7, 2023
084d258
remove unnecessary parameter
lenasal Sep 7, 2023
43c57d1
solve_adjoint revision, WC notebook
lenasal Sep 8, 2023
84539f1
refactor tests
lenasal Sep 8, 2023
8013141
Merge branch 'neurolib-dev:master' into master
lenasal Sep 11, 2023
07a63af
Merge branch 'neurolib-dev:master' into OCdev
lenasal Sep 11, 2023
9d38e0b
Update timeIntegration.py
lenasal Sep 11, 2023
b21b201
Update plot_oc.py
lenasal Sep 11, 2023
38cf5c4
Merge pull request #2 from lenasal/lenasal-patch-1
lenasal Sep 11, 2023
7a8f06e
shorten example runtime
lenasal Sep 12, 2023
0fc6cc1
Merge branch 'master' into OCdev
lenasal Sep 14, 2023
03c9bca
Delete examples/example-5.6-oc-aln-model-noisy.ipynb
lenasal Sep 19, 2023
602f33d
Delete examples/example-5.2-oc-phenomenological-model-noisy.ipynb
lenasal Sep 19, 2023
7ca319a
Update plot_oc.py
lenasal Sep 20, 2023
6b1c364
Update cost_functions.py
lenasal Sep 20, 2023
588ad9c
added test for solve_adjoint
lenasal Sep 20, 2023
ab23f58
Update test_oc.py
lenasal Sep 22, 2023
596eb2d
Update oc.py
lenasal Sep 25, 2023
e4c55bb
Update oc.py
lenasal Sep 26, 2023
a947708
fix bug in WC jacobian
lenasal Dec 11, 2023
e688bfd
Rename example-5.3-oc-wc-model-deterministic.ipynb to example-5.2-oc-…
lenasal Dec 15, 2023
ab586ad
Rename example-5.4-oc-wc-model-noisy.ipynb to example-5.3-oc-wc-model…
lenasal Dec 15, 2023
b8969be
Rename example-5.5-oc-aln-model-deterministic.ipynb to example-5.4-oc…
lenasal Dec 15, 2023
af1d1d2
Update README.md
lenasal Dec 15, 2023
a48fed0
Update README.md
lenasal Dec 15, 2023
8a633e4
Update README.md
lenasal Dec 15, 2023
1eba12c
Update README.md
lenasal Dec 20, 2023
f7e2d28
Merge branch 'OCdev' of github.com:lenasal/neurolib into OCdev
lenasal Dec 20, 2023
e44d911
move plot_oc to neurolib.utils
lenasal Dec 20, 2023
9f0c69d
restore plot_oc.py in correct form
lenasal Dec 20, 2023
25d1a2c
Merge branch 'neurolib-dev:master' into OCdev
lenasal Dec 21, 2023
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
34 changes: 33 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -95,6 +95,10 @@ neurolib/ # Main module
├── optimize/ # Optimization submodule
├── evolution/ # Evolutionary optimization
└── exploration/ # Parameter exploration
├── control/optimal_control/ # (Optimal) control submodule
lenasal marked this conversation as resolved.
Show resolved Hide resolved
├── oc.py # Optimal control base class
├── cost_functions.py # cost functions for OC
├── /.../ # Implemented OC models
├── data/ # Empirical datasets (structural, functional)
├── utils/ # Utility belt
├── atlases.py # Atlases (Region names, coordinates)
Expand All @@ -120,6 +124,7 @@ Example [IPython Notebooks](examples/) on how to use the library can be found in
- [Example 0.6](https://mybinder.org/v2/gh/neurolib-dev/neurolib/master?filepath=examples%2Fexample-0.6-custom-model.ipynb) - Minimal example of how to implement your own model in `neurolib`
- [Example 1.2](https://mybinder.org/v2/gh/neurolib-dev/neurolib/master?filepath=examples%2Fexample-1.2-brain-network-exploration.ipynb) - Parameter exploration of a brain network and fitting to BOLD data
- [Example 2.0](https://mybinder.org/v2/gh/neurolib-dev/neurolib/master?filepath=examples%2Fexample-2-evolutionary-optimization-minimal.ipynb) - A simple example of the evolutionary optimization framework
- [Example 5.2](https://mybinder.org/v2/gh/neurolib-dev/neurolib/master?filepath=examples%2Fexample-5.2-oc-wc-model-deterministic.ipynb) - Example of optimal control of the noise-free Wilson-Cowan model

A basic overview of the functionality of `neurolib` is also given in the following.

Expand Down Expand Up @@ -282,6 +287,31 @@ This will gives us a summary of the last generation and plots a distribution of
<img src="https://github.com/neurolib-dev/neurolib/raw/master/resources/evolution_animated.gif">
</p>

### Optimal control
The optimal control module enables to compute efficient stimulation for your neural model. If you know how your output should look like, this module computes the optimal input. Detailes example notebooks can be found in the [example folder](https://github.com/neurolib-dev/neurolib/tree/master/examples) (examples 5.1, 5.2, 5.3, 5.4). In optimal control computations, you trade precision with respect to a target against control strength. You can determine how much each contribution affects the results, by setting weights accordingly.

To compute an optimal control signal, you need to create a model (e.g., an FHN model) and define a target state (e.g., a sine curve with period 2).
```python
from neurolib.models.fhn import FHNModel
model = FHNModel()

duration = 10.
model.params["duration"] = duration
dt = model.params["dt"]

period = 2.
target = np.sin(2. * np.pi * np.arange(0, duration+dt, dt) / period)
```
You can then create a controlled model and run the iterative optimization to find the most efficient control input. The optimal control and the controlled model activity can be taken from the controlled model.
```python
model_controlled = oc_fhn.OcFhn(model, target)
model_controlled.optimize(500) # run 500 iterations
optimal_control = model_controlled.control
optimal_state = model_controlled.get_xs()
```

For a comprehensive study on optimal control of the Wilson-Cowan model based on the neurolib optimal control module, see Salfenmoser, L. & Obermayer, K. Optimal control of a Wilson–Cowan model of neural population dynamics. Chaos 33, 043135 (2023). https://doi.org/10.1063/5.0144682.

## More information

### Built With
Expand Down Expand Up @@ -313,9 +343,11 @@ Cakan, C., Jajcay, N. & Obermayer, K. neurolib: A Simulation Framework for Whole

Caglar Cakan (cakan@ni.tu-berlin.de)
Department of Software Engineering and Theoretical Computer Science, Technische Universität Berlin, Germany
Bernstein Center for Computational Neuroscience Berlin, Germany
Bernstein Center for Computational Neuroscience Berlin, Germany

### Acknowledgments
This work was supported by the Deutsche Forschungsgemeinschaft (DFG, German Research Foundation) with the project number 327654276 (SFB 1315) and the Research Training Group GRK1589/2.

The optimal control module was developed by Lena Salfenmoser and Martin Krück supported by the DFG project 163436311 (SFB 910).

<!--end-include-in-documentation-->
708 changes: 708 additions & 0 deletions examples/example-5.1-oc-phenomenological-model-deterministic.ipynb

Large diffs are not rendered by default.

662 changes: 662 additions & 0 deletions examples/example-5.2-oc-wc-model-deterministic.ipynb

Large diffs are not rendered by default.

567 changes: 567 additions & 0 deletions examples/example-5.3-oc-wc-model-noisy.ipynb

Large diffs are not rendered by default.

859 changes: 859 additions & 0 deletions examples/example-5.4-oc-aln-model-deterministic.ipynb

Large diffs are not rendered by default.

Empty file added neurolib/control/__init__.py
Empty file.
Empty file.
210 changes: 210 additions & 0 deletions neurolib/control/optimal_control/cost_functions.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,210 @@
import numpy as np
import numba


@numba.njit
def accuracy_cost(x, target_timeseries, weights, cost_matrix, dt, interval=(0, None)):
"""Total cost related to the accuracy, weighted sum of contributions.

:param x: State of dynamical system.
:type x: np.ndarray
:param target_timeseries: Target state.
:type target_timeseries: np.darray
:param weights: Dictionary of weights.
:type weights: dictionary
:param cost_matrix: Matrix of channels to take into account
:type cost_matrix: ndarray
:param dt: Time step.
:type dt: float
:param interval: (t_start, t_end). Indices of start and end point of the slice (both inclusive) in time
dimension. Only 'int' positive index-notation allowed (i.e. no negative indices or 'None').
:type interval: tuple, optional

:return: Accuracy cost.
:rtype: float
"""

cost_timeseries = np.zeros((target_timeseries.shape))

# timeseries of control vector is weighted sum of contributing cost functionals
if weights["w_p"] != 0.0:
cost_timeseries += weights["w_p"] * precision_cost(x, target_timeseries, cost_matrix, interval)

cost = 0.0
# integrate over nodes, channels, and time
if weights["w_p"] != 0.0:
for n in range(x.shape[0]):
for v in range(x.shape[1]):
for t in range(interval[0], interval[1]):
cost += cost_timeseries[n, v, t] * dt

return cost


@numba.njit
def derivative_accuracy_cost(x, target_timeseries, weights, cost_matrix, interval=(0, None)):
"""Derivative of the 'accuracy_cost' wrt. the state 'x'.

:param x: State of dynamical system.
:type x: np.ndarray
:param target_timeseries: Target state.
:type target_timeseries: np.darray
:param weights: Dictionary of weights.
:type weights: dictionary
:param cost_matrix: Matrix of channels to take into account
:type cost_matrix: ndarray
:param interval: (t_start, t_end). Indices of start and end point of the slice (both inclusive) in time
dimension. Only 'int' positive index-notation allowed (i.e. no negative indices or 'None').
:type interval: tuple, optional

:return: Accuracy cost derivative.
:rtype: ndarray
"""

der = np.zeros((target_timeseries.shape))

if weights["w_p"] != 0.0:
der += weights["w_p"] * derivative_precision_cost(x, target_timeseries, cost_matrix, interval)

return der


@numba.njit
def precision_cost(x_sim, x_target, cost_matrix, interval=(0, None)):
"""Summed squared difference between target and simulation within specified time interval weighted by w_p.
Penalizes deviation from the target.

:param x_sim: N x V x T array that contains the simulated time series.
:type x_sim: np.ndarray
:param x_target: N x V x T array that contains the target time series.
:type x_target: np.ndarray
:param cost_matrix: N x V binary matrix that defines nodes and channels of precision measurement. Defaults to
None.
:type cost_matrix: np.ndarray
:param interval: (t_start, t_end). Indices of start and end point of the slice (both inclusive) in time
dimension. Only 'int' positive index-notation allowed (i.e. no negative indices or 'None').
:type interval: tuple

:return: Precision cost for time interval.
:rtype: float
"""

cost = np.zeros((x_target.shape))

# integrate over nodes, channels, and time
for n in range(x_target.shape[0]):
for v in range(x_target.shape[1]):
for t in range(interval[0], interval[1]):
cost[n, v, t] = 0.5 * cost_matrix[n, v] * (x_target[n, v, t] - x_sim[n, v, t]) ** 2

return cost


@numba.njit
def derivative_precision_cost(x_sim, x_target, cost_matrix, interval):
"""Derivative of 'precision_cost' wrt. 'x_sim'.

:param x_sim: N x V x T array that contains the simulated time series.
:type x_sim: np.ndarray
:param x_target: N x V x T array that contains the target time series.
:type x_target: np.ndarray
:param cost_matrix: N x V binary matrix that defines nodes and channels of precision measurement, defaults to
None
:type cost_matrix: np.ndarray
:param interval: (t_start, t_end). Indices of start and end point of the slice (both inclusive) in time
dimension. Only 'int' positive index-notation allowed (i.e. no negative indices or 'None').
:type interval: tuple

:return: Control-dimensions x T array of precision cost gradients.
:rtype: np.ndarray
"""

derivative = np.zeros(x_target.shape)

# integrate over nodes, variables, and time
for n in range(x_target.shape[0]):
for v in range(x_target.shape[1]):
for t in range(interval[0], interval[1]):
derivative[n, v, t] = -cost_matrix[n, v] * (x_target[n, v, t] - x_sim[n, v, t])

return derivative


@numba.njit
def control_strength_cost(u, weights, dt):
"""Total cost related to the control strength, weighted sum of contributions.

:param u: Control-dimensions x T array. Control signals.
:type u: np.ndarray
:param weights: Dictionary of weights.
:type weights: dictionary
:param dt: Time step.
:type dt: float

:return: control strength cost of the control.
:rtype: float
"""

cost_timeseries = np.zeros((u.shape))

# timeseries of control vector is weighted sum of contributing cost functionals
if weights["w_2"] != 0.0:
cost_timeseries += weights["w_2"] * L2_cost(u)

cost = 0.0
# integrate over nodes, channels, and time
if weights["w_2"] != 0.0:
for n in range(u.shape[0]):
for v in range(u.shape[1]):
for t in range(u.shape[2]):
cost += cost_timeseries[n, v, t] * dt

return cost


@numba.njit
def derivative_control_strength_cost(u, weights):
"""Derivative of the 'control_strength_cost' wrt. the control 'u'.

:param u: Control-dimensions x T array. Control signals.
:type u: np.ndarray
:param weights: Dictionary of weights.
:type weights: dictionary

:return: Control-dimensions x T array of L2-cost gradients.
:rtype: np.ndarray
"""

der = np.zeros((u.shape))

if weights["w_2"] != 0.0:
der += weights["w_2"] * derivative_L2_cost(u)

return der


@numba.njit
def L2_cost(u):
"""'Energy' or 'L2' cost. Penalizes for control strength.

:param u: Control-dimensions x T array. Control signals.
:type u: np.ndarray

:return: L2 cost of the control.
:rtype: float
"""

return 0.5 * u**2.0


@numba.njit
def derivative_L2_cost(u):
"""Derivative of the 'L2_cost' wrt. the control 'u'.

:param u: Control-dimensions x T array. Control signals.
:type u: np.ndarray

:return: Control-dimensions x T array of L2-cost gradients.
:rtype: np.ndarray
"""
return u