mxlpy 0.8.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 (48) hide show
  1. mxlpy/__init__.py +165 -0
  2. mxlpy/distributions.py +339 -0
  3. mxlpy/experimental/__init__.py +12 -0
  4. mxlpy/experimental/diff.py +226 -0
  5. mxlpy/fit.py +291 -0
  6. mxlpy/fns.py +191 -0
  7. mxlpy/integrators/__init__.py +19 -0
  8. mxlpy/integrators/int_assimulo.py +146 -0
  9. mxlpy/integrators/int_scipy.py +146 -0
  10. mxlpy/label_map.py +610 -0
  11. mxlpy/linear_label_map.py +303 -0
  12. mxlpy/mc.py +548 -0
  13. mxlpy/mca.py +280 -0
  14. mxlpy/meta/__init__.py +11 -0
  15. mxlpy/meta/codegen_latex.py +516 -0
  16. mxlpy/meta/codegen_modebase.py +110 -0
  17. mxlpy/meta/codegen_py.py +107 -0
  18. mxlpy/meta/source_tools.py +320 -0
  19. mxlpy/model.py +1737 -0
  20. mxlpy/nn/__init__.py +10 -0
  21. mxlpy/nn/_tensorflow.py +0 -0
  22. mxlpy/nn/_torch.py +129 -0
  23. mxlpy/npe.py +277 -0
  24. mxlpy/parallel.py +171 -0
  25. mxlpy/parameterise.py +27 -0
  26. mxlpy/paths.py +36 -0
  27. mxlpy/plot.py +875 -0
  28. mxlpy/py.typed +0 -0
  29. mxlpy/sbml/__init__.py +14 -0
  30. mxlpy/sbml/_data.py +77 -0
  31. mxlpy/sbml/_export.py +644 -0
  32. mxlpy/sbml/_import.py +599 -0
  33. mxlpy/sbml/_mathml.py +691 -0
  34. mxlpy/sbml/_name_conversion.py +52 -0
  35. mxlpy/sbml/_unit_conversion.py +74 -0
  36. mxlpy/scan.py +629 -0
  37. mxlpy/simulator.py +655 -0
  38. mxlpy/surrogates/__init__.py +31 -0
  39. mxlpy/surrogates/_poly.py +97 -0
  40. mxlpy/surrogates/_torch.py +196 -0
  41. mxlpy/symbolic/__init__.py +10 -0
  42. mxlpy/symbolic/strikepy.py +582 -0
  43. mxlpy/symbolic/symbolic_model.py +75 -0
  44. mxlpy/types.py +474 -0
  45. mxlpy-0.8.0.dist-info/METADATA +106 -0
  46. mxlpy-0.8.0.dist-info/RECORD +48 -0
  47. mxlpy-0.8.0.dist-info/WHEEL +4 -0
  48. mxlpy-0.8.0.dist-info/licenses/LICENSE +674 -0
mxlpy/nn/__init__.py ADDED
@@ -0,0 +1,10 @@
1
+ """Collection of neural network architectures."""
2
+
3
+ import contextlib
4
+
5
+ __all__ = ["tensorflow", "torch"]
6
+
7
+ with contextlib.suppress(ImportError):
8
+ from . import _torch as torch
9
+
10
+ from . import _tensorflow as tensorflow
File without changes
mxlpy/nn/_torch.py ADDED
@@ -0,0 +1,129 @@
1
+ """Neural network architectures.
2
+
3
+ This module provides implementations of neural network architectures used for mechanistic learning.
4
+
5
+ """
6
+
7
+ from __future__ import annotations
8
+
9
+ from typing import TYPE_CHECKING, cast
10
+
11
+ import torch
12
+ from torch import nn
13
+
14
+ if TYPE_CHECKING:
15
+ from collections.abc import Callable
16
+
17
+ __all__ = ["DefaultDevice", "LSTM", "MLP"]
18
+
19
+ DefaultDevice = torch.device("cpu")
20
+
21
+
22
+ class MLP(nn.Module):
23
+ """Multilayer Perceptron (MLP) for surrogate modeling and neural posterior estimation.
24
+
25
+ Attributes:
26
+ net: Sequential neural network model.
27
+
28
+ Methods:
29
+ forward: Forward pass through the neural network.
30
+
31
+ """
32
+
33
+ def __init__(
34
+ self,
35
+ n_inputs: int,
36
+ neurons_per_layer: list[int],
37
+ activation: Callable | None = None,
38
+ output_activation: Callable | None = None,
39
+ ) -> None:
40
+ """Initializes the MLP with the given number of inputs and list of (hidden) layers.
41
+
42
+ Args:
43
+ n_inputs: The number of input features.
44
+ neurons_per_layer: Number of neurons per layer
45
+ n_outputs: A list containing the number of neurons in hidden and output layer.
46
+ activation: The activation function to be applied after each hidden layer (default nn.ReLU)
47
+ output_activation: The activation function to be applied after the final (output) layer
48
+
49
+ For instance, MLP(10, layers = [50, 50, 10]) initializes a neural network with the following architecture:
50
+ - Linear layer with `n_inputs` inputs and 50 outputs
51
+ - ReLU activation
52
+ - Linear layer with 50 inputs and 50 outputs
53
+ - ReLU activation
54
+ - Linear layer with 50 inputs and 10 outputs
55
+
56
+ The weights of the linear layers are initialized with a normal distribution
57
+ (mean=0, std=0.1) and the biases are initialized to 0.
58
+
59
+ """
60
+ super().__init__()
61
+ self.layers = neurons_per_layer
62
+ self.activation = nn.ReLU() if activation is None else activation
63
+ self.output_activation = output_activation
64
+
65
+ levels = []
66
+ previous_neurons = n_inputs
67
+
68
+ for idx, neurons in enumerate(self.layers):
69
+ if idx == (len(self.layers) - 1):
70
+ levels.append(nn.Linear(previous_neurons, neurons))
71
+
72
+ if self.output_activation:
73
+ levels.append(self.output_activation)
74
+
75
+ else:
76
+ levels.append(nn.Linear(previous_neurons, neurons))
77
+
78
+ if self.activation:
79
+ levels.append(self.activation)
80
+
81
+ previous_neurons = neurons
82
+
83
+ self.net = nn.Sequential(*levels)
84
+
85
+ for m in self.net.modules():
86
+ if isinstance(m, nn.Linear):
87
+ nn.init.normal_(m.weight, mean=0, std=0.1)
88
+ nn.init.constant_(m.bias, val=0)
89
+
90
+ def forward(self, x: torch.Tensor) -> torch.Tensor:
91
+ """Forward pass through the neural network.
92
+
93
+ Args:
94
+ x: Input tensor.
95
+
96
+ Returns:
97
+ torch.Tensor: Output tensor.
98
+
99
+ """
100
+ return self.net(x)
101
+
102
+
103
+ class LSTM(nn.Module):
104
+ """Default LSTM neural network model for time-series approximation."""
105
+
106
+ def __init__(self, n_inputs: int, n_outputs: int, n_hidden: int) -> None:
107
+ """Initializes the neural network model.
108
+
109
+ Args:
110
+ n_inputs (int): Number of input features.
111
+ n_outputs (int): Number of output features.
112
+ n_hidden (int): Number of hidden units in the LSTM layer.
113
+
114
+ """
115
+ super().__init__()
116
+
117
+ self.n_hidden = n_hidden
118
+
119
+ self.lstm = nn.LSTM(n_inputs, n_hidden)
120
+ self.to_out = nn.Linear(n_hidden, n_outputs)
121
+
122
+ nn.init.normal_(self.to_out.weight, mean=0, std=0.1)
123
+ nn.init.constant_(self.to_out.bias, val=0)
124
+
125
+ def forward(self, x: torch.Tensor) -> torch.Tensor:
126
+ """Forward pass through the neural network."""
127
+ # lstm_out, (hidden_state, cell_state)
128
+ _, (hn, _) = self.lstm(x)
129
+ return cast(torch.Tensor, self.to_out(hn[-1])) # Use last hidden state
mxlpy/npe.py ADDED
@@ -0,0 +1,277 @@
1
+ """Neural Network Parameter Estimation (NPE) Module.
2
+
3
+ This module provides classes and functions for training neural network models to estimate
4
+ parameters in metabolic models. It includes functionality for both steady-state and
5
+ time-series data.
6
+
7
+ Functions:
8
+ train_torch_surrogate: Train a PyTorch surrogate model
9
+ train_torch_time_course_estimator: Train a PyTorch time course estimator
10
+ """
11
+
12
+ from __future__ import annotations
13
+
14
+ __all__ = [
15
+ "AbstractEstimator",
16
+ "DefaultCache",
17
+ "TorchSSEstimator",
18
+ "TorchTimeCourseEstimator",
19
+ "train_torch_ss_estimator",
20
+ "train_torch_time_course_estimator",
21
+ ]
22
+
23
+ from abc import abstractmethod
24
+ from dataclasses import dataclass
25
+ from pathlib import Path
26
+ from typing import TYPE_CHECKING, cast
27
+
28
+ import numpy as np
29
+ import pandas as pd
30
+ import torch
31
+ import tqdm
32
+ from torch import nn
33
+ from torch.optim.adam import Adam
34
+
35
+ from mxlpy.nn._torch import LSTM, MLP, DefaultDevice
36
+ from mxlpy.parallel import Cache
37
+
38
+ if TYPE_CHECKING:
39
+ from collections.abc import Callable
40
+
41
+ from torch.optim.optimizer import ParamsT
42
+
43
+ DefaultCache = Cache(Path(".cache"))
44
+
45
+
46
+ @dataclass(kw_only=True)
47
+ class AbstractEstimator:
48
+ """Abstract class for parameter estimation using neural networks."""
49
+
50
+ parameter_names: list[str]
51
+
52
+ @abstractmethod
53
+ def predict(self, features: pd.Series | pd.DataFrame) -> pd.DataFrame:
54
+ """Predict the target values for the given features."""
55
+
56
+
57
+ @dataclass(kw_only=True)
58
+ class TorchSSEstimator(AbstractEstimator):
59
+ """Estimator for steady state data using PyTorch models."""
60
+
61
+ model: torch.nn.Module
62
+
63
+ def predict(self, features: pd.Series | pd.DataFrame) -> pd.DataFrame:
64
+ """Predict the target values for the given features."""
65
+ with torch.no_grad():
66
+ pred = self.model(torch.tensor(features.to_numpy(), dtype=torch.float32))
67
+ return pd.DataFrame(pred, columns=self.parameter_names)
68
+
69
+
70
+ @dataclass(kw_only=True)
71
+ class TorchTimeCourseEstimator(AbstractEstimator):
72
+ """Estimator for time course data using PyTorch models."""
73
+
74
+ model: torch.nn.Module
75
+
76
+ def predict(self, features: pd.Series | pd.DataFrame) -> pd.DataFrame:
77
+ """Predict the target values for the given features."""
78
+ idx = cast(pd.MultiIndex, features.index)
79
+ features_ = torch.Tensor(
80
+ np.swapaxes(
81
+ features.to_numpy().reshape(
82
+ (
83
+ len(idx.levels[0]),
84
+ len(idx.levels[1]),
85
+ len(features.columns),
86
+ )
87
+ ),
88
+ axis1=0,
89
+ axis2=1,
90
+ ),
91
+ )
92
+ with torch.no_grad():
93
+ pred = self.model(features_)
94
+ return pd.DataFrame(pred, columns=self.parameter_names)
95
+
96
+
97
+ def _train_batched(
98
+ approximator: nn.Module,
99
+ features: torch.Tensor,
100
+ targets: torch.Tensor,
101
+ epochs: int,
102
+ optimizer: Adam,
103
+ batch_size: int,
104
+ ) -> pd.Series:
105
+ losses = {}
106
+
107
+ for epoch in tqdm.trange(epochs):
108
+ permutation = torch.randperm(features.size()[0])
109
+ epoch_loss = 0
110
+ for i in range(0, features.size()[0], batch_size):
111
+ optimizer.zero_grad()
112
+ indices = permutation[i : i + batch_size]
113
+
114
+ loss = torch.mean(
115
+ torch.abs(approximator(features[indices]) - targets[indices])
116
+ )
117
+ loss.backward()
118
+ optimizer.step()
119
+ epoch_loss += loss.detach().numpy()
120
+
121
+ losses[epoch] = epoch_loss / (features.size()[0] / batch_size)
122
+ return pd.Series(losses, dtype=float)
123
+
124
+
125
+ def _train_full(
126
+ approximator: nn.Module,
127
+ features: torch.Tensor,
128
+ targets: torch.Tensor,
129
+ epochs: int,
130
+ optimizer: Adam,
131
+ ) -> pd.Series:
132
+ losses = {}
133
+ for i in tqdm.trange(epochs):
134
+ optimizer.zero_grad()
135
+ loss = torch.mean(torch.abs(approximator(features) - targets))
136
+ loss.backward()
137
+ optimizer.step()
138
+ losses[i] = loss.detach().numpy()
139
+ return pd.Series(losses, dtype=float)
140
+
141
+
142
+ def train_torch_ss_estimator(
143
+ features: pd.DataFrame,
144
+ targets: pd.DataFrame,
145
+ epochs: int,
146
+ batch_size: int | None = None,
147
+ approximator: nn.Module | None = None,
148
+ optimimzer_cls: Callable[[ParamsT], Adam] = Adam,
149
+ device: torch.device = DefaultDevice,
150
+ ) -> tuple[TorchSSEstimator, pd.Series]:
151
+ """Train a PyTorch steady state estimator.
152
+
153
+ This function trains a neural network model to estimate steady state data
154
+ using the provided features and targets. It supports both full-batch and
155
+ mini-batch training.
156
+
157
+ Examples:
158
+ >>> train_torch_ss_estimator(features, targets, epochs=100)
159
+
160
+ Args:
161
+ features: DataFrame containing the input features for training
162
+ targets: DataFrame containing the target values for training
163
+ epochs: Number of training epochs
164
+ batch_size: Size of mini-batches for training (None for full-batch)
165
+ approximator: Predefined neural network model (None to use default MLP)
166
+ optimimzer_cls: Optimizer class to use for training (default: Adam)
167
+ device: Device to run the training on (default: DefaultDevice)
168
+
169
+ Returns:
170
+ tuple[TorchTimeSeriesEstimator, pd.Series]: Trained estimator and loss history
171
+
172
+ """
173
+ if approximator is None:
174
+ n_hidden = max(2 * len(features.columns) * len(targets.columns), 10)
175
+ n_outputs = len(targets.columns)
176
+ approximator = MLP(
177
+ n_inputs=len(features.columns),
178
+ neurons_per_layer=[n_hidden, n_hidden, n_outputs],
179
+ ).to(device)
180
+
181
+ features_ = torch.Tensor(features.to_numpy(), device=device)
182
+ targets_ = torch.Tensor(targets.to_numpy(), device=device)
183
+
184
+ optimizer = optimimzer_cls(approximator.parameters())
185
+ if batch_size is None:
186
+ losses = _train_full(
187
+ approximator=approximator,
188
+ features=features_,
189
+ targets=targets_,
190
+ epochs=epochs,
191
+ optimizer=optimizer,
192
+ )
193
+ else:
194
+ losses = _train_batched(
195
+ approximator=approximator,
196
+ features=features_,
197
+ targets=targets_,
198
+ epochs=epochs,
199
+ optimizer=optimizer,
200
+ batch_size=batch_size,
201
+ )
202
+
203
+ return TorchSSEstimator(
204
+ model=approximator,
205
+ parameter_names=list(targets.columns),
206
+ ), losses
207
+
208
+
209
+ def train_torch_time_course_estimator(
210
+ features: pd.DataFrame,
211
+ targets: pd.DataFrame,
212
+ epochs: int,
213
+ batch_size: int | None = None,
214
+ approximator: nn.Module | None = None,
215
+ optimimzer_cls: Callable[[ParamsT], Adam] = Adam,
216
+ device: torch.device = DefaultDevice,
217
+ ) -> tuple[TorchTimeCourseEstimator, pd.Series]:
218
+ """Train a PyTorch time course estimator.
219
+
220
+ This function trains a neural network model to estimate time course data
221
+ using the provided features and targets. It supports both full-batch and
222
+ mini-batch training.
223
+
224
+ Examples:
225
+ >>> train_torch_time_course_estimator(features, targets, epochs=100)
226
+
227
+ Args:
228
+ features: DataFrame containing the input features for training
229
+ targets: DataFrame containing the target values for training
230
+ epochs: Number of training epochs
231
+ batch_size: Size of mini-batches for training (None for full-batch)
232
+ approximator: Predefined neural network model (None to use default LSTM)
233
+ optimimzer_cls: Optimizer class to use for training (default: Adam)
234
+ device: Device to run the training on (default: DefaultDevice)
235
+
236
+ Returns:
237
+ tuple[TorchTimeSeriesEstimator, pd.Series]: Trained estimator and loss history
238
+
239
+ """
240
+ if approximator is None:
241
+ approximator = LSTM(
242
+ n_inputs=len(features.columns),
243
+ n_outputs=len(targets.columns),
244
+ n_hidden=1,
245
+ ).to(device)
246
+
247
+ optimizer = optimimzer_cls(approximator.parameters())
248
+ features_ = torch.Tensor(
249
+ np.swapaxes(
250
+ features.to_numpy().reshape((len(targets), -1, len(features.columns))),
251
+ axis1=0,
252
+ axis2=1,
253
+ ),
254
+ device=device,
255
+ )
256
+ targets_ = torch.Tensor(targets.to_numpy(), device=device)
257
+ if batch_size is None:
258
+ losses = _train_full(
259
+ approximator=approximator,
260
+ features=features_,
261
+ targets=targets_,
262
+ epochs=epochs,
263
+ optimizer=optimizer,
264
+ )
265
+ else:
266
+ losses = _train_batched(
267
+ approximator=approximator,
268
+ features=features_,
269
+ targets=targets_,
270
+ epochs=epochs,
271
+ optimizer=optimizer,
272
+ batch_size=batch_size,
273
+ )
274
+ return TorchTimeCourseEstimator(
275
+ model=approximator,
276
+ parameter_names=list(targets.columns),
277
+ ), losses
mxlpy/parallel.py ADDED
@@ -0,0 +1,171 @@
1
+ """Parallel Execution Module.
2
+
3
+ This module provides functions and classes for parallel execution and caching of
4
+ computation results. It includes functionality for parallel processing and result
5
+ caching using multiprocessing and pickle.
6
+
7
+ Classes:
8
+ Cache: Cache class for storing and retrieving computation results.
9
+
10
+ Functions:
11
+ parallelise: Execute a function in parallel over a collection of inputs.
12
+ """
13
+
14
+ from __future__ import annotations
15
+
16
+ import multiprocessing
17
+ import pickle
18
+ import sys
19
+ from dataclasses import dataclass
20
+ from functools import partial
21
+ from pathlib import Path
22
+ from typing import TYPE_CHECKING, Any, cast
23
+
24
+ import pebble
25
+ from tqdm import tqdm
26
+
27
+ __all__ = ["Cache", "parallelise"]
28
+
29
+ if TYPE_CHECKING:
30
+ from collections.abc import Callable, Collection, Hashable
31
+
32
+
33
+ def _pickle_name(k: Hashable) -> str:
34
+ return f"{k}.p"
35
+
36
+
37
+ def _pickle_load(file: Path) -> Any:
38
+ with file.open("rb") as fp:
39
+ return pickle.load(fp) # nosec
40
+
41
+
42
+ def _pickle_save(file: Path, data: Any) -> None:
43
+ with file.open("wb") as fp:
44
+ pickle.dump(data, fp)
45
+
46
+
47
+ @dataclass
48
+ class Cache:
49
+ """Cache class for storing and retrieving computation results.
50
+
51
+ Attributes:
52
+ tmp_dir: Directory to store cache files.
53
+ name_fn: Function to generate file names from keys.
54
+ load_fn: Function to load data from files.
55
+ save_fn: Function to save data to files.
56
+
57
+ """
58
+
59
+ tmp_dir: Path = Path(".cache")
60
+ name_fn: Callable[[Any], str] = _pickle_name
61
+ load_fn: Callable[[Path], Any] = _pickle_load
62
+ save_fn: Callable[[Path, Any], None] = _pickle_save
63
+
64
+
65
+ def _load_or_run[K: Hashable, Tin, Tout](
66
+ inp: tuple[K, Tin],
67
+ fn: Callable[[Tin], Tout],
68
+ cache: Cache | None,
69
+ ) -> tuple[K, Tout]:
70
+ """Load data from cache or execute function and save result.
71
+
72
+ Args:
73
+ inp: Tuple containing a key and input value.
74
+ fn: Function to execute if result is not in cache.
75
+ cache: Optional cache to store and retrieve results.
76
+
77
+ Returns:
78
+ tuple[K, Tout]: Tuple containing the key and the result of the function.
79
+
80
+ """
81
+ k, v = inp
82
+ if cache is None:
83
+ res = fn(v)
84
+ else:
85
+ file = cache.tmp_dir / cache.name_fn(k)
86
+ if file.exists():
87
+ return k, cast(Tout, cache.load_fn(file))
88
+ res = fn(v)
89
+ cache.save_fn(file, res)
90
+ return k, res
91
+
92
+
93
+ def parallelise[K: Hashable, Tin, Tout](
94
+ fn: Callable[[Tin], Tout],
95
+ inputs: Collection[tuple[K, Tin]],
96
+ *,
97
+ cache: Cache | None = None,
98
+ parallel: bool = True,
99
+ max_workers: int | None = None,
100
+ timeout: float | None = None,
101
+ disable_tqdm: bool = False,
102
+ tqdm_desc: str | None = None,
103
+ ) -> dict[Tin, Tout]:
104
+ """Execute a function in parallel over a collection of inputs.
105
+
106
+ Examples:
107
+ >>> parallelise(square, [("a", 2), ("b", 3), ("c", 4)])
108
+ {"a": 4, "b": 9, "c": 16}
109
+
110
+ Args:
111
+ fn: Function to execute in parallel. Takes a single input and returns a result.
112
+ inputs: Collection of (key, input) tuples to process.
113
+ cache: Optional cache to store and retrieve results.
114
+ parallel: Whether to execute in parallel (default: True).
115
+ max_workers: Maximum number of worker processes (default: None, uses all available CPUs).
116
+ timeout: Maximum time (in seconds) to wait for each worker to complete (default: None).
117
+ disable_tqdm: Whether to disable the tqdm progress bar (default: False).
118
+ tqdm_desc: Description for the tqdm progress bar (default: None).
119
+
120
+ Returns:
121
+ dict[Tin, Tout]: Dictionary mapping inputs to their corresponding outputs.
122
+
123
+ """
124
+ if cache is not None:
125
+ cache.tmp_dir.mkdir(parents=True, exist_ok=True)
126
+
127
+ if sys.platform in ["win32", "cygwin"]:
128
+ parallel = False
129
+
130
+ worker: Callable[[K, Tin], tuple[K, Tout]] = partial(
131
+ _load_or_run,
132
+ fn=fn,
133
+ cache=cache,
134
+ ) # type: ignore
135
+
136
+ results: dict[Tin, Tout]
137
+ if parallel:
138
+ results = {}
139
+ max_workers = (
140
+ multiprocessing.cpu_count() if max_workers is None else max_workers
141
+ )
142
+
143
+ with (
144
+ tqdm(
145
+ total=len(inputs),
146
+ disable=disable_tqdm,
147
+ desc=tqdm_desc,
148
+ ) as pbar,
149
+ pebble.ProcessPool(max_workers=max_workers) as pool,
150
+ ):
151
+ future = pool.map(worker, inputs, timeout=timeout)
152
+ it = future.result()
153
+ while True:
154
+ try:
155
+ key, value = next(it)
156
+ pbar.update(1)
157
+ results[key] = value
158
+ except StopIteration:
159
+ break
160
+ except TimeoutError:
161
+ pbar.update(1)
162
+ else:
163
+ results = dict(
164
+ tqdm(
165
+ map(worker, inputs), # type: ignore
166
+ total=len(inputs),
167
+ disable=disable_tqdm,
168
+ desc=tqdm_desc,
169
+ ) # type: ignore
170
+ ) # type: ignore
171
+ return results
mxlpy/parameterise.py ADDED
@@ -0,0 +1,27 @@
1
+ """Module to parameterise models."""
2
+
3
+ from pathlib import Path
4
+
5
+ import pandas as pd
6
+ from parameteriser.brenda.v0 import Brenda
7
+
8
+ __all__ = ["get_km_and_kcat_from_brenda"]
9
+
10
+
11
+ def get_km_and_kcat_from_brenda(
12
+ ec: str,
13
+ brenda_path: Path,
14
+ ) -> tuple[pd.DataFrame, pd.DataFrame]:
15
+ """Obtain michaelis and catalytic constants for given ec number.
16
+
17
+ You can obtain the database from https://www.brenda-enzymes.org/download.php
18
+ """
19
+ brenda = Brenda()
20
+ brenda.read_database(brenda_path)
21
+
22
+ kms, kcats = brenda.get_kms_and_kcats(
23
+ ec=ec,
24
+ filter_mutant=True,
25
+ filter_missing_sequences=True,
26
+ )
27
+ return kms, kcats
mxlpy/paths.py ADDED
@@ -0,0 +1,36 @@
1
+ """Shared paths between the mxlpy package."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import shutil
6
+ from pathlib import Path
7
+
8
+ __all__ = [
9
+ "default_tmp_dir",
10
+ ]
11
+
12
+
13
+ def default_tmp_dir(tmp_dir: Path | None, *, remove_old_cache: bool) -> Path:
14
+ """Returns the default temporary directory path.
15
+
16
+ If `tmp_dir` is None, it defaults to the user's home directory under ".cache/mxlpy".
17
+ Optionally removes old cache if specified.
18
+
19
+ Args:
20
+ tmp_dir (Path | None): The temporary directory path. If None, defaults to
21
+ Path.home() / ".cache" / "mxlpy".
22
+ remove_old_cache (bool): If True, removes the old cache directory if it exists.
23
+ Defaults to False.
24
+
25
+ Returns:
26
+ Path: The path to the temporary directory.
27
+
28
+ """
29
+ if tmp_dir is None:
30
+ tmp_dir = Path.home() / ".cache" / "mxlpy"
31
+
32
+ if tmp_dir.exists() and remove_old_cache:
33
+ shutil.rmtree(tmp_dir)
34
+
35
+ tmp_dir.mkdir(exist_ok=True, parents=True)
36
+ return tmp_dir