circulation 0.1.0__tar.gz

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.
@@ -0,0 +1,7 @@
1
+ Copyright 2024 Henrik Finsberg
2
+
3
+ Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
4
+
5
+ The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
6
+
7
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
@@ -0,0 +1,43 @@
1
+ Metadata-Version: 2.1
2
+ Name: circulation
3
+ Version: 0.1.0
4
+ Summary: Closed loop blood circulation model in FEniCS
5
+ Author-email: Henrik Finsberg <henriknf@simula.no>
6
+ License: Copyright 2024 Henrik Finsberg
7
+
8
+ Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
9
+
10
+ The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
11
+
12
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
13
+
14
+ Description-Content-Type: text/markdown
15
+ License-File: LICENSE
16
+ Requires-Dist: numpy
17
+ Requires-Dist: pint
18
+ Requires-Dist: rich
19
+ Provides-Extra: test
20
+ Requires-Dist: pytest; extra == "test"
21
+ Requires-Dist: pytest-cov; extra == "test"
22
+ Provides-Extra: demos
23
+ Requires-Dist: matplotlib; extra == "demos"
24
+ Provides-Extra: docs
25
+ Requires-Dist: jupyter-book; extra == "docs"
26
+ Requires-Dist: jupytext; extra == "docs"
27
+ Requires-Dist: circulation[demos]; extra == "docs"
28
+ Provides-Extra: all
29
+ Requires-Dist: circulation[test]; extra == "all"
30
+ Requires-Dist: circulation[plot]; extra == "all"
31
+ Requires-Dist: circulation[docs]; extra == "all"
32
+ Requires-Dist: circulation[dev]; extra == "all"
33
+
34
+ # Cardiac circulation models
35
+
36
+ TBW
37
+
38
+
39
+ ## Install
40
+
41
+ ```
42
+ python -m pip install circulation
43
+ ```
@@ -0,0 +1,10 @@
1
+ # Cardiac circulation models
2
+
3
+ TBW
4
+
5
+
6
+ ## Install
7
+
8
+ ```
9
+ python -m pip install circulation
10
+ ```
@@ -0,0 +1,118 @@
1
+ [build-system] # Require setuptool version due to https://github.com/pypa/setuptools/issues/2938
2
+ requires = ["setuptools>=61.0.0", "wheel"]
3
+
4
+ [project]
5
+ name = "circulation"
6
+ version = "0.1.0"
7
+ description = "Closed loop blood circulation model in FEniCS"
8
+ authors = [{ name = "Henrik Finsberg", email = "henriknf@simula.no" }]
9
+ license = { file = "LICENSE" }
10
+ readme = "README.md"
11
+ dependencies = [
12
+ "numpy",
13
+ "pint",
14
+ "rich"
15
+ ]
16
+
17
+
18
+ [project.optional-dependencies]
19
+ test = ["pytest", "pytest-cov"]
20
+ demos = ["matplotlib"]
21
+ docs = ["jupyter-book", "jupytext", "circulation[demos]"]
22
+ all = [
23
+ "circulation[test]",
24
+ "circulation[plot]",
25
+ "circulation[docs]",
26
+ "circulation[dev]",
27
+ ]
28
+
29
+ [tool.setuptools.packages.find]
30
+ where = ["src"]
31
+
32
+
33
+ [tool.pytest.ini_options]
34
+ addopts = [
35
+ "--cov=circulation",
36
+ "--cov-report=html",
37
+ "--cov-report=term-missing",
38
+ "-v",
39
+ ]
40
+
41
+ testpaths = ["tests"]
42
+
43
+ [tool.mypy]
44
+ files = ["src/circulation", "tests"]
45
+ ignore_missing_imports = true
46
+ exclude = [
47
+ "docs",
48
+ "examples",
49
+ ]
50
+
51
+
52
+
53
+ [tool.ruff]
54
+
55
+ # Exclude a variety of commonly ignored directories.
56
+ exclude = [
57
+ "examples",
58
+ ".bzr",
59
+ ".direnv",
60
+ ".eggs",
61
+ ".git",
62
+ ".hg",
63
+ ".mypy_cache",
64
+ ".nox",
65
+ ".pants.d",
66
+ ".pytype",
67
+ ".ruff_cache",
68
+ ".svn",
69
+ ".tox",
70
+ ".venv",
71
+ "__pypackages__",
72
+ "_build",
73
+ "buck-out",
74
+ "build",
75
+ "dist",
76
+ "node_modules",
77
+ "venv",
78
+ ]
79
+
80
+ # Same as Black.
81
+ line-length = 100
82
+
83
+ # Assume Python 3.10.
84
+ target-version = "py310"
85
+
86
+ [tool.ruff.lint]
87
+ # Enable pycodestyle (`E`) and Pyflakes (`F`) codes by default.
88
+ select = ["E", "F"]
89
+ ignore = ["E402", "E741", "E743", "E731"]
90
+
91
+ # Allow autofix for all enabled rules (when `--fix`) is provided.
92
+ fixable = ["A", "B", "C", "D", "E", "F"]
93
+ unfixable = []
94
+
95
+ # Allow unused variables when underscore-prefixed.
96
+ dummy-variable-rgx = "^(_+|(_+[a-zA-Z0-9_]*[a-zA-Z0-9]+?))$"
97
+
98
+
99
+ [tool.ruff.lint.mccabe]
100
+ # Unlike Flake8, default to a complexity level of 10.
101
+ max-complexity = 10
102
+
103
+
104
+ [tool.bumpversion]
105
+ allow_dirty = false
106
+ commit = true
107
+ message = "Bump version: {current_version} → {new_version}"
108
+ tag = true
109
+ sign_tags = false
110
+ tag_name = "v{new_version}"
111
+ tag_message = "Bump version: {current_version} → {new_version}"
112
+ current_version = "1.1.2"
113
+
114
+
115
+ [[tool.bumpversion.files]]
116
+ filename = "pyproject.toml"
117
+ search = 'version = "{current_version}"'
118
+ replace = 'version = "{new_version}"'
@@ -0,0 +1,4 @@
1
+ [egg_info]
2
+ tag_build =
3
+ tag_date = 0
4
+
@@ -0,0 +1,3 @@
1
+ from . import base, log, regazzoni2020, zenkur, units, time_varying_elastance
2
+
3
+ __all__ = ["base", "log", "regazzoni2020", "zenkur", "units", "time_varying_elastance"]
@@ -0,0 +1,208 @@
1
+ from __future__ import annotations
2
+ from typing import Callable, Any
3
+ from abc import ABC, abstractmethod
4
+ import json
5
+ from collections import defaultdict
6
+ import numpy as np
7
+ import time
8
+ import logging
9
+ from rich.table import Table
10
+
11
+ from . import units
12
+ from . import time_varying_elastance
13
+ from . import log
14
+
15
+
16
+ logger = logging.getLogger(__name__)
17
+
18
+
19
+ def smooth_heavyside(x):
20
+ return np.arctan(np.pi / 2 * x * 200) * 1 / np.pi + 0.5
21
+
22
+
23
+ def remove_units(parameters: dict[str, Any]) -> dict[str, Any]:
24
+ d = {}
25
+ for k, v in parameters.items():
26
+ if isinstance(v, units.pint.Quantity):
27
+ d[k] = v.magnitude
28
+ elif isinstance(v, dict):
29
+ d[k] = remove_units(v)
30
+ else:
31
+ d[k] = v
32
+ return d
33
+
34
+
35
+ class CirculationModel(ABC):
36
+ def __init__(
37
+ self,
38
+ parameters: dict[str, Any] | None = None,
39
+ add_units: bool = False,
40
+ callback: Callable[[float], None] | None = None,
41
+ verbose: bool = False,
42
+ ):
43
+ self.parameters = type(self).default_parameters()
44
+ if parameters is not None:
45
+ self.parameters.update(parameters)
46
+ if not add_units:
47
+ self.parameters = remove_units(self.parameters)
48
+ self._add_units = add_units
49
+
50
+ if callback is not None:
51
+ assert callable(callback), "callback must be callable"
52
+
53
+ self.callback = callback
54
+ else:
55
+ self.callback = lambda t: None
56
+ self._verbose = verbose
57
+
58
+ def _initialize(self):
59
+ self.var = {}
60
+ self.state = type(self).default_initial_conditions()
61
+ self.update_state()
62
+ self.update_static_variables(0.0)
63
+
64
+ @property
65
+ def THB(self):
66
+ if self._add_units:
67
+ return (1 / self.parameters["BPM"]).to(units.ureg("s"))
68
+
69
+ return 60.0 / self.parameters["BPM"]
70
+
71
+ @staticmethod
72
+ @abstractmethod
73
+ def default_parameters() -> dict[str, Any]: ...
74
+
75
+ @abstractmethod
76
+ def update_static_variables(self, t: float):
77
+ pass
78
+
79
+ def update_state(self, state: dict[str, float] | None = None):
80
+ if state is not None:
81
+ self.state.update(state)
82
+
83
+ if not self._add_units:
84
+ self.state = remove_units(self.state)
85
+
86
+ @staticmethod
87
+ @abstractmethod
88
+ def default_initial_conditions() -> dict[str, float]: ...
89
+
90
+ def time_varying_elastance(self, EA, EB, tC, TC, TR, **kwargs):
91
+ return time_varying_elastance.blanco_ventricle(
92
+ EA=EA,
93
+ EB=EB,
94
+ tC=tC,
95
+ TC=TC,
96
+ TR=TR,
97
+ THB=self.THB,
98
+ )
99
+
100
+ def flux_through_valve(self, p1, p2, R):
101
+ return (p1 - p2) / R(p1, p2)
102
+
103
+ def _R(
104
+ self,
105
+ Rmin: float,
106
+ Rmax: float,
107
+ unit_R: float = 1.0,
108
+ unit_p: float = 1.0,
109
+ ) -> Callable[[float, float], float]:
110
+ return lambda w, v: unit_R * 10.0 ** (
111
+ np.log10(Rmin / unit_R)
112
+ + (np.log10(Rmax / unit_R) - np.log10(Rmin / unit_R))
113
+ * smooth_heavyside((v - w) / unit_p)
114
+ )
115
+
116
+ @abstractmethod
117
+ def step(self, t: float, dt: float) -> None: ...
118
+
119
+ def solve(
120
+ self,
121
+ T: float | None = None,
122
+ num_cycles: int | None = None,
123
+ initial_state: dict[str, float] | None = None,
124
+ dt: float = 1e-3,
125
+ dt_eval: float | None = None,
126
+ ):
127
+ logger.info("Running circulation model")
128
+ if T is None:
129
+ assert num_cycles is not None, "Please provide num_cycles or T"
130
+ T = self.THB * num_cycles
131
+
132
+ initial_state = initial_state or dict()
133
+
134
+ if dt_eval is None:
135
+ output_every_n_steps = 1
136
+ else:
137
+ output_every_n_steps = np.round(dt_eval / dt)
138
+
139
+ self.update_state(state=initial_state)
140
+ self.initialize_output()
141
+ t = 0.0
142
+ if self._add_units:
143
+ t *= units.ureg("s")
144
+ dt *= units.ureg("s")
145
+
146
+ self.store(t)
147
+
148
+ time_start = time.time()
149
+
150
+ i = 0
151
+ while t < T:
152
+ self.callback(t)
153
+ self.step(t, dt)
154
+ if i % output_every_n_steps == 0:
155
+ self.store(t)
156
+ if self._verbose:
157
+ self.print_info()
158
+ t += dt
159
+ i += 1
160
+
161
+ duration = time.time() - time_start
162
+
163
+ logger.info("Done running circulation model in elapsed time %1.4f s" % duration)
164
+ return self.results
165
+
166
+ def initialize_output(self):
167
+ self.results = defaultdict(list)
168
+
169
+ def store(self, t):
170
+ get = lambda x: x if not self._add_units else x.magnitude
171
+
172
+ self.results["time"].append(get(t))
173
+ for k, v in self.state.items():
174
+ self.results[k].append(get(v))
175
+ for k, v in self.var.items():
176
+ self.results[k].append(get(v))
177
+
178
+ def save_state(self, filename):
179
+ with open(filename, mode="w", newline="") as outfile:
180
+ json.dump(self.state, outfile, indent=2)
181
+
182
+ @property
183
+ def volumes(self) -> dict[str, float]:
184
+ return {}
185
+
186
+ @property
187
+ def pressures(self) -> dict[str, float]:
188
+ return {}
189
+
190
+ @property
191
+ def flows(self) -> dict[str, float]:
192
+ return {}
193
+
194
+ def print_info(self):
195
+ msg = []
196
+ for attr, title in [
197
+ (self.volumes, "Volumes"),
198
+ (self.pressures, "Pressures"),
199
+ (self.flows, "Flows"),
200
+ ]:
201
+ table = Table(title=title)
202
+ row = []
203
+ for k, v in attr.items():
204
+ table.add_column(k)
205
+ row.append(f"{v:.3f}")
206
+ table.add_row(*row)
207
+ msg.append(f"\n{log.log_table(table)}")
208
+ logger.info("".join(msg))
@@ -0,0 +1,24 @@
1
+ import logging
2
+ from rich.logging import RichHandler
3
+ from rich.console import Console
4
+ from rich.text import Text
5
+
6
+
7
+ def log_table(rich_table):
8
+ """Generate an ascii formatted presentation of a Rich table
9
+ Eliminates any column styling
10
+ """
11
+ console = Console(width=150)
12
+ with console.capture() as capture:
13
+ console.print(rich_table)
14
+ return Text.from_ansi(capture.get())
15
+
16
+
17
+ def setup_logging(level=logging.DEBUG, comm=None):
18
+ handlers = [RichHandler(console=Console(width=200))]
19
+ if comm is not None:
20
+ handlers[0].addFilter(lambda record: 1 if comm.rank == 0 else 0)
21
+ logging.basicConfig(
22
+ level=level,
23
+ handlers=handlers,
24
+ )
@@ -0,0 +1,115 @@
1
+ import numpy as np
2
+ import json
3
+ import time
4
+ from collections import defaultdict
5
+ # from scipy.integrate import RK45, solve_ivp
6
+
7
+
8
+ from . import base
9
+ from . import units
10
+
11
+ mL = units.ureg("mL")
12
+ mmHg = units.ureg("mmHg")
13
+ s = units.ureg("s")
14
+
15
+
16
+ class LVOnly(base.CirculationModel):
17
+ """
18
+ 0D model of the left ventricle only.
19
+
20
+ """
21
+
22
+ def __init__(self, parameters: dict[str, float] | None = None, add_units=False):
23
+ super().__init__(parameters, add_units=add_units)
24
+
25
+ ############ Chambers
26
+ chambers = self.parameters["chambers"]
27
+
28
+ self.E_LV = self.time_varying_elastance(**chambers["LV"])
29
+ self.p_LV_func = lambda V, t: self.E_LV(t) * (V - chambers["LV"]["V0"])
30
+ self.var = {}
31
+
32
+ @staticmethod
33
+ def default_parameters() -> base.CirculcationModelParams:
34
+ return {
35
+ "BPM": 75.0 * units.ureg("1/minutes"),
36
+ "chambers": {
37
+ "LV": {
38
+ "EA": 2.75 * mmHg / mL,
39
+ "EB": 0.008 * mmHg / mL,
40
+ "TC": 0.34 * s,
41
+ "TR": 0.17 * s,
42
+ "tC": 0.00 * s,
43
+ "V0": -9.0 * mL,
44
+ },
45
+ },
46
+ "circulation": {
47
+ "SYS": {
48
+ "Rao": 0.5 * mmHg * s / mL,
49
+ "R_sys": 2.5 * mmHg * s / mL,
50
+ "p_dia": 10.0 * mmHg,
51
+ "C_sys": 0.1 * mL / mmHg,
52
+ "Pp": 4.5 * mmHg,
53
+ },
54
+ },
55
+ }
56
+
57
+ @staticmethod
58
+ def default_initial_conditions() -> dict[str, float]:
59
+ return {
60
+ "V_LV": 100.0 * mL,
61
+ "p_ao": 70.0 * mmHg,
62
+ "dp_ao_dt": 0.0 * mmHg / s,
63
+ }
64
+
65
+ def update_static_variables(self, t):
66
+ self.var["p_LV"] = self.p_LV_func(self.state["V_LV"], t)
67
+
68
+ def step(self, t, dt):
69
+ self.update_static_variables(t)
70
+
71
+ p_ao = self.state["p_ao"]
72
+ dp_ao_dt = self.state["dp_ao_dt"]
73
+ p_LV = self.var["p_LV"]
74
+
75
+ C_sys = self.parameters["circulation"]["SYS"]["C_sys"]
76
+ R_ao = self.parameters["circulation"]["SYS"]["Rao"]
77
+ R_sys = self.parameters["circulation"]["SYS"]["R_sys"]
78
+ p_dia = self.parameters["circulation"]["SYS"]["p_dia"]
79
+
80
+ Q = (p_LV - p_ao) / R_ao
81
+ Q_R = (p_ao - p_dia) / R_sys
82
+ Q_C = C_sys * dp_ao_dt
83
+
84
+ dQ_C_dt = (Q - Q_R - Q_C) / C_sys
85
+ d2p_ao_dt2 = dQ_C_dt
86
+
87
+ self.state["p_ao"] += dt * dp_ao_dt
88
+ self.state["dp_ao_dt"] += dt * d2p_ao_dt2
89
+ if p_LV > p_ao:
90
+ self.state["V_LV"] += -dt * Q
91
+
92
+ def print_info(self):
93
+ C_VEN_SYS = self.parameters["circulation"]["SYS"]["C_VEN"]
94
+ C_AR_SYS = self.parameters["circulation"]["SYS"]["C_AR"]
95
+
96
+ print("V_LV = %4.2f mL" % self.state["V_LV"])
97
+ print("V_AR_SYS = %4.2f mL" % (C_AR_SYS * self.state["p_AR_SYS"]))
98
+ print("V_VEN_SYS = %4.2f mL" % (C_VEN_SYS * self.state["p_VEN_SYS"]))
99
+
100
+ V_tot_heart = (
101
+ self.state["V_LA"]
102
+ + self.state["V_LV"]
103
+ + self.state["V_RA"]
104
+ + self.state["V_RV"]
105
+ )
106
+ V_tot_SYS = (
107
+ C_AR_SYS * self.state["p_AR_SYS"] + C_VEN_SYS * self.state["p_VEN_SYS"]
108
+ )
109
+
110
+ V_tot = V_tot_heart + V_tot_SYS
111
+ print("======================")
112
+ print("V (heart) = %4.2f mL" % V_tot_heart)
113
+ print("V (SYS) = %4.2f mL" % V_tot_SYS)
114
+ print("======================")
115
+ print("V = %4.2f mL" % V_tot)