Skip to content

API Reference

Auto-generated API documentation from source code docstrings.

High-Level API

The Builder and VirtualCell classes provide the simplest interface for creating and simulating virtual cell models. See Quick Start for usage examples.

synthetic.api.Builder

Factory for creating virtual cell models.

Provides a static method for creating VirtualCell instances with a clean, fluent API.

Source code in src/synthetic/api.py
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
class Builder:
    """
    Factory for creating virtual cell models.

    Provides a static method for creating VirtualCell instances with
    a clean, fluent API.
    """

    @staticmethod
    def specify(
        degree_cascades: List[int],
        name: str = "VirtualCell",
        random_seed: Optional[int] = None,
        feedback_density: float = 1,
        auto_compile: bool = True,
        auto_drug: bool = True,
        drug_name: str = "D",
        drug_start_time: float = 5000.0,
        drug_value: float = 100.0,
        drug_regulation_type: str = "down",
        simulation_end: float = 10000.0,
    ) -> VirtualCell:
        """
        Create a virtual cell specification.

        Args:
            degree_cascades: List of cascade counts per degree, e.g., [1, 2, 5]
            name: Name for the virtual cell
            random_seed: Optional random seed for reproducibility
            feedback_density: Proportion of feedback connections (0-1)
            auto_compile: Compile immediately after creation (default: True)
            auto_drug: Auto-generate a drug targeting degree 1 R species (default: True)
            drug_name: Name for auto-generated drug (default: "D")
            drug_start_time: Time at which auto-drug becomes active (default: 5000.0)
            drug_value: Active concentration for auto-drug (default: 100.0)
            drug_regulation_type: Regulation type for auto-drug: "up" or "down" (default: "down")
            simulation_end: Simulation end time for make_dataset_drug_response (default: 10000.0)

        Returns:
            VirtualCell instance (compiled if auto_compile=True)
        """
        vc = VirtualCell(
            degree_cascades=degree_cascades,
            name=name,
            random_seed=random_seed,
            feedback_density=feedback_density,
            auto_compile=auto_compile,
            auto_drug=auto_drug,
            drug_name=drug_name,
            drug_start_time=drug_start_time,
            drug_value=drug_value,
            drug_regulation_type=drug_regulation_type,
            simulation_end=simulation_end,
        )
        if auto_compile:
            vc.compile()
        return vc

    @staticmethod
    def from_endpoint(
        endpoint: str,
        simulation_end: float = 10000.0,
        drug_names: Optional[List[str]] = None,
        timeout: float = 300.0,
        auto_compile: bool = True,
    ) -> 'RemoteCell':
        """
        Create a remote cell model from an HTTP endpoint.

        The server must implement the HTTP Solver API:
        - POST /simulate: Run simulation with optional state/parameter overrides
        - GET /states: Return default state values
        - GET /parameters: Return default parameter values

        Args:
            endpoint: HTTP endpoint URL (e.g., "http://localhost:8000/simulate")
            simulation_end: Simulation end time for make_dataset_drug_response (default: 10000.0)
            drug_names: Names of drug species on the server to exclude from features
            timeout: Request timeout in seconds (default: 300.0)
            auto_compile: Validate endpoint and fetch metadata immediately (default: True)

        Returns:
            RemoteCell instance (compiled if auto_compile=True)
        """
        rc = RemoteCell(
            endpoint=endpoint,
            simulation_end=simulation_end,
            drug_names=drug_names,
            timeout=timeout,
        )
        if auto_compile:
            rc.compile()
        return rc

from_endpoint(endpoint: str, simulation_end: float = 10000.0, drug_names: Optional[List[str]] = None, timeout: float = 300.0, auto_compile: bool = True) -> RemoteCell staticmethod

Create a remote cell model from an HTTP endpoint.

The server must implement the HTTP Solver API: - POST /simulate: Run simulation with optional state/parameter overrides - GET /states: Return default state values - GET /parameters: Return default parameter values

Parameters:

Name Type Description Default
endpoint str

HTTP endpoint URL (e.g., "http://localhost:8000/simulate")

required
simulation_end float

Simulation end time for make_dataset_drug_response (default: 10000.0)

10000.0
drug_names Optional[List[str]]

Names of drug species on the server to exclude from features

None
timeout float

Request timeout in seconds (default: 300.0)

300.0
auto_compile bool

Validate endpoint and fetch metadata immediately (default: True)

True

Returns:

Type Description
RemoteCell

RemoteCell instance (compiled if auto_compile=True)

Source code in src/synthetic/api.py
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
@staticmethod
def from_endpoint(
    endpoint: str,
    simulation_end: float = 10000.0,
    drug_names: Optional[List[str]] = None,
    timeout: float = 300.0,
    auto_compile: bool = True,
) -> 'RemoteCell':
    """
    Create a remote cell model from an HTTP endpoint.

    The server must implement the HTTP Solver API:
    - POST /simulate: Run simulation with optional state/parameter overrides
    - GET /states: Return default state values
    - GET /parameters: Return default parameter values

    Args:
        endpoint: HTTP endpoint URL (e.g., "http://localhost:8000/simulate")
        simulation_end: Simulation end time for make_dataset_drug_response (default: 10000.0)
        drug_names: Names of drug species on the server to exclude from features
        timeout: Request timeout in seconds (default: 300.0)
        auto_compile: Validate endpoint and fetch metadata immediately (default: True)

    Returns:
        RemoteCell instance (compiled if auto_compile=True)
    """
    rc = RemoteCell(
        endpoint=endpoint,
        simulation_end=simulation_end,
        drug_names=drug_names,
        timeout=timeout,
    )
    if auto_compile:
        rc.compile()
    return rc

specify(degree_cascades: List[int], name: str = 'VirtualCell', random_seed: Optional[int] = None, feedback_density: float = 1, auto_compile: bool = True, auto_drug: bool = True, drug_name: str = 'D', drug_start_time: float = 5000.0, drug_value: float = 100.0, drug_regulation_type: str = 'down', simulation_end: float = 10000.0) -> VirtualCell staticmethod

Create a virtual cell specification.

Parameters:

Name Type Description Default
degree_cascades List[int]

List of cascade counts per degree, e.g., [1, 2, 5]

required
name str

Name for the virtual cell

'VirtualCell'
random_seed Optional[int]

Optional random seed for reproducibility

None
feedback_density float

Proportion of feedback connections (0-1)

1
auto_compile bool

Compile immediately after creation (default: True)

True
auto_drug bool

Auto-generate a drug targeting degree 1 R species (default: True)

True
drug_name str

Name for auto-generated drug (default: "D")

'D'
drug_start_time float

Time at which auto-drug becomes active (default: 5000.0)

5000.0
drug_value float

Active concentration for auto-drug (default: 100.0)

100.0
drug_regulation_type str

Regulation type for auto-drug: "up" or "down" (default: "down")

'down'
simulation_end float

Simulation end time for make_dataset_drug_response (default: 10000.0)

10000.0

Returns:

Type Description
VirtualCell

VirtualCell instance (compiled if auto_compile=True)

Source code in src/synthetic/api.py
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
@staticmethod
def specify(
    degree_cascades: List[int],
    name: str = "VirtualCell",
    random_seed: Optional[int] = None,
    feedback_density: float = 1,
    auto_compile: bool = True,
    auto_drug: bool = True,
    drug_name: str = "D",
    drug_start_time: float = 5000.0,
    drug_value: float = 100.0,
    drug_regulation_type: str = "down",
    simulation_end: float = 10000.0,
) -> VirtualCell:
    """
    Create a virtual cell specification.

    Args:
        degree_cascades: List of cascade counts per degree, e.g., [1, 2, 5]
        name: Name for the virtual cell
        random_seed: Optional random seed for reproducibility
        feedback_density: Proportion of feedback connections (0-1)
        auto_compile: Compile immediately after creation (default: True)
        auto_drug: Auto-generate a drug targeting degree 1 R species (default: True)
        drug_name: Name for auto-generated drug (default: "D")
        drug_start_time: Time at which auto-drug becomes active (default: 5000.0)
        drug_value: Active concentration for auto-drug (default: 100.0)
        drug_regulation_type: Regulation type for auto-drug: "up" or "down" (default: "down")
        simulation_end: Simulation end time for make_dataset_drug_response (default: 10000.0)

    Returns:
        VirtualCell instance (compiled if auto_compile=True)
    """
    vc = VirtualCell(
        degree_cascades=degree_cascades,
        name=name,
        random_seed=random_seed,
        feedback_density=feedback_density,
        auto_compile=auto_compile,
        auto_drug=auto_drug,
        drug_name=drug_name,
        drug_start_time=drug_start_time,
        drug_value=drug_value,
        drug_regulation_type=drug_regulation_type,
        simulation_end=simulation_end,
    )
    if auto_compile:
        vc.compile()
    return vc

synthetic.api.VirtualCell

High-level abstraction for a virtual cell model.

Uses DegreeInteractionSpec for network topology and KineticParameterTuner for biologically plausible kinetic parameters.

This class provides a simple API for creating and managing virtual cell models without needing to understand the underlying complexity of the Synthetic library's architecture.

Source code in src/synthetic/api.py
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
class VirtualCell:
    """
    High-level abstraction for a virtual cell model.

    Uses DegreeInteractionSpec for network topology and KineticParameterTuner
    for biologically plausible kinetic parameters.

    This class provides a simple API for creating and managing virtual cell
    models without needing to understand the underlying complexity of the
    Synthetic library's architecture.
    """

    def __init__(
        self,
        degree_cascades: List[int],
        name: str = "VirtualCell",
        random_seed: Optional[int] = None,
        feedback_density: float = 0.5,
        auto_compile: bool = True,
        auto_drug: bool = True,
        drug_name: str = "D",
        drug_start_time: float = 5000.0,
        drug_value: float = 100.0,
        drug_regulation_type: str = "down",
        simulation_end: float = 10000.0,
    ):
        """
        Initialize a virtual cell model.

        Args:
            degree_cascades: List of cascade counts per degree, e.g., [1, 2, 5]
            name: Name for the virtual cell
            random_seed: Optional random seed for reproducibility
            feedback_density: Proportion of feedback connections (0-1)
            auto_compile: Compile immediately after creation (default: True)
            auto_drug: Auto-generate a drug targeting degree 1 R species (default: True)
            drug_name: Name for auto-generated drug (default: "D")
            drug_start_time: Time at which auto-drug becomes active (default: 5000.0)
            drug_value: Active concentration for auto-drug (default: 100.0)
            drug_regulation_type: Regulation type for auto-drug: "up" or "down" (default: "down")
            simulation_end: Simulation end time for make_dataset_drug_response (default: 10000.0)
        """
        self._degree_cascades = degree_cascades
        self._name = name
        self._random_seed = random_seed
        self._feedback_density = feedback_density
        self._auto_compile = auto_compile
        self._auto_drug = auto_drug
        self._auto_drug_name: Optional[str] = drug_name if auto_drug else None
        self._drug_start_time = drug_start_time
        self._auto_drug_value = drug_value
        self._auto_drug_regulation_type = drug_regulation_type
        self._simulation_end = simulation_end
        self._drugs: List[Tuple[Drug, Optional[float]]] = []
        self._spec: Optional[DegreeInteractionSpec] = None
        self._model: Optional[ModelBuilder] = None
        self._tuner: Optional[KineticParameterTuner] = None
        self._compiled = False

    def add_drug(
        self,
        name: str,
        start_time: float = 500.0,
        default_value: float = 0.0,
        regulation: Optional[List[str]] = None,
        regulation_type: Optional[List[str]] = None,
        value: Optional[float] = None,
    ) -> 'VirtualCell':
        """
        Add a drug to the cell model.

        Drugs can only target degree 1 R species. The drug appears at start_time
        via a piecewise assignment rule and regulates the specified species.

        Args:
            name: Name of the drug
            start_time: Time at which drug becomes active (default: 500.0)
            default_value: Default value when drug is not active (default: 0.0)
            regulation: List of target species (must be degree 1 R species)
            regulation_type: List of regulation types ('up' or 'down')
            value: Optional override value for when drug is active

        Returns:
            self for method chaining
        """
        drug = Drug(
            name=name,
            start_time=start_time,
            default_value=default_value,
            regulation=regulation,
            regulation_type=regulation_type,
        )
        self._drugs.append((drug, value))
        return self

    def list_drugs(self) -> List[Dict[str, Any]]:
        """
        List all drugs in the system (both auto-generated and manually added).

        Returns:
            List of dictionaries with drug information:
            [{'name': 'D', 'targets': ['R1_1'], 'types': ['down'],
              'start_time': 5000.0, 'default_value': 0.0, 'is_auto': True}, ...]
        """
        drugs_info = []
        for drug, value in self._drugs:
            drugs_info.append({
                'name': drug.name,
                'targets': drug.regulation,
                'types': drug.regulation_type,
                'start_time': drug.start_time,
                'default_value': drug.default_value,
                'is_auto': drug.name == self._auto_drug_name
            })
        return drugs_info

    def _generate_auto_drug(self) -> None:
        """
        Generate auto-drug based on degree_cascades[0].

        Creates a drug targeting all degree 1 R species (R1_1, R1_2, etc.)
        with count based on degree_cascades[0].
        """
        cascade_count = self._degree_cascades[0]
        targets = []

        # Generate targets: R1_1, R1_2, ... based on cascade_count
        for i in range(cascade_count):
            targets.append(f"R1_{i + 1}")

        # Create and store auto-drug
        drug = Drug(
            name=self._auto_drug_name,
            start_time=self._drug_start_time,
            default_value=0.0,
            regulation=targets,
            regulation_type=[self._auto_drug_regulation_type] * len(targets),
        )
        self._drugs.append((drug, self._auto_drug_value))

    def compile(
        self,
        mean_range_species: Tuple[int, int] = (50, 150),
        rangeScale_params: Tuple[float, float] = (0.8, 1.2),
        rangeMultiplier_params: Tuple[float, float] = (0.9, 1.1),
        use_kinetic_tuner: bool = True,
        active_percentage_range: Tuple[float, float] = (0.3, 0.7),
        X_total_multiplier: float = 5.0,
        ki_val: float = 100.0,
        v_max_f_random_range: Tuple[float, float] = (5.0, 10.0),
    ) -> 'VirtualCell':
        """
        Compile the model (lazy initialization).

        Creates the underlying DegreeInteractionSpec, ModelBuilder, and optionally
        applies KineticParameterTuner for biologically plausible parameters.

        If auto_drug is enabled, automatically generates a drug targeting degree 1
        R species and applies its parameters to the model.

        Args:
            mean_range_species: Range for initial species values
            rangeScale_params: Range for parameter scaling
            rangeMultiplier_params: Range for parameter multiplier
            use_kinetic_tuner: Whether to use KineticParameterTuner (default: True)
            active_percentage_range: Target active percentage range for tuning
            X_total_multiplier: Multiplier for Km_b calculation
            ki_val: Constant Ki value for inhibitors
            v_max_f_random_range: Range for total forward Vmax

        Returns:
            self for method chaining
        """
        # Generate auto-drug if enabled
        if self._auto_drug:
            self._generate_auto_drug()

        # Create specification
        self._spec = DegreeInteractionSpec(degree_cascades=self._degree_cascades)
        self._spec.generate_specifications(
            random_seed=self._random_seed,
            feedback_density=self._feedback_density,
        )

        # Add drugs (auto-drug + any manually added)
        for drug, value in self._drugs:
            self._spec.add_drug(drug, value)

        # Generate model
        self._model = self._spec.generate_network(
            network_name=self._name,
            mean_range_species=mean_range_species,
            rangeScale_params=rangeScale_params,
            rangeMultiplier_params=rangeMultiplier_params,
            random_seed=self._random_seed,
        )
        self._model.precompile()

        # Apply kinetic tuning if requested
        if use_kinetic_tuner:
            self._tuner = KineticParameterTuner(self._model, random_seed=self._random_seed)
            updated_params = self._tuner.generate_parameters(
                active_percentage_range=active_percentage_range,
                X_total_multiplier=X_total_multiplier,
                ki_val=ki_val,
                v_max_f_random_range=v_max_f_random_range,
            )
            for param_name, value in updated_params.items():
                self._model.set_parameter(param_name, value)

        # Apply auto-drug parameters using regulator_parameter_map
        if self._auto_drug_name:
            regulator_parameter_map = self._model.get_regulator_parameter_map()
            drug_params = regulator_parameter_map.get(self._auto_drug_name, {})
            for param_name in drug_params:
                self._model.set_parameter(param_name, self._auto_drug_value)

        self._compiled = True
        return self

    def get_species_names(self, exclude_drugs: bool = True) -> List[str]:
        """
        Get list of species names.

        Args:
            exclude_drugs: Whether to exclude drug species (default: True)

        Returns:
            List of species names
        """
        if not self._compiled:
            raise ValueError("Model must be compiled first. Call compile().")
        return self._model.get_state_variables().keys()

    def get_initial_values(self, exclude_drugs: bool = True) -> Dict[str, float]:
        """
        Get initial species values from the compiled model.

        Args:
            exclude_drugs: Whether to exclude drug species (default: True)

        Returns:
            Dictionary mapping species names to initial values
        """
        if not self._compiled:
            raise ValueError("Model must be compiled first. Call compile().")

        initial_values = self._model.get_state_variables().copy()

        if exclude_drugs:
            # Remove drugs from initial values (they are in model.variables)
            for drug_name in [d[0].name for d in self._drugs]:
                initial_values.pop(drug_name, None)

        return initial_values

    def get_target_concentrations(self) -> Dict[str, float]:
        """
        Get target active concentrations from the kinetic tuner.

        Returns an empty dict if kinetic tuning was not used during compilation.

        Returns:
            Dictionary mapping species names to target concentrations
        """
        if not self._compiled:
            raise ValueError("Model must be compiled first. Call compile().")
        if self._tuner is None:
            return {}
        return self._tuner.get_target_concentrations()

    @property
    def spec(self) -> DegreeInteractionSpec:
        """
        Access to underlying specification.

        Returns the DegreeInteractionSpec object. Raises ValueError if model
        has not been compiled.

        Returns:
            DegreeInteractionSpec object
        """
        if self._spec is None:
            raise ValueError("Model must be compiled first. Call compile().")
        return self._spec

    @property
    def model(self) -> ModelBuilder:
        """
        Access to underlying model.

        Returns the ModelBuilder object. Raises ValueError if model
        has not been compiled.

        Returns:
            ModelBuilder object
        """
        if self._model is None:
            raise ValueError("Model must be compiled first. Call compile().")
        return self._model

    @property
    def tuner(self) -> KineticParameterTuner:
        """
        Access to underlying kinetic tuner.

        Returns the KineticParameterTuner object, or None if kinetic
        tuning was not used during compilation.

        Returns:
            KineticParameterTuner object or None
        """
        return self._tuner

compile(mean_range_species: Tuple[int, int] = (50, 150), rangeScale_params: Tuple[float, float] = (0.8, 1.2), rangeMultiplier_params: Tuple[float, float] = (0.9, 1.1), use_kinetic_tuner: bool = True, active_percentage_range: Tuple[float, float] = (0.3, 0.7), X_total_multiplier: float = 5.0, ki_val: float = 100.0, v_max_f_random_range: Tuple[float, float] = (5.0, 10.0)) -> VirtualCell

Compile the model (lazy initialization).

Creates the underlying DegreeInteractionSpec, ModelBuilder, and optionally applies KineticParameterTuner for biologically plausible parameters.

If auto_drug is enabled, automatically generates a drug targeting degree 1 R species and applies its parameters to the model.

Parameters:

Name Type Description Default
mean_range_species Tuple[int, int]

Range for initial species values

(50, 150)
rangeScale_params Tuple[float, float]

Range for parameter scaling

(0.8, 1.2)
rangeMultiplier_params Tuple[float, float]

Range for parameter multiplier

(0.9, 1.1)
use_kinetic_tuner bool

Whether to use KineticParameterTuner (default: True)

True
active_percentage_range Tuple[float, float]

Target active percentage range for tuning

(0.3, 0.7)
X_total_multiplier float

Multiplier for Km_b calculation

5.0
ki_val float

Constant Ki value for inhibitors

100.0
v_max_f_random_range Tuple[float, float]

Range for total forward Vmax

(5.0, 10.0)

Returns:

Type Description
VirtualCell

self for method chaining

Source code in src/synthetic/api.py
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
def compile(
    self,
    mean_range_species: Tuple[int, int] = (50, 150),
    rangeScale_params: Tuple[float, float] = (0.8, 1.2),
    rangeMultiplier_params: Tuple[float, float] = (0.9, 1.1),
    use_kinetic_tuner: bool = True,
    active_percentage_range: Tuple[float, float] = (0.3, 0.7),
    X_total_multiplier: float = 5.0,
    ki_val: float = 100.0,
    v_max_f_random_range: Tuple[float, float] = (5.0, 10.0),
) -> 'VirtualCell':
    """
    Compile the model (lazy initialization).

    Creates the underlying DegreeInteractionSpec, ModelBuilder, and optionally
    applies KineticParameterTuner for biologically plausible parameters.

    If auto_drug is enabled, automatically generates a drug targeting degree 1
    R species and applies its parameters to the model.

    Args:
        mean_range_species: Range for initial species values
        rangeScale_params: Range for parameter scaling
        rangeMultiplier_params: Range for parameter multiplier
        use_kinetic_tuner: Whether to use KineticParameterTuner (default: True)
        active_percentage_range: Target active percentage range for tuning
        X_total_multiplier: Multiplier for Km_b calculation
        ki_val: Constant Ki value for inhibitors
        v_max_f_random_range: Range for total forward Vmax

    Returns:
        self for method chaining
    """
    # Generate auto-drug if enabled
    if self._auto_drug:
        self._generate_auto_drug()

    # Create specification
    self._spec = DegreeInteractionSpec(degree_cascades=self._degree_cascades)
    self._spec.generate_specifications(
        random_seed=self._random_seed,
        feedback_density=self._feedback_density,
    )

    # Add drugs (auto-drug + any manually added)
    for drug, value in self._drugs:
        self._spec.add_drug(drug, value)

    # Generate model
    self._model = self._spec.generate_network(
        network_name=self._name,
        mean_range_species=mean_range_species,
        rangeScale_params=rangeScale_params,
        rangeMultiplier_params=rangeMultiplier_params,
        random_seed=self._random_seed,
    )
    self._model.precompile()

    # Apply kinetic tuning if requested
    if use_kinetic_tuner:
        self._tuner = KineticParameterTuner(self._model, random_seed=self._random_seed)
        updated_params = self._tuner.generate_parameters(
            active_percentage_range=active_percentage_range,
            X_total_multiplier=X_total_multiplier,
            ki_val=ki_val,
            v_max_f_random_range=v_max_f_random_range,
        )
        for param_name, value in updated_params.items():
            self._model.set_parameter(param_name, value)

    # Apply auto-drug parameters using regulator_parameter_map
    if self._auto_drug_name:
        regulator_parameter_map = self._model.get_regulator_parameter_map()
        drug_params = regulator_parameter_map.get(self._auto_drug_name, {})
        for param_name in drug_params:
            self._model.set_parameter(param_name, self._auto_drug_value)

    self._compiled = True
    return self

add_drug(name: str, start_time: float = 500.0, default_value: float = 0.0, regulation: Optional[List[str]] = None, regulation_type: Optional[List[str]] = None, value: Optional[float] = None) -> VirtualCell

Add a drug to the cell model.

Drugs can only target degree 1 R species. The drug appears at start_time via a piecewise assignment rule and regulates the specified species.

Parameters:

Name Type Description Default
name str

Name of the drug

required
start_time float

Time at which drug becomes active (default: 500.0)

500.0
default_value float

Default value when drug is not active (default: 0.0)

0.0
regulation Optional[List[str]]

List of target species (must be degree 1 R species)

None
regulation_type Optional[List[str]]

List of regulation types ('up' or 'down')

None
value Optional[float]

Optional override value for when drug is active

None

Returns:

Type Description
VirtualCell

self for method chaining

Source code in src/synthetic/api.py
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
def add_drug(
    self,
    name: str,
    start_time: float = 500.0,
    default_value: float = 0.0,
    regulation: Optional[List[str]] = None,
    regulation_type: Optional[List[str]] = None,
    value: Optional[float] = None,
) -> 'VirtualCell':
    """
    Add a drug to the cell model.

    Drugs can only target degree 1 R species. The drug appears at start_time
    via a piecewise assignment rule and regulates the specified species.

    Args:
        name: Name of the drug
        start_time: Time at which drug becomes active (default: 500.0)
        default_value: Default value when drug is not active (default: 0.0)
        regulation: List of target species (must be degree 1 R species)
        regulation_type: List of regulation types ('up' or 'down')
        value: Optional override value for when drug is active

    Returns:
        self for method chaining
    """
    drug = Drug(
        name=name,
        start_time=start_time,
        default_value=default_value,
        regulation=regulation,
        regulation_type=regulation_type,
    )
    self._drugs.append((drug, value))
    return self

list_drugs() -> List[Dict[str, Any]]

List all drugs in the system (both auto-generated and manually added).

Returns:

Type Description
List[Dict[str, Any]]

List of dictionaries with drug information:

List[Dict[str, Any]]

[{'name': 'D', 'targets': ['R1_1'], 'types': ['down'], 'start_time': 5000.0, 'default_value': 0.0, 'is_auto': True}, ...]

Source code in src/synthetic/api.py
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
def list_drugs(self) -> List[Dict[str, Any]]:
    """
    List all drugs in the system (both auto-generated and manually added).

    Returns:
        List of dictionaries with drug information:
        [{'name': 'D', 'targets': ['R1_1'], 'types': ['down'],
          'start_time': 5000.0, 'default_value': 0.0, 'is_auto': True}, ...]
    """
    drugs_info = []
    for drug, value in self._drugs:
        drugs_info.append({
            'name': drug.name,
            'targets': drug.regulation,
            'types': drug.regulation_type,
            'start_time': drug.start_time,
            'default_value': drug.default_value,
            'is_auto': drug.name == self._auto_drug_name
        })
    return drugs_info

get_species_names(exclude_drugs: bool = True) -> List[str]

Get list of species names.

Parameters:

Name Type Description Default
exclude_drugs bool

Whether to exclude drug species (default: True)

True

Returns:

Type Description
List[str]

List of species names

Source code in src/synthetic/api.py
251
252
253
254
255
256
257
258
259
260
261
262
263
def get_species_names(self, exclude_drugs: bool = True) -> List[str]:
    """
    Get list of species names.

    Args:
        exclude_drugs: Whether to exclude drug species (default: True)

    Returns:
        List of species names
    """
    if not self._compiled:
        raise ValueError("Model must be compiled first. Call compile().")
    return self._model.get_state_variables().keys()

get_initial_values(exclude_drugs: bool = True) -> Dict[str, float]

Get initial species values from the compiled model.

Parameters:

Name Type Description Default
exclude_drugs bool

Whether to exclude drug species (default: True)

True

Returns:

Type Description
Dict[str, float]

Dictionary mapping species names to initial values

Source code in src/synthetic/api.py
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
def get_initial_values(self, exclude_drugs: bool = True) -> Dict[str, float]:
    """
    Get initial species values from the compiled model.

    Args:
        exclude_drugs: Whether to exclude drug species (default: True)

    Returns:
        Dictionary mapping species names to initial values
    """
    if not self._compiled:
        raise ValueError("Model must be compiled first. Call compile().")

    initial_values = self._model.get_state_variables().copy()

    if exclude_drugs:
        # Remove drugs from initial values (they are in model.variables)
        for drug_name in [d[0].name for d in self._drugs]:
            initial_values.pop(drug_name, None)

    return initial_values

get_target_concentrations() -> Dict[str, float]

Get target active concentrations from the kinetic tuner.

Returns an empty dict if kinetic tuning was not used during compilation.

Returns:

Type Description
Dict[str, float]

Dictionary mapping species names to target concentrations

Source code in src/synthetic/api.py
287
288
289
290
291
292
293
294
295
296
297
298
299
300
def get_target_concentrations(self) -> Dict[str, float]:
    """
    Get target active concentrations from the kinetic tuner.

    Returns an empty dict if kinetic tuning was not used during compilation.

    Returns:
        Dictionary mapping species names to target concentrations
    """
    if not self._compiled:
        raise ValueError("Model must be compiled first. Call compile().")
    if self._tuner is None:
        return {}
    return self._tuner.get_target_concentrations()

synthetic.api.make_dataset_drug_response(n: int, cell_model: Union[VirtualCell, RemoteCell], target_specie: str = 'Oa', perturbation_type: str = 'conserve_rules', perturbation_params: Optional[Dict[str, Any]] = None, parameter_values: Optional[Dict[str, float]] = None, param_perturbation_type: str = 'lognormal', param_perturbation_params: Optional[Dict[str, Any]] = None, simulation_params: Optional[Dict[str, Any]] = None, seed: Optional[int] = None, param_seed: Optional[int] = None, solver_type: str = 'scipy', jit: bool = True, verbose: bool = False, n_cores: int = 1, require_all_successful: bool = False, return_details: bool = True, capture_all_species: bool = True, exclude_outcome_from_features: bool = True, exclude_activated_from_features: bool = True, as_pandas: bool = True, return_timecourse: bool = False) -> Union[Tuple[pd.DataFrame, pd.Series], Tuple[np.ndarray, np.ndarray], Dict[str, Any]]

Generate synthetic drug response dataset.

Creates a dataset compatible with scikit-learn's make_regression format. The feature matrix X contains species concentrations, and the target vector y contains the outcome values.

Drugs are NOT included in the X features - they affect the simulation but are not part of the feature matrix.

Parameters:

Name Type Description Default
n int

Number of samples to generate

required
cell_model Union[VirtualCell, RemoteCell]

VirtualCell instance (must be compiled)

required
target_specie str

Name of the outcome species to use as target (default: 'Oa')

'Oa'
perturbation_type str

Type of initial value perturbation ('uniform', 'gaussian', 'lognormal', 'lhs')

'conserve_rules'
perturbation_params Optional[Dict[str, Any]]

Parameters for perturbation distribution

None
parameter_values Optional[Dict[str, float]]

Dictionary of kinetic parameter values to perturb (optional)

None
param_perturbation_type str

Type of kinetic parameter perturbation ('none', 'uniform', 'gaussian', 'lognormal', 'lhs')

'lognormal'
param_perturbation_params Optional[Dict[str, Any]]

Parameters for kinetic parameter perturbation (optional)

None
simulation_params Optional[Dict[str, Any]]

Dictionary with 'start', 'end', 'points' keys

None
seed Optional[int]

Random seed for reproducibility (initial value perturbations)

None
param_seed Optional[int]

Random seed for parameter perturbations (uses seed if not provided)

None
solver_type str

Type of solver ('scipy', 'roadrunner', or 'http')

'scipy'
jit bool

Whether to use JIT compilation (only for scipy solver)

True
verbose bool

Whether to show progress bar

False
require_all_successful bool

Whether to require all samples to succeed (default: False)

False
return_details bool

If True, returns extended data structure with intermediate datasets (default: True)

True
capture_all_species bool

If True, captures timecourses for all species in returned data.

True
as_pandas bool

If True (default), returns pandas DataFrame for X and Series for y with feature names. If False, returns numpy arrays for X and y.

True
return_timecourse bool

If True, returns dictionary with X, y, timecourse, parameters, and metadata (default: False)

False

Returns:

Type Description
Union[Tuple[DataFrame, Series], Tuple[ndarray, ndarray], Dict[str, Any]]

If return_timecourse=False: If as_pandas=True: Tuple of (X, y) where X is pandas DataFrame with feature names and y is pandas Series If as_pandas=False: Tuple of (X, y) where X is numpy array (n_samples, n_features) and y is numpy array (n_samples,)

Union[Tuple[DataFrame, Series], Tuple[ndarray, ndarray], Dict[str, Any]]

If return_timecourse=True: Dictionary with keys: - 'X': Feature matrix (basal state values) - 'y': Target values - 'timecourse': Timecourse simulation data (DataFrame with numpy arrays) - 'parameters': Kinetic parameters dataframe (None if not perturbed) - 'metadata': Dictionary with metadata about generation process

Raises:

Type Description
ValueError

If cell_model is not compiled or has invalid parameters

Source code in src/synthetic/api.py
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
def make_dataset_drug_response(
    n: int,
    cell_model: Union[VirtualCell, 'RemoteCell'],
    target_specie: str = 'Oa',
    perturbation_type: str = 'conserve_rules',
    perturbation_params: Optional[Dict[str, Any]] = None,
    parameter_values: Optional[Dict[str, float]] = None,
    param_perturbation_type: str = 'lognormal',
    param_perturbation_params: Optional[Dict[str, Any]] = None,
    simulation_params: Optional[Dict[str, Any]] = None,
    seed: Optional[int] = None,
    param_seed: Optional[int] = None,
    solver_type: str = 'scipy',
    jit: bool = True,
    verbose: bool = False,
    n_cores: int = 1,
    require_all_successful: bool = False,
    return_details: bool = True,
    capture_all_species: bool = True,
    exclude_outcome_from_features: bool = True,
    exclude_activated_from_features: bool = True,
    as_pandas: bool = True,
    return_timecourse: bool = False,
) -> Union[Tuple[pd.DataFrame, pd.Series], Tuple[np.ndarray, np.ndarray], Dict[str, Any]]:
    """
    Generate synthetic drug response dataset.

    Creates a dataset compatible with scikit-learn's make_regression format.
    The feature matrix X contains species concentrations, and the target
    vector y contains the outcome values.

    Drugs are NOT included in the X features - they affect the simulation
    but are not part of the feature matrix.

    Args:
        n: Number of samples to generate
        cell_model: VirtualCell instance (must be compiled)
        target_specie: Name of the outcome species to use as target (default: 'Oa')
        perturbation_type: Type of initial value perturbation ('uniform', 'gaussian', 'lognormal', 'lhs')
        perturbation_params: Parameters for perturbation distribution
        parameter_values: Dictionary of kinetic parameter values to perturb (optional)
        param_perturbation_type: Type of kinetic parameter perturbation ('none', 'uniform', 'gaussian', 'lognormal', 'lhs')
        param_perturbation_params: Parameters for kinetic parameter perturbation (optional)
        simulation_params: Dictionary with 'start', 'end', 'points' keys
        seed: Random seed for reproducibility (initial value perturbations)
        param_seed: Random seed for parameter perturbations (uses seed if not provided)
        solver_type: Type of solver ('scipy', 'roadrunner', or 'http')
        jit: Whether to use JIT compilation (only for scipy solver)
        verbose: Whether to show progress bar
        require_all_successful: Whether to require all samples to succeed (default: False)
        return_details: If True, returns extended data structure with intermediate datasets (default: True)
        capture_all_species: If True, captures timecourses for all species in returned data.
        as_pandas: If True (default), returns pandas DataFrame for X and Series for y with feature names.
                  If False, returns numpy arrays for X and y.
        return_timecourse: If True, returns dictionary with X, y, timecourse, parameters, and metadata (default: False)

    Returns:
        If return_timecourse=False:
            If as_pandas=True: Tuple of (X, y) where X is pandas DataFrame with feature names
                and y is pandas Series
            If as_pandas=False: Tuple of (X, y) where X is numpy array (n_samples, n_features)
                and y is numpy array (n_samples,)
        If return_timecourse=True: Dictionary with keys:
            - 'X': Feature matrix (basal state values)
            - 'y': Target values
            - 'timecourse': Timecourse simulation data (DataFrame with numpy arrays)
            - 'parameters': Kinetic parameters dataframe (None if not perturbed)
            - 'metadata': Dictionary with metadata about generation process

    Raises:
        ValueError: If cell_model is not compiled or has invalid parameters
    """
    from .utils.data_generation_helpers import make_data

    if not cell_model._compiled:
        raise ValueError("cell_model must be compiled. Call cell_model.compile() first.")

    # Set default simulation parameters (use cell_model's simulation_end)
    if simulation_params is None:
        simulation_params = {'start': 0, 'end': cell_model._simulation_end, 'points': 101}

    # Validate simulation parameters
    if 'start' not in simulation_params or 'end' not in simulation_params or 'points' not in simulation_params:
        raise ValueError('simulation_params must contain "start", "end", and "points" keys')

    # Set default perturbation parameters for conserve_rules
    if perturbation_params is None:
        perturbation_params = {'shape': 0.5, 'base_shape': 0.01, 'max_shape': 0.5}

    # Auto-extract parameter values from cell model if not provided
    if parameter_values is None:
        parameter_values = cell_model.model.get_parameters()

    # Set default parameter perturbation parameters
    if param_perturbation_params is None:
        param_perturbation_params = {'shape': 0.1}

    # Pass model_spec to conserve_rules for auto-generation of species ranges
    # Note: This is optional - if model_spec is not provided, conserve_rules will use
    # the species_range dictionary if provided, or auto-generate from initial_values
    if perturbation_type == 'conserve_rules' and 'model_spec' not in perturbation_params and 'species_range' not in perturbation_params:
        if hasattr(cell_model, 'spec') and cell_model.spec is not None:
            perturbation_params = perturbation_params.copy()
            perturbation_params['model_spec'] = cell_model.spec
        else:
            raise ValueError(
                "conserve_rules perturbation requires network topology (spec), "
                "which is not available for remote models. Either:\n"
                "  - Use a different perturbation_type (e.g., 'lognormal')\n"
                "  - Provide 'species_range' in perturbation_params explicitly"
            )

    # Get initial values (excluding drugs)
    initial_values = cell_model.get_initial_values(exclude_drugs=True)
    # Exclude any species with 'a' at the end of their name (outcome species and activated species)
    # Since they should not be perturbed initially
    initial_values = {k: v for k, v in initial_values.items() if not k.endswith('a')}
    initial_values.pop('O')

    # Create and compile solver
    if solver_type == 'scipy':
        solver = ScipySolver()
        antimony_str = cell_model.model.get_antimony_model()
        solver.compile(antimony_str, jit=jit)
    elif solver_type == 'roadrunner':
        from .Solver.RoadrunnerSolver import RoadrunnerSolver
        solver = RoadrunnerSolver()
        sbml_str = cell_model.model.get_sbml_model()
        solver.compile(sbml_str)
    elif solver_type == 'http':
        if not isinstance(cell_model, RemoteCell):
            raise ValueError(
                "solver_type='http' requires a RemoteCell. "
                "Use RemoteCell(endpoint_url) or Builder.from_endpoint(url)."
            )
        solver = cell_model.solver
    else:
        raise ValueError(f"Unsupported solver_type: {solver_type}. Use 'scipy', 'roadrunner', or 'http'")

    # Generate feature and target data using make_data
    result = make_data(
        initial_values=initial_values,
        perturbation_type=perturbation_type,
        perturbation_params=perturbation_params,
        n_samples=n,
        solver=solver,
        parameter_values=parameter_values,
        param_perturbation_type=param_perturbation_type,
        param_perturbation_params=param_perturbation_params,
        simulation_params=simulation_params,
        target_method="fold_change_drug",
        seed=seed,
        param_seed=param_seed,
        require_all_successful=require_all_successful,
        return_details=return_details,
        capture_all_species=capture_all_species,
        outcome_var=target_specie,
        verbose=verbose,
        n_cores=n_cores,
    )

    if return_details:
        # Return extended data structure
        # Use 'features' (perturbed initial values) as X, not 'basal_data' (pre-drug simulation state)
        X = result['features'].copy()
        if exclude_activated_from_features:
            X = X[[col for col in X.columns if not col.endswith('a')]]
        if exclude_outcome_from_features:
            X = X.drop(columns=['O'], errors='ignore')
        y = pd.Series(result['targets'].iloc[:, 0].values, name=target_specie, index=result['targets'].index, dtype=float)
        if not as_pandas:
            X = X.values.astype(np.float64)
            y = y.values.ravel().astype(np.float64)

        if return_timecourse:
            return {
                'X': X,
                'y': y,
                'timecourse': result['timecourse'],
                'parameters': result['parameters'],
                'metadata': result['metadata']
            }
        return X, y
    else:
        raise NotImplementedError("return_details=False is not implemented in this version.")

Model Building

Core classes for building biochemical reaction networks from scratch. See Model Building for the full guide.

synthetic.ModelBuilder.ModelBuilder

Docstring

Source code in src/synthetic/ModelBuilder.py
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
class ModelBuilder:

    '''
    Docstring
    '''

    def __init__(self, name):
        self.name = name

        self.reactions: List[Reaction] = []
        # these two fields are coupled to self.reaction
        self.pre_compiled = False
        self.states = {}
        self.parameters = {}

        self.variables = {}
        self.enforce_state_values = {}
        self.custom_strings = {}

    def set_parameter(self, parameter_name: str, value: float):
        '''
        Set a parameter value in the model
        '''
        if parameter_name not in self.parameters:
            raise Exception(f'Parameter {parameter_name} not found in the model')
        if not self.pre_compiled: 
            raise Exception('Model must be pre-compiled before setting a parameter value, run self.precompile()')
        self.parameters[parameter_name] = value

    def get_parameter(self, parameter_name: str) -> float:
        '''
        Get a parameter value in the model
        '''
        if parameter_name not in self.parameters:
            raise Exception(f'Parameter {parameter_name} not found in the model')
        return self.parameters[parameter_name]

    def set_state(self, state_name: str, value: float):
        '''
        Set a state value in the model
        '''
        if state_name not in self.states:
            raise Exception(f'State {state_name} not found in the model')
        if not self.pre_compiled: 
            raise Exception('Model must be pre-compiled before setting a state value, run self.precompile()')
        self.states[state_name] = value

    def get_state(self, state_name: str) -> float:
        '''
        Get a state value in the model
        '''
        if state_name not in self.states:
            raise Exception(f'State {state_name} not found in the model')
        return self.states[state_name]

    def get_parameters(self) -> dict:
        '''
        Extracts parameters and their values from all reactions 
        in the class and returns a dict while subjecting to a naming rule.

        If model is pre-compiled, returns the cached parameters.
        '''
        if self.pre_compiled:
            return self.parameters.copy()

        parameters = {}
        i = 0
        while i < len(self.reactions):
            r = self.reactions[i]
            # first, get the parameters names from the archtype
            # and perform naming rule


            #Here, a simple naming rule is implemented. It simply appends the reaction index 
            #to the parameter name
            #TODO: implement more complex naming rules in the future 

            r_index = f'J{i}'

            parameters.update(r.get_reaction_parameters(r_index))

            i += 1

        return parameters

    def get_state_variables(self) -> dict:
        '''
        Extracts state variables and their values from all reactions 
        in the class and returns a dict

        non-unique state variables will only be repeated once, their 
        default value will only follow the first repeated state variable

        If model is pre-compiled, returns the cached states.
        '''
        if self.pre_compiled:
            return self.states.copy()

        states = {}
        for r in self.reactions:
            states.update(r.get_reaction_states())

        # enforce state values if defined in the class
        for k, v in self.enforce_state_values.items():
            states[k] = v

        return states

    def get_other_variables(self):
        '''
        Doc
        '''
        return self.variables

    def get_all_variables_keys(self, with_time=False):
        '''
        Doc
        '''
        if with_time:
            return list(self.states.keys()) + list(self.variables.keys()) + ['time']

        return list(self.get_state_variables().keys()) + list(self.variables.keys())

    def get_custom_variable_keys(self):
        '''
        Doc
        '''
        return list(self.variables.keys())

    def get_regulator_parameter_map(self) -> dict:
        '''
        Returns mapping from regulator (extra_state) names to parameter names (with r_index).
        The mapping is aggregated across all reactions in the model.
        '''
        if not self.pre_compiled:
            self.precompile()

        regulator_map = {}
        for i, r in enumerate(self.reactions):
            r_index = f'J{i}'
            for regulator in r.extra_states:
                param_bases = r.get_parameters_for_regulator(regulator)
                for param_base in param_bases:
                    param_name = f"{param_base}_{r_index}"
                    regulator_map.setdefault(regulator, []).append(param_name)
        return regulator_map

    def get_parameter_regulator_map(self) -> dict:
        '''
        Returns mapping from parameter names (with r_index) to regulator (extra_state) names.
        The mapping is aggregated across all reactions in the model.
        '''
        if not self.pre_compiled:
            self.precompile()

        param_map = {}
        for i, r in enumerate(self.reactions):
            r_index = f'J{i}'
            for param_base in r.archtype.parameters:
                regulator = r.get_regulator_for_parameter(param_base)
                if regulator:
                    param_name = f"{param_base}_{r_index}"
                    param_map[param_name] = regulator
        return param_map


    def add_reaction(self, reaction: Reaction):
        '''
        Add a reaction to the model, the reaction must be an instance of the Reaction class
        '''

        # validate that the reaction has a unique name within the model if a name is defined
        if reaction.name != '':
            for r in self.reactions:
                if r.name == reaction.name:
                    raise Exception(f'Reaction name is not unique within the model {reaction.name}')

        self.reactions.append(reaction)
        # reset the pre_compiled flag, since the model has changed 
        self.pre_compiled = False

    def inject_antimony_string_at(self, ant_string: str, position: str = 'reaction'):

        '''
        position can only be in str: top, reaction, state, parameters, end 
        '''
        warnings.warn('Adding variables using this function will result in a variable mismatch with antimony variables, since the variables will not be registered within the class itself', SyntaxWarning)
        all_positions = ['top', 'reaction', 'state', 'parameters', 'end']
        for p in all_positions:
            if p == position:
                if p in self.custom_strings:
                    self.custom_strings[p] += ant_string + '\n'
                else: 
                    self.custom_strings[p] = ant_string + '\n'
                break

    def add_enforce_state_value(self, state_name: str, value: float):
        '''
        Doc
        '''
        self.enforce_state_values[state_name] = value

    def add_custom_variables(self, variable_name, reaction_rule):
        '''
        Doc
        '''
        self.variables[variable_name] = reaction_rule


    def add_simple_piecewise(self, before_value: float, activation_time: float, after_value: float, state_name: str):
        '''
        Adds a simple piecewise function to the state variable state_name
        '''
        self.variables[state_name] = f'{state_name} := piecewise({before_value}, time < {activation_time}, {after_value})'
        # self.inject_antimony_string_at(f"{state_name} := piecewise({after_value}, time > {activation_time}, {before_value})", 'parameters')

    def delete_reaction(self, reaction_name: str):
        '''
        Deletes a reaction from the model
        '''
        for r in self.reactions:
            if r.name == reaction_name:
                self.reactions.remove(r)
                break

        self.pre_compiled = False

    def copy(self, overwrite_name='') -> 'ModelBuilder':
        '''
        Copy the model
        '''

        name = self.name if overwrite_name == '' else overwrite_name

        new_model = ModelBuilder(name)
        for r in self.reactions:
            new_model.add_reaction(r.copy())
        new_model.variables = self.variables
        new_model.enforce_state_values = self.enforce_state_values
        new_model.custom_strings = self.custom_strings

        # If the original model is pre-compiled, copy the pre-compiled state
        if self.pre_compiled:
            new_model.parameters = self.parameters.copy()
            new_model.states = self.states.copy()
            new_model.pre_compiled = True

        return new_model

    def combine(self, model: 'ModelBuilder', reactions_only=False) -> 'ModelBuilder':
        '''
        Combine two models
        '''
        new_model = self.copy()
        for r in model.reactions:
            new_model.add_reaction(r.copy())

        if not reactions_only:
            new_model.variables.update(model.variables)
            new_model.enforce_state_values.update(model.enforce_state_values)
            new_model.custom_strings.update(model.custom_strings)
        return new_model

    def __str__(self) -> str:

        return self.head()

    def head(self):
        '''
        Returns the general characteristics of the model
        '''
        return_str = ''
        return_str += f'Model Name {self.name}\n'
        return_str += f'Number of Reactions {len(self.reactions)}\n'
        return_str += f'Number of State Variables {len(self.states)}\n'
        return_str += f'Number of Parameters {len(self.parameters)}\n'
        return_str += f'Number of Custom Variables {len(self.variables)}\n'
        return_str += f'Number of Enforced State Values {len(self.enforce_state_values)}\n'
        return_str += f'Number of Custom Strings {len(self.custom_strings)}\n'
        return return_str

    def precompile(self):
        '''
        Populates the state and parameter variables list in the class which are used to generate the antimony text 
        The pre-compiled model will have functionalities for getting and setting specific state and parameter values, 
        which gets passed directly into the antimony string 
        '''
        self.parameters = self.get_parameters()
        self.states = self.get_state_variables()
        self.pre_compiled = True

    def get_antimony_model(self):
        '''
        Doc
        '''

        if not self.pre_compiled:
            raise Exception('Model must be pre-compiled before generating antimony string, run self.precompile(), the pre-compiled model will have functionalities for getting and setting specific state and parameter values, which gets passed directly into the antimony string')

        antimony_string = ''

        antimony_string += f'model {self.name}\n\n'

        # add top custom str 
        if 'top' in self.custom_strings:
            antimony_string += self.custom_strings['top']

        # add reactions

        # first, add reaction custom str 
        if 'reaction' in self.custom_strings:
            antimony_string += self.custom_strings['reaction']

        i = 0
        while i < len(self.reactions):
            r = self.reactions[i]
            r_index = f'J{i}'
            antimony_string += r.get_antimony_reaction_str(r_index)
            antimony_string += '\n'
            if r.reversible: 
                antimony_string += r.get_antimony_reactions_reverse_str(r_index)
                antimony_string += '\n'
            i += 1

        # add state vars

        # first, add state custom str
        antimony_string += '\n'
        antimony_string += '# State variables in the system\n'
        if 'state' in self.custom_strings:
            antimony_string += self.custom_strings['state']

        all_states = self.states
        for key, val in all_states.items():
            antimony_string += f'{key}={val}\n'
        antimony_string += '\n'

        # add parameters

        # first, add parameter custom str
        antimony_string += '# Parameters in the system\n'
        if 'parameters' in self.custom_strings:
            antimony_string += self.custom_strings['parameters']

        all_params = self.parameters
        for key, val in all_params.items():
            antimony_string += f'{key}={val}\n'

        # add other variables
        antimony_string += '\n'
        antimony_string += '# Other variables in the system\n'
        for key, val in self.variables.items():
            antimony_string += f'{val}\n'
        antimony_string += '\n' 

        # add end custom str
        if 'end' in self.custom_strings:
            antimony_string += self.custom_strings['end']

        antimony_string += '\nend'

        return antimony_string

    def get_sbml_model(self) -> str:

        '''
        Doc
        '''

        ant_model = self.get_antimony_model()
        antimony.clearPreviousLoads()
        antimony.freeAll()
        code = antimony.loadAntimonyString(ant_model)
        if code >= 0:
            mid = antimony.getMainModuleName()
            sbml_model = antimony.getSBMLString(mid)
            return sbml_model

        raise Exception('Error in loading antimony model', code)

    def get_sbml_model_from(self, ant_model) -> str:
        """
        Doc
        """

        antimony.clearPreviousLoads()
        antimony.freeAll()
        code = antimony.loadAntimonyString(ant_model)
        if code >= 0:
            mid = antimony.getMainModuleName()
            sbml_model = antimony.getSBMLString(mid)
            return sbml_model

        raise Exception("Error in loading antimony model", code)

    def save_antimony_model_as(self, file_name: str):
        '''
        Doc
        '''
        ant_model = self.get_antimony_model()
        with open(file_name, 'w') as f:
            f.write(ant_model)

    def save_sbml_model_as(self, file_name: str):
        '''
        Doc
        '''
        sbml_model = self.get_sbml_model()
        with open(file_name, 'w') as f:
            f.write(sbml_model)

    def save_model_as_pickle(self, file_name: str):
        '''
        Doc
        '''
        with open(file_name, 'wb') as f:
            pickle.dump(self, f)

    def plot(self):
        '''
        Plots the results of the simulation
        '''
        self.r_model.plot()

add_reaction(reaction: Reaction)

Add a reaction to the model, the reaction must be an instance of the Reaction class

Source code in src/synthetic/ModelBuilder.py
177
178
179
180
181
182
183
184
185
186
187
188
189
190
def add_reaction(self, reaction: Reaction):
    '''
    Add a reaction to the model, the reaction must be an instance of the Reaction class
    '''

    # validate that the reaction has a unique name within the model if a name is defined
    if reaction.name != '':
        for r in self.reactions:
            if r.name == reaction.name:
                raise Exception(f'Reaction name is not unique within the model {reaction.name}')

    self.reactions.append(reaction)
    # reset the pre_compiled flag, since the model has changed 
    self.pre_compiled = False

delete_reaction(reaction_name: str)

Deletes a reaction from the model

Source code in src/synthetic/ModelBuilder.py
227
228
229
230
231
232
233
234
235
236
def delete_reaction(self, reaction_name: str):
    '''
    Deletes a reaction from the model
    '''
    for r in self.reactions:
        if r.name == reaction_name:
            self.reactions.remove(r)
            break

    self.pre_compiled = False

precompile()

Populates the state and parameter variables list in the class which are used to generate the antimony text The pre-compiled model will have functionalities for getting and setting specific state and parameter values, which gets passed directly into the antimony string

Source code in src/synthetic/ModelBuilder.py
292
293
294
295
296
297
298
299
300
def precompile(self):
    '''
    Populates the state and parameter variables list in the class which are used to generate the antimony text 
    The pre-compiled model will have functionalities for getting and setting specific state and parameter values, 
    which gets passed directly into the antimony string 
    '''
    self.parameters = self.get_parameters()
    self.states = self.get_state_variables()
    self.pre_compiled = True

get_parameters() -> dict

Extracts parameters and their values from all reactions in the class and returns a dict while subjecting to a naming rule.

If model is pre-compiled, returns the cached parameters.

Source code in src/synthetic/ModelBuilder.py
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
def get_parameters(self) -> dict:
    '''
    Extracts parameters and their values from all reactions 
    in the class and returns a dict while subjecting to a naming rule.

    If model is pre-compiled, returns the cached parameters.
    '''
    if self.pre_compiled:
        return self.parameters.copy()

    parameters = {}
    i = 0
    while i < len(self.reactions):
        r = self.reactions[i]
        # first, get the parameters names from the archtype
        # and perform naming rule


        #Here, a simple naming rule is implemented. It simply appends the reaction index 
        #to the parameter name
        #TODO: implement more complex naming rules in the future 

        r_index = f'J{i}'

        parameters.update(r.get_reaction_parameters(r_index))

        i += 1

    return parameters

get_state_variables() -> dict

Extracts state variables and their values from all reactions in the class and returns a dict

non-unique state variables will only be repeated once, their default value will only follow the first repeated state variable

If model is pre-compiled, returns the cached states.

Source code in src/synthetic/ModelBuilder.py
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
def get_state_variables(self) -> dict:
    '''
    Extracts state variables and their values from all reactions 
    in the class and returns a dict

    non-unique state variables will only be repeated once, their 
    default value will only follow the first repeated state variable

    If model is pre-compiled, returns the cached states.
    '''
    if self.pre_compiled:
        return self.states.copy()

    states = {}
    for r in self.reactions:
        states.update(r.get_reaction_states())

    # enforce state values if defined in the class
    for k, v in self.enforce_state_values.items():
        states[k] = v

    return states

set_parameter(parameter_name: str, value: float)

Set a parameter value in the model

Source code in src/synthetic/ModelBuilder.py
30
31
32
33
34
35
36
37
38
def set_parameter(self, parameter_name: str, value: float):
    '''
    Set a parameter value in the model
    '''
    if parameter_name not in self.parameters:
        raise Exception(f'Parameter {parameter_name} not found in the model')
    if not self.pre_compiled: 
        raise Exception('Model must be pre-compiled before setting a parameter value, run self.precompile()')
    self.parameters[parameter_name] = value

get_parameter(parameter_name: str) -> float

Get a parameter value in the model

Source code in src/synthetic/ModelBuilder.py
40
41
42
43
44
45
46
def get_parameter(self, parameter_name: str) -> float:
    '''
    Get a parameter value in the model
    '''
    if parameter_name not in self.parameters:
        raise Exception(f'Parameter {parameter_name} not found in the model')
    return self.parameters[parameter_name]

set_state(state_name: str, value: float)

Set a state value in the model

Source code in src/synthetic/ModelBuilder.py
48
49
50
51
52
53
54
55
56
def set_state(self, state_name: str, value: float):
    '''
    Set a state value in the model
    '''
    if state_name not in self.states:
        raise Exception(f'State {state_name} not found in the model')
    if not self.pre_compiled: 
        raise Exception('Model must be pre-compiled before setting a state value, run self.precompile()')
    self.states[state_name] = value

get_state(state_name: str) -> float

Get a state value in the model

Source code in src/synthetic/ModelBuilder.py
58
59
60
61
62
63
64
def get_state(self, state_name: str) -> float:
    '''
    Get a state value in the model
    '''
    if state_name not in self.states:
        raise Exception(f'State {state_name} not found in the model')
    return self.states[state_name]

get_regulator_parameter_map() -> dict

Returns mapping from regulator (extra_state) names to parameter names (with r_index). The mapping is aggregated across all reactions in the model.

Source code in src/synthetic/ModelBuilder.py
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
def get_regulator_parameter_map(self) -> dict:
    '''
    Returns mapping from regulator (extra_state) names to parameter names (with r_index).
    The mapping is aggregated across all reactions in the model.
    '''
    if not self.pre_compiled:
        self.precompile()

    regulator_map = {}
    for i, r in enumerate(self.reactions):
        r_index = f'J{i}'
        for regulator in r.extra_states:
            param_bases = r.get_parameters_for_regulator(regulator)
            for param_base in param_bases:
                param_name = f"{param_base}_{r_index}"
                regulator_map.setdefault(regulator, []).append(param_name)
    return regulator_map

get_parameter_regulator_map() -> dict

Returns mapping from parameter names (with r_index) to regulator (extra_state) names. The mapping is aggregated across all reactions in the model.

Source code in src/synthetic/ModelBuilder.py
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
def get_parameter_regulator_map(self) -> dict:
    '''
    Returns mapping from parameter names (with r_index) to regulator (extra_state) names.
    The mapping is aggregated across all reactions in the model.
    '''
    if not self.pre_compiled:
        self.precompile()

    param_map = {}
    for i, r in enumerate(self.reactions):
        r_index = f'J{i}'
        for param_base in r.archtype.parameters:
            regulator = r.get_regulator_for_parameter(param_base)
            if regulator:
                param_name = f"{param_base}_{r_index}"
                param_map[param_name] = regulator
    return param_map

get_antimony_model()

Doc

Source code in src/synthetic/ModelBuilder.py
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
def get_antimony_model(self):
    '''
    Doc
    '''

    if not self.pre_compiled:
        raise Exception('Model must be pre-compiled before generating antimony string, run self.precompile(), the pre-compiled model will have functionalities for getting and setting specific state and parameter values, which gets passed directly into the antimony string')

    antimony_string = ''

    antimony_string += f'model {self.name}\n\n'

    # add top custom str 
    if 'top' in self.custom_strings:
        antimony_string += self.custom_strings['top']

    # add reactions

    # first, add reaction custom str 
    if 'reaction' in self.custom_strings:
        antimony_string += self.custom_strings['reaction']

    i = 0
    while i < len(self.reactions):
        r = self.reactions[i]
        r_index = f'J{i}'
        antimony_string += r.get_antimony_reaction_str(r_index)
        antimony_string += '\n'
        if r.reversible: 
            antimony_string += r.get_antimony_reactions_reverse_str(r_index)
            antimony_string += '\n'
        i += 1

    # add state vars

    # first, add state custom str
    antimony_string += '\n'
    antimony_string += '# State variables in the system\n'
    if 'state' in self.custom_strings:
        antimony_string += self.custom_strings['state']

    all_states = self.states
    for key, val in all_states.items():
        antimony_string += f'{key}={val}\n'
    antimony_string += '\n'

    # add parameters

    # first, add parameter custom str
    antimony_string += '# Parameters in the system\n'
    if 'parameters' in self.custom_strings:
        antimony_string += self.custom_strings['parameters']

    all_params = self.parameters
    for key, val in all_params.items():
        antimony_string += f'{key}={val}\n'

    # add other variables
    antimony_string += '\n'
    antimony_string += '# Other variables in the system\n'
    for key, val in self.variables.items():
        antimony_string += f'{val}\n'
    antimony_string += '\n' 

    # add end custom str
    if 'end' in self.custom_strings:
        antimony_string += self.custom_strings['end']

    antimony_string += '\nend'

    return antimony_string

get_sbml_model() -> str

Doc

Source code in src/synthetic/ModelBuilder.py
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
def get_sbml_model(self) -> str:

    '''
    Doc
    '''

    ant_model = self.get_antimony_model()
    antimony.clearPreviousLoads()
    antimony.freeAll()
    code = antimony.loadAntimonyString(ant_model)
    if code >= 0:
        mid = antimony.getMainModuleName()
        sbml_model = antimony.getSBMLString(mid)
        return sbml_model

    raise Exception('Error in loading antimony model', code)

add_simple_piecewise(before_value: float, activation_time: float, after_value: float, state_name: str)

Adds a simple piecewise function to the state variable state_name

Source code in src/synthetic/ModelBuilder.py
220
221
222
223
224
def add_simple_piecewise(self, before_value: float, activation_time: float, after_value: float, state_name: str):
    '''
    Adds a simple piecewise function to the state variable state_name
    '''
    self.variables[state_name] = f'{state_name} := piecewise({before_value}, time < {activation_time}, {after_value})'

combine(model: ModelBuilder, reactions_only=False) -> ModelBuilder

Combine two models

Source code in src/synthetic/ModelBuilder.py
260
261
262
263
264
265
266
267
268
269
270
271
272
def combine(self, model: 'ModelBuilder', reactions_only=False) -> 'ModelBuilder':
    '''
    Combine two models
    '''
    new_model = self.copy()
    for r in model.reactions:
        new_model.add_reaction(r.copy())

    if not reactions_only:
        new_model.variables.update(model.variables)
        new_model.enforce_state_values.update(model.enforce_state_values)
        new_model.custom_strings.update(model.custom_strings)
    return new_model

copy(overwrite_name='') -> ModelBuilder

Copy the model

Source code in src/synthetic/ModelBuilder.py
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
def copy(self, overwrite_name='') -> 'ModelBuilder':
    '''
    Copy the model
    '''

    name = self.name if overwrite_name == '' else overwrite_name

    new_model = ModelBuilder(name)
    for r in self.reactions:
        new_model.add_reaction(r.copy())
    new_model.variables = self.variables
    new_model.enforce_state_values = self.enforce_state_values
    new_model.custom_strings = self.custom_strings

    # If the original model is pre-compiled, copy the pre-compiled state
    if self.pre_compiled:
        new_model.parameters = self.parameters.copy()
        new_model.states = self.states.copy()
        new_model.pre_compiled = True

    return new_model

head()

Returns the general characteristics of the model

Source code in src/synthetic/ModelBuilder.py
278
279
280
281
282
283
284
285
286
287
288
289
290
def head(self):
    '''
    Returns the general characteristics of the model
    '''
    return_str = ''
    return_str += f'Model Name {self.name}\n'
    return_str += f'Number of Reactions {len(self.reactions)}\n'
    return_str += f'Number of State Variables {len(self.states)}\n'
    return_str += f'Number of Parameters {len(self.parameters)}\n'
    return_str += f'Number of Custom Variables {len(self.variables)}\n'
    return_str += f'Number of Enforced State Values {len(self.enforce_state_values)}\n'
    return_str += f'Number of Custom Strings {len(self.custom_strings)}\n'
    return return_str

synthetic.Reaction.Reaction

This class represents a reaction in the system. ENSURE: use (a,) instead of (a) for tuples typing reaction_archtype: ReactionArchtype, reactants: Tuple[str], products: Tuple[str], extra_states: Tuple[str] = (), parameters_values: Union[dict, tuple] = (), reactant_values: Union[dict, tuple] = (), product_values: Union[dict, tuple] = ()

This class performs two types of matching:
  1. Index-based matching.
  2. Name-based matching < - far more reliable but difficult to implement
Source code in src/synthetic/Reaction.py
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
class Reaction: 
    '''
    This class represents a reaction in the system.
        ENSURE: use (a,) instead of (a) for tuples typing
        reaction_archtype: ReactionArchtype, 
        reactants: Tuple[str], 
        products: Tuple[str], 
        extra_states: Tuple[str] = (),
        parameters_values: Union[dict, tuple] = (),
        reactant_values: Union[dict, tuple] = (),
        product_values: Union[dict, tuple] = ()

    NOTE: This class performs two types of matching:
        1. Index-based matching.
        2. Name-based matching < - far more reliable but difficult to implement

    '''
    def __init__(self, 
        reaction_archtype: ReactionArchtype, 
        reactants: Tuple[str], 
        products: Tuple[str], 
        reaction_name: str = '',
        extra_states: Tuple[str] = (),
        parameters_values: Union[dict, tuple, int, float] = (),
        reactant_values: Union[dict, tuple, int, float] = (),
        product_values: Union[dict, tuple, int, float] = (),
        linked_parameters: Tuple[LinkedParameters] = (),
        use_parameter_from_reaction: str = '',
        zero_init: bool = True):

        self.archtype = reaction_archtype
        # reactants, products and extra states must be provided in the length of the archtype

        assert len(reactants) == reaction_archtype.reactants_count, f'length of reactants must be equal to the number of reactants in the reaction archtype, {len(reactants)} != {reaction_archtype.reactants_count}'
        assert len(products) == reaction_archtype.products_count, f'length of products must be equal to the number of products in the reaction archtype, {len(products)} != {reaction_archtype.products_count}'
        assert len(extra_states) == reaction_archtype.extra_states_count, f'length of extra_states must be equal to the number of extra_states in the reaction archtype, {len(extra_states)} != {reaction_archtype.extra_states_count}'

        self.name = reaction_name
        self.parameter_r_index = use_parameter_from_reaction

        # must specify reactant, product and extra state names if given in rate law
        self.reactants_names = reactants    
        self.products_names = products
        self.extra_states = extra_states

        # need to map reactant, product and extra state names to archtype names in 
        # the forms of dict 
        self.reactant_names_to_archtype_names = self._direct_tuples_to_dict(reactants, reaction_archtype.reactants)
        self.product_names_to_archtype_names = self._direct_tuples_to_dict(products, reaction_archtype.products)
        self.extra_states_names_to_archtype_names = self._direct_tuples_to_dict(extra_states, reaction_archtype.extra_states)

        # Compute regulator-parameter mapping
        self.regulator_parameters, self.parameter_regulators = self._compute_regulator_parameter_mapping()

        if zero_init: 
            reactant_values = {i: 0 for i in self.reactants_names}
            product_values = {i: 0 for i in self.products_names}

        # override values if provided
        self.parameters_values = self._unify_value_types_to_dict(parameters_values, self.archtype.parameters)
        self.reactant_values = self._unify_value_types_to_dict(reactant_values, reactants)
        self.product_values = self._unify_value_types_to_dict(product_values, products)

        if isinstance(parameters_values, dict):
            assert self._exist_in_archtype(parameters_values, self.archtype.parameters), 'parameters_values supplied in dict format must match the parameter names in the archtype'

        if isinstance(reactant_values, dict):
            assert self._dict_vals_exist_in_tuple(reactant_values, reactants), 'reactant_values supplied in dict format must match the reactant names in the reaction'

        if isinstance(product_values, dict):
            assert self._dict_vals_exist_in_tuple(product_values, products), 'product_values supplied in dict format must match the product names in the reaction'

        # checking assumed values existence for validation logic on reaction values assignment 

        assert len(self.parameters_values) == self.archtype.parameters_count or len(self.archtype.assume_parameters_values) > 0, f'Since, archtype do not have assumed parameters, length of parameters_values must be equal to the number of parameters in the reaction archtype, {len(parameters_values)} != {len(self.archtype.parameters)}'
        assert len(self.reactant_values) == self.archtype.reactants_count or len(self.archtype.assume_reactant_values) > 0, f'Since, archtype do not have assumed reactant values, length of reactant_values must be equal to the number of reactants in the reaction, {len(reactant_values)} != {len(reactants)}'
        assert len(self.product_values) == self.archtype.products_count or len(self.archtype.assume_product_values) > 0, f'Since, archtype do not have assumed product values, length of product_values must be equal to the number of products in the reaction, {len(product_values)} != {len(products)}'

        # reversibility unchangable in Reaction, but only in Archtype
        self.reversible = self.archtype.reversible

        # linked parameters

        self.linked_parameters = linked_parameters
        if self.exists_linked_parameters():
            assert len(self.linked_parameters) == self.archtype.parameters_count, f'length of linked_parameters must be equal to the number of parameters in the reaction archtype, {len(linked_parameters)} != {self.archtype.parameters_count}'

    def exists_linked_parameters(self) -> bool:
        return len(self.linked_parameters) > 0

    def _unify_value_types_to_dict(self, values: Union[dict, tuple, int, float], names: Tuple[str]) -> Dict[str, float]:
        '''
        unifies the value types to dict if not already in dict format
        '''
        if isinstance(values, dict):
            return values
        elif isinstance(values, tuple):
            return {names[i]: values[i] for i in range(len(values))}
        else:
            return {names[0]: values}

    def _dict_vals_exist_in_tuple(self, dict_vals: Dict[str, str], tuple_vals: Tuple[str]) -> bool:
        '''
        checks if all the values in the dict exist in the tuple
        '''
        for val in dict_vals.keys():
            if val not in tuple_vals:
                return False
        return True

    def _exist_in_archtype(self, reaction_dict: Dict[str, str], archtype_dict: Dict[str, str]) -> bool:
        '''
        checks if all the keys in the reaction dict exist in the archtype dict
        '''
        for key in reaction_dict:
            if key not in archtype_dict:
                return False
        return True

    def _direct_tuples_to_dict(self, reaction_tuple, archtype_tuple) -> Dict:
        '''
        maps a tuple of reaction-based names to the archtype-based names
        '''
        return {reaction_tuple[i]: archtype_tuple[i] for i in range(len(archtype_tuple))}

    def _compute_regulator_parameter_mapping(self):
        '''
        Compute mapping between regulators (extra_states) and parameters.
        Returns two dictionaries:
            regulator_parameters: mapping actual extra_state name -> list of parameter base names
            parameter_regulators: mapping parameter base name -> extra_state name
        '''
        regulator_parameters = {}
        parameter_regulators = {}
        # Prefix mapping based on ArchtypeCollections naming conventions
        # Map parameter prefix to possible extra_state prefix letters (without leading &/?)
        # Some parameter prefixes may map to multiple possibilities; we'll match the first that exists.
        prefix_map = {
            'Ka': ['A'],   # stimulators
            'Kc': ['W'],   # stimulator_weak
            'Ki': ['L', 'I'],   # allosteric_inhibitors (L) or mass action allo_inhibitors (I)
            'Kic': ['I'],  # competitive_inhibitors
            'Ks': ['A'],   # synthesis stimulators
            'Kw': ['W'],   # mass action additive stimulators
            'Kir': ['I'],  # reverse allosteric inhibitors
            'Kcr': ['C'],  # reverse competitive inhibitors
            'Kwr': ['W'],  # reverse additive stimulators
            'Ksr': ['A'],  # reverse stimulators
        }
        import re
        for param in self.archtype.parameters:
            # Extract prefix and optional numeric suffix
            match = re.match(r'([A-Za-z]+)(\d*)', param)
            if not match:
                continue
            prefix = match.group(1)
            suffix = match.group(2) if match.group(2) else ''
            if prefix in prefix_map:
                expected_prefix_list = prefix_map[prefix]
                # Find extra_state with matching suffix and prefix
                for arch_extra in self.archtype.extra_states:
                    es_match = re.match(r'([&?])([A-Za-z]+)(\d*)', arch_extra)
                    if es_match:
                        es_prefix = es_match.group(2)
                        es_suffix = es_match.group(3)
                        if es_suffix == suffix and es_prefix in expected_prefix_list:
                            # Map to actual extra_state name using extra_states_names_to_archtype_names inverse
                            actual_extra = None
                            for actual, arch in self.extra_states_names_to_archtype_names.items():
                                if arch == arch_extra:
                                    actual_extra = actual
                                    break
                            if actual_extra is not None:
                                regulator_parameters.setdefault(actual_extra, []).append(param)
                                parameter_regulators[param] = actual_extra
                            break
        return regulator_parameters, parameter_regulators

    def get_parameters_for_regulator(self, regulator_name: str) -> list:
        '''
        Returns list of parameter base names associated with the given regulator.
        '''
        return self.regulator_parameters.get(regulator_name, [])

    def get_regulator_for_parameter(self, param_name: str) -> str:
        '''
        Returns the regulator name associated with the given parameter base name.
        Returns empty string if no association.
        '''
        return self.parameter_regulators.get(param_name, '')

    def get_reaction_parameters(self, r_index) -> Dict[str, float]:
        '''
        returns a dictionary of the parameters in the reaction
        '''


        parameters = {}
        # linked parameters bypass the archtype parameters and are directly assigned
        # they will void r_index assignment completely
        if self.exists_linked_parameters():
            for i in range(len(self.linked_parameters)):
                parameters[str(self.linked_parameters[i])] = self.linked_parameters[i].get_value()
            return parameters

        if self.name != '':
            r_index = self.name

        # if parameter_r_index is not None, then the parameter values are assigned to the reaction
        # priority is above self.name assignment
        if self.parameter_r_index != '':
            r_index = self.parameter_r_index

        if len(self.archtype.assume_parameters_values) > 0: 
            # if the reaction archtype has parameters_values specified, use those
            # to create a dictionary 
            parameters = {f"{p}_{r_index}": 0 for p in self.archtype.parameters}
            for key, val in self.archtype.assume_parameters_values.items():
                parameters[f"{key}_{r_index}"] = val

        # override parameters if provided
        if len(self.parameters_values) > 0: 
            # if the specific reaction has parameters_values specified, 
            # it will override the default values
            if isinstance(self.parameters_values, dict):
                for key, val in self.parameters_values.items():
                    parameters[f"{key}_{r_index}"] = val

            else:
                raise ValueError('parameters_values must be a dictionary or tuple')

        return parameters

    def get_reaction_states(self) -> Dict[str, float]:

        '''
        Extracts state variables and their values from all reactions
        in the class and returns a dict, where state variables are 
        the reactants and products

        non-unique state variables will only be repeated once, their 
        default value will only follow the first repeated state variable
        '''

        states = {}
        for reactant in self.reactants_names:
            states[reactant] = self.archtype.assume_reactant_values[self.reactant_names_to_archtype_names[reactant]]
        for product in self.products_names:
            states[product] = self.archtype.assume_product_values[self.product_names_to_archtype_names[product]]

        # override values if provided
        if len(self.reactant_values) > 0:
            if isinstance(self.reactant_values, dict):
                for key, val in self.reactant_values.items():
                    states[key] = val
            else:
                raise ValueError('reactant_values must be a dictionary or tuple')

        if len(self.product_values) > 0:
            if isinstance(self.product_values, dict):
                for key, val in self.product_values.items():
                    states[key] = val 
            else:
                raise ValueError('product_values must be a dictionary or tuple')

        return states



    def get_antimony_reaction_str(self, r_index: str) -> str:
        '''
        generates an antimony string for the reaction, given the index of the reaction 
            r_index: str, represents reaction name in the system, usually an simple index 

        '''
        if self.name != '':
            r_index = self.name

        reactant_str = ' + '.join(self.reactants_names)
        product_str = ' + '.join(self.products_names)
        rate_law_str = self.archtype.rate_law 
        # rate law substitution needs to occur for reactants, products, extra states and parameters
        i = 0 
        while i < len(self.reactants_names):
            archtype_name = self.archtype.reactants[i]
            replacement_name = self.reactants_names[i]
            # Use regular expression to replace whole words only
            pattern = r'(?<!\w)' + re.escape(archtype_name) + r'(?!\w)'
            rate_law_str = re.sub(pattern, replacement_name, rate_law_str)
            i += 1 

        i = 0
        while i < len(self.products_names):
            archtype_name = self.archtype.products[i]
            replacement_name = self.products_names[i]
            # Use regular expression to replace whole words only
            pattern = r'(?<!\w)' + re.escape(archtype_name) + r'(?!\w)'
            rate_law_str = re.sub(pattern, replacement_name, rate_law_str)
            i += 1

        i = 0
        while i < len(self.archtype.extra_states):
            archtype_name = self.archtype.extra_states[i]
            replacement_name = self.extra_states[i]
            # Use regular expression to replace whole words only
            pattern = r'(?<!\w)' + re.escape(archtype_name) + r'(?!\w)'
            rate_law_str = re.sub(pattern, replacement_name, rate_law_str)
            i += 1


        i = 0
        while i < len(self.archtype.extra_states):
            archtype_name = self.archtype.extra_states[i]
            replacement_name = self.extra_states[i]
            # Use regular expression to replace whole words only
            pattern = r'(?<!\w)' + re.escape(archtype_name) + r'(?!\w)'
            rate_law_str = re.sub(pattern, replacement_name, rate_law_str)
            i += 1

        r_index_p = r_index 
        if self.parameter_r_index != '':
            r_index_p = self.parameter_r_index

        i = 0
        while i < len(self.archtype.parameters):
            archtype_name = self.archtype.parameters[i]
            if self.exists_linked_parameters():
                replacement_name = str(self.linked_parameters[i])
            else: 
                replacement_name = archtype_name + '_' + r_index_p
            # Use regular expression to replace whole words only
            pattern = r'(?<!\w)' + re.escape(archtype_name) + r'(?!\w)'
            rate_law_str = re.sub(pattern, replacement_name, rate_law_str)
            i += 1

        return f'{r_index}: {reactant_str} -> {product_str}; {rate_law_str}'

    def get_antimony_reactions_reverse_str(self, r_index: str) -> str:
        '''
        generates an antimony string for the reverse reaction, given the index of the reaction 
            r_index: str, represents reaction name in the system, usually an simple index 

        '''
        if self.name != '':
            r_index = self.name

        reactant_str = ' + '.join(self.reactants_names)
        product_str = ' + '.join(self.products_names)
        rate_law_str = self.archtype.reverse_rate_law 
        # rate law substitution needs to occur for reactants, products, extra states and parameters
        i = 0 
        while i < len(self.reactants_names):
            archtype_name = self.archtype.reactants[i]
            replacement_name = self.reactants_names[i]
            # Use regular expression to replace whole words only
            pattern = r'(?<!\w)' + re.escape(archtype_name) + r'(?!\w)'
            rate_law_str = re.sub(pattern, replacement_name, rate_law_str)
            i += 1 

        i = 0
        while i < len(self.products_names):
            archtype_name = self.archtype.products[i]
            replacement_name = self.products_names[i]
            # Use regular expression to replace whole words only
            pattern = r'(?<!\w)' + re.escape(archtype_name) + r'(?!\w)'
            rate_law_str = re.sub(pattern, replacement_name, rate_law_str)
            i += 1


        i = 0
        while i < len(self.archtype.extra_states):
            archtype_name = self.archtype.extra_states[i]
            replacement_name = self.extra_states[i]
            # Use regular expression to replace whole words only
            pattern = r'(?<!\w)' + re.escape(archtype_name) + r'(?!\w)'
            rate_law_str = re.sub(pattern, replacement_name, rate_law_str)
            i += 1

        r_index_p = r_index 
        if self.parameter_r_index != '':
            r_index_p = self.parameter_r_index

        i = 0
        while i < len(self.archtype.parameters):
            archtype_name = self.archtype.parameters[i]
            if self.exists_linked_parameters():
                replacement_name = str(self.linked_parameters[i])
            else:
                replacement_name = archtype_name + "_" + r_index_p
            # Use regular expression to replace whole words only
            pattern = r'(?<!\w)' + re.escape(archtype_name) + r'(?!\w)'
            rate_law_str = re.sub(pattern, replacement_name, rate_law_str)
            i += 1

        return f'{r_index}r: {product_str} -> {reactant_str}; {rate_law_str}'

    def copy(self) -> 'Reaction':
        '''
        returns a copy of the reaction
        '''
        return copy(self)


    def __str__(self) -> str:

        if self.archtype.reversible:
            return self.get_antimony_reaction_str(r_index='for') + '\n' + self.get_antimony_reactions_reverse_str(r_index='rev')

        return self.get_antimony_reaction_str(r_index='react' if self.name == '' else self.name)

copy() -> Reaction

returns a copy of the reaction

Source code in src/synthetic/Reaction.py
403
404
405
406
407
def copy(self) -> 'Reaction':
    '''
    returns a copy of the reaction
    '''
    return copy(self)

get_antimony_reaction_str(r_index: str) -> str

generates an antimony string for the reaction, given the index of the reaction r_index: str, represents reaction name in the system, usually an simple index

Source code in src/synthetic/Reaction.py
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
def get_antimony_reaction_str(self, r_index: str) -> str:
    '''
    generates an antimony string for the reaction, given the index of the reaction 
        r_index: str, represents reaction name in the system, usually an simple index 

    '''
    if self.name != '':
        r_index = self.name

    reactant_str = ' + '.join(self.reactants_names)
    product_str = ' + '.join(self.products_names)
    rate_law_str = self.archtype.rate_law 
    # rate law substitution needs to occur for reactants, products, extra states and parameters
    i = 0 
    while i < len(self.reactants_names):
        archtype_name = self.archtype.reactants[i]
        replacement_name = self.reactants_names[i]
        # Use regular expression to replace whole words only
        pattern = r'(?<!\w)' + re.escape(archtype_name) + r'(?!\w)'
        rate_law_str = re.sub(pattern, replacement_name, rate_law_str)
        i += 1 

    i = 0
    while i < len(self.products_names):
        archtype_name = self.archtype.products[i]
        replacement_name = self.products_names[i]
        # Use regular expression to replace whole words only
        pattern = r'(?<!\w)' + re.escape(archtype_name) + r'(?!\w)'
        rate_law_str = re.sub(pattern, replacement_name, rate_law_str)
        i += 1

    i = 0
    while i < len(self.archtype.extra_states):
        archtype_name = self.archtype.extra_states[i]
        replacement_name = self.extra_states[i]
        # Use regular expression to replace whole words only
        pattern = r'(?<!\w)' + re.escape(archtype_name) + r'(?!\w)'
        rate_law_str = re.sub(pattern, replacement_name, rate_law_str)
        i += 1


    i = 0
    while i < len(self.archtype.extra_states):
        archtype_name = self.archtype.extra_states[i]
        replacement_name = self.extra_states[i]
        # Use regular expression to replace whole words only
        pattern = r'(?<!\w)' + re.escape(archtype_name) + r'(?!\w)'
        rate_law_str = re.sub(pattern, replacement_name, rate_law_str)
        i += 1

    r_index_p = r_index 
    if self.parameter_r_index != '':
        r_index_p = self.parameter_r_index

    i = 0
    while i < len(self.archtype.parameters):
        archtype_name = self.archtype.parameters[i]
        if self.exists_linked_parameters():
            replacement_name = str(self.linked_parameters[i])
        else: 
            replacement_name = archtype_name + '_' + r_index_p
        # Use regular expression to replace whole words only
        pattern = r'(?<!\w)' + re.escape(archtype_name) + r'(?!\w)'
        rate_law_str = re.sub(pattern, replacement_name, rate_law_str)
        i += 1

    return f'{r_index}: {reactant_str} -> {product_str}; {rate_law_str}'

get_antimony_reactions_reverse_str(r_index: str) -> str

generates an antimony string for the reverse reaction, given the index of the reaction r_index: str, represents reaction name in the system, usually an simple index

Source code in src/synthetic/Reaction.py
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
def get_antimony_reactions_reverse_str(self, r_index: str) -> str:
    '''
    generates an antimony string for the reverse reaction, given the index of the reaction 
        r_index: str, represents reaction name in the system, usually an simple index 

    '''
    if self.name != '':
        r_index = self.name

    reactant_str = ' + '.join(self.reactants_names)
    product_str = ' + '.join(self.products_names)
    rate_law_str = self.archtype.reverse_rate_law 
    # rate law substitution needs to occur for reactants, products, extra states and parameters
    i = 0 
    while i < len(self.reactants_names):
        archtype_name = self.archtype.reactants[i]
        replacement_name = self.reactants_names[i]
        # Use regular expression to replace whole words only
        pattern = r'(?<!\w)' + re.escape(archtype_name) + r'(?!\w)'
        rate_law_str = re.sub(pattern, replacement_name, rate_law_str)
        i += 1 

    i = 0
    while i < len(self.products_names):
        archtype_name = self.archtype.products[i]
        replacement_name = self.products_names[i]
        # Use regular expression to replace whole words only
        pattern = r'(?<!\w)' + re.escape(archtype_name) + r'(?!\w)'
        rate_law_str = re.sub(pattern, replacement_name, rate_law_str)
        i += 1


    i = 0
    while i < len(self.archtype.extra_states):
        archtype_name = self.archtype.extra_states[i]
        replacement_name = self.extra_states[i]
        # Use regular expression to replace whole words only
        pattern = r'(?<!\w)' + re.escape(archtype_name) + r'(?!\w)'
        rate_law_str = re.sub(pattern, replacement_name, rate_law_str)
        i += 1

    r_index_p = r_index 
    if self.parameter_r_index != '':
        r_index_p = self.parameter_r_index

    i = 0
    while i < len(self.archtype.parameters):
        archtype_name = self.archtype.parameters[i]
        if self.exists_linked_parameters():
            replacement_name = str(self.linked_parameters[i])
        else:
            replacement_name = archtype_name + "_" + r_index_p
        # Use regular expression to replace whole words only
        pattern = r'(?<!\w)' + re.escape(archtype_name) + r'(?!\w)'
        rate_law_str = re.sub(pattern, replacement_name, rate_law_str)
        i += 1

    return f'{r_index}r: {product_str} -> {reactant_str}; {rate_law_str}'

get_parameters_for_regulator(regulator_name: str) -> list

Returns list of parameter base names associated with the given regulator.

Source code in src/synthetic/Reaction.py
185
186
187
188
189
def get_parameters_for_regulator(self, regulator_name: str) -> list:
    '''
    Returns list of parameter base names associated with the given regulator.
    '''
    return self.regulator_parameters.get(regulator_name, [])

get_reaction_parameters(r_index) -> Dict[str, float]

returns a dictionary of the parameters in the reaction

Source code in src/synthetic/Reaction.py
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
def get_reaction_parameters(self, r_index) -> Dict[str, float]:
    '''
    returns a dictionary of the parameters in the reaction
    '''


    parameters = {}
    # linked parameters bypass the archtype parameters and are directly assigned
    # they will void r_index assignment completely
    if self.exists_linked_parameters():
        for i in range(len(self.linked_parameters)):
            parameters[str(self.linked_parameters[i])] = self.linked_parameters[i].get_value()
        return parameters

    if self.name != '':
        r_index = self.name

    # if parameter_r_index is not None, then the parameter values are assigned to the reaction
    # priority is above self.name assignment
    if self.parameter_r_index != '':
        r_index = self.parameter_r_index

    if len(self.archtype.assume_parameters_values) > 0: 
        # if the reaction archtype has parameters_values specified, use those
        # to create a dictionary 
        parameters = {f"{p}_{r_index}": 0 for p in self.archtype.parameters}
        for key, val in self.archtype.assume_parameters_values.items():
            parameters[f"{key}_{r_index}"] = val

    # override parameters if provided
    if len(self.parameters_values) > 0: 
        # if the specific reaction has parameters_values specified, 
        # it will override the default values
        if isinstance(self.parameters_values, dict):
            for key, val in self.parameters_values.items():
                parameters[f"{key}_{r_index}"] = val

        else:
            raise ValueError('parameters_values must be a dictionary or tuple')

    return parameters

get_reaction_states() -> Dict[str, float]

Extracts state variables and their values from all reactions in the class and returns a dict, where state variables are the reactants and products

non-unique state variables will only be repeated once, their default value will only follow the first repeated state variable

Source code in src/synthetic/Reaction.py
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
def get_reaction_states(self) -> Dict[str, float]:

    '''
    Extracts state variables and their values from all reactions
    in the class and returns a dict, where state variables are 
    the reactants and products

    non-unique state variables will only be repeated once, their 
    default value will only follow the first repeated state variable
    '''

    states = {}
    for reactant in self.reactants_names:
        states[reactant] = self.archtype.assume_reactant_values[self.reactant_names_to_archtype_names[reactant]]
    for product in self.products_names:
        states[product] = self.archtype.assume_product_values[self.product_names_to_archtype_names[product]]

    # override values if provided
    if len(self.reactant_values) > 0:
        if isinstance(self.reactant_values, dict):
            for key, val in self.reactant_values.items():
                states[key] = val
        else:
            raise ValueError('reactant_values must be a dictionary or tuple')

    if len(self.product_values) > 0:
        if isinstance(self.product_values, dict):
            for key, val in self.product_values.items():
                states[key] = val 
        else:
            raise ValueError('product_values must be a dictionary or tuple')

    return states

get_regulator_for_parameter(param_name: str) -> str

Returns the regulator name associated with the given parameter base name. Returns empty string if no association.

Source code in src/synthetic/Reaction.py
191
192
193
194
195
196
def get_regulator_for_parameter(self, param_name: str) -> str:
    '''
    Returns the regulator name associated with the given parameter base name.
    Returns empty string if no association.
    '''
    return self.parameter_regulators.get(param_name, '')

synthetic.ReactionArchtype.ReactionArchtype

ReactionArchtype is a factory class that generates Reaction objects name: str, reactants: Tuple[str], products: Tuple[str], parameters: Tuple[str], rate_law: str, extra_states: Tuple[str] = (), assume_parameters_values: Union[dict, tuple] = None, assume_reactant_values: Union[dict, tuple] = None, assume_product_values: Union[dict, tuple] = None

Source code in src/synthetic/ReactionArchtype.py
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
class ReactionArchtype:

    '''
    ReactionArchtype is a factory class that generates Reaction objects
        name: str, 
        reactants: Tuple[str], 
        products: Tuple[str], 
        parameters: Tuple[str], 
        rate_law: str, 
        extra_states: Tuple[str] = (),
        assume_parameters_values: Union[dict, tuple] = None,
        assume_reactant_values: Union[dict, tuple] = None,
        assume_product_values: Union[dict, tuple] = None
    '''

    def __init__(self, 
        name: str, 
        reactants: Tuple[str], 
        products: Tuple[str], 
        parameters: Tuple[str], 
        rate_law: str, 
        extra_states: Tuple[str] = (),
        assume_parameters_values: Union[dict, tuple, None] = None,
        assume_reactant_values: Union[dict, tuple, None] = None,
        assume_product_values: Union[dict, tuple, None] = None,
        reversible: bool = False,
        reverse_rate_law: str = None):

        assert len(reactants) == len(set(reactants)), 'reactants must be unique'
        assert len(products) == 0 or len(products) == len(set(products)), 'products must be unique'
        assert len(parameters) == len(set(parameters)), 'parameters must be unique'
        assert len(extra_states) == len(set(extra_states)), 'extra_states must be unique'
        assert reversible is False or reverse_rate_law is not None, 'reverse_rate_law must be provided if reversible is True'

        self.name = name
        self.reactants = reactants
        self.products = products
        self.parameters = parameters
        self.extra_states = extra_states
        self.rate_law = rate_law

        # reverse reaction between reactants and products
        self.reversible = reversible
        self.reverse_rate_law = reverse_rate_law

        self.reactants_count = len(reactants)
        self.products_count = len(products)
        self.state_variables_count = len(reactants) + len(products)
        self.extra_states_count = len(extra_states)
        self.parameters_count = len(parameters)

        if reversible:
            self.validate_rate_laws(rate_law, reverse_rate_law)
        else:
            self.validate_rate_law(rate_law)
        self.validate_parameters(assume_parameters_values, parameters)
        self.validate_reactant_values(assume_reactant_values, reactants)
        self.validate_product_values(assume_product_values, products)

        # assumed values are used to fill in the missing values in the rate law
        # always update None or tuple into dict objects, so that Reaction class
        # only uses dict to handle assumed values logic 
        self.assume_parameters_values = self._convert_tuple_to_dict(assume_parameters_values, parameters)
        self.assume_reactant_values = self._convert_tuple_to_dict(assume_reactant_values, reactants)
        self.assume_product_values = self._convert_tuple_to_dict(assume_product_values, products)



    def _convert_tuple_to_dict(self, tuple: Union[dict, tuple, None], reference_tuple: Tuple[str]) -> dict:
        '''
        this function converts a tuple to a dict by 
        referring i-th element in the tuple to the i-th element in the reference_tuple
        '''
        # do not do anything if tuple is dict 
        if isinstance(tuple, dict):
            return tuple

        if tuple is None:
            return {}
        elif len(tuple) == 0: 
            return {}

        new_dict = {}
        for idx, value in enumerate(tuple):
            key = reference_tuple[idx]
            new_dict[key] = value

        return new_dict


    def validate_rate_law(self, rate_law) -> bool:
        '''
        this function validates the rate_law against the archtype
            It expects the rate_law to contain the parameters
            It expects the rate_law to contain the extra states
            ^ copilot generated
        '''

        for parameter in self.parameters:
            if rate_law.find(parameter) == -1:
                raise ValueError(f'{parameter} is not in the rate law')

        for extra_state in self.extra_states:
            if rate_law.find(extra_state) == -1:
                raise ValueError(f'{extra_state} is not in the rate law')

        return True

    def validate_rate_laws(self, rate_law, reverse_rate_law) -> bool:
        '''
        this function validates the rate_law against the archtype
            It expects the rate_law to contain the parameters
            It expects the rate_law to contain the extra states
            ^ copilot generated
        '''

        for parameter in self.parameters:
            if rate_law.find(parameter) == -1 and reverse_rate_law.find(parameter) == -1:
                raise ValueError(f'{parameter} is not in the rate law or reverse rate law')

        for extra_state in self.extra_states:
            if rate_law.find(extra_state) == -1 and reverse_rate_law.find(extra_state) == -1:
                raise ValueError(f'{extra_state} is not in the rate law or reverse rate law')

        return True

    def _abstract_validate_values(self, values: Union[tuple, dict, None], contained_list: Tuple) -> bool:

        '''
        this function validates the values against the archtype
        if values is tuple: 
            then it needs to be smaller than the number of [reactants, products, parameters] in the archtype
            assume first element in tuple matches with first element in self.parameters

        if values is dict:
            then it needs to be smaller than the number of [reactants, products, parameters] in the archtype
            cannot have dict keys that are not in self.parameters 

        '''

        if values is None:
            return True

        if len(values) != len(contained_list):
                raise ValueError(f'length of {values} is not the same as the archtype {contained_list}')

        if isinstance(values, dict):
            for key in values:
                if key not in contained_list:
                    raise ValueError(f'{key} is not in the {contained_list}')

        return True

    def validate_parameters(self, parameter_values, parameters_list) -> bool:

        '''
        Delegate to abstract implementation at _abstract_validate_values 
        '''

        return self._abstract_validate_values(parameter_values, parameters_list)


    def validate_reactant_values(self, reactant_values, reactant_list) -> bool:

        '''
        Delegate to abstract implementation at _abstract_validate_values 
        '''

        return self._abstract_validate_values(reactant_values, reactant_list)


    def validate_product_values(self, product_values, products_list) -> bool:

        '''
        Delegate to abstract implementation at _abstract_validate_values 
        '''

        return self._abstract_validate_values(product_values, products_list)


    def __str__(self) -> str:
        return f'{self.name} {self.reactants} {self.products} {self.parameters} {self.rate_law}'

validate_parameters(parameter_values, parameters_list) -> bool

Delegate to abstract implementation at _abstract_validate_values

Source code in src/synthetic/ReactionArchtype.py
156
157
158
159
160
161
162
def validate_parameters(self, parameter_values, parameters_list) -> bool:

    '''
    Delegate to abstract implementation at _abstract_validate_values 
    '''

    return self._abstract_validate_values(parameter_values, parameters_list)

validate_product_values(product_values, products_list) -> bool

Delegate to abstract implementation at _abstract_validate_values

Source code in src/synthetic/ReactionArchtype.py
174
175
176
177
178
179
180
def validate_product_values(self, product_values, products_list) -> bool:

    '''
    Delegate to abstract implementation at _abstract_validate_values 
    '''

    return self._abstract_validate_values(product_values, products_list)

validate_rate_law(rate_law) -> bool

this function validates the rate_law against the archtype It expects the rate_law to contain the parameters It expects the rate_law to contain the extra states ^ copilot generated

Source code in src/synthetic/ReactionArchtype.py
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
def validate_rate_law(self, rate_law) -> bool:
    '''
    this function validates the rate_law against the archtype
        It expects the rate_law to contain the parameters
        It expects the rate_law to contain the extra states
        ^ copilot generated
    '''

    for parameter in self.parameters:
        if rate_law.find(parameter) == -1:
            raise ValueError(f'{parameter} is not in the rate law')

    for extra_state in self.extra_states:
        if rate_law.find(extra_state) == -1:
            raise ValueError(f'{extra_state} is not in the rate law')

    return True

validate_rate_laws(rate_law, reverse_rate_law) -> bool

this function validates the rate_law against the archtype It expects the rate_law to contain the parameters It expects the rate_law to contain the extra states ^ copilot generated

Source code in src/synthetic/ReactionArchtype.py
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
def validate_rate_laws(self, rate_law, reverse_rate_law) -> bool:
    '''
    this function validates the rate_law against the archtype
        It expects the rate_law to contain the parameters
        It expects the rate_law to contain the extra states
        ^ copilot generated
    '''

    for parameter in self.parameters:
        if rate_law.find(parameter) == -1 and reverse_rate_law.find(parameter) == -1:
            raise ValueError(f'{parameter} is not in the rate law or reverse rate law')

    for extra_state in self.extra_states:
        if rate_law.find(extra_state) == -1 and reverse_rate_law.find(extra_state) == -1:
            raise ValueError(f'{extra_state} is not in the rate law or reverse rate law')

    return True

validate_reactant_values(reactant_values, reactant_list) -> bool

Delegate to abstract implementation at _abstract_validate_values

Source code in src/synthetic/ReactionArchtype.py
165
166
167
168
169
170
171
def validate_reactant_values(self, reactant_values, reactant_list) -> bool:

    '''
    Delegate to abstract implementation at _abstract_validate_values 
    '''

    return self._abstract_validate_values(reactant_values, reactant_list)

Specifications

Classes for defining network topology, regulations, and drug interactions. See Model Building for details.

synthetic.Specs.BaseSpec.BaseSpec

Bases: ABC

Minimal abstract model specification. Contains only the essential contract for generating models. At the core, generate specifications takes in specific inputs from the user, which is then used to infer the regulation list.

Attributes:

Name Type Description
regulations List[Regulation]

List of regulations applicable to the model.

Source code in src/synthetic/Specs/BaseSpec.py
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
class BaseSpec(ABC):
    """
    Minimal abstract model specification. Contains only the essential contract for generating models.
    At the core, generate specifications takes in specific inputs from the user, which is then 
    used to infer the regulation list. 

    Attributes:
        regulations (List[Regulation]): List of regulations applicable to the model.
    """

    # Core regulation storage 
    regulations: List[Regulation]
    species_list: List[str]

    def __init__(self):
        self.regulations = [] 
        self.species_list = [] # this will be the final list of species in the model

    @abstractmethod
    def generate_specifications(self, **kwargs):
        """
        Populate the specification's internal state.
        This includes species lists and regulations based on the specific model type.
        """
        pass

    @abstractmethod
    def generate_network(self, network_name: str, **kwargs) -> ModelBuilder:
        """
        Generate a complete ModelBuilder instance from the specification.
        """
        pass

generate_network(network_name: str, **kwargs) -> ModelBuilder abstractmethod

Generate a complete ModelBuilder instance from the specification.

Source code in src/synthetic/Specs/BaseSpec.py
33
34
35
36
37
38
@abstractmethod
def generate_network(self, network_name: str, **kwargs) -> ModelBuilder:
    """
    Generate a complete ModelBuilder instance from the specification.
    """
    pass

generate_specifications(**kwargs) abstractmethod

Populate the specification's internal state. This includes species lists and regulations based on the specific model type.

Source code in src/synthetic/Specs/BaseSpec.py
25
26
27
28
29
30
31
@abstractmethod
def generate_specifications(self, **kwargs):
    """
    Populate the specification's internal state.
    This includes species lists and regulations based on the specific model type.
    """
    pass

synthetic.Specs.DegreeInteractionSpec.DegreeInteractionSpec

Bases: MichaelisNetworkSpec

Multi-degree drug interaction network specification.

Generates networks with hierarchical degrees of interaction: - Degree 1: D -> {R} -> {I} -> O (central pathway) - Degrees 2+: R -> I only (independent cascades influencing lower degrees)

Each degree contains multiple cascades defined by degree_cascades list. Higher degrees provide feedback regulation to immediate lower degrees.

Example

spec = DegreeInteractionSpec(degree_cascades=[1, 2, 5, 10]) spec.generate_specifications(random_seed=42) model = spec.generate_network("multi_degree_network")

Source code in src/synthetic/Specs/DegreeInteractionSpec.py
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
class DegreeInteractionSpec(MichaelisNetworkSpec):
    """
    Multi-degree drug interaction network specification.

    Generates networks with hierarchical degrees of interaction:
    - Degree 1: D -> {R} -> {I} -> O (central pathway)
    - Degrees 2+: R -> I only (independent cascades influencing lower degrees)

    Each degree contains multiple cascades defined by degree_cascades list.
    Higher degrees provide feedback regulation to immediate lower degrees.

    Example:
        spec = DegreeInteractionSpec(degree_cascades=[1, 2, 5, 10])
        spec.generate_specifications(random_seed=42)
        model = spec.generate_network("multi_degree_network")
    """

    def __init__(self, degree_cascades: List[int], critical_pathways: Optional[int] = None):
        """
        Initialize degree interaction specification.

        Args:
            degree_cascades: List of cascade counts per degree, e.g., [1, 2, 5, 10]
            critical_pathways: Optional override for degree 1 cascade count
        """
        super().__init__()
        # Validate inputs before accessing degree_cascades[0]
        if len(degree_cascades) < 1:
            raise ValueError("degree_cascades must contain at least one element")

        self.degree_cascades = degree_cascades
        self.critical_pathways = critical_pathways or degree_cascades[0]
        self.degree_species: Dict[int, Dict[str, List[str]]] = {}  # {degree: {'R': [...], 'I': [...]}}
        self.degree_regulations: Dict[int, List[Regulation]] = {}  # Regulations per degree
        self._logger = logging.getLogger(__name__)

        if self.critical_pathways != degree_cascades[0]:
            self._logger.warning(f"critical_pathways ({self.critical_pathways}) differs from degree_cascades[0] ({degree_cascades[0]})")

    def generate_species_names(self) -> None:
        """
        Generate species names for all degrees based on cascade counts.
        Follows naming convention: R{degree}_{index}, I{degree}_{index}
        """
        self.degree_species.clear()

        for deg_idx, cascade_count in enumerate(self.degree_cascades):
            degree = deg_idx + 1  # 1-indexed degrees
            r_species = []
            i_species = []

            for cascade_idx in range(cascade_count):
                r_name = f"R{degree}_{cascade_idx + 1}"
                i_name = f"I{degree}_{cascade_idx + 1}"
                r_species.append(r_name)
                i_species.append(i_name)

                # Add to global species list
                self.add_species(r_name, group=f"degree_{degree}")
                self.add_species(i_name, group=f"degree_{degree}")

            self.degree_species[degree] = {'R': r_species, 'I': i_species}

        # Add outcome species O (only one)
        self.add_species("O", group="outcome")

    def generate_ordinary_regulations(self) -> None:
        """
        Generate ordinary regulations within each cascade:
        - Degree 1: R_i -> I_i, I_i -> O
        - Degrees 2+: R_i -> I_i only
        """
        self.degree_regulations.clear()

        for degree, species_dict in self.degree_species.items():
            degree_regs = []
            r_species = species_dict['R']
            i_species = species_dict['I']

            # Each cascade: R_i -> I_i
            for r_name, i_name in zip(r_species, i_species):
                reg = Regulation(from_specie=r_name, to_specie=i_name, reg_type='up')
                self.regulations.append(reg)
                degree_regs.append(reg)

            # Degree 1: I_i -> O
            if degree == 1:
                for i_name in i_species:
                    reg = Regulation(from_specie=i_name, to_specie='O', reg_type='up')
                    self.regulations.append(reg)
                    degree_regs.append(reg)

            self.degree_regulations[degree] = degree_regs

        # Track ordinary regulations (non-feedback)
        self.ordinary_regulations = self.regulations.copy()

    def generate_feedback_regulations(self, random_seed: Optional[int] = None, 
                                     feedback_density: float = 0.5) -> None:
        """
        Generate feedback regulations between adjacent degrees following structured rules.

        Rules:
        1. Downward regulations (n -> n-1): MANDATORY
           - For each cascade i in degree n > 1:
             - Regulator: I{n}_i (I species of that cascade)
             - Target: Random R or I species in degree (n-1)
             - Type: Random 'up' or 'down'

        2. Upward regulations (n-1 -> n): DENSITY-CONTROLLED
           - For each cascade i in degree n > 1:
             - Create candidate regulation:
               - Regulator: Random R or I species in degree (n-1)
               - Target: Random R{n}_i or I{n}_i
               - Type: Random 'up' or 'down'
           - Trim from outermost degrees first:
             - Keep only floor(feedback_density * cascade_count) upward regulations per degree
             - Randomly select which cascades keep their upward regulation

        Args:
            random_seed: Random seed for reproducibility
            feedback_density: Proportion of upward regulations to keep (0-1)
                - 0: No upward regulations
                - 1: All cascades get upward regulation
                - (0,1): Random subset based on density
        """
        if random_seed is not None:
            rng = np.random.default_rng(random_seed)
        else:
            rng = np.random.default_rng()

        # Clear existing feedback regulations
        self.feedback_regulations = []

        # Store candidate upward regulations by degree for trimming
        upward_candidates_by_degree: Dict[int, List[Tuple[int, Regulation]]] = {}
        # (degree, (cascade_index, regulation))

        # Helper function to check if regulation already exists
        def regulation_exists(regulator: str, target: str) -> bool:
            return any(
                r.from_specie == regulator and r.to_specie == target
                for r in self.regulations + self.feedback_regulations
            )

        # Generate regulations for each degree n > 1
        for degree in range(2, len(self.degree_cascades) + 1):
            prev_degree = degree - 1

            # Get species from both degrees
            prev_r_species = self.degree_species[prev_degree]['R']
            prev_i_species = self.degree_species[prev_degree]['I']
            prev_all_species = prev_r_species + prev_i_species

            curr_r_species = self.degree_species[degree]['R']
            curr_i_species = self.degree_species[degree]['I']
            curr_all_species = curr_r_species + curr_i_species

            if not prev_all_species or not curr_all_species:
                continue

            cascade_count = len(curr_r_species)  # Should be same as len(curr_i_species)
            upward_candidates_by_degree[degree] = []

            # 1. MANDATORY DOWNWARD REGULATIONS (n -> n-1)
            for i in range(cascade_count):
                regulator = curr_i_species[i]  # I{degree}_{i+1}

                # Randomly select target from previous degree
                target = rng.choice(prev_all_species)
                reg_type = rng.choice(['up', 'down'])

                # Ensure no duplicate regulation
                attempts = 0
                while regulation_exists(regulator, target) and attempts < 10:
                    target = rng.choice(prev_all_species)
                    attempts += 1

                reg = Regulation(from_specie=regulator, to_specie=target, reg_type=reg_type)
                self.regulations.append(reg)
                self.feedback_regulations.append(reg)

            # 2. CREATE CANDIDATE UPWARD REGULATIONS (n-1 -> n)
            for i in range(cascade_count):
                # Randomly select regulator from previous degree
                regulator = rng.choice(prev_all_species)

                # Randomly select target from current cascade (R or I)
                target_options = [curr_r_species[i], curr_i_species[i]]
                target = rng.choice(target_options)

                reg_type = rng.choice(['up', 'down'])

                # Ensure no duplicate regulation
                attempts = 0
                while regulation_exists(regulator, target) and attempts < 10:
                    regulator = rng.choice(prev_all_species)
                    target = rng.choice(target_options)
                    attempts += 1

                reg = Regulation(from_specie=regulator, to_specie=target, reg_type=reg_type)
                upward_candidates_by_degree[degree].append((i, reg))

        # 3. TRIM UPWARD REGULATIONS FROM OUTERMOST DEGREES FIRST
        # Process degrees from highest to lowest
        degrees_sorted = sorted(upward_candidates_by_degree.keys(), reverse=True)

        for degree in degrees_sorted:
            candidates = upward_candidates_by_degree[degree]
            if not candidates:
                continue

            cascade_count = len(self.degree_species[degree]['R'])

            # Calculate how many upward regulations to keep
            if feedback_density <= 0:
                # No upward regulations
                continue
            elif feedback_density >= 1:
                # Keep all upward regulations
                num_to_keep = len(candidates)
            else:
                # Keep proportion based on density
                num_to_keep = max(1, int(feedback_density * cascade_count))
                num_to_keep = min(num_to_keep, len(candidates))

            # Randomly select which cascades keep their upward regulation
            # We want to select num_to_keep unique cascade indices
            cascade_indices = list(set(idx for idx, _ in candidates))
            if len(cascade_indices) > num_to_keep:
                keep_indices = set(rng.choice(cascade_indices, size=num_to_keep, replace=False))
            else:
                keep_indices = set(cascade_indices)

            # Add kept regulations
            for cascade_idx, reg in candidates:
                if cascade_idx in keep_indices:
                    self.regulations.append(reg)
                    self.feedback_regulations.append(reg)

            self._logger.debug(
                f"Degree {degree}: Kept {len(keep_indices)}/{cascade_count} upward regulations "
                f"(density={feedback_density})"
            )

        self._logger.info(
            f"Generated {len(self.feedback_regulations)} feedback regulations "
            f"(density={feedback_density})"
        )

    def generate_specifications(self, random_seed: Optional[int] = None, 
                               feedback_density: float = 0.5, **kwargs):
        """
        Generate complete network specifications.

        Args:
            random_seed: Random seed for reproducibility
            feedback_density: Proportion of feedback connections to create (0-1)
            **kwargs: Additional arguments (unused, for compatibility)
        """
        # Clear existing state
        self.regulations = []
        self.species_list = []
        self.species_groups = {}
        self.ordinary_regulations = []
        self.feedback_regulations = []
        self.drugs = []
        self.drug_values = {}

        # Generate species and regulations
        self.generate_species_names()
        self.generate_ordinary_regulations()
        self.generate_feedback_regulations(random_seed, feedback_density)

        self._logger.info(
            f"Generated {len(self.degree_cascades)}-degree network with "
            f"{len(self.species_list)} species and {len(self.regulations)} regulations"
        )

    def add_drug(self, drug: Drug, value: Optional[float] = None):
        """
        Add a drug to the model, validating it only targets degree 1 R species.

        Args:
            drug: Drug object containing name, start_time, default_value, and regulations
            value: Optional override for drug value

        Raises:
            ValueError: If drug targets non-degree-1 species or non-R species
        """
        # Validate drug targets
        for target_species in drug.regulation:
            # Check if target is a degree 1 R species
            is_degree1_r = any(
                target_species == r_name 
                for r_name in self.degree_species.get(1, {}).get('R', [])
            )

            if not is_degree1_r:
                raise ValueError(
                    f"Drug {drug.name} can only target degree 1 R species. "
                    f"Invalid target: {target_species}"
                )

        # Call parent method
        super().add_drug(drug, value)

    def get_species_by_degree(self, degree: int, species_type: str = 'all') -> List[str]:
        """
        Get species for a specific degree.

        Args:
            degree: Degree number (1-indexed)
            species_type: 'R', 'I', or 'all'

        Returns:
            List of species names
        """
        if degree not in self.degree_species:
            return []

        species_dict = self.degree_species[degree]
        if species_type == 'R':
            return species_dict['R']
        elif species_type == 'I':
            return species_dict['I']
        elif species_type == 'all':
            return species_dict['R'] + species_dict['I']
        else:
            raise ValueError("species_type must be 'R', 'I', or 'all'")

    def get_regulations_by_degree(self, degree: Optional[int] = None) -> List[Regulation]:
        """
        Get regulations for a specific degree or all degrees.

        Args:
            degree: Degree number (1-indexed) or None for all

        Returns:
            List of Regulation objects
        """
        if degree is None:
            return self.regulations.copy()
        elif degree in self.degree_regulations:
            return self.degree_regulations[degree].copy()
        else:
            return []

    def get_total_species_count(self) -> int:
        """Get total number of species in the network."""
        return len(self.species_list)

    def get_total_cascades(self) -> int:
        """Get total number of cascades across all degrees."""
        return sum(self.degree_cascades)

    def __str__(self) -> str:
        """String representation of the specification."""
        return (f"DegreeInteractionSpec(degrees={len(self.degree_cascades)}, "
                f"cascades={self.degree_cascades}, "
                f"species={self.get_total_species_count()}, "
                f"regulations={len(self.regulations)})")

generate_specifications(random_seed: Optional[int] = None, feedback_density: float = 0.5, **kwargs)

Generate complete network specifications.

Parameters:

Name Type Description Default
random_seed Optional[int]

Random seed for reproducibility

None
feedback_density float

Proportion of feedback connections to create (0-1)

0.5
**kwargs

Additional arguments (unused, for compatibility)

{}
Source code in src/synthetic/Specs/DegreeInteractionSpec.py
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
def generate_specifications(self, random_seed: Optional[int] = None, 
                           feedback_density: float = 0.5, **kwargs):
    """
    Generate complete network specifications.

    Args:
        random_seed: Random seed for reproducibility
        feedback_density: Proportion of feedback connections to create (0-1)
        **kwargs: Additional arguments (unused, for compatibility)
    """
    # Clear existing state
    self.regulations = []
    self.species_list = []
    self.species_groups = {}
    self.ordinary_regulations = []
    self.feedback_regulations = []
    self.drugs = []
    self.drug_values = {}

    # Generate species and regulations
    self.generate_species_names()
    self.generate_ordinary_regulations()
    self.generate_feedback_regulations(random_seed, feedback_density)

    self._logger.info(
        f"Generated {len(self.degree_cascades)}-degree network with "
        f"{len(self.species_list)} species and {len(self.regulations)} regulations"
    )

add_drug(drug: Drug, value: Optional[float] = None)

Add a drug to the model, validating it only targets degree 1 R species.

Parameters:

Name Type Description Default
drug Drug

Drug object containing name, start_time, default_value, and regulations

required
value Optional[float]

Optional override for drug value

None

Raises:

Type Description
ValueError

If drug targets non-degree-1 species or non-R species

Source code in src/synthetic/Specs/DegreeInteractionSpec.py
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
def add_drug(self, drug: Drug, value: Optional[float] = None):
    """
    Add a drug to the model, validating it only targets degree 1 R species.

    Args:
        drug: Drug object containing name, start_time, default_value, and regulations
        value: Optional override for drug value

    Raises:
        ValueError: If drug targets non-degree-1 species or non-R species
    """
    # Validate drug targets
    for target_species in drug.regulation:
        # Check if target is a degree 1 R species
        is_degree1_r = any(
            target_species == r_name 
            for r_name in self.degree_species.get(1, {}).get('R', [])
        )

        if not is_degree1_r:
            raise ValueError(
                f"Drug {drug.name} can only target degree 1 R species. "
                f"Invalid target: {target_species}"
            )

    # Call parent method
    super().add_drug(drug, value)

get_species_by_degree(degree: int, species_type: str = 'all') -> List[str]

Get species for a specific degree.

Parameters:

Name Type Description Default
degree int

Degree number (1-indexed)

required
species_type str

'R', 'I', or 'all'

'all'

Returns:

Type Description
List[str]

List of species names

Source code in src/synthetic/Specs/DegreeInteractionSpec.py
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
def get_species_by_degree(self, degree: int, species_type: str = 'all') -> List[str]:
    """
    Get species for a specific degree.

    Args:
        degree: Degree number (1-indexed)
        species_type: 'R', 'I', or 'all'

    Returns:
        List of species names
    """
    if degree not in self.degree_species:
        return []

    species_dict = self.degree_species[degree]
    if species_type == 'R':
        return species_dict['R']
    elif species_type == 'I':
        return species_dict['I']
    elif species_type == 'all':
        return species_dict['R'] + species_dict['I']
    else:
        raise ValueError("species_type must be 'R', 'I', or 'all'")

get_regulations_by_degree(degree: Optional[int] = None) -> List[Regulation]

Get regulations for a specific degree or all degrees.

Parameters:

Name Type Description Default
degree Optional[int]

Degree number (1-indexed) or None for all

None

Returns:

Type Description
List[Regulation]

List of Regulation objects

Source code in src/synthetic/Specs/DegreeInteractionSpec.py
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
def get_regulations_by_degree(self, degree: Optional[int] = None) -> List[Regulation]:
    """
    Get regulations for a specific degree or all degrees.

    Args:
        degree: Degree number (1-indexed) or None for all

    Returns:
        List of Regulation objects
    """
    if degree is None:
        return self.regulations.copy()
    elif degree in self.degree_regulations:
        return self.degree_regulations[degree].copy()
    else:
        return []

synthetic.Specs.MichaelisNetworkSpec.MichaelisNetworkSpec

Bases: BaseSpec

Generic Michaelis-Menten network specification with ModelSpec4-style drug mechanism.

Features: 1. Generic species management (any network topology) 2. ModelSpec4's reaction generation scheme 3. ModelSpec4's drug mechanism (drugs as species with regulations) 4. Flexible specification generation (random or manual) 5. Michaelis-Menten kinetics with up/down regulation

Example usage:

spec = MichaelisNetworkSpec()
spec.generate_specifications(num_species=5, num_regulations=8, random_seed=42)
model = spec.generate_network("my_network")
print(model.get_antimony_model())

Source code in src/synthetic/Specs/MichaelisNetworkSpec.py
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
class MichaelisNetworkSpec(BaseSpec):
    """
    Generic Michaelis-Menten network specification with ModelSpec4-style drug mechanism.

    Features:
    1. Generic species management (any network topology)
    2. ModelSpec4's reaction generation scheme
    3. ModelSpec4's drug mechanism (drugs as species with regulations)
    4. Flexible specification generation (random or manual)
    5. Michaelis-Menten kinetics with up/down regulation

    Example usage:
    ```python
    spec = MichaelisNetworkSpec()
    spec.generate_specifications(num_species=5, num_regulations=8, random_seed=42)
    model = spec.generate_network("my_network")
    print(model.get_antimony_model())
    ```
    """

    def __init__(self, use_basal_activation: bool = False):
        super().__init__()
        self.use_basal_activation = use_basal_activation
        self.drugs: List[Drug] = []
        self.drug_values: Dict[str, float] = {}
        self.species_groups: Dict[str, List[str]] = {}
        self.randomise_parameters = True
        self.ordinary_regulations: List[Regulation] = []
        self.feedback_regulations: List[Regulation] = []
        self._logger = logging.getLogger(__name__)

    # === Species Management ===
    def add_species(self, species: str, group: str = "default"):
        """
        Add species to the model.

        Args:
            species: Name of the species
            group: Optional group name for categorization
        """
        if species not in self.species_list:
            self.species_list.append(species)
        if group not in self.species_groups:
            self.species_groups[group] = []
        if species not in self.species_groups[group]:
            self.species_groups[group].append(species)

    def get_species_by_group(self, group: str) -> List[str]:
        """Get all species in a specific group."""
        return self.species_groups.get(group, [])

    # === Drug Mechanism (from ModelSpec4) ===
    def add_drug(self, drug: Drug, value: Optional[float] = None):
        """
        Add a drug to the model using ModelSpec4's mechanism.

        Args:
            drug: Drug object containing name, start_time, default_value, and regulations
            value: Optional override for drug value
        """
        self.drugs.append(drug)
        if value is not None:
            self.drug_values[drug.name] = value
        else:
            self.drug_values[drug.name] = drug.default_value

        # Add drug as a species
        self.add_species(drug.name, "drugs")

        # Create regulations from drug to target species
        for i in range(len(drug.regulation)):
            specie = drug.regulation[i]
            reg_type = drug.regulation_type[i]

            # Validate target species exists
            if specie not in self.species_list:
                raise ValueError(f"Drug model not compatible: Specie {specie} not found in the model")
            if reg_type not in ['up', 'down']:
                raise ValueError("Drug model not compatible: Regulation type must be either 'up' or 'down'")

            # Create Regulation object
            reg = Regulation(from_specie=drug.name, to_specie=specie, reg_type=reg_type)
            self.regulations.append(reg)

    def clear_drugs(self):
        """Remove all drugs and their associated regulations."""
        # Remove drug species
        for drug in self.drugs:
            if drug.name in self.species_list:
                self.species_list.remove(drug.name)
            if "drugs" in self.species_groups and drug.name in self.species_groups["drugs"]:
                self.species_groups["drugs"].remove(drug.name)

        # Remove drug regulations
        drug_names = [d.name for d in self.drugs]
        self.regulations = [r for r in self.regulations if r.from_specie not in drug_names]

        # Clear drug lists
        self.drugs = []
        self.drug_values = {}

    # === Regulation Management ===
    def add_regulation(self, from_specie: str, to_specie: str, reg_type: str, 
                       is_feedback: bool = False):
        """
        Add regulation between species.

        Args:
            from_specie: Regulating species
            to_specie: Regulated species
            reg_type: 'up' or 'down'
            is_feedback: Whether this is a feedback regulation
        """
        if reg_type not in ['up', 'down']:
            raise ValueError("Regulation type must be either 'up' or 'down'")

        if from_specie not in self.species_list:
            self.add_species(from_specie)
        if to_specie not in self.species_list:
            self.add_species(to_specie)

        reg = Regulation(from_specie, to_specie, reg_type)
        self.regulations.append(reg)

        # Track as ordinary or feedback
        if is_feedback:
            self.feedback_regulations.append(reg)
        else:
            self.ordinary_regulations.append(reg)

    def get_regulators_for_species(self, specie: str) -> List[Tuple[str, str]]:
        """
        Get all regulators for a species.

        Returns:
            List of (regulator_name, reg_type) tuples
        """
        regulators = []
        for reg in self.regulations:
            if reg.to_specie == specie:
                regulators.append((reg.from_specie, reg.reg_type))
        return regulators

    # === Core Abstract Method Implementations ===
    def generate_specifications(self, 
                               num_species: Optional[int] = None,
                               num_regulations: Optional[int] = None,
                               species_names: Optional[List[str]] = None,
                               regulation_list: Optional[List[Tuple[str, str, str]]] = None,
                               random_seed: Optional[int] = None,
                               **kwargs):
        """
        Generate network specifications.

        Can generate random network or use provided species/regulations.

        Args:
            num_species: Number of species for random generation
            num_regulations: Number of regulations for random generation
            species_names: List of species names for manual specification
            regulation_list: List of (from_specie, to_specie, reg_type) tuples
            random_seed: Random seed for reproducibility
        """
        # Clear existing state
        self.regulations = []
        self.species_list = []
        self.species_groups = {}
        self.ordinary_regulations = []
        self.feedback_regulations = []

        if random_seed is not None:
            rng = np.random.default_rng(random_seed)
        else:
            rng = np.random.default_rng()

        # Handle manual specification
        if species_names is not None:
            for species in species_names:
                self.add_species(species)

        # Handle random generation
        elif num_species is not None:
            # Generate species names S1, S2, ..., SN
            species_names = [f"S{i+1}" for i in range(num_species)]
            for species in species_names:
                self.add_species(species)

        # Add regulations
        if regulation_list is not None:
            for from_specie, to_specie, reg_type in regulation_list:
                self.add_regulation(from_specie, to_specie, reg_type)

        elif num_regulations is not None and len(self.species_list) > 0:
            # Generate random regulations
            species = self.species_list.copy()
            for _ in range(num_regulations):
                from_specie = rng.choice(species)
                to_specie = rng.choice([s for s in species if s != from_specie])
                reg_type = rng.choice(['up', 'down'])
                self.add_regulation(from_specie, to_specie, reg_type, is_feedback=True)

        self._logger.debug(f"Generated specifications: {len(self.species_list)} species, {len(self.regulations)} regulations")

    def generate_network(self,
                        network_name: str,
                        mean_range_species: Tuple[int, int] = (1, 100),
                        rangeScale_params: Tuple[float, float] = (0.5, 2.0),
                        rangeMultiplier_params: Tuple[float, float] = (0.8, 1.2),
                        random_seed: Optional[int] = None,
                        receptor_basal_activation: bool = False,
                        **kwargs) -> ModelBuilder:
        """
        Generate ModelBuilder using Michaelis-Menten reaction scheme.

        Args:
            network_name: Name of the network
            mean_range_species: Range for initial species values
            rangeScale_params: Range for parameter scaling
            rangeMultiplier_params: Range for parameter multiplier
            random_seed: Random seed for reproducibility
            receptor_basal_activation: Whether to use basal activation for all species

        Returns:
            Pre-compiled ModelBuilder object
        """
        model = ModelBuilder(network_name)

        # Set up random number generator
        if random_seed is not None:
            rng = np.random.default_rng(random_seed)
        else:
            rng = np.random.default_rng()

        def add_reactions(specie: str, model: ModelBuilder, basal: bool = False):
            """Helper to add forward and reverse reactions for a species."""
            forward_reaction = self.get_forward_reaction(
                specie, mean_range_species, rangeScale_params, 
                rangeMultiplier_params, rng, basal=basal
            )
            reverse_reaction = self.get_reverse_reaction(
                specie, rangeScale_params, rangeMultiplier_params, rng
            )
            # Add reverse first, then forward (ModelSpec4 pattern)
            model.add_reaction(reverse_reaction)
            model.add_reaction(forward_reaction)

        # Generate reactions for all species (excluding drugs)
        non_drug_species = [s for s in self.species_list if s not in [d.name for d in self.drugs]]

        for specie in non_drug_species:
            add_reactions(specie, model, basal=receptor_basal_activation)

        # Handle drugs (add piecewise functions)
        for drug in self.drugs:
            model.add_simple_piecewise(
                0, drug.start_time, self.drug_values[drug.name], drug.name
            )

        model.precompile()

        self._logger.debug(f"Generated model {network_name} with {len(model.reactions)} reactions")
        self._logger.debug(f"Species: {len(model.states)}, Parameters: {len(model.parameters)}")

        return model

    # === Reaction Generation Helpers (from ModelSpec4) ===
    def generate_forward_archtype_and_regulators(self, specie: str) -> Tuple[ReactionArchtype, List[str]]:
        """
        Generate forward reaction archtype and regulators for a species.
        Direct copy from ModelSpec4.
        """
        all_regulations = [(reg.from_specie, reg.to_specie) for reg in self.regulations]
        all_regulation_types = [reg.reg_type for reg in self.regulations]

        regulators_for_specie = []
        for i, reg in enumerate(all_regulations):
            if reg[1] == specie:
                reg_type = all_regulation_types[i]
                regulators_for_specie.append((reg[0], reg_type))

        if len(regulators_for_specie) == 0:
            return michaelis_menten, []

        total_up_regulations = len([r for r in regulators_for_specie if r[1] == 'up'])
        total_down_regulations = len([r for r in regulators_for_specie if r[1] == 'down'])

        rate_law = create_archtype_michaelis_menten_v2(
            stimulators=0,
            stimulator_weak=total_up_regulations,
            allosteric_inhibitors=total_down_regulations,
            competitive_inhibitors=0
        )

        # Sort regulators by type, up first and down second
        regulators_for_specie = sorted(regulators_for_specie, key=lambda x: x[1], reverse=True)
        regulators_sorted = [r[0] for r in regulators_for_specie]

        return rate_law, regulators_sorted

    def generate_forward_archtype_and_regulators_basal(self, specie: str) -> Tuple[ReactionArchtype, List[str]]:
        """
        Generate forward reaction archtype with basal activation.
        Direct copy from ModelSpec4.
        """
        all_regulations = [(reg.from_specie, reg.to_specie) for reg in self.regulations]
        all_regulation_types = [reg.reg_type for reg in self.regulations]

        regulators_for_specie = []
        for i, reg in enumerate(all_regulations):
            if reg[1] == specie:
                reg_type = all_regulation_types[i]
                regulators_for_specie.append((reg[0], reg_type))

        if len(regulators_for_specie) == 0:
            return michaelis_menten, []

        total_up_regulations = len([r for r in regulators_for_specie if r[1] == 'up'])
        total_down_regulations = len([r for r in regulators_for_specie if r[1] == 'down'])

        rate_law = create_archtype_basal_michaelis(
            stimulators=0,
            stimulator_weak=total_up_regulations,
            allosteric_inhibitors=total_down_regulations,
            competitive_inhibitors=0
        )

        regulators_for_specie = sorted(regulators_for_specie, key=lambda x: x[1], reverse=True)
        regulators_sorted = [r[0] for r in regulators_for_specie]

        return rate_law, regulators_sorted

    def generate_reverse_archtype_and_regulators(self, specie: str) -> Tuple[ReactionArchtype, List[str]]:
        """
        Generate reverse reaction archtype and regulators.
        Direct copy from ModelSpec4.
        """
        all_regulations = [(reg.from_specie, reg.to_specie) for reg in self.regulations]
        all_regulation_types = [reg.reg_type for reg in self.regulations]

        regulators_for_specie = []
        for i, reg in enumerate(all_regulations):
            if reg[1] == specie:
                reg_type = all_regulation_types[i]
                if reg_type == 'down':
                    regulators_for_specie.append((reg[0], reg_type))

        if len(regulators_for_specie) == 0:
            return michaelis_menten, []

        return michaelis_menten, []

    def generate_random_parameters(self, 
                                  reaction_archtype: ReactionArchtype,
                                  scale_range: Tuple[float, float],
                                  multiplier_range: Tuple[float, float],
                                  random_seed: Optional[int] = None) -> Tuple:
        """
        Generate random parameters informed by scale.
        Direct copy from ModelSpec4.
        """
        if random_seed is not None:
            rng = np.random.default_rng(random_seed)
        else:
            rng = np.random.default_rng()

        assumed_values = reaction_archtype.assume_parameters_values
        r_params = []
        for _, value in assumed_values.items():
            rand = rng.uniform(value * scale_range[0], value * scale_range[1])
            rand *= rng.uniform(multiplier_range[0], multiplier_range[1])
            r_params.append(rand)

        return tuple(r_params)

    # === Reaction Creation Methods ===
    def get_forward_reaction(self, specie: str, mean_range_species: Tuple[int, int],
                            rangeScale_params: Tuple[float, float],
                            rangeMultiplier_params: Tuple[float, float],
                            rng: np.random.Generator,
                            basal: bool = False) -> Reaction:
        """
        Create forward reaction for a species.
        Adapted from ModelSpec4.
        """
        if basal or self.use_basal_activation:
            forward_rate_law, regulators = self.generate_forward_archtype_and_regulators_basal(specie)
        else:
            forward_rate_law, regulators = self.generate_forward_archtype_and_regulators(specie)

        activated_regulators = []
        for r in regulators:
            if 'D' in r:  # Drug does not get activated (ModelSpec4 pattern)
                activated_regulators.append(r)
            else:
                activated_regulators.append(r + 'a')

        forward_params = self.generate_random_parameters(
            forward_rate_law, rangeScale_params, rangeMultiplier_params, rng
        )
        forward_state_val = rng.integers(mean_range_species[0], mean_range_species[1])

        forward_reaction = Reaction(
            forward_rate_law,
            (specie,),
            (specie + 'a',),
            reactant_values=forward_state_val,
            extra_states=tuple(activated_regulators),
            parameters_values=tuple(forward_params),
            zero_init=False
        )
        return forward_reaction

    def get_reverse_reaction(self, specie: str,
                            rangeScale_params: Tuple[float, float],
                            rangeMultiplier_params: Tuple[float, float],
                            rng: np.random.Generator) -> Reaction:
        """
        Create reverse reaction for a species.
        Adapted from ModelSpec4.
        """
        reverse_rate_law, regulators = self.generate_reverse_archtype_and_regulators(specie)

        activated_regulators = []
        for r in regulators:
            if 'D' in r:
                activated_regulators.append(r)
            else:
                activated_regulators.append(r + 'a')

        reverse_params = self.generate_random_parameters(
            reverse_rate_law, rangeScale_params, rangeMultiplier_params, rng
        )

        reverse_reaction = Reaction(
            reverse_rate_law,
            (specie + 'a',),
            (specie,),
            extra_states=tuple(activated_regulators),
            parameters_values=tuple(reverse_params),
            zero_init=False
        )
        return reverse_reaction

    # === Utility Methods ===
    def get_all_species(self, 
                       include_drugs: bool = True,
                       include_default: bool = True) -> List[str]:
        """
        Get all species in the model.

        Args:
            include_drugs: Whether to include drug species
            include_default: Whether to include non-drug species

        Returns:
            List of species names
        """
        species = []
        if include_default:
            drug_names = [d.name for d in self.drugs]
            species.extend([s for s in self.species_list if s not in drug_names])
        if include_drugs:
            species.extend([d.name for d in self.drugs])
        return species

    def __str__(self) -> str:
        """String representation of the specification."""
        return (f"MichaelisNetworkSpec(species={len(self.species_list)}, "
                f"regulations={len(self.regulations)}, drugs={len(self.drugs)})")

__str__() -> str

String representation of the specification.

Source code in src/synthetic/Specs/MichaelisNetworkSpec.py
478
479
480
481
def __str__(self) -> str:
    """String representation of the specification."""
    return (f"MichaelisNetworkSpec(species={len(self.species_list)}, "
            f"regulations={len(self.regulations)}, drugs={len(self.drugs)})")

add_drug(drug: Drug, value: Optional[float] = None)

Add a drug to the model using ModelSpec4's mechanism.

Parameters:

Name Type Description Default
drug Drug

Drug object containing name, start_time, default_value, and regulations

required
value Optional[float]

Optional override for drug value

None
Source code in src/synthetic/Specs/MichaelisNetworkSpec.py
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
def add_drug(self, drug: Drug, value: Optional[float] = None):
    """
    Add a drug to the model using ModelSpec4's mechanism.

    Args:
        drug: Drug object containing name, start_time, default_value, and regulations
        value: Optional override for drug value
    """
    self.drugs.append(drug)
    if value is not None:
        self.drug_values[drug.name] = value
    else:
        self.drug_values[drug.name] = drug.default_value

    # Add drug as a species
    self.add_species(drug.name, "drugs")

    # Create regulations from drug to target species
    for i in range(len(drug.regulation)):
        specie = drug.regulation[i]
        reg_type = drug.regulation_type[i]

        # Validate target species exists
        if specie not in self.species_list:
            raise ValueError(f"Drug model not compatible: Specie {specie} not found in the model")
        if reg_type not in ['up', 'down']:
            raise ValueError("Drug model not compatible: Regulation type must be either 'up' or 'down'")

        # Create Regulation object
        reg = Regulation(from_specie=drug.name, to_specie=specie, reg_type=reg_type)
        self.regulations.append(reg)

add_regulation(from_specie: str, to_specie: str, reg_type: str, is_feedback: bool = False)

Add regulation between species.

Parameters:

Name Type Description Default
from_specie str

Regulating species

required
to_specie str

Regulated species

required
reg_type str

'up' or 'down'

required
is_feedback bool

Whether this is a feedback regulation

False
Source code in src/synthetic/Specs/MichaelisNetworkSpec.py
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
def add_regulation(self, from_specie: str, to_specie: str, reg_type: str, 
                   is_feedback: bool = False):
    """
    Add regulation between species.

    Args:
        from_specie: Regulating species
        to_specie: Regulated species
        reg_type: 'up' or 'down'
        is_feedback: Whether this is a feedback regulation
    """
    if reg_type not in ['up', 'down']:
        raise ValueError("Regulation type must be either 'up' or 'down'")

    if from_specie not in self.species_list:
        self.add_species(from_specie)
    if to_specie not in self.species_list:
        self.add_species(to_specie)

    reg = Regulation(from_specie, to_specie, reg_type)
    self.regulations.append(reg)

    # Track as ordinary or feedback
    if is_feedback:
        self.feedback_regulations.append(reg)
    else:
        self.ordinary_regulations.append(reg)

add_species(species: str, group: str = 'default')

Add species to the model.

Parameters:

Name Type Description Default
species str

Name of the species

required
group str

Optional group name for categorization

'default'
Source code in src/synthetic/Specs/MichaelisNetworkSpec.py
45
46
47
48
49
50
51
52
53
54
55
56
57
58
def add_species(self, species: str, group: str = "default"):
    """
    Add species to the model.

    Args:
        species: Name of the species
        group: Optional group name for categorization
    """
    if species not in self.species_list:
        self.species_list.append(species)
    if group not in self.species_groups:
        self.species_groups[group] = []
    if species not in self.species_groups[group]:
        self.species_groups[group].append(species)

clear_drugs()

Remove all drugs and their associated regulations.

Source code in src/synthetic/Specs/MichaelisNetworkSpec.py
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
def clear_drugs(self):
    """Remove all drugs and their associated regulations."""
    # Remove drug species
    for drug in self.drugs:
        if drug.name in self.species_list:
            self.species_list.remove(drug.name)
        if "drugs" in self.species_groups and drug.name in self.species_groups["drugs"]:
            self.species_groups["drugs"].remove(drug.name)

    # Remove drug regulations
    drug_names = [d.name for d in self.drugs]
    self.regulations = [r for r in self.regulations if r.from_specie not in drug_names]

    # Clear drug lists
    self.drugs = []
    self.drug_values = {}

generate_forward_archtype_and_regulators(specie: str) -> Tuple[ReactionArchtype, List[str]]

Generate forward reaction archtype and regulators for a species. Direct copy from ModelSpec4.

Source code in src/synthetic/Specs/MichaelisNetworkSpec.py
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
def generate_forward_archtype_and_regulators(self, specie: str) -> Tuple[ReactionArchtype, List[str]]:
    """
    Generate forward reaction archtype and regulators for a species.
    Direct copy from ModelSpec4.
    """
    all_regulations = [(reg.from_specie, reg.to_specie) for reg in self.regulations]
    all_regulation_types = [reg.reg_type for reg in self.regulations]

    regulators_for_specie = []
    for i, reg in enumerate(all_regulations):
        if reg[1] == specie:
            reg_type = all_regulation_types[i]
            regulators_for_specie.append((reg[0], reg_type))

    if len(regulators_for_specie) == 0:
        return michaelis_menten, []

    total_up_regulations = len([r for r in regulators_for_specie if r[1] == 'up'])
    total_down_regulations = len([r for r in regulators_for_specie if r[1] == 'down'])

    rate_law = create_archtype_michaelis_menten_v2(
        stimulators=0,
        stimulator_weak=total_up_regulations,
        allosteric_inhibitors=total_down_regulations,
        competitive_inhibitors=0
    )

    # Sort regulators by type, up first and down second
    regulators_for_specie = sorted(regulators_for_specie, key=lambda x: x[1], reverse=True)
    regulators_sorted = [r[0] for r in regulators_for_specie]

    return rate_law, regulators_sorted

generate_forward_archtype_and_regulators_basal(specie: str) -> Tuple[ReactionArchtype, List[str]]

Generate forward reaction archtype with basal activation. Direct copy from ModelSpec4.

Source code in src/synthetic/Specs/MichaelisNetworkSpec.py
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
def generate_forward_archtype_and_regulators_basal(self, specie: str) -> Tuple[ReactionArchtype, List[str]]:
    """
    Generate forward reaction archtype with basal activation.
    Direct copy from ModelSpec4.
    """
    all_regulations = [(reg.from_specie, reg.to_specie) for reg in self.regulations]
    all_regulation_types = [reg.reg_type for reg in self.regulations]

    regulators_for_specie = []
    for i, reg in enumerate(all_regulations):
        if reg[1] == specie:
            reg_type = all_regulation_types[i]
            regulators_for_specie.append((reg[0], reg_type))

    if len(regulators_for_specie) == 0:
        return michaelis_menten, []

    total_up_regulations = len([r for r in regulators_for_specie if r[1] == 'up'])
    total_down_regulations = len([r for r in regulators_for_specie if r[1] == 'down'])

    rate_law = create_archtype_basal_michaelis(
        stimulators=0,
        stimulator_weak=total_up_regulations,
        allosteric_inhibitors=total_down_regulations,
        competitive_inhibitors=0
    )

    regulators_for_specie = sorted(regulators_for_specie, key=lambda x: x[1], reverse=True)
    regulators_sorted = [r[0] for r in regulators_for_specie]

    return rate_law, regulators_sorted

generate_network(network_name: str, mean_range_species: Tuple[int, int] = (1, 100), rangeScale_params: Tuple[float, float] = (0.5, 2.0), rangeMultiplier_params: Tuple[float, float] = (0.8, 1.2), random_seed: Optional[int] = None, receptor_basal_activation: bool = False, **kwargs) -> ModelBuilder

Generate ModelBuilder using Michaelis-Menten reaction scheme.

Parameters:

Name Type Description Default
network_name str

Name of the network

required
mean_range_species Tuple[int, int]

Range for initial species values

(1, 100)
rangeScale_params Tuple[float, float]

Range for parameter scaling

(0.5, 2.0)
rangeMultiplier_params Tuple[float, float]

Range for parameter multiplier

(0.8, 1.2)
random_seed Optional[int]

Random seed for reproducibility

None
receptor_basal_activation bool

Whether to use basal activation for all species

False

Returns:

Type Description
ModelBuilder

Pre-compiled ModelBuilder object

Source code in src/synthetic/Specs/MichaelisNetworkSpec.py
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
def generate_network(self,
                    network_name: str,
                    mean_range_species: Tuple[int, int] = (1, 100),
                    rangeScale_params: Tuple[float, float] = (0.5, 2.0),
                    rangeMultiplier_params: Tuple[float, float] = (0.8, 1.2),
                    random_seed: Optional[int] = None,
                    receptor_basal_activation: bool = False,
                    **kwargs) -> ModelBuilder:
    """
    Generate ModelBuilder using Michaelis-Menten reaction scheme.

    Args:
        network_name: Name of the network
        mean_range_species: Range for initial species values
        rangeScale_params: Range for parameter scaling
        rangeMultiplier_params: Range for parameter multiplier
        random_seed: Random seed for reproducibility
        receptor_basal_activation: Whether to use basal activation for all species

    Returns:
        Pre-compiled ModelBuilder object
    """
    model = ModelBuilder(network_name)

    # Set up random number generator
    if random_seed is not None:
        rng = np.random.default_rng(random_seed)
    else:
        rng = np.random.default_rng()

    def add_reactions(specie: str, model: ModelBuilder, basal: bool = False):
        """Helper to add forward and reverse reactions for a species."""
        forward_reaction = self.get_forward_reaction(
            specie, mean_range_species, rangeScale_params, 
            rangeMultiplier_params, rng, basal=basal
        )
        reverse_reaction = self.get_reverse_reaction(
            specie, rangeScale_params, rangeMultiplier_params, rng
        )
        # Add reverse first, then forward (ModelSpec4 pattern)
        model.add_reaction(reverse_reaction)
        model.add_reaction(forward_reaction)

    # Generate reactions for all species (excluding drugs)
    non_drug_species = [s for s in self.species_list if s not in [d.name for d in self.drugs]]

    for specie in non_drug_species:
        add_reactions(specie, model, basal=receptor_basal_activation)

    # Handle drugs (add piecewise functions)
    for drug in self.drugs:
        model.add_simple_piecewise(
            0, drug.start_time, self.drug_values[drug.name], drug.name
        )

    model.precompile()

    self._logger.debug(f"Generated model {network_name} with {len(model.reactions)} reactions")
    self._logger.debug(f"Species: {len(model.states)}, Parameters: {len(model.parameters)}")

    return model

generate_random_parameters(reaction_archtype: ReactionArchtype, scale_range: Tuple[float, float], multiplier_range: Tuple[float, float], random_seed: Optional[int] = None) -> Tuple

Generate random parameters informed by scale. Direct copy from ModelSpec4.

Source code in src/synthetic/Specs/MichaelisNetworkSpec.py
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
def generate_random_parameters(self, 
                              reaction_archtype: ReactionArchtype,
                              scale_range: Tuple[float, float],
                              multiplier_range: Tuple[float, float],
                              random_seed: Optional[int] = None) -> Tuple:
    """
    Generate random parameters informed by scale.
    Direct copy from ModelSpec4.
    """
    if random_seed is not None:
        rng = np.random.default_rng(random_seed)
    else:
        rng = np.random.default_rng()

    assumed_values = reaction_archtype.assume_parameters_values
    r_params = []
    for _, value in assumed_values.items():
        rand = rng.uniform(value * scale_range[0], value * scale_range[1])
        rand *= rng.uniform(multiplier_range[0], multiplier_range[1])
        r_params.append(rand)

    return tuple(r_params)

generate_reverse_archtype_and_regulators(specie: str) -> Tuple[ReactionArchtype, List[str]]

Generate reverse reaction archtype and regulators. Direct copy from ModelSpec4.

Source code in src/synthetic/Specs/MichaelisNetworkSpec.py
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
def generate_reverse_archtype_and_regulators(self, specie: str) -> Tuple[ReactionArchtype, List[str]]:
    """
    Generate reverse reaction archtype and regulators.
    Direct copy from ModelSpec4.
    """
    all_regulations = [(reg.from_specie, reg.to_specie) for reg in self.regulations]
    all_regulation_types = [reg.reg_type for reg in self.regulations]

    regulators_for_specie = []
    for i, reg in enumerate(all_regulations):
        if reg[1] == specie:
            reg_type = all_regulation_types[i]
            if reg_type == 'down':
                regulators_for_specie.append((reg[0], reg_type))

    if len(regulators_for_specie) == 0:
        return michaelis_menten, []

    return michaelis_menten, []

generate_specifications(num_species: Optional[int] = None, num_regulations: Optional[int] = None, species_names: Optional[List[str]] = None, regulation_list: Optional[List[Tuple[str, str, str]]] = None, random_seed: Optional[int] = None, **kwargs)

Generate network specifications.

Can generate random network or use provided species/regulations.

Parameters:

Name Type Description Default
num_species Optional[int]

Number of species for random generation

None
num_regulations Optional[int]

Number of regulations for random generation

None
species_names Optional[List[str]]

List of species names for manual specification

None
regulation_list Optional[List[Tuple[str, str, str]]]

List of (from_specie, to_specie, reg_type) tuples

None
random_seed Optional[int]

Random seed for reproducibility

None
Source code in src/synthetic/Specs/MichaelisNetworkSpec.py
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
def generate_specifications(self, 
                           num_species: Optional[int] = None,
                           num_regulations: Optional[int] = None,
                           species_names: Optional[List[str]] = None,
                           regulation_list: Optional[List[Tuple[str, str, str]]] = None,
                           random_seed: Optional[int] = None,
                           **kwargs):
    """
    Generate network specifications.

    Can generate random network or use provided species/regulations.

    Args:
        num_species: Number of species for random generation
        num_regulations: Number of regulations for random generation
        species_names: List of species names for manual specification
        regulation_list: List of (from_specie, to_specie, reg_type) tuples
        random_seed: Random seed for reproducibility
    """
    # Clear existing state
    self.regulations = []
    self.species_list = []
    self.species_groups = {}
    self.ordinary_regulations = []
    self.feedback_regulations = []

    if random_seed is not None:
        rng = np.random.default_rng(random_seed)
    else:
        rng = np.random.default_rng()

    # Handle manual specification
    if species_names is not None:
        for species in species_names:
            self.add_species(species)

    # Handle random generation
    elif num_species is not None:
        # Generate species names S1, S2, ..., SN
        species_names = [f"S{i+1}" for i in range(num_species)]
        for species in species_names:
            self.add_species(species)

    # Add regulations
    if regulation_list is not None:
        for from_specie, to_specie, reg_type in regulation_list:
            self.add_regulation(from_specie, to_specie, reg_type)

    elif num_regulations is not None and len(self.species_list) > 0:
        # Generate random regulations
        species = self.species_list.copy()
        for _ in range(num_regulations):
            from_specie = rng.choice(species)
            to_specie = rng.choice([s for s in species if s != from_specie])
            reg_type = rng.choice(['up', 'down'])
            self.add_regulation(from_specie, to_specie, reg_type, is_feedback=True)

    self._logger.debug(f"Generated specifications: {len(self.species_list)} species, {len(self.regulations)} regulations")

get_all_species(include_drugs: bool = True, include_default: bool = True) -> List[str]

Get all species in the model.

Parameters:

Name Type Description Default
include_drugs bool

Whether to include drug species

True
include_default bool

Whether to include non-drug species

True

Returns:

Type Description
List[str]

List of species names

Source code in src/synthetic/Specs/MichaelisNetworkSpec.py
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
def get_all_species(self, 
                   include_drugs: bool = True,
                   include_default: bool = True) -> List[str]:
    """
    Get all species in the model.

    Args:
        include_drugs: Whether to include drug species
        include_default: Whether to include non-drug species

    Returns:
        List of species names
    """
    species = []
    if include_default:
        drug_names = [d.name for d in self.drugs]
        species.extend([s for s in self.species_list if s not in drug_names])
    if include_drugs:
        species.extend([d.name for d in self.drugs])
    return species

get_forward_reaction(specie: str, mean_range_species: Tuple[int, int], rangeScale_params: Tuple[float, float], rangeMultiplier_params: Tuple[float, float], rng: np.random.Generator, basal: bool = False) -> Reaction

Create forward reaction for a species. Adapted from ModelSpec4.

Source code in src/synthetic/Specs/MichaelisNetworkSpec.py
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
def get_forward_reaction(self, specie: str, mean_range_species: Tuple[int, int],
                        rangeScale_params: Tuple[float, float],
                        rangeMultiplier_params: Tuple[float, float],
                        rng: np.random.Generator,
                        basal: bool = False) -> Reaction:
    """
    Create forward reaction for a species.
    Adapted from ModelSpec4.
    """
    if basal or self.use_basal_activation:
        forward_rate_law, regulators = self.generate_forward_archtype_and_regulators_basal(specie)
    else:
        forward_rate_law, regulators = self.generate_forward_archtype_and_regulators(specie)

    activated_regulators = []
    for r in regulators:
        if 'D' in r:  # Drug does not get activated (ModelSpec4 pattern)
            activated_regulators.append(r)
        else:
            activated_regulators.append(r + 'a')

    forward_params = self.generate_random_parameters(
        forward_rate_law, rangeScale_params, rangeMultiplier_params, rng
    )
    forward_state_val = rng.integers(mean_range_species[0], mean_range_species[1])

    forward_reaction = Reaction(
        forward_rate_law,
        (specie,),
        (specie + 'a',),
        reactant_values=forward_state_val,
        extra_states=tuple(activated_regulators),
        parameters_values=tuple(forward_params),
        zero_init=False
    )
    return forward_reaction

get_regulators_for_species(specie: str) -> List[Tuple[str, str]]

Get all regulators for a species.

Returns:

Type Description
List[Tuple[str, str]]

List of (regulator_name, reg_type) tuples

Source code in src/synthetic/Specs/MichaelisNetworkSpec.py
143
144
145
146
147
148
149
150
151
152
153
154
def get_regulators_for_species(self, specie: str) -> List[Tuple[str, str]]:
    """
    Get all regulators for a species.

    Returns:
        List of (regulator_name, reg_type) tuples
    """
    regulators = []
    for reg in self.regulations:
        if reg.to_specie == specie:
            regulators.append((reg.from_specie, reg.reg_type))
    return regulators

get_reverse_reaction(specie: str, rangeScale_params: Tuple[float, float], rangeMultiplier_params: Tuple[float, float], rng: np.random.Generator) -> Reaction

Create reverse reaction for a species. Adapted from ModelSpec4.

Source code in src/synthetic/Specs/MichaelisNetworkSpec.py
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
def get_reverse_reaction(self, specie: str,
                        rangeScale_params: Tuple[float, float],
                        rangeMultiplier_params: Tuple[float, float],
                        rng: np.random.Generator) -> Reaction:
    """
    Create reverse reaction for a species.
    Adapted from ModelSpec4.
    """
    reverse_rate_law, regulators = self.generate_reverse_archtype_and_regulators(specie)

    activated_regulators = []
    for r in regulators:
        if 'D' in r:
            activated_regulators.append(r)
        else:
            activated_regulators.append(r + 'a')

    reverse_params = self.generate_random_parameters(
        reverse_rate_law, rangeScale_params, rangeMultiplier_params, rng
    )

    reverse_reaction = Reaction(
        reverse_rate_law,
        (specie + 'a',),
        (specie,),
        extra_states=tuple(activated_regulators),
        parameters_values=tuple(reverse_params),
        zero_init=False
    )
    return reverse_reaction

get_species_by_group(group: str) -> List[str]

Get all species in a specific group.

Source code in src/synthetic/Specs/MichaelisNetworkSpec.py
60
61
62
def get_species_by_group(self, group: str) -> List[str]:
    """Get all species in a specific group."""
    return self.species_groups.get(group, [])

synthetic.Specs.Drug.Drug

Source code in src/synthetic/Specs/Drug.py
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
class Drug: 

    def __init__(self, name, start_time, default_value, regulation=None, regulation_type=None):
        ''' 
        A drug class that represents a drug that can be applied to a model. 
        Input: 
            name: str | The name of the drug
            start_time: int | The time at which the drug is applied to the model.
            default_value: float | The default value of the drug in the model
            regulation: List[str] | The list of species that the drug regulates 
            regulation_type: List[str] | The type of regulation that the drug has on the species, either 'up' or 'down'
        '''
        self.name = name
        self.start_time = start_time
        self.default_value = default_value
        self.regulation = [] if regulation is None else regulation
        self.regulation_type = [] if regulation_type is None else regulation_type
        assert len(self.regulation) == len(self.regulation_type), "The regulation and regulation_type lists must be the same length"

    def __str__(self):
        return f"Drug({self.name}, {self.start_time}, {self.regulation}, {self.regulation_type})"

    def __repr__(self):
        return str(self)

    def add_regulation(self, specie, type): 
        ''' 
        Adds a regulation to the drug. 
        Input: 
            specie: str | The name of the specie to regulate
            type: str | The type of regulation, either 'up' or 'down'
        '''
        self.regulation.append(specie)
        self.regulation_type.append(type)

    def add_regulations(self, species, types):
        ''' 
        Adds multiple regulations to the drug. 
        Input: 
            species: List[str] | The list of species to regulate
            types: List[str] | The list of types of regulation, either 'up' or 'down'
        '''
        assert len(species) == len(types), "The species and types lists must be the same length"
        for i in range(len(species)): 
            self.add_regulation(species[i], types[i])

    def print_regulation(self): 
        ''' 
        Prints the regulation of the drug. 
        '''
        for i in range(len(self.regulation)): 
            print(f"{self.regulation[i]}: {self.regulation_type[i]}")

__init__(name, start_time, default_value, regulation=None, regulation_type=None)

A drug class that represents a drug that can be applied to a model. Input: name: str | The name of the drug start_time: int | The time at which the drug is applied to the model. default_value: float | The default value of the drug in the model regulation: List[str] | The list of species that the drug regulates regulation_type: List[str] | The type of regulation that the drug has on the species, either 'up' or 'down'

Source code in src/synthetic/Specs/Drug.py
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
def __init__(self, name, start_time, default_value, regulation=None, regulation_type=None):
    ''' 
    A drug class that represents a drug that can be applied to a model. 
    Input: 
        name: str | The name of the drug
        start_time: int | The time at which the drug is applied to the model.
        default_value: float | The default value of the drug in the model
        regulation: List[str] | The list of species that the drug regulates 
        regulation_type: List[str] | The type of regulation that the drug has on the species, either 'up' or 'down'
    '''
    self.name = name
    self.start_time = start_time
    self.default_value = default_value
    self.regulation = [] if regulation is None else regulation
    self.regulation_type = [] if regulation_type is None else regulation_type
    assert len(self.regulation) == len(self.regulation_type), "The regulation and regulation_type lists must be the same length"

add_regulation(specie, type)

Adds a regulation to the drug. Input: specie: str | The name of the specie to regulate type: str | The type of regulation, either 'up' or 'down'

Source code in src/synthetic/Specs/Drug.py
26
27
28
29
30
31
32
33
34
def add_regulation(self, specie, type): 
    ''' 
    Adds a regulation to the drug. 
    Input: 
        specie: str | The name of the specie to regulate
        type: str | The type of regulation, either 'up' or 'down'
    '''
    self.regulation.append(specie)
    self.regulation_type.append(type)

add_regulations(species, types)

Adds multiple regulations to the drug. Input: species: List[str] | The list of species to regulate types: List[str] | The list of types of regulation, either 'up' or 'down'

Source code in src/synthetic/Specs/Drug.py
36
37
38
39
40
41
42
43
44
45
def add_regulations(self, species, types):
    ''' 
    Adds multiple regulations to the drug. 
    Input: 
        species: List[str] | The list of species to regulate
        types: List[str] | The list of types of regulation, either 'up' or 'down'
    '''
    assert len(species) == len(types), "The species and types lists must be the same length"
    for i in range(len(species)): 
        self.add_regulation(species[i], types[i])

print_regulation()

Prints the regulation of the drug.

Source code in src/synthetic/Specs/Drug.py
47
48
49
50
51
52
def print_regulation(self): 
    ''' 
    Prints the regulation of the drug. 
    '''
    for i in range(len(self.regulation)): 
        print(f"{self.regulation[i]}: {self.regulation_type[i]}")

synthetic.Specs.Regulation.Regulation dataclass

Class to store the regulation information

Source code in src/synthetic/Specs/Regulation.py
3
4
5
6
7
8
@dataclass
class Regulation:
    """Class to store the regulation information"""
    from_specie: str
    to_specie: str
    reg_type: str

Solvers

ODE simulation backends. Both concrete solvers inherit from the abstract Solver base class, which defines the compile() and simulate() interface. See Solving ODEs for usage.

synthetic.Solver.ScipySolver.ScipySolver

Bases: Solver

Solver using scipy to solve the ODEs.

Source code in src/synthetic/Solver/ScipySolver.py
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
class ScipySolver(Solver):
    """
    Solver using scipy to solve the ODEs. 
    """

    def __init__(self):
        super().__init__()
        # reactions, species, parameters, y0, parameter_values
        self.reactions = None
        self.species = None
        self.parameters = None
        self.y0 = None
        self.parameter_values = None
        self.assignment_rules = None
        self.func = None
        self.jit = False

        self.last_sim_result = None

    def compile(self, compile_str: str, **kwargs) -> None:
        """
        Compile the model from an Antimony string and generate ODE function.
        Assignment rule variables are treated like pseudo-parameters with
        time-based value changes during simulation.
        """
        result = self._parse_antimony_model(compile_str)
        reactions, species, parameters, y0, parameter_values, assignment_rules = result

        self.reactions = reactions
        self.species = species
        self.assignment_rules = assignment_rules

        # Extend parameters with assignment rule variables
        self.assignment_rule_vars = sorted(assignment_rules.keys())
        self.parameters = parameters            # already includes rule vars
        self.parameter_values = parameter_values  
        self.y0 = y0

        self.jit = kwargs.get("jit", False)
        if not self.jit:
            self.func = self._reactions_to_ode_func(
                reactions, species, self.parameters, assignment_rule_vars=self.assignment_rule_vars
            )
        else:
            self.func = self._reactions_to_jit_ode_func(
                reactions, species, self.parameters, assignment_rule_vars=self.assignment_rule_vars
            )


    def simulate(self, start: float, stop: float, step: float) -> pd.DataFrame:
        """
        Simulate the ODE system from start to stop with a given step size.
        Handles piecewise assignment rule changes at change-points.
        """
        if self.func is None:
            raise ValueError("Model instance is not created. Please call compile() first.")

        # Generate full time vector and extract rule breakpoints
        t_full = np.linspace(start, stop, step)
        change_points = sorted(
            {rule["time"] for rule in self.assignment_rules.values() if start < rule["time"] < stop}
        )
        time_segments = [start] + change_points + [stop]

        all_results = []
        y_current = np.array(self.y0, dtype=float)
        param_current = list(self.parameter_values)
        param_map = {p: i for i, p in enumerate(self.parameters)}

        for i in range(len(time_segments) - 1):
            t0, t1 = time_segments[i], time_segments[i + 1]
            mask = (t_full >= t0) & (t_full <= t1)
            t_segment = np.unique(t_full[mask])  # Remove duplicate times

            if len(t_segment) < 2:
                continue  # Skip short segments

            # Safety checks
            if not np.all(np.isfinite(y_current)):
                raise ValueError(f"Non-finite state values before integrating [{t0}, {t1}]: {y_current}")
            if not np.all(np.isfinite(param_current)):
                raise ValueError(f"Non-finite parameter values before integrating [{t0}, {t1}]: {param_current}")

            try:
                if self.jit:
                    def ode_wrapper(y, t, *args):
                        return self.func(y, t, np.array(args))
                    sol = odeint(ode_wrapper, y_current, t_segment, args=tuple(param_current))
                else:
                    sol = odeint(self.func, y_current, t_segment, args=tuple(param_current))
            except Exception as e:
                raise RuntimeError(f"ODE integration failed between t={t0} and t={t1}: {e}")

            # Store segment result
            df_segment = pd.DataFrame(sol, columns=self.species)
            df_segment.insert(0, "time", t_segment)
            all_results.append(df_segment)

            # Update state for next segment
            y_current = sol[-1]

            # Apply assignment rule changes at t1
            for var, rule in self.assignment_rules.items():
                if np.isclose(rule["time"], t1):
                    idx = param_map.get(var)
                    if idx is None:
                        raise KeyError(f"Assignment rule targets unknown parameter '{var}'")
                    param_current[idx] = rule["after"]
                    # Optional debug log:
                    # print(f"At t={t1}, setting {var} = {rule['after']}")

        final_result = pd.concat(all_results, ignore_index=True)
        self.last_sim_result = final_result
        return final_result




    def set_state_values(self, state_values: Dict[str, float]) -> bool:
        """
        Hot swapping of state variables in the running instance of the model, note this is setting the initial values of the state variables.
        Set the values of state variables in the model instance, this should only possible after compiling the model. 
        Not every solver will support this, so it is possible that this function to return an not implemented error.
        returns True if the state variable was set successfully, False otherwise.
        """
        # Check if the model is created
        if self.func is None:
            raise ValueError("Model instance is not created. Please call compile() first.")

        # Check if the state values are valid
        for key in state_values.keys():
            if key not in self.species:
                raise ValueError(f"State variable {key} is not valid. Valid state variables are: {self.species}")

        # Set the state values
        for key, value in state_values.items():
            index = self.species.index(key)
            self.y0[index] = value

        return True

    def set_parameter_values(self, parameter_values: Dict[str, float]) -> bool:
        """
        Hot swapping of parameters in the running instance of the model.
        Set the values of parameter variables in the model instance, this should only possible after compiling the model. 
        Not every solver will support this, so it is possible that this function to return an not implemented error.
        returns True if the state variable was set successfully, False otherwise.
        """
        # Check if the model is created
        if self.func is None:
            raise ValueError("Model instance is not created. Please call compile() first.")

        # Check if the parameter values are valid
        for key in parameter_values.keys():
            if key not in self.parameters:
                raise ValueError(f"Parameter {key} is not valid. Valid parameters are: {self.parameters}")

        # Set the parameter values
        for key, value in parameter_values.items():
            index = self.parameters.index(key)
            self.parameter_values[index] = value

        return True

    def get_species_list(self):
        """
        Get list of species (state variable) names in the compiled model.

        Returns:
            List of species names

        Raises:
            RuntimeError: If solver not compiled
        """
        if self.species is None:
            raise RuntimeError("Model instance is not created. Please call compile() first.")

        return list(self.species)


    def _parse_antimony_model(self, antimony_str: str) -> Tuple[
        List[str], List[str], List[str], List[float], List[float], Dict[str, Dict[str, float]]
    ]:
        """
        Parses an Antimony model string and extracts:
        - reactions
        - species
        - parameters
        - initial conditions (y0)
        - parameter values
        - assignment rules as dicts of {var: {'before': val, 'after': val, 'time': t}}
        """
        reactions = []
        species_set = set()
        species_dict = {}
        parameter_dict = {}
        assignment_rules = {}

        for line in antimony_str.splitlines():
            line = line.strip()
            if not line or line.startswith("#") or line.startswith("model ") or line == "end":
                continue

            # Reaction line
            if ":" in line and ";" in line:
                _, rxn = line.split(":", 1)
                rxn = rxn.strip()
                reactions.append(rxn)

                reaction_part, _ = map(str.strip, rxn.split(";"))
                if "->" in reaction_part:
                    lhs, rhs = map(str.strip, reaction_part.split("->"))
                    reactants = [s.strip() for s in lhs.split("+")]
                    products = [s.strip() for s in rhs.split("+")]
                    species_set.update(reactants + products)

            # Assignment rule
            elif ":=" in line:
                var, expr = map(str.strip, line.split(":=", 1))
                rule = self._parse_piecewise_rule(expr)
                if rule:
                    assignment_rules[var] = rule

            # Initial value
            elif "=" in line:
                var, val = map(str.strip, line.split("=", 1))
                try:
                    val = float(val)
                    if var in species_set:
                        species_dict[var] = val
                    else:
                        parameter_dict[var] = val
                except ValueError:
                    continue  # skip non-numeric initial values

        species = sorted(species_dict)
        y0 = [species_dict[s] for s in species]
        parameters = sorted(parameter_dict)
        parameter_values = [parameter_dict[p] for p in parameters]

        # Treat assignment rule names as "pseudo-parameters"
        parameters += sorted(assignment_rules.keys())
        parameter_values += [rule['before'] for rule in assignment_rules.values()]
        return reactions, species, parameters, y0, parameter_values, assignment_rules


    def _parse_piecewise_rule(self, expr: str) -> Dict[str, float] | None:
        """
        Parses simple piecewise expressions like:
        'piecewise(0, time < 500, 500)' → {'before': 0.0, 'after': 500.0, 'time': 500.0}
        """
        match = re.match(r"piecewise\(([^,]+),\s*time\s*<\s*([0-9.]+),\s*([^)]+)\)", expr)
        if match:
            val1, time_str, val2 = match.groups()
            try:
                return {
                    "before": float(val1),
                    "after": float(val2),
                    "time": float(time_str)
                }
            except ValueError:
                return None
        return None


    def _reactions_to_ode_func(self, reactions, species, parameters, assignment_rule_vars=None):
        """
        Convert a list of reactions to an ODE function using sympy.
        Supports symbolic variables for both parameters and assignment rules.
        """
        species_syms = {s: sp.Symbol(s) for s in species}
        param_syms = {p: sp.Symbol(p) for p in parameters}
        rule_syms = {r: sp.Symbol(r) for r in assignment_rule_vars or []}

        all_syms = {**species_syms, **param_syms, **rule_syms}

        derivs = {s: 0 for s in species}

        for rxn in reactions:
            reaction_part, rate_expr = map(str.strip, rxn.split(";"))
            rate = sp.sympify(rate_expr, locals=all_syms)

            if "<->" in reaction_part:
                raise NotImplementedError("Reversible reactions not yet supported.")

            reactants_str, products_str = map(str.strip, reaction_part.split("->"))
            reactants = [r.strip() for r in reactants_str.split("+") if r.strip()]
            products = [p.strip() for p in products_str.split("+") if p.strip()]

            for r in reactants:
                derivs[r] -= rate
            for p in products:
                derivs[p] += rate

        dydt_exprs = [derivs[s] for s in species]

        # 🟢 Correct: single flat argument list
        all_inputs = list(species_syms.values()) + list(param_syms.values())
        dydt_func = sp.lambdify(all_inputs, dydt_exprs, modules="numpy")

        def func(y, t, *params):
            return np.array(dydt_func(*y, *params)).flatten()

        return func




    def _reactions_to_jit_ode_func(self, reactions, species, parameters, assignment_rule_vars=None):
        """
        Create a Numba-compiled ODE function that supports assignment rules as parameters.
        """
        # Create symbols
        species_syms = {s: sp.Symbol(s) for s in species}
        param_syms = {p: sp.Symbol(p) for p in parameters}
        rule_syms = {r: sp.Symbol(r) for r in assignment_rule_vars or []}
        all_syms = {**species_syms, **param_syms, **rule_syms}

        # Derivative dictionary
        derivs = {s: 0 for s in species}

        for rxn in reactions:
            reaction_part, rate_expr = map(str.strip, rxn.split(";"))
            rate = sp.sympify(rate_expr, locals=all_syms)

            if "<->" in reaction_part:
                raise NotImplementedError("Reversible reactions not yet supported.")

            reactants_str, products_str = map(str.strip, reaction_part.split("->"))
            reactants = [r.strip() for r in reactants_str.split("+") if r.strip()]
            products = [p.strip() for p in products_str.split("+") if p.strip()]

            for r in reactants:
                derivs[r] -= rate
            for p in products:
                derivs[p] += rate

        dydt_exprs = [derivs[s] for s in species]

        # Generate symbolic subs
        species_subs = {species_syms[s]: sp.Symbol(f"y[{i}]") for i, s in enumerate(species)}
        param_subs = {param_syms[p]: sp.Symbol(f"params[{i}]") for i, p in enumerate(parameters)}

        func_lines = ["def generated_func(y, t, params):"]
        func_lines.append(f"    dydt = np.empty({len(dydt_exprs)})")

        for i, expr in enumerate(dydt_exprs):
            substituted = expr.subs({**species_subs, **param_subs})
            code_line = sp.ccode(substituted)
            func_lines.append(f"    dydt[{i}] = {code_line}")

        func_lines.append("    return dydt")

        func_code = "\n".join(func_lines)

        local_vars = {"np": np}
        exec(func_code, local_vars)
        generated_func = local_vars["generated_func"]

        return njit(generated_func)

compile(compile_str: str, **kwargs) -> None

Compile the model from an Antimony string and generate ODE function. Assignment rule variables are treated like pseudo-parameters with time-based value changes during simulation.

Source code in src/synthetic/Solver/ScipySolver.py
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
def compile(self, compile_str: str, **kwargs) -> None:
    """
    Compile the model from an Antimony string and generate ODE function.
    Assignment rule variables are treated like pseudo-parameters with
    time-based value changes during simulation.
    """
    result = self._parse_antimony_model(compile_str)
    reactions, species, parameters, y0, parameter_values, assignment_rules = result

    self.reactions = reactions
    self.species = species
    self.assignment_rules = assignment_rules

    # Extend parameters with assignment rule variables
    self.assignment_rule_vars = sorted(assignment_rules.keys())
    self.parameters = parameters            # already includes rule vars
    self.parameter_values = parameter_values  
    self.y0 = y0

    self.jit = kwargs.get("jit", False)
    if not self.jit:
        self.func = self._reactions_to_ode_func(
            reactions, species, self.parameters, assignment_rule_vars=self.assignment_rule_vars
        )
    else:
        self.func = self._reactions_to_jit_ode_func(
            reactions, species, self.parameters, assignment_rule_vars=self.assignment_rule_vars
        )

simulate(start: float, stop: float, step: float) -> pd.DataFrame

Simulate the ODE system from start to stop with a given step size. Handles piecewise assignment rule changes at change-points.

Source code in src/synthetic/Solver/ScipySolver.py
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
def simulate(self, start: float, stop: float, step: float) -> pd.DataFrame:
    """
    Simulate the ODE system from start to stop with a given step size.
    Handles piecewise assignment rule changes at change-points.
    """
    if self.func is None:
        raise ValueError("Model instance is not created. Please call compile() first.")

    # Generate full time vector and extract rule breakpoints
    t_full = np.linspace(start, stop, step)
    change_points = sorted(
        {rule["time"] for rule in self.assignment_rules.values() if start < rule["time"] < stop}
    )
    time_segments = [start] + change_points + [stop]

    all_results = []
    y_current = np.array(self.y0, dtype=float)
    param_current = list(self.parameter_values)
    param_map = {p: i for i, p in enumerate(self.parameters)}

    for i in range(len(time_segments) - 1):
        t0, t1 = time_segments[i], time_segments[i + 1]
        mask = (t_full >= t0) & (t_full <= t1)
        t_segment = np.unique(t_full[mask])  # Remove duplicate times

        if len(t_segment) < 2:
            continue  # Skip short segments

        # Safety checks
        if not np.all(np.isfinite(y_current)):
            raise ValueError(f"Non-finite state values before integrating [{t0}, {t1}]: {y_current}")
        if not np.all(np.isfinite(param_current)):
            raise ValueError(f"Non-finite parameter values before integrating [{t0}, {t1}]: {param_current}")

        try:
            if self.jit:
                def ode_wrapper(y, t, *args):
                    return self.func(y, t, np.array(args))
                sol = odeint(ode_wrapper, y_current, t_segment, args=tuple(param_current))
            else:
                sol = odeint(self.func, y_current, t_segment, args=tuple(param_current))
        except Exception as e:
            raise RuntimeError(f"ODE integration failed between t={t0} and t={t1}: {e}")

        # Store segment result
        df_segment = pd.DataFrame(sol, columns=self.species)
        df_segment.insert(0, "time", t_segment)
        all_results.append(df_segment)

        # Update state for next segment
        y_current = sol[-1]

        # Apply assignment rule changes at t1
        for var, rule in self.assignment_rules.items():
            if np.isclose(rule["time"], t1):
                idx = param_map.get(var)
                if idx is None:
                    raise KeyError(f"Assignment rule targets unknown parameter '{var}'")
                param_current[idx] = rule["after"]
                # Optional debug log:
                # print(f"At t={t1}, setting {var} = {rule['after']}")

    final_result = pd.concat(all_results, ignore_index=True)
    self.last_sim_result = final_result
    return final_result

set_state_values(state_values: Dict[str, float]) -> bool

Hot swapping of state variables in the running instance of the model, note this is setting the initial values of the state variables. Set the values of state variables in the model instance, this should only possible after compiling the model. Not every solver will support this, so it is possible that this function to return an not implemented error. returns True if the state variable was set successfully, False otherwise.

Source code in src/synthetic/Solver/ScipySolver.py
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
def set_state_values(self, state_values: Dict[str, float]) -> bool:
    """
    Hot swapping of state variables in the running instance of the model, note this is setting the initial values of the state variables.
    Set the values of state variables in the model instance, this should only possible after compiling the model. 
    Not every solver will support this, so it is possible that this function to return an not implemented error.
    returns True if the state variable was set successfully, False otherwise.
    """
    # Check if the model is created
    if self.func is None:
        raise ValueError("Model instance is not created. Please call compile() first.")

    # Check if the state values are valid
    for key in state_values.keys():
        if key not in self.species:
            raise ValueError(f"State variable {key} is not valid. Valid state variables are: {self.species}")

    # Set the state values
    for key, value in state_values.items():
        index = self.species.index(key)
        self.y0[index] = value

    return True

set_parameter_values(parameter_values: Dict[str, float]) -> bool

Hot swapping of parameters in the running instance of the model. Set the values of parameter variables in the model instance, this should only possible after compiling the model. Not every solver will support this, so it is possible that this function to return an not implemented error. returns True if the state variable was set successfully, False otherwise.

Source code in src/synthetic/Solver/ScipySolver.py
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
def set_parameter_values(self, parameter_values: Dict[str, float]) -> bool:
    """
    Hot swapping of parameters in the running instance of the model.
    Set the values of parameter variables in the model instance, this should only possible after compiling the model. 
    Not every solver will support this, so it is possible that this function to return an not implemented error.
    returns True if the state variable was set successfully, False otherwise.
    """
    # Check if the model is created
    if self.func is None:
        raise ValueError("Model instance is not created. Please call compile() first.")

    # Check if the parameter values are valid
    for key in parameter_values.keys():
        if key not in self.parameters:
            raise ValueError(f"Parameter {key} is not valid. Valid parameters are: {self.parameters}")

    # Set the parameter values
    for key, value in parameter_values.items():
        index = self.parameters.index(key)
        self.parameter_values[index] = value

    return True

synthetic.Solver.RoadrunnerSolver.RoadrunnerSolver

Bases: Solver

RoadRunner-based ODE solver for biochemical models.

This solver uses the libRoadRunner library to compile and simulate biochemical models defined in Antimony or SBML formats. It provides an interface for setting initial states and parameters, and returns simulation results as pandas DataFrames.

Inherits from

Solver: Abstract base class for ODE solvers

Source code in src/synthetic/Solver/RoadrunnerSolver.py
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
class RoadrunnerSolver(Solver):
    """
    RoadRunner-based ODE solver for biochemical models.

    This solver uses the libRoadRunner library to compile and simulate
    biochemical models defined in Antimony or SBML formats. It provides
    an interface for setting initial states and parameters, and returns
    simulation results as pandas DataFrames.

    Inherits from:
        Solver: Abstract base class for ODE solvers
    """

    def __init__(self):
        super().__init__()
        self.roadrunner_instance = None
        self.last_sim_result = None

    def compile(self, compile_str: str, **kwargs):
        """
        Compile a model string using libRoadRunner.

        Args:
            compile_str: Model definition in Antimony or SBML format
            **kwargs: Additional options passed to RoadRunner constructor

        Returns:
            RoadRunner: The compiled RoadRunner instance
        """
        from roadrunner import RoadRunner
        self.roadrunner_instance = RoadRunner(compile_str, **kwargs)

    def simulate(self, start: float, stop: float, step: float) -> pd.DataFrame:
        """
        Simulate the problem from start to stop with a given step size.
        Returns a pandas dataframe with the results with the following columns:
        - time: time points of the simulation
        - [species]: species names
        with each row corresponds to a time point and each column corresponds to a species.
        """

        # Check if the roadrunner instance is created
        if self.roadrunner_instance is None:
            raise ValueError("RoadRunner instance is not created. Please call compile() first.")

        runner = self.roadrunner_instance
        res = runner.simulate(start, stop, step)
        # Convert the result to a pandas dataframe, by default, this will not work 


        ## First step is to obtain all the state variables in the model
        state_vars = runner.model.getFloatingSpeciesIds()

        new_data = []
        new_data.append(res['time'])
        for state in state_vars:
            new_data.append(res[f'[{state}]'])

        # Convert the result to a pandas dataframe
        df = pd.DataFrame(new_data).T
        df.columns = ['time'] + list(state_vars)

        # reset the model to the initial state
        runner.resetToOrigin()
        return df

    def set_state_values(self, state_values: Dict[str, float]) -> bool:
        """
        Hot swapping of state variables in the running instance of the model, note this is setting the initial values of the state variables.
        Set the values of state variables in the model instance, this should only possible after compiling the model. 
        Not every solver will support this, so it is possible that this function to return an not implemented error.
        returns True if the state variable was set successfully, False otherwise.
        """
        # Check if the roadrunner instance is created
        if self.roadrunner_instance is None:
            raise ValueError("RoadRunner instance is not created. Please call compile() first.")

        runner = self.roadrunner_instance

        # Set the state values in the model instance
        for state, value in state_values.items():
            try:
                runner[f'init({state})'] = value
            except Exception as e:
                print(f"Error setting state variable {state}: {e}")
                return False

        return True

    def get_species_list(self):
        """
        Get list of species (state variable) names in the compiled model.

        Returns:
            List of species names

        Raises:
            RuntimeError: If solver not compiled
        """
        if self.roadrunner_instance is None:
            raise RuntimeError("RoadRunner instance is not created. Please call compile() first.")

        return list(self.roadrunner_instance.model.getFloatingSpeciesIds())


    def set_parameter_values(self, parameter_values: Dict[str, float]) -> bool:
        """
        Hot swapping of parameters in the running instance of the model.
        Set the values of parameter variables in the model instance, this should only possible after compiling the model. 
        Not every solver will support this, so it is possible that this function to return an not implemented error.
        returns True if the state variable was set successfully, False otherwise.
        """
        # Check if the roadrunner instance is created
        if self.roadrunner_instance is None:
            raise ValueError("RoadRunner instance is not created. Please call compile() first.")

        runner = self.roadrunner_instance

        # Set the parameter values in the model instance
        for param, value in parameter_values.items():
            try:
                runner[param] = value
            except Exception as e:
                print(f"Error setting parameter {param}: {e}")
                return False

        return True

compile(compile_str: str, **kwargs)

Compile a model string using libRoadRunner.

Parameters:

Name Type Description Default
compile_str str

Model definition in Antimony or SBML format

required
**kwargs

Additional options passed to RoadRunner constructor

{}

Returns:

Name Type Description
RoadRunner

The compiled RoadRunner instance

Source code in src/synthetic/Solver/RoadrunnerSolver.py
25
26
27
28
29
30
31
32
33
34
35
36
37
def compile(self, compile_str: str, **kwargs):
    """
    Compile a model string using libRoadRunner.

    Args:
        compile_str: Model definition in Antimony or SBML format
        **kwargs: Additional options passed to RoadRunner constructor

    Returns:
        RoadRunner: The compiled RoadRunner instance
    """
    from roadrunner import RoadRunner
    self.roadrunner_instance = RoadRunner(compile_str, **kwargs)

simulate(start: float, stop: float, step: float) -> pd.DataFrame

Simulate the problem from start to stop with a given step size. Returns a pandas dataframe with the results with the following columns: - time: time points of the simulation - [species]: species names with each row corresponds to a time point and each column corresponds to a species.

Source code in src/synthetic/Solver/RoadrunnerSolver.py
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
def simulate(self, start: float, stop: float, step: float) -> pd.DataFrame:
    """
    Simulate the problem from start to stop with a given step size.
    Returns a pandas dataframe with the results with the following columns:
    - time: time points of the simulation
    - [species]: species names
    with each row corresponds to a time point and each column corresponds to a species.
    """

    # Check if the roadrunner instance is created
    if self.roadrunner_instance is None:
        raise ValueError("RoadRunner instance is not created. Please call compile() first.")

    runner = self.roadrunner_instance
    res = runner.simulate(start, stop, step)
    # Convert the result to a pandas dataframe, by default, this will not work 


    ## First step is to obtain all the state variables in the model
    state_vars = runner.model.getFloatingSpeciesIds()

    new_data = []
    new_data.append(res['time'])
    for state in state_vars:
        new_data.append(res[f'[{state}]'])

    # Convert the result to a pandas dataframe
    df = pd.DataFrame(new_data).T
    df.columns = ['time'] + list(state_vars)

    # reset the model to the initial state
    runner.resetToOrigin()
    return df

set_state_values(state_values: Dict[str, float]) -> bool

Hot swapping of state variables in the running instance of the model, note this is setting the initial values of the state variables. Set the values of state variables in the model instance, this should only possible after compiling the model. Not every solver will support this, so it is possible that this function to return an not implemented error. returns True if the state variable was set successfully, False otherwise.

Source code in src/synthetic/Solver/RoadrunnerSolver.py
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
def set_state_values(self, state_values: Dict[str, float]) -> bool:
    """
    Hot swapping of state variables in the running instance of the model, note this is setting the initial values of the state variables.
    Set the values of state variables in the model instance, this should only possible after compiling the model. 
    Not every solver will support this, so it is possible that this function to return an not implemented error.
    returns True if the state variable was set successfully, False otherwise.
    """
    # Check if the roadrunner instance is created
    if self.roadrunner_instance is None:
        raise ValueError("RoadRunner instance is not created. Please call compile() first.")

    runner = self.roadrunner_instance

    # Set the state values in the model instance
    for state, value in state_values.items():
        try:
            runner[f'init({state})'] = value
        except Exception as e:
            print(f"Error setting state variable {state}: {e}")
            return False

    return True

set_parameter_values(parameter_values: Dict[str, float]) -> bool

Hot swapping of parameters in the running instance of the model. Set the values of parameter variables in the model instance, this should only possible after compiling the model. Not every solver will support this, so it is possible that this function to return an not implemented error. returns True if the state variable was set successfully, False otherwise.

Source code in src/synthetic/Solver/RoadrunnerSolver.py
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
def set_parameter_values(self, parameter_values: Dict[str, float]) -> bool:
    """
    Hot swapping of parameters in the running instance of the model.
    Set the values of parameter variables in the model instance, this should only possible after compiling the model. 
    Not every solver will support this, so it is possible that this function to return an not implemented error.
    returns True if the state variable was set successfully, False otherwise.
    """
    # Check if the roadrunner instance is created
    if self.roadrunner_instance is None:
        raise ValueError("RoadRunner instance is not created. Please call compile() first.")

    runner = self.roadrunner_instance

    # Set the parameter values in the model instance
    for param, value in parameter_values.items():
        try:
            runner[param] = value
        except Exception as e:
            print(f"Error setting parameter {param}: {e}")
            return False

    return True

Utilities

Helpers for parameter tuning, feature generation, and dataset creation. See Obtaining Data, Advanced, and Use Cases for context.

synthetic.utils.kinetic_tuner.KineticParameterTuner

Generate kinetic parameters that achieve target active percentage ranges.

This tuner solves the full nonlinear kinetic equations to ensure that each species reaches a specified active percentage at steady state, enabling robust signal propagation through multi-degree networks.

Attributes:

Name Type Description
model

The ModelBuilder object containing the network structure

rng

numpy random number generator for reproducibility

Source code in src/synthetic/utils/kinetic_tuner.py
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
class KineticParameterTuner:
    """
    Generate kinetic parameters that achieve target active percentage ranges.

    This tuner solves the full nonlinear kinetic equations to ensure that
    each species reaches a specified active percentage at steady state,
    enabling robust signal propagation through multi-degree networks.

    Attributes:
        model: The ModelBuilder object containing the network structure
        rng: numpy random number generator for reproducibility
    """

    def __init__(self, model: ModelBuilder, random_seed: Optional[int] = None):
        """
        Initialize the parameter tuner for a specific model.

        Args:
            model: ModelBuilder object with network structure
            random_seed: Optional seed for reproducible parameter generation
        """
        if not model.pre_compiled:
            raise ValueError("Model must be pre-compiled before parameter tuning")

        self.model = model
        self.rng = np.random.default_rng(random_seed)

        # Cache state information for performance
        self.all_states = model.get_state_variables()
        self.active_states = {k: v for k, v in self.all_states.items() if k.endswith('a')}
        self.inactive_states = {k: v for k, v in self.all_states.items() if not k.endswith('a')}

        # Get regulator-parameter mappings from ModelBuilder
        self.regulator_param_map = model.get_regulator_parameter_map()
        self.param_regulator_map = model.get_parameter_regulator_map()

        # Parse drug concentrations from model variables
        self.drug_concentrations = self._parse_drug_concentrations(model)
        self._target_concentrations = {}

        # Validate that each active state has a corresponding inactive state
        self._validate_state_pairs()

    def _parse_drug_concentrations(self, model: ModelBuilder) -> Dict[str, float]:
        """
        Parse drug concentrations from model variables.

        Looks for piecewise functions in model.variables and extracts
        the default (before activation) concentration.

        Args:
            model: ModelBuilder object

        Returns:
            Dictionary mapping drug names to their concentrations
        """
        drug_concentrations = {}

        # Check model variables for piecewise functions
        for var_name, var_expression in model.variables.items():
            # Look for piecewise patterns
            if 'piecewise' in var_expression.lower():
                # Try to parse: var_name := piecewise(before_value, time < activation_time, after_value)
                try:
                    # Extract the before_value (default concentration)
                    # Simple parsing - find the first number after 'piecewise('
                    import re
                    match = re.search(r'piecewise\(([^,]+)', var_expression)
                    if match:
                        before_value_str = match.group(1).strip()
                        # Try to convert to float
                        try:
                            before_value = float(before_value_str)
                            drug_concentrations[var_name] = before_value
                        except ValueError:
                            # Might be a variable name or expression
                            # Check if it's a number in the expression
                            num_match = re.search(r'[-+]?\d*\.?\d+', before_value_str)
                            if num_match:
                                before_value = float(num_match.group())
                                drug_concentrations[var_name] = before_value
                except Exception as e:
                    # If parsing fails, continue with other variables
                    print(f"Warning: Could not parse drug concentration for {var_name}: {e}")

        return drug_concentrations

    def _validate_state_pairs(self):
        """Ensure each active state Xa has a corresponding inactive state X."""
        for active_state in self.active_states.keys():
            inactive_state = active_state[:-1]  # Remove trailing 'a'
            if inactive_state not in self.inactive_states:
                raise ValueError(
                    f"Active state {active_state} has no corresponding inactive state {inactive_state}"
                )

    def generate_parameters(
        self,
        active_percentage_range: Tuple[float, float] = (0.3, 0.7),
        X_total_multiplier: float = 5.0,
        ki_val: float = 100.0,
        v_max_f_random_range: Tuple[float, float] = (5.0, 10.0)
    ) -> Dict[str, float]:
        """
        Generate kinetic parameters to achieve target active percentages.

        Args:
            active_percentage_range: Range for target active percentages (e.g., (0.3, 0.7))
            X_total_multiplier: Multiplier for setting km_b = X_total × multiplier
            ki_val: Constant value for all inhibition constants Ki
            v_max_f_random_range: Range for total forward vmax (Σ kc_i × [Y_i_a])

        Returns:
            Dictionary mapping parameter names to tuned values

        Raises:
            ValueError: If target active percentages cannot be achieved
            RuntimeError: If parameter structure doesn't match expected pattern
        """
        # Step 1: Initialize target active concentrations for all species
        if not self._target_concentrations:
            self._initialize_target_concentrations(active_percentage_range)
        else: 
            print("Using existing target concentrations")

        target_concentrations = self._target_concentrations

        # Step 2: Process each activated species to determine parameters
        parameter_values = {}

        for active_state in self.active_states.keys():
            # Get corresponding inactive state
            inactive_state = active_state[:-1]

            # Get total concentration (inactive + active)
            X_total = self.all_states[inactive_state] + self.all_states[active_state]

            # Get target active concentration
            X_a_target = target_concentrations[active_state]
            p_target = X_a_target / X_total

            # Get parameters for this state
            params = get_parameters_for_state(self.model, active_state)
            forward_params = params['as_product']
            backward_params = params['as_reactant']

            # Categorize parameters
            km_b = [p for p in backward_params if p.startswith('Km')]
            km_f = [p for p in forward_params if p.startswith('Km')]
            ki_f = [p for p in forward_params if p.startswith('Ki')]
            vmax_f = [p for p in forward_params if p.startswith('Vmax')]
            kc_f = [p for p in forward_params if p.startswith('Kc')]

            # Combine related parameter types
            all_km_f = km_f + ki_f  # Km and Ki both affect denominator
            all_vmax_f = vmax_f + kc_f  # Vmax and Kc both contribute to numerator

            # Get backward Vmax
            vmax_b = [p for p in backward_params if p.startswith('Vmax')]

            # Validate parameter structure
            if not vmax_b:
                raise ValueError(f"No backward Vmax found for state {active_state}")
            if len(vmax_b) > 1:
                raise ValueError(f"Multiple backward Vmax found for state {active_state}: {vmax_b}")

            # Step 3: Identify regulators for this state using ModelBuilder mapping
            regulators = self._identify_regulators_for_state(active_state, forward_params)

            # Step 4: Solve for parameters using the corrected kinetic equations
            state_params = self._solve_state_parameters(
                active_state=active_state,
                X_total=X_total,
                p_target=p_target,
                all_vmax_f=all_vmax_f,
                regulators=regulators,
                vmax_b_param=vmax_b[0],
                all_km_f=all_km_f,
                km_b_params=km_b,
                target_concentrations=target_concentrations,
                X_total_multiplier=X_total_multiplier,
                ki_val=ki_val,
                v_max_f_random_range=v_max_f_random_range
            )

            parameter_values.update(state_params)

        return parameter_values

    def _identify_regulators_for_state(self, active_state: str, forward_params: List[str]) -> Dict[str, List[str]]:
        """
        Identify regulators for a given activated state using ModelBuilder mapping.

        Returns a dictionary with regulator types:
        {
            'stimulators': [list of stimulator species],
            'inhibitors': [list of inhibitor species]
        }

        Args:
            active_state: Name of the activated species
            forward_params: List of forward parameter names

        Returns:
            Dictionary of regulator lists by type
        """
        regulators = {'stimulators': [], 'inhibitors': []}

        # Get all parameters that produce this active state
        for param_name in forward_params:
            # Check if this parameter has a regulator
            regulator = self.param_regulator_map.get(param_name)
            if regulator:
                # Determine if this regulator is a stimulator or inhibitor
                # based on parameter prefix
                if param_name.startswith(('Kc', 'Ka', 'Ks', 'Kw', 'Vmax')):
                    # Stimulator parameters
                    if regulator not in regulators['stimulators']:
                        regulators['stimulators'].append(regulator)
                elif param_name.startswith(('Ki', 'Kic', 'Kil', 'Kir')):
                    # Inhibitor parameters
                    if regulator not in regulators['inhibitors']:
                        regulators['inhibitors'].append(regulator)
                elif param_name.startswith('Km'):
                    # Km parameters may be associated with either, check context
                    # For now, treat as neutral
                    pass

        return regulators

    def _initialize_target_concentrations(
        self, 
        active_percentage_range: Tuple[float, float]
    ) -> Dict[str, float]:
        """
        Initialize target active concentrations for all species.

        Args:
            active_percentage_range: Range for random active percentages

        Returns:
            Dictionary mapping active state names to target concentrations
        """
        target_concentrations = {}

        for active_state, active_value in self.active_states.items():
            inactive_state = active_state[:-1]
            inactive_value = self.all_states[inactive_state]

            X_total = inactive_value + active_value

            # Randomly select active percentage within range
            p = self.rng.uniform(active_percentage_range[0], active_percentage_range[1])

            # Compute target active concentration
            X_a_target = p * X_total

            target_concentrations[active_state] = X_a_target

        self._target_concentrations = target_concentrations

        return target_concentrations

    def _get_regulator_concentration(self, regulator: str, target_concentrations: Dict[str, float]) -> float:
        """
        Get concentration of a regulator species.

        Args:
            regulator: Name of regulator species
            target_concentrations: Dictionary of target active concentrations

        Returns:
            Regulator concentration (active form if available, otherwise inactive form)
        """
        # Check if regulator has active form
        active_regulator = regulator + 'a' if not regulator.endswith('a') else regulator
        if active_regulator in target_concentrations:
            return target_concentrations[active_regulator]

        # Check if regulator is in states (inactive form)
        if regulator in self.all_states:
            return self.all_states[regulator]

        # Default to 0 if regulator not found
        return 0.0

    def _solve_state_parameters(
        self,
        active_state: str,
        X_total: float,
        p_target: float,
        all_vmax_f: List[str],
        regulators: Dict[str, List[str]],
        vmax_b_param: str,
        all_km_f: List[str],
        km_b_params: List[str],
        target_concentrations: Dict[str, float],
        X_total_multiplier: float,
        ki_val: float,
        v_max_f_random_range: Tuple[float, float]
    ) -> Dict[str, float]:
        """
        Solve kinetic equations for a single activated species using corrected algorithm.

        Args:
            active_state: Name of the activated species
            X_total: Total concentration of the species (inactive + active)
            p_target: Target active percentage [X_a]/X_total
            all_vmax_f: List of forward Vmax/Kc parameter names
            regulators: Dictionary of regulator species by type
            vmax_b_param: Backward Vmax parameter name
            all_km_f: List of forward Km/Ki parameter names
            km_b_params: List of backward Km parameter names
            target_concentrations: Dictionary of target active concentrations
            X_total_multiplier: Multiplier for km_b calculation
            ki_val: Constant value for Ki parameters
            v_max_f_random_range: Range for total forward vmax

        Returns:
            Dictionary of parameter values for this state
        """
        parameter_values = {}

        # Step 1: Determine total forward vmax (Σ kc_i × [Y_i_a])
        total_vmax_f = self.rng.uniform(v_max_f_random_range[0], v_max_f_random_range[1])

        # Step 2: Determine backward vmax from equation: p = vmax_f / (vmax_f + vmax_b)
        if p_target <= 0 or p_target >= 1:
            raise ValueError(
                f"Target active percentage {p_target} for {active_state} must be between 0 and 1"
            )

        vmax_b_value = total_vmax_f * (1.0 / p_target - 1.0)

        # Step 3: Set backward Vmax parameter
        parameter_values[vmax_b_param] = vmax_b_value

        # Step 4: Distribute total_vmax_f among forward parameters
        stimulators = regulators.get('stimulators', [])
        if all_vmax_f:
            # Separate Vmax and Kc parameters
            vmax_params = [p for p in all_vmax_f if p.startswith('Vmax')]
            kc_params = [p for p in all_vmax_f if p.startswith('Kc')]

            # For Vmax parameters: assign directly (they're constants, not multiplied by regulator)
            # For Kc parameters: need to multiply by regulator concentration

            if kc_params:
                # We have Kc parameters that need regulator concentrations
                if stimulators and len(stimulators) >= len(kc_params):
                    # Get stimulator concentrations for Kc parameters
                    stimulator_concs = []
                    for i in range(len(kc_params)):
                        stimulator = stimulators[i] if i < len(stimulators) else stimulators[0]
                        conc = self._get_regulator_concentration(stimulator, target_concentrations)
                        stimulator_concs.append(conc)

                    # Avoid division by zero
                    stimulator_concs = [max(conc, 1e-6) for conc in stimulator_concs]

                    # Distribute total_vmax_f among Kc parameters so that kc_i × [Y_i_a] are equal
                    # First, allocate some portion to Vmax parameters if they exist
                    vmax_portion = 0.0
                    if vmax_params:
                        # Reserve a small portion for Vmax parameters
                        vmax_portion = total_vmax_f * 0.2  # 20% for Vmax
                        kc_portion = total_vmax_f - vmax_portion
                    else:
                        kc_portion = total_vmax_f

                    # Distribute kc_portion among Kc parameters
                    n_kc = len(kc_params)
                    constant_per_kc = kc_portion / n_kc

                    for i, param in enumerate(kc_params):
                        if i < len(stimulator_concs):
                            kc_value = constant_per_kc / stimulator_concs[i]
                            parameter_values[param] = kc_value
                        else:
                            # Fallback: use average concentration
                            avg_conc = sum(stimulator_concs) / len(stimulator_concs) if stimulator_concs else 1.0
                            kc_value = constant_per_kc / avg_conc
                            parameter_values[param] = kc_value

                    # Distribute vmax_portion among Vmax parameters
                    if vmax_params:
                        vmax_per_param = vmax_portion / len(vmax_params)
                        for param in vmax_params:
                            parameter_values[param] = vmax_per_param
                else:
                    # No stimulators identified or mismatch - use simplified distribution
                    vmax_f_per_param = total_vmax_f / len(all_vmax_f)
                    for param in all_vmax_f:
                        parameter_values[param] = vmax_f_per_param
            else:
                # Only Vmax parameters (no Kc)
                vmax_per_param = total_vmax_f / len(vmax_params)
                for param in vmax_params:
                    parameter_values[param] = vmax_per_param

        # Step 5: Set backward Km parameters
        km_b_value = X_total * X_total_multiplier
        for param in km_b_params:
            parameter_values[param] = km_b_value

        # Step 6: Set forward Km and Ki parameters with corrected calculation
        # According to competitive inhibition kinetics: v = Vmax * S / (Km * (1 + I/Ki) + S)
        # To achieve target steady state with inhibitors, we need: km_f × (1 + Σ [inhibitor_a]/ki_val) ≈ km_b
        # Therefore: km_f = km_b / (1 + Σ [inhibitor_a]/ki_val)
        inhibitors = regulators.get('inhibitors', [])

        # Calculate inhibitor sum term
        inhibitor_sum = 0.0
        for inhibitor in inhibitors:
            inhibitor_conc = self._get_regulator_concentration(inhibitor, target_concentrations)
            inhibitor_sum += inhibitor_conc / ki_val

        # Avoid division by zero
        inhibitor_denominator = 1.0 + inhibitor_sum
        if inhibitor_denominator == 0:
            inhibitor_denominator = 1.0

        # Apply formula: km_f = km_b / (1 + Σ [inhibitor_a]/ki_val)
        km_f_value = km_b_value / inhibitor_denominator

        for param in all_km_f:
            if param.startswith('Ki'):
                # Ki parameters are set to constant ki_val
                parameter_values[param] = ki_val
            else:  # Km parameter
                # Apply the calculated km_f value
                parameter_values[param] = km_f_value

        return parameter_values

    def apply_parameters(self, parameter_dict: Dict[str, float]) -> ModelBuilder:
        """
        Apply tuned parameters to the model.

        Args:
            parameter_dict: Dictionary of parameter values from generate_parameters()

        Returns:
            New ModelBuilder object with applied parameters
        """
        # Create a copy of the model
        new_model = self.model.copy()

        # Apply all parameters
        for param_name, param_value in parameter_dict.items():
            new_model.set_parameter(param_name, param_value)

        return new_model

    def get_target_concentrations(self) -> Dict[str, float]:
        """
        Get the target active concentrations for all species.

        Returns:
            Dictionary mapping active state names to target concentrations
        """
        return self._target_concentrations

generate_parameters(active_percentage_range: Tuple[float, float] = (0.3, 0.7), X_total_multiplier: float = 5.0, ki_val: float = 100.0, v_max_f_random_range: Tuple[float, float] = (5.0, 10.0)) -> Dict[str, float]

Generate kinetic parameters to achieve target active percentages.

Parameters:

Name Type Description Default
active_percentage_range Tuple[float, float]

Range for target active percentages (e.g., (0.3, 0.7))

(0.3, 0.7)
X_total_multiplier float

Multiplier for setting km_b = X_total × multiplier

5.0
ki_val float

Constant value for all inhibition constants Ki

100.0
v_max_f_random_range Tuple[float, float]

Range for total forward vmax (Σ kc_i × [Y_i_a])

(5.0, 10.0)

Returns:

Type Description
Dict[str, float]

Dictionary mapping parameter names to tuned values

Raises:

Type Description
ValueError

If target active percentages cannot be achieved

RuntimeError

If parameter structure doesn't match expected pattern

Source code in src/synthetic/utils/kinetic_tuner.py
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
def generate_parameters(
    self,
    active_percentage_range: Tuple[float, float] = (0.3, 0.7),
    X_total_multiplier: float = 5.0,
    ki_val: float = 100.0,
    v_max_f_random_range: Tuple[float, float] = (5.0, 10.0)
) -> Dict[str, float]:
    """
    Generate kinetic parameters to achieve target active percentages.

    Args:
        active_percentage_range: Range for target active percentages (e.g., (0.3, 0.7))
        X_total_multiplier: Multiplier for setting km_b = X_total × multiplier
        ki_val: Constant value for all inhibition constants Ki
        v_max_f_random_range: Range for total forward vmax (Σ kc_i × [Y_i_a])

    Returns:
        Dictionary mapping parameter names to tuned values

    Raises:
        ValueError: If target active percentages cannot be achieved
        RuntimeError: If parameter structure doesn't match expected pattern
    """
    # Step 1: Initialize target active concentrations for all species
    if not self._target_concentrations:
        self._initialize_target_concentrations(active_percentage_range)
    else: 
        print("Using existing target concentrations")

    target_concentrations = self._target_concentrations

    # Step 2: Process each activated species to determine parameters
    parameter_values = {}

    for active_state in self.active_states.keys():
        # Get corresponding inactive state
        inactive_state = active_state[:-1]

        # Get total concentration (inactive + active)
        X_total = self.all_states[inactive_state] + self.all_states[active_state]

        # Get target active concentration
        X_a_target = target_concentrations[active_state]
        p_target = X_a_target / X_total

        # Get parameters for this state
        params = get_parameters_for_state(self.model, active_state)
        forward_params = params['as_product']
        backward_params = params['as_reactant']

        # Categorize parameters
        km_b = [p for p in backward_params if p.startswith('Km')]
        km_f = [p for p in forward_params if p.startswith('Km')]
        ki_f = [p for p in forward_params if p.startswith('Ki')]
        vmax_f = [p for p in forward_params if p.startswith('Vmax')]
        kc_f = [p for p in forward_params if p.startswith('Kc')]

        # Combine related parameter types
        all_km_f = km_f + ki_f  # Km and Ki both affect denominator
        all_vmax_f = vmax_f + kc_f  # Vmax and Kc both contribute to numerator

        # Get backward Vmax
        vmax_b = [p for p in backward_params if p.startswith('Vmax')]

        # Validate parameter structure
        if not vmax_b:
            raise ValueError(f"No backward Vmax found for state {active_state}")
        if len(vmax_b) > 1:
            raise ValueError(f"Multiple backward Vmax found for state {active_state}: {vmax_b}")

        # Step 3: Identify regulators for this state using ModelBuilder mapping
        regulators = self._identify_regulators_for_state(active_state, forward_params)

        # Step 4: Solve for parameters using the corrected kinetic equations
        state_params = self._solve_state_parameters(
            active_state=active_state,
            X_total=X_total,
            p_target=p_target,
            all_vmax_f=all_vmax_f,
            regulators=regulators,
            vmax_b_param=vmax_b[0],
            all_km_f=all_km_f,
            km_b_params=km_b,
            target_concentrations=target_concentrations,
            X_total_multiplier=X_total_multiplier,
            ki_val=ki_val,
            v_max_f_random_range=v_max_f_random_range
        )

        parameter_values.update(state_params)

    return parameter_values

get_target_concentrations() -> Dict[str, float]

Get the target active concentrations for all species.

Returns:

Type Description
Dict[str, float]

Dictionary mapping active state names to target concentrations

Source code in src/synthetic/utils/kinetic_tuner.py
496
497
498
499
500
501
502
503
def get_target_concentrations(self) -> Dict[str, float]:
    """
    Get the target active concentrations for all species.

    Returns:
        Dictionary mapping active state names to target concentrations
    """
    return self._target_concentrations

synthetic.utils.make_feature_data.make_feature_data(initial_values: Dict[str, float], perturbation_type: str, perturbation_params: Dict[str, Any], n_samples: int, seed: Optional[int] = None) -> pd.DataFrame

Generate feature data using specified perturbation type.

This function provides a unified interface for generating feature data using the enhanced perturbation functions from PerturbationUtils.

Parameters:

Name Type Description Default
initial_values Dict[str, float]

Dictionary mapping parameter names to initial values

required
perturbation_type str

Type of perturbation ('uniform', 'gaussian', 'lognormal', 'lhs', 'conserve_rules')

required
perturbation_params Dict[str, Any]

Parameters for the perturbation distribution

required
n_samples int

Number of samples to generate

required
seed Optional[int]

Random seed for reproducibility

None

Returns:

Type Description
DataFrame

DataFrame with shape (n_samples, n_parameters)

Raises:

Type Description
ValueError

If parameters are invalid or unsupported perturbation type

Examples:

>>> initial_values = {'A': 10.0, 'B': 20.0}
>>> params = {'std': 2.0}
>>> df = make_feature_data(initial_values, 'gaussian', params, n_samples=100, seed=42)
Source code in src/synthetic/utils/make_feature_data.py
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
def make_feature_data(
    initial_values: Dict[str, float],
    perturbation_type: str,
    perturbation_params: Dict[str, Any],
    n_samples: int,
    seed: Optional[int] = None
) -> pd.DataFrame:
    """
    Generate feature data using specified perturbation type.

    This function provides a unified interface for generating feature data
    using the enhanced perturbation functions from PerturbationUtils.

    Args:
        initial_values: Dictionary mapping parameter names to initial values
        perturbation_type: Type of perturbation ('uniform', 'gaussian', 'lognormal', 'lhs', 'conserve_rules')
        perturbation_params: Parameters for the perturbation distribution
        n_samples: Number of samples to generate
        seed: Random seed for reproducibility

    Returns:
        DataFrame with shape (n_samples, n_parameters)

    Raises:
        ValueError: If parameters are invalid or unsupported perturbation type

    Examples:
        >>> initial_values = {'A': 10.0, 'B': 20.0}
        >>> params = {'std': 2.0}
        >>> df = make_feature_data(initial_values, 'gaussian', params, n_samples=100, seed=42)
    """
    # Validate initial values
    validate_initial_values(initial_values)

    # Validate perturbation parameters
    validate_feature_data_params(perturbation_type, perturbation_params)

    # Map perturbation type to appropriate generator
    generator_map = {
        'uniform': generate_uniform_perturbation_dataframe,
        'gaussian': generate_gaussian_perturbation_dataframe,
        'lognormal': generate_lognormal_perturbation_dataframe,
        'lhs': generate_lhs_perturbation_dataframe,
        'conserve_rules': make_feature_data_conserve_rules
    }

    if perturbation_type not in generator_map:
        raise ValueError(
            f"Unsupported perturbation type: {perturbation_type}. "
            f"Supported types: {list(generator_map.keys())}"
        )

    # Get the appropriate generator function
    generator = generator_map[perturbation_type]

    # Generate the dataframe
    if perturbation_type == 'conserve_rules':
        # Special handling for conserve_rules to pass model_spec if available
        model_spec = perturbation_params.pop('model_spec', None)
        df = generator(
            initial_values=initial_values,
            perturbation_params=perturbation_params,
            n_samples=n_samples,
            seed=seed,
            model_spec=model_spec
        )
        # Restore model_spec if it was removed
        if model_spec is not None:
            perturbation_params['model_spec'] = model_spec
    else:
        df = generator(
            initial_values=initial_values,
            perturbation_params=perturbation_params,
            n_samples=n_samples,
            seed=seed
        )

    return df

synthetic.utils.make_target_data.make_target_data_with_params(solver: Solver, feature_df: pd.DataFrame, parameter_df: pd.DataFrame = None, simulation_params: Dict[str, Any] = None, n_cores: int = 1, outcome_var: str = 'Cp', capture_all_species: bool = False, verbose: bool = False, target_method: str = 'last_point') -> Tuple[pd.DataFrame, Union[List[np.ndarray], pd.DataFrame]]

Generate target data with optional kinetic parameter perturbation.

Parameters:

Name Type Description Default
solver Solver

Solver object (ScipySolver or RoadrunnerSolver) - can load any SBML/Antimony model

required
feature_df DataFrame

DataFrame of perturbed initial values

required
parameter_df DataFrame

DataFrame of perturbed kinetic parameters (optional)

None
simulation_params Dict[str, Any]

Dictionary with 'start', 'end', 'points' keys

None
n_cores int

Number of cores for parallel processing (-1 for all cores)

1
outcome_var str

Variable to extract as target

'Cp'
capture_all_species bool

If True, returns DataFrame with timecourses for all species. If False, returns list of arrays for outcome_var only.

False
verbose bool

Whether to show progress bar

False
target_method str

Method for calculating target values ('last_point' or 'fold_change_drug'). 'last_point' (default) returns last time point value. 'fold_change_drug' returns fold change from drug start to end time.

'last_point'

Returns:

Type Description
DataFrame

Tuple of (target_df, time_course_data)

Union[List[ndarray], DataFrame]

time_course_data is either List[np.ndarray] (if capture_all_species=False)

Tuple[DataFrame, Union[List[ndarray], DataFrame]]

or pd.DataFrame (if capture_all_species=True)

Source code in src/synthetic/utils/make_target_data.py
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
def make_target_data_with_params(
    solver: Solver,
    feature_df: pd.DataFrame,
    parameter_df: pd.DataFrame = None,
    simulation_params: Dict[str, Any] = None,
    n_cores: int = 1,
    outcome_var: str = "Cp",
    capture_all_species: bool = False,
    verbose: bool = False,
    target_method: str = "last_point",
) -> Tuple[pd.DataFrame, Union[List[np.ndarray], pd.DataFrame]]:
    """
    Generate target data with optional kinetic parameter perturbation.

    Args:
        solver: Solver object (ScipySolver or RoadrunnerSolver) - can load any SBML/Antimony model
        feature_df: DataFrame of perturbed initial values
        parameter_df: DataFrame of perturbed kinetic parameters (optional)
        simulation_params: Dictionary with 'start', 'end', 'points' keys
        n_cores: Number of cores for parallel processing (-1 for all cores)
        outcome_var: Variable to extract as target
        capture_all_species: If True, returns DataFrame with timecourses for all species.
                           If False, returns list of arrays for outcome_var only.
        verbose: Whether to show progress bar
        target_method: Method for calculating target values ('last_point' or 'fold_change_drug').
                      'last_point' (default) returns last time point value.
                      'fold_change_drug' returns fold change from drug start to end time.

    Returns:
        Tuple of (target_df, time_course_data)
        time_course_data is either List[np.ndarray] (if capture_all_species=False)
        or pd.DataFrame (if capture_all_species=True)
    """
    # Import target calculator
    from .target_calculators import calculate_target_from_series

    # Set default simulation parameters
    if simulation_params is None:
        simulation_params = {"start": 0, "end": 500, "points": 100}

    # Validate simulation parameters
    if (
        "start" not in simulation_params
        or "end" not in simulation_params
        or "points" not in simulation_params
    ):
        raise ValueError(
            'Simulation parameters must contain "start", "end" and "points" keys'
        )

    start = simulation_params["start"]
    end = simulation_params["end"]
    points = simulation_params["points"]

    # Calculate drug start time for fold_change_drug method
    # Note: make_target_data_with_params doesn't have drug_start_time parameter,
    # so for fold_change_drug we use the midpoint as drug start
    used_drug_start_time = (start + end) / 2

    # Determine species to capture
    species_to_capture = []
    if capture_all_species:
        # Instead of trying to get species from model_spec (deprecated method),
        # we'll capture all species that appear in simulation results.
        # We'll do an initial simulation to discover available species
        try:
            # Use first row of feature_df to get simulation results format
            test_values = feature_df.iloc[0].to_dict()
            solver.set_state_values(test_values)
            if parameter_df is not None:
                test_param_values = parameter_df.iloc[0].to_dict()
                solver.set_parameter_values(test_param_values)

            test_res = solver.simulate(start, end, points)

            # Capture all columns except 'time' and any drug columns
            all_columns = list(test_res.columns)
            species_to_capture = [
                col for col in all_columns if col != "time" and col != outcome_var
            ]

            # Also include outcome_var if not already included
            if outcome_var not in species_to_capture:
                species_to_capture.append(outcome_var)

        except Exception as e:
            # If test simulation fails, fall back to empty list
            # We'll still try to capture species from actual simulations
            warnings.warn(f"Could not discover species from test simulation: {e}")
            species_to_capture = []

    def simulate_perturbation_single(i: int) -> Tuple[float, np.ndarray]:
        """Simulate a single perturbation and capture only outcome_var."""
        perturbed_values = feature_df.iloc[i].to_dict()

        # Set perturbed initial values into solver
        solver.set_state_values(perturbed_values)

        # Set perturbed kinetic parameters if provided
        if parameter_df is not None:
            parameter_values = parameter_df.iloc[i].to_dict()
            solver.set_parameter_values(parameter_values)

        # Run simulation
        res = solver.simulate(start, end, points)

        # Extract target value and time course
        target_value = calculate_target_from_series(
            series=res[outcome_var],
            target_method=target_method,
            simulation_params=simulation_params,
            drug_start_time=used_drug_start_time,
        )
        time_course = res[outcome_var].values

        return target_value, time_course

    def simulate_perturbation_all_species(
        i: int,
    ) -> Tuple[float, Dict[str, np.ndarray]]:
        """Simulate a single perturbation and capture timecourses for all species."""
        perturbed_values = feature_df.iloc[i].to_dict()

        # Set perturbed initial values into solver
        solver.set_state_values(perturbed_values)

        # Set perturbed kinetic parameters if provided
        if parameter_df is not None:
            parameter_values = parameter_df.iloc[i].to_dict()
            solver.set_parameter_values(parameter_values)

        # Run simulation
        res = solver.simulate(start, end, points)

        # Extract target value
        target_value = calculate_target_from_series(
            series=res[outcome_var],
            target_method=target_method,
            simulation_params=simulation_params,
            drug_start_time=used_drug_start_time,
        )

        # Capture timecourses for all species
        time_courses = {}
        for species in species_to_capture:
            if species in res.columns:
                time_courses[species] = res[species].values

        return target_value, time_courses

    if capture_all_species:
        # Use parallel processing if requested
        if n_cores > 1 or n_cores == -1:
            results = Parallel(n_jobs=n_cores)(
                delayed(simulate_perturbation_all_species)(i)
                for i in tqdm(
                    range(feature_df.shape[0]),
                    desc="Simulating perturbations",
                    disable=not verbose,
                )
            )
            all_targets, time_course_dicts = zip(*results)
            all_targets = list(all_targets)
            time_course_dicts = list(time_course_dicts)
        else:
            # Sequential processing
            all_targets = []
            time_course_dicts = []

            for i in tqdm(
                range(feature_df.shape[0]),
                desc="Simulating perturbations",
                disable=not verbose,
            ):
                target_value, time_courses = simulate_perturbation_all_species(i)
                all_targets.append(target_value)
                time_course_dicts.append(time_courses)

        # Create target DataFrame
        target_df = pd.DataFrame(all_targets, columns=[outcome_var])

        # Create timecourse DataFrame
        timecourse_df = pd.DataFrame(time_course_dicts)

        return target_df, timecourse_df
    else:
        # Use parallel processing if requested
        if n_cores > 1 or n_cores == -1:
            results = Parallel(n_jobs=n_cores)(
                delayed(simulate_perturbation_single)(i)
                for i in tqdm(
                    range(feature_df.shape[0]),
                    desc="Simulating perturbations",
                    disable=not verbose,
                )
            )
            all_targets, time_course_data = zip(*results)
            all_targets = list(all_targets)
            time_course_data = list(time_course_data)
        else:
            # Sequential processing
            all_targets = []
            time_course_data = []

            for i in tqdm(
                range(feature_df.shape[0]),
                desc="Simulating perturbations",
                disable=not verbose,
            ):
                target_value, time_course = simulate_perturbation_single(i)
                all_targets.append(target_value)
                time_course_data.append(time_course)

        # Create target DataFrame
        target_df = pd.DataFrame(all_targets, columns=[outcome_var])

        return target_df, time_course_data

synthetic.utils.make_target_data.calculate_targets_from_timecourse(timecourse_data: Union[pd.DataFrame, List[np.ndarray]], outcome_var: str, target_method: str = 'last_point', simulation_params: Optional[Dict[str, Any]] = None, drug_start_time: Optional[float] = None) -> pd.DataFrame

Calculate target values from timecourse data.

This is the target generation component that processes timecourse arrays to generate target values using specified methods.

Parameters:

Name Type Description Default
timecourse_data Union[DataFrame, List[ndarray]]

Timecourse data (DataFrame with species columns or list of outcome arrays)

required
outcome_var str

Variable to extract as target

required
target_method str

Method for calculating targets ('last_point' or 'fold_change_drug')

'last_point'
simulation_params Optional[Dict[str, Any]]

Simulation parameters (required for fold_change_drug)

None
drug_start_time Optional[float]

Drug start time (required for fold_change_drug)

None

Returns:

Type Description
DataFrame

DataFrame with single column containing target values

Raises:

Type Description
ValueError

If target_method is invalid or required parameters missing

Examples:

>>> timecourse_df = pd.DataFrame({
...     'Cp': [np.array([1, 2, 3]), np.array([4, 5, 6])],
...     'Oa': [np.array([0.5, 1.0, 1.5]), np.array([2.0, 2.5, 3.0])]
... })
>>> targets = calculate_targets_from_timecourse(
...     timecourse_df, 'Cp', target_method='last_point'
... )
>>> targets
    Cp
0  3.0
1  6.0
Source code in src/synthetic/utils/make_target_data.py
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
def calculate_targets_from_timecourse(
    timecourse_data: Union[pd.DataFrame, List[np.ndarray]],
    outcome_var: str,
    target_method: str = "last_point",
    simulation_params: Optional[Dict[str, Any]] = None,
    drug_start_time: Optional[float] = None,
) -> pd.DataFrame:
    """
    Calculate target values from timecourse data.

    This is the target generation component that processes timecourse arrays
    to generate target values using specified methods.

    Args:
        timecourse_data: Timecourse data (DataFrame with species columns or list of outcome arrays)
        outcome_var: Variable to extract as target
        target_method: Method for calculating targets ('last_point' or 'fold_change_drug')
        simulation_params: Simulation parameters (required for fold_change_drug)
        drug_start_time: Drug start time (required for fold_change_drug)

    Returns:
        DataFrame with single column containing target values

    Raises:
        ValueError: If target_method is invalid or required parameters missing

    Examples:
        >>> timecourse_df = pd.DataFrame({
        ...     'Cp': [np.array([1, 2, 3]), np.array([4, 5, 6])],
        ...     'Oa': [np.array([0.5, 1.0, 1.5]), np.array([2.0, 2.5, 3.0])]
        ... })
        >>> targets = calculate_targets_from_timecourse(
        ...     timecourse_df, 'Cp', target_method='last_point'
        ... )
        >>> targets
            Cp
        0  3.0
        1  6.0
    """

    if isinstance(timecourse_data, pd.DataFrame):
        # DataFrame format: extract outcome_var and calculate targets
        if outcome_var not in timecourse_data.columns:
            raise ValueError(
                f"outcome_var '{outcome_var}' not found in timecourse_data columns"
            )

        target_values = []
        for idx, row in timecourse_data.iterrows():
            series_array = row[outcome_var]
            series = pd.Series(series_array)
            target = calculate_target_from_series(
                series=series,
                target_method=target_method,
                simulation_params=simulation_params,
                drug_start_time=drug_start_time,
            )
            target_values.append(target)

        target_df = pd.DataFrame(
            {outcome_var: target_values}, index=timecourse_data.index
        )
    else:
        # List format: each item is already outcome_var timecourse
        target_values = []
        for timecourse in timecourse_data:
            series = pd.Series(timecourse)
            target = calculate_target_from_series(
                series=series,
                target_method=target_method,
                simulation_params=simulation_params,
                drug_start_time=drug_start_time,
            )
            target_values.append(target)

        target_df = pd.DataFrame({outcome_var: target_values})

    return target_df