Skip to content

ModelBuilder API

Back to API Reference

Builds a Model. Guide: Building Models, Transitions.

ModelBuilder

A fluent interface that writes the process of a model, once.

The builder adds bins, accumulators, stratifications, transitions and parameters: the process, which is the same for every kind of model. build joins it with a structure, which lays the process out (such as Aggregate, amounts per compartment), and an engine, which runs it. Each method that adds returns the builder, so the calls chain.

Source code in commol/api/model_builder.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
 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
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
563
564
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
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
class ModelBuilder:
    """
    A fluent interface that writes the process of a model, once.

    The builder adds bins, accumulators, stratifications, transitions and
    parameters: the process, which is the same for every kind of model.
    `build` joins it with a structure, which lays the process out (such as
    `Aggregate`, amounts per compartment), and an engine, which runs it.
    Each method that adds returns the builder, so the calls chain.
    """

    def __init__(
        self,
        name: str,
        description: str | None = None,
        version: str | None = None,
        bin_unit: str | None = None,
        step_unit: str | None = None,
        origin: date | None = None,
    ) -> None:
        """
        Initialize the ModelBuilder.

        Parameters
        ----------
        name : str
            The unique name that identifies the model.
        description : str | None, default=None
            A human-readable description of the model's purpose and function.
        version : str | None, default=None
            The version number of the model.
        bin_unit : str | None, default=None
            The default unit for all bins.
            Individual bins can override this with their own unit parameter.
            Units are optional but required for model.check_unit_consistency().
        step_unit : str | None, default=None
            Unit of one step on the axis, of any single dimension (for example
            ``"day"`` or ``"meter"``). The unit check requires every flow to be
            ``<bin unit>/<step_unit>``, and ``Model.axis_units()`` converts
            values to steps of it. None means ``step``, the default increment
            of any axis.
        origin : date | None, default=None
            Calendar moment of position 0: a `datetime.datetime` with no time
            zone, or a `datetime.date`, read as its midnight. With it,
            ``Model.axis_units()`` converts between dates and positions, and
            ``results.plot.series()`` labels its ticks with dates. It
            needs a ``step_unit`` of time whose length is a whole number of
            days or a whole fraction of a day, such as ``"hour"`` or
            ``"day"``; `build` raises ``ValueError`` otherwise, or for a
            moment with a time zone.
        """
        self._name: str = name
        self._description: str | None = description
        self._version: str | None = version
        self._bin_unit: str | None = bin_unit
        self._step_unit: str | None = step_unit
        self._origin: date | None = origin

        self._bins: list[Bin] = []
        self._accumulators: list[Accumulator] = []
        self._stratifications: list[Stratification] = []
        self._transitions: list[Transition] = []
        self._parameters: list[Parameter] = []
        self._series_counter: int = 0

        logger.info(
            (
                f"Initialized ModelBuilder: name='{self._name}', "
                f"version='{self._version or 'N/A'}'"
            )
        )

    def add_bin(self, id: str, name: str, unit: str | None = None) -> Self:
        """
        Add a bin to the model.

        Parameters
        ----------
        id : str
            Unique identifier for the bin.
        name : str
            Human-readable name for the bin.
        unit : str | None, default=None
            Unit of measurement for this bin. If None, uses the model-level bin_unit.

        Returns
        -------
        ModelBuilder
            Self for method chaining.
        """
        # Use bin-specific unit, or fall back to model-level bin_unit
        final_unit = unit if unit is not None else self._bin_unit
        self._bins.append(Bin(id=id, name=name, unit=final_unit))
        logger.info(f"Added bin: id='{id}', name='{name}', unit='{final_unit}'")
        return self

    def add_accumulator(self, id: str, name: str) -> Self:
        """
        Add an accumulator: a cumulative event counter in the model outputs.

        A transition adds its flow to the accumulators it names
        (``add_transition(accumulators=...)``). An accumulator is an output,
        not a part of the state, so ``total`` leaves it out.

        Parameters
        ----------
        id : str
            Unique identifier for the accumulator. It names its output, which
            stratifications expand as they expand a bin (``acc_g1``,
            ``acc_g2``).
        name : str
            Human-readable name for the accumulator.

        Returns
        -------
        ModelBuilder
            Self for method chaining.
        """
        self._accumulators.append(Accumulator(id=id, name=name))
        logger.info(f"Added accumulator: id='{id}', name='{name}'")
        return self

    def add_stratification(
        self,
        id: str,
        categories: list[str],
        description: str | None = None,
        conditions: list[StratificationConditionDict] | None = None,
    ) -> Self:
        """
        Add a stratification to the model.

        Parameters
        ----------
        id : str
            Unique identifier for the stratification.
        categories : list[str]
            list of category identifiers within this stratification.
        description : str | None, default=None
            Human-readable description of the stratification.
        conditions : list[dict] | None, default=None
            When set, this stratification only expands compartments whose
            already-applied categories satisfy ALL conditions. Each dict must
            contain "stratification" and "category" keys referencing a
            stratification declared before this one.

            Example: only apply the `sub` stratification to `group1`::

                conditions = [{"stratification": "group", "category": "group1"}]

        Returns
        -------
        ModelBuilder
            Self for method chaining.

        Raises
        ------
        ValueError
            If any condition references a stratification not yet declared.
        """
        if conditions:
            declared_ids = {s.id for s in self._stratifications}
            for cond in conditions:
                if cond["stratification"] not in declared_ids:
                    raise ValueError(
                        f"Stratification '{id}': condition references "
                        f"'{cond['stratification']}' which has not been declared yet. "
                        "Conditions may only reference stratifications declared before "
                        "this one."
                    )

        condition_objects = (
            [StratificationCondition(**c) for c in conditions] if conditions else None
        )
        self._stratifications.append(
            Stratification(
                id=id,
                categories=categories,
                description=description,
                conditions=condition_objects,
            )
        )
        logger.info(f"Added stratification: id='{id}', categories={categories}")
        return self

    def add_parameter(
        self,
        id: str,
        value: float | str | list[tuple[float, float]] | None,
        description: str | None = None,
        unit: str | None = None,
        mode: str | None = None,
    ) -> Self:
        """
        Add a global parameter to the model.

        Parameters
        ----------
        id : str
            Unique identifier for the parameter.
        value : float | str | list[tuple[float, float]] | None
            Value of the parameter. Can be:
            - float: A numerical constant value
            - str: A mathematical formula that can reference other parameters,
                   special variables (total, total_<category>, step, t, pi, e),
                   or contain mathematical expressions (e.g., "k1 * 2",
                   "total_g1 / total")
            - list[tuple[float, float]]: Empirical series as (position, value)
                   points; requires ``mode`` to be set.
            - None: Indicates that the parameter needs to be calibrated before use

        description : str | None, default=None
            Human-readable description of the parameter.
        unit : str | None, default=None
            Unit of the parameter (e.g., "1/day", "dimensionless", "item").
            Used for unit consistency checking in equations.
        mode : str | None, default=None
            Required when ``value`` is a list of (position, value) points.
            Selects how the series is read: ``"pulse"`` (the value on the step
            of a point, 0 on every other step; integer positions only),
            ``"step_function"`` (the value of the last point at or before
            ``t``), or ``"linear"`` (linear interpolation in ``t``).

        Returns
        -------
        ModelBuilder
            Self for method chaining.

        Raises
        ------
        ValueError
            If ``value`` is a list but ``mode`` is not provided, if
            ``mode`` is provided without a list ``value``, or if a formula
            ``value`` fails the security check or is not in the language of
            formulas.
        """
        if isinstance(value, list):
            if mode is None:
                raise ValueError(
                    f"Parameter '{id}': 'mode' is required when 'value' is a "
                    "series list. Use mode='pulse', 'step_function', or 'linear'."
                )
            param_value: float | str | SeriesValue | None = SeriesValue(
                data=value, mode=mode
            )
        else:
            if mode is not None:
                raise ValueError(
                    f"Parameter '{id}': 'mode' is only valid when 'value' is a "
                    "series list."
                )
            param_value = value
        self._ensure_parameter_id_available(id)
        self._parameters.append(
            Parameter(id=id, value=param_value, description=description, unit=unit)
        )
        logger.info(f"Added parameter: id='{id}', value={value}, unit='{unit}'")
        return self

    def _ensure_parameter_id_available(self, id: str) -> None:
        if any(parameter.id == id for parameter in self._parameters):
            raise ValueError(f"Parameter id '{id}' already exists")

    def _register_series_pattern(
        self,
        pattern: AxisPattern,
        *,
        transition_id: str,
        source_bin: str,
        target_bin: str,
    ) -> AxisPattern:
        """Auto-register a series parameter for pulse-type patterns.

        If ``pattern`` has numeric pulse data, registers a ``"pulse"`` series
        parameter and returns a ``_ComputedAxisPattern`` whose formula is the
        generated parameter name. Otherwise returns ``pattern`` unchanged.
        """
        data = pattern._as_series_data()
        if data is None:
            return pattern
        conditions = pattern.conditions
        if transition_id and conditions:
            src_cats = "_".join(c["category"] for c in conditions if "category" in c)
            tgt_cats = "_".join(
                c["to"] if "to" in c else c["category"]
                for c in conditions
                if "to" in c or "category" in c
            )
            src = f"{source_bin}_{src_cats}" if source_bin else src_cats
            tgt = f"{target_bin}_{tgt_cats}" if target_bin else tgt_cats
            param_name = f"{transition_id}_{src}_to_{tgt}"
        else:
            param_name = f"_series_{self._series_counter}"
            self._series_counter += 1
        self._ensure_parameter_id_available(param_name)
        self._parameters.append(
            Parameter(
                id=param_name,
                value=SeriesValue(data=data, mode="pulse"),
            )
        )
        return _ComputedAxisPattern(
            computed_formula=param_name,
            conditions=conditions,
            source_compartment=pattern.source_compartment,
        )

    def add_transition(
        self,
        id: str,
        source: list[str],
        target: list[str],
        rate: "str | float | AxisPattern | None" = None,
        stratified_rates: list[StratifiedRateDict] | None = None,
        per_compartment: bool | None = None,
        accumulators: list[str] | None = None,
        impulse_at: list[float] | None = None,
        impulse_every: tuple[float, float] | None = None,
    ) -> Self:
        """
        Add a transition between states to the model.

        This method supports two distinct behaviors:

        When you specify multiple sources without the $compartment placeholder,
        a single transition is created that affects all sources simultaneously.
        The rate is evaluated once, at each position the engine reads it, and
        that value applies to all source compartments at once. What the value
        means (an amount moved in one step or an instantaneous rate) is the
        engine's; see "What a rate means" in the Core Concepts guide.

        When you use the $compartment placeholder in the rate formula with multiple
        sources, the system automatically expands this into multiple independent
        transitions - one for each source compartment. Each transition has its own
        rate calculation where $compartment is replaced with the actual compartment
        name.

        Each transition's rate is evaluated independently, giving per-compartment
        dynamics. This suits an outflow such as ``k1 * $compartment``, where the
        flow of each compartment is proportional to its own amount.

        **$compartment Usage Rules**:
        - Only valid with several sources (and one or no target) or several
          targets (and one or no source)
        - Can be used with stratified_rates - the placeholder will be expanded in
          both the base rate and all stratified rate expressions
        - The placeholder $compartment will be replaced with each source compartment
          name

        **$compartment Restrictions**:
        - Using $compartment with a single source will raise an error (use the
          compartment name directly instead)
        - Using $compartment with multiple targets will raise an error (ambiguous
          which target corresponds to which source)

        Parameters
        ----------
        id : str
            Unique identifier for the transition. When using $compartment expansion,
            the system will append "__<compartment_name>" to create unique IDs for
            each expanded transition (e.g., "out__A", "out__B").
        source : list[str]
            List of source state/category identifiers. When using $compartment in
            the rate, each source will generate a separate transition.
        target : list[str]
            List of target state/category identifiers. When using $compartment
            with several targets, each target generates a separate transition.
        rate : str | float | AxisPattern | None, default=None
            Default mathematical formula, parameter reference, or constant value for
            the transition rate. Used when no stratified rate matches.
            Can be:
            - A parameter reference
            - A constant value
            - A mathematical formula
            - A formula with $compartment placeholder

            Special variables available in formulas:
            - total: The sum of every compartment, accumulators excluded
            - total_<category>…: The sum of the compartments with these
              categories, in the declaration order of the stratifications
            - t: The current position on the axis
            - step: The step that holds it, ``floor(t)``; in a
              DifferenceEquations model ``t`` and ``step`` are equal
            - pi, e: Mathematical constants
            - $compartment: Expands to each source compartment name (only with
              multiple sources)

        stratified_rates : list[dict] | None, default=None
            List of stratification-specific rates. Each dict must contain:
            - "conditions": List of dicts with "stratification" and "category" keys
            - "rate": Rate expression string

        per_compartment : bool | None, default=None
            When True, each id of a source or target bin in a rate reads the
            compartment of the flow (``A_g1``) instead of the total of the bin.
            Any other bin keeps its total: in a transition from ``A`` to ``B``,
            ``k * A * (C + D) / total`` reads ``A_g1`` and the totals of ``C``
            and ``D``. It applies to the fallback rate, to every stratified
            rate, and to every transition that ``$compartment`` expands to,
            where ``$compartment`` reads the compartment that flows. A
            transition between categories ignores it.

        accumulators : list[str] | None, default=None
            Ids of accumulators that add up the flow of this transition.

        impulse_at : list[float] | None, default=None
            Make the transition an impulse at these positions on the axis. At
            each one, ``rate`` is the fraction of the source (proportional) or the
            amount (absolute) moved at once, before the flows of that step. A
            DifferenceEquations or StochasticSteps model needs integer
            positions.

        impulse_every : tuple[float, float] | None, default=None
            ``(period, offset)``: make the transition an impulse at ``offset``,
            ``offset + period``, ``offset + 2 * period``, ...

        Returns
        -------
        ModelBuilder
            Self for method chaining.

        Raises
        ------
        ValueError
            - If $compartment is used with only one source compartment
            - If $compartment is used with multiple targets
            - If rate is None when using $compartment
        """
        # If `rate` is a AxisPattern, extract its rate string and stratified
        # rates and route them into the existing pipeline. A AxisPattern fully
        # specifies how the rate changes along the axis, so passing `stratified_rates=`
        # alongside it is a conflict.
        if isinstance(rate, AxisPattern):
            if impulse_at is not None or impulse_every is not None:
                raise ValueError(
                    f"Transition '{id}': an impulse moves its rate at once; pass "
                    "a fraction or an amount as `rate=`, not a AxisPattern."
                )
            if stratified_rates is not None:
                raise ValueError(
                    f"Transition '{id}': pass either a AxisPattern as `rate=` "
                    "or `stratified_rates=`, not both."
                )
            src_bin = source[0] if source else ""
            tgt_bin = target[0] if target else ""
            if isinstance(rate, _ScheduleAxisPattern):
                resolved = rate.model_copy(
                    update={
                        "patterns": [
                            _GroupEntry(
                                pattern=self._register_series_pattern(
                                    entry.pattern,
                                    transition_id=id,
                                    source_bin=src_bin,
                                    target_bin=tgt_bin,
                                ),
                                absolute=entry.absolute,
                            )
                            for entry in rate.patterns
                        ]
                    }
                )
                rate = resolved
            else:
                rate = self._register_series_pattern(
                    rate, transition_id=id, source_bin=src_bin, target_bin=tgt_bin
                )
            stratified_rates = rate._builder_stratified_rates()
            rate = rate._builder_rate()

        # Convert rate to string if numeric
        if isinstance(rate, int) or isinstance(rate, float):
            rate = str(rate)

        # Check for $compartment placeholder and handle expansion
        if rate and "$compartment" in rate:
            self._validate_compartment_placeholder(id, source, target)
            self._expand_compartment_transition(
                id,
                source,
                target,
                rate,
                stratified_rates,
                per_compartment,
                accumulators,
                impulse_at,
                impulse_every,
            )
            return self

        stratified_rates_objects = _stratified_rate_objects(stratified_rates)
        self._transitions.append(
            Transition(
                id=id,
                source=source,
                target=target,
                accumulators=accumulators or [],
                rate=rate,
                stratified_rates=stratified_rates_objects,
                per_compartment=per_compartment,
                impulse_at=impulse_at,
                impulse_every=impulse_every,
            )
        )
        logger.info(
            (
                f"Added transition: id='{id}', source={source}, target={target}, "
                f"rate='{rate}', stratified_rates={
                    len(stratified_rates_objects) if stratified_rates_objects else 0
                }"
            )
        )
        return self

    def _validate_compartment_placeholder(
        self,
        id: str,
        source: list[str],
        target: list[str],
    ) -> None:
        """
        Validate that $compartment placeholder is used correctly.

        Parameters
        ----------
        id : str
            Transition identifier (for error messages)
        source : list[str]
            Source compartments
        target : list[str]
            Target compartments
        rate : str
            Rate formula
        stratified_rates : list[StratifiedRateDict] | None
            Stratified rates

        Raises
        ------
        ValueError
            If $compartment usage violates any rules
        """
        # Check that we have either multiple sources OR multiple targets, but not both
        has_multiple_sources = len(source) > 1
        has_multiple_targets = len(target) > 1

        if not has_multiple_sources and not has_multiple_targets:
            raise ValueError(
                (
                    f"Transition '{id}': $compartment placeholder requires either "
                    f"multiple source compartments or multiple target compartments "
                    f"(found {len(source)} source(s) and {len(target)} target(s)). "
                    f"If you have a single source/target, use the compartment name "
                    f"directly in the rate formula instead of $compartment."
                )
            )

        if has_multiple_sources and has_multiple_targets:
            raise ValueError(
                (
                    f"Transition '{id}': $compartment placeholder cannot be used "
                    f"with both multiple sources and multiple targets "
                    f"(found {len(source)} sources and {len(target)} targets). "
                    f"This would create ambiguous mappings. Use either multiple "
                    f"sources with single/empty target, or single/empty source with "
                    f"multiple targets."
                )
            )

    def _expand_compartment_transition(
        self,
        id: str,
        source: list[str],
        target: list[str],
        rate: str,
        stratified_rates: list[StratifiedRateDict] | None,
        per_compartment: bool | None,
        accumulators: list[str] | None,
        impulse_at: list[float] | None,
        impulse_every: tuple[float, float] | None,
    ) -> None:
        """
        Expand a transition with $compartment placeholder into multiple transitions.

        Parameters
        ----------
        id : str
            Base transition identifier
        source : list[str]
            Source compartments
            (will create one transition per source if multiple sources)
        target : list[str]
            Target compartments
            (will create one transition per target if multiple targets)
        rate : str
            Rate formula containing $compartment
        stratified_rates : list[StratifiedRateDict] | None
            Stratified rates (can contain $compartment which will be expanded)
        per_compartment, accumulators, impulse_at, impulse_every : optional
            The arguments of `add_transition` that every expanded transition
            keeps
        """
        # Determine if we're expanding over sources or targets
        has_multiple_sources = len(source) > 1

        if has_multiple_sources:
            compartments = source
            expand_type = "source"
        else:
            compartments = target
            expand_type = "target"

        logger.info(
            (
                f"Expanding transition '{id}' with $compartment placeholder: "
                f"{len(compartments)} {expand_type} compartments will create "
                f"{len(compartments)} separate transitions"
            )
        )

        for compartment in compartments:
            # Replace $compartment with actual compartment name in base rate
            expanded_rate = rate.replace("$compartment", compartment)

            expanded_stratified_rates = _stratified_rate_objects(
                stratified_rates, compartment
            )

            # Generate unique ID for this expanded transition
            expanded_id = f"{id}__{compartment}"

            # add_transition accepts several sources or several targets.
            if has_multiple_sources:
                expanded_source = [compartment]
                expanded_target = target
            else:
                expanded_source = source
                expanded_target = [compartment]

            self._transitions.append(
                Transition(
                    id=expanded_id,
                    source=expanded_source,
                    target=expanded_target,
                    accumulators=accumulators or [],
                    rate=expanded_rate,
                    stratified_rates=expanded_stratified_rates,
                    per_compartment=per_compartment,
                    impulse_at=impulse_at,
                    impulse_every=impulse_every,
                )
            )

            strat_info = (
                f", {len(expanded_stratified_rates)} stratified rates"
                if expanded_stratified_rates
                else ""
            )
            logger.info(
                (
                    f"  Created expanded transition: id='{expanded_id}', "
                    f"source=['{compartment}'], target={target}, "
                    f"rate='{expanded_rate}'{strat_info}"
                )
            )

        logger.info(
            f"Successfully expanded transition '{id}' into {len(compartments)} "
            "transitions"
        )

    def get_summary(self) -> dict[str, str | int | list[str] | None]:
        """
        Get a summary of the current model builder state.

        Returns
        -------
        dict[str, dict[str, str | int | list[str] | None]]
            Dictionary containing summary information about the model being built.
        """
        return {
            "name": self._name,
            "description": self._description,
            "version": self._version,
            "bins_count": len(self._bins),
            "bin_ids": [state.id for state in self._bins],
            "stratifications_count": len(self._stratifications),
            "stratification_ids": [strat.id for strat in self._stratifications],
            "transitions_count": len(self._transitions),
            "transition_ids": [trans.id for trans in self._transitions],
            "parameters_count": len(self._parameters),
            "parameter_ids": [param.id for param in self._parameters],
        }

    def clone(self) -> Self:
        """
        Create a deep copy of this ModelBuilder.

        Returns
        -------
        ModelBuilder
            A new ModelBuilder instance with the same configuration: every
            bin, accumulator, stratification, transition and parameter.
            Changes to one builder do not affect the other.
        """
        return copy.deepcopy(self)

    def reset(self) -> Self:
        """
        Reset the builder to empty state.

        The name, description, version, ``bin_unit``, ``step_unit`` and
        ``origin`` are kept. Every bin,
        accumulator, stratification, transition and parameter is removed.

        Returns
        -------
        ModelBuilder
            Self for method chaining.
        """
        self._bins.clear()
        self._accumulators.clear()
        self._stratifications.clear()
        self._transitions.clear()
        self._parameters.clear()
        self._series_counter = 0
        return self

    def process(self) -> Process:
        """
        The process the builder has written so far.

        Returns
        -------
        Process
            The bins, accumulators, stratifications and transitions.

        Raises
        ------
        ValueError
            If ids repeat, or a transition or a stratified rate names an id
            the process does not have.
        """
        return Process(
            bins=self._bins,
            accumulators=self._accumulators,
            stratifications=self._stratifications,
            transitions=self._transitions,
        )

    def build(
        self,
        structure: StructureT,
        engine: EngineName,
        settings: EngineSettings | None = None,
    ) -> Model[StructureT]:
        """
        Join the process with a structure and an engine into a model.

        The process is written once; the structure lays it out and sets the
        kind of the model, so one builder builds every kind its process fits:

        ``builder.build(Aggregate(bin_amounts={"A": 990, "B": 10, "C": 0}),
        engine="DifferentialEquations")``

        Parameters
        ----------
        structure : ModelStructure
            How the process is laid out, such as `Aggregate` (amounts per
            compartment). The model is a ``Model`` of its class.
        engine : EngineName
            The engine that runs the model, which must run the kind of the
            structure: ``"DifferenceEquations"`` (discrete time),
            ``"DifferentialEquations"`` (continuous time), ``"StochasticEvents"``
            or ``"StochasticSteps"`` (at random).
        settings : EngineSettings | None, default=None
            Settings of that engine; None uses its defaults: `ODESolver` for
            ``"DifferentialEquations"``, `StochasticEventsSettings` and
            `StochasticStepsSettings` for the stochastic engines.

        Returns
        -------
        Model[StructureT]
            The model, of the class of ``structure``.

        Raises
        ------
        ValueError
            If validation fails, the structure does not fit the process (for
            example a fraction names no bin, or a rate reads ``neighbors_<bin>``
            and the structure has no ``neighbors``), the engine is unknown or
            does not run the kind of the structure, the settings are not
            settings of that engine, a series point or an impulse position is
            one the engine cannot run (a position between two steps for an
            engine that steps only at integers, or a ``"pulse"`` point between
            two steps), a per-compartment override names an unknown
            compartment, a stochastic engine gets an amount that is not whole,
            or the origin has a time zone or a step unit that is not of fixed
            calendar length.
        """
        model: Model[StructureT] = Model(
            name=self._name,
            description=self._description,
            version=self._version,
            parameters=self._parameters,
            engine=ModelEngine(type=engine, settings=settings),
            process=self.process(),
            structure=structure,
            step_unit=self._step_unit,
            origin=self._origin,
        )

        logger.info(f"Model '{self._name}' successfully built for the {engine} engine.")

        return model

Methods:

__init__

__init__(name: str, description: str | None = None, version: str | None = None, bin_unit: str | None = None, step_unit: str | None = None, origin: date | None = None) -> None

Initialize the ModelBuilder.

Parameters:

Name Type Description Default
name str

The unique name that identifies the model.

required
description str | None

A human-readable description of the model's purpose and function.

None
version str | None

The version number of the model.

None
bin_unit str | None

The default unit for all bins. Individual bins can override this with their own unit parameter. Units are optional but required for model.check_unit_consistency().

None
step_unit str | None

Unit of one step on the axis, of any single dimension (for example "day" or "meter"). The unit check requires every flow to be <bin unit>/<step_unit>, and Model.axis_units() converts values to steps of it. None means step, the default increment of any axis.

None
origin date | None

Calendar moment of position 0: a datetime.datetime with no time zone, or a datetime.date, read as its midnight. With it, Model.axis_units() converts between dates and positions, and results.plot.series() labels its ticks with dates. It needs a step_unit of time whose length is a whole number of days or a whole fraction of a day, such as "hour" or "day"; build raises ValueError otherwise, or for a moment with a time zone.

None
Source code in commol/api/model_builder.py
def __init__(
    self,
    name: str,
    description: str | None = None,
    version: str | None = None,
    bin_unit: str | None = None,
    step_unit: str | None = None,
    origin: date | None = None,
) -> None:
    """
    Initialize the ModelBuilder.

    Parameters
    ----------
    name : str
        The unique name that identifies the model.
    description : str | None, default=None
        A human-readable description of the model's purpose and function.
    version : str | None, default=None
        The version number of the model.
    bin_unit : str | None, default=None
        The default unit for all bins.
        Individual bins can override this with their own unit parameter.
        Units are optional but required for model.check_unit_consistency().
    step_unit : str | None, default=None
        Unit of one step on the axis, of any single dimension (for example
        ``"day"`` or ``"meter"``). The unit check requires every flow to be
        ``<bin unit>/<step_unit>``, and ``Model.axis_units()`` converts
        values to steps of it. None means ``step``, the default increment
        of any axis.
    origin : date | None, default=None
        Calendar moment of position 0: a `datetime.datetime` with no time
        zone, or a `datetime.date`, read as its midnight. With it,
        ``Model.axis_units()`` converts between dates and positions, and
        ``results.plot.series()`` labels its ticks with dates. It
        needs a ``step_unit`` of time whose length is a whole number of
        days or a whole fraction of a day, such as ``"hour"`` or
        ``"day"``; `build` raises ``ValueError`` otherwise, or for a
        moment with a time zone.
    """
    self._name: str = name
    self._description: str | None = description
    self._version: str | None = version
    self._bin_unit: str | None = bin_unit
    self._step_unit: str | None = step_unit
    self._origin: date | None = origin

    self._bins: list[Bin] = []
    self._accumulators: list[Accumulator] = []
    self._stratifications: list[Stratification] = []
    self._transitions: list[Transition] = []
    self._parameters: list[Parameter] = []
    self._series_counter: int = 0

    logger.info(
        (
            f"Initialized ModelBuilder: name='{self._name}', "
            f"version='{self._version or 'N/A'}'"
        )
    )

add_bin

add_bin(id: str, name: str, unit: str | None = None) -> Self

Add a bin to the model.

Parameters:

Name Type Description Default
id str

Unique identifier for the bin.

required
name str

Human-readable name for the bin.

required
unit str | None

Unit of measurement for this bin. If None, uses the model-level bin_unit.

None

Returns:

Type Description
ModelBuilder

Self for method chaining.

Source code in commol/api/model_builder.py
def add_bin(self, id: str, name: str, unit: str | None = None) -> Self:
    """
    Add a bin to the model.

    Parameters
    ----------
    id : str
        Unique identifier for the bin.
    name : str
        Human-readable name for the bin.
    unit : str | None, default=None
        Unit of measurement for this bin. If None, uses the model-level bin_unit.

    Returns
    -------
    ModelBuilder
        Self for method chaining.
    """
    # Use bin-specific unit, or fall back to model-level bin_unit
    final_unit = unit if unit is not None else self._bin_unit
    self._bins.append(Bin(id=id, name=name, unit=final_unit))
    logger.info(f"Added bin: id='{id}', name='{name}', unit='{final_unit}'")
    return self

add_accumulator

add_accumulator(id: str, name: str) -> Self

Add an accumulator: a cumulative event counter in the model outputs.

A transition adds its flow to the accumulators it names (add_transition(accumulators=...)). An accumulator is an output, not a part of the state, so total leaves it out.

Parameters:

Name Type Description Default
id str

Unique identifier for the accumulator. It names its output, which stratifications expand as they expand a bin (acc_g1, acc_g2).

required
name str

Human-readable name for the accumulator.

required

Returns:

Type Description
ModelBuilder

Self for method chaining.

Source code in commol/api/model_builder.py
def add_accumulator(self, id: str, name: str) -> Self:
    """
    Add an accumulator: a cumulative event counter in the model outputs.

    A transition adds its flow to the accumulators it names
    (``add_transition(accumulators=...)``). An accumulator is an output,
    not a part of the state, so ``total`` leaves it out.

    Parameters
    ----------
    id : str
        Unique identifier for the accumulator. It names its output, which
        stratifications expand as they expand a bin (``acc_g1``,
        ``acc_g2``).
    name : str
        Human-readable name for the accumulator.

    Returns
    -------
    ModelBuilder
        Self for method chaining.
    """
    self._accumulators.append(Accumulator(id=id, name=name))
    logger.info(f"Added accumulator: id='{id}', name='{name}'")
    return self

add_stratification

add_stratification(id: str, categories: list[str], description: str | None = None, conditions: list[ConditionDict] | None = None) -> Self

Add a stratification to the model.

Parameters:

Name Type Description Default
id str

Unique identifier for the stratification.

required
categories list[str]

list of category identifiers within this stratification.

required
description str | None

Human-readable description of the stratification.

None
conditions list[dict] | None

When set, this stratification only expands compartments whose already-applied categories satisfy ALL conditions. Each dict must contain "stratification" and "category" keys referencing a stratification declared before this one.

Example: only apply the sub stratification to group1::

conditions = [{"stratification": "group", "category": "group1"}]
None

Returns:

Type Description
ModelBuilder

Self for method chaining.

Raises:

Type Description
ValueError

If any condition references a stratification not yet declared.

Source code in commol/api/model_builder.py
def add_stratification(
    self,
    id: str,
    categories: list[str],
    description: str | None = None,
    conditions: list[StratificationConditionDict] | None = None,
) -> Self:
    """
    Add a stratification to the model.

    Parameters
    ----------
    id : str
        Unique identifier for the stratification.
    categories : list[str]
        list of category identifiers within this stratification.
    description : str | None, default=None
        Human-readable description of the stratification.
    conditions : list[dict] | None, default=None
        When set, this stratification only expands compartments whose
        already-applied categories satisfy ALL conditions. Each dict must
        contain "stratification" and "category" keys referencing a
        stratification declared before this one.

        Example: only apply the `sub` stratification to `group1`::

            conditions = [{"stratification": "group", "category": "group1"}]

    Returns
    -------
    ModelBuilder
        Self for method chaining.

    Raises
    ------
    ValueError
        If any condition references a stratification not yet declared.
    """
    if conditions:
        declared_ids = {s.id for s in self._stratifications}
        for cond in conditions:
            if cond["stratification"] not in declared_ids:
                raise ValueError(
                    f"Stratification '{id}': condition references "
                    f"'{cond['stratification']}' which has not been declared yet. "
                    "Conditions may only reference stratifications declared before "
                    "this one."
                )

    condition_objects = (
        [StratificationCondition(**c) for c in conditions] if conditions else None
    )
    self._stratifications.append(
        Stratification(
            id=id,
            categories=categories,
            description=description,
            conditions=condition_objects,
        )
    )
    logger.info(f"Added stratification: id='{id}', categories={categories}")
    return self

add_parameter

add_parameter(id: str, value: float | str | list[tuple[float, float]] | None, description: str | None = None, unit: str | None = None, mode: str | None = None) -> Self

Add a global parameter to the model.

Parameters:

Name Type Description Default
id str

Unique identifier for the parameter.

required
value float | str | list[tuple[float, float]] | None

Value of the parameter. Can be: - float: A numerical constant value - str: A mathematical formula that can reference other parameters, special variables (total, total_, step, t, pi, e), or contain mathematical expressions (e.g., "k1 * 2", "total_g1 / total") - list[tuple[float, float]]: Empirical series as (position, value) points; requires mode to be set. - None: Indicates that the parameter needs to be calibrated before use

required
description str | None

Human-readable description of the parameter.

None
unit str | None

Unit of the parameter (e.g., "1/day", "dimensionless", "item"). Used for unit consistency checking in equations.

None
mode str | None

Required when value is a list of (position, value) points. Selects how the series is read: "pulse" (the value on the step of a point, 0 on every other step; integer positions only), "step_function" (the value of the last point at or before t), or "linear" (linear interpolation in t).

None

Returns:

Type Description
ModelBuilder

Self for method chaining.

Raises:

Type Description
ValueError

If value is a list but mode is not provided, if mode is provided without a list value, or if a formula value fails the security check or is not in the language of formulas.

Source code in commol/api/model_builder.py
def add_parameter(
    self,
    id: str,
    value: float | str | list[tuple[float, float]] | None,
    description: str | None = None,
    unit: str | None = None,
    mode: str | None = None,
) -> Self:
    """
    Add a global parameter to the model.

    Parameters
    ----------
    id : str
        Unique identifier for the parameter.
    value : float | str | list[tuple[float, float]] | None
        Value of the parameter. Can be:
        - float: A numerical constant value
        - str: A mathematical formula that can reference other parameters,
               special variables (total, total_<category>, step, t, pi, e),
               or contain mathematical expressions (e.g., "k1 * 2",
               "total_g1 / total")
        - list[tuple[float, float]]: Empirical series as (position, value)
               points; requires ``mode`` to be set.
        - None: Indicates that the parameter needs to be calibrated before use

    description : str | None, default=None
        Human-readable description of the parameter.
    unit : str | None, default=None
        Unit of the parameter (e.g., "1/day", "dimensionless", "item").
        Used for unit consistency checking in equations.
    mode : str | None, default=None
        Required when ``value`` is a list of (position, value) points.
        Selects how the series is read: ``"pulse"`` (the value on the step
        of a point, 0 on every other step; integer positions only),
        ``"step_function"`` (the value of the last point at or before
        ``t``), or ``"linear"`` (linear interpolation in ``t``).

    Returns
    -------
    ModelBuilder
        Self for method chaining.

    Raises
    ------
    ValueError
        If ``value`` is a list but ``mode`` is not provided, if
        ``mode`` is provided without a list ``value``, or if a formula
        ``value`` fails the security check or is not in the language of
        formulas.
    """
    if isinstance(value, list):
        if mode is None:
            raise ValueError(
                f"Parameter '{id}': 'mode' is required when 'value' is a "
                "series list. Use mode='pulse', 'step_function', or 'linear'."
            )
        param_value: float | str | SeriesValue | None = SeriesValue(
            data=value, mode=mode
        )
    else:
        if mode is not None:
            raise ValueError(
                f"Parameter '{id}': 'mode' is only valid when 'value' is a "
                "series list."
            )
        param_value = value
    self._ensure_parameter_id_available(id)
    self._parameters.append(
        Parameter(id=id, value=param_value, description=description, unit=unit)
    )
    logger.info(f"Added parameter: id='{id}', value={value}, unit='{unit}'")
    return self

add_transition

add_transition(id: str, source: list[str], target: list[str], rate: str | float | AxisPattern | None = None, stratified_rates: list[StratifiedRateDict] | None = None, per_compartment: bool | None = None, accumulators: list[str] | None = None, impulse_at: list[float] | None = None, impulse_every: tuple[float, float] | None = None) -> Self

Add a transition between states to the model.

This method supports two distinct behaviors:

When you specify multiple sources without the $compartment placeholder, a single transition is created that affects all sources simultaneously. The rate is evaluated once, at each position the engine reads it, and that value applies to all source compartments at once. What the value means (an amount moved in one step or an instantaneous rate) is the engine's; see "What a rate means" in the Core Concepts guide.

When you use the $compartment placeholder in the rate formula with multiple sources, the system automatically expands this into multiple independent transitions - one for each source compartment. Each transition has its own rate calculation where $compartment is replaced with the actual compartment name.

Each transition's rate is evaluated independently, giving per-compartment dynamics. This suits an outflow such as k1 * $compartment, where the flow of each compartment is proportional to its own amount.

$compartment Usage Rules: - Only valid with several sources (and one or no target) or several targets (and one or no source) - Can be used with stratified_rates - the placeholder will be expanded in both the base rate and all stratified rate expressions - The placeholder $compartment will be replaced with each source compartment name

$compartment Restrictions: - Using $compartment with a single source will raise an error (use the compartment name directly instead) - Using $compartment with multiple targets will raise an error (ambiguous which target corresponds to which source)

Parameters:

Name Type Description Default
id str

Unique identifier for the transition. When using $compartment expansion, the system will append "__" to create unique IDs for each expanded transition (e.g., "out__A", "out__B").

required
source list[str]

List of source state/category identifiers. When using $compartment in the rate, each source will generate a separate transition.

required
target list[str]

List of target state/category identifiers. When using $compartment with several targets, each target generates a separate transition.

required
rate str | float | AxisPattern | None

Default mathematical formula, parameter reference, or constant value for the transition rate. Used when no stratified rate matches. Can be: - A parameter reference - A constant value - A mathematical formula - A formula with $compartment placeholder

Special variables available in formulas: - total: The sum of every compartment, accumulators excluded - total_…: The sum of the compartments with these categories, in the declaration order of the stratifications - t: The current position on the axis - step: The step that holds it, floor(t); in a DifferenceEquations model t and step are equal - pi, e: Mathematical constants - $compartment: Expands to each source compartment name (only with multiple sources)

None
stratified_rates list[dict] | None

List of stratification-specific rates. Each dict must contain: - "conditions": List of dicts with "stratification" and "category" keys - "rate": Rate expression string

None
per_compartment bool | None

When True, each id of a source or target bin in a rate reads the compartment of the flow (A_g1) instead of the total of the bin. Any other bin keeps its total: in a transition from A to B, k * A * (C + D) / total reads A_g1 and the totals of C and D. It applies to the fallback rate, to every stratified rate, and to every transition that $compartment expands to, where $compartment reads the compartment that flows. A transition between categories ignores it.

None
accumulators list[str] | None

Ids of accumulators that add up the flow of this transition.

None
impulse_at list[float] | None

Make the transition an impulse at these positions on the axis. At each one, rate is the fraction of the source (proportional) or the amount (absolute) moved at once, before the flows of that step. A DifferenceEquations or StochasticSteps model needs integer positions.

None
impulse_every tuple[float, float] | None

(period, offset): make the transition an impulse at offset, offset + period, offset + 2 * period, ...

None

Returns:

Type Description
ModelBuilder

Self for method chaining.

Raises:

Type Description
ValueError
  • If $compartment is used with only one source compartment
  • If $compartment is used with multiple targets
  • If rate is None when using $compartment
Source code in commol/api/model_builder.py
def add_transition(
    self,
    id: str,
    source: list[str],
    target: list[str],
    rate: "str | float | AxisPattern | None" = None,
    stratified_rates: list[StratifiedRateDict] | None = None,
    per_compartment: bool | None = None,
    accumulators: list[str] | None = None,
    impulse_at: list[float] | None = None,
    impulse_every: tuple[float, float] | None = None,
) -> Self:
    """
    Add a transition between states to the model.

    This method supports two distinct behaviors:

    When you specify multiple sources without the $compartment placeholder,
    a single transition is created that affects all sources simultaneously.
    The rate is evaluated once, at each position the engine reads it, and
    that value applies to all source compartments at once. What the value
    means (an amount moved in one step or an instantaneous rate) is the
    engine's; see "What a rate means" in the Core Concepts guide.

    When you use the $compartment placeholder in the rate formula with multiple
    sources, the system automatically expands this into multiple independent
    transitions - one for each source compartment. Each transition has its own
    rate calculation where $compartment is replaced with the actual compartment
    name.

    Each transition's rate is evaluated independently, giving per-compartment
    dynamics. This suits an outflow such as ``k1 * $compartment``, where the
    flow of each compartment is proportional to its own amount.

    **$compartment Usage Rules**:
    - Only valid with several sources (and one or no target) or several
      targets (and one or no source)
    - Can be used with stratified_rates - the placeholder will be expanded in
      both the base rate and all stratified rate expressions
    - The placeholder $compartment will be replaced with each source compartment
      name

    **$compartment Restrictions**:
    - Using $compartment with a single source will raise an error (use the
      compartment name directly instead)
    - Using $compartment with multiple targets will raise an error (ambiguous
      which target corresponds to which source)

    Parameters
    ----------
    id : str
        Unique identifier for the transition. When using $compartment expansion,
        the system will append "__<compartment_name>" to create unique IDs for
        each expanded transition (e.g., "out__A", "out__B").
    source : list[str]
        List of source state/category identifiers. When using $compartment in
        the rate, each source will generate a separate transition.
    target : list[str]
        List of target state/category identifiers. When using $compartment
        with several targets, each target generates a separate transition.
    rate : str | float | AxisPattern | None, default=None
        Default mathematical formula, parameter reference, or constant value for
        the transition rate. Used when no stratified rate matches.
        Can be:
        - A parameter reference
        - A constant value
        - A mathematical formula
        - A formula with $compartment placeholder

        Special variables available in formulas:
        - total: The sum of every compartment, accumulators excluded
        - total_<category>…: The sum of the compartments with these
          categories, in the declaration order of the stratifications
        - t: The current position on the axis
        - step: The step that holds it, ``floor(t)``; in a
          DifferenceEquations model ``t`` and ``step`` are equal
        - pi, e: Mathematical constants
        - $compartment: Expands to each source compartment name (only with
          multiple sources)

    stratified_rates : list[dict] | None, default=None
        List of stratification-specific rates. Each dict must contain:
        - "conditions": List of dicts with "stratification" and "category" keys
        - "rate": Rate expression string

    per_compartment : bool | None, default=None
        When True, each id of a source or target bin in a rate reads the
        compartment of the flow (``A_g1``) instead of the total of the bin.
        Any other bin keeps its total: in a transition from ``A`` to ``B``,
        ``k * A * (C + D) / total`` reads ``A_g1`` and the totals of ``C``
        and ``D``. It applies to the fallback rate, to every stratified
        rate, and to every transition that ``$compartment`` expands to,
        where ``$compartment`` reads the compartment that flows. A
        transition between categories ignores it.

    accumulators : list[str] | None, default=None
        Ids of accumulators that add up the flow of this transition.

    impulse_at : list[float] | None, default=None
        Make the transition an impulse at these positions on the axis. At
        each one, ``rate`` is the fraction of the source (proportional) or the
        amount (absolute) moved at once, before the flows of that step. A
        DifferenceEquations or StochasticSteps model needs integer
        positions.

    impulse_every : tuple[float, float] | None, default=None
        ``(period, offset)``: make the transition an impulse at ``offset``,
        ``offset + period``, ``offset + 2 * period``, ...

    Returns
    -------
    ModelBuilder
        Self for method chaining.

    Raises
    ------
    ValueError
        - If $compartment is used with only one source compartment
        - If $compartment is used with multiple targets
        - If rate is None when using $compartment
    """
    # If `rate` is a AxisPattern, extract its rate string and stratified
    # rates and route them into the existing pipeline. A AxisPattern fully
    # specifies how the rate changes along the axis, so passing `stratified_rates=`
    # alongside it is a conflict.
    if isinstance(rate, AxisPattern):
        if impulse_at is not None or impulse_every is not None:
            raise ValueError(
                f"Transition '{id}': an impulse moves its rate at once; pass "
                "a fraction or an amount as `rate=`, not a AxisPattern."
            )
        if stratified_rates is not None:
            raise ValueError(
                f"Transition '{id}': pass either a AxisPattern as `rate=` "
                "or `stratified_rates=`, not both."
            )
        src_bin = source[0] if source else ""
        tgt_bin = target[0] if target else ""
        if isinstance(rate, _ScheduleAxisPattern):
            resolved = rate.model_copy(
                update={
                    "patterns": [
                        _GroupEntry(
                            pattern=self._register_series_pattern(
                                entry.pattern,
                                transition_id=id,
                                source_bin=src_bin,
                                target_bin=tgt_bin,
                            ),
                            absolute=entry.absolute,
                        )
                        for entry in rate.patterns
                    ]
                }
            )
            rate = resolved
        else:
            rate = self._register_series_pattern(
                rate, transition_id=id, source_bin=src_bin, target_bin=tgt_bin
            )
        stratified_rates = rate._builder_stratified_rates()
        rate = rate._builder_rate()

    # Convert rate to string if numeric
    if isinstance(rate, int) or isinstance(rate, float):
        rate = str(rate)

    # Check for $compartment placeholder and handle expansion
    if rate and "$compartment" in rate:
        self._validate_compartment_placeholder(id, source, target)
        self._expand_compartment_transition(
            id,
            source,
            target,
            rate,
            stratified_rates,
            per_compartment,
            accumulators,
            impulse_at,
            impulse_every,
        )
        return self

    stratified_rates_objects = _stratified_rate_objects(stratified_rates)
    self._transitions.append(
        Transition(
            id=id,
            source=source,
            target=target,
            accumulators=accumulators or [],
            rate=rate,
            stratified_rates=stratified_rates_objects,
            per_compartment=per_compartment,
            impulse_at=impulse_at,
            impulse_every=impulse_every,
        )
    )
    logger.info(
        (
            f"Added transition: id='{id}', source={source}, target={target}, "
            f"rate='{rate}', stratified_rates={
                len(stratified_rates_objects) if stratified_rates_objects else 0
            }"
        )
    )
    return self

get_summary

get_summary() -> dict[str, str | int | list[str] | None]

Get a summary of the current model builder state.

Returns:

Type Description
dict[str, dict[str, str | int | list[str] | None]]

Dictionary containing summary information about the model being built.

Source code in commol/api/model_builder.py
def get_summary(self) -> dict[str, str | int | list[str] | None]:
    """
    Get a summary of the current model builder state.

    Returns
    -------
    dict[str, dict[str, str | int | list[str] | None]]
        Dictionary containing summary information about the model being built.
    """
    return {
        "name": self._name,
        "description": self._description,
        "version": self._version,
        "bins_count": len(self._bins),
        "bin_ids": [state.id for state in self._bins],
        "stratifications_count": len(self._stratifications),
        "stratification_ids": [strat.id for strat in self._stratifications],
        "transitions_count": len(self._transitions),
        "transition_ids": [trans.id for trans in self._transitions],
        "parameters_count": len(self._parameters),
        "parameter_ids": [param.id for param in self._parameters],
    }

clone

clone() -> Self

Create a deep copy of this ModelBuilder.

Returns:

Type Description
ModelBuilder

A new ModelBuilder instance with the same configuration: every bin, accumulator, stratification, transition and parameter. Changes to one builder do not affect the other.

Source code in commol/api/model_builder.py
def clone(self) -> Self:
    """
    Create a deep copy of this ModelBuilder.

    Returns
    -------
    ModelBuilder
        A new ModelBuilder instance with the same configuration: every
        bin, accumulator, stratification, transition and parameter.
        Changes to one builder do not affect the other.
    """
    return copy.deepcopy(self)

reset

reset() -> Self

Reset the builder to empty state.

The name, description, version, bin_unit, step_unit and origin are kept. Every bin, accumulator, stratification, transition and parameter is removed.

Returns:

Type Description
ModelBuilder

Self for method chaining.

Source code in commol/api/model_builder.py
def reset(self) -> Self:
    """
    Reset the builder to empty state.

    The name, description, version, ``bin_unit``, ``step_unit`` and
    ``origin`` are kept. Every bin,
    accumulator, stratification, transition and parameter is removed.

    Returns
    -------
    ModelBuilder
        Self for method chaining.
    """
    self._bins.clear()
    self._accumulators.clear()
    self._stratifications.clear()
    self._transitions.clear()
    self._parameters.clear()
    self._series_counter = 0
    return self

process

process() -> Process

The process the builder has written so far.

Returns:

Type Description
Process

The bins, accumulators, stratifications and transitions.

Raises:

Type Description
ValueError

If ids repeat, or a transition or a stratified rate names an id the process does not have.

Source code in commol/api/model_builder.py
def process(self) -> Process:
    """
    The process the builder has written so far.

    Returns
    -------
    Process
        The bins, accumulators, stratifications and transitions.

    Raises
    ------
    ValueError
        If ids repeat, or a transition or a stratified rate names an id
        the process does not have.
    """
    return Process(
        bins=self._bins,
        accumulators=self._accumulators,
        stratifications=self._stratifications,
        transitions=self._transitions,
    )

build

build(structure: StructureT, engine: EngineName, settings: EngineSettings | None = None) -> Model[StructureT]

Join the process with a structure and an engine into a model.

The process is written once; the structure lays it out and sets the kind of the model, so one builder builds every kind its process fits:

builder.build(Aggregate(bin_amounts={"A": 990, "B": 10, "C": 0}), engine="DifferentialEquations")

Parameters:

Name Type Description Default
structure ModelStructure

How the process is laid out, such as Aggregate (amounts per compartment). The model is a Model of its class.

required
engine EngineName

The engine that runs the model, which must run the kind of the structure: "DifferenceEquations" (discrete time), "DifferentialEquations" (continuous time), "StochasticEvents" or "StochasticSteps" (at random).

required
settings EngineSettings | None

Settings of that engine; None uses its defaults: ODESolver for "DifferentialEquations", StochasticEventsSettings and StochasticStepsSettings for the stochastic engines.

None

Returns:

Type Description
Model[StructureT]

The model, of the class of structure.

Raises:

Type Description
ValueError

If validation fails, the structure does not fit the process (for example a fraction names no bin, or a rate reads neighbors_<bin> and the structure has no neighbors), the engine is unknown or does not run the kind of the structure, the settings are not settings of that engine, a series point or an impulse position is one the engine cannot run (a position between two steps for an engine that steps only at integers, or a "pulse" point between two steps), a per-compartment override names an unknown compartment, a stochastic engine gets an amount that is not whole, or the origin has a time zone or a step unit that is not of fixed calendar length.

Source code in commol/api/model_builder.py
def build(
    self,
    structure: StructureT,
    engine: EngineName,
    settings: EngineSettings | None = None,
) -> Model[StructureT]:
    """
    Join the process with a structure and an engine into a model.

    The process is written once; the structure lays it out and sets the
    kind of the model, so one builder builds every kind its process fits:

    ``builder.build(Aggregate(bin_amounts={"A": 990, "B": 10, "C": 0}),
    engine="DifferentialEquations")``

    Parameters
    ----------
    structure : ModelStructure
        How the process is laid out, such as `Aggregate` (amounts per
        compartment). The model is a ``Model`` of its class.
    engine : EngineName
        The engine that runs the model, which must run the kind of the
        structure: ``"DifferenceEquations"`` (discrete time),
        ``"DifferentialEquations"`` (continuous time), ``"StochasticEvents"``
        or ``"StochasticSteps"`` (at random).
    settings : EngineSettings | None, default=None
        Settings of that engine; None uses its defaults: `ODESolver` for
        ``"DifferentialEquations"``, `StochasticEventsSettings` and
        `StochasticStepsSettings` for the stochastic engines.

    Returns
    -------
    Model[StructureT]
        The model, of the class of ``structure``.

    Raises
    ------
    ValueError
        If validation fails, the structure does not fit the process (for
        example a fraction names no bin, or a rate reads ``neighbors_<bin>``
        and the structure has no ``neighbors``), the engine is unknown or
        does not run the kind of the structure, the settings are not
        settings of that engine, a series point or an impulse position is
        one the engine cannot run (a position between two steps for an
        engine that steps only at integers, or a ``"pulse"`` point between
        two steps), a per-compartment override names an unknown
        compartment, a stochastic engine gets an amount that is not whole,
        or the origin has a time zone or a step unit that is not of fixed
        calendar length.
    """
    model: Model[StructureT] = Model(
        name=self._name,
        description=self._description,
        version=self._version,
        parameters=self._parameters,
        engine=ModelEngine(type=engine, settings=settings),
        process=self.process(),
        structure=structure,
        step_unit=self._step_unit,
        origin=self._origin,
    )

    logger.info(f"Model '{self._name}' successfully built for the {engine} engine.")

    return model