Skip to content

Core API Reference

The core module implements the Ecopath mass-balance solver, Ecosim dynamic simulation, and supporting subsystems (stanzas, forcing, optimization).

Functional Development Workflows

This reference now covers functional developments added around the baseline Ecopath/Ecosim pipeline.

Workflow Primary API Entry Points Typical Outcome
Balanced baseline modeling create_rpath_params(), rpath(), rsim_scenario(), rsim_run() Mass-balanced static model and dynamic biomass trajectories
Recruitment-aware dynamics RickerRecruitment, BevertonHoltRecruitment, MyersRecruitment, RsimScenario.set_recruitment_model(), RsimScenario.apply_recruitment_to_forcing() Group-specific recruitment multipliers injected into monthly forcing
Metabolism scaling TemperatureDependence, MetabolicModel, compute_temperature_adjusted_metabolism() Temperature/body-size adjusted metabolic rates
Fishing strategy prototyping DynamicLogisticSelectivity, TimeVaryingSelectivity, SpatialSelectivity, FishingOptimization Selectivity and effort-allocation experiments before full scenario runs
Uncertainty and risk SensitivityAnalyzer, UncertaintyPropagation, RiskAssessment Local/global sensitivity, ensemble uncertainty, collapse/extinction risk metrics

Recruitment-enabled scenario pattern

from pypath import rsim_scenario
from pypath.core.recruitment import RickerRecruitment

scenario = rsim_scenario(model, params, years=range(1, 51))
scenario.set_recruitment_model("Cod", RickerRecruitment(alpha=0.8, beta=0.02, rmax=1.5))

ssb = {"Cod": 1200.0}
scenario.apply_recruitment_to_forcing(month_index=0, time=0.0, ssb_by_group=ssb)

Ecopath (Mass-Balance)

pypath.core.ecopath

Ecopath mass-balance model implementation.

This module contains the core Rpath class and the rpath() function that performs mass-balance calculations for food web models.

Rpath dataclass

Balanced Ecopath model.

This class represents a mass-balanced food web model created by the rpath() function.

Attributes:

Name Type Description
NUM_GROUPS int

Total number of groups (living + dead + gears)

NUM_LIVING int

Number of living groups (consumers + producers)

NUM_DEAD int

Number of detritus groups

NUM_GEARS int

Number of fishing fleets

Group ndarray

Names of all groups

type ndarray

Type codes (0=consumer, 1=producer, 2=detritus, 3=fleet)

TL ndarray

Trophic levels

Biomass ndarray

Biomass values (t/km²)

PB ndarray

Production/Biomass ratios (1/year)

QB ndarray

Consumption/Biomass ratios (1/year)

EE ndarray

Ecotrophic efficiencies

GE ndarray

Gross efficiencies (P/Q)

M0 ndarray

Other mortality rates (M0 = PB * (1 - EE))

BA ndarray

Biomass accumulation rates

Unassim ndarray

Unassimilated consumption fractions

DC ndarray

Diet composition matrix

DetFate ndarray

Detritus fate matrix

Landings ndarray

Landings by group and fleet

Discards ndarray

Discards by group and fleet

eco_name str

Ecosystem name

eco_area float

Ecosystem area (km²)

Source code in pypath/core/ecopath.py
 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
@dataclass
class Rpath:
    """Balanced Ecopath model.

    This class represents a mass-balanced food web model created by the
    rpath() function.

    Attributes
    ----------
    NUM_GROUPS : int
        Total number of groups (living + dead + gears)
    NUM_LIVING : int
        Number of living groups (consumers + producers)
    NUM_DEAD : int
        Number of detritus groups
    NUM_GEARS : int
        Number of fishing fleets
    Group : np.ndarray
        Names of all groups
    type : np.ndarray
        Type codes (0=consumer, 1=producer, 2=detritus, 3=fleet)
    TL : np.ndarray
        Trophic levels
    Biomass : np.ndarray
        Biomass values (t/km²)
    PB : np.ndarray
        Production/Biomass ratios (1/year)
    QB : np.ndarray
        Consumption/Biomass ratios (1/year)
    EE : np.ndarray
        Ecotrophic efficiencies
    GE : np.ndarray
        Gross efficiencies (P/Q)
    M0 : np.ndarray
        Other mortality rates (M0 = PB * (1 - EE))
    BA : np.ndarray
        Biomass accumulation rates
    Unassim : np.ndarray
        Unassimilated consumption fractions
    DC : np.ndarray
        Diet composition matrix
    DetFate : np.ndarray
        Detritus fate matrix
    Landings : np.ndarray
        Landings by group and fleet
    Discards : np.ndarray
        Discards by group and fleet
    eco_name : str
        Ecosystem name
    eco_area : float
        Ecosystem area (km²)
    """

    NUM_GROUPS: int
    NUM_LIVING: int
    NUM_DEAD: int
    NUM_GEARS: int
    Group: np.ndarray
    type: np.ndarray
    TL: np.ndarray
    Biomass: np.ndarray
    PB: np.ndarray
    QB: np.ndarray
    EE: np.ndarray
    GE: np.ndarray
    M0: np.ndarray
    BA: np.ndarray
    Unassim: np.ndarray
    DC: np.ndarray
    DetFate: np.ndarray
    Landings: np.ndarray
    Discards: np.ndarray
    eco_name: str = ""
    eco_area: float = 1.0
    # Detritus import per group (t/km2/yr, 0 except on detritus groups);
    # Ecosim adds it as a constant inflow (EwE DetInFlow, audit A2)
    DetInput: np.ndarray = field(default_factory=lambda: np.zeros(0))
    # EwE migration per group (0 on fleets): Immigration and Emigration flows
    # (t/km2/yr) and EmigRate (emigration per unit of B, used where Emigration
    # is 0); audit A1-s2. Ecopath balances living groups' only; detritus
    # migration is reported for Ecosim
    Immigration: np.ndarray = field(default_factory=lambda: np.zeros(0))
    Emigration: np.ndarray = field(default_factory=lambda: np.zeros(0))
    EmigRate: np.ndarray = field(default_factory=lambda: np.zeros(0))
    # Whose conventions the model follows, from RpathParams.compat (D1)
    compat: str = "rpath"

    def __repr__(self) -> str:
        max_ee = np.nanmax(self.EE[: self.NUM_LIVING + self.NUM_DEAD])
        if max_ee > 1:
            status = "Unbalanced!"
            unbalanced = self.Group[np.where(self.EE > 1)[0]]
            status_detail = f"\nGroups with EE > 1: {list(unbalanced)}"
        else:
            status = "Balanced"
            status_detail = ""

        return (
            f"Rpath model: {self.eco_name}\n"
            f"Model Area: {self.eco_area}\n"
            f"     Status: {status}{status_detail}\n"
            f"     Groups: {self.NUM_GROUPS} "
            f"(living={self.NUM_LIVING}, dead={self.NUM_DEAD}, gears={self.NUM_GEARS})"
        )

    def summary(self) -> pd.DataFrame:
        """Get summary table of model results.

        Returns
        -------
        pd.DataFrame
            Summary with Group, Type, TL, Biomass, PB, QB, EE, GE, and Removals.
        """
        removals = np.nansum(self.Landings, axis=1) + np.nansum(self.Discards, axis=1)

        return pd.DataFrame(
            {
                "Group": self.Group,
                "Type": self.type,
                "TL": self.TL,
                "Biomass": self.Biomass,
                "PB": self.PB,
                "QB": self.QB,
                "EE": self.EE,
                "GE": self.GE,
                "Removals": removals,
            }
        )
summary
summary() -> pd.DataFrame

Get summary table of model results.

Returns:

Type Description
DataFrame

Summary with Group, Type, TL, Biomass, PB, QB, EE, GE, and Removals.

Source code in pypath/core/ecopath.py
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
def summary(self) -> pd.DataFrame:
    """Get summary table of model results.

    Returns
    -------
    pd.DataFrame
        Summary with Group, Type, TL, Biomass, PB, QB, EE, GE, and Removals.
    """
    removals = np.nansum(self.Landings, axis=1) + np.nansum(self.Discards, axis=1)

    return pd.DataFrame(
        {
            "Group": self.Group,
            "Type": self.type,
            "TL": self.TL,
            "Biomass": self.Biomass,
            "PB": self.PB,
            "QB": self.QB,
            "EE": self.EE,
            "GE": self.GE,
            "Removals": removals,
        }
    )

EweDetritusFate dataclass

EwE6's detritus fate on a balanced model (see :func:ewe_detritus_fate).

Each array has one value per group, in the model's group order, and is 0 except on detritus groups.

Attributes:

Name Type Description
input_to_det ndarray

Inflow (EwE InputToDet): import, living groups' deaths and egestion, discards and the surplus other pools passed on.

det_eaten ndarray

Consumption of the pool (EwE DetEaten).

passed_on ndarray

Surplus passed on to the other pools (EwE DetPassedOn, the Ecopath FlowToDet of a detritus group).

ba ndarray

Biomass accumulation: the model's BA plus the surplus share the pool sends to itself (EwE BA after CalcBAofDetritus).

ee ndarray

Ecotrophic efficiency, det_eaten / input_to_det (EwE EE).

Source code in pypath/core/ecopath.py
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
@dataclass
class EweDetritusFate:
    """EwE6's detritus fate on a balanced model (see :func:`ewe_detritus_fate`).

    Each array has one value per group, in the model's group order, and is 0
    except on detritus groups.

    Attributes
    ----------
    input_to_det : np.ndarray
        Inflow (EwE InputToDet): import, living groups' deaths and egestion,
        discards and the surplus other pools passed on.
    det_eaten : np.ndarray
        Consumption of the pool (EwE DetEaten).
    passed_on : np.ndarray
        Surplus passed on to the other pools (EwE DetPassedOn, the Ecopath
        FlowToDet of a detritus group).
    ba : np.ndarray
        Biomass accumulation: the model's BA plus the surplus share the pool
        sends to itself (EwE BA after CalcBAofDetritus).
    ee : np.ndarray
        Ecotrophic efficiency, det_eaten / input_to_det (EwE EE).
    """

    input_to_det: np.ndarray
    det_eaten: np.ndarray
    passed_on: np.ndarray
    ba: np.ndarray
    ee: np.ndarray

rpath

rpath(rpath_params: RpathParams, eco_name: str = '', eco_area: float = 1.0, debug: bool = False) -> Union[Rpath, Tuple[Rpath, Dict[str, object]]]

Balance an Ecopath model.

Performs initial mass balance using an RpathParams object. Preserves the original group order from the input parameters.

The mass balance equation solved is:

Production = Predation Mortality + Fishing Mortality + Other Mortality + Biomass Accumulation + Net Migration

Or equivalently: B_i * PB_i * EE_i = Σ(B_j * QB_j * DC_ji) + Y_i + BA_i

Parameters:

Name Type Description Default
rpath_params RpathParams

R object containing the parameters needed to create an Rpath model.

required
eco_name str

Name of the ecosystem (stored as attribute).

''
eco_area float

Area of the ecosystem (stored as attribute).

1.0
debug bool

If False (default), return only the balanced Rpath object. If True, return a tuple (rpath_obj, diagnostics) where diagnostics is a dict containing intermediate matrices (A, b_vec, x, diet_values, nodetrdiet, living_idx, no_b, no_ee).

False

Returns:

Type Description
Rpath or tuple[Rpath, dict]

Balanced model that can be supplied to rsim_scenario(). When debug=True, returns (Rpath, diagnostics).

Raises:

Type Description
ValueError

If the model cannot be balanced due to missing parameters.

Notes

When debug=True the function returns a tuple (rpath_obj, diagnostics) where diagnostics contains intermediate matrices useful for debugging (A, b_vec, x, diet_values, nodetrdiet, living_idx, no_b, no_ee).

Examples:

>>> params = create_rpath_params(...)
>>> # Fill in parameter values
>>> model = rpath(params, eco_name='Georges Bank')
>>> print(model)
Source code in pypath/core/ecopath.py
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
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
def rpath(
    rpath_params: RpathParams,
    eco_name: str = "",
    eco_area: float = 1.0,
    debug: bool = False,
) -> Union[Rpath, Tuple[Rpath, Dict[str, object]]]:
    """Balance an Ecopath model.

    Performs initial mass balance using an RpathParams object.
    Preserves the original group order from the input parameters.

    The mass balance equation solved is:

    Production = Predation Mortality + Fishing Mortality +
                 Other Mortality + Biomass Accumulation + Net Migration

    Or equivalently:
    B_i * PB_i * EE_i = Σ(B_j * QB_j * DC_ji) + Y_i + BA_i

    Parameters
    ----------
    rpath_params : RpathParams
        R object containing the parameters needed to create an Rpath model.
    eco_name : str, optional
        Name of the ecosystem (stored as attribute).
    eco_area : float, optional
        Area of the ecosystem (stored as attribute).
    debug : bool, optional
        If False (default), return only the balanced Rpath object.
        If True, return a tuple ``(rpath_obj, diagnostics)`` where
        *diagnostics* is a dict containing intermediate matrices
        (A, b_vec, x, diet_values, nodetrdiet, living_idx, no_b, no_ee).

    Returns
    -------
    Rpath or tuple[Rpath, dict]
        Balanced model that can be supplied to rsim_scenario().
        When *debug=True*, returns ``(Rpath, diagnostics)``.

    Raises
    ------
    ValueError
        If the model cannot be balanced due to missing parameters.

    Notes
    -----
    When ``debug=True`` the function returns a tuple
    ``(rpath_obj, diagnostics)`` where ``diagnostics`` contains
    intermediate matrices useful for debugging (A, b_vec, x,
    diet_values, nodetrdiet, living_idx, no_b, no_ee).

    Examples
    --------
    >>> params = create_rpath_params(...)
    >>> # Fill in parameter values
    >>> model = rpath(params, eco_name='Georges Bank')
    >>> print(model)
    """
    compat = getattr(rpath_params, "compat", "rpath")
    if compat not in ("rpath", "ewe"):
        raise ValueError(f"compat must be 'rpath' or 'ewe', got {compat!r}")
    # Make a deep copy to avoid modifying original
    model_df = rpath_params.model.copy()
    diet_df = rpath_params.diet.copy()

    # Get dimensions - PRESERVE ORIGINAL ORDER
    ngroups = len(model_df)

    # Create index arrays for each group type (preserving original order)
    types_arr = model_df["Type"].values.astype(float)
    living_idx = np.where(types_arr < 2)[0]  # Indices of living groups
    dead_idx = np.where(types_arr == 2)[0]  # Indices of detritus groups
    fleet_idx = np.where(types_arr == 3)[0]  # Indices of fleet groups

    nliving = len(living_idx)
    ndead = len(dead_idx)
    ngear = len(fleet_idx)

    # Extract arrays from model DataFrame (original order)
    groups = model_df["Group"].values
    types = types_arr
    biomass = model_df["Biomass"].values.astype(float)
    pb = model_df["PB"].values.astype(float)
    qb = model_df["QB"].values.astype(float)
    ee = model_df["EE"].values.astype(float)
    prodcons = model_df["ProdCons"].values.astype(float)
    bioacc = model_df["BioAcc"].values.astype(float)
    unassim = model_df["Unassim"].values.astype(float)

    # Replace NaN with 0 for BioAcc and Unassim
    bioacc = np.where(np.isnan(bioacc), 0.0, bioacc)

    # EwE migration of living groups (cEcoPathModel.vb:466-489): Immigration
    # and Emigration are flows, EmigRate is emigration per unit of biomass,
    # used where Emigration is 0. A detritus group's migration is left out of
    # the balance, as in EwE (InputToDet = DtImp + flows, vb 628; its export
    # skips migration, vb 912-916), and only reported for Ecosim.
    def _group_values(col, groups_mask):
        if col not in model_df.columns:
            return np.zeros(ngroups)
        vals = pd.to_numeric(model_df[col], errors="coerce").to_numpy(dtype=float)
        return np.where(groups_mask, np.nan_to_num(vals, nan=0.0), 0.0)

    living_mask = types < 2
    immigration = _group_values("Immigration", living_mask)
    emigration = _group_values("Emigration", living_mask)
    emig_rate = np.where(emigration == 0, _group_values("EmigRate", living_mask), 0.0)
    # reported: every group's migration, detritus included
    migrating = types <= 2
    immigration_out = _group_values("Immigration", migrating)
    emigration_out = _group_values("Emigration", migrating)
    emig_rate_out = np.where(
        emigration_out == 0, _group_values("EmigRate", migrating), 0.0
    )
    # BiomAccRate where BiomAcc is 0 counts as BiomAccRate x B, like EmigRate
    # (cEcoPathModel.vb:466, 2047, 2097); its BA is reported after the solve
    ba_rate = np.where(bioacc == 0, _group_values("BioAccRate", living_mask), 0.0)
    balance_rate = emig_rate + ba_rate
    unassim = np.where(np.isnan(unassim), 0.0, unassim)

    # Get diet matrix - columns are predators (living groups only)
    living_group_names = groups[living_idx].tolist()
    diet_cols = [g for g in living_group_names if g in diet_df.columns]

    # Build diet matrix with rows matching original group order
    diet_prey_names = diet_df["Group"].tolist()
    all_group_names = groups.tolist()

    # Create mapping from diet prey names to row indices in diet_df
    prey_name_to_diet_row = {name: i for i, name in enumerate(diet_prey_names)}

    # Build diet matrix (rows = ALL groups + Import, cols = predators in living_idx order)
    # Need ngroups rows (one per group) + 1 row for Import
    n_pred = len(diet_cols)
    diet_values = np.zeros(
        (ngroups + 1, n_pred)
    )  # ngroups rows for groups + 1 for Import

    # Map each group to its diet row; Import goes at index ngroups, after all
    # groups, if present. The diet table has no fleet rows, so its row count
    # says nothing about whether Import is there (#53).
    # The rows are taken from the table in one lookup: a lookup per group was
    # three quarters of a balance's time.
    targets = list(enumerate(all_group_names)) + [(ngroups, "Import")]
    placed = [
        (new_row_idx, prey_name_to_diet_row[name])
        for new_row_idx, name in targets
        if name in prey_name_to_diet_row
    ]
    if placed:
        new_rows = [new_row_idx for new_row_idx, _ in placed]
        old_rows = [old_row_idx for _, old_row_idx in placed]
        diet_values[new_rows, :] = diet_df.loc[old_rows, diet_cols].to_numpy(
            dtype=float
        )

    diet_values = np.nan_to_num(diet_values, nan=0.0)

    # Adjust diet for mixotrophs (Type between 0 and 1)
    for col_idx, grp_idx in enumerate(living_idx):
        if 0 < types[grp_idx] < 1:
            mix_q = 1 - types[grp_idx]
            diet_values[:, col_idx] *= mix_q

    # Extract diet for living groups only (prey rows are living groups)
    # nodetrdiet[i, j] = fraction of predator j's total consumption from prey i.
    # Imported diet is simply not local: Ecopath charges local prey the raw
    # fractions, as Rpath and EwE do (Rpath's import-normalised diet serves
    # only the trophic levels; see below). Normalising here overstated
    # predation by 1/(1 - import) (#53).
    nodetrdiet = diet_values[np.ix_(living_idx, range(nliving))]

    # Fill in GE (P/Q), QB, or PB from other inputs
    # Compute GE = PB/QB when QB is present and non-zero, otherwise use prodcons
    ge = np.where((~np.isnan(qb)) & (qb != 0) & (~np.isnan(pb)), pb / qb, prodcons)
    # Replace NaN GE with 0 (safe default) and avoid dividing by zero below
    ge = np.nan_to_num(ge, nan=0.0)
    # Only fill QB where it's missing and we have a non-zero GE
    # Use np.divide with where to avoid divide-by-zero warnings when GE is zero
    safe_pb_over_ge = np.empty_like(pb)
    safe_pb_over_ge[:] = np.nan
    np.divide(pb, ge, out=safe_pb_over_ge, where=(ge != 0))
    qb = np.where(np.isnan(qb) & (ge != 0), safe_pb_over_ge, qb)
    # Fill PB where missing from prodcons * QB
    pb = np.where(np.isnan(pb), prodcons * qb, pb)

    # As a last resort, if both PB and QB are missing for a *living* group, set reasonable defaults
    both_missing = np.isnan(pb) & np.isnan(qb) & (types < 2)
    if np.any(both_missing):
        # Use a small default turnover/consumption rate to allow balancing for living groups
        pb = np.where(both_missing, 1.0, pb)
        qb = np.where(both_missing, 1.0, qb)

    # Remember which biomass, PB and EE values were originally missing (before filling defaults)
    original_no_b = np.isnan(biomass)
    original_pb_missing = np.isnan(model_df["PB"].values.astype(float))
    original_no_ee = np.isnan(model_df["EE"].values.astype(float))
    # Groups where B and EE are known but PB is missing → solve for PB
    original_no_pb = original_pb_missing & ~original_no_b & ~original_no_ee

    # Keep biomass as NaN for living groups when originally missing so the solver treats them
    # as unknowns and solves for biomass when EE is provided (this matches R's behavior).
    # Previously we set a default value (1.0) here which prevented solving for biomass for
    # groups with EE specified but missing biomass (e.g., Megabenthos). Do not fill here.
    # biomass = np.where(np.isnan(biomass) & (types < 2), 1.0, biomass)

    # For fleet groups (type == 3), ensure biomass/PB/QB/EE are zero to match R conventions
    fleet_mask = types == 3
    if np.any(fleet_mask):
        biomass[fleet_mask] = np.where(
            np.isnan(biomass[fleet_mask]), 0.0, biomass[fleet_mask]
        )
        pb[fleet_mask] = np.where(np.isnan(pb[fleet_mask]), 0.0, pb[fleet_mask])
        qb[fleet_mask] = np.where(np.isnan(qb[fleet_mask]), 0.0, qb[fleet_mask])
        ee[fleet_mask] = np.where(np.isnan(ee[fleet_mask]), 0.0, ee[fleet_mask])

    # Get landings and discards matrices
    det_groups = groups[dead_idx].tolist()
    fleet_groups = groups[fleet_idx].tolist()

    # Find landings columns (fleet names)
    landing_cols = fleet_groups
    discard_cols = [f"{f}.disc" for f in fleet_groups]

    landmat = np.zeros((ngroups, ngear))
    discardmat = np.zeros((ngroups, ngear))

    for g_idx, col in enumerate(landing_cols):
        if col in model_df.columns:
            landmat[:, g_idx] = model_df[col].values.astype(float)
    for g_idx, col in enumerate(discard_cols):
        if col in model_df.columns:
            discardmat[:, g_idx] = model_df[col].values.astype(float)

    landmat = np.nan_to_num(landmat, nan=0.0)
    discardmat = np.nan_to_num(discardmat, nan=0.0)

    totcatchmat = landmat + discardmat
    totcatch = np.sum(totcatchmat, axis=1)
    _landings = np.sum(landmat, axis=1)
    _discards = np.sum(discardmat, axis=1)

    # Flag missing parameters (use the ORIGINAL missing-biomass mask)
    no_b = original_no_b
    no_ee = np.isnan(ee)
    logger.debug("original_no_b: %s", original_no_b)
    logger.debug("initial no_ee: %s", no_ee)

    # Iterative solve to handle EE>1 cases by capping EE at 1 and re-solving
    # Start with masks from current state
    it_max = 5
    it = 0
    iterations = []
    while True:
        it += 1
        # Extract living group values for this iteration
        living_biomass = biomass[living_idx]
        living_qb = qb[living_idx]
        living_pb = pb[living_idx]
        living_ee = ee[living_idx]
        living_bioacc = bioacc[living_idx]
        living_catch = totcatch[living_idx]
        living_migration = emigration[living_idx] - immigration[living_idx]
        living_rate = balance_rate[living_idx]
        # Determine which variables are unknown in this iteration
        living_no_b = np.isnan(living_biomass)
        living_no_ee = np.isnan(living_ee)

        # Build unknown-biomass mask for predators whose B is being solved
        pred_unknown_mask = np.array(
            [
                original_no_b[pred_global] or np.isnan(biomass[pred_global])
                for pred_global in living_idx
            ],
            dtype=bool,
        )

        A, b_vec = _build_balance_system(
            nliving,
            living_idx,
            living_biomass,
            living_pb,
            living_ee,
            living_qb,
            living_catch,
            living_bioacc,
            nodetrdiet,
            original_no_pb,
            pred_unknown_mask,
            living_migration=living_migration,
            living_emig_rate=living_rate,
        )

        # Validate
        if not np.all(np.isfinite(A)) or not np.all(np.isfinite(b_vec)):
            logger.debug("A finite mask: %s", np.isfinite(A))
            logger.debug("A: %s", A)
            logger.debug("b_vec finite mask: %s", np.isfinite(b_vec))
            logger.debug("b_vec: %s", b_vec)
            raise ValueError(
                "Model is missing or invalid parameters - can't be balanced. Use check_rpath_params() to diagnose."
            )

        # Solve linear system
        n = A.shape[0]
        try:
            if n <= 50:
                x = _gauss_solve(A, b_vec)
            else:
                x = np.linalg.solve(A, b_vec)
        except (ValueError, np.linalg.LinAlgError):
            logger.warning("Primary solver failed, falling back to least-squares")
            try:
                x = np.linalg.lstsq(A, b_vec, rcond=1e-6)[0]
            except (ValueError, np.linalg.LinAlgError) as e:
                raise ValueError(
                    "Unable to solve linear system during balancing"
                ) from e

        # Assign solved values back to living groups for this iteration
        for i, idx in enumerate(living_idx):
            logger.debug(
                "idx=%s iter=%s living_no_b=%s living_no_ee=%s x=%s biomass_before=%s",
                idx,
                it,
                living_no_b[i],
                living_no_ee[i],
                x[i],
                biomass[idx],
            )
            if original_no_pb[idx]:
                pb[idx] = x[i]
                logger.debug("Assigned pb[%s] = %s", idx, x[i])
                # Recalculate QB from estimated PB if QB was originally missing
                orig_qb = model_df["QB"].values.astype(float)[idx]
                if np.isnan(orig_qb) and ge[idx] > 0:
                    qb[idx] = pb[idx] / ge[idx]
                    logger.debug("Recalculated qb[%s] = %s from pb/ge", idx, qb[idx])
            elif living_no_ee[i]:
                ee[idx] = x[i]
                logger.debug("Assigned ee[%s] = %s", idx, x[i])
            if living_no_b[i]:
                biomass[idx] = x[i]
                logger.debug(
                    "Assigned biomass[%s] = %s biomass_after=%s",
                    idx,
                    x[i],
                    biomass[idx],
                )

        # Record iteration snapshot for diagnostics
        iterations.append(
            {
                "iter": it,
                "A": A.copy(),
                "b_vec": b_vec.copy(),
                "x": x.copy(),
                "ee": ee.copy(),
                "biomass": biomass.copy(),
            }
        )
        # Check for EE values > 1 for groups that were originally missing EE
        flipped = False
        # Find groups with EE > 1 eligible for flipping: those whose EE and biomass were both originally missing
        over = [
            (i, idx, ee[idx])
            for i, idx in enumerate(living_idx)
            if original_no_ee[idx]
            and original_no_b[idx]
            and not np.isnan(ee[idx])
            and ee[idx] > 1.0
        ]
        if over:
            # Flip only the largest eligible violation to avoid cascade effects
            over.sort(key=lambda t: t[2], reverse=True)
            i, idx, val = over[0]
            logger.debug(
                "ee[%s] = %s > 1.0 (largest eligible), capping to 1 and solving for biomass next iteration",
                idx,
                val,
            )
            ee[idx] = 1.0
            biomass[idx] = np.nan
            flipped = True

        # If no flips or reached iteration limit, break
        if not flipped or it >= it_max:
            break

    # After iterations, compute final A/b_vec once more for diagnostics
    living_biomass = biomass[living_idx]
    living_qb = qb[living_idx]
    living_pb = pb[living_idx]
    living_ee = ee[living_idx]
    pred_unknown_mask = np.array(
        [
            original_no_b[pred_global] or np.isnan(biomass[pred_global])
            for pred_global in living_idx
        ],
        dtype=bool,
    )
    A, b_vec = _build_balance_system(
        nliving,
        living_idx,
        living_biomass,
        living_pb,
        living_ee,
        living_qb,
        living_catch,
        living_bioacc,
        nodetrdiet,
        original_no_pb,
        pred_unknown_mask,
        living_migration=emigration[living_idx] - immigration[living_idx],
        living_emig_rate=balance_rate[living_idx],
    )

    # Save final solve results in context for debug output
    # (x and b_vec/A are available from the last iteration)
    try:
        if n <= 50:
            x = _gauss_solve(A, b_vec)
        else:
            x = np.linalg.solve(A, b_vec)
    except (ValueError, np.linalg.LinAlgError):
        logger.warning("Final solver failed, falling back to least-squares")
        try:
            x = np.linalg.lstsq(A, b_vec, rcond=1e-6)[0]
        except (ValueError, np.linalg.LinAlgError) as e:
            raise ValueError("Unable to solve linear system during balancing") from e

    # A rate group's biomass accumulation, BiomAccRate x the solved B
    bioacc = np.where(ba_rate != 0, ba_rate * np.nan_to_num(biomass), bioacc)

    # Calculate M0 (other mortality) for living groups (detritus handled after
    # detritus PB/biomass is computed below)
    m0 = np.zeros(ngroups)
    for i, idx in enumerate(living_idx):
        ee_val = ee[idx] if np.isfinite(ee[idx]) else 1.0
        m0[idx] = pb[idx] * (1 - ee_val)

    # Flows to detritus from living groups. M0 is negative where EE > 1; Rpath
    # (loss = M0 B + B QB Unassim) and EwE's Ecopath (FlowToDet) both count
    # it as it is (deviation M0)
    qb_loss = np.where(np.isnan(qb), 0.0, qb)
    loss = np.zeros(ngroups)
    for idx in living_idx:
        loss[idx] = (m0[idx] * biomass[idx]) + (
            biomass[idx] * qb_loss[idx] * unassim[idx]
        )
    # Add discards from fleets
    # For each fleet, sum discards across all living groups
    for f_idx, fleet_global_idx in enumerate(fleet_idx):
        loss[fleet_global_idx] = np.sum(discardmat[living_idx, f_idx])

    # Get detritus fate matrix
    detfate = np.zeros((ngroups, ndead))
    for d_idx, det_name in enumerate(det_groups):
        if det_name in model_df.columns:
            detfate[:, d_idx] = model_df[det_name].values.astype(float)
    detfate = np.nan_to_num(detfate, nan=0.0)

    # Detrital inputs
    det_input = np.zeros(ndead)
    for d_idx, det_idx in enumerate(dead_idx):
        det_input[d_idx] = (
            model_df["DetInput"].values[det_idx]
            if "DetInput" in model_df.columns
            else 0.0
        )
    det_input = np.nan_to_num(det_input, nan=0.0)
    det_input_full = np.zeros(ngroups)
    det_input_full[dead_idx] = det_input

    # Stage 1: Inputs from living + gear sources only (not other detritus)
    living_fleet_idx = np.concatenate([living_idx, fleet_idx])
    living_fleet_loss = loss[living_fleet_idx]
    living_fleet_detfate = detfate[living_fleet_idx, :]
    detinputs1 = (
        np.sum(living_fleet_loss[:, np.newaxis] * living_fleet_detfate, axis=0)
        + det_input
    )

    # Detritus consumption by living groups (vectorized)
    # diet_values rows are in original order, columns are in living_idx order
    det_diet = diet_values[dead_idx, :nliving]  # (ndead, nliving)
    bio_qb_living = np.nan_to_num(biomass[living_idx] * qb[living_idx])
    detcons = det_diet @ bio_qb_living  # (ndead,)

    # Stage 2: Route unconsumed detritus through detritus-to-detritus fate matrix
    det_unused = np.maximum(0.0, detinputs1 - detcons)
    detdetfate = detfate[dead_idx, :]  # rows for detritus groups only
    detinputs = detinputs1 + np.sum(det_unused[:, np.newaxis] * detdetfate, axis=0)

    # Detritus EE
    with np.errstate(divide="ignore", invalid="ignore"):
        det_ee = np.where(detinputs > 0, detcons / detinputs, 0.0)
    for d_idx, det_idx in enumerate(dead_idx):
        ee[det_idx] = det_ee[d_idx]

    # Set detritus biomass and PB
    default_det_pb = 0.5
    det_pb = np.zeros(ndead)
    det_b = np.zeros(ndead)
    for d_idx, det_idx in enumerate(dead_idx):
        det_pb_input = pb[det_idx]
        det_b_input = biomass[det_idx]

        # Ensure detinputs is non-negative
        det_in = max(0.0, detinputs[d_idx])

        # Treat PB as missing if original input was missing (avoid placeholder 1.0 from both_missing)
        if np.isnan(det_pb_input) or det_pb_input <= 0 or original_pb_missing[det_idx]:
            det_pb[d_idx] = default_det_pb
        else:
            det_pb[d_idx] = det_pb_input

        # If biomass was originally missing (we filled prior defaults), treat as missing
        if np.isnan(det_b_input) or det_b_input <= 0 or original_no_b[det_idx]:
            det_b[d_idx] = det_in / det_pb[d_idx] if det_pb[d_idx] > 0 else 0
        else:
            det_b[d_idx] = det_b_input

        # Recalculate PB based on actual inputs and biomass
        # PB for detritus = total inputs / biomass (turnover rate)
        if det_b[d_idx] > 0 and det_in > 0:
            det_pb[d_idx] = det_in / det_b[d_idx]
        elif det_b[d_idx] > 0:
            # No inputs calculated, use default or input PB
            det_pb[d_idx] = (
                default_det_pb if np.isnan(det_pb_input) else max(0.01, det_pb_input)
            )

        biomass[det_idx] = det_b[d_idx]
        pb[det_idx] = det_pb[d_idx]

    # Compute M0 for detritus groups now that PB and EE are finalized for detritus
    for d_idx, det_idx in enumerate(dead_idx):
        m0[det_idx] = pb[det_idx] * (1 - ee[det_idx])

    # Trophic level calculations
    # TL = 1 + sum_i(DC_ij * TL_i) for each predator j
    # Build full diet matrix for all groups (living + dead)
    n_bio = nliving + ndead
    bio_idx = np.concatenate(
        [living_idx, dead_idx]
    )  # Indices of living+dead in original order

    full_diet = np.zeros((n_bio, n_bio))

    # Fill in diet values - rows are prey (in bio_idx order), cols are predators (living only)
    full_diet[:, :nliving] = diet_values[bio_idx, :nliving]

    # Normalize to exclude import
    import_row = (
        diet_values[ngroups, :] if diet_values.shape[0] > ngroups else np.zeros(nliving)
    )
    total_diet = np.sum(full_diet[:, :nliving], axis=0)
    import_fracs = (
        import_row[:nliving] if len(import_row) >= nliving else np.zeros(nliving)
    )
    denom = 1.0 - import_fracs
    norm_mask = (total_diet > 0) & (denom > 0) & (import_fracs < 1)
    safe_denom = np.where(norm_mask, denom, 1.0)
    full_diet[:, :nliving] = np.where(
        norm_mask[np.newaxis, :],
        full_diet[:, :nliving] / safe_denom[np.newaxis, :],
        0.0,
    )

    # Set up linear system: (I - DC^T) * TL = 1
    tl_matrix = np.eye(n_bio) - full_diet.T
    b_tl = np.ones(n_bio)

    # Solve TL system robustly
    try:
        n_tl = tl_matrix.shape[0]
        if n_tl <= 50:
            tl_bio = _gauss_solve(tl_matrix, b_tl)
        else:
            tl_bio = np.linalg.solve(tl_matrix, b_tl)
    except (ValueError, np.linalg.LinAlgError):
        logger.warning("TL solve failed, falling back to least-squares")
        tl_bio = np.linalg.lstsq(tl_matrix, b_tl, rcond=1e-6)[0]

    # Map TL back to original order
    tl = np.ones(ngroups)
    for i, idx in enumerate(bio_idx):
        tl[idx] = tl_bio[i]

    # TL for fleets = weighted average of caught groups
    for g_idx, fleet_global_idx in enumerate(fleet_idx):
        geartot = np.sum(landmat[:, g_idx] + discardmat[:, g_idx])
        if geartot > 0:
            caught = (landmat[:, g_idx] + discardmat[:, g_idx]) / geartot
            tl[fleet_global_idx] = 1 + np.sum(caught * tl)

    # Prepare output arrays (in original order)
    biomass_out = biomass.copy()
    pb_out = pb.copy()
    qb_out = qb.copy()
    qb_out[np.isnan(qb_out)] = 0.0
    ee_out = ee.copy()
    ee_out[fleet_idx] = 0.0  # Fleet EE is always 0

    # Calculate GE (gross efficiency), handling zero QB values
    with np.errstate(divide="ignore", invalid="ignore"):
        ge_out = np.where(qb_out > 0, pb_out / qb_out, 0.0)
    ge_out = np.nan_to_num(ge_out, nan=0.0)

    # M0 (other mortality) for living groups, 0 for others
    m0_out = m0.copy()

    # Prepare diet matrix output (rows = groups + import, cols = living predators)
    diet_out = np.zeros((ngroups + 1, nliving))
    diet_out[:ngroups, :] = diet_values[:ngroups, :]
    if diet_values.shape[0] > ngroups:
        diet_out[ngroups, :] = diet_values[ngroups, :]  # Import row

    rpath_obj = Rpath(
        NUM_GROUPS=ngroups,
        NUM_LIVING=nliving,
        NUM_DEAD=ndead,
        NUM_GEARS=ngear,
        Group=groups.astype(str),
        type=types,
        TL=tl,
        Biomass=biomass_out,
        PB=pb_out,
        QB=qb_out,
        EE=ee_out,
        GE=ge_out,
        M0=m0_out,
        BA=bioacc,
        Unassim=unassim,
        DC=diet_out,
        DetFate=detfate,
        Landings=landmat,
        Discards=discardmat,
        eco_name=eco_name,
        eco_area=eco_area,
        DetInput=det_input_full,
        Immigration=immigration_out,
        Emigration=emigration_out,
        EmigRate=emig_rate_out,
        compat=compat,
    )
    if compat == "ewe":
        _report_ewe_detritus(rpath_obj)

    if debug:
        diagnostics = {
            "A": A,
            "b_vec": b_vec,
            "x": x,
            "diet_values": diet_values,
            "nodetrdiet": nodetrdiet,
            "living_idx": living_idx,
            "no_b": no_b,
            "no_ee": no_ee,
            "pb": pb,
            "qb": qb,
            "biomass_before": model_df["Biomass"].values.astype(float),
            "biomass_after": biomass.copy(),
            "detinputs": detinputs,
            "detcons": detcons,
            "det_pb": det_pb,
            "det_b": det_b,
            "iterations": iterations,
        }
        return rpath_obj, diagnostics

    return rpath_obj

ewe_detritus_fate

ewe_detritus_fate(model: Rpath) -> EweDetritusFate

Route detritus between pools as EwE6's Ecopath does.

EwE (cEcoPathModel.CalcFateOfDetritus and CalcBAofDetritus, vb 619-668) takes the detritus pools in group order. A pool's surplus, inflow minus consumption, goes to every other pool j in the fraction DF(i, j); a later pool's surplus therefore includes what earlier pools passed to it, while what a later pool passes back to an earlier one only adds to that pool's inflow. The fraction a pool sends to itself is not inflow but biomass accumulation, BA += (inflow - consumption - catch) x DF(i, i).

:func:rpath keeps Rpath v1.1's routing instead (a pool's own share counts as inflow; only the first-stage surpluses are passed on), so its detritus EE differ wherever a pool has a fate to itself or passes on detritus another pool passed to it. Ecosim's EwE rule uses this routing.

Source code in pypath/core/ecopath.py
 983
 984
 985
 986
 987
 988
 989
 990
 991
 992
 993
 994
 995
 996
 997
 998
 999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
def ewe_detritus_fate(model: Rpath) -> EweDetritusFate:
    """Route detritus between pools as EwE6's Ecopath does.

    EwE (cEcoPathModel.CalcFateOfDetritus and CalcBAofDetritus, vb 619-668)
    takes the detritus pools in group order. A pool's surplus, inflow minus
    consumption, goes to every other pool j in the fraction DF(i, j); a later
    pool's surplus therefore includes what earlier pools passed to it, while
    what a later pool passes back to an earlier one only adds to that pool's
    inflow. The fraction a pool sends to itself is not inflow but biomass
    accumulation, BA += (inflow - consumption - catch) x DF(i, i).

    :func:`rpath` keeps Rpath v1.1's routing instead (a pool's own share
    counts as inflow; only the first-stage surpluses are passed on), so its
    detritus EE differ wherever a pool has a fate to itself or passes on
    detritus another pool passed to it. Ecosim's EwE rule uses this routing.
    """
    types = np.asarray(model.type, dtype=float)
    n = len(types)
    living = np.where(types < 2)[0]
    dead = np.where(types == 2)[0]
    fleets = np.where(types == 3)[0]
    biomass = np.nan_to_num(np.asarray(model.Biomass, dtype=float))
    qb = np.nan_to_num(np.asarray(model.QB, dtype=float))
    m0 = np.nan_to_num(np.asarray(model.M0, dtype=float))
    unassim = np.nan_to_num(np.asarray(model.Unassim, dtype=float))
    fate = np.nan_to_num(np.asarray(model.DetFate, dtype=float))
    diet = np.nan_to_num(np.asarray(model.DC, dtype=float))
    landings = np.nan_to_num(np.asarray(model.Landings, dtype=float))
    discards = np.nan_to_num(np.asarray(model.Discards, dtype=float))
    imports = np.zeros(n)
    if len(model.DetInput) == n:
        imports = np.nan_to_num(np.asarray(model.DetInput, dtype=float))

    # Flows into each pool from living groups (deaths, as rpath() counts them,
    # and egestion; CalcGS_Det_FlowToDet) and fleets (discards)
    loss = np.zeros(n)
    loss[living] = m0[living] * biomass[living] + (
        biomass[living] * qb[living] * unassim[living]
    )
    for f_col, f in enumerate(fleets):
        loss[f] = discards[living, f_col].sum()
    sources = np.concatenate([living, fleets])
    inflow = imports[dead] + loss[sources] @ fate[sources, :]
    # CalcDetEaten: B x QB x DC of every consumer (DC columns follow living)
    eaten = diet[dead, :] @ (biomass[living] * qb[living])
    passed = np.zeros(len(dead))
    for k in range(len(dead)):
        surplus = inflow[k] - eaten[k]
        if surplus > 0:
            for j in range(len(dead)):
                if j != k:
                    inflow[j] += surplus * fate[dead[k], j]
                    passed[k] += surplus * fate[dead[k], j]
    catch = landings[dead].sum(axis=1) + discards[dead].sum(axis=1)
    own = fate[dead, np.arange(len(dead))]
    ba = np.nan_to_num(np.asarray(model.BA, dtype=float))[dead]
    ba = ba + (inflow - eaten - catch) * own
    with np.errstate(divide="ignore", invalid="ignore"):
        ee = np.where(inflow > 0, eaten / inflow, 0.0)

    def _full(values):
        out = np.zeros(n)
        out[dead] = values
        return out

    return EweDetritusFate(
        input_to_det=_full(inflow),
        det_eaten=_full(eaten),
        passed_on=_full(passed),
        ba=_full(ba),
        ee=_full(ee),
    )

Parameters

pypath.core.params

Parameter data structures for PyPath.

This module contains the RpathParams class and functions for creating, reading, writing, and validating Ecopath parameter files.

RpathStanzaParams dataclass

Parameters for multi-stanza (age-structured) groups.

Attributes:

Name Type Description
n_stanza_groups int

Number of stanza group sets (e.g., juvenile + adult = 1 set)

stgroups DataFrame

Stanza group parameters (VBGF_Ksp, VBGF_d, Wmat, etc.)

stindiv DataFrame

Individual stanza parameters (First, Last, Z, Leading)

Source code in pypath/core/params.py
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
@dataclass
class RpathStanzaParams:
    """Parameters for multi-stanza (age-structured) groups.

    Attributes
    ----------
    n_stanza_groups : int
        Number of stanza group sets (e.g., juvenile + adult = 1 set)
    stgroups : pd.DataFrame
        Stanza group parameters (VBGF_Ksp, VBGF_d, Wmat, etc.)
    stindiv : pd.DataFrame
        Individual stanza parameters (First, Last, Z, Leading)
    """

    n_stanza_groups: int = 0
    stgroups: Optional[pd.DataFrame] = None
    stindiv: Optional[pd.DataFrame] = None

RpathParams dataclass

Container for Rpath model parameters.

This class holds all parameters needed to create a balanced Ecopath model.

Attributes:

Name Type Description
model DataFrame

Basic parameters for each group including: - Group: Group name - Type: 0=consumer, 1=producer, 2=detritus, 3=fleet - Biomass: Biomass (t/km²) - PB: Production/Biomass ratio (1/year) - QB: Consumption/Biomass ratio (1/year) - EE: Ecotrophic efficiency - ProdCons: Production/Consumption ratio (GE) - BioAcc: Biomass accumulation rate - Unassim: Unassimilated consumption fraction - DetInput: Detrital input (for detritus groups) Plus columns for detritus fate and landings/discards by fleet.

diet DataFrame

Diet composition matrix where rows are prey (including Import) and columns are predators. Values are fractions (0-1).

stanzas RpathStanzaParams

Multi-stanza (age-structured) group parameters.

pedigree DataFrame

Data quality/pedigree information for parameters.

remarks DataFrame

Comments/remarks for parameter values. Has same structure as model with string values containing remarks for each cell.

compat {'rpath', 'ewe'}

Whose conventions the model follows (roadmap decision D1): "ewe" for models read from EwE (read_ewemdb, read_ewef, ecobase_to_rpath), "rpath" (the default) for models built here or read from Rpath CSVs. rpath() reports EwE's detritus routing for "ewe" (see ewe_detritus_fate). Ecosim's fast-group rule defaults to it (rsim_scenario, rsim_params: 'ewe' for "ewe", 'rpath' otherwise); an explicit fast_group_rule wins.

Examples:

>>> params = create_rpath_params(
...     groups=['Phyto', 'Zoo', 'Fish', 'Detritus', 'Fleet'],
...     types=[1, 0, 0, 2, 3]
... )
>>> params.model['Biomass'] = [10.0, 5.0, 2.0, 100.0, np.nan]
Source code in pypath/core/params.py
 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
@dataclass
class RpathParams:
    """Container for Rpath model parameters.

    This class holds all parameters needed to create a balanced Ecopath model.

    Attributes
    ----------
    model : pd.DataFrame
        Basic parameters for each group including:
        - Group: Group name
        - Type: 0=consumer, 1=producer, 2=detritus, 3=fleet
        - Biomass: Biomass (t/km²)
        - PB: Production/Biomass ratio (1/year)
        - QB: Consumption/Biomass ratio (1/year)
        - EE: Ecotrophic efficiency
        - ProdCons: Production/Consumption ratio (GE)
        - BioAcc: Biomass accumulation rate
        - Unassim: Unassimilated consumption fraction
        - DetInput: Detrital input (for detritus groups)
        Plus columns for detritus fate and landings/discards by fleet.

    diet : pd.DataFrame
        Diet composition matrix where rows are prey (including Import)
        and columns are predators. Values are fractions (0-1).

    stanzas : RpathStanzaParams
        Multi-stanza (age-structured) group parameters.

    pedigree : pd.DataFrame
        Data quality/pedigree information for parameters.

    remarks : pd.DataFrame
        Comments/remarks for parameter values. Has same structure as model
        with string values containing remarks for each cell.

    compat : {"rpath", "ewe"}
        Whose conventions the model follows (roadmap decision D1): "ewe" for
        models read from EwE (``read_ewemdb``, ``read_ewef``,
        ``ecobase_to_rpath``), "rpath" (the default) for models built here or
        read from Rpath CSVs. ``rpath()`` reports EwE's detritus routing for
        "ewe" (see ``ewe_detritus_fate``). Ecosim's fast-group rule defaults
        to it (``rsim_scenario``, ``rsim_params``: ``'ewe'`` for "ewe",
        ``'rpath'`` otherwise); an explicit ``fast_group_rule`` wins.

    Examples
    --------
    >>> params = create_rpath_params(
    ...     groups=['Phyto', 'Zoo', 'Fish', 'Detritus', 'Fleet'],
    ...     types=[1, 0, 0, 2, 3]
    ... )
    >>> params.model['Biomass'] = [10.0, 5.0, 2.0, 100.0, np.nan]
    """

    model: pd.DataFrame
    diet: pd.DataFrame
    stanzas: RpathStanzaParams = field(default_factory=RpathStanzaParams)
    pedigree: Optional[pd.DataFrame] = None
    remarks: Optional[pd.DataFrame] = None
    ecosim: Optional[Dict[str, Any]] = None
    compat: str = "rpath"

    def __repr__(self) -> str:
        n_groups = len(self.model)
        n_living = len(self.model[self.model["Type"] <= 1])
        n_dead = len(self.model[self.model["Type"] == 2])
        n_fleet = len(self.model[self.model["Type"] == 3])
        return (
            f"RpathParams(\n"
            f"  groups={n_groups} (living={n_living}, detritus={n_dead}, fleets={n_fleet})\n"
            f"  stanzas={self.stanzas.n_stanza_groups}\n"
            f")"
        )

get_groups_by_type

get_groups_by_type(groups: List[str], types: List[int]) -> Dict[str, List[str]]

Return dict mapping type names to group lists.

Parameters:

Name Type Description Default
groups list of str

Names of all groups in the model.

required
types list of int

Type code for each group (0=consumer, 1=producer, 2=detritus, 3=fleet).

required

Returns:

Type Description
dict

Dictionary with keys: 'consumers', 'producers', 'detritus', 'fleets', 'living' (types 0 and 1), and 'prey' (types 0, 1, and 2).

Source code in pypath/core/params.py
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 get_groups_by_type(groups: List[str], types: List[int]) -> Dict[str, List[str]]:
    """Return dict mapping type names to group lists.

    Parameters
    ----------
    groups : list of str
        Names of all groups in the model.
    types : list of int
        Type code for each group (0=consumer, 1=producer, 2=detritus, 3=fleet).

    Returns
    -------
    dict
        Dictionary with keys: 'consumers', 'producers', 'detritus', 'fleets',
        'living' (types 0 and 1), and 'prey' (types 0, 1, and 2).
    """
    groups = list(groups)
    types = list(types)
    return {
        "consumers": [g for g, t in zip(groups, types) if t == 0],
        "producers": [g for g, t in zip(groups, types) if t == 1],
        "detritus": [g for g, t in zip(groups, types) if t == 2],
        "fleets": [g for g, t in zip(groups, types) if t == 3],
        "living": [g for g, t in zip(groups, types) if t < 2],
        "prey": [g for g, t in zip(groups, types) if t < 3],
    }

create_rpath_params

create_rpath_params(groups: List[str], types: List[int], stgroups: Optional[List[str]] = None) -> RpathParams

Create a shell RpathParams object with empty parameter values.

Creates the basic structure for an Ecopath model that can be filled in with actual parameter values.

Parameters:

Name Type Description Default
groups list of str

Names of all groups in the model (living, detritus, and fleets).

required
types list of int

Type code for each group: - 0: Consumer - 1: Primary producer (or value 0-1 for mixotrophs) - 2: Detritus - 3: Fleet/fishery

required
stgroups list of str

Stanza group assignment for each group. Use None for non-stanza groups. Groups with the same stanza group name will be linked (e.g., juvenile/adult).

None

Returns:

Type Description
RpathParams

Parameter object with NA values ready to be filled in.

Examples:

>>> params = create_rpath_params(
...     groups=['Phyto', 'Zoo', 'SmallFish', 'LargeFish', 'Detritus', 'Fleet'],
...     types=[1, 0, 0, 0, 2, 3],
...     stgroups=[None, None, 'Fish', 'Fish', None, None]
... )
Source code in pypath/core/params.py
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
def create_rpath_params(
    groups: List[str], types: List[int], stgroups: Optional[List[str]] = None
) -> RpathParams:
    """Create a shell RpathParams object with empty parameter values.

    Creates the basic structure for an Ecopath model that can be filled
    in with actual parameter values.

    Parameters
    ----------
    groups : list of str
        Names of all groups in the model (living, detritus, and fleets).
    types : list of int
        Type code for each group:
        - 0: Consumer
        - 1: Primary producer (or value 0-1 for mixotrophs)
        - 2: Detritus
        - 3: Fleet/fishery
    stgroups : list of str, optional
        Stanza group assignment for each group. Use None for non-stanza groups.
        Groups with the same stanza group name will be linked (e.g., juvenile/adult).

    Returns
    -------
    RpathParams
        Parameter object with NA values ready to be filled in.

    Examples
    --------
    >>> params = create_rpath_params(
    ...     groups=['Phyto', 'Zoo', 'SmallFish', 'LargeFish', 'Detritus', 'Fleet'],
    ...     types=[1, 0, 0, 0, 2, 3],
    ...     stgroups=[None, None, 'Fish', 'Fish', None, None]
    ... )
    """
    if len(groups) != len(types):
        raise ValueError("groups and types must have the same length")

    n_groups = len(groups)

    # Identify group types
    gbt = get_groups_by_type(groups, types)
    pred_groups = gbt["living"]  # Consumers/producers
    prey_groups = gbt["prey"]  # All except fleets
    det_groups = gbt["detritus"]
    fleet_groups = gbt["fleets"]

    # Create model DataFrame
    model_data = {
        "Group": groups,
        "Type": types,
        "Biomass": [np.nan] * n_groups,
        "PB": [np.nan] * n_groups,
        "QB": [np.nan] * n_groups,
        "EE": [np.nan] * n_groups,
        "ProdCons": [np.nan] * n_groups,
        "BioAcc": [np.nan] * n_groups,
        "Unassim": [np.nan] * n_groups,
        "DetInput": [np.nan] * n_groups,
    }

    # Add detrital fate columns
    for det in det_groups:
        model_data[det] = [np.nan] * n_groups
        # Set DetInput to 0 for detritus groups
        for i, t in enumerate(types):
            if t == 2:
                model_data["DetInput"][i] = 0.0

    # Add landing and discard columns for each fleet
    n_bio = len([t for t in types if t < 3])  # Non-fleet groups
    for fleet in fleet_groups:
        # Landings
        model_data[fleet] = [0.0] * n_bio + [np.nan] * len(fleet_groups)
        # Discards
        model_data[f"{fleet}.disc"] = [0.0] * n_bio + [np.nan] * len(fleet_groups)

    model = pd.DataFrame(model_data)

    # Create diet DataFrame
    diet_data = {"Group": prey_groups + ["Import"]}
    for pred in pred_groups:
        diet_data[pred] = [np.nan] * (len(prey_groups) + 1)
    diet = pd.DataFrame(diet_data)

    # Create stanza parameters if provided
    stanza_params = RpathStanzaParams()
    if stgroups is not None and any(s is not None for s in stgroups):
        # Get unique stanza groups
        unique_stgroups = sorted(set(s for s in stgroups if s is not None))
        n_stanza_groups = len(unique_stgroups)

        # Count stanzas per group
        nstanzas = [sum(1 for s in stgroups if s == sg) for sg in unique_stgroups]

        stgroups_df = pd.DataFrame(
            {
                "StGroupNum": range(1, n_stanza_groups + 1),
                "StanzaGroup": unique_stgroups,
                "nstanzas": nstanzas,
                "VBGF_Ksp": [np.nan] * n_stanza_groups,
                "VBGF_d": [0.66667] * n_stanza_groups,
                "Wmat": [np.nan] * n_stanza_groups,
                "BAB": [0.0] * n_stanza_groups,
                "RecPower": [1.0] * n_stanza_groups,
            }
        )

        # Individual stanza records
        stindiv_records = []
        for i, (g, t, sg) in enumerate(zip(groups, types, stgroups)):
            if sg is not None:
                st_group_num = unique_stgroups.index(sg) + 1
                stindiv_records.append(
                    {
                        "StGroupNum": st_group_num,
                        "StanzaNum": 0,  # Will be assigned later
                        "GroupNum": i + 1,
                        "Group": g,
                        "First": np.nan,
                        "Last": np.nan,
                        "Z": np.nan,
                        "Leading": np.nan,
                    }
                )

        stindiv_df = pd.DataFrame(stindiv_records)

        stanza_params = RpathStanzaParams(
            n_stanza_groups=n_stanza_groups, stgroups=stgroups_df, stindiv=stindiv_df
        )

    # Create pedigree DataFrame
    pedigree_data = {
        "Group": groups,
        "Biomass": [1.0] * n_groups,
        "PB": [1.0] * n_groups,
        "QB": [1.0] * n_groups,
        "Diet": [1.0] * n_groups,
    }
    # Add fleet pedigree columns
    for fleet in fleet_groups:
        pedigree_data[fleet] = [1.0] * n_groups
    pedigree = pd.DataFrame(pedigree_data)

    return RpathParams(model=model, diet=diet, stanzas=stanza_params, pedigree=pedigree)

read_rpath_params

read_rpath_params(model_file: Union[str, Path], diet_file: Union[str, Path], pedigree_file: Optional[Union[str, Path]] = None, stanza_group_file: Optional[Union[str, Path]] = None, stanza_file: Optional[Union[str, Path]] = None) -> RpathParams

Read Rpath parameters from CSV files.

Parameters:

Name Type Description Default
model_file str or Path

Path to CSV file with model parameters.

required
diet_file str or Path

Path to CSV file with diet composition matrix.

required
pedigree_file str or Path

Path to CSV file with pedigree information.

None
stanza_group_file str or Path

Path to CSV file with stanza group parameters.

None
stanza_file str or Path

Path to CSV file with individual stanza parameters.

None

Returns:

Type Description
RpathParams

Parameter object populated from files.

Source code in pypath/core/params.py
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
def read_rpath_params(
    model_file: Union[str, Path],
    diet_file: Union[str, Path],
    pedigree_file: Optional[Union[str, Path]] = None,
    stanza_group_file: Optional[Union[str, Path]] = None,
    stanza_file: Optional[Union[str, Path]] = None,
) -> RpathParams:
    """Read Rpath parameters from CSV files.

    Parameters
    ----------
    model_file : str or Path
        Path to CSV file with model parameters.
    diet_file : str or Path
        Path to CSV file with diet composition matrix.
    pedigree_file : str or Path, optional
        Path to CSV file with pedigree information.
    stanza_group_file : str or Path, optional
        Path to CSV file with stanza group parameters.
    stanza_file : str or Path, optional
        Path to CSV file with individual stanza parameters.

    Returns
    -------
    RpathParams
        Parameter object populated from files.
    """
    model = pd.read_csv(model_file)
    diet = pd.read_csv(diet_file)

    # Read stanza files if provided
    stanza_params = RpathStanzaParams()
    if stanza_group_file is not None and stanza_file is not None:
        stgroups = pd.read_csv(stanza_group_file)
        stindiv = pd.read_csv(stanza_file)
        stanza_params = RpathStanzaParams(
            n_stanza_groups=len(stgroups), stgroups=stgroups, stindiv=stindiv
        )

    # Read pedigree if provided
    pedigree = None
    if pedigree_file is not None:
        pedigree = pd.read_csv(pedigree_file)
    else:
        # Create default pedigree
        fleet_groups = model[model["Type"] == 3]["Group"].tolist()
        pedigree_data = {
            "Group": model["Group"].tolist(),
            "Biomass": [1.0] * len(model),
            "PB": [1.0] * len(model),
            "QB": [1.0] * len(model),
            "Diet": [1.0] * len(model),
        }
        for fleet in fleet_groups:
            pedigree_data[fleet] = [1.0] * len(model)
        pedigree = pd.DataFrame(pedigree_data)

    return RpathParams(model=model, diet=diet, stanzas=stanza_params, pedigree=pedigree)

write_rpath_params

write_rpath_params(params: RpathParams, eco_name: str, path: Union[str, Path] = '') -> None

Write Rpath parameters to CSV files.

Parameters:

Name Type Description Default
params RpathParams

Parameter object to write.

required
eco_name str

Ecosystem name used in file names.

required
path str or Path

Directory path for output files.

''
Source code in pypath/core/params.py
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
def write_rpath_params(
    params: RpathParams, eco_name: str, path: Union[str, Path] = ""
) -> None:
    """Write Rpath parameters to CSV files.

    Parameters
    ----------
    params : RpathParams
        Parameter object to write.
    eco_name : str
        Ecosystem name used in file names.
    path : str or Path
        Directory path for output files.
    """
    path = Path(path)

    params.model.to_csv(path / f"{eco_name}_model.csv", index=False)
    params.diet.to_csv(path / f"{eco_name}_diet.csv", index=False)

    if params.pedigree is not None:
        params.pedigree.to_csv(path / f"{eco_name}_pedigree.csv", index=False)

    # Save the tables whenever they are present: rsim_scenario uses them even
    # when n_stanza_groups was left at 0.
    st = params.stanzas
    if (
        st is not None
        and isinstance(st.stgroups, pd.DataFrame)
        and isinstance(st.stindiv, pd.DataFrame)
        and (len(st.stgroups) > 0 or len(st.stindiv) > 0)
    ):
        st.stgroups.to_csv(path / f"{eco_name}_stanza_groups.csv", index=False)
        st.stindiv.to_csv(path / f"{eco_name}_stanzas.csv", index=False)

check_rpath_params

check_rpath_params(params: RpathParams) -> bool

Check Rpath parameter files for consistency.

Validates that parameter files are filled out correctly and data is in the expected locations.

Parameters:

Name Type Description Default
params RpathParams

Parameter object to validate.

required

Returns:

Type Description
bool

True if parameters are valid, False otherwise.

Raises:

Type Description
warn

For each validation issue found.

Source code in pypath/core/params.py
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
def check_rpath_params(params: RpathParams) -> bool:
    """Check Rpath parameter files for consistency.

    Validates that parameter files are filled out correctly and data
    is in the expected locations.

    Parameters
    ----------
    params : RpathParams
        Parameter object to validate.

    Returns
    -------
    bool
        True if parameters are valid, False otherwise.

    Raises
    ------
    warnings.warn
        For each validation issue found.
    """
    model = params.model
    diet = params.diet

    n_warnings = 0

    # Check that all types are represented
    type_requirements = [
        (0, "consumer"),
        (1, "producer"),
        (2, "detrital group"),
        (3, "fleet"),
    ]
    for type_val, type_name in type_requirements:
        if len(model[model["Type"] == type_val]) == 0:
            warnings.warn(f"Model must contain at least 1 {type_name}")
            n_warnings += 1

    # Check that either Biomass or EE is provided for living groups
    living = model[model["Type"] < 2]
    missing_both = living[living["Biomass"].isna() & living["EE"].isna()]
    if len(missing_both) > 0:
        groups = missing_both["Group"].tolist()
        warnings.warn(f"Groups missing both Biomass and EE: {groups}")
        n_warnings += 1

    # Inform about PB estimation capability
    has_b_ee_no_pb = living[
        ~living["Biomass"].isna() & ~living["EE"].isna() & living["PB"].isna()
    ]
    if len(has_b_ee_no_pb) > 0:
        groups = has_b_ee_no_pb["Group"].tolist()
        logger.info("Groups with B+EE but missing PB (will be estimated): %s", groups)

    # Check that consumers have QB or ProdCons
    consumers = model[model["Type"] < 1]
    missing_qb = consumers[consumers["QB"].isna() & consumers["ProdCons"].isna()]
    if len(missing_qb) > 0:
        groups = missing_qb["Group"].tolist()
        warnings.warn(f"Consumers missing both QB and ProdCons: {groups}")
        n_warnings += 1

    # Check for invalid QB values (negative or sentinel -9999)
    if "QB" in consumers.columns:
        invalid_qb = consumers[
            consumers["QB"].notna()
            & ((consumers["QB"] < 0) | (consumers["QB"] == -9999))
        ]
        if len(invalid_qb) > 0:
            groups = invalid_qb["Group"].tolist()
            warnings.warn(
                f"Consumers with invalid QB values (negative or -9999): {groups}"
            )
            n_warnings += 1

    # Check diet columns sum to ~1 for consumers
    _n_living = len(model[model["Type"] <= 1])
    pred_groups = model[model["Type"] < 2]["Group"].tolist()

    for pred in pred_groups:
        if pred in diet.columns:
            col_sum = diet[pred].sum()
            pred_type = model[model["Group"] == pred]["Type"].values[0]
            expected = 1.0 - pred_type  # Producers have diet = 0
            if not np.isclose(col_sum, expected, atol=0.01) and not np.isnan(col_sum):
                warnings.warn(
                    f"Diet column '{pred}' sums to {col_sum:.3f}, expected ~{expected}"
                )
                n_warnings += 1

    # Ecosim needs the groups in block order, each with a block's type
    reason = _ecosim_refusal(model["Group"], model["Type"])
    if reason is not None:
        warnings.warn(f"Ecopath balances this model, but Ecosim refuses it. {reason}")
        n_warnings += 1

    # Check Import row exists
    if "Import" not in diet["Group"].values and "import" not in diet["Group"].values:
        warnings.warn("Diet matrix is missing the Import row")
        n_warnings += 1

    if n_warnings == 0:
        logger.info("Rpath parameter file is functional.")
        return True
    else:
        logger.warning(
            "Rpath parameter file needs attention! (%d warnings)", n_warnings
        )
        return False

Ecosim (Dynamic Simulation)

The Ecosim engine runs time-dynamic food web simulations using foraging arena theory. Key entry points:

  • rsim_scenario() — create a scenario from a balanced Ecopath model
  • rsim_run() — run the simulation with RK4 or Adams-Bashforth integration, or with a continuous SciPy solver (see below)

Integration methods

Method Description
"RK4" 4th-order Runge-Kutta. Stable, self-starting. Good for short runs.
"AB" Adams-Bashforth 2-step (matches Rpath). Uses 1 month RK4 warmup then AB2: B_{n+1} = B_n + dt/2 * (3*f_n - f_{n-1}). Includes dynamic fast equilibrium for NoIntegrate groups and Rpath-style biomass bounds. Recommended for calibration and comparison with EwE/Rpath.
"lsoda", "dop853", "radau", "bdf" Continuous pathway (not EwE parity): SciPy's solve_ivp, one call per month, with the defect corrections applied. Results differ from EwE by design; see Continuous Integration Pathway.

Consumption formula

The consumption kernel uses the full Rpath foraging arena functional response:

Q = QQbase * PDY * PYY^(HandleSwitch*COUPLED) *
    DD / (DD - 1 + ((1-Hself)*PYY + Hself*HandleSuite)^(HandleSwitch*COUPLED)) *
    VV / (VV - 1 + (1-Sself)*PDY + Sself*PredSuite)

Where PredSuite and HandleSuite are pooled competitor biomass sums across all predator-prey links sharing the same prey or predator.

The pooling weights (PredPredWeight, PreyPreyWeight) are Rpath's: VV is converted to a rate, VV * QQ / B_prey, before the weight formula, and each prey's (predator's) weights are normalised to sum to 1.

Foraging time

Predators dynamically adjust foraging time using the Rpath formula:

Ftime_new = 0.1 + 0.9 * Ftime_old * ((1 - FtimeAdj) + FtimeAdj * QBopt / (FoodGain / B))

Capped at 2.0. Groups with FtimeAdj = 0 do not adjust foraging time.

NoIntegrate groups (fast equilibrium)

Groups flagged as NoIntegrate (typically detritus, meiobenthos, and other fast-turnover groups) use instantaneous equilibrium instead of ODE integration when running with the AB method:

biomeq = TotGain / (TotLoss / B)
B_new = 0.5 * biomeq + 0.5 * B_old

This matches Rpath's SORWT=0.5 smoothing.

pypath.core.ecosim

Ecosim dynamic simulation implementation.

This module will contain the core Ecosim simulation engine, including the derivative calculations and integration methods.

RunCancelled

Bases: RuntimeError

Raised by rsim_run when its on_month callback asks the run to stop.

Source code in pypath/core/ecosim.py
70
71
class RunCancelled(RuntimeError):
    """Raised by ``rsim_run`` when its ``on_month`` callback asks the run to stop."""

RsimParams dataclass

Dynamic simulation parameters.

Contains all parameters needed to run an Ecosim simulation, derived from a balanced Rpath model.

Attributes:

Name Type Description
NUM_GROUPS int

Total number of groups

NUM_LIVING int

Number of living groups

NUM_DEAD int

Number of detritus groups

NUM_GEARS int

Number of fishing fleets

NUM_BIO int

Number of biomass groups (living + dead)

spname list

Species/group names with "Outside" as first element

spnum ndarray

Species numbers (0 to NUM_GROUPS)

B_BaseRef ndarray

Reference biomass values

MzeroMort ndarray

Other mortality rate (M0 = PB * (1-EE))

UnassimRespFrac ndarray

Unassimilated fraction of consumption

ActiveRespFrac ndarray

Active respiration fraction

FtimeAdj ndarray

Foraging time adjustment rate

FtimeQBOpt ndarray

Optimal Q/B for foraging time

PBopt ndarray

Base production/biomass

NoIntegrate ndarray

Fast equilibrium flag (0 = fast eq, else normal)

HandleSelf ndarray

Prey-overlap weight of each predator's handling time, one value per group (length NUM_GROUPS + 1, as Rpath); every link of a predator takes that predator's value. An array of one value per link (length len(PreyFrom)) is also accepted.

ScrambleSelf ndarray

Predator-overlap weight of the vulnerability term, per group and keyed by the predator, as HandleSelf

Source code in pypath/core/ecosim.py
 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
@dataclass
class RsimParams:
    """Dynamic simulation parameters.

    Contains all parameters needed to run an Ecosim simulation,
    derived from a balanced Rpath model.

    Attributes
    ----------
    NUM_GROUPS : int
        Total number of groups
    NUM_LIVING : int
        Number of living groups
    NUM_DEAD : int
        Number of detritus groups
    NUM_GEARS : int
        Number of fishing fleets
    NUM_BIO : int
        Number of biomass groups (living + dead)
    spname : list
        Species/group names with "Outside" as first element
    spnum : np.ndarray
        Species numbers (0 to NUM_GROUPS)
    B_BaseRef : np.ndarray
        Reference biomass values
    MzeroMort : np.ndarray
        Other mortality rate (M0 = PB * (1-EE))
    UnassimRespFrac : np.ndarray
        Unassimilated fraction of consumption
    ActiveRespFrac : np.ndarray
        Active respiration fraction
    FtimeAdj : np.ndarray
        Foraging time adjustment rate
    FtimeQBOpt : np.ndarray
        Optimal Q/B for foraging time
    PBopt : np.ndarray
        Base production/biomass
    NoIntegrate : np.ndarray
        Fast equilibrium flag (0 = fast eq, else normal)
    HandleSelf : np.ndarray
        Prey-overlap weight of each predator's handling time, one value per
        group (length NUM_GROUPS + 1, as Rpath); every link of a predator
        takes that predator's value. An array of one value per link (length
        ``len(PreyFrom)``) is also accepted.
    ScrambleSelf : np.ndarray
        Predator-overlap weight of the vulnerability term, per group and
        keyed by the predator, as HandleSelf

    Predator-Prey Link Arrays
    -------------------------
    PreyFrom : np.ndarray
        Prey index for each link
    PreyTo : np.ndarray
        Predator index for each link
    QQ : np.ndarray
        Base consumption rate for each link
    DD : np.ndarray
        Handling time parameter
    VV : np.ndarray
        Vulnerability parameter
    HandleSwitch : np.ndarray
        Prey switching exponent
    PredPredWeight : np.ndarray
        Predator density weight
    PreyPreyWeight : np.ndarray
        Prey density weight
    NumPredPreyLinks : int
        Number of predator-prey links

    Fishing Link Arrays
    -------------------
    FishFrom : np.ndarray
        Fished group index
    FishThrough : np.ndarray
        Fleet index
    FishQ : np.ndarray
        Fishing rate (catch/biomass)
    FishTo : np.ndarray
        Destination (0=outside, or detritus)
    NumFishingLinks : int
        Number of fishing links

    Detritus Link Arrays
    --------------------
    DetFrac : np.ndarray
        Fraction flowing to detritus
    DetFrom : np.ndarray
        Source group index
    DetTo : np.ndarray
        Detritus destination index
    NumDetLinks : int
        Number of detritus links
    """

    NUM_GROUPS: int
    NUM_LIVING: int
    NUM_DEAD: int
    NUM_GEARS: int
    NUM_BIO: int
    spname: List[str]
    spnum: np.ndarray
    B_BaseRef: np.ndarray
    MzeroMort: np.ndarray
    UnassimRespFrac: np.ndarray
    ActiveRespFrac: np.ndarray
    FtimeAdj: np.ndarray
    FtimeQBOpt: np.ndarray
    PBopt: np.ndarray
    NoIntegrate: np.ndarray
    HandleSelf: np.ndarray
    ScrambleSelf: np.ndarray

    # Predator-prey links
    PreyFrom: np.ndarray
    PreyTo: np.ndarray
    QQ: np.ndarray
    DD: np.ndarray
    VV: np.ndarray
    HandleSwitch: np.ndarray
    PredPredWeight: np.ndarray
    PreyPreyWeight: np.ndarray
    NumPredPreyLinks: int

    # Fishing links
    FishFrom: np.ndarray
    FishThrough: np.ndarray
    FishQ: np.ndarray
    FishTo: np.ndarray
    NumFishingLinks: int

    # Detritus links
    DetFrac: np.ndarray
    DetFrom: np.ndarray
    DetTo: np.ndarray
    NumDetLinks: int

    # Group type information
    # PP_type: 0=consumer, 1=producer, 2=detritus
    PP_type: np.ndarray = None

    # Fleet group indices (0-based) for resolving gear indices from FishThrough.
    # Required when groups are in non-canonical order (e.g. detritus first).
    fleet_idx: np.ndarray = None

    # Integration parameters
    BURN_YEARS: int = -1
    COUPLED: int = 1
    RK4_STEPS: int = 4
    SENSE_LIMIT: Tuple[float, float] = (1e-4, 1e4)
    # Accepted for compatibility and ignored: runs no longer adjust M0 (#54;
    # neither Rpath nor EwE does).
    MONTHLY_M0_ADJUST: bool = True
    # EwE6 solves NoIntegrate groups at equilibrium in every RK4 stage;
    # Rpath's rk4_run integrates them (fast_group_rule='rpath').
    RK4_FAST_EQUILIBRIUM: bool = True
    # EwE6 updates the feeding time from the consumption of the start-of-month
    # state (rk4: EatenByAvg after the first Derivt); the 'rpath' rule keeps
    # PyPath's end-of-month consumption.
    FTIME_START_OF_MONTH: bool = True
    # EwE6 arena: prey Ftime and vulnerability forcing scale the inflow to the
    # vulnerable pool (saturating); the 'rpath' rule keeps Rpath's linear prey
    # term (audit D1).
    PREY_FTIME_ARENA: bool = True
    # EwE6 multi-stanza age table: it ends where a cohort reaches 90 % of
    # W_inf and closes with a Ford-Walford plus group, re-closed each month;
    # the 'rpath' rule keeps Rpath's 99.999 % table and numbers-weighted
    # plus group (rsim_scenario -> rpath_stanzas(rule=...)).
    STANZA_WALFORD_PLUS_GROUP: bool = True
    # Rpath's per-link handling term DD / (DD - 1 + preyYY). EwE6 has none:
    # its handling time acts on the predator's total intake (Hden), so under
    # the EwE rule the derivative gets no link handling (_handling_matrix).
    LINK_HANDLING_TERM: bool = False
    # EwE6 sends the unscaled mo x B to detritus while the group loses
    # mo x (1 - MoPred + MoPred x Ftime) x B (SimDetritusMT, vb 3160-3166),
    # so its detritus budget is not closed when Ftime != 1; the 'rpath' rule
    # sends the scaled flow and keeps it closed.
    DETRITUS_MO_UNSCALED: bool = True
    # EwE6's monthly stanza update reads growth from the step's last RK4
    # stage (Eatenby at y + h k3) and survival from its first (LossSt, with
    # the start-of-month stanza biomass); the 'rpath' rule takes both from
    # the end-of-month state, as Rpath's RK4 does.
    STANZA_STAGE_RATES: bool = True
    # Rpath 1.2.0's catch: F times the log mean of the biomass over each RK4
    # sub-step (AB: over the month), not the month-end biomass (EwE6)
    CATCH_LOG_MEAN: bool = False
    # EwE6 handling time (D5): each predator's search rate is divided by Hden,
    # updated once per Derivt from its intake (CmCo = QBmax / QB0); the
    # 'rpath' rule keeps Rpath's per-link handling term instead.
    EWE_HANDLING_TIME: bool = True
    # EwE6 other mortality in Derivt is moTot (CalcBaseAdditiveMort, vb
    # 3802-3816; Derivt vb 3058-3081): non-additive predation mortality
    # (PaddP), and no other mortality for an eaten group with mo <= 0 (EE > 1);
    # the 'rpath' rule keeps mo (see _mo_tot_setup).
    EWE_MO_TOT: bool = True
    # EwE6 Ecosim options. Defaults keep Rpath's behaviour; EwE databases set
    # them (EcosimScenarioGroup.MoPred/FtimeMax, EcosimScenario.UseVarPQ and
    # ForagingTimeLowerLimit, EcopathGroup.vbK).
    MoPred: Optional[np.ndarray] = None  # other mortality follows feeding time
    FtimeMax: Optional[np.ndarray] = None  # feeding-time cap per group
    VbK: Optional[np.ndarray] = None  # von Bertalanffy K per group
    AssimEff: Optional[np.ndarray] = None  # GE0 * (PB + 3 K) / PB
    ForagingTimeLowerLimit: float = 0.1  # EwE6: 0.01
    UseVarPQ: bool = False  # GE = AssimEff * Z / (Z + 3 K)
    SwitchPower: Optional[np.ndarray] = None  # EwE6 prey switching per predator
    # EwE6 predator effect on feeding time (EcosimScenarioGroup.RiskTime): the
    # share of the optimal consumption that scales with predation risk
    RiskTime: Optional[np.ndarray] = None
    # EwE6 QBmax / QB0 per group (EcosimScenarioGroup.CmCo, default 1000)
    CmCo: Optional[np.ndarray] = None
    # EwE6 share of predation mortality that adds to other mortality
    # (EcosimScenarioGroup.AdditivePredMort, default 1); below 1 other
    # mortality compensates (see _mo_tot_setup). Used under the EwE rule.
    PaddP: Optional[np.ndarray] = None
    # EwE6 nutrient limitation of primary production: the free share of the
    # total nutrient at the base (EcosimScenario.NutBaseFreeProp, EwE default
    # 0.9999); None (the 'rpath' rule) = no limitation
    NutBaseFreeProp: Optional[float] = None
    # Constant detritus import per group, indexed like B_BaseRef (EwE
    # DetInFlow, cEcoSimModel.vb:3119-3124); None or zeros = no import.
    DetInput: Optional[np.ndarray] = None
    # EwE6 detritus fate between pools (audit P7), indexed like B_BaseRef:
    # a pool moves DetPassedProp x B x DF to each other pool and, besides
    # consumption, loses an export rate fixed at the first derivative so it
    # grows at DetBA (which holds the share it sends to itself). None (the
    # 'rpath' rule) = Rpath's detritus links.
    DetPassedProp: Optional[np.ndarray] = None
    DetBA: Optional[np.ndarray] = None
    # EwE6 migration of living groups (audit A1-s2), indexed like B_BaseRef:
    # Immigration flows into the group (t/km2/yr) and Emig x B leaves it,
    # Emig = Emigration / B0 (SetupSimVariables, cEcoSimModel.vb:4528; EwE's
    # Ecosim does not use EmigRate for living groups). None = no migration.
    Immigration: Optional[np.ndarray] = None
    Emig: Optional[np.ndarray] = None
    # Rpath's EmigRate (emigration per unit of B), kept for the continuous
    # path only; index 0 unused. None = the Rpath object has no EmigRate.
    EmigRate: Optional[np.ndarray] = None
    # EwE6 pred/prey mediation functions (core.mediation.EweMediation, D3),
    # applied under the EwE rule; None = no mediation
    EweMediation: Optional[object] = None

RsimState dataclass

State variables for Ecosim simulation.

Attributes:

Name Type Description
Biomass ndarray

Current biomass values

N ndarray

Numbers (for stanza groups)

Ftime ndarray

Foraging time multiplier

Source code in pypath/core/ecosim.py
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
@dataclass
class RsimState:
    """State variables for Ecosim simulation.

    Attributes
    ----------
    Biomass : np.ndarray
        Current biomass values
    N : np.ndarray
        Numbers (for stanza groups)
    Ftime : np.ndarray
        Foraging time multiplier
    """

    Biomass: np.ndarray
    N: np.ndarray
    Ftime: np.ndarray
    SpawnBio: Optional[np.ndarray] = None
    StanzaPred: Optional[np.ndarray] = None
    EggsStanza: Optional[np.ndarray] = None
    NageS: Optional[np.ndarray] = None
    WageS: Optional[np.ndarray] = None
    QageS: Optional[np.ndarray] = None

RsimForcing dataclass

Forcing matrices for environmental and biological effects.

All matrices are (n_months x n_groups+1) where first column is "Outside".

Attributes:

Name Type Description
ForcedPrey ndarray

Prey availability multiplier

ForcedMort ndarray

Mortality multiplier

ForcedRecs ndarray

Recruitment multiplier

ForcedSearch ndarray

Search rate multiplier

ForcedActresp ndarray

Active respiration multiplier

ForcedMigrate ndarray

Migration rate

ForcedBio ndarray

Forced biomass values (-1 = not forced)

Source code in pypath/core/ecosim.py
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
@dataclass
class RsimForcing:
    """Forcing matrices for environmental and biological effects.

    All matrices are (n_months x n_groups+1) where first column is "Outside".

    Attributes
    ----------
    ForcedPrey : np.ndarray
        Prey availability multiplier
    ForcedMort : np.ndarray
        Mortality multiplier
    ForcedRecs : np.ndarray
        Recruitment multiplier
    ForcedSearch : np.ndarray
        Search rate multiplier
    ForcedActresp : np.ndarray
        Active respiration multiplier
    ForcedMigrate : np.ndarray
        Migration rate
    ForcedBio : np.ndarray
        Forced biomass values (-1 = not forced)
    """

    ForcedPrey: np.ndarray
    ForcedMort: np.ndarray
    ForcedRecs: np.ndarray
    ForcedSearch: np.ndarray
    ForcedActresp: np.ndarray
    ForcedMigrate: np.ndarray
    ForcedBio: np.ndarray
    ForcedEffort: Optional[np.ndarray] = None
    # EwE link-level forcing, (months, prey, predator) multipliers: a link's
    # search rate and its vulnerable-pool inflow (ApplyAVmodifiers per link).
    # None unless an EwE scenario assigns shapes to single links.
    ForcedSearchLink: Optional[np.ndarray] = None
    ForcedVulLink: Optional[np.ndarray] = None
    # EwE6 nutrient forcing shape (EcosimScenario.NutForcingShapeID), one
    # multiplier of the total nutrient per month; None = 1
    NutForcing: Optional[np.ndarray] = None

RsimFishing dataclass

Fishing forcing matrices.

Attributes:

Name Type Description
ForcedEffort ndarray

Monthly effort multiplier (n_months x n_gears+1)

ForcedFRate ndarray

Annual F rate by species (n_years x n_bio+1)

ForcedCatch ndarray

Annual forced catch by species (n_years x n_bio+1)

Source code in pypath/core/ecosim.py
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
@dataclass
class RsimFishing:
    """Fishing forcing matrices.

    Attributes
    ----------
    ForcedEffort : np.ndarray
        Monthly effort multiplier (n_months x n_gears+1)
    ForcedFRate : np.ndarray
        Annual F rate by species (n_years x n_bio+1)
    ForcedCatch : np.ndarray
        Annual forced catch by species (n_years x n_bio+1)
    """

    ForcedEffort: np.ndarray
    ForcedFRate: np.ndarray
    ForcedCatch: np.ndarray
    # Where True (per year and group) ForcedFRate / ForcedCatch replace the
    # gears' fishing on the group (EwE6 setFishTime); elsewhere they are added
    # as a clean fishery landing Outside (Rpath). None = add everywhere.
    ForcedFReplace: Optional[np.ndarray] = None

RsimScenario dataclass

Complete Ecosim simulation scenario.

Attributes:

Name Type Description
params RsimParams

Dynamic simulation parameters

start_state RsimState

Initial state variables

forcing RsimForcing

Environmental forcing matrices

fishing RsimFishing

Fishing forcing matrices

stanzas dict

Multi-stanza parameters (if any)

eco_name str

Ecosystem name

start_year int

First year of simulation

ecospace (EcospaceParams, optional)

Spatial ECOSPACE parameters (if None, runs non-spatial Ecosim)

environmental_drivers (EnvironmentalDrivers, optional)

Time-varying environmental layers for habitat capacity

Source code in pypath/core/ecosim.py
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
@dataclass
class RsimScenario:
    """Complete Ecosim simulation scenario.

    Attributes
    ----------
    params : RsimParams
        Dynamic simulation parameters
    start_state : RsimState
        Initial state variables
    forcing : RsimForcing
        Environmental forcing matrices
    fishing : RsimFishing
        Fishing forcing matrices
    stanzas : dict
        Multi-stanza parameters (if any)
    eco_name : str
        Ecosystem name
    start_year : int
        First year of simulation
    ecospace : EcospaceParams, optional
        Spatial ECOSPACE parameters (if None, runs non-spatial Ecosim)
    environmental_drivers : EnvironmentalDrivers, optional
        Time-varying environmental layers for habitat capacity
    """

    params: RsimParams
    start_state: RsimState
    forcing: RsimForcing
    fishing: RsimFishing
    stanzas: Optional[RsimStanzas] = None
    # Optional stanza biomass time series (filled during run if stanzas present)
    stanza_biomass: Optional[np.ndarray] = None
    eco_name: str = ""
    start_year: int = 1
    ecospace: Optional["EcospaceParams"] = (
        None  # Forward reference to avoid circular import
    )
    environmental_drivers: Optional["EnvironmentalDrivers"] = None

RsimOutput dataclass

Output from Ecosim simulation run.

Attributes:

Name Type Description
out_Biomass ndarray

Monthly biomass values (n_months x n_groups+1)

out_Catch ndarray

Monthly catch (n_months x n_groups+1): the month-end biomass times the month's fishing mortality (out_FishMort), / 12, so forced F and forced catch are included (EwE6's BB x FishTime). On the continuous path, the month-mean biomass instead (the integral of F x B over the month).

out_Gear_Catch ndarray

Monthly catch by gear link: the gears' share (effort and fleet mediation). A forced F has no fleet breakdown, so where it replaces the gears their links carry 0. Month-mean biomass on the continuous path, as out_Catch.

annual_Biomass ndarray

Annual biomass (n_years x n_groups+1)

annual_Catch ndarray

Annual catch (n_years x n_groups+1)

annual_QB ndarray

Annual Q/B values

annual_Qlink ndarray

Annual consumption by pred-prey pair

stanza_biomass ndarray or None

Monthly sum(N * W) of each multi-stanza group (n_months+1 x n_groups+1, zero for other groups); equals out_Biomass in those columns. None without stanzas.

out_FishMort ndarray or None

Fishing mortality (per year) applied in each month, as the derivative applies it (effort, forced F and catch; EwE6's FishTime), n_months+1 x n_groups+1; row m is month m, row 0 the base F (FishQ at effort 1). Predicts catch as B x F in ewe_sum_of_squares.

out_Hden ndarray or None

EwE6's handling-time term Hden of each predator at the end of each month (n_months+1 x n_groups+1; row 0 the run's start, CmCo / (CmCo + 1)). None when EWE_HANDLING_TIME is off. Recorded by rsim_run; Ecospace keeps one Hden per patch and does not record it. On the continuous path, Hden solved exactly at each month's integrated end state, before the stanza update overwrites the stanza groups, and at the start state (month-1 forcing) in row 0.

end_state RsimState

Final state at end of simulation

crash_year int

Year of crash (-1 if no crash)

crashed_groups set

Set of group indices that crashed (biomass < threshold)

pred ndarray

Predator names for Qlink columns

prey ndarray

Prey names for Qlink columns

start_state RsimState

Initial state (copy)

params dict

Summary parameters

solver_info dict or None

Continuous path only: method, rtol, atol, hden_tol, jacobian ("reuse" or "solver"), the corrections applied, the EwE numerics switches ignored (ignored_switches), rhs_evals (every right-hand side evaluation of the run: solver, Jacobian columns, start checks, quadrature and output rates; the measure of cost) and per month (months) nfev, njev, nlu (as SciPy reports them: under "reuse" nfev leaves out the Jacobian columns and njev counts reused Jacobians too), jac_fresh and jac_reused (the month's Jacobians formed by finite differences and reused under "reuse"; 0 under "solver" and for DOP853), steps, last_step (the month's last full step, a diagnostic: no month's first step is set), status, t_reached, degraded (a month mean fell back to the start state), clips, hden_passes_max (kernel passes of the month's largest handling-time solve), kernel_check (the month's check of the vectorised consumption pass against the link loop, relative; above ecosim_continuous.KERNEL_CHECK_TOL a WARNING names the month) and min_state. The options in force: forcing_interpolation and fast_groups (model options), positivity (numerics) and qs_rate; under fast_groups="quasi-steady" the selected groups qs_groups with their qs_base_rate (per year), the qualifying groups kept as states qs_excluded ("forced", "stanza"), qs_separation (set in month 1; None without quasi-steady groups), the solve's tolerance qs_tol and per month qs_inner_max and qs_fallbacks (None without quasi-steady groups). None for RK4 and AB.

out_Catch_month_end ndarray or None

Continuous path only: EwE's booking, the month's F times the month-end biomass / 12 (n_months+1 x n_groups+1). None for RK4 and AB.

Source code in pypath/core/ecosim.py
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
@dataclass
class RsimOutput:
    """Output from Ecosim simulation run.

    Attributes
    ----------
    out_Biomass : np.ndarray
        Monthly biomass values (n_months x n_groups+1)
    out_Catch : np.ndarray
        Monthly catch (n_months x n_groups+1): the month-end biomass times
        the month's fishing mortality (``out_FishMort``), / 12, so forced F
        and forced catch are included (EwE6's BB x FishTime). On the
        continuous path, the month-mean biomass instead (the integral of
        F x B over the month).
    out_Gear_Catch : np.ndarray
        Monthly catch by gear link: the gears' share (effort and fleet
        mediation). A forced F has no fleet breakdown, so where it replaces
        the gears their links carry 0. Month-mean biomass on the continuous
        path, as ``out_Catch``.
    annual_Biomass : np.ndarray
        Annual biomass (n_years x n_groups+1)
    annual_Catch : np.ndarray
        Annual catch (n_years x n_groups+1)
    annual_QB : np.ndarray
        Annual Q/B values
    annual_Qlink : np.ndarray
        Annual consumption by pred-prey pair
    stanza_biomass : np.ndarray or None
        Monthly sum(N * W) of each multi-stanza group (n_months+1 x
        n_groups+1, zero for other groups); equals ``out_Biomass`` in those
        columns. None without stanzas.
    out_FishMort : np.ndarray or None
        Fishing mortality (per year) applied in each month, as the derivative
        applies it (effort, forced F and catch; EwE6's FishTime), n_months+1 x
        n_groups+1; row m is month m, row 0 the base F (FishQ at effort 1).
        Predicts catch as B x F in ``ewe_sum_of_squares``.
    out_Hden : np.ndarray or None
        EwE6's handling-time term Hden of each predator at the end of each
        month (n_months+1 x n_groups+1; row 0 the run's start, CmCo / (CmCo +
        1)). None when ``EWE_HANDLING_TIME`` is off. Recorded by ``rsim_run``;
        Ecospace keeps one Hden per patch and does not record it. On the
        continuous path, Hden solved exactly at each month's integrated end
        state, before the stanza update overwrites the stanza groups, and at
        the start state (month-1 forcing) in row 0.
    end_state : RsimState
        Final state at end of simulation
    crash_year : int
        Year of crash (-1 if no crash)
    crashed_groups : set
        Set of group indices that crashed (biomass < threshold)
    pred : np.ndarray
        Predator names for Qlink columns
    prey : np.ndarray
        Prey names for Qlink columns
    start_state : RsimState
        Initial state (copy)
    params : dict
        Summary parameters
    solver_info : dict or None
        Continuous path only: ``method``, ``rtol``, ``atol``, ``hden_tol``,
        ``jacobian`` (``"reuse"`` or ``"solver"``), the ``corrections``
        applied, the EwE numerics switches ignored (``ignored_switches``),
        ``rhs_evals`` (every right-hand side evaluation of the run: solver,
        Jacobian columns, start checks, quadrature and output rates; the
        measure of cost) and per month (``months``) ``nfev``, ``njev``,
        ``nlu`` (as SciPy reports them: under ``"reuse"`` ``nfev`` leaves out
        the Jacobian columns and ``njev`` counts reused Jacobians too),
        ``jac_fresh`` and ``jac_reused`` (the month's Jacobians formed by
        finite differences and reused under ``"reuse"``; 0 under
        ``"solver"`` and for DOP853), ``steps``, ``last_step`` (the month's
        last full step, a diagnostic: no month's first step is set),
        ``status``, ``t_reached``, ``degraded`` (a month
        mean fell back to the start state), ``clips``, ``hden_passes_max``
        (kernel passes of the month's largest handling-time solve),
        ``kernel_check`` (the month's check of the vectorised consumption
        pass against the link loop, relative; above
        ``ecosim_continuous.KERNEL_CHECK_TOL`` a WARNING names the month)
        and ``min_state``. The options in force: ``forcing_interpolation``
        and ``fast_groups`` (model options), ``positivity`` (numerics) and
        ``qs_rate``; under ``fast_groups="quasi-steady"`` the selected
        groups ``qs_groups`` with their ``qs_base_rate`` (per year), the
        qualifying groups kept as states ``qs_excluded`` (``"forced"``,
        ``"stanza"``), ``qs_separation`` (set in month 1; None without
        quasi-steady groups), the solve's tolerance ``qs_tol`` and per month
        ``qs_inner_max`` and ``qs_fallbacks`` (None without quasi-steady
        groups). None for RK4 and AB.
    out_Catch_month_end : np.ndarray or None
        Continuous path only: EwE's booking, the month's F times the
        month-end biomass / 12 (n_months+1 x n_groups+1). None for RK4 and AB.
    """

    out_Biomass: np.ndarray
    out_Catch: np.ndarray
    out_Gear_Catch: np.ndarray
    annual_Biomass: np.ndarray
    annual_Catch: np.ndarray
    annual_QB: np.ndarray
    annual_Qlink: np.ndarray
    end_state: RsimState
    crash_year: int
    crashed_groups: set
    pred: np.ndarray
    prey: np.ndarray
    Gear_Catch_sp: np.ndarray
    Gear_Catch_gear: np.ndarray
    Gear_Catch_disp: np.ndarray
    start_state: RsimState
    params: dict
    stanza_biomass: Optional[np.ndarray] = None
    ecotracer: "EcotracerResult | None" = None
    fleet_dynamics: "FleetDynamicsResult | None" = None
    out_FishMort: Optional[np.ndarray] = None
    out_Hden: Optional[np.ndarray] = None
    solver_info: Optional[dict] = None
    out_Catch_month_end: Optional[np.ndarray] = None
    # Notes about the run for its reader (an app shows them): inputs the run
    # did not use as given, each also raised as a UserWarning
    notes: List[str] = field(default_factory=list)

RunSetup dataclass

The per-run inputs that rsim_run's paths share (_run_setup).

params_dict and fishing_dict are the derivative's dicts and state the start biomass after the stanza start. stanzas is the scenario's stanza object, stanza_state its age structure (None when the run goes without it) and stanza_idx the stanza groups. ftime is a copy of start_state.Ftime, which the run updates in place; risk0 is RiskTime's base predation risk (None when RiskTime is off) and handling _ewe_handling_setup's (hden0, hden_start, cmco_qb) or None. params_dict["_hden"] is hden_start, EwE's start value, before the run's start-of-run derivative advances it.

Source code in pypath/core/ecosim.py
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
@dataclass
class RunSetup:
    """The per-run inputs that ``rsim_run``'s paths share (``_run_setup``).

    ``params_dict`` and ``fishing_dict`` are the derivative's dicts and
    ``state`` the start biomass after the stanza start. ``stanzas`` is the
    scenario's stanza object, ``stanza_state`` its age structure (None when
    the run goes without it) and ``stanza_idx`` the stanza groups. ``ftime``
    is a copy of ``start_state.Ftime``, which the run updates in place;
    ``risk0`` is RiskTime's base predation risk (None when RiskTime is
    off) and ``handling`` ``_ewe_handling_setup``'s ``(hden0, hden_start,
    cmco_qb)`` or None. ``params_dict["_hden"]`` is ``hden_start``, EwE's
    start value, before the run's start-of-run derivative advances it.
    """

    params_dict: dict
    fishing_dict: dict
    state: np.ndarray
    n_months: int
    n_years: int
    n_groups: int
    stanzas: Optional[RsimStanzas]
    stanza_state: Optional[RsimStanzaState]
    stanza_idx: np.ndarray
    ftime: np.ndarray
    risk0: Optional[np.ndarray]
    handling: Optional[Tuple[np.ndarray, np.ndarray, np.ndarray]]

SubstepCheck dataclass

What substep_check found.

max_difference is the largest relative difference of any group's biomass in any month between the run at substeps and the run at finer sub-steps (infinite if either is not finite), at group in month. converged says whether it is within the tolerance asked.

Source code in pypath/core/ecosim.py
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
@dataclass
class SubstepCheck:
    """What ``substep_check`` found.

    ``max_difference`` is the largest relative difference of any group's
    biomass in any month between the run at ``substeps`` and the run at
    ``finer`` sub-steps (infinite if either is not finite), at ``group`` in
    ``month``. ``converged`` says whether it is within the tolerance asked.
    """

    substeps: int
    finer: int
    max_difference: float
    group: str
    month: int
    converged: bool

detritus_self_fates

detritus_self_fates(rpath, nliving: int, ndead: int) -> dict

Detritus groups whose detritus fate points to themselves.

Returns {group name: fraction} for every dead group with a fate fraction > 0 to its own pool.

Source code in pypath/core/ecosim.py
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
def detritus_self_fates(rpath, nliving: int, ndead: int) -> dict:
    """Detritus groups whose detritus fate points to themselves.

    Returns ``{group name: fraction}`` for every dead group with a fate
    fraction > 0 to its own pool.
    """
    out = {}
    det_fate = np.asarray(rpath.DetFate, dtype=float)
    for k in range(ndead):
        row = nliving + k
        if row < det_fate.shape[0] and k < det_fate.shape[1]:
            frac = det_fate[row, k]
            if np.isfinite(frac) and frac > 0:
                out[str(rpath.Group[row])] = float(frac)
    return out

default_fast_group_rule

default_fast_group_rule(rpath, rpath_params=None) -> str

The fast-group rule a model gets when none is named (roadmap D1).

"ewe" when the model's origin, its compat, is "ewe" (models read from EwE: read_ewemdb, read_ewef, ecobase_to_rpath) and "rpath" otherwise (models built from CSV or in code). compat is read from rpath_params when it is given and has one, else from rpath; a missing compat counts as "rpath".

Parameters:

Name Type Description Default
rpath Rpath

Balanced Ecopath model (or anything with a compat attribute).

required
rpath_params RpathParams

The model's parameters; their compat takes precedence.

None

Returns:

Type Description
str

"ewe" or "rpath".

Source code in pypath/core/ecosim.py
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
def default_fast_group_rule(rpath, rpath_params=None) -> str:
    """The fast-group rule a model gets when none is named (roadmap D1).

    ``"ewe"`` when the model's origin, its ``compat``, is ``"ewe"`` (models
    read from EwE: ``read_ewemdb``, ``read_ewef``, ``ecobase_to_rpath``) and
    ``"rpath"`` otherwise (models built from CSV or in code). ``compat`` is
    read from ``rpath_params`` when it is given and has one, else from
    ``rpath``; a missing ``compat`` counts as ``"rpath"``.

    Parameters
    ----------
    rpath : Rpath
        Balanced Ecopath model (or anything with a ``compat`` attribute).
    rpath_params : RpathParams, optional
        The model's parameters; their ``compat`` takes precedence.

    Returns
    -------
    str
        ``"ewe"`` or ``"rpath"``.
    """
    source = rpath
    if rpath_params is not None and hasattr(rpath_params, "compat"):
        source = rpath_params
    return "ewe" if getattr(source, "compat", "rpath") == "ewe" else "rpath"

rsim_params

rsim_params(rpath: Rpath, mscramble: float = 2.0, mhandle: float = 1000.0, preyswitch: float = 1.0, scrambleselfwt: float = 0.0, handleselfwt: float = 0.0, steps_yr: int = 12, steps_m: int = 1, fast_group_rule: Optional[str] = None) -> RsimParams

Convert Rpath model to Ecosim simulation parameters.

Parameters:

Name Type Description Default
rpath Rpath

Balanced Ecopath model

required
mscramble float

Base vulnerability parameter (default 2.0 = mixed response)

2.0
mhandle float

Base handling time parameter (default 1000 = off)

1000.0
preyswitch float

Prey switching exponent (default 1.0 = off)

1.0
scrambleselfwt float

Predator overlap weight (0 = individual, 1 = all overlap), the start value of every group's ScrambleSelf (applied to each link of that group as predator)

0.0
handleselfwt float

Prey overlap weight (0 = individual, 1 = all overlap), the start value of every group's HandleSelf (keyed by predator, as ScrambleSelf)

0.0
steps_yr int

Timesteps per year (default 12 = monthly)

12
steps_m int

Sub-timesteps per month (default 1)

1
fast_group_rule ('ewe', 'rpath')

Which groups are solved as fast equilibria (NoIntegrate) instead of being integrated. Default: by the model's origin (compat): 'ewe' for EwE imports, 'rpath' otherwise (see :func:default_fast_group_rule). "ewe" follows EwE6: a group whose total loss rate at the start, |loss|/B, exceeds 24 per year (predation + other mortality + fishing; for detritus the inflow minus biomass accumulation). "rpath" follows Rpath: other-mortality flow M0*B above 24 (use it to compare with Rpath outputs). The rule also sets the integrator to match: under "ewe" RK4 takes one step a month with the fast groups at equilibrium in every stage (EwE6 rk4 / SetTimeSteps); under "rpath" four explicit sub-steps. It also picks the multi-stanza age table :func:rsim_scenario builds (STANZA_WALFORD_PLUS_GROUP): EwE6's, closed by a Ford-Walford plus group, or Rpath's.

"ewe"

Returns:

Type Description
RsimParams

Parameters object for simulation

Raises:

Type Description
ValueError

If the balanced model's groups are not in block order (living groups, types 0 and 1, then detritus, 2, then fleets, 3), a group is a mixotroph (0 < type < 1), or a group has some other type.

Source code in pypath/core/ecosim.py
 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
 846
 847
 848
 849
 850
 851
 852
 853
 854
 855
 856
 857
 858
 859
 860
 861
 862
 863
 864
 865
 866
 867
 868
 869
 870
 871
 872
 873
 874
 875
 876
 877
 878
 879
 880
 881
 882
 883
 884
 885
 886
 887
 888
 889
 890
 891
 892
 893
 894
 895
 896
 897
 898
 899
 900
 901
 902
 903
 904
 905
 906
 907
 908
 909
 910
 911
 912
 913
 914
 915
 916
 917
 918
 919
 920
 921
 922
 923
 924
 925
 926
 927
 928
 929
 930
 931
 932
 933
 934
 935
 936
 937
 938
 939
 940
 941
 942
 943
 944
 945
 946
 947
 948
 949
 950
 951
 952
 953
 954
 955
 956
 957
 958
 959
 960
 961
 962
 963
 964
 965
 966
 967
 968
 969
 970
 971
 972
 973
 974
 975
 976
 977
 978
 979
 980
 981
 982
 983
 984
 985
 986
 987
 988
 989
 990
 991
 992
 993
 994
 995
 996
 997
 998
 999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
def rsim_params(
    rpath: Rpath,
    mscramble: float = 2.0,
    mhandle: float = 1000.0,
    preyswitch: float = 1.0,
    scrambleselfwt: float = 0.0,
    handleselfwt: float = 0.0,
    steps_yr: int = 12,
    steps_m: int = 1,
    fast_group_rule: Optional[str] = None,
) -> RsimParams:
    """Convert Rpath model to Ecosim simulation parameters.

    Parameters
    ----------
    rpath : Rpath
        Balanced Ecopath model
    mscramble : float
        Base vulnerability parameter (default 2.0 = mixed response)
    mhandle : float
        Base handling time parameter (default 1000 = off)
    preyswitch : float
        Prey switching exponent (default 1.0 = off)
    scrambleselfwt : float
        Predator overlap weight (0 = individual, 1 = all overlap), the start
        value of every group's ``ScrambleSelf`` (applied to each link of
        that group as predator)
    handleselfwt : float
        Prey overlap weight (0 = individual, 1 = all overlap), the start
        value of every group's ``HandleSelf`` (keyed by predator, as
        ``ScrambleSelf``)
    steps_yr : int
        Timesteps per year (default 12 = monthly)
    steps_m : int
        Sub-timesteps per month (default 1)
    fast_group_rule : {"ewe", "rpath"}, optional
        Which groups are solved as fast equilibria (``NoIntegrate``) instead
        of being integrated. Default: by the model's origin (``compat``):
        ``'ewe'`` for EwE imports, ``'rpath'`` otherwise (see
        :func:`default_fast_group_rule`). ``"ewe"`` follows EwE6: a group whose
        total loss rate at the start, |loss|/B, exceeds 24 per year
        (predation + other mortality + fishing; for detritus the inflow minus
        biomass accumulation). ``"rpath"`` follows Rpath: other-mortality
        flow M0*B above 24 (use it to compare with Rpath outputs). The rule
        also sets the integrator to match: under ``"ewe"`` RK4 takes one step
        a month with the fast groups at equilibrium in every stage (EwE6
        rk4 / SetTimeSteps); under ``"rpath"`` four explicit sub-steps.
        It also picks the multi-stanza age table :func:`rsim_scenario`
        builds (``STANZA_WALFORD_PLUS_GROUP``): EwE6's, closed by a
        Ford-Walford plus group, or Rpath's.

    Returns
    -------
    RsimParams
        Parameters object for simulation

    Raises
    ------
    ValueError
        If the balanced model's groups are not in block order (living
        groups, types 0 and 1, then detritus, 2, then fleets, 3), a group
        is a mixotroph (0 < type < 1), or a group has some other type.
    """
    # Ecosim's arrays assume living groups, then detritus, then fleets; any
    # other order, a group with no block, or a mixotroph gave silently wrong
    # results
    _require_ecosim_groups(rpath.Group, rpath.type)
    if fast_group_rule is None:
        fast_group_rule = default_fast_group_rule(rpath)
    if fast_group_rule not in ("ewe", "rpath"):
        raise ValueError(
            f"fast_group_rule must be 'ewe' or 'rpath', got {fast_group_rule!r}"
        )
    nliving = rpath.NUM_LIVING
    ndead = rpath.NUM_DEAD
    ngear = rpath.NUM_GEARS
    ngroups = rpath.NUM_GROUPS
    nbio = nliving + ndead

    # 0-based indices of fleet groups (needed for gear index resolution when
    # groups are in non-canonical order)
    fleet_idx_arr = np.where(rpath.type == 3)[0]

    # Species names with "Outside" prepended
    spname = ["Outside"] + list(rpath.Group)
    spnum = np.arange(ngroups + 1)

    # Reference biomass (with leading 1.0 for Outside)
    b_baseref = np.concatenate([[1.0], rpath.Biomass])

    # Other mortality M0 = PB * (1 - EE)
    mzero = np.concatenate([[0.0], rpath.PB * (1.0 - rpath.EE)])

    # Unassimilated fraction
    unassim = np.concatenate([[0.0], rpath.Unassim])

    # Build PP_type array: 0=consumer, 1=producer, 2=detritus
    # This is based on the actual group types from the Rpath model
    pp_type = np.zeros(ngroups + 1, dtype=int)
    types = np.asarray(rpath.type, dtype=int)
    pp_type[1:] = np.where(types == 0, 0, np.where(types == 1, 1, 2))

    # Active respiration = 1 - P/Q - Unassim (for consumers)
    qb = rpath.QB.copy()
    # Replace invalid QB values (-9999 or negative) with 0 for non-consumers
    qb = np.where((qb < 0) | (qb == -9999) | np.isnan(qb), 0.0, qb)

    pb = rpath.PB
    active_resp = np.zeros(ngroups + 1)
    for i in range(nliving):
        if qb[i] > 0:
            active_resp[i + 1] = max(0, 1.0 - (pb[i] / qb[i]) - rpath.Unassim[i])

    # Foraging time parameters
    ftime_adj = np.zeros(ngroups + 1)
    # For producers (type=1), use PB as the "consumption" rate
    # For consumers (type=0), use QB
    # For detritus (type=2) and fleets (type=3), use 1.0 as default
    ftime_qbopt_values = np.where(
        rpath.type == 1,
        rpath.PB,
        np.where(
            (rpath.type == 0) & (qb > 0),
            qb,
            0.0,  # Default for detritus, fleets, or invalid QB
        ),
    )
    ftime_qbopt = np.concatenate([[1.0], ftime_qbopt_values])
    pbopt = np.concatenate([[1.0], rpath.PB])

    # NoIntegrate (fast-equilibrium) flags are set after the predator-prey and
    # fishing links exist; see _fast_group_flags below.

    # Predator-prey handling parameters
    handle_self = np.full(ngroups + 1, handleselfwt)
    scramble_self = np.full(ngroups + 1, scrambleselfwt)

    # Build predator-prey links
    # Primary production links (producers eating "Outside")
    prim_to = []
    prim_from = []
    prim_q = []

    for i in range(nliving):
        if rpath.type[i] > 0 and rpath.type[i] <= 1:  # Producer or mixotroph
            prim_to.append(i + 1)  # +1 for 0-indexing offset
            prim_from.append(0)  # From Outside
            q = rpath.PB[i] * rpath.Biomass[i]
            # Adjust for mixotrophs
            if rpath.type[i] < 1:
                q = q / rpath.GE[i] * rpath.type[i] if rpath.GE[i] > 0 else q
            prim_q.append(q)

    # Predator-prey links from diet matrix
    # NOTE: Only consumers (type=0) can be predators in the diet matrix
    pred_to = []
    pred_from = []
    pred_q = []

    dc = rpath.DC[: nliving + ndead, :nliving].copy()

    # Normalize incomplete diets to sum to 1.0 (excluding import)
    # This ensures proper mass balance at equilibrium
    import_row = (
        rpath.DC[-1, :nliving] if len(rpath.DC) > nliving + ndead else np.zeros(nliving)
    )
    for pred_idx in range(nliving):
        if rpath.type[pred_idx] != 0:  # Skip non-consumers
            continue
        if qb[pred_idx] <= 0 or qb[pred_idx] == -9999 or np.isnan(qb[pred_idx]):
            continue

        # Calculate diet sum (excluding import)
        diet_sum = np.sum(dc[:, pred_idx])
        import_frac = import_row[pred_idx] if pred_idx < len(import_row) else 0
        total_diet = diet_sum + import_frac

        # Normalize if diet is incomplete (sums to less than 1.0)
        # This can happen with incomplete data or data entry errors
        if total_diet > 0 and abs(total_diet - 1.0) > 1e-6:
            # Normalize DC column to make total sum to 1.0
            scale_factor = 1.0 / total_diet
            dc[:, pred_idx] *= scale_factor
            import_row[pred_idx] *= scale_factor
    # Build valid predator mask: consumers (type==0) with valid QB
    valid_pred = (
        (rpath.type[:nliving] == 0)
        & (qb[:nliving] > 0)
        & (qb[:nliving] != -9999)
        & ~np.isnan(qb[:nliving])
    )
    # Find all nonzero DC entries using vectorized indexing (predator-major order)
    for pred_idx in np.where(valid_pred)[0]:
        prey_indices = np.where(dc[: nliving + ndead, pred_idx] > 0)[0]
        for prey_idx in prey_indices:
            q = dc[prey_idx, pred_idx] * qb[pred_idx] * rpath.Biomass[pred_idx]
            if q > 0:
                pred_from.append(prey_idx + 1)
                pred_to.append(pred_idx + 1)
                pred_q.append(q)

    # Handle import links: prey from Outside (index 0)
    import_valid = valid_pred & (import_row[:nliving] > 0)
    for pred_idx in np.where(import_valid)[0]:
        q = import_row[pred_idx] * qb[pred_idx] * rpath.Biomass[pred_idx]
        if q > 0:
            pred_from.append(0)  # From Outside
            pred_to.append(pred_idx + 1)
            pred_q.append(q)

    # Combine links
    prey_from = np.array([0] + prim_from + pred_from)
    prey_to = np.array([0] + prim_to + pred_to)
    qq = np.array([0.0] + prim_q + pred_q)

    numpredprey = len(qq) - 1

    # Vulnerability and handling parameters
    dd = np.full(len(qq), mhandle)
    vv = np.full(len(qq), mscramble)
    handle_switch = np.full(len(qq), preyswitch)
    handle_switch[0] = 0

    # Calculate predator and prey weights for scramble
    btmp = b_baseref

    # Rpath's scramble weights: VV is converted to a per-prey-biomass rate
    # (VV * QQ / B_prey; 0 where B_prey <= 0) before the weight formula, whose
    # denominator is then B_pred * QQ * (VV - 1), positive for VV > 1.
    aa = np.zeros(len(qq))
    vv_rate = np.zeros(len(qq))

    for i in range(1, len(qq)):
        prey_b = btmp[prey_from[i]]
        pred_b = btmp[prey_to[i]]
        if prey_b > 0:
            vv_rate[i] = vv[i] * qq[i] / prey_b
        if prey_b > 0 and pred_b > 0:
            numerator = 2.0 * qq[i] * vv_rate[i]
            denominator = vv_rate[i] * pred_b * prey_b - qq[i] * pred_b
            if abs(denominator) > EPSILON:
                aa[i] = numerator / denominator

    pred_pred_weight = aa * btmp[prey_to]
    prey_prey_weight = aa * btmp[prey_from]

    # Normalize weights
    pred_tot_weight = np.zeros(ngroups + 1)
    prey_tot_weight = np.zeros(ngroups + 1)

    for i in range(1, len(qq)):
        pred_tot_weight[prey_from[i]] += pred_pred_weight[i]
        prey_tot_weight[prey_to[i]] += prey_prey_weight[i]

    for i in range(1, len(qq)):
        if pred_tot_weight[prey_from[i]] > 0:
            pred_pred_weight[i] /= pred_tot_weight[prey_from[i]]
        if prey_tot_weight[prey_to[i]] > 0:
            prey_prey_weight[i] /= prey_tot_weight[prey_to[i]]

    # Build fishing links
    fish_from = [0]
    fish_through = [0]
    fish_q = [0.0]
    fish_to = [0]

    for gear_idx in range(ngear):
        # Use fleet_idx_arr to get the actual 0-based group index of this fleet,
        # rather than assuming canonical ordering (nliving + ndead + gear_idx).
        fleet_grp_0based = int(fleet_idx_arr[gear_idx])
        fleet_grp_1based = fleet_grp_0based + 1
        for grp_idx in range(ngroups):
            landing = rpath.Landings[grp_idx, gear_idx]
            if landing > 0 and b_baseref[grp_idx + 1] > 0:
                fish_from.append(grp_idx + 1)
                fish_through.append(fleet_grp_1based)
                fish_q.append(landing / b_baseref[grp_idx + 1])
                fish_to.append(0)  # Landings go Outside

            discard = rpath.Discards[grp_idx, gear_idx]
            if discard > 0 and b_baseref[grp_idx + 1] > 0:
                if ndead == 0:
                    warnings.warn(
                        f"Discard for group {rpath.Group[grp_idx]} "
                        f"({discard:.4f}) cannot be routed: no detritus "
                        f"groups in model. Discards will be lost.",
                        UserWarning,
                        stacklevel=2,
                    )
                    # Route to Outside instead of silently vanishing
                    fish_from.append(grp_idx + 1)
                    fish_through.append(fleet_grp_1based)
                    fish_q.append(discard / b_baseref[grp_idx + 1])
                    fish_to.append(0)  # Outside
                    continue
                # Discards go to detritus based on fate
                for det_idx in range(ndead):
                    det_frac = (
                        rpath.DetFate[fleet_grp_0based, det_idx]
                        if fleet_grp_0based < len(rpath.DetFate)
                        else 1.0 / ndead
                    )
                    if det_frac > 0:
                        fish_from.append(grp_idx + 1)
                        fish_through.append(fleet_grp_1based)
                        fish_q.append(discard * det_frac / b_baseref[grp_idx + 1])
                        # Use dead global indices to avoid arithmetic/indexing ambiguity
                        fish_to.append(nliving + det_idx + 1)

    fish_from = np.array(fish_from)
    fish_through = np.array(fish_through)
    fish_q = np.array(fish_q)
    fish_to = np.array(fish_to)
    if fast_group_rule == "ewe":
        _warn_detritus_fishery(rpath, fish_from)

    # Build detritus links
    det_from = [0]
    det_to = [0]
    det_frac_list = [0.0]

    # DEBUG: print per-detritus source groups from rpath.DetFate to help trace missing links
    for det_idx in range(ndead):
        sources = [
            (i, rpath.Group[i]) for i in range(ngroups) if rpath.DetFate[i, det_idx] > 0
        ]
        # Use nliving + det_idx as the detritus global group index (no +1)
        logger.debug(
            "DetFate det_idx=%s dest_global=%s sources=%s",
            det_idx,
            nliving + det_idx,
            sources,
        )

    # FIX: Use ngroups instead of nliving+ndead to include gear rows (22-24) that contribute to detritus
    for grp_idx in range(ngroups):
        for det_idx in range(ndead):
            frac = rpath.DetFate[grp_idx, det_idx]
            if frac > 0:
                det_from.append(grp_idx + 1)
                det_to.append(nliving + det_idx + 1)
                det_frac_list.append(frac)
                # DEBUG: show each det link created
                logger.debug(
                    "DETLINK: grp_idx=%s det_idx=%s frac=%s det_to=%s",
                    grp_idx,
                    det_idx,
                    frac,
                    nliving + det_idx + 1,
                )
        # Flow to outside (1 - sum of det fate)
        det_out = 1.0 - np.sum(rpath.DetFate[grp_idx, :])
        if det_out > 0:
            det_from.append(grp_idx + 1)
            det_to.append(0)
            det_frac_list.append(det_out)

    det_from = np.array(det_from)
    det_to = np.array(det_to)
    det_frac = np.array(det_frac_list)

    # DEBUG: detect detritus columns with no DetFate sources and report mapping
    try:
        dead_idx = np.arange(nliving, nliving + ndead)
        # Sum DetFate over ALL source groups including gears
        col_sums = np.sum(rpath.DetFate[:, :], axis=0)
        zero_cols = np.where(col_sums == 0)[0]
        if len(zero_cols) > 0:
            det_names = [
                rpath.Group[int(dead_idx[zc])] for zc in zero_cols if zc < len(dead_idx)
            ]
            warnings.warn(
                f"DetFate columns with zero source fractions: "
                f"cols={zero_cols.tolist()}, detritus={det_names}. "
                f"These detritus groups receive no flow from any source.",
                UserWarning,
                stacklevel=2,
            )
        # Also report which detritus columns appear in det_to mapping
        det_to_cols = np.unique(
            (det_to[(det_to > nliving) & (det_to <= nliving + ndead)] - nliving - 1)
        )
        logger.debug("DetTo mapped detritus columns (indices): %s", det_to_cols)
        logger.debug("Unique DetTo values: %s", np.unique(det_to))
    except Exception as e:
        logger.debug("DetFate diagnostic logging failed: %s", e)

    _warn_detritus_self_fate(rpath, nliving, ndead)
    # EwE6 detritus fate between pools (audit P7), for the EwE rule
    ewe_fate = ewe_detritus_fate(rpath) if fast_group_rule == "ewe" else None
    immigration_sim, emig_sim = _migration_vectors(
        rpath, b_baseref, nliving, ndead, detritus=fast_group_rule == "ewe"
    )
    no_integrate = _fast_group_flags(
        fast_group_rule,
        threshold=2.0 * steps_yr * steps_m,
        rpath=rpath,
        nliving=nliving,
        ndead=ndead,
        b_baseref=b_baseref,
        mzero=mzero,
        unassim=unassim,
        pp_type=pp_type,
        prey_from=prey_from,
        prey_to=prey_to,
        qq=qq,
        fish_from=fish_from,
        fish_to=fish_to,
        fish_q=fish_q,
        ewe_fate=ewe_fate,
        immigration=immigration_sim,
        emig=emig_sim,
    )
    det_passed_prop = det_ba = None
    if ewe_fate is not None:
        det_passed_prop, det_ba = _ewe_detritus_vectors(ewe_fate, b_baseref)

    return RsimParams(
        NUM_GROUPS=ngroups,
        NUM_LIVING=nliving,
        NUM_DEAD=ndead,
        NUM_GEARS=ngear,
        NUM_BIO=nbio,
        spname=spname,
        spnum=spnum,
        B_BaseRef=b_baseref,
        MzeroMort=mzero,
        UnassimRespFrac=unassim,
        ActiveRespFrac=active_resp,
        FtimeAdj=ftime_adj,
        FtimeQBOpt=ftime_qbopt,
        PBopt=pbopt,
        NoIntegrate=no_integrate,
        RK4_FAST_EQUILIBRIUM=(fast_group_rule == "ewe"),
        FTIME_START_OF_MONTH=(fast_group_rule == "ewe"),
        PREY_FTIME_ARENA=(fast_group_rule == "ewe"),
        STANZA_WALFORD_PLUS_GROUP=(fast_group_rule == "ewe"),
        LINK_HANDLING_TERM=(fast_group_rule == "rpath"),
        DETRITUS_MO_UNSCALED=(fast_group_rule == "ewe"),
        STANZA_STAGE_RATES=(fast_group_rule == "ewe"),
        CATCH_LOG_MEAN=(fast_group_rule == "rpath"),
        EWE_HANDLING_TIME=(fast_group_rule == "ewe"),
        EWE_MO_TOT=(fast_group_rule == "ewe"),
        # EwE6 takes one RK4 step a month (SetTimeSteps: StepsPerMonth = 1);
        # Rpath's rk4_run takes four sub-steps.
        RK4_STEPS=(1 if fast_group_rule == "ewe" else 4),
        MoPred=np.zeros(ngroups + 1),
        FtimeMax=np.full(ngroups + 1, 2.0),
        SwitchPower=np.zeros(ngroups + 1),
        RiskTime=np.zeros(ngroups + 1),
        CmCo=np.full(ngroups + 1, 1000.0),
        PaddP=np.ones(ngroups + 1),
        NutBaseFreeProp=(0.9999 if fast_group_rule == "ewe" else None),
        DetInput=_det_input_vector(rpath, ngroups),
        DetPassedProp=det_passed_prop,
        DetBA=det_ba,
        Immigration=immigration_sim,
        Emig=emig_sim,
        EmigRate=_emig_rate_vector(rpath, len(b_baseref)),
        VbK=np.zeros(ngroups + 1),
        AssimEff=np.zeros(ngroups + 1),
        HandleSelf=handle_self,
        ScrambleSelf=scramble_self,
        PreyFrom=prey_from,
        PreyTo=prey_to,
        QQ=qq,
        DD=dd,
        VV=vv,
        HandleSwitch=handle_switch,
        PredPredWeight=pred_pred_weight,
        PreyPreyWeight=prey_prey_weight,
        NumPredPreyLinks=numpredprey,
        FishFrom=fish_from,
        FishThrough=fish_through,
        FishQ=fish_q,
        FishTo=fish_to,
        NumFishingLinks=len(fish_from) - 1,
        DetFrac=det_frac,
        DetFrom=det_from,
        DetTo=det_to,
        NumDetLinks=len(det_from) - 1,
        PP_type=pp_type,
        fleet_idx=fleet_idx_arr,
    )

rsim_state

rsim_state(params: RsimParams) -> RsimState

Create initial state vectors for simulation.

Parameters:

Name Type Description Default
params RsimParams

Simulation parameters

required

Returns:

Type Description
RsimState

Initial state with biomass, N, and Ftime

Source code in pypath/core/ecosim.py
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
def rsim_state(params: RsimParams) -> RsimState:
    """Create initial state vectors for simulation.

    Parameters
    ----------
    params : RsimParams
        Simulation parameters

    Returns
    -------
    RsimState
        Initial state with biomass, N, and Ftime
    """
    return RsimState(
        Biomass=params.B_BaseRef.copy(),
        N=np.zeros(params.NUM_GROUPS + 1),
        Ftime=np.ones(params.NUM_GROUPS + 1),
    )

rsim_forcing

rsim_forcing(params: RsimParams, years: range) -> RsimForcing

Create forcing matrices with default values.

Parameters:

Name Type Description Default
params RsimParams

Simulation parameters

required
years range

Years of simulation

required

Returns:

Type Description
RsimForcing

Forcing matrices initialized to default values

Source code in pypath/core/ecosim.py
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
def rsim_forcing(params: RsimParams, years: range) -> RsimForcing:
    """Create forcing matrices with default values.

    Parameters
    ----------
    params : RsimParams
        Simulation parameters
    years : range
        Years of simulation

    Returns
    -------
    RsimForcing
        Forcing matrices initialized to default values
    """
    nyrs = len(years)
    n_months = nyrs * 12
    n_groups = params.NUM_GROUPS + 1

    # Default forcing = 1.0 (no change)
    ones = np.ones((n_months, n_groups))

    return RsimForcing(
        ForcedPrey=ones.copy(),
        ForcedMort=ones.copy(),
        ForcedRecs=ones.copy(),
        ForcedSearch=ones.copy(),
        ForcedActresp=ones.copy(),
        ForcedMigrate=np.zeros((n_months, n_groups)),
        ForcedBio=np.full((n_months, n_groups), -1.0),  # -1 = not forced
        ForcedEffort=ones.copy(),
    )

rsim_fishing

rsim_fishing(params: RsimParams, years: range) -> RsimFishing

Create fishing matrices with default values.

Parameters:

Name Type Description Default
params RsimParams

Simulation parameters

required
years range

Years of simulation

required

Returns:

Type Description
RsimFishing

Fishing matrices initialized to default values

Source code in pypath/core/ecosim.py
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
def rsim_fishing(params: RsimParams, years: range) -> RsimFishing:
    """Create fishing matrices with default values.

    Parameters
    ----------
    params : RsimParams
        Simulation parameters
    years : range
        Years of simulation

    Returns
    -------
    RsimFishing
        Fishing matrices initialized to default values
    """
    nyrs = len(years)
    n_months = nyrs * 12

    # Effort matrix (monthly, for gears)
    effort = np.ones((n_months, params.NUM_GEARS + 1))

    # F rate and Catch matrices (annual, for biomass groups)
    frate = np.zeros((nyrs, params.NUM_BIO + 1))
    catch = np.zeros((nyrs, params.NUM_BIO + 1))

    return RsimFishing(
        ForcedEffort=effort,
        ForcedFRate=frate,
        ForcedCatch=catch,
    )

rsim_scenario

rsim_scenario(rpath: Rpath, rpath_params: RpathParams, years: range = range(1, 101), vulnerability: float = 2.0, scenario_overrides: dict = None, fast_group_rule: Optional[str] = None) -> RsimScenario

Create a complete Ecosim scenario.

Parameters:

Name Type Description Default
rpath Rpath

Balanced Ecopath model

required
rpath_params RpathParams

Original model parameters

required
years range

Years to simulate; years[0] becomes the scenario's start_year, where every rsim_run starts

range(1, 101)
vulnerability float

Base vulnerability parameter (default 2.0 = mixed response) Controls predator-prey functional response: - 1.0 = donor control (top-down) - 2.0 = mixed control - Higher values = more bottom-up control

2.0
scenario_overrides dict

EwE scenario-level parameter overrides. Keys: - 'ftime_adjust': dict mapping 0-based group index -> FtimeAdjust value - 'vv_overrides': dict mapping (prey_0based, pred_0based) -> VV value - 'forced_bio': dict mapping 0-based group index -> array of annual biomass values - 'nut_base_free_prop': EwE's NutBaseFreeProp (EWE rule only) - 'nut_forcing': monthly factors on EwE's total nutrient, from the first simulated month; months past its end take 1 - 'cm_co': dict mapping 0-based group index -> QBmax/QB0 (handling)

None
fast_group_rule ('ewe', 'rpath')

Passed to :func:rsim_params. Default: by the model's origin (compat): 'ewe' for EwE imports, 'rpath' otherwise. The compat of rpath_params takes precedence over the balanced model's (:func:default_fast_group_rule); an explicit rule wins.

"ewe"

Returns:

Type Description
RsimScenario

Complete scenario ready for simulation

Raises:

Type Description
ValueError

If years has fewer than 2 years, or the balanced model's groups are not in block order: living groups (types 0 and 1), then detritus (2), then fleets (3); or a group is a mixotroph (0 < type < 1). Ecopath balances such models; Ecosim refuses them (see :func:rsim_params).

Source code in pypath/core/ecosim.py
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
def rsim_scenario(
    rpath: Rpath,
    rpath_params: RpathParams,
    years: range = range(1, 101),
    vulnerability: float = 2.0,
    scenario_overrides: dict = None,
    fast_group_rule: Optional[str] = None,
) -> RsimScenario:
    """Create a complete Ecosim scenario.

    Parameters
    ----------
    rpath : Rpath
        Balanced Ecopath model
    rpath_params : RpathParams
        Original model parameters
    years : range
        Years to simulate; ``years[0]`` becomes the scenario's
        ``start_year``, where every ``rsim_run`` starts
    vulnerability : float, optional
        Base vulnerability parameter (default 2.0 = mixed response)
        Controls predator-prey functional response:
        - 1.0 = donor control (top-down)
        - 2.0 = mixed control
        - Higher values = more bottom-up control
    scenario_overrides : dict, optional
        EwE scenario-level parameter overrides. Keys:
        - 'ftime_adjust': dict mapping 0-based group index -> FtimeAdjust value
        - 'vv_overrides': dict mapping (prey_0based, pred_0based) -> VV value
        - 'forced_bio': dict mapping 0-based group index -> array of annual biomass values
        - 'nut_base_free_prop': EwE's NutBaseFreeProp (EWE rule only)
        - 'nut_forcing': monthly factors on EwE's total nutrient, from the
          first simulated month; months past its end take 1
        - 'cm_co': dict mapping 0-based group index -> QBmax/QB0 (handling)
    fast_group_rule : {"ewe", "rpath"}, optional
        Passed to :func:`rsim_params`. Default: by the model's origin
        (``compat``): ``'ewe'`` for EwE imports, ``'rpath'`` otherwise. The
        ``compat`` of ``rpath_params`` takes precedence over the balanced
        model's (:func:`default_fast_group_rule`); an explicit rule wins.

    Returns
    -------
    RsimScenario
        Complete scenario ready for simulation

    Raises
    ------
    ValueError
        If ``years`` has fewer than 2 years, or the balanced model's groups
        are not in block order: living groups (types 0 and 1), then
        detritus (2), then fleets (3); or a group is a mixotroph (0 < type
        < 1). Ecopath balances such models; Ecosim refuses them (see
        :func:`rsim_params`).
    """
    if len(years) < 2:
        raise ValueError("Years must be a range of at least 2 years")

    if fast_group_rule is None:
        fast_group_rule = default_fast_group_rule(rpath, rpath_params)
    params = rsim_params(
        rpath, mscramble=vulnerability, fast_group_rule=fast_group_rule
    )
    # Apply scenario-level overrides from EwE database
    if scenario_overrides:
        # Apply FtimeAdjust per group
        if "ftime_adjust" in scenario_overrides:
            for g, val in scenario_overrides["ftime_adjust"].items():
                ecosim_idx = g + 1  # 0-based group -> 1-based ecosim index
                if ecosim_idx < len(params.FtimeAdj):
                    params.FtimeAdj[ecosim_idx] = val

        # Apply VV overrides from forcing matrix
        if "vv_overrides" in scenario_overrides:
            vv_dict = scenario_overrides["vv_overrides"]
            for lk in range(len(params.PreyFrom)):
                prey_g = params.PreyFrom[lk] - 1  # ecosim -> 0-based
                pred_g = params.PreyTo[lk] - 1
                if (prey_g, pred_g) in vv_dict:
                    params.VV[lk] = vv_dict[(prey_g, pred_g)]

        # EwE6 maximum relative P/B of producers (EcosimScenarioGroup.Pbmaxs):
        # production PBmaxs*PB*B / (1 + (PBmaxs-1)*B/B0) is Rpath's producer
        # link with VV = PBmaxs / (PBmaxs - 1); PBmaxs <= 1 is linear.
        if scenario_overrides.get("pb_maxs"):
            for g, pbmax in scenario_overrides["pb_maxs"].items():
                if pbmax is None or not np.isfinite(pbmax):
                    continue
                prod = g + 1
                if not (0 < prod < len(params.PP_type)) or params.PP_type[prod] != 1:
                    continue
                vv = pbmax / (pbmax - 1.0) if pbmax > 1.0 + 1e-9 else 1e10
                for lk in range(1, len(params.PreyFrom)):
                    if params.PreyFrom[lk] == 0 and params.PreyTo[lk] == prod:
                        params.VV[lk] = vv

        # EwE6 Ecosim options (per group: 0-based model index -> value)
        for key, attr in (
            ("mo_pred", "MoPred"),
            ("ftime_max", "FtimeMax"),
            ("vbk", "VbK"),
            ("switch_power", "SwitchPower"),
            ("risk_time", "RiskTime"),
            ("cm_co", "CmCo"),
            ("padd_p", "PaddP"),
        ):
            if scenario_overrides.get(key):
                arr = getattr(params, attr)
                for g, val in scenario_overrides[key].items():
                    if val is None or not np.isfinite(val):
                        continue
                    ecosim_idx = g + 1
                    if 0 < ecosim_idx < len(arr):
                        arr[ecosim_idx] = float(val)
        if "use_var_pq" in scenario_overrides:
            params.UseVarPQ = bool(scenario_overrides["use_var_pq"])
        if (
            scenario_overrides.get("nut_base_free_prop") is not None
            and params.NutBaseFreeProp is not None
        ):
            params.NutBaseFreeProp = float(scenario_overrides["nut_base_free_prop"])
        if scenario_overrides.get("foraging_time_lower_limit") is not None:
            params.ForagingTimeLowerLimit = float(
                scenario_overrides["foraging_time_lower_limit"]
            )
        _set_assimilation_efficiency(params)

    # Preserve optional instrumentation and debug controls set on the
    # original RpathParams object by copying them onto the generated
    # rsim params object. This allows callers/tests to attach
    # 'INSTRUMENT_GROUPS' or 'instrument_callback' to the rpath_params
    # and have them available during simulation without changing
    # existing callsites.
    try:
        for _attr in (
            "INSTRUMENT_GROUPS",
            "VERBOSE_DEBUG",
            "instrument_callback",
            "spname",
            "INSTRUMENT_ASSUME_1BASED",
            "model",
        ):
            if hasattr(rpath_params, _attr):
                setattr(params, _attr, getattr(rpath_params, _attr))
    except Exception as e:
        logger.debug("attribute transfer from rpath_params failed: %s", e)

    state = rsim_state(params)
    forcing = rsim_forcing(params, years)
    fishing = rsim_fishing(params, years)
    # EwE nutrient forcing: one factor per month on the total nutrient;
    # months past the series' end take 1 (no forcing)
    if scenario_overrides and scenario_overrides.get("nut_forcing") is not None:
        series = np.asarray(scenario_overrides["nut_forcing"], dtype=float)
        nut = np.ones(forcing.ForcedBio.shape[0])
        n = min(len(series), len(nut))
        nut[:n] = series[:n]
        forcing.NutForcing = nut

    # Stanza handling: initialize if rpath_params contains stanza definitions
    stanzas = None
    if has_stanza_tables(getattr(rpath_params, "stanzas", None)):
        try:
            # RpathParams keeps the stanza tables as DataFrames; convert them
            # once and hand the same object to both steps, because
            # rpath_stanzas writes the age structure that rsim_stanzas reads.
            # ecosim_stanza_params returns an EcosimStanzaParams it is given
            # as it is: copy it, so the scenario's table (and rule) never
            # lands in the user's object.
            stanza_params = copy.deepcopy(
                ecosim_stanza_params(rpath_params.stanzas, rpath_params.model)
            )
            # rpath_stanzas writes stanza Biomass/QB into the model table.
            # Work on a copy so building a scenario never edits the user's
            # balanced inputs. To use Rpath's workflow, call
            # rpath_stanzas(params) before rpath(params).
            work = copy.copy(rpath_params)
            work.model = rpath_params.model.copy()
            table_rule = (
                "ewe"
                if getattr(params, "STANZA_WALFORD_PLUS_GROUP", False)
                else "rpath"
            )
            rpath_stanzas(work, stanza_params=stanza_params, rule=table_rule)
            stanzas = rsim_stanzas(work, state, params, stanza_params=stanza_params)
        except Exception as e:
            logger.warning(
                "Multi-stanza setup failed; Ecosim runs without the stanza "
                "age structure: %s",
                e,
                exc_info=logger.isEnabledFor(logging.DEBUG),
            )
            stanzas = None

    return RsimScenario(
        params=params,
        start_state=state,
        forcing=forcing,
        fishing=fishing,
        stanzas=stanzas,
        eco_name=rpath.eco_name,
        start_year=years[0],
    )

integrate_groups

integrate_groups(scenario: 'RsimScenario', groups, substeps=None) -> 'RsimScenario'

A copy of a scenario in which the named fast groups are integrated.

Under the EwE rule a group whose turnover is fast (plankton, often detritus) is not integrated: every step sets its biomass to its local equilibrium (NoIntegrate). Such a group cannot be moved between the patches of a spatial run, by diffusion or by water (pypath.spatial.WaterTransport). This clears the flag of the groups named, which are then integrated like the others; the rest of the EwE rule stays, and the other fast groups stay fast.

An integrated group needs sub-steps in proportion to its turnover, and the number cannot be read off its P/B alone: use substep_check. In a 25-group lagoon model zooplankton needed 1 sub-step a month, zooplankton with phytoplankton 4, and detritus, turning over 3,400 times a year, 128; a pool that fast is better left as it is. With enough sub-steps the run differs from the default by what separates an equilibrium from its integration (1e-4 to 1e-3 of the biomass in the models tried).

Every sub-step also brings the groups left fast halfway to their equilibrium, so with more sub-steps they follow it more closely.

Parameters:

Name Type Description Default
scenario RsimScenario

From rsim_scenario or ecosim_scenario_from_ewemdb. It is not changed.

required
groups sequence of str or int

The groups to integrate: names, or rows where 0 is the first group (the numbering of EcospaceParams arrays and of WaterTransport.groups). A group that is integrated already is left as it is; so is every group under the Rpath rule.

required
substeps int

RK4 sub-steps per month for the copy (RK4_STEPS). Default: unchanged, which under the EwE rule is 1.

None

Returns:

Type Description
RsimScenario

A deep copy with the flags, and the sub-steps if given, changed.

Source code in pypath/core/ecosim.py
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
def integrate_groups(scenario: "RsimScenario", groups, substeps=None) -> "RsimScenario":
    """A copy of a scenario in which the named fast groups are integrated.

    Under the EwE rule a group whose turnover is fast (plankton, often
    detritus) is not integrated: every step sets its biomass to its local
    equilibrium (``NoIntegrate``). Such a group cannot be moved between the
    patches of a spatial run, by diffusion or by water
    (``pypath.spatial.WaterTransport``). This clears the flag of the groups
    named, which are then integrated like the others; the rest of the EwE
    rule stays, and the other fast groups stay fast.

    An integrated group needs sub-steps in proportion to its turnover, and
    the number cannot be read off its P/B alone: use ``substep_check``. In a
    25-group lagoon model zooplankton needed 1 sub-step a month, zooplankton
    with phytoplankton 4, and detritus, turning over 3,400 times a year,
    128; a pool that fast is better left as it is. With enough sub-steps the
    run differs from the default by what separates an equilibrium from its
    integration (1e-4 to 1e-3 of the biomass in the models tried).

    Every sub-step also brings the groups left fast halfway to their
    equilibrium, so with more sub-steps they follow it more closely.

    Parameters
    ----------
    scenario : RsimScenario
        From ``rsim_scenario`` or ``ecosim_scenario_from_ewemdb``. It is
        not changed.
    groups : sequence of str or int
        The groups to integrate: names, or rows where 0 is the first group
        (the numbering of ``EcospaceParams`` arrays and of
        ``WaterTransport.groups``). A group that is integrated already is
        left as it is; so is every group under the Rpath rule.
    substeps : int, optional
        RK4 sub-steps per month for the copy (``RK4_STEPS``). Default:
        unchanged, which under the EwE rule is 1.

    Returns
    -------
    RsimScenario
        A deep copy with the flags, and the sub-steps if given, changed.
    """
    if substeps is not None and (
        isinstance(substeps, bool) or int(substeps) != substeps or substeps < 1
    ):
        raise ValueError(
            f"substeps must be a whole number of 1 or more, not {substeps!r}"
        )
    out = copy.deepcopy(scenario)
    rows = _group_state_rows(out.params, groups)
    if getattr(out.params, "RK4_FAST_EQUILIBRIUM", True):
        flags = np.array(out.params.NoIntegrate, copy=True)
        flags[rows] = 0
        out.params.NoIntegrate = flags
    # under the Rpath rule RK4 integrates every group: nothing to clear
    if substeps is not None:
        out.params.RK4_STEPS = int(substeps)
    return out

substep_check

substep_check(scenario: 'RsimScenario', years: Optional[range] = None, *, factor: int = 2, tolerance: float = 0.001, ecospace=None) -> SubstepCheck

Does the run change when its RK4 sub-steps are multiplied?

Runs the scenario as it is and with factor times its sub-steps (RK4_STEPS), and compares the biomass of every living and detritus group in every month. A run with too few sub-steps for an integrated group's turnover differs widely or fails; one with enough differs by little. The scenario is not changed. Check a scenario that moves (changed fishing, forcing): one at rest shows nothing.

A run that fails counts as an infinite difference. rsim_run puts a floor of 1e-10 where a month's biomass is not finite, so a group that started above the floor and is found at it in either run is taken to have failed there (a group that truly collapses that far is reported the same way). The spatial run keeps non-finite values, which count too.

With ecospace, or for a scenario that carries one, both runs are spatial runs (rsim_run_spatial) and every patch is compared: the sub-steps a spatial run needs are checked on the spatial run.

Parameters:

Name Type Description Default
scenario RsimScenario

The scenario to check, e.g. from integrate_groups.

required
years range

As for rsim_run.

None
factor int

The finer run has factor times the sub-steps (default 2).

2
tolerance float

converged is True when the largest relative difference is at most this (default 1e-3).

0.001
ecospace EcospaceParams

Check the spatial run on these spatial parameters. Default: the scenario's own ecospace, if it has one; otherwise plain Ecosim.

None
Source code in pypath/core/ecosim.py
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
def substep_check(
    scenario: "RsimScenario",
    years: Optional[range] = None,
    *,
    factor: int = 2,
    tolerance: float = 1e-3,
    ecospace=None,
) -> SubstepCheck:
    """Does the run change when its RK4 sub-steps are multiplied?

    Runs the scenario as it is and with ``factor`` times its sub-steps
    (``RK4_STEPS``), and compares the biomass of every living and detritus
    group in every month. A run with too few sub-steps for an integrated
    group's turnover differs widely or fails; one with enough differs by
    little. The scenario is not changed. Check a scenario that moves
    (changed fishing, forcing): one at rest shows nothing.

    A run that fails counts as an infinite difference. ``rsim_run`` puts a
    floor of 1e-10 where a month's biomass is not finite, so a group that
    started above the floor and is found at it in either run is taken to
    have failed there (a group that truly collapses that far is reported
    the same way). The spatial run keeps non-finite values, which count
    too.

    With ``ecospace``, or for a scenario that carries one, both runs are
    spatial runs (``rsim_run_spatial``) and every patch is compared: the
    sub-steps a spatial run needs are checked on the spatial run.

    Parameters
    ----------
    scenario : RsimScenario
        The scenario to check, e.g. from ``integrate_groups``.
    years : range, optional
        As for ``rsim_run``.
    factor : int
        The finer run has ``factor`` times the sub-steps (default 2).
    tolerance : float
        ``converged`` is True when the largest relative difference is at
        most this (default 1e-3).
    ecospace : EcospaceParams, optional
        Check the spatial run on these spatial parameters. Default: the
        scenario's own ``ecospace``, if it has one; otherwise plain Ecosim.
    """
    if isinstance(factor, bool) or int(factor) != factor or factor < 2:
        raise ValueError(f"factor must be a whole number of 2 or more, not {factor!r}")
    coarse = int(getattr(scenario.params, "RK4_STEPS", 4) or 1)
    finer = copy.deepcopy(scenario)
    finer.params.RK4_STEPS = coarse * int(factor)
    names = [str(n).strip() for n in scenario.params.spname]
    n_bio = int(scenario.params.NUM_LIVING) + int(scenario.params.NUM_DEAD)
    if ecospace is None:
        ecospace = getattr(scenario, "ecospace", None)

    def biomass(which):
        """[months, groups] or, for a spatial run, [months, groups, patches]."""
        if ecospace is None:
            return np.asarray(rsim_run(which, years=years).out_Biomass)
        from pypath.spatial.integration import rsim_run_spatial

        out = rsim_run_spatial(which, ecospace=copy.deepcopy(ecospace), years=years)
        return np.asarray(out.out_Biomass_spatial)

    with np.errstate(all="ignore"):
        a = biomass(copy.deepcopy(scenario))[:, 1 : n_bio + 1]
        b = biomass(finer)[:, 1 : n_bio + 1]
    # a failed month: not finite, or at the floor rsim_run puts in its place
    floor = EPSILON * (1.0 + 1e-9)
    started = (a[0] > 10.0 * EPSILON)[np.newaxis]
    failed = ~(np.isfinite(a) & np.isfinite(b)) | (
        started & ((a <= floor) | (b <= floor))
    )
    with np.errstate(all="ignore"):
        diff = np.abs(a - b) / np.maximum(np.abs(b), 1e-300)
    diff = np.where(failed, np.inf, diff)
    where = np.unravel_index(int(np.argmax(diff)), diff.shape)
    month, col = int(where[0]), int(where[1])
    worst = float(diff[where])
    return SubstepCheck(
        substeps=coarse,
        finer=coarse * int(factor),
        max_difference=worst,
        group=names[col + 1],
        month=int(month),
        converged=bool(worst <= tolerance),
    )

rsim_run

rsim_run(scenario: RsimScenario, method: str = 'RK4', years: Optional[range] = None, *, mediation=None, ecotracer=None, fleet_dynamics=None, solver_options: Optional[dict] = None, on_month: Optional[Callable[[int, int], Optional[bool]]] = None) -> RsimOutput

Run Ecosim simulation.

Parameters:

Name Type Description Default
scenario RsimScenario

Simulation scenario

required
method str

Integration method, case-insensitive:

  • 'RK4' (Runge-Kutta 4) and 'AB' (Adams-Bashforth) step EwE's and Rpath's monthly scheme (the parity paths);
  • 'lsoda' (the choice for stiff models), 'dop853', 'radau' and 'bdf' (CONTINUOUS_METHODS) solve the continuous Ecosim equations month by month with SciPy's solve_ivp, with the defect corrections of the continuous pathway (R2, R4, R5, detritus fate applied once, Hden solved exactly from a recalibrated Hden0). They differ from EwE by design; RsimOutput.solver_info lists the corrections applied and the EwE numerics switches ignored.

Anything else raises ValueError.

'RK4'
years range

Years to run (default: all years in scenario). It must start at the scenario's first year (scenario.start_year) and runs the first len(years) years: range(scenario.start_year, scenario.start_year + n). A range starting at any other year raises ValueError, since the run always reads forcing and effort from the scenario's first month on.

None
solver_options dict

Options of the continuous methods (unused by RK4 and AB): rtol (> 0, default 1e-6), atol (a scalar > 0 or one value

0 per group 1..NUM_LIVING + NUM_DEAD; default 1e-8 * (rtol / 1e-6) * max(B0_i, 1e-6 * max(B0))), corrections (bool, default True; False leaves out R2, R4, R5 and DF once, while handling time is still solved exactly from the recalibrated Hden0), on_failure ("raise", the default, or "warn"), hden_tol (the relative residual to which handling time is solved, in (0, 1e-8], default 1e-12) and jacobian ("reuse", the default: LSODA, BDF and Radau get finite-difference Jacobians that are reused across the monthly restarts, ecosim_continuous.JacobianReuse; "solver": the solver forms its own; DOP853 uses none either way). positivity is a numerical option too (opt-in; the same equations, so the same solution to the tolerance): "clip", the default, clips biomass at 0 in the right-hand side; "log" integrates ln B (never negative, a group at the 1e-20 floor can only grow; the monthly means stay of B). forcing_interpolation is a model option, not a numerical one (opt-in; it changes the equations and so the results): "constant", the default, holds each month's forcing; "linear" lets ForcedPrey, ForcedMort, ForcedSearch (with the production forcing), ForcedMigrate, ForcedActresp, NutForcing and the link forcing vary inside the month as a continuous tent through mid-month, and "smooth" as one quadratic per month, both keeping every monthly mean and non-negative forcing >= 0 (ecosim_continuous.ForcingInterpolant). Effort, forced F and catch, forced biomass, ForcedRecs, fleet dynamics and quotas stay monthly-held either way. fast_groups is a model option too (opt-in): "states", the default, integrates every group; "quasi-steady" takes the NoIntegrate groups whose base loss rate (LossPropToB / B at the unforced base) exceeds qs_rate (a number > 0 per year, default 365) out of the state and solves their dB/dt = 0 at every evaluation (ecosim_continuous.QuasiSteady); groups forced in any month and stanza groups stay states, and when none qualifies a WARNING says so and every group is a state. solver_info lists qs_groups, their qs_base_rate, qs_excluded and qs_separation (the slowest selected base loss rate over the largest |Re lambda| of the reduced Jacobian at the start of month 1; a WARNING below 10), and each month's qs_inner_max and qs_fallbacks; qs_tol is the solve's tolerance, |dB_f/dt| <= qs_tol x TotGain_f, min(1e-10, max(1e-2 x rtol, 1e-13)). Only attracting roots are accepted (a producer also has an unstable one near B = 1e-10). A selected group's out_Biomass is its solved value (row 0 keeps the start value) and the monthly budget residuals are None. A failed month raises RuntimeError naming the month; with "warn" it is logged, with the month, and the run continues from the last state reached. Even with "warn", a handling-time or quasi-steady solve that fails inside the right-hand side, and a non-finite derivative or non-finite rates at a month's start state, raise. Other keys and invalid values raise ValueError. On the continuous path out_Catch is the month's F times the month-mean biomass / 12 (the integral of F x B) and out_Catch_month_end is EwE's F x month-end biomass / 12; out_Hden[m] is solved at the integrated month-end state, before the stanza update.

None
on_month callable

Called as on_month(month, n_months) once per simulated month, on every method, at the very end of that month's iteration, after every output for the month is stored (the year's annual Qlink included). month is the number of months completed so far, from 1; n_months is the run's total. Returning True stops the run with RunCancelled; only the bool True stops the run, and any other value (None or False) continues it. An exception the callback raises propagates unchanged. A month already in progress is never interrupted. Without it (None, the default) the run is unchanged.

None

Returns:

Type Description
RsimOutput

Simulation results

Raises:

Type Description
RunCancelled

When on_month returns True.

Source code in pypath/core/ecosim.py
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
def rsim_run(
    scenario: RsimScenario,
    method: str = "RK4",
    years: Optional[range] = None,
    *,
    mediation=None,
    ecotracer=None,
    fleet_dynamics=None,
    solver_options: Optional[dict] = None,
    on_month: Optional[Callable[[int, int], Optional[bool]]] = None,
) -> RsimOutput:
    """Run Ecosim simulation.

    Parameters
    ----------
    scenario : RsimScenario
        Simulation scenario
    method : str
        Integration method, case-insensitive:

        - ``'RK4'`` (Runge-Kutta 4) and ``'AB'`` (Adams-Bashforth) step
          EwE's and Rpath's monthly scheme (the parity paths);
        - ``'lsoda'`` (the choice for stiff models), ``'dop853'``,
          ``'radau'`` and ``'bdf'`` (``CONTINUOUS_METHODS``) solve the
          continuous Ecosim equations month by month with SciPy's
          ``solve_ivp``, with the defect corrections of the continuous
          pathway (R2, R4, R5, detritus fate applied once, Hden solved
          exactly from a recalibrated Hden0). They differ from EwE by
          design; ``RsimOutput.solver_info`` lists the corrections applied
          and the EwE numerics switches ignored.

        Anything else raises ``ValueError``.
    years : range, optional
        Years to run (default: all years in scenario). It must start at the
        scenario's first year (``scenario.start_year``) and runs the first
        ``len(years)`` years: ``range(scenario.start_year,
        scenario.start_year + n)``. A range starting at any other year raises
        ``ValueError``, since the run always reads forcing and effort from
        the scenario's first month on.
    solver_options : dict, optional
        Options of the continuous methods (unused by RK4 and AB):
        ``rtol`` (> 0, default 1e-6), ``atol`` (a scalar > 0 or one value
        > 0 per group 1..NUM_LIVING + NUM_DEAD; default
        ``1e-8 * (rtol / 1e-6) * max(B0_i, 1e-6 * max(B0))``),
        ``corrections`` (bool, default True; False leaves out R2, R4, R5 and DF once, while handling time is
        still solved exactly from the recalibrated Hden0), ``on_failure``
        (``"raise"``, the default, or ``"warn"``), ``hden_tol`` (the
        relative residual to which handling time is solved, in (0, 1e-8],
        default 1e-12) and ``jacobian`` (``"reuse"``, the default: LSODA,
        BDF and Radau get finite-difference Jacobians that are reused across
        the monthly restarts, ``ecosim_continuous.JacobianReuse``;
        ``"solver"``: the solver forms its own; DOP853 uses none either
        way). ``positivity`` is a numerical option too (opt-in; the same
        equations, so the same solution to the tolerance): ``"clip"``, the
        default, clips biomass at 0 in the right-hand side; ``"log"``
        integrates ``ln B`` (never negative, a group at the 1e-20 floor can
        only grow; the monthly means stay of B). ``forcing_interpolation`` is a model option, not a numerical
        one (opt-in; it changes the equations and so the results):
        ``"constant"``, the default, holds each month's forcing;
        ``"linear"`` lets ForcedPrey, ForcedMort, ForcedSearch (with the
        production forcing), ForcedMigrate, ForcedActresp, NutForcing and
        the link forcing vary inside the month as a continuous tent through
        mid-month, and ``"smooth"`` as one quadratic per month, both keeping
        every monthly mean and non-negative forcing >= 0
        (``ecosim_continuous.ForcingInterpolant``). Effort, forced F and
        catch, forced biomass, ForcedRecs, fleet dynamics and quotas stay
        monthly-held either way. ``fast_groups`` is a model option too
        (opt-in): ``"states"``, the default, integrates every group;
        ``"quasi-steady"`` takes the ``NoIntegrate`` groups whose base loss
        rate (``LossPropToB / B`` at the unforced base) exceeds ``qs_rate``
        (a number > 0 per year, default 365) out of the state and solves
        their ``dB/dt = 0`` at every evaluation
        (``ecosim_continuous.QuasiSteady``); groups forced in any month and
        stanza groups stay states, and when none qualifies a WARNING says
        so and every group is a state. ``solver_info`` lists ``qs_groups``,
        their ``qs_base_rate``, ``qs_excluded`` and ``qs_separation`` (the
        slowest selected base loss rate over the largest ``|Re lambda|`` of
        the reduced Jacobian at the start of month 1; a WARNING below 10),
        and each month's ``qs_inner_max`` and ``qs_fallbacks``; ``qs_tol``
        is the solve's tolerance, ``|dB_f/dt| <= qs_tol x TotGain_f``,
        ``min(1e-10, max(1e-2 x rtol, 1e-13))``. Only attracting roots are
        accepted (a producer also has an unstable one near B = 1e-10). A selected group's
        ``out_Biomass`` is its solved value (row 0 keeps the start value)
        and the monthly budget residuals are None. A failed month raises
        ``RuntimeError`` naming the month; with ``"warn"`` it is logged, with
        the month, and the run continues from the last state reached. Even
        with ``"warn"``, a handling-time or quasi-steady solve that fails
        inside the right-hand side, and a non-finite derivative or non-finite
        rates at a month's start state, raise. Other keys and invalid values raise
        ``ValueError``. On the continuous path ``out_Catch`` is the month's F
        times the month-mean biomass / 12 (the integral of F x B) and
        ``out_Catch_month_end`` is EwE's F x month-end biomass / 12;
        ``out_Hden[m]`` is solved at the integrated month-end state, before
        the stanza update.
    on_month : callable, optional
        Called as ``on_month(month, n_months)`` once per simulated month, on
        every method, at the very end of that month's iteration, after every
        output for the month is stored (the year's annual Qlink included).
        ``month`` is the number of months completed so far, from 1;
        ``n_months`` is the run's total. Returning True stops the run with
        ``RunCancelled``; only the bool True stops the run, and any other
        value (None or False) continues it. An exception the callback raises
        propagates unchanged. A month already in progress is never
        interrupted. Without it (None, the default) the run is unchanged.

    Returns
    -------
    RsimOutput
        Simulation results

    Raises
    ------
    RunCancelled
        When ``on_month`` returns True.
    """
    from pypath.core.ecosim_deriv import integrate_ab, integrate_rk4

    _continuous = not isinstance(method, str) or method.upper() not in ("RK4", "AB")
    if _continuous:
        from pypath.core.ecosim_continuous import continuous_options

        _cont_opts = continuous_options(
            method,
            solver_options,
            int(scenario.params.NUM_LIVING) + int(scenario.params.NUM_DEAD),
        )
        _cont_method = _cont_opts["method"]
        _on_failure = _cont_opts["on_failure"]
        # params_dict["ibm_groups"] is taken from params.ibm_groups below
        if getattr(scenario.params, "ibm_groups", None):
            raise ValueError(
                "IBM groups are not supported by the continuous methods; use "
                "method='RK4' or 'AB'"
            )

    scenario, _run_notes = _without_stanza_forced_biomass(scenario)
    setup = _run_setup(scenario, years, mediation=mediation)
    params = scenario.params
    fishing_obj = scenario.fishing
    params_dict = setup.params_dict
    fishing_dict = setup.fishing_dict
    n_months = setup.n_months
    n_years = setup.n_years
    n_groups = setup.n_groups
    state = setup.state
    stanzas_obj = setup.stanzas
    stanza_state = setup.stanza_state
    stanza_idx = setup.stanza_idx

    # Initialize output arrays
    out_biomass = np.zeros((n_months + 1, n_groups))
    out_catch = np.zeros((n_months + 1, n_groups))
    out_gear_catch = np.zeros((n_months + 1, params.NumFishingLinks + 1))
    # F applied in each month (EwE6 FishTime); predicts catch as B x F
    out_fishmort = np.zeros((n_months + 1, n_groups))

    # Multi-stanza biomass by month, when the run has the age structure
    stanza_biomass = None
    if stanza_state is not None:
        stanza_biomass = np.zeros((n_months + 1, n_groups))
        stanza_biomass[0, stanza_idx] = state[stanza_idx]

    out_biomass[0] = state

    # History for Adams-Bashforth
    derivs_history = []

    dt = 1.0 / 12.0  # Monthly timestep
    # Rpath integrates each month in RK4_STEPS sub-steps
    rk4_steps = int(getattr(params, "RK4_STEPS", 4) or 1)
    _catch_log_mean = bool(getattr(params, "CATCH_LOG_MEAN", False))
    crash_year = -1
    crashed_groups = set()  # Track which groups have crashed
    crash_threshold = 1e-4  # More reasonable threshold (0.0001 vs 0.000001)

    # Initialize annual Qlink accumulator if links exist
    annual_qlink = (
        np.zeros((n_years, len(params.PreyFrom))) if len(params.PreyFrom) > 0 else None
    )

    # Pre-compute the NoIntegrate mask once (NoIntegrate never changes during sim).
    # This avoids recomputing np.asarray(...) != 0 four times per month.
    no_integrate_mask = (
        np.asarray(params_dict.get("NoIntegrate", np.zeros(n_groups))) != 0
    )

    # Ftime is dynamically adjusted when FtimeAdj > 0, from the setup's copy
    # of the start state; updated each month based on consumption.
    _ftime_current = setup.ftime
    _ftime_adj = params.FtimeAdj
    _ftime_qbopt = params.FtimeQBOpt
    _has_ftime_adj = np.any(_ftime_adj > 0)
    # EwE6 RiskTime, with the setup's base predation risk (None when off)
    _risk_time = getattr(params, "RiskTime", None)
    _risk0 = setup.risk0
    _has_risk = _risk0 is not None
    _risk_mo = np.asarray(params.MzeroMort, dtype=float)

    # Build gear lookup from fleet_idx once before the monthly loop,
    # for non-canonical group ordering support.
    _run_gear_lookup = {}
    if hasattr(params, "fleet_idx") and params.fleet_idx is not None:
        for _pos, _grp0 in enumerate(params.fleet_idx):
            _run_gear_lookup[int(_grp0)] = _pos + 1

    # Ecotracer initialization
    _ecotracer_conc = None
    _ecotracer_out = None
    if ecotracer is not None:
        from pypath.core.ecotracer import ecotracer_step as _ecotracer_step_fn

        n_eco_groups = params.NUM_GROUPS
        _ecotracer_conc = ecotracer.czero[:n_eco_groups].copy()
        _ecotracer_out = np.zeros((n_months + 1, n_eco_groups))
        _ecotracer_out[0] = _ecotracer_conc.copy()

    # Fleet dynamics initialization
    _fleet_capacity = None
    _fleet_out_effort = None
    _fleet_out_revenue = None
    _fleet_out_cost = None
    _fleet_out_profit = None
    _fleet_cumul_catch = None
    _original_fish_q = None
    if fleet_dynamics is not None:
        from pypath.core.fleet_dynamics import apply_quota_caps as _fleet_quota_fn
        from pypath.core.fleet_dynamics import fleet_dynamics_step as _fleet_step_fn

        _n_fd_fleets = params.NUM_GEARS
        _fleet_capacity = fishing_obj.ForcedEffort[0, 1 : _n_fd_fleets + 1].copy()
        _fleet_out_effort = np.zeros((n_months + 1, _n_fd_fleets))
        _fleet_out_revenue = np.zeros((n_months + 1, _n_fd_fleets))
        _fleet_out_cost = np.zeros((n_months + 1, _n_fd_fleets))
        _fleet_out_profit = np.zeros((n_months + 1, _n_fd_fleets))
        _fleet_out_effort[0] = _fleet_capacity.copy()
        _fleet_cumul_catch = np.zeros((_n_fd_fleets, params.NUM_GROUPS))
        _original_fish_q = params.FishQ.copy()

    # Row 0: the base F (EwE6 starts FishTime at Fish1 = catch / B)
    out_fishmort[0] = fishing_mortality(params_dict, {}, fishing_dict)[0]

    # EwE6 handling time (D5; values set in _run_setup): out_hden[0] is the
    # run's start value, which one Derivt at the start biomass advances
    # before month 1 (SetTimeSteps).
    out_hden = None
    _hden_start_pending = False
    # EwE6 DetritusOut, set by the first derivative after FirstTime is armed
    _det_out_pending = params_dict["DetPassedProp"] is not None
    if setup.handling is not None:
        out_hden = np.zeros((n_months + 1, n_groups))
        out_hden[0] = setup.handling[1]  # hden_start
        _hden_start_pending = True

    # Continuous path: one pure right-hand side for the run. It holds its own
    # copy of params_dict with the corrections, the recalibrated Hden0 and
    # DetritusOut fixed at the base state, so EwE's start-of-run Hden step
    # and the DetritusOut reset do not apply.
    rhs = None
    solver_info = None
    out_catch_month_end = None
    if _continuous:
        from pypath.core.ecosim_continuous import (
            KERNEL_CHECK_TOL,
            QS_TOL,
            ContinuousRHS,
            JacobianReuse,
            QuasiSteady,
            default_atol,
            feeding_time,
            integrate_month,
            month_budget,
            quasi_steady_groups,
        )

        _n_bio_c = params.NUM_LIVING + params.NUM_DEAD
        # feeding time is integrated as a state (None without FtimeAdj)
        _feeding = feeding_time(params, _risk0) if _has_ftime_adj else None
        _ft_groups = None if _feeding is None else _feeding.groups
        rhs = ContinuousRHS(
            params_dict,
            fishing_dict,
            _n_bio_c,
            params.B_BaseRef,
            switches={
                k: getattr(params, k, None)
                for k in (
                    "RK4_FAST_EQUILIBRIUM",
                    "STANZA_STAGE_RATES",
                    "FTIME_START_OF_MONTH",
                    "RK4_STEPS",
                )
            },
            corrections=_cont_opts["corrections"],
            hden_tol=_cont_opts["hden_tol"],
            feeding=_feeding,
        )
        _hden_start_pending = False
        _det_out_pending = False
        _rtol = _cont_opts["rtol"]
        _atol = _cont_opts["atol"]
        if _atol is None:
            _atol = default_atol(
                np.asarray(params.B_BaseRef, dtype=float)[1 : _n_bio_c + 1], _rtol
            )
        _atol = np.asarray(_atol, dtype=float)
        _atol_run = _atol
        if _ft_groups is not None:
            # a feeding time is about 1: rtol governs and atol is a floor
            _atol_run = np.concatenate(
                [
                    np.broadcast_to(_atol, (_n_bio_c,)),
                    np.full(len(_ft_groups), 1e-2 * _rtol),
                ]
            )
        # FD Jacobians reused across the months (the run's; not the RHS's).
        # Their difference step's floor is atol / rtol, the biomass states'
        # capped at the default atol's ratio, 0.01 x max(B0, 1e-6 x max B0),
        # so a large user atol does not make the step large (the default
        # atol gives its own ratio exactly)
        _jac_reuse = (
            JacobianReuse(_cont_method, _atol_run, _rtol)
            if _cont_opts["jacobian"] == "reuse"
            else None
        )
        _n_state_c = _n_bio_c + (0 if _ft_groups is None else len(_ft_groups))
        _fd_floor = np.broadcast_to(_atol_run, (_n_state_c,)) / _rtol
        _fd_floor[:_n_bio_c] = np.minimum(
            _fd_floor[:_n_bio_c],
            default_atol(
                np.asarray(params.B_BaseRef, dtype=float)[1 : _n_bio_c + 1], _rtol
            )
            / _rtol,
        )
        # a model option: forcing varying inside each month (None when no
        # interpolated key varies in time, or under "constant")
        _interp_kind = _cont_opts["forcing_interpolation"]
        _interp = (
            None
            if _interp_kind == "constant"
            else _forcing_interpolant(scenario, setup, _interp_kind)
        )
        if _interp_kind != "constant":
            logger.info(
                "continuous path: forcing_interpolation=%r (a model option: "
                "forcing varies inside each month, monthly means kept); "
                "interpolated keys %s",
                _interp_kind,
                [] if _interp is None else list(_interp.keys),
            )
        # a model option: fast groups solved quasi-steady (QuasiSteady): the
        # NoIntegrate groups whose base loss rate exceeds qs_rate, less those
        # forced in any month of the run and the stanza groups
        _qs = None
        _qs_groups: list = []
        _qs_excluded: dict = {"forced": [], "stanza": []}
        _qs_rates: list = []
        # the solve's tolerance, two orders under a user rtol below 1e-8
        # (floored at about the residual's roundoff)
        _qs_tol = min(QS_TOL, max(1e-2 * _rtol, 1e-13))
        if _cont_opts["fast_groups"] == "quasi-steady":
            _qs_rate = _cont_opts["qs_rate"]
            _base_rate = rhs.base_loss_rate()
            _fb = np.asarray(scenario.forcing.ForcedBio, dtype=float)[:n_months]
            _forced_any = np.zeros(_n_bio_c, dtype=bool)
            _n_fb = min(_fb.shape[1] - 1, _n_bio_c)
            _forced_any[:_n_fb] = np.any(_fb[:, 1 : _n_fb + 1] > 0, axis=0)
            _qs_groups, _qs_excluded = quasi_steady_groups(
                _base_rate,
                params.NoIntegrate,
                _qs_rate,
                forced=_forced_any,
                stanza=stanza_idx,
            )
            _qs_rates = [float(_base_rate[g - 1]) for g in _qs_groups]
            if _qs_excluded["forced"] or _qs_excluded["stanza"]:
                logger.info(
                    "continuous path: quasi-steady candidates excluded (kept "
                    "as states for the whole run): forced in some month %s, "
                    "stanza groups %s",
                    _qs_excluded["forced"],
                    _qs_excluded["stanza"],
                )
            if _qs_groups:
                _qs = QuasiSteady(
                    _qs_groups,
                    rhs,
                    step_floor=_atol_run / _rtol,
                    tol=_qs_tol,
                    names=[params.spname[g] for g in _qs_groups],
                )
                logger.info(
                    "continuous path: fast_groups='quasi-steady' (a model "
                    "option: their dB/dt = 0 is solved at every evaluation); "
                    "groups %s, base loss rates %s /yr > qs_rate %g",
                    [f"{g} {params.spname[g]}" for g in _qs_groups],
                    [round(r, 1) for r in _qs_rates],
                    _qs_rate,
                )
            else:
                _flagged = [
                    i
                    for i in range(1, _n_bio_c + 1)
                    if np.asarray(params.NoIntegrate)[i] != 0
                ]
                logger.warning(
                    "fast_groups='quasi-steady': no group qualifies (NoIntegrate "
                    "groups' base loss rates %s /yr, qs_rate %g; excluded %s); "
                    "every group is a state",
                    {g: round(float(_base_rate[g - 1]), 1) for g in _flagged},
                    _qs_rate,
                    _qs_excluded,
                )
        solver_info = {
            "method": _cont_method,
            "rtol": _rtol,
            "atol": _atol.tolist() if _atol.ndim else float(_atol),
            # the feeding-time states' atol (the tail of the solver's vector)
            "atol_ftime": (
                _atol_run[_n_bio_c:].tolist() if _ft_groups is not None else []
            ),
            "hden_tol": _cont_opts["hden_tol"],
            "jacobian": _cont_opts["jacobian"],
            # the opt-in options: forcing_interpolation and fast_groups change
            # the model, positivity is numerics (the same equations)
            "forcing_interpolation": _interp_kind,
            "positivity": _cont_opts["positivity"],
            "fast_groups": _cont_opts["fast_groups"],
            "qs_rate": _cont_opts["qs_rate"],
            # the quasi-steady groups, their base loss rates (per year), the
            # qualifying groups kept as states, and the separation (set in
            # month 1; None without quasi-steady groups)
            "qs_groups": list(_qs_groups),
            "qs_base_rate": list(_qs_rates),
            "qs_excluded": _qs_excluded,
            "qs_separation": None,
            # the quasi-steady solve's tolerance (|dB_f/dt| / TotGain_f)
            "qs_tol": _qs_tol,
            "corrections": list(rhs.corrections),
            "ignored_switches": list(rhs.ignored_switches),
            "ftime_groups": [] if _ft_groups is None else _ft_groups.tolist(),
            "months": [],
        }
        out_catch_month_end = np.zeros((n_months + 1, n_groups))

    # The compiled RK4 step (pypath.core.ecosim_fast) when numba is installed
    # and the run uses only options it covers; else integrate_rk4
    _fast_rk4 = None
    if not _continuous and method.upper() == "RK4":
        from pypath.core import ecosim_fast as _ecosim_fast

        if (
            _ecosim_fast.ENABLED
            and _ecosim_fast.python_hooks_intact(sys.modules[__name__])
            and _ecosim_fast.unsupported_reason(
                params_dict, fishing_dict, scenario.forcing
            )
            is None
        ):
            _fast_rk4 = _ecosim_fast.FastRK4(params_dict, fishing_dict)
    # The compiled derivative for Adams-Bashforth, under the same gates
    _fast_ab = None
    if not _continuous and method.upper() == "AB":
        from pypath.core import ecosim_fast as _ecosim_fast

        if (
            _ecosim_fast.ENABLED
            and _ecosim_fast.AB_ENABLED
            and _ecosim_fast.python_hooks_intact(sys.modules[__name__])
            and _ecosim_fast.unsupported_reason(
                params_dict, fishing_dict, scenario.forcing
            )
            is None
        ):
            _fast_ab = _ecosim_fast.FastRK4(params_dict, fishing_dict)
    # ... and the whole monthly loop compiled (ecosim_fast.CompiledRun) when
    # the run has no fleet dynamics, Ecotracer or mediation
    _compiled = None
    _fast_loop = _fast_rk4 if _fast_rk4 is not None else _fast_ab
    if (
        _fast_loop is not None
        and ecotracer is None
        and fleet_dynamics is None
        and mediation is None
    ):
        _compiled = _ecosim_fast.CompiledRun.build(
            scenario,
            setup,
            _fast_loop,
            rk4_steps,
            dt,
            (
                out_biomass,
                out_catch,
                out_gear_catch,
                out_fishmort,
                stanza_biomass,
                out_hden,
                annual_qlink,
            ),
            **({"method": "AB"} if _fast_ab is not None else {}),
        )
    if _compiled is not None:
        if on_month is None:
            state = _compiled.run(state, 1, n_months)
        else:
            for _m in range(1, n_months + 1):
                state = _compiled.run(state, _m, _m)
                if on_month(_m, n_months) is True:
                    raise RunCancelled(f"run cancelled after month {_m} of {n_months}")
        crash_year, crashed_groups = _compiled.crash_info()

    # Main simulation loop (none left to run after the compiled loop)
    for month in range(1, (0 if _compiled is not None else n_months) + 1):
        # Debug: indicate loop iteration for first few months
        if month <= 6:
            logger.debug("entering month loop month=%s", month)
        t = month * dt
        year_idx = (month - 1) // 12
        month_in_year = (month - 1) % 12

        # Build forcing dict for this timestep (Ftime is _ftime_current itself)
        forcing_dict = _month_forcing(scenario, setup, month, _ftime_current)
        # Forced biomass replaces the group's state (EwE6 setForcedBiomass,
        # applied before and after the step); the derivative sees it too.
        _forced_now = forcing_dict["ForcedBio"]
        _forced_mask = np.asarray(_forced_now) > 0
        if np.any(_forced_mask):
            state[_forced_mask] = np.asarray(_forced_now)[_forced_mask]
        # Forced fishing mortality / catches for the month (Rpath ForcedFRate
        # and ForcedCatch, EwE forced F and catch), as a rate fixed at the
        # start of the month as EwE6 setFishTime does.
        _ff_rate, _ff_replace = _forced_fishing_rate(
            fishing_obj, year_idx, state, params.NUM_GROUPS
        )
        if _ff_rate is not None:
            forcing_dict["ForcedF"] = _ff_rate
            forcing_dict["ForcedFReplace"] = _ff_replace
        month_start_state = state.copy()
        # Rpath 1.2.0's catch (CATCH_LOG_MEAN): the RK4 step adds each
        # sub-step's log-mean biomass times its length here
        _catch_bio = np.zeros(len(state)) if _catch_log_mean else None
        # passed only when used, so a stand-in integrator without it works
        _catch_kw = {} if _catch_bio is None else {"catch_bio": _catch_bio}
        if _hden_start_pending:
            # EwE6 SetTimeSteps: one Derivt at the start biomass advances Hden
            deriv_vector(
                month_start_state.copy(), params_dict, forcing_dict, fishing_dict
            )
            _hden_start_pending = False
        if _det_out_pending:
            # EwE6 arms FirstTime again after SetTimeSteps (vb 860), so the
            # month's first Derivt fixes each pool's DetritusOut (vb 3202)
            params_dict["_det_out"][:] = np.nan
            _det_out_pending = False
        if _fleet_capacity is not None and month > 1 and (month - 1) % 12 == 0:
            # A new quota year: the TAC-closed links reopen before this month
            # runs (the derivative reads fishing_dict), and its catch starts
            # the year's cumulative catch
            _fleet_cumul_catch[:] = 0.0
            params.FishQ = _original_fish_q.copy()
            fishing_dict["FishQ"] = params.FishQ
        # The month's F, as the derivative applies it (EwE6 setFishTime)
        _fleet_med_now = None
        if params_dict.get("_mediation") is not None:
            _fleet_med_now = params_dict["_mediation"].compute_fleet_multipliers(
                month_start_state,
                params_dict.get("Bbase", month_start_state),
                params_dict.get("NUM_GEARS", 0),
            )
        _month_f, _month_link_f = fishing_mortality(
            params_dict, forcing_dict, fishing_dict, fleet_med=_fleet_med_now
        )
        out_fishmort[month] = _month_f
        # EwE6's feeding-time update uses the consumption of this state as
        # Derivt computes it (rk4 accumulates EatenByAvg after its first
        # Derivt), so prey Ftime and mediation are included: take the
        # derivative's FoodGain now.
        _fg_ftime = None
        _fg_start = (
            _has_ftime_adj
            and getattr(params, "FTIME_START_OF_MONTH", False)
            and not _continuous
        )
        _fg_from_stage = _fg_start and _ftime_rates_from_first_stage(
            method, params_dict
        )
        if _fg_start:
            if not _fg_from_stage:
                _fg_rates: dict = {}
                with _frozen_hden(params_dict):
                    deriv_vector(
                        month_start_state.copy(),
                        params_dict,
                        forcing_dict,
                        fishing_dict,
                        rates=_fg_rates,
                    )
                _fg_ftime = np.asarray(_fg_rates["FoodGain"], dtype=float)
            # EwE's ratio is per predator index (CBlast = EatenByAvg /
            # PredAvg, Cbase = StartEatenBy / pred; vb 1762, 3310). That is
            # the biomass for a simple group, and sum(N * WWa) for a stanza
            # group: in biomass units B0 * StanzaPredRatio, taken now, at the
            # start of the month.
            _ftime_index = np.array(month_start_state, dtype=float, copy=True)
            _stanza_ratio_now = forcing_dict.get("StanzaPredRatio")
            if _stanza_ratio_now is not None:
                _sr = np.asarray(_stanza_ratio_now, dtype=float)
                _has_sr = np.isfinite(_sr)
                _ftime_index[_has_sr] = (
                    np.asarray(params.B_BaseRef, dtype=float)[_has_sr] * _sr[_has_sr]
                )

        # EwE6's stanza update reads the step's first and last RK4 stages.
        _stanza_stages = (
            {}
            if stanza_state is not None
            and method.upper() == "RK4"
            and getattr(params, "STANZA_STAGE_RATES", False)
            else None
        )
        # Integration step
        if method.upper() == "RK4":
            old_state = state.copy()
            _stages = _stanza_stages
            if _fg_from_stage and _stages is None:
                _stages = {}
            if _fast_rk4 is not None:
                state = _fast_rk4.step(
                    state,
                    forcing_dict,
                    _month_f,
                    _month_link_f,
                    dt,
                    n_steps=rk4_steps,
                    stage_rates=_stages,
                    **_catch_kw,
                )
            else:
                state = integrate_rk4(
                    state,
                    params_dict,
                    forcing_dict,
                    fishing_dict,
                    dt,
                    n_steps=rk4_steps,
                    stage_rates=_stages,
                    **_catch_kw,
                )
            if _fg_from_stage:
                _fg_rates = _stages["first"]
                _fg_ftime = np.asarray(_fg_rates["FoodGain"], dtype=float)
        elif method.upper() == "AB" and _fast_ab is not None:
            # integrate_ab and its bookkeeping below, on the compiled derivative
            _ab_packed = _fast_ab.month(forcing_dict, _month_f, _month_link_f, 1, dt)
            if month <= 1:
                state = _fast_ab.step(state, forcing_dict, _month_f, _month_link_f, dt)
                new_deriv, _ = _fast_ab.deriv(state, _ab_packed)
                new_deriv = np.nan_to_num(new_deriv, nan=0.0, posinf=1e6, neginf=-1e6)
                new_deriv = np.clip(new_deriv, -1e6, 1e6)
                if np.any(no_integrate_mask):
                    new_deriv[no_integrate_mask] = 0.0
            else:
                state, new_deriv = _ab_step_compiled(
                    _fast_ab, _ab_packed, state, derivs_history, params_dict, dt
                )
                if np.any(no_integrate_mask):
                    from pypath.core.ecosim_deriv import compute_biomeq

                    _, _eq = _fast_ab.deriv(month_start_state, _ab_packed, frozen=True)
                    for i in np.where(no_integrate_mask)[0]:
                        if i == 0 or i > params.NUM_LIVING + params.NUM_DEAD:
                            continue
                        state[i] = compute_biomeq(
                            float(_eq[5, i]),
                            float(_eq[6, i]),
                            float(month_start_state[i]),
                        )
                    new_deriv[no_integrate_mask] = 0.0
            derivs_history.insert(0, new_deriv)
            if len(derivs_history) > 1:
                derivs_history.pop()
        elif method.upper() == "AB":
            # Warmup: use RK4 for the first month to populate derivative history
            # before switching to Adams-Bashforth 2-step (matching Rpath)
            if month <= 1:
                # Use one RK4 step then switch to AB2
                old_state = state.copy()
                # Mark parent integration method so RK4 instrumentation reports 'AB' for warmup
                params_dict["_integration_parent_method"] = "AB"
                try:
                    state = integrate_rk4(
                        state, params_dict, forcing_dict, fishing_dict, dt
                    )
                finally:
                    # Clean up the temporary context flag
                    params_dict.pop("_integration_parent_method", None)
                try:
                    new_deriv = deriv_vector(
                        state, params_dict, forcing_dict, fishing_dict
                    )
                    # Sanitize derivative before storing to history to avoid
                    # carrying non-finite or extreme values into Adams-Bashforth
                    new_deriv = np.nan_to_num(
                        new_deriv, nan=0.0, posinf=1e6, neginf=-1e6
                    )
                    new_deriv = np.clip(new_deriv, -1e6, 1e6)
                    # Zero derivatives for NoIntegrate groups to align with Rpath
                    if np.any(no_integrate_mask):
                        new_deriv[no_integrate_mask] = 0.0
                    derivs_history.insert(0, new_deriv)
                    if len(derivs_history) > 1:
                        derivs_history.pop()
                except Exception as e:
                    logger.debug("derivative history update failed: %s", e)
            else:
                if params_dict.get("VERBOSE_INSTRUMENTATION"):
                    logger.debug(
                        "DEBUG-INTEGRATOR: about to call integrate_ab with params_dict['INSTRUMENT_GROUPS']=%r",
                        params_dict.get("INSTRUMENT_GROUPS", None),
                    )
                state, new_deriv = integrate_ab(
                    state, derivs_history, params_dict, forcing_dict, fishing_dict, dt
                )
                # Fast equilibrium for NoIntegrate groups (Rpath adams_run):
                # B = (1 - SORWT) * biomeq + SORWT * B_old with
                # biomeq = TotGain / (TotLoss / B_old), from the derivative
                # at the start of the month; SORWT = 0.5.
                if np.any(no_integrate_mask):
                    from pypath.core.ecosim_deriv import compute_biomeq

                    eq_rates: dict = {}
                    with _frozen_hden(params_dict):
                        deriv_vector(
                            month_start_state.copy(),
                            params_dict,
                            forcing_dict,
                            fishing_dict,
                            rates=eq_rates,
                        )
                    if "TotGain" in eq_rates:
                        for i in np.where(no_integrate_mask)[0]:
                            if i == 0 or i > params.NUM_LIVING + params.NUM_DEAD:
                                continue
                            state[i] = compute_biomeq(
                                float(eq_rates["TotGain"][i]),
                                float(eq_rates["TotLoss"][i]),
                                float(month_start_state[i]),
                            )
                    new_deriv[no_integrate_mask] = 0.0
                derivs_history.insert(0, new_deriv)
                if len(derivs_history) > 1:
                    derivs_history.pop()
        else:
            # Continuous path: solve_ivp over the month with the month's
            # forcing, effort, forced F, forced biomass, StanzaPredRatio and
            # Ftime held (with forcing_interpolation, the interpolated keys
            # vary in time instead); slot 0 and the gear slots keep their
            # values.
            assert rhs is not None  # built above for the continuous methods
            _y0 = np.array(state[1 : _n_bio_c + 1], dtype=float, copy=True)
            if _ft_groups is not None:
                # a start Ftime outside [lower, cap] is clipped (the RHS
                # clips on use, so the dynamics do not change)
                _y0 = np.concatenate(
                    [
                        _y0,
                        np.clip(
                            _ftime_current[_ft_groups],
                            _feeding.lower,
                            _feeding.cap[_ft_groups],
                        ),
                    ]
                )
            # a failure in this month names it (start rates and integration)
            _month_label = f"month {month} (year {year_idx + scenario.start_year})"
            _forcing_at = None if _interp is None else _interp.for_month(month - 1, dt)
            try:
                if _qs is None:
                    rhs.set_month(
                        forcing_dict,
                        state,
                        _forced_mask,
                        _forced_now,
                        forcing_at=_forcing_at,
                    )
                else:
                    # also fixes the quasi-steady solve's start and chord
                    # Jacobian for the month
                    _qs.set_month(
                        forcing_dict,
                        state,
                        _forced_mask,
                        _forced_now,
                        forcing_at=_forcing_at,
                        y0=_y0,
                    )
                if _qs is not None and month == 1:
                    # the separation of time scales, once: the slowest
                    # quasi-steady group against the reduced Jacobian
                    _lam = _qs.reduced_rate()
                    _sep = min(_qs_rates) / _lam if _lam > 0.0 else float("inf")
                    assert solver_info is not None
                    solver_info["qs_separation"] = _sep
                    if _sep < 10.0:
                        logger.warning(
                            "fast_groups='quasi-steady': poor separation "
                            "qs_separation = %.3g < 10 (slowest quasi-steady "
                            "group %.3g /yr, largest |Re lambda| of the reduced "
                            "Jacobian %.3g /yr): the reduction may be "
                            "inaccurate; raise qs_rate",
                            _sep,
                            min(_qs_rates),
                            _lam,
                        )
                _start_rates = (
                    rhs.rates(_y0) if month == 1 and out_hden is not None else None
                )
                # under "log" the Jacobian is differentiated in z, and under
                # quasi-steady groups in the slow states: the month's solver
                # function is built inside integrate_month
                _jac = (
                    None
                    if _jac_reuse is None
                    or _cont_opts["positivity"] == "log"
                    or _qs is not None
                    else _jac_reuse.for_month(rhs, step_floor=_fd_floor)
                )
                res = integrate_month(
                    rhs,
                    _y0,
                    dt,
                    _cont_method,
                    _rtol,
                    _atol_run,
                    on_failure=_on_failure,
                    label=_month_label,
                    n_bio=_n_bio_c,
                    jac=_jac,
                    positivity=_cont_opts["positivity"],
                    jac_factory=(None if _jac_reuse is None else _jac_reuse.for_month),
                    # the split rule only where a tent has a kink: with no
                    # key varying in time the forcing is held
                    forcing_interpolation=(
                        "constant" if _interp is None else _interp_kind
                    ),
                    quasi_steady=_qs,
                    step_floor=_fd_floor,
                )
            except RuntimeError as e:
                if _month_label in str(e):  # already names the month
                    raise
                raise RuntimeError(f"{_month_label}: {e}") from e
            if month == 1 and out_hden is not None:
                out_hden[0] = _start_rates["Hden"]  # Hden solved at the start
            state = state.copy()
            state[1 : _n_bio_c + 1] = res.y_end[:_n_bio_c]
            _y_mean_full = np.zeros(n_groups)
            _y_mean_full[1 : _n_bio_c + 1] = res.y_mean
            _ftime_range = None
            if _ft_groups is not None:
                _ft_end = res.y_end[_n_bio_c:]
                _ftime_range = [float(_ft_end.min()), float(_ft_end.max())]
            # the month's mass budget over the integrated biomass states,
            # before the stanza overwrite, forced re-apply and floor below
            # (None under quasi-steady groups)
            _budget, _pool_budget = month_budget(
                _y0,
                res,
                params.NUM_LIVING,
                _n_bio_c,
                forced=bool(np.any(_forced_mask)),
                quasi_steady=_qs is not None,
            )
            solver_info["months"].append(
                {
                    "month": month,
                    "nfev": res.nfev,
                    "njev": res.njev,
                    "nlu": res.nlu,
                    "jac_fresh": (
                        0 if _jac_reuse is None else _jac_reuse.stats["jac_fresh"]
                    ),
                    "jac_reused": (
                        0 if _jac_reuse is None else _jac_reuse.stats["jac_reused"]
                    ),
                    "steps": res.steps,
                    "last_step": res.last_step,
                    "status": res.status,
                    "t_reached": res.t_reached,
                    "degraded": bool(res.degraded),
                    "clips": int(rhs.stats["clips"]),
                    "hden_passes_max": int(rhs.stats["hden_passes_max"]),
                    "hden_residual_max": float(rhs.stats["hden_residual_max"]),
                    "kernel_check": float(rhs.stats["kernel_check"]),
                    "min_state": float(rhs.stats["min_state"]),
                    "ftime_range": _ftime_range,
                    "budget_residual": _budget,
                    "pool_budget_residual": _pool_budget,
                    "nutrient_floor": int(rhs.stats["nutrient_floor"]),
                    "negative_export": int(rhs.stats["negative_export"]),
                    "qs_inner_max": (
                        None if _qs is None else int(_qs.stats["qs_inner_max"])
                    ),
                    # solves that fell back to pseudo-transient continuation
                    # and to hybr, and the evaluations those stages took
                    "qs_fallbacks": (
                        None if _qs is None else dict(_qs.stats["qs_fallbacks"])
                    ),
                }
            )
            _kernel_check = solver_info["months"][-1]["kernel_check"]
            if _kernel_check > KERNEL_CHECK_TOL:  # NaN (no check) does not warn
                logger.warning(
                    "%s: kernel_check %.3g > %g: the vectorised consumption "
                    "pass disagrees with the link loop at the month's checked "
                    "evaluation, so this run's consumption is not the loop's",
                    _month_label,
                    _kernel_check,
                    KERNEL_CHECK_TOL,
                )
        if np.any(_forced_mask):
            state[_forced_mask] = np.asarray(_forced_now)[_forced_mask]

        # Replace invalid numeric values to prevent NaN/inf runaway and
        # ensure non-negative biomass (the continuous path's month end is
        # finite and floored at 1e-20 already)
        if not _continuous:
            state = np.where(np.isfinite(state), state, EPSILON)
            state = np.maximum(state, EPSILON)
        # EwE6's RiskRate divides by BBAvg, the biomass after the month's RK4
        # and before the stanza update overwrites the stanza groups.
        _b_integrated = state.copy() if _has_risk else None

        # Multi-stanza update (Rpath SplitUpdate + SplitSetPred). The rates
        # come from the derivative where Rpath takes them: after the month's
        # integration for RK4, at the start of the month for AB.
        if stanza_state is not None:
            if _continuous:
                # Continuous path: the month means of FoodGain and of
                # LossPropToB / B, the latter at unit biomass so survival is
                # exp(-integral of Z dt)
                split_update(
                    stanzas_obj,
                    stanza_state,
                    np.ones(len(state)),
                    res.food_gain_mean,
                    res.loss_rate_mean,
                    forced_recs=forcing_dict.get("ForcedRecs"),
                    month_index=month - 1,
                )
            elif _stanza_stages:
                # EwE6 rule: growth from the last stage's consumption,
                # survival from the first stage's loss over the stanza
                # groups' start-of-month biomass (cEcoSimModel.rk4).
                split_update(
                    stanzas_obj,
                    stanza_state,
                    month_start_state,
                    _stanza_stages["last"]["FoodGain"],
                    _stanza_stages["first"]["LossPropToB"],
                    forced_recs=forcing_dict.get("ForcedRecs"),
                    month_index=month - 1,
                )
            else:
                rate_state = month_start_state if method.upper() == "AB" else state
                stanza_rates: dict = {}
                if _fast_ab is not None:
                    _, _sr_rates = _fast_ab.deriv(rate_state, _ab_packed, frozen=True)
                    stanza_rates["FoodGain"] = _sr_rates[0]
                    stanza_rates["LossPropToB"] = _sr_rates[2]
                else:
                    with _frozen_hden(params_dict):
                        deriv_vector(
                            rate_state.copy(),
                            params_dict,
                            forcing_dict,
                            fishing_dict,
                            rates=stanza_rates,
                        )
                split_update(
                    stanzas_obj,
                    stanza_state,
                    rate_state,
                    stanza_rates["FoodGain"],
                    stanza_rates["LossPropToB"],
                    forced_recs=forcing_dict.get("ForcedRecs"),
                    month_index=month - 1,
                )
            # Overwrite the stanza groups' biomass with sum(N * W)
            split_set_pred(stanzas_obj, stanza_state, state)
            stanza_biomass[month, stanza_idx] = state[stanza_idx]

        # Check for crash (biomass < threshold)
        # Use more reasonable threshold to avoid false alarms from numerical noise
        if crash_year < 0:
            low_biomass_groups = np.where(
                state[1 : params.NUM_LIVING + 1] < crash_threshold
            )[0]
            if len(low_biomass_groups) > 0:
                # Record first crash year
                crash_year = year_idx + scenario.start_year
                # Track which groups crashed
                for grp_idx in low_biomass_groups:
                    crashed_groups.add(grp_idx + 1)  # +1 because we sliced from index 1

        # Store results
        out_biomass[month] = state
        if out_hden is not None:
            if _continuous:
                # Hden solved at the integrated month-end state res.y_end, as
                # it was before the stanza update above overwrote the stanza
                # groups
                try:
                    # under the forcing at the time reached
                    out_hden[month] = rhs.rates(res.y_end, res.t_reached)["Hden"]
                except RuntimeError as e:
                    if _month_label in str(e):  # already names the month
                        raise
                    raise RuntimeError(f"{_month_label}: {e}") from e
            else:
                out_hden[month] = params_dict["_hden"]

        # Compute consumption QQ matrix for this month to track Qlinks
        QQ_month = _compute_Q_matrix(params_dict, state, forcing_dict)
        # Ecotracer step (after biomass integration and Q computation)
        if _ecotracer_conc is not None:
            n_eco = len(_ecotracer_conc)
            eco_biomass = state[1 : n_eco + 1]
            eco_Q = QQ_month[1 : n_eco + 1, 1 : n_eco + 1]
            # detritus_fate=None for now (Phase 1 simplification)
            _ecotracer_conc = _ecotracer_step_fn(
                _ecotracer_conc,
                eco_biomass,
                eco_Q,
                ecotracer,
                dt=1.0 / 12,
                detritus_fate=None,
                n_living=params.NUM_LIVING,
            )
            _ecotracer_out[month] = _ecotracer_conc.copy()
        # Dynamic Ftime adjustment (Rpath ecosim.cpp; EwE6 rk4):
        # new_Ftime = L + (1-L)*Ft*((1-adj) + adj*QBopt/(FoodGain/B)), capped.
        # EwE rule: FoodGain per predator index of the start-of-month state
        # (CBlast; B for simple groups, B0 * StanzaPredRatio for stanza
        # groups); 'rpath' rule: FoodGain/B of the end-of-month state.
        # The continuous path integrates feeding time as states instead: the
        # month-end states are the next month's Ftime (after the Qlinks and
        # tracer above, which belong to this month's).
        if _continuous and _ft_groups is not None:
            _ftime_current[_ft_groups] = _ft_end
        if _has_ftime_adj and not _continuous:
            _ftime_lower = float(getattr(params, "ForagingTimeLowerLimit", 0.1))
            _ftime_max = getattr(params, "FtimeMax", None)
            _b_src = _ftime_index if _fg_ftime is not None else state
            # EwE updates integrated groups only (NoIntegrate = i or < 0,
            # cEcoSimModel.vb ~1761-1771): fast groups keep their Ftime.
            _skip_fast = _fg_ftime is not None
            _no_int = np.asarray(params.NoIntegrate)
            _end_rates = None  # 'rpath' rule RiskTime: month-end derivative
            for i in range(1, params.NUM_LIVING + 1):
                if _skip_fast and _no_int[i] != 0:
                    continue
                if _ftime_adj[i] > 0 and _b_src[i] > 0 and _ftime_qbopt[i] > 0:
                    if _fg_ftime is not None:
                        food_gain = float(_fg_ftime[i])
                    else:
                        food_gain = float(np.nansum(QQ_month[:, i]))
                    qopt = float(_ftime_qbopt[i])
                    if _has_risk and _risk_time[i] > 0:
                        # EwE rule: predation of the start-of-month Derivt
                        # (EatenOfAvg) over the biomass after RK4 (BBAvg);
                        # 'rpath' rule: both from the month-end state.
                        if _fg_ftime is not None:
                            eaten_of = float(_fg_rates["FoodLoss"][i])
                            b_risk = float(_b_integrated[i])
                        else:
                            if _end_rates is None:
                                _end_rates = {}
                                with _frozen_hden(params_dict):
                                    deriv_vector(
                                        state.copy(),
                                        params_dict,
                                        forcing_dict,
                                        fishing_dict,
                                        rates=_end_rates,
                                    )
                            eaten_of = float(_end_rates["FoodLoss"][i])
                            b_risk = float(state[i])
                        qopt = _risk_qopt(
                            qopt,
                            float(_risk_time[i]),
                            float(_risk0[i]),
                            eaten_of,
                            b_risk,
                            float(_risk_mo[i]),
                        )
                    _ftime_current[i] = _ftime_update_rpath(
                        _ftime_current[i],
                        _ftime_adj[i],
                        qopt,
                        food_gain,
                        _b_src[i],
                        lower=_ftime_lower,
                        cap=float(_ftime_max[i]) if _ftime_max is not None else 2.0,
                    )
        # Accumulate monthly Q (converted to monthly by dividing by 12)
        if annual_qlink is not None:
            for li in range(len(params.PreyFrom)):
                prey = params.PreyFrom[li]
                pred = params.PreyTo[li]
                if prey < QQ_month.shape[0] and pred < QQ_month.shape[1]:
                    annual_qlink[year_idx, li] += QQ_month[prey, pred] / 12.0

        # Catch for this month: EwE6's BB x FishTime (PopulateResults,
        # cEcoSimModel.vb:2222-2389), the month-end biomass times the F set
        # for the month, forced F and forced catch included. The gear links
        # carry the gears' share (effort and fleet mediation); a forced F has
        # no fleet breakdown, as EwE books it under fleet 0.
        # Rpath 1.2.0 (CATCH_LOG_MEAN): F times the log-mean biomass over
        # each RK4 sub-step, or for AB over the month from its start to its
        # end after the stanza update (rk4_run's cum_Catch, Adams_run)
        _n_bio = params.NUM_LIVING + params.NUM_DEAD
        if _catch_log_mean and not _continuous:
            _cb = (
                log_mean(month_start_state, state) / 12.0
                if method.upper() == "AB"
                else _catch_bio
            )
            for i in range(1, len(params.FishFrom)):
                grp = params.FishFrom[i]
                out_gear_catch[month, i] = _month_link_f[i] * _cb[grp]
            out_catch[month, 1 : _n_bio + 1] = (
                _month_f[1 : _n_bio + 1] * _cb[1 : _n_bio + 1]
            )
        else:
            for i in range(1, len(params.FishFrom)):
                grp = params.FishFrom[i]
                out_gear_catch[month, i] = _month_link_f[i] * state[grp] / 12.0
            out_catch[month, 1 : _n_bio + 1] = (
                _month_f[1 : _n_bio + 1] * state[1 : _n_bio + 1] / 12.0
            )
        if _continuous:
            # Continuous path: the month's F times the month-mean biomass, the
            # integral of F x B over the month; EwE's month-end booking above
            # is kept in out_Catch_month_end.
            out_catch_month_end[month] = out_catch[month]
            for i in range(1, len(params.FishFrom)):
                grp = params.FishFrom[i]
                out_gear_catch[month, i] = _month_link_f[i] * _y_mean_full[grp] / 12.0
            out_catch[month, 1 : _n_bio + 1] = (
                _month_f[1 : _n_bio + 1] * _y_mean_full[1 : _n_bio + 1] / 12.0
            )

        # Fleet dynamics step (after catch computation)
        if _fleet_capacity is not None:
            # Accumulate catch into cumulative tracker by fleet and group
            for i in range(1, len(params.FishFrom)):
                gear_group_idx = params.FishThrough[i]
                gear_0based = int(gear_group_idx) - 1
                if _run_gear_lookup:
                    gear_idx = _run_gear_lookup.get(gear_0based, 0)
                else:
                    gear_idx = int(gear_group_idx - params.NUM_LIVING - params.NUM_DEAD)
                fleet_0 = gear_idx - 1
                group_0 = int(params.FishFrom[i]) - 1
                if 0 <= fleet_0 < _n_fd_fleets and 0 <= group_0 < params.NUM_GROUPS:
                    _fleet_cumul_catch[fleet_0, group_0] += out_gear_catch[month, i]

            # Update capacity and effort
            _fleet_capacity, _fleet_effort = _fleet_step_fn(
                _fleet_capacity,
                out_gear_catch[month],
                _fleet_cumul_catch,
                fleet_dynamics,
                params.FishThrough,
                params.FishFrom,
                _run_gear_lookup,
                n_fleets=_n_fd_fleets,
            )

            # Write effort into ForcedEffort for next month
            if month < n_months:
                fishing_obj.ForcedEffort[month, 1 : _n_fd_fleets + 1] = _fleet_effort

            # Apply quota caps if TAC is set
            if fleet_dynamics.tac is not None:
                capped_q = _fleet_quota_fn(
                    params.FishQ,
                    _fleet_cumul_catch,
                    fleet_dynamics.tac,
                    params.FishThrough,
                    params.FishFrom,
                    _run_gear_lookup,
                )
                params.FishQ = capped_q
                fishing_dict["FishQ"] = capped_q  # propagate to derivative

            # Store results — compute revenue/cost/profit for output
            _revenue = np.zeros(_n_fd_fleets)
            for i in range(1, len(params.FishThrough)):
                gear_group_idx = params.FishThrough[i]
                gear_0based = int(gear_group_idx) - 1
                if _run_gear_lookup:
                    gear_idx = _run_gear_lookup.get(gear_0based, 0)
                else:
                    gear_idx = int(gear_group_idx - params.NUM_LIVING - params.NUM_DEAD)
                fleet_0 = gear_idx - 1
                if 0 <= fleet_0 < _n_fd_fleets and i < len(fleet_dynamics.price):
                    _revenue[fleet_0] += (
                        out_gear_catch[month, i] * fleet_dynamics.price[i]
                    )

            _cost = np.zeros(_n_fd_fleets)
            for g in range(_n_fd_fleets):
                _cost[g] = (
                    fleet_dynamics.fixed_cost[g] / 12.0
                    + (fleet_dynamics.variable_cost[g] + fleet_dynamics.sailing_cost[g])
                    * _fleet_capacity[g]
                )

            _fleet_out_effort[month] = _fleet_effort
            _fleet_out_revenue[month] = _revenue
            _fleet_out_cost[month] = _cost
            _fleet_out_profit[month] = _revenue - _cost

        # Last in the month, with every output for it stored: the caller may
        # stop the run here, between months (never inside one).
        if on_month is not None and on_month(month, n_months) is True:
            raise RunCancelled(f"run cancelled after month {month} of {n_months}")

    # Calculate annual values
    annual_biomass = np.zeros((n_years, n_groups))
    annual_catch = np.zeros((n_years, n_groups))
    annual_qb = np.zeros((n_years, n_groups))

    for yr in range(n_years):
        start_m = yr * 12 + 1
        end_m = (yr + 1) * 12 + 1
        annual_biomass[yr] = np.mean(out_biomass[start_m:end_m], axis=0)
        annual_catch[yr] = np.sum(out_catch[start_m:end_m], axis=0)

    # If Qlink accumulation was tracked, ensure shape is set
    if "annual_qlink" not in locals():
        annual_qlink = np.zeros((n_years, len(params.PreyFrom)))

    # If stanza_biomass was not computed (no stanzas), set to None
    if stanza_biomass is None:
        stanza_biomass_out = None
    else:
        stanza_biomass_out = stanza_biomass

    # Ecotracer annual averaging
    _ecotracer_result = None
    if _ecotracer_out is not None:
        from pypath.core.ecotracer import EcotracerResult

        n_eco_groups = _ecotracer_out.shape[1]
        annual_conc = np.zeros((n_years, n_eco_groups))
        for yr in range(n_years):
            start_m = yr * 12 + 1
            end_m = (yr + 1) * 12 + 1
            annual_conc[yr] = np.mean(_ecotracer_out[start_m:end_m], axis=0)

        group_names = [params.spname[i] for i in range(1, n_eco_groups + 1)]
        _ecotracer_result = EcotracerResult(
            out_Conc=_ecotracer_out,
            annual_Conc=annual_conc,
            group_names=group_names,
        )

    # Fleet dynamics annual averaging
    _fleet_result = None
    if _fleet_out_effort is not None:
        from pypath.core.fleet_dynamics import FleetDynamicsResult

        annual_effort = np.zeros((n_years, _n_fd_fleets))
        annual_profit = np.zeros((n_years, _n_fd_fleets))
        for yr in range(n_years):
            start_m = yr * 12 + 1
            end_m = (yr + 1) * 12 + 1
            annual_effort[yr] = np.mean(_fleet_out_effort[start_m:end_m], axis=0)
            annual_profit[yr] = np.sum(_fleet_out_profit[start_m:end_m], axis=0)

        fleet_names = []
        if hasattr(params, "fleet_idx") and params.fleet_idx is not None:
            for fi in params.fleet_idx:
                idx_1based = int(fi) + 1
                if idx_1based < len(params.spname):
                    fleet_names.append(params.spname[idx_1based])
                else:
                    fleet_names.append(f"Fleet{idx_1based}")
        else:
            fleet_names = [f"Fleet{i + 1}" for i in range(_n_fd_fleets)]

        _fleet_result = FleetDynamicsResult(
            out_Effort=_fleet_out_effort,
            out_Revenue=_fleet_out_revenue,
            out_Cost=_fleet_out_cost,
            out_Profit=_fleet_out_profit,
            annual_Effort=annual_effort,
            annual_Profit=annual_profit,
            fleet_names=fleet_names,
        )

    # Create end state
    end_state = RsimState(
        Biomass=state.copy(),
        N=np.zeros(n_groups),
        # the feeding time as updated month by month, not the start value
        Ftime=np.asarray(_ftime_current, dtype=float).copy(),
    )

    # Build predator-prey identifiers for output
    pred_names = np.array(
        [params.spname[params.PreyTo[i]] for i in range(len(params.PreyTo))]
    )
    prey_names = np.array(
        [params.spname[params.PreyFrom[i]] for i in range(len(params.PreyFrom))]
    )

    # Gear catch identifiers
    gear_catch_sp = np.array(
        [params.spname[params.FishFrom[i]] for i in range(len(params.FishFrom))]
    )
    gear_catch_gear = np.array(
        [
            (
                params.spname[params.FishThrough[i]]
                if params.FishThrough[i] < len(params.spname)
                else f"Gear{params.FishThrough[i]}"
            )
            for i in range(len(params.FishThrough))
        ]
    )
    gear_catch_disp = np.where(params.FishTo == 0, "Landings", "Discards")

    # Return full monthly time series including the initial snapshot (index 0).
    # Tests and downstream code expect the initial state to be included as row 0.

    if solver_info is not None:
        assert rhs is not None
        # every right-hand side evaluation of the run: solver, start checks,
        # quadrature and output rates
        solver_info["rhs_evals"] = int(rhs.evals)
    return RsimOutput(
        notes=list(_run_notes),
        out_Biomass=out_biomass,
        out_Catch=out_catch,
        out_Gear_Catch=out_gear_catch,
        annual_Biomass=annual_biomass,
        annual_Catch=annual_catch,
        annual_QB=annual_qb,
        annual_Qlink=annual_qlink,
        stanza_biomass=stanza_biomass_out,
        out_FishMort=out_fishmort,
        out_Hden=out_hden,
        end_state=end_state,
        crash_year=crash_year,
        crashed_groups=crashed_groups,
        pred=pred_names,
        prey=prey_names,
        Gear_Catch_sp=gear_catch_sp,
        Gear_Catch_gear=gear_catch_gear,
        Gear_Catch_disp=gear_catch_disp,
        start_state=copy.deepcopy(scenario.start_state),
        params={
            "NUM_GROUPS": params.NUM_GROUPS,
            "NUM_LIVING": params.NUM_LIVING,
            "years": n_years,
            # M0 as used by this run, including its small-residual adjustments
            "M0": np.asarray(params_dict["M0"]).copy(),
        },
        ecotracer=_ecotracer_result,
        fleet_dynamics=_fleet_result,
        solver_info=solver_info,
        out_Catch_month_end=out_catch_month_end,
    )

ODE Derivatives

The consumption kernel and derivative vector used by the Ecosim ODE solver.

Key functions:

  • deriv_vector() — compute dB/dt for all groups at a given state
  • _compute_consumption_python() — foraging arena consumption matrix (Rpath-compatible)
  • compute_biomeq() — fast equilibrium for NoIntegrate groups
  • integrate_rk4() — single RK4 step
  • integrate_ab() — single AB2 step with Rpath-style biomass bounds

pypath.core.ecosim_deriv

Ecosim derivative calculation and integration routines.

This module contains the core numerical routines for Ecosim simulation: - deriv_vector: Calculate derivatives for all state variables - RK4 and Adams-Bashforth integration methods - Prey switching and mediation functions - Primary production forcing

These are ported from the C++ ecosim.cpp file in Rpath.

The sparse consumption loop runs as a numba kernel (_compute_consumption_sparse_numba, bit-identical to the Python loop _compute_consumption_sparse_python) when numba is installed. Setting the environment variable PYPATH_NUMBA_CONSUMPTION=0 (or false, no, off) before this module is imported keeps the Python loop.

KernelInputs dataclass

What the consumption loop reads in one deriv_vector call.

Handed to params["_hden_solver"] on the continuous path (_hden_exact) so that handling time can be solved on the kernel alone. predYY is unscaled: the loop's predator term is predYY * hden0 / Hden. VV and QQbase are after the prey-switching, arena and search remaps; link_prey / link_pred are the links the loop visits, in its order; eat_eff is the loop's (producers at 1) and index the predator abundance of the Hden update. The pooling arrays, HandleSwitch, med_multipliers and eat_eff are None when the loop gets None. BB is a copy; the other arrays may be shared with the call, so read them only.

Source code in pypath/core/ecosim_deriv.py
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
@dataclass(frozen=True)
class KernelInputs:
    """What the consumption loop reads in one ``deriv_vector`` call.

    Handed to ``params["_hden_solver"]`` on the continuous path
    (``_hden_exact``) so that handling time can be solved on the kernel
    alone. ``predYY`` is unscaled: the loop's predator term is
    ``predYY * hden0 / Hden``. ``VV`` and ``QQbase`` are after the
    prey-switching, arena and search remaps; ``link_prey`` / ``link_pred``
    are the links the loop visits, in its order; ``eat_eff`` is the loop's
    (producers at 1) and ``index`` the predator abundance of the Hden update.
    The pooling arrays, ``HandleSwitch``, ``med_multipliers`` and ``eat_eff``
    are None when the loop gets None. ``BB`` is a copy; the other arrays may
    be shared with the call, so read them only.
    """

    BB: np.ndarray
    preyYY: np.ndarray
    predYY: np.ndarray
    hden0: np.ndarray
    VV: np.ndarray
    DD: np.ndarray
    QQbase: np.ndarray
    link_prey: np.ndarray
    link_pred: np.ndarray
    ScrambleSelf: Optional[np.ndarray]
    HandleSelf: Optional[np.ndarray]
    PredPredWeight: Optional[np.ndarray]
    PreyPreyWeight: Optional[np.ndarray]
    HandleSwitch: Optional[np.ndarray]
    COUPLED: float
    med_multipliers: Optional[np.ndarray]
    eat_eff: Optional[np.ndarray]
    index: np.ndarray
    cmco_qb: np.ndarray

HdenKernel

The link loop's consumption as a vector function of Hden.

Only the predator term (PDY, the VV denominator and the predator suite) depends on Hden. The prey term, the DD factor, the base flow and the mediation multiplier are computed once here, with the loop's skips (B <= 0 at either end, QQbase <= 0); :meth:q applies its clamp at 0.

Source code in pypath/core/ecosim_deriv.py
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
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
class HdenKernel:
    """The link loop's consumption as a vector function of Hden.

    Only the predator term (``PDY``, the VV denominator and the predator
    suite) depends on Hden. The prey term, the DD factor, the base flow and
    the mediation multiplier are computed once here, with the loop's skips
    (B <= 0 at either end, ``QQbase <= 0``); :meth:`q` applies its clamp at 0.
    """

    def __init__(self, inputs: KernelInputs):
        self.inputs = inputs
        prey = np.asarray(inputs.link_prey, dtype=np.int64)
        pred = np.asarray(inputs.link_pred, dtype=np.int64)
        self.n = len(inputs.BB)
        bb = inputs.BB
        qbase = np.asarray(inputs.QQbase, dtype=float)[prey, pred]
        live = ~((bb[prey] <= 0.0) | (bb[pred] <= 0.0) | (qbase <= 0.0))
        # the consuming links; prey-0 links enter the suites, not the sum
        s = live & (prey >= 1)
        pyy = inputs.preyYY[prey]
        hs_exp = np.zeros(len(prey))
        if inputs.HandleSwitch is not None:
            hs_exp = np.asarray(inputs.HandleSwitch, dtype=float)[prey, pred]
            hs_exp = hs_exp * inputs.COUPLED
        switch = hs_exp > 0.0
        pyy_term = pyy.copy()
        pyy_term[switch] = np.maximum(pyy[switch], 1e-10) ** hs_exp[switch]
        pooling = (
            inputs.ScrambleSelf is not None
            and inputs.HandleSelf is not None
            and inputs.PredPredWeight is not None
            and inputs.PreyPreyWeight is not None
        )
        if pooling:
            handle_suite = np.bincount(
                pred,
                weights=pyy * np.asarray(inputs.PreyPreyWeight)[prey, pred],
                minlength=self.n,
            )
            hself = np.asarray(inputs.HandleSelf, dtype=float)[prey, pred]
            dd_prey_eff = (1.0 - hself) * pyy + hself * handle_suite[pred]
        else:
            dd_prey_eff = pyy
        dd_denom = np.maximum(dd_prey_eff, 1e-10)
        dd_denom[switch] = dd_denom[switch] ** hs_exp[switch]
        dd = np.asarray(inputs.DD, dtype=float)[prey, pred]
        dd_term = dd / np.maximum(dd - 1.0 + dd_denom, 1e-10)
        base = qbase * pyy_term * dd_term
        if inputs.med_multipliers is not None:
            base = base * np.asarray(inputs.med_multipliers)[prey, pred]
        self.prey, self.pred = prey[s], pred[s]
        self.base = base[s]
        self.vv = np.asarray(inputs.VV, dtype=float)[prey, pred][s]
        # EatEff divides the predator term of the VV denominator and suite
        eat = None if inputs.eat_eff is None else np.asarray(inputs.eat_eff, float)
        self.eat = None if eat is None else eat[self.pred]
        # the predator suite: every visited link's (prey, pred, weight,
        # EatEff), and the consuming links' ScrambleSelf
        self.suite: Optional[tuple] = None
        if pooling:
            self.suite = (
                prey,
                pred,
                np.asarray(inputs.PredPredWeight, dtype=float)[prey, pred],
                None if eat is None else eat[pred],
                np.asarray(inputs.ScrambleSelf, dtype=float)[prey, pred][s],
            )

    def coupled(self) -> bool:
        """Whether one predator's Hden reaches another's consumption: a
        consuming link with ``ScrambleSelf > 0`` shares its prey's suite."""
        return self.suite is not None and bool(np.any(self.suite[4] > 0.0))

    def q(self, hden: np.ndarray) -> np.ndarray:
        """``sum over prey >= 1 of Q[prey, j]`` at ``hden``, per group ``j``,
        as the loop's ``HdenConsumption``."""
        inputs = self.inputs
        pred_yy = inputs.predYY * (inputs.hden0 / hden)
        pdy = pred_yy[self.pred]
        vv_pred_eff = pdy if self.eat is None else pdy / self.eat
        if self.suite is not None:
            s_prey, s_pred, s_weight, s_eat, sself = self.suite
            s_pdy = pred_yy[s_pred] if s_eat is None else pred_yy[s_pred] / s_eat
            pred_suite = np.bincount(s_prey, weights=s_pdy * s_weight, minlength=self.n)
            vv_pred_eff = (1.0 - sself) * vv_pred_eff + sself * pred_suite[self.prey]
        vv = self.vv
        vv_term = vv / np.maximum(vv - 1.0 + np.maximum(vv_pred_eff, 1e-10), 1e-10)
        flow = self.base * pdy * vv_term
        flow = np.where(flow > 0.0, flow, 0.0)
        return np.bincount(self.pred, weights=flow, minlength=self.n)

    def q_and_dq(self, hden: np.ndarray) -> tuple[np.ndarray, np.ndarray]:
        """``(q, dq)`` at ``hden``: ``q`` as :meth:`q`, and ``dq[j]`` the
        derivative of ``q[j]`` with respect to ``hden[j]``.

        With ``pdy = predYY * hden0 / H_j``, ``eff`` the predator term of the
        VV denominator and ``den = max(vv - 1 + max(eff, 1e-10), 1e-10)``:
        ``dq[j] = sum over j's links of base * (vv_term - pdy * vv / den**2
        * d eff / d pdy) * (-pdy / H_j)``. A clamped ``eff`` or ``den``
        contributes no ``d eff`` term, and a link whose flow is clamped at 0
        contributes nothing. Each ``q[j]`` depends on ``H_j`` alone only when
        no consuming link has ``ScrambleSelf > 0``: raises ``ValueError`` when
        :meth:`coupled`.
        """
        if getattr(self, "_coupled", None) is None:
            self._coupled = self.coupled()  # the inputs are fixed: once
        if self._coupled:
            raise ValueError(
                "handling time: q_and_dq needs independent predators; the map "
                "is coupled (a consuming link has ScrambleSelf > 0)"
            )
        inputs = self.inputs
        pred_yy = inputs.predYY * (inputs.hden0 / hden)
        pdy = pred_yy[self.pred]
        vv_pred_eff = pdy if self.eat is None else pdy / self.eat
        deff = 1.0 if self.eat is None else 1.0 / self.eat
        if self.suite is not None:
            s_prey, s_pred, s_weight, s_eat, sself = self.suite
            s_pdy = pred_yy[s_pred] if s_eat is None else pred_yy[s_pred] / s_eat
            pred_suite = np.bincount(s_prey, weights=s_pdy * s_weight, minlength=self.n)
            vv_pred_eff = (1.0 - sself) * vv_pred_eff + sself * pred_suite[self.prey]
            deff = (1.0 - sself) * deff  # no ScrambleSelf: no suite term
        vv = self.vv
        eff = np.maximum(vv_pred_eff, 1e-10)
        den = np.maximum(vv - 1.0 + eff, 1e-10)
        vv_term = vv / den
        flow = self.base * pdy * vv_term
        keep = flow > 0.0
        flow = np.where(keep, flow, 0.0)
        q = np.bincount(self.pred, weights=flow, minlength=self.n)
        free = (vv_pred_eff > 1e-10) & (vv - 1.0 + eff > 1e-10)
        dden = np.where(free, pdy * vv / den**2 * deff, 0.0)
        dflow = self.base * (vv_term - dden) * (-pdy / hden[self.pred])
        dq = np.bincount(
            self.pred, weights=np.where(keep, dflow, 0.0), minlength=self.n
        )
        return q, dq
coupled
coupled() -> bool

Whether one predator's Hden reaches another's consumption: a consuming link with ScrambleSelf > 0 shares its prey's suite.

Source code in pypath/core/ecosim_deriv.py
824
825
826
827
def coupled(self) -> bool:
    """Whether one predator's Hden reaches another's consumption: a
    consuming link with ``ScrambleSelf > 0`` shares its prey's suite."""
    return self.suite is not None and bool(np.any(self.suite[4] > 0.0))
q
q(hden: ndarray) -> np.ndarray

sum over prey >= 1 of Q[prey, j] at hden, per group j, as the loop's HdenConsumption.

Source code in pypath/core/ecosim_deriv.py
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
def q(self, hden: np.ndarray) -> np.ndarray:
    """``sum over prey >= 1 of Q[prey, j]`` at ``hden``, per group ``j``,
    as the loop's ``HdenConsumption``."""
    inputs = self.inputs
    pred_yy = inputs.predYY * (inputs.hden0 / hden)
    pdy = pred_yy[self.pred]
    vv_pred_eff = pdy if self.eat is None else pdy / self.eat
    if self.suite is not None:
        s_prey, s_pred, s_weight, s_eat, sself = self.suite
        s_pdy = pred_yy[s_pred] if s_eat is None else pred_yy[s_pred] / s_eat
        pred_suite = np.bincount(s_prey, weights=s_pdy * s_weight, minlength=self.n)
        vv_pred_eff = (1.0 - sself) * vv_pred_eff + sself * pred_suite[self.prey]
    vv = self.vv
    vv_term = vv / np.maximum(vv - 1.0 + np.maximum(vv_pred_eff, 1e-10), 1e-10)
    flow = self.base * pdy * vv_term
    flow = np.where(flow > 0.0, flow, 0.0)
    return np.bincount(self.pred, weights=flow, minlength=self.n)
q_and_dq
q_and_dq(hden: ndarray) -> tuple[np.ndarray, np.ndarray]

(q, dq) at hden: q as :meth:q, and dq[j] the derivative of q[j] with respect to hden[j].

With pdy = predYY * hden0 / H_j, eff the predator term of the VV denominator and den = max(vv - 1 + max(eff, 1e-10), 1e-10): dq[j] = sum over j's links of base * (vv_term - pdy * vv / den**2 * d eff / d pdy) * (-pdy / H_j). A clamped eff or den contributes no d eff term, and a link whose flow is clamped at 0 contributes nothing. Each q[j] depends on H_j alone only when no consuming link has ScrambleSelf > 0: raises ValueError when :meth:coupled.

Source code in pypath/core/ecosim_deriv.py
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
def q_and_dq(self, hden: np.ndarray) -> tuple[np.ndarray, np.ndarray]:
    """``(q, dq)`` at ``hden``: ``q`` as :meth:`q`, and ``dq[j]`` the
    derivative of ``q[j]`` with respect to ``hden[j]``.

    With ``pdy = predYY * hden0 / H_j``, ``eff`` the predator term of the
    VV denominator and ``den = max(vv - 1 + max(eff, 1e-10), 1e-10)``:
    ``dq[j] = sum over j's links of base * (vv_term - pdy * vv / den**2
    * d eff / d pdy) * (-pdy / H_j)``. A clamped ``eff`` or ``den``
    contributes no ``d eff`` term, and a link whose flow is clamped at 0
    contributes nothing. Each ``q[j]`` depends on ``H_j`` alone only when
    no consuming link has ``ScrambleSelf > 0``: raises ``ValueError`` when
    :meth:`coupled`.
    """
    if getattr(self, "_coupled", None) is None:
        self._coupled = self.coupled()  # the inputs are fixed: once
    if self._coupled:
        raise ValueError(
            "handling time: q_and_dq needs independent predators; the map "
            "is coupled (a consuming link has ScrambleSelf > 0)"
        )
    inputs = self.inputs
    pred_yy = inputs.predYY * (inputs.hden0 / hden)
    pdy = pred_yy[self.pred]
    vv_pred_eff = pdy if self.eat is None else pdy / self.eat
    deff = 1.0 if self.eat is None else 1.0 / self.eat
    if self.suite is not None:
        s_prey, s_pred, s_weight, s_eat, sself = self.suite
        s_pdy = pred_yy[s_pred] if s_eat is None else pred_yy[s_pred] / s_eat
        pred_suite = np.bincount(s_prey, weights=s_pdy * s_weight, minlength=self.n)
        vv_pred_eff = (1.0 - sself) * vv_pred_eff + sself * pred_suite[self.prey]
        deff = (1.0 - sself) * deff  # no ScrambleSelf: no suite term
    vv = self.vv
    eff = np.maximum(vv_pred_eff, 1e-10)
    den = np.maximum(vv - 1.0 + eff, 1e-10)
    vv_term = vv / den
    flow = self.base * pdy * vv_term
    keep = flow > 0.0
    flow = np.where(keep, flow, 0.0)
    q = np.bincount(self.pred, weights=flow, minlength=self.n)
    free = (vv_pred_eff > 1e-10) & (vv - 1.0 + eff > 1e-10)
    dden = np.where(free, pdy * vv / den**2 * deff, 0.0)
    dflow = self.base * (vv_term - dden) * (-pdy / hden[self.pred])
    dq = np.bincount(
        self.pred, weights=np.where(keep, dflow, 0.0), minlength=self.n
    )
    return q, dq

SimState dataclass

Current state of the simulation.

Source code in pypath/core/ecosim_deriv.py
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
@dataclass
class SimState:
    """Current state of the simulation."""

    # Biomass and related state variables (indexed 0 to NUM_GROUPS)
    Biomass: np.ndarray  # Current biomass
    Ftime: np.ndarray  # Fishing time forcing

    # Consumption tracking
    QQ: np.ndarray  # Consumption Q[prey, pred] matrix

    # Forcing arrays
    force_bybio: np.ndarray  # Biomass forcing
    force_byprey: np.ndarray  # Prey-specific forcing

prey_switch_weights

prey_switch_weights(VV, QQbase, Bbase) -> np.ndarray

EwE6 base search rates A[prey, pred] up to a per-predator factor.

EwE6 MakeAMatrixCell: with the vulnerability exchange rate v = VV * Q0 / B0_prey, A = 2 Dzero Q0 v / max(P0 (B0_prey v - Q0), 1e-20) = 2 Dzero VV Q0^2 / B0_prey / max(P0 Q0 (VV - 1), 1e-20). The predator's 2 Dzero cancels in the switching factor and is left out. Row 0 (imports) gets no weight.

Source code in pypath/core/ecosim_deriv.py
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
def prey_switch_weights(VV, QQbase, Bbase) -> np.ndarray:
    """EwE6 base search rates ``A[prey, pred]`` up to a per-predator factor.

    EwE6 MakeAMatrixCell: with the vulnerability exchange rate
    ``v = VV * Q0 / B0_prey``,
    ``A = 2 Dzero Q0 v / max(P0 (B0_prey v - Q0), 1e-20)``
    ``  = 2 Dzero VV Q0^2 / B0_prey / max(P0 Q0 (VV - 1), 1e-20)``.
    The predator's ``2 Dzero`` cancels in the switching factor and is left
    out. Row 0 (imports) gets no weight.
    """
    VV = np.asarray(VV, dtype=float)
    Q0 = np.asarray(QQbase, dtype=float)
    n = Q0.shape[0]
    b0 = np.zeros(n)
    b = np.asarray(Bbase, dtype=float)[:n]
    b0[: len(b)] = b
    b_prey = b0[:, None]
    p0 = b0[None, :]
    ok = (Q0 > 0) & (b_prey > 0)
    ok[0, :] = False
    denv = np.maximum(p0 * Q0 * (VV - 1.0), 1e-20)
    with np.errstate(divide="ignore", invalid="ignore", over="ignore"):
        weights = np.where(ok, VV * Q0 * Q0 / np.where(ok, b_prey, 1.0) / denv, 0.0)
    return np.nan_to_num(weights, nan=0.0, posinf=1e300)

ewe_prey_multiplier_arena

ewe_prey_multiplier_arena(VV, QQbase, f)

EwE6 prey Ftime / vulnerability forcing in the arena (audit D1).

EwE scales only the flow into the vulnerable pool, Veff = VulArena * f (cEcoSimModel.vb:2886-2905). For a private arena that is Rpath's form with the prey term B/B0 (f left out) and, per link of a prey with f != 1, VV' = 1 + (VV - 1)(1 + f) / 2 and QQbase' = QQbase * VV * f / VV': Q = Q0 x f K y / ((K - 1)(1 + f)/2 + y) instead of Q0 (f x) K y / (K - 1 + y).

VV and QQbase are (prey, predator) matrices; f is per prey, or a (prey, predator) matrix when a link carries its own vulnerability forcing. Row 0 (a producer's link from group 0) is not remapped. Returns new arrays; the inputs are not modified.

Source code in pypath/core/ecosim_deriv.py
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
def ewe_prey_multiplier_arena(VV, QQbase, f):
    """EwE6 prey Ftime / vulnerability forcing in the arena (audit D1).

    EwE scales only the flow into the vulnerable pool, Veff = VulArena * f
    (cEcoSimModel.vb:2886-2905). For a private arena that is Rpath's form with
    the prey term B/B0 (f left out) and, per link of a prey with f != 1,
    VV' = 1 + (VV - 1)(1 + f) / 2 and QQbase' = QQbase * VV * f / VV':
    Q = Q0 x f K y / ((K - 1)(1 + f)/2 + y) instead of Q0 (f x) K y / (K - 1 + y).

    ``VV`` and ``QQbase`` are (prey, predator) matrices; ``f`` is per prey, or a
    (prey, predator) matrix when a link carries its own vulnerability forcing.
    Row 0 (a producer's link from group 0) is not remapped. Returns new arrays;
    the inputs are not modified.
    """
    f = np.asarray(f, dtype=float)
    if f.ndim == 2:
        mask = f != 1.0
        mask[0, :] = False
        if not mask.any():
            return VV, QQbase
        VV = np.array(VV, dtype=float)
        QQbase = np.array(QQbase, dtype=float)
        vv_new = 1.0 + (VV[mask] - 1.0) * (1.0 + f[mask]) / 2.0
        QQbase[mask] = np.where(
            vv_new > 0,
            QQbase[mask] * VV[mask] * f[mask] / np.where(vv_new > 0, vv_new, 1.0),
            0.0,
        )
        VV[mask] = vv_new
        return VV, QQbase
    rows = np.flatnonzero(f != 1.0)
    rows = rows[(rows > 0) & (rows < VV.shape[0])]
    if rows.size == 0:
        return VV, QQbase
    VV = np.array(VV, dtype=float)
    QQbase = np.array(QQbase, dtype=float)
    fr = f[rows][:, None]
    vv_old = VV[rows, :]
    vv_new = 1.0 + (vv_old - 1.0) * (1.0 + fr) / 2.0
    QQbase[rows, :] = np.where(
        vv_new > 0,
        QQbase[rows, :] * vv_old * fr / np.where(vv_new > 0, vv_new, 1.0),
        0.0,
    )
    VV[rows, :] = vv_new
    return VV, QQbase
ewe_link_search_arena(VV, QQbase, s)

EwE6 search-rate forcing on single links (ApplyAVmodifiers per link).

A multiplier s on a link's search rate replaces the predator term y by s*y in that link's arena: Q = Q0 x K s y / (K - 1 + s y). That is Rpath's form with VV' = 1 + (VV - 1) / s and QQbase' = QQbase * VV / VV'. It composes with ewe_prey_multiplier_arena (apply that one first). s is a (prey, predator) matrix; s = 0 stops the link. Row 0 is not remapped. Returns new arrays; the inputs are not modified.

Source code in pypath/core/ecosim_deriv.py
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
def ewe_link_search_arena(VV, QQbase, s):
    """EwE6 search-rate forcing on single links (ApplyAVmodifiers per link).

    A multiplier s on a link's search rate replaces the predator term y by
    s*y in that link's arena: Q = Q0 x K s y / (K - 1 + s y). That is Rpath's
    form with VV' = 1 + (VV - 1) / s and QQbase' = QQbase * VV / VV'. It
    composes with ewe_prey_multiplier_arena (apply that one first). ``s`` is a
    (prey, predator) matrix; s = 0 stops the link. Row 0 is not remapped.
    Returns new arrays; the inputs are not modified.
    """
    s = np.asarray(s, dtype=float)
    mask = s != 1.0
    mask[0, :] = False
    if not mask.any():
        return VV, QQbase
    VV = np.array(VV, dtype=float)
    QQbase = np.array(QQbase, dtype=float)
    pos = mask & (s > 0)
    vv_new = 1.0 + (VV[pos] - 1.0) / s[pos]
    QQbase[pos] = QQbase[pos] * VV[pos] / vv_new
    VV[pos] = vv_new
    QQbase[mask & (s <= 0)] = 0.0
    return VV, QQbase

apply_prey_switching

apply_prey_switching(BB, VV, QQbase, switch_power, Bbase, weights=None)

EwE6 prey switching as an effective vulnerability and base flow.

EwE6 (SetRelaSwitch) multiplies the search rate of link (i, j) by r = [A_ij B_i^s / sum_k A_kj B_k^s] / [A_ij B0_i^s / sum_k A_kj B0_k^s] with s the predator's SwitchPower. In the closed-form kernel Q = Q0 PYY PDY VV / (VV - 1 + PDY) a search-rate factor r is Q = Q0 PYY (r PDY) VV / (VV - 1 + r PDY), i.e. the kernel with VV' = 1 + (VV - 1) / r and Q0' = Q0 VV / VV'. Returns copies of VV and QQbase with those values on the switching predators' links; the inputs are left untouched. Bbase is the base biomass EwE6 normalises by (Ecospace: the map-wide Ecosim base).

Source code in pypath/core/ecosim_deriv.py
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
def apply_prey_switching(BB, VV, QQbase, switch_power, Bbase, weights=None):
    """EwE6 prey switching as an effective vulnerability and base flow.

    EwE6 (SetRelaSwitch) multiplies the search rate of link (i, j) by
    ``r = [A_ij B_i^s / sum_k A_kj B_k^s] / [A_ij B0_i^s / sum_k A_kj B0_k^s]``
    with ``s`` the predator's SwitchPower. In the closed-form kernel
    ``Q = Q0 PYY PDY VV / (VV - 1 + PDY)`` a search-rate factor ``r`` is
    ``Q = Q0 PYY (r PDY) VV / (VV - 1 + r PDY)``, i.e. the kernel with
    ``VV' = 1 + (VV - 1) / r`` and ``Q0' = Q0 VV / VV'``. Returns copies of
    VV and QQbase with those values on the switching predators' links;
    the inputs are left untouched. ``Bbase`` is the base biomass EwE6
    normalises by (Ecospace: the map-wide Ecosim base).
    """
    Q0 = np.asarray(QQbase, dtype=float)
    n = Q0.shape[0]
    sp = np.asarray(switch_power, dtype=float)
    s_all = np.full(n, float(sp)) if sp.ndim == 0 else np.zeros(n)
    if sp.ndim:
        m = min(n, len(sp))
        s_all[:m] = sp[:m]
    preds = np.nonzero(s_all > 0)[0]
    if preds.size == 0:
        return VV, QQbase
    if weights is None:
        weights = prey_switch_weights(VV, Q0, Bbase)
    b = np.zeros(n)
    bb = np.asarray(BB, dtype=float)[:n]
    b[: len(bb)] = np.maximum(bb, 0.0)
    b0 = np.zeros(n)
    bref = np.asarray(Bbase, dtype=float)[:n]
    b0[: len(bref)] = bref
    vv_out = np.array(VV, dtype=float, copy=True)
    q_out = np.array(Q0, dtype=float, copy=True)
    for j in preds:
        a = weights[:, j]
        rows = np.nonzero(a > 0)[0]
        if rows.size == 0:
            continue
        s = s_all[j]
        now = a[rows] * b[rows] ** s
        base = a[rows] * b0[rows] ** s
        share_now = now / (now.sum() + 1e-20)
        share_base = base / (base.sum() + 1e-20)
        r = np.where(share_base > 0, share_now / np.maximum(share_base, 1e-300), 1.0)
        r = np.maximum(r, 1e-20)
        vv = vv_out[rows, j]
        vv_new = 1.0 + (vv - 1.0) / r
        q_out[rows, j] = q_out[rows, j] * vv / vv_new
        vv_out[rows, j] = vv_new
    return vv_out, q_out

prey_switching

prey_switching(BB: ndarray, Bbase: ndarray, pred: int, ActiveLink: ndarray, switch_power: float = 2.0) -> np.ndarray

Calculate prey switching factors.

Not used by the simulation, and not EwE6's formula: Ecosim runs use :func:apply_prey_switching (EwE6 SetRelaSwitch) with each predator's SwitchPower.

Prey switching occurs when predators preferentially consume more abundant prey, stabilizing the system. Uses a power function of relative abundance.

Parameters:

Name Type Description Default
BB ndarray

Current biomass array

required
Bbase ndarray

Baseline biomass array

required
pred int

Predator index

required
ActiveLink ndarray

Active link matrix [prey, pred]

required
switch_power float

Prey switching power (default 2.0, range 0-2) - 0: No switching - 1: Linear switching - 2: Strong switching (Murdoch switching)

2.0

Returns:

Type Description
ndarray

Switching factors for each prey (indexed by prey)

Source code in pypath/core/ecosim_deriv.py
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
def prey_switching(
    BB: np.ndarray,
    Bbase: np.ndarray,
    pred: int,
    ActiveLink: np.ndarray,
    switch_power: float = 2.0,
) -> np.ndarray:
    """
    Calculate prey switching factors.

    Not used by the simulation, and not EwE6's formula: Ecosim runs use
    :func:`apply_prey_switching` (EwE6 SetRelaSwitch) with each
    predator's ``SwitchPower``.

    Prey switching occurs when predators preferentially consume more abundant
    prey, stabilizing the system. Uses a power function of relative abundance.

    Parameters
    ----------
    BB : np.ndarray
        Current biomass array
    Bbase : np.ndarray
        Baseline biomass array
    pred : int
        Predator index
    ActiveLink : np.ndarray
        Active link matrix [prey, pred]
    switch_power : float
        Prey switching power (default 2.0, range 0-2)
        - 0: No switching
        - 1: Linear switching
        - 2: Strong switching (Murdoch switching)

    Returns
    -------
    np.ndarray
        Switching factors for each prey (indexed by prey)
    """
    n_groups = len(BB)
    switch_factor = np.ones(n_groups)

    if switch_power <= 0:
        return switch_factor

    # Sum of relative prey abundance for this predator
    total_rel = 0.0
    n_active = 0
    for prey in range(1, n_groups):
        if ActiveLink[prey, pred] and Bbase[prey] > 0:
            total_rel += (BB[prey] / Bbase[prey]) ** switch_power
            n_active += 1

    if total_rel <= 0:
        return switch_factor

    # Calculate switching factor for each prey
    for prey in range(1, n_groups):
        if ActiveLink[prey, pred] and Bbase[prey] > 0:
            rel_abund = (BB[prey] / Bbase[prey]) ** switch_power
            switch_factor[prey] = rel_abund / total_rel * n_active

    return switch_factor

mediation_function

mediation_function(mediation_type: int, med_bio: float, med_base: float, med_params: Dict[str, float]) -> float

.. deprecated:: Use :class:pypath.core.mediation.MediationShape and its evaluate() method instead. This function is kept for backward compatibility.

Calculate mediation effect on predation.

Mediation allows a third party (mediator) to affect the predator-prey interaction, representing effects like habitat provision or fear.

Parameters:

Name Type Description Default
mediation_type int

Type of mediation function: - 0: No mediation (returns 1.0) - 1: Positive mediation (more mediator = more predation) - 2: Negative mediation (more mediator = less predation) - 3: U-shaped (optimal at intermediate mediator biomass)

required
med_bio float

Current mediator biomass

required
med_base float

Baseline mediator biomass

required
med_params dict

Parameters including 'low', 'high', 'shape'

required

Returns:

Type Description
float

Mediation multiplier (>0)

Source code in pypath/core/ecosim_deriv.py
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
def mediation_function(
    mediation_type: int, med_bio: float, med_base: float, med_params: Dict[str, float]
) -> float:
    """.. deprecated::
        Use :class:`pypath.core.mediation.MediationShape` and its ``evaluate()``
        method instead. This function is kept for backward compatibility.

    Calculate mediation effect on predation.

    Mediation allows a third party (mediator) to affect the predator-prey
    interaction, representing effects like habitat provision or fear.

    Parameters
    ----------
    mediation_type : int
        Type of mediation function:
        - 0: No mediation (returns 1.0)
        - 1: Positive mediation (more mediator = more predation)
        - 2: Negative mediation (more mediator = less predation)
        - 3: U-shaped (optimal at intermediate mediator biomass)
    med_bio : float
        Current mediator biomass
    med_base : float
        Baseline mediator biomass
    med_params : dict
        Parameters including 'low', 'high', 'shape'

    Returns
    -------
    float
        Mediation multiplier (>0)
    """
    if mediation_type == 0 or med_base <= 0:
        return 1.0

    low = med_params.get("low", 0.5)
    high = med_params.get("high", 2.0)
    shape = med_params.get("shape", 1.0)

    x = med_bio / med_base  # Relative biomass

    if mediation_type == 1:  # Positive mediation
        # Saturating increase
        med_mult = low + (high - low) * (x**shape) / (1.0 + x**shape)
    elif mediation_type == 2:  # Negative mediation
        # Saturating decrease
        med_mult = high - (high - low) * (x**shape) / (1.0 + x**shape)
    elif mediation_type == 3:  # U-shaped
        # Optimal at x=1, declines at extremes
        diff = abs(x - 1.0)
        med_mult = high - (high - low) * (diff**shape) / (1.0 + diff**shape)
    else:
        med_mult = 1.0

    return max(med_mult, 0.001)  # Ensure positive

primary_production_forcing

primary_production_forcing(BB: ndarray, Bbase: ndarray, PB: ndarray, PP_forcing: ndarray, PP_type: ndarray, NUM_LIVING: int) -> np.ndarray

Calculate primary production with environmental forcing.

In Ecosim/Rpath, primary producers use density-dependent production to ensure stability. The production rate decreases as biomass increases above baseline, mimicking nutrient limitation.

Parameters:

Name Type Description Default
BB ndarray

Current biomass

required
Bbase ndarray

Baseline biomass

required
PB ndarray

Production/biomass ratios

required
PP_forcing ndarray

Primary production forcing multipliers by group

required
PP_type ndarray

Producer type by group: - 0: Not a producer (consumer) - 1: Primary producer (density-dependent, default) - 2: Detritus (no production)

required
NUM_LIVING int

Number of living groups

required

Returns:

Type Description
ndarray

Primary production rates

Source code in pypath/core/ecosim_deriv.py
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
def primary_production_forcing(
    BB: np.ndarray,
    Bbase: np.ndarray,
    PB: np.ndarray,
    PP_forcing: np.ndarray,
    PP_type: np.ndarray,
    NUM_LIVING: int,
) -> np.ndarray:
    """
    Calculate primary production with environmental forcing.

    In Ecosim/Rpath, primary producers use density-dependent production
    to ensure stability. The production rate decreases as biomass
    increases above baseline, mimicking nutrient limitation.

    Parameters
    ----------
    BB : np.ndarray
        Current biomass
    Bbase : np.ndarray
        Baseline biomass
    PB : np.ndarray
        Production/biomass ratios
    PP_forcing : np.ndarray
        Primary production forcing multipliers by group
    PP_type : np.ndarray
        Producer type by group:
        - 0: Not a producer (consumer)
        - 1: Primary producer (density-dependent, default)
        - 2: Detritus (no production)
    NUM_LIVING : int
        Number of living groups

    Returns
    -------
    np.ndarray
        Primary production rates
    """
    n_groups = len(BB)
    production = np.zeros(n_groups)

    for i in range(1, min(NUM_LIVING + 1, n_groups)):
        if PP_type[i] == 0:
            # Not a producer - production calculated from consumption
            continue
        elif PP_type[i] == 1:
            # Primary producer: density-dependent production
            # In Rpath/EwE, this follows: P = PB * B * forcing * (2 - B/Bbase)
            # This gives equilibrium at B = Bbase when forcing = 1
            # and ensures stability by reducing growth as B increases
            if Bbase[i] > 0:
                rel_bio = BB[i] / Bbase[i]
                # Production is PB * B at baseline, decreases as B increases
                # This factor = 2 - rel_bio ensures:
                # - At B = Bbase: factor = 1.0, production = PB * B
                # - At B = 2*Bbase: factor = 0.0, production = 0
                # - At B = 0: factor = 2.0, production = 2 * PB * B (rapid recovery)
                dd_factor = max(0, 2.0 - rel_bio)
                production[i] = PB[i] * BB[i] * PP_forcing[i] * dd_factor
            else:
                production[i] = PB[i] * BB[i] * PP_forcing[i]
        # PP_type == 2 is detritus, no production

    return production

fishing_mortality

fishing_mortality(params: dict, forcing: dict, fishing: dict, fleet_med: ndarray | None = None) -> tuple[np.ndarray, np.ndarray]

Fishing mortality per group (per year) under one month's forcing.

The gears' FishQ x effort (forcing["ForcedEffort"], times the fleet mediation multipliers when given) plus the forced fishing of the month (forcing["ForcedF"], which replaces the gears where ForcedFReplace is set). This is the F deriv_vector applies, EwE6's FishTime. Returns (FishMort, link_fish_rate): F by group (NUM_GROUPS + 1) and the per-biomass catch rate of each fishing link.

Source code in pypath/core/ecosim_deriv.py
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
def fishing_mortality(
    params: dict,
    forcing: dict,
    fishing: dict,
    fleet_med: np.ndarray | None = None,
) -> tuple[np.ndarray, np.ndarray]:
    """Fishing mortality per group (per year) under one month's forcing.

    The gears' FishQ x effort (``forcing["ForcedEffort"]``, times the fleet
    mediation multipliers when given) plus the forced fishing of the month
    (``forcing["ForcedF"]``, which replaces the gears where
    ``ForcedFReplace`` is set). This is the F ``deriv_vector`` applies, EwE6's
    FishTime. Returns ``(FishMort, link_fish_rate)``: F by group
    (``NUM_GROUPS + 1``) and the per-biomass catch rate of each fishing link.
    """
    if len(_fishing_links(fishing)[0]) < _FISHING_VECTORIZE_MIN_LINKS:
        return _fishing_mortality_loop(params, forcing, fishing, fleet_med)
    NUM_GROUPS = params["NUM_GROUPS"]
    NUM_LIVING = params["NUM_LIVING"]
    NUM_DEAD = params["NUM_DEAD"]
    NUM_GEARS = params.get("NUM_GEARS", 0)
    FishMort = np.zeros(NUM_GROUPS + 1)

    ForcedEffort = forcing.get("ForcedEffort", np.ones(max(NUM_GEARS + 1, 1)))
    FishFrom, FishThrough, FishQ = _fishing_links(fishing)

    # fleet_idx: 0-based array of fleet group indices, used to resolve gear
    # indices from FishThrough values without assuming canonical group ordering.
    if isinstance(params, dict):
        fleet_idx = params.get("fleet_idx", None)
    else:
        fleet_idx = getattr(params, "fleet_idx", None)

    # Build a fast lookup from 0-based group index to 1-based gear index.
    # Falls back to the legacy arithmetic when fleet_idx is not available.
    _gear_lookup = {}
    if fleet_idx is not None:
        for pos, grp_0 in enumerate(fleet_idx):
            _gear_lookup[int(grp_0)] = pos + 1  # 1-based gear index

    # Calculate fishing mortality with effort scaling per gear
    # FishThrough contains 1-based GROUP indices of fleets.
    # _link_fish_rate[i] is the per-biomass catch rate of fishing link i
    # (Rpath: caught = FishQ * Effort * B), used for discards to FishTo.
    # Vectorised over fishing links (index 0 is a placeholder). np.add.at
    # accumulates sequentially in link order, as the loop form does, so the
    # results are bit-for-bit identical.
    n_fl = len(FishFrom)
    _link_fish_rate = np.zeros(n_fl)
    if n_fl > 1:
        _from = np.asarray(FishFrom[1:]).astype(np.int64)
        _through = np.asarray(FishThrough[1:]).astype(np.int64)
        _q = np.asarray(FishQ[1:], dtype=float)
        if _gear_lookup:
            # dict.get(g, 0) for every link, as an array lookup table
            _lut = np.zeros(max(_gear_lookup) + 1, dtype=np.int64)
            _lut[list(_gear_lookup)] = list(_gear_lookup.values())
            _g0 = _through - 1
            _valid = (_g0 >= 0) & (_g0 < len(_lut))
            gear_idx = np.zeros(n_fl - 1, dtype=np.int64)
            gear_idx[_valid] = _lut[_g0[_valid]]
        else:
            gear_idx = _through - NUM_LIVING - NUM_DEAD
        _fe = np.asarray(ForcedEffort, dtype=float)
        _in = (gear_idx > 0) & (gear_idx < len(_fe))
        effort_mult = np.ones(n_fl - 1)
        effort_mult[_in] = _fe[gear_idx[_in]]
        if fleet_med is not None:
            _fm = np.asarray(fleet_med, dtype=float)
            _okm = (gear_idx > 0) & (gear_idx <= len(_fm))
            effort_mult[_okm] = effort_mult[_okm] * _fm[gear_idx[_okm] - 1]
        rate = _q * effort_mult
        np.add.at(FishMort, _from, rate)
        _link_fish_rate[1:] = rate
    _forced_f = forcing.get("ForcedF")
    if _forced_f is not None:
        _ff = np.asarray(_forced_f, dtype=float)
        _replace = np.asarray(
            forcing.get("ForcedFReplace", np.zeros(len(_ff), dtype=bool)), dtype=bool
        )
        n_bio_groups = NUM_LIVING + NUM_DEAD
        hi = min(len(_ff), n_bio_groups + 1)
        if hi > 1:
            grps = np.arange(1, hi)
            rep = grps[grps < len(_replace)]
            rep = rep[_replace[rep]]
            if rep.size:
                FishMort[rep] = 0.0
                if n_fl > 1:
                    _mark = np.zeros(NUM_GROUPS + 2, dtype=bool)
                    _mark[rep] = True
                    _link_fish_rate[1:][_mark[_from]] = 0.0
            FishMort[1:hi] += _ff[1:hi]
    return FishMort, _link_fish_rate

deriv_vector

deriv_vector(state: ndarray, params: dict, forcing: dict, fishing: dict, t: float = 0.0, rates: dict | None = None) -> np.ndarray

Calculate derivatives for all state variables in Ecosim.

This is the core function that implements the Ecosim differential equations based on foraging arena theory with prey switching and mediation support.

The functional response is: C_ij = (a_ij * v_ij * B_i * B_j * T_j * S_ij * D_j * M_ij) / (v_ij + v_ijT_jD_j + a_ijB_jD_j + a_ijd_ijB_j*D_j^2)

Where: a_ij = base search rate (from QQ/BB setup) v_ij = vulnerability exchange rate B_i = prey biomass B_j = predator biomass T_j = time forcing on predator S_ij = prey switching factor D_j = handling time factor d_ij = handling time for this link M_ij = mediation multiplier

Parameters:

Name Type Description Default
state ndarray

Current state vector (biomass values) indexed 0 to NUM_GROUPS

required
params dict

Model parameters containing: - NUM_GROUPS: Total number of groups - NUM_LIVING: Number of living groups - NUM_DEAD: Number of detritus groups - NUM_GEARS: Number of fishing gears - PB: Production/Biomass ratios - QB: Consumption/Biomass ratios - ActiveLink: Boolean array [prey, pred] of active links - DC: Diet composition matrix [prey, pred] - VV: Vulnerability parameters [prey, pred] - DD: Handling time parameters [prey, pred] - Bbase: Baseline biomass [group] - DetFrac: Fraction to detritus [group] - Unassim: Unassimilated fraction [group] - SwitchPower: per-group EwE6 prey switching power (array, 0 = off); see apply_prey_switching. SwitchA / SwitchBbase optionally give the pre-computed search-rate weights and normalising base biomass - PP_type: Producer type array [group] - Mediation: Mediation configuration dict

required
forcing dict

Forcing arrays: - ForcedBio: Forced biomass values [group] - ForcedMigrate: Migration forcing [group] - ForcedCatch: Forced catch [group] - ForcedEffort: Forced effort [gear] - PP_forcing: Primary production forcing [group] - Ftime: Time forcing [group] - StanzaPredRatio: StanzaPred / baseStanzaPred for multi-stanza groups, NaN elsewhere; replaces B / Bbase in the predator term

required
fishing dict

Fishing parameters: - FishingMort: Base fishing mortality [group] - EffortCap: Effort cap [gear]

required
t float

Current time (for time-varying forcing)

0.0
rates dict

If given, filled with per-group rates (per year) as Rpath's derivative returns them: FoodGain (consumption by the group), FoodLoss (eaten by predators), MzeroLoss, FishingLoss and LossPropToB (their sum). Multi-stanza updates use these. The continuous path's mass budget reads Production (the living kernel's, x RecruitmentMult), Import (imported diet), NutFree and NutFloor (the free nutrient as used, NaN without nutrient limitation, and whether its floor binds), Landed (the catch of the fishing links to no detritus pool plus the forced F) and, with detritus links, Discards and DetExport (see _rpath_detritus_derivs).

None

Returns:

Type Description
ndarray

Derivative vector (dB/dt for each group)

Source code in pypath/core/ecosim_deriv.py
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
def deriv_vector(
    state: np.ndarray,
    params: dict,
    forcing: dict,
    fishing: dict,
    t: float = 0.0,
    rates: dict | None = None,
) -> np.ndarray:
    """
    Calculate derivatives for all state variables in Ecosim.

    This is the core function that implements the Ecosim differential equations
    based on foraging arena theory with prey switching and mediation support.

    The functional response is:
        C_ij = (a_ij * v_ij * B_i * B_j * T_j * S_ij * D_j * M_ij) /
               (v_ij + v_ij*T_j*D_j + a_ij*B_j*D_j + a_ij*d_ij*B_j*D_j^2)

    Where:
        a_ij = base search rate (from QQ/BB setup)
        v_ij = vulnerability exchange rate
        B_i = prey biomass
        B_j = predator biomass
        T_j = time forcing on predator
        S_ij = prey switching factor
        D_j = handling time factor
        d_ij = handling time for this link
        M_ij = mediation multiplier

    Parameters
    ----------
    state : np.ndarray
        Current state vector (biomass values) indexed 0 to NUM_GROUPS
    params : dict
        Model parameters containing:
        - NUM_GROUPS: Total number of groups
        - NUM_LIVING: Number of living groups
        - NUM_DEAD: Number of detritus groups
        - NUM_GEARS: Number of fishing gears
        - PB: Production/Biomass ratios
        - QB: Consumption/Biomass ratios
        - ActiveLink: Boolean array [prey, pred] of active links
        - DC: Diet composition matrix [prey, pred]
        - VV: Vulnerability parameters [prey, pred]
        - DD: Handling time parameters [prey, pred]
        - Bbase: Baseline biomass [group]
        - DetFrac: Fraction to detritus [group]
        - Unassim: Unassimilated fraction [group]
        - SwitchPower: per-group EwE6 prey switching power (array, 0 = off);
          see apply_prey_switching. SwitchA / SwitchBbase optionally give
          the pre-computed search-rate weights and normalising base biomass
        - PP_type: Producer type array [group]
        - Mediation: Mediation configuration dict
    forcing : dict
        Forcing arrays:
        - ForcedBio: Forced biomass values [group]
        - ForcedMigrate: Migration forcing [group]
        - ForcedCatch: Forced catch [group]
        - ForcedEffort: Forced effort [gear]
        - PP_forcing: Primary production forcing [group]
        - Ftime: Time forcing [group]
        - StanzaPredRatio: StanzaPred / baseStanzaPred for multi-stanza
          groups, NaN elsewhere; replaces B / Bbase in the predator term
    fishing : dict
        Fishing parameters:
        - FishingMort: Base fishing mortality [group]
        - EffortCap: Effort cap [gear]
    t : float
        Current time (for time-varying forcing)
    rates : dict, optional
        If given, filled with per-group rates (per year) as Rpath's
        derivative returns them: ``FoodGain`` (consumption by the group),
        ``FoodLoss`` (eaten by predators), ``MzeroLoss``, ``FishingLoss``
        and ``LossPropToB`` (their sum). Multi-stanza updates use these.
        The continuous path's mass budget reads ``Production`` (the living
        kernel's, x RecruitmentMult), ``Import`` (imported diet), ``NutFree``
        and ``NutFloor`` (the free nutrient as used, NaN without nutrient
        limitation, and whether its floor binds), ``Landed`` (the catch of
        the fishing links to no detritus pool plus the forced F) and, with
        detritus links, ``Discards`` and ``DetExport`` (see
        ``_rpath_detritus_derivs``).

    Returns
    -------
    np.ndarray
        Derivative vector (dB/dt for each group)
    """
    NUM_GROUPS = params["NUM_GROUPS"]
    NUM_LIVING = params["NUM_LIVING"]
    NUM_DEAD = params["NUM_DEAD"]
    NUM_GEARS = params.get("NUM_GEARS", 0)

    # Initialize output arrays
    deriv = np.zeros(NUM_GROUPS + 1)  # +1 for 0-indexing with outside

    # Extract parameters
    PB = params["PB"]
    QB = params.get("QB", np.zeros(NUM_GROUPS + 1))
    ActiveLink = params["ActiveLink"]
    VV = params["VV"]
    DD = params["DD"]
    Unassim = params.get("Unassim", np.zeros(NUM_GROUPS + 1))
    Bbase = params.get("Bbase", state.copy())  # Baseline biomass
    PP_type = params.get("PP_type", np.zeros(NUM_GROUPS + 1, dtype=int))
    _mediation = params.get("_mediation", None)
    # Pre-fetch spname and M0 once to avoid repeated dict lookups and
    # default-argument allocations ([None]*N, np.zeros) inside inner loops.
    spname_list = params.get("spname", None)
    M0_arr = params.get("M0", None)
    _TRACE_DEBUG_GROUPS = params.get("TRACE_DEBUG_GROUPS", None)

    # Current biomass (state variable)
    BB = state.copy()

    instrument_set = _resolve_instrument_groups(params, spname_list, NUM_GROUPS)

    # Initialize consumption matrix
    QQ = np.zeros((NUM_GROUPS + 1, NUM_GROUPS + 1))

    # =========================================================================
    # STEP 1: Calculate predation pressure from each predator on each prey
    # Using foraging arena functional response with prey switching
    #
    # From Rpath ecosim.cpp (vectorized version):
    # Q = QQ * PDY * pow(PYY, HandleSwitch * COUPLED) *
    #     ( DD / ( DD-1.0 + pow((1-Hself)*PYY + Hself*PySuite, HandleSwitch*COUPLED)) ) *
    #     ( VV / ( VV-1.0 + (1-Sself)*PDY + Sself*PdSuite) );
    #
    # Where:
    #   QQ = base consumption rate (DC * QB * Bpred_baseline)
    #   PDY = predYY = Ftime * Bpred / Bpred_baseline (relative predator biomass)
    #   PYY = preyYY = Bprey / Bprey_baseline * force_byprey (relative prey biomass)
    #   DD = handling time (large = no handling time effect, approaching 1.0)
    #   VV = vulnerability (large = no density dependence)
    # =========================================================================

    # Get time-varying forcing (default to 1.0)
    Ftime = forcing.get("Ftime", np.ones(NUM_GROUPS + 1))
    ForcedBio = forcing.get("ForcedBio", np.zeros(NUM_GROUPS + 1))
    PP_forcing = forcing.get("PP_forcing", np.ones(NUM_GROUPS + 1))
    # EwE6 nutrient limitation (EWE rule: params["NutBaseFreeProp"]): the
    # producers' production scales with the free nutrient the biomass leaves
    _nut_prop = params.get("NutBaseFreeProp")
    if _nut_prop is not None:
        _nb = slice(1, NUM_LIVING + NUM_DEAD + 1)
        # Ecospace: NutTot from the map-wide base, not a patch's (_nut_base)
        _nut_base = params.get("_nut_base")
        _nut_f = _ewe_nutrient_factor(
            float(np.sum(state[_nb])),
            float(np.sum((Bbase if _nut_base is None else _nut_base)[_nb])),
            _nut_prop,
            float(forcing.get("NutForcing", 1.0)),
        )
        if rates is not None:
            # the free nutrient as used, and whether its floor binds
            _nut_free, _nut_free0 = _ewe_nutrient_free(
                float(np.sum(state[_nb])),
                float(np.sum((Bbase if _nut_base is None else _nut_base)[_nb])),
                _nut_prop,
                float(forcing.get("NutForcing", 1.0)),
            )
            rates["NutFree"] = _nut_free
            rates["NutFloor"] = bool(_nut_free <= 0.00101 * _nut_free0)
        if _nut_f != 1.0:
            PP_forcing = np.array(PP_forcing, dtype=float, copy=True)
            _producer = np.asarray(PP_type, dtype=float)[: len(PP_forcing)] > 0
            _producer[0] = False
            PP_forcing[_producer] *= _nut_f
    elif rates is not None:
        rates["NutFree"] = float("nan")  # no nutrient limitation
        rates["NutFloor"] = False
    # Ecospace feeding efficiency (EwE's EatEff = the cell's habitat capacity):
    # it scales producers' production (pbb, cSpaceSolver.vb 1008) and divides
    # consumers' predator term in the vulnerable pool (vb 883)
    _kernel_eat_eff = None
    _eat_eff = params.get("_eat_eff")
    if _eat_eff is not None:
        _eat_eff = np.asarray(_eat_eff, dtype=float)
        _producer = np.asarray(PP_type, dtype=float)[: len(_eat_eff)] > 0
        _producer[0] = False
        PP_forcing = np.array(PP_forcing, dtype=float, copy=True)
        PP_forcing[: len(_eat_eff)][_producer] *= _eat_eff[_producer]
        _kernel_eat_eff = _eat_eff.copy()
        _kernel_eat_eff[_producer] = 1.0  # their gain carries EatEff above
    ForcedPrey = forcing.get("ForcedPrey", np.ones(NUM_GROUPS + 1))
    ForcedSearch = forcing.get("ForcedSearch", None)
    ForcedMort = forcing.get("ForcedMort", None)
    ForcedMigrate = forcing.get("ForcedMigrate", np.zeros(NUM_GROUPS + 1))
    ForcedActresp = forcing.get("ForcedActresp", np.ones(NUM_GROUPS + 1))
    ForcedRecs = forcing.get("ForcedRecs", np.ones(NUM_GROUPS + 1))
    RecruitmentAdj = forcing.get("RecruitmentAdj", np.ones(NUM_GROUPS + 1))

    # Calculate relative biomass arrays (vectorized)
    # preyYY = Ftime * B / Bbase * prey_forcing (where Bbase > 0)
    # Ftime is applied to both preyYY and predYY to match Rpath C++ ecosim.cpp
    safe_bbase = np.where(Bbase > 0, Bbase, 1.0)
    preyYY = np.zeros(NUM_GROUPS + 1)
    preyYY[1:] = np.where(
        Bbase[1:] > 0,
        Ftime[1:] * BB[1:] / safe_bbase[1:] * ForcedPrey[1:],
        0.0,
    )
    # EwE arena (D1): prey Ftime and vulnerability forcing enter through the
    # vulnerable-pool inflow (remapped VV / QQbase below), not the prey term.
    _ewe_prey_f = None
    if params.get("PREY_FTIME_ARENA", False):
        _ewe_prey_f = np.ones(NUM_GROUPS + 1)
        _ewe_prey_f[1:] = Ftime[1:] * ForcedPrey[1:]
        preyYY[1:] = np.where(Bbase[1:] > 0, BB[1:] / safe_bbase[1:], 0.0)
    if params.get("RpathPrimaryProduction", False) and Bbase[0] > 0:
        # Group 0 ("the sun") is the prey of the producers' links
        preyYY[0] = Ftime[0] * BB[0] / safe_bbase[0] * ForcedPrey[0]

    # predYY = Ftime * B / Bbase (where Bbase > 0, living groups only)
    predYY = np.zeros(NUM_GROUPS + 1)
    sl = slice(1, NUM_LIVING + 1)
    predYY[sl] = np.where(
        Bbase[sl] > 0,
        Ftime[sl] * BB[sl] / safe_bbase[sl],
        0.0,
    )
    # Multi-stanza groups eat in proportion to their age structure's
    # consumption index, StanzaPred / baseStanzaPred, not their biomass
    # (Rpath deriv_vector). NaN marks groups without stanzas.
    _stanza_ratio = forcing.get("StanzaPredRatio")
    if _stanza_ratio is not None:
        _has_ratio = np.isfinite(_stanza_ratio)
        predYY[_has_ratio] = Ftime[_has_ratio] * _stanza_ratio[_has_ratio]
    # Search-rate forcing (Rpath force_bysearch, EwE SearchRate) scales a
    # consumer's effective biomass in the foraging arena. A producer's
    # ForcedSearch is its production forcing (PP_forcing), applied with the
    # production term instead.
    if ForcedSearch is not None:
        _fs = np.asarray(ForcedSearch, dtype=float)
        if _fs.shape[0] == NUM_GROUPS + 1:
            _consumer = np.asarray(PP_type, dtype=float)[: NUM_GROUPS + 1] == 0
            _consumer[0] = False
            predYY[_consumer] = predYY[_consumer] * _fs[_consumer]

    # Get base consumption matrix
    QQbase = params.get("QQbase", np.zeros((NUM_GROUPS + 1, NUM_GROUPS + 1)))

    # EwE6 prey switching (SwitchPower): each link's search rate scales with
    # the prey's share of the predator's base-weighted prey pool. Applied as
    # the equivalent vulnerability and base flow of the closed-form kernel.
    _switch_power = params.get("SwitchPower")
    if _switch_power is not None and np.any(np.asarray(_switch_power) > 0):
        VV, QQbase = apply_prey_switching(
            BB,
            VV,
            QQbase,
            _switch_power,
            params.get("SwitchBbase", Bbase),
            params.get("SwitchA"),
        )
    # EwE6 pred/prey mediation (D3): each mediated link's search rate or
    # vulnerability is multiplied by its shapes' values at this biomass and
    # the month's fleet effort (SetMedFunctions at the start of every Derivt
    # with FishRateGear(fleet, TimeNow), ApplyAVmodifiers). Ecospace passes
    # its own mediator effort ("MediationEffort", cSpaceSolver.vb:516-528).
    _med_search = _med_vul = None
    _ewe_med = params.get("EweMediation")
    if _ewe_med is not None and _ewe_prey_f is not None:
        # spatial IBM runs pass absolute patch biomass; mediation needs density
        _med_bb = BB * params.get("_mediation_density_scale", 1.0)
        _med_effort = forcing.get("MediationEffort", forcing.get("ForcedEffort"))
        _med_search, _med_vul = _ewe_med.link_factors(
            _med_bb,
            NUM_GROUPS + 1,
            _med_effort,
            interpolate=params.get("MEDIATION_INTERPOLATE", False),
        )
    if _ewe_prey_f is not None:
        _f_arena = _ewe_prey_f
        _vul_link = forcing.get("ForcedVulLink")
        if _vul_link is not None:
            # a link's own vulnerability forcing joins the prey's f
            _f_arena = _ewe_prey_f[:, None] * np.asarray(_vul_link, dtype=float)
        if _med_vul is not None:
            _f_arena = (
                _f_arena if _f_arena.ndim == 2 else _f_arena[:, None]
            ) * _med_vul
        VV, QQbase = ewe_prey_multiplier_arena(VV, QQbase, _f_arena)
    # EwE link-level search-rate forcing (built only for EwE-rule scenarios)
    _search_link = forcing.get("ForcedSearchLink")
    if _med_search is not None:
        _search_link = (
            _med_search
            if _search_link is None
            else np.asarray(_search_link, dtype=float) * _med_search
        )
    if _search_link is not None:
        VV, QQbase = ewe_link_search_arena(VV, QQbase, _search_link)

    # Extract suite-pooling parameters (None means old behaviour / no pooling)
    _ScrambleSelf = params.get("ScrambleSelf")
    _HandleSelf = params.get("HandleSelf")
    _PredPredWeight = params.get("PredPredWeight")
    _PreyPreyWeight = params.get("PreyPreyWeight")
    _HandleSwitch = params.get("HandleSwitch")
    _COUPLED = params.get("COUPLED", 1)

    # Compute mediation multipliers (if mediation functions are configured)
    _med_multipliers = None
    if _mediation is not None:
        _med_multipliers = _mediation.compute_group_multipliers(BB, Bbase, ActiveLink)

    # Compute fleet mediation multipliers (applied to fishing effort per gear)
    _fleet_med = None
    if _mediation is not None:
        _fleet_med = _mediation.compute_fleet_multipliers(BB, Bbase, NUM_GEARS)

    # Compute the consumption matrix. Use pre-computed sparse link arrays
    # when available (avoids iterating over inactive links) through
    # _compute_consumption_sparse (the numba kernel, or the Python loop);
    # otherwise fall back to the dense Python kernel.
    _link_prey = params.get("_link_prey", None)
    _link_pred = params.get("_link_pred", None)
    # The continuous path (``_KERNEL_VECTOR``, set by ContinuousRHS on its
    # own params only) runs the sparse loop's vectorised twin; the dense
    # loop, without link arrays, is kept as it is.
    _kernel_vector = bool(params.get("_KERNEL_VECTOR", False))

    def _run_kernel(pred_yy):
        if _link_prey is not None and _link_pred is not None:
            _sparse_kernel = (
                _compute_consumption_vector
                if _kernel_vector
                else _compute_consumption_sparse
            )
            _sparse_kernel(
                QQ,
                BB,
                VV,
                DD,
                QQbase,
                preyYY,
                pred_yy,
                _link_prey,
                _link_pred,
                len(_link_prey),
                ScrambleSelf=_ScrambleSelf,
                HandleSelf=_HandleSelf,
                PredPredWeight=_PredPredWeight,
                PreyPreyWeight=_PreyPreyWeight,
                HandleSwitch=_HandleSwitch,
                COUPLED=_COUPLED,
                med_multipliers=_med_multipliers,
                eat_eff=_kernel_eat_eff,
            )
        else:
            # ActiveLink may be a boolean array; ensure it is integer for numba.
            _active_int = (
                ActiveLink.astype(np.int64)
                if ActiveLink.dtype != np.int64
                else ActiveLink
            )
            _compute_consumption(
                QQ,
                BB,
                _active_int,
                VV,
                DD,
                QQbase,
                preyYY,
                pred_yy,
                NUM_LIVING,
                NUM_GROUPS,
                ScrambleSelf=_ScrambleSelf,
                HandleSelf=_HandleSelf,
                PredPredWeight=_PredPredWeight,
                PreyPreyWeight=_PreyPreyWeight,
                HandleSwitch=_HandleSwitch,
                COUPLED=_COUPLED,
                med_multipliers=_med_multipliers,
                eat_eff=_kernel_eat_eff,
            )

    # EwE6 handling time (D5): each predator's search rate is divided by
    # Hden, the base rates carrying Dzero = Hden0, so the predator term is
    # scaled by Hden0 / Hden. Hden is updated once per call from the
    # consumption at the previous Hden, then the consumption is recomputed
    # (Derivt, cEcoSimModel.vb 2890-2969). rsim_run keeps Hden between calls
    # and freezes it for calls that are not integration stages. With
    # ``_hden_exact`` (the continuous path) the caller solves Hden and it is
    # used as given, with no update; or ``params["_hden_solver"]`` solves it
    # here on the kernel's inputs.
    _hden = params.get("_hden")
    if _hden is not None:
        _hden0 = params["_hden0"]
        _cmco_qb = params["_cmco_qb"]
        _hden_exact = params.get("_hden_exact", False)
        _hden_solver = params.get("_hden_solver") if _hden_exact else None
        if _hden_solver is not None:
            # Continuous path: Hden from the solver, given what the loop
            # reads, then one kernel pass at it
            _index = np.array(BB, dtype=float, copy=True)
            if _stanza_ratio is not None:
                _index[_has_ratio] = Bbase[_has_ratio] * _stanza_ratio[_has_ratio]
            if _link_prey is not None and _link_pred is not None:
                _lp, _lq = _link_prey, _link_pred
            else:  # the dense loop's links: predators 1..NUM_LIVING
                _lp, _lq = np.nonzero(
                    ActiveLink[1 : NUM_GROUPS + 1, 1 : NUM_LIVING + 1]
                )
                _lp, _lq = _lp + 1, _lq + 1
            _inputs = KernelInputs(
                BB=BB.copy(),
                preyYY=preyYY,
                predYY=predYY,
                hden0=np.asarray(_hden0, dtype=float),
                VV=VV,
                DD=DD,
                QQbase=QQbase,
                link_prey=_lp,
                link_pred=_lq,
                ScrambleSelf=_ScrambleSelf,
                HandleSelf=_HandleSelf,
                PredPredWeight=_PredPredWeight,
                PreyPreyWeight=_PreyPreyWeight,
                HandleSwitch=_HandleSwitch,
                COUPLED=_COUPLED,
                med_multipliers=_med_multipliers,
                eat_eff=_kernel_eat_eff,
                index=_index,
                cmco_qb=np.asarray(_cmco_qb, dtype=float),
            )
            _hden_solved = np.array(_hden_solver(_inputs), dtype=float, copy=True)
            _run_kernel(predYY * (_hden0 / _hden_solved))
            if rates is not None:
                rates["Hden"] = _hden_solved
        elif _hden_exact:
            # Continuous path: one kernel pass at the given Hden, which is
            # neither updated nor written; the caller carries Hden.
            _run_kernel(predYY * (_hden0 / _hden))
        else:
            _run_kernel(predYY * (_hden0 / _hden))
            _index = np.array(BB, dtype=float, copy=True)
            if _stanza_ratio is not None:
                _index[_has_ratio] = Bbase[_has_ratio] * _stanza_ratio[_has_ratio]
            _hden_new = _ewe_hden_update(_hden, QQ[1:, :].sum(axis=0), _index, _cmco_qb)
            if not params.get("_hden_frozen", False):
                _hden[:] = _hden_new
            _run_kernel(predYY * (_hden0 / _hden_new))
        if rates is not None:
            rates["HdenConsumption"] = QQ[1:, :].sum(axis=0)
    else:
        _run_kernel(predYY)

    # Post-loop instrumentation: log per-link breakdown for interesting groups
    if instrument_set:
        try:
            for pred in range(1, NUM_LIVING + 1):
                for prey in range(1, NUM_GROUPS + 1):
                    if QQ[prey, pred] <= 0.0:
                        continue
                    prey0 = prey - 1
                    pred0 = pred - 1
                    if prey0 in instrument_set or pred0 in instrument_set:
                        pname = spname_list[prey] if spname_list is not None else None
                        prname = spname_list[pred] if spname_list is not None else None
                        qbase = QQbase[prey, pred]
                        PYY = preyYY[prey]
                        PDY = predYY[pred]
                        dd = DD[prey, pred]
                        vv = VV[prey, pred]
                        dd_term = dd / max(dd - 1.0 + max(PYY, 1e-10), 1e-10)
                        vv_term = vv / max(vv - 1.0 + max(PDY, 1e-10), 1e-10)
                        logger.debug(
                            "INSTR Q prey=%s name=%s pred=%s name=%s qbase=%.6e PDY=%.6e PYY=%.6e dd_term=%.6e vv_term=%.6e Q_calc=%.6e",
                            prey,
                            pname,
                            pred,
                            prname,
                            qbase,
                            PDY,
                            PYY,
                            dd_term,
                            vv_term,
                            QQ[prey, pred],
                        )
        except Exception as e:
            logger.debug("Instrumentation error in Q calculation: %s", e)

    # =========================================================================
    # STEP 2: Apply forced biomass adjustments
    # =========================================================================
    # (group by group, as the loops these array forms replace: the same
    # operations on the same numbers, so the same bits)
    _fb = np.asarray(ForcedBio)[1 : NUM_GROUPS + 1]
    _forced = _fb > 0
    if _forced.any():
        BB[1 : NUM_GROUPS + 1][_forced] = _fb[_forced]

    # =========================================================================
    # STEP 3: Calculate fishing mortality with forced effort
    # =========================================================================
    Catch = np.zeros(NUM_GROUPS + 1)
    FishFrom = _fishing_links(fishing)[0]
    FishMort, _link_fish_rate = fishing_mortality(
        params, forcing, fishing, fleet_med=_fleet_med
    )

    Catch[1 : NUM_LIVING + 1] = FishMort[1 : NUM_LIVING + 1] * BB[1 : NUM_LIVING + 1]
    for i in range(1, NUM_LIVING + 1) if instrument_set else ():
        try:
            # i is spname index (1..); instrument_set uses 0-based group indices
            if instrument_set and (i - 1) in instrument_set:
                name = spname_list[i] if spname_list is not None else None
                logger.debug(
                    "INSTR FISH grp=%s name=%s FishMort=%.6e BB=%.6e Catch=%.6e",
                    i,
                    name,
                    FishMort[i],
                    BB[i],
                    Catch[i],
                )
        except Exception as e:
            logger.debug("Instrumentation error in fishing: %s", e)

    # Debugging: print fishing details for small models to trace if fishing is applied

    # =========================================================================
    # STEP 4: Calculate derivatives for living groups
    # =========================================================================

    # Calculate primary production for producers
    pp_rates = primary_production_forcing(
        BB, Bbase, PB, PP_forcing, PP_type, NUM_LIVING
    )
    # Rpath: a producer's gain is its consumption from group 0 ("the sun"),
    # through the same functional response as any link (saturating in the
    # producer's own biomass via VV). rsim_run opts in to this.
    if params.get("RpathPrimaryProduction", False):
        _lv = slice(1, NUM_LIVING + 1)
        _suns = (np.asarray(PP_type)[_lv] > 0) & (QQbase[0, _lv] > 0)
        if _suns.any():
            pp_rates[_lv][_suns] = (
                QQ[0, _lv][_suns] * np.asarray(PP_forcing)[_lv][_suns]
            )

    # IBM integration: check if any groups are replaced by IBMs
    ibm_groups = params.get("ibm_groups", {})

    # Handle IBM groups first (non-numba-compatible path)
    for i in ibm_groups:
        if 1 <= i <= NUM_LIVING:
            from pypath.ibm.integration import apply_ibm_to_derivative

            spatial_ctx = params.get("_ibm_spatial_context_%d" % i, None)
            apply_ibm_to_derivative(
                deriv=deriv,
                QQ=QQ,
                BB=BB,
                ibm_group=ibm_groups[i],
                forcing=forcing,
                dt=params.get("_dt", 1 / 12),
                spatial_context=spatial_ctx,
            )

    # Prepare arrays for the numba-accelerated living-group derivative kernel
    _M0_safe = (
        M0_arr
        if (M0_arr is not None and isinstance(M0_arr, np.ndarray))
        else np.zeros(NUM_GROUPS + 1)
    )
    _GE_arr = np.zeros(NUM_GROUPS + 1)
    _qb_living = np.asarray(QB)[1 : NUM_LIVING + 1]
    _eats = _qb_living > 0.0
    _GE_arr[1 : NUM_LIVING + 1][_eats] = (
        np.asarray(PB)[1 : NUM_LIVING + 1][_eats] / _qb_living[_eats]
    )
    # base GE (EwE SimGE) for the fast-group biomeq; UseVarPQ may change _GE_arr
    _GE_base = _GE_arr.copy()
    _ibm_mask = np.zeros(NUM_GROUPS + 1, dtype=np.int64)
    for _ibm_i in ibm_groups:
        if 0 <= _ibm_i <= NUM_GROUPS:
            _ibm_mask[_ibm_i] = 1
    _PP_type_int = np.asarray(PP_type, dtype=np.int64)

    _forced_recs_arr = np.asarray(ForcedRecs, dtype=float).reshape(-1)
    if _forced_recs_arr.size != NUM_GROUPS + 1:
        _forced_recs_arr = np.ones(NUM_GROUPS + 1)

    _recruitment_adj_arr = np.asarray(RecruitmentAdj, dtype=float).reshape(-1)
    if _recruitment_adj_arr.size != NUM_GROUPS + 1:
        _recruitment_adj_arr = np.ones(NUM_GROUPS + 1)

    _RecruitmentMult = _forced_recs_arr * _recruitment_adj_arr
    _RecruitmentMult = np.where(
        np.isfinite(_RecruitmentMult) & (_RecruitmentMult > 0.0),
        _RecruitmentMult,
        1.0,
    )

    _forced_actresp_arr = np.asarray(ForcedActresp, dtype=float).reshape(-1)
    if _forced_actresp_arr.size != NUM_GROUPS + 1:
        _forced_actresp_arr = np.ones(NUM_GROUPS + 1)
    _forced_actresp_arr = np.where(
        np.isfinite(_forced_actresp_arr) & (_forced_actresp_arr > 0.0),
        _forced_actresp_arr,
        1.0,
    )

    _MetabolicMult = _forced_actresp_arr.copy()

    # Optional model-based temperature + size metabolic scaling
    _met_model = params.get("MetabolismModel", None)
    _met_temp = params.get("MetabolicTemperature", None)
    _met_mass = params.get("MetabolicBodyMass", None)
    if _met_model is not None and _met_temp is not None and _met_mass is not None:
        try:
            temp_arr = np.asarray(_met_temp, dtype=float).reshape(-1)
            mass_arr = np.asarray(_met_mass, dtype=float).reshape(-1)
            if temp_arr.size == NUM_GROUPS + 1 and mass_arr.size == NUM_GROUPS + 1:
                ref_temp = _met_model.temperature_dependence.reference_temperature
                base_temp = np.full(NUM_GROUPS + 1, ref_temp, dtype=float)
                met_rates = _met_model.compute_metabolic_rate_batch(
                    body_mass=mass_arr,
                    temperature=temp_arr,
                    activity_multiplier=_forced_actresp_arr,
                )
                baseline = _met_model.compute_metabolic_rate_batch(
                    body_mass=mass_arr,
                    temperature=base_temp,
                    activity_multiplier=np.ones(NUM_GROUPS + 1, dtype=float),
                )
                _model_mult = np.where(baseline > 0.0, met_rates / baseline, 1.0)
                _MetabolicMult *= np.where(
                    np.isfinite(_model_mult) & (_model_mult > 0.0), _model_mult, 1.0
                )
        except Exception as _met_err:
            logger.debug("Metabolic model scaling skipped: %s", _met_err)

    _M0_effective = _M0_safe * _MetabolicMult
    # Other mortality as it reaches detritus (see DETRITUS_MO_UNSCALED below).
    _M0_detritus = _M0_effective
    # EwE6 (Derivt): other mortality follows feeding time,
    # M0 * (1 - MoPred + MoPred * Ftime).
    _mo_pred = params.get("MoPred", None)
    if _mo_pred is not None:
        _mo_pred = np.asarray(_mo_pred, dtype=float)
        if _mo_pred.shape[0] == NUM_GROUPS + 1 and np.any(_mo_pred != 0.0):
            _M0_effective = _M0_effective * (
                1.0 - _mo_pred + _mo_pred * np.asarray(Ftime, dtype=float)
            )
    # Other-mortality forcing (EwE6 MortOther; Rpath force_bymort) scales M0.
    # The scaled rate also feeds the detritus flows. (Rpath additionally
    # scales the predation loss without the predator's gain.)
    if ForcedMort is not None:
        _fm = np.asarray(ForcedMort, dtype=float)
        if _fm.shape[0] == NUM_GROUPS + 1:
            _M0_effective = _M0_effective * _fm
            _M0_detritus = _M0_detritus * _fm
    # EwE rule: detritus receives the unscaled mo x B (times other-mortality
    # forcing), as EwE6's SimDetritusMT (vb 3160-3166), although the group
    # loses the Ftime-scaled flow; 'rpath' rule: the scaled flow, so the
    # detritus budget stays closed.
    if not params.get("DETRITUS_MO_UNSCALED", False):
        _M0_detritus = _M0_effective
    _mo_tot_gate = params.get("DETRITUS_MO_TOT", False)
    # EwE6 other mortality moTot = moMax / (1 + Qh x Eatenof / StartEatenOf)
    # in place of mo for every eaten group (Derivt, vb 3058-3081): with
    # PaddP < 1 other mortality compensates for predation, and an eaten group
    # with mo <= 0 (EE > 1) loses none. The detritus flow keeps mo
    # (SimDetritusMT, vb 3165) unless ``DETRITUS_MO_TOT`` is set (the
    # continuous path's R5 closure), when it receives moTot x B as well.
    _mo_tot = params.get("_mo_tot")
    if _mo_tot is not None:
        _mo_max, _qh, _start_eaten_of = _mo_tot
        _eaten_of = np.zeros(NUM_GROUPS + 1)
        _eaten_of[1 : NUM_LIVING + 1] = QQ[1 : NUM_LIVING + 1, 1 : NUM_LIVING + 1].sum(
            axis=1
        )
        _mo_tot_f = _mo_tot_factor(_eaten_of, _start_eaten_of, _M0_safe, _mo_max, _qh)
        _M0_effective = _M0_effective * _mo_tot_f
        if _mo_tot_gate:
            # R5 closure: detritus receives the same moTot x B the group loses.
            _M0_detritus = _M0_detritus * _mo_tot_f
    # EwE6 UseVarPQ: gross efficiency follows the total loss rate Z,
    # GE = AssimEff * Z / (Z + 3 K); AssimEff is set so GE = GE0 at Z = PB.
    if params.get("UseVarPQ", False):
        _vbk = params.get("VbK", None)
        _aeff = params.get("AssimEff", None)
        if _vbk is not None and _aeff is not None:
            _vbk = np.asarray(_vbk, dtype=float)
            _aeff = np.asarray(_aeff, dtype=float)
            for _gi in range(1, NUM_LIVING + 1):
                if (
                    _vbk[_gi] > 0.0
                    and _aeff[_gi] > 0.0
                    and QB[_gi] > 0.0
                    and BB[_gi] > 0.0
                ):
                    _pred_loss = float(np.sum(QQ[_gi, 1 : NUM_LIVING + 1]))
                    _z = (
                        _pred_loss / BB[_gi]
                        + float(FishMort[_gi])
                        + float(_M0_effective[_gi])
                    )
                    if _z > 0.0:
                        _GE_arr[_gi] = _aeff[_gi] * _z / (_z + 3.0 * _vbk[_gi])

    # Imported diet (EwE-F derivs: qq = consumption + QBoutside * B). A
    # consumer's intake from outside the model is QB * import * B: it grows
    # with the consumer's own biomass and does not depend on local prey, so it
    # bypasses the foraging arena. rsim_params stores the base intake in the
    # link from group 0, so QBoutside = QQbase[0, i] / Bbase[i]. Producers'
    # group-0 link is their primary production and is left alone.
    import_q = np.zeros(NUM_GROUPS + 1)
    _lv = slice(1, NUM_LIVING + 1)
    _imports = (np.asarray(PP_type)[_lv] <= 0) & (Bbase[_lv] > 0) & (QQbase[0, _lv] > 0)
    if _imports.any():
        import_q[_lv][_imports] = (
            QQbase[0, _lv][_imports] / Bbase[_lv][_imports] * BB[_lv][_imports]
        )
        QQ[0, _lv][_imports] = import_q[_lv][_imports]

    _compute_living_derivs(
        deriv,
        QQ,
        BB,
        _M0_effective,
        ForcedMigrate,
        FishMort,
        pp_rates,
        _GE_arr,
        _RecruitmentMult,
        _PP_type_int,
        PB,
        QB,
        _ibm_mask,
        NUM_LIVING,
        NUM_GROUPS,
    )

    # EwE6 migration (audit A1-s2): Immigration flows into a living group and
    # Emig x B leaves it (cEcoSimModel.vb:3081, 3111)
    _immigration = params.get("Immigration")
    _emig = params.get("Emig")
    _living = slice(1, NUM_LIVING + 1)
    emig_loss = np.zeros(NUM_GROUPS + 1)
    immig_gain = np.zeros(NUM_GROUPS + 1)
    if _emig is not None:
        emig_loss[_living] = np.asarray(_emig, dtype=float)[_living] * BB[_living]
        deriv[_living] -= emig_loss[_living]
    if _immigration is not None:
        immig_gain[_living] = np.asarray(_immigration, dtype=float)[_living]
        deriv[_living] += immig_gain[_living]

    if rates is not None:
        food_gain = np.zeros(NUM_GROUPS + 1)
        food_loss = np.zeros(NUM_GROUPS + 1)
        food_gain[1:] = QQ[1:, 1:].sum(axis=0) + import_q[1:]
        food_loss[1:] = QQ[1:, 1 : NUM_LIVING + 1].sum(axis=1)
        mzero_loss = _M0_effective * BB
        fishing_loss = FishMort * BB
        rates["FoodGain"] = food_gain
        rates["FoodLoss"] = food_loss
        rates["MzeroLoss"] = mzero_loss
        rates["FishingLoss"] = fishing_loss
        rates["EmigLoss"] = emig_loss
        rates["LossPropToB"] = food_loss + mzero_loss + fishing_loss + emig_loss
        rates["LossPropToB"][0] = 0.0
        # The living kernel's production x RecruitmentMult, by its branches:
        # a producer's primary production (PP_type as the kernel's int), a
        # consumer's GE x consumption (row 0, the import, included), else
        # PB x B. IBM groups have none.
        _lv = slice(1, NUM_LIVING + 1)
        _production = np.zeros(NUM_GROUPS + 1)
        _production[_lv] = _RecruitmentMult[_lv] * np.where(
            _PP_type_int[_lv] > 0,
            pp_rates[_lv],
            np.where(
                QB[_lv] > 0.0,
                _GE_arr[_lv] * QQ[:, _lv].sum(axis=0),
                PB[_lv] * BB[_lv],
            ),
        )
        _production[_ibm_mask != 0] = 0.0
        rates["Production"] = _production
        rates["Import"] = import_q.copy()
        # Landed catch by group fished, from the fishing links to no detritus
        # pool (a link without a FishTo entry included) plus the forced F,
        # which is landed Outside (fishing_mortality)
        _n_bio = NUM_LIVING + NUM_DEAD
        _landed = np.zeros(NUM_GROUPS + 1)
        _fish_from = np.asarray(FishFrom, dtype=np.int64)[1:]
        _fish_to = np.asarray(params.get("FishTo", np.zeros(len(FishFrom))))
        _dest = np.zeros(len(_fish_from), dtype=np.int64)
        _m = min(len(_fish_to) - 1, len(_dest))
        if _m > 0:
            _dest[:_m] = np.asarray(_fish_to[1 : _m + 1], dtype=np.int64)
        _off = ~((_dest > NUM_LIVING) & (_dest <= _n_bio))
        np.add.at(
            _landed,
            _fish_from[_off],
            np.asarray(_link_fish_rate, dtype=float)[1:][_off] * BB[_fish_from[_off]],
        )
        _forced_f = forcing.get("ForcedF")
        if _forced_f is not None:
            _ff = np.asarray(_forced_f, dtype=float)
            _nf = min(len(_ff), _n_bio + 1)
            _landed[1:_nf] += _ff[1:_nf] * BB[1:_nf]
        if params.get("DetPassedProp") is not None:
            # EwE rule: a pool's catch never leaves the pool (R6), so none of
            # it is landed; FishingLoss still reports it
            _landed[NUM_LIVING + 1 : _n_bio + 1] = 0.0
        rates["Landed"] = _landed

    # Post-kernel instrumentation / debug logging for living groups
    # (kept outside numba kernel because it uses Python objects: strings, logging, etc.)
    _need_instr = bool(instrument_set) or _TRACE_DEBUG_GROUPS is not None

    if _need_instr:
        for i in range(1, NUM_LIVING + 1):
            if i in ibm_groups:
                continue

            # Recompute per-group terms for logging (cheap scalar ops)
            consumption = float(np.sum(QQ[1:, i])) + float(import_q[i])
            predation_loss = float(np.sum(QQ[i, 1 : NUM_LIVING + 1]))
            m0 = float(_M0_effective[i])
            if PP_type[i] > 0:
                production = float(pp_rates[i])
            elif QB[i] > 0:
                production = float(_GE_arr[i] * consumption)
            else:
                production = float(PB[i] * BB[i])

            production *= float(_RecruitmentMult[i])

            # Debug trace for specific groups if requested
            try:
                trace_groups = _TRACE_DEBUG_GROUPS
                if trace_groups is not None and i in trace_groups:
                    name = spname_list[i] if spname_list is not None else None
                    logger.debug(
                        "TRACE DERIV i=%s name=%s production=%.6e predation_loss=%.6e fish_loss=%.6e m0_loss=%.6e deriv=%.6e",
                        i,
                        name,
                        production,
                        predation_loss,
                        FishMort[i] * BB[i],
                        m0 * BB[i],
                        deriv[i],
                    )
            except Exception as e:
                logger.debug("TRACE_DEBUG_GROUPS instrumentation error: %s", e)

            # Instrumentation: detailed per-term breakdown for selected groups
            try:
                if instrument_set and (i - 1) in instrument_set:
                    name = spname_list[i] if spname_list is not None else None
                    unassim_loss = consumption * Unassim[i]
                    fish_loss = FishMort[i] * BB[i]
                    m0_loss = m0 * BB[i]
                    logger.debug(
                        "INSTR DERIV i=%s name=%s production=%.12e consumption=%.12e unassim_loss=%.12e predation_loss=%.12e fish_loss=%.12e m0_loss=%.12e deriv=%.12e",
                        i,
                        name,
                        production,
                        consumption,
                        unassim_loss,
                        predation_loss,
                        fish_loss,
                        m0_loss,
                        deriv[i],
                    )

                    if predation_loss > 0:
                        contribs = []
                        for pred2 in range(1, NUM_LIVING + 1):
                            qval = QQ[i, pred2]
                            if qval > 0:
                                pname = (
                                    spname_list[pred2]
                                    if spname_list is not None
                                    else None
                                )
                                contribs.append((pred2, pname, qval))
                        if contribs:
                            logger.debug("INSTR PREDATORS for prey i={}:".format(i))
                            for pid, pname, qv in contribs:
                                logger.debug(
                                    "  pred=%s name=%s Q=%.12e", pid, pname, qv
                                )
            except Exception as e:
                logger.debug("Instrumentation error in deriv breakdown: %s", e)

    # =========================================================================
    # STEP 5: Calculate derivatives for detritus groups
    # =========================================================================
    # rsim_run passes Rpath's detritus links; use Rpath's budget then.
    _det_link_from = params.get("DetLinkFrom", None)
    if _det_link_from is not None:
        # Discards and DetExport, for the rates only
        _det_flows: Optional[dict] = None if rates is None else {}
        det_gain, det_loss = _rpath_detritus_derivs(
            deriv,
            QQ,
            BB,
            _M0_detritus,
            Unassim,
            _det_link_from,
            params["DetLinkTo"],
            params["DetLinkFrac"],
            FishFrom,
            params.get("FishTo", np.zeros(len(FishFrom))),
            _link_fish_rate,
            NUM_LIVING,
            NUM_DEAD,
            import_q=import_q,
            det_input=_det_inflow(
                params.get("DetInput"), _immigration, NUM_LIVING, NUM_DEAD
            ),
            det_passed_prop=params.get("DetPassedProp"),
            det_ba=params.get("DetBA"),
            det_out=params.get("_det_out"),
            det_emig=_emig,
            pass_on=params.get("_detritus_pass_on", True),
            df_once=params.get("DETRITUS_DF_ONCE", False),
            flows=_det_flows,
            fish_mort=FishMort,
        )
        if rates is not None and _det_flows is not None:
            dead = slice(NUM_LIVING + 1, NUM_LIVING + NUM_DEAD + 1)
            rates["DetGain"] = np.zeros(NUM_GROUPS + 1)
            rates["DetLoss"] = np.zeros(NUM_GROUPS + 1)
            rates["DetGain"][dead] = det_gain[dead]
            rates["DetLoss"][dead] = det_loss[dead]
            rates["Discards"] = np.zeros(NUM_GROUPS + 1)
            rates["Discards"][dead] = _det_flows["Discards"][dead]
            rates["DetExport"] = np.zeros(NUM_GROUPS + 1)
            _export = _det_flows["DetExport"]  # groups 0..NUM_LIVING+NUM_DEAD
            rates["DetExport"][1 : len(_export)] = _export[1:]
            # Rpath TotGain / TotLoss (biomeq = TotGain / (TotLoss / B)).
            # Living gain is all consumption, including a producer's link
            # from group 0; every remaining term of the derivative is loss.
            tot_gain = np.zeros(NUM_GROUPS + 1)
            tot_gain[1 : NUM_LIVING + 1] = (
                QQ[1:, 1 : NUM_LIVING + 1].sum(axis=0) + import_q[1 : NUM_LIVING + 1]
            )
            producers = np.asarray(PP_type[: NUM_LIVING + 1]) > 0
            producers[0] = False
            tot_gain[: NUM_LIVING + 1][producers] = pp_rates[: NUM_LIVING + 1][
                producers
            ]
            tot_gain[dead] = det_gain[dead]
            food_or_pp = tot_gain.copy()
            tot_gain = tot_gain + immig_gain  # Immigration is gain (vb 3112)
            rates["TotGain"] = tot_gain
            rates["TotLoss"] = tot_gain - deriv
            rates["TotLoss"][0] = 0.0
            # EwE6 biomeq terms (cEcoSimModel.vb:3112): a consumer gains its net
            # production SimGE * Eatenby and loses predation, other mortality,
            # fishing and emigration; respiration and egestion are not losses.
            # Producers and detritus keep the terms above.
            net_gain = tot_gain.copy()
            net_loss = rates["TotLoss"].copy()
            cons = np.zeros(NUM_GROUPS + 1, dtype=bool)
            cons[1 : NUM_LIVING + 1] = (~producers[1:]) & (QB[1 : NUM_LIVING + 1] > 0)
            net_gain[cons] = _GE_base[cons] * food_or_pp[cons] + immig_gain[cons]
            net_loss[cons] = (
                _GE_arr[cons] * food_or_pp[cons] * _RecruitmentMult[cons]
                + immig_gain[cons]
                - deriv[cons]
            )
            rates["NetGain"] = net_gain
            rates["NetLoss"] = net_loss
        return deriv

    DetFrac_raw = params.get("DetFrac", np.zeros((NUM_GROUPS + 1, NUM_DEAD + 1)))
    # RsimParams may store detritus fractions in two formats:
    # 1) a full 2D array shaped (NUM_GROUPS+1, NUM_DEAD+1), or
    # 2) a flat link-list array with accompanying DetFrom/DetTo arrays.
    # Handle both formats robustly and normalize to a 2D matrix DetFrac.
    DetFrac = np.asarray(DetFrac_raw)
    if DetFrac.ndim == 2:
        # Already a matrix - ensure full width if it's a single-column or truncated
        if DetFrac.shape != (NUM_GROUPS + 1, NUM_DEAD + 1):
            mat = np.zeros((NUM_GROUPS + 1, NUM_DEAD + 1))
            # copy what we have into the left/top corner
            r = min(mat.shape[0], DetFrac.shape[0])
            c = min(mat.shape[1], DetFrac.shape[1])
            mat[:r, :c] = DetFrac[:r, :c]
            DetFrac = mat

    elif DetFrac.ndim == 1:
        # Link-list format: try to reconstruct a full matrix using DetFrom/DetTo
        det_from = getattr(params, "DetFrom", None)
        det_to = getattr(params, "DetTo", None)
        if det_from is not None and det_to is not None:
            mat = np.zeros((NUM_GROUPS + 1, NUM_DEAD + 1))
            # det_from/det_to are arrays of same length as DetFrac
            for k in range(len(DetFrac)):
                f = int(det_from[k])
                t = int(det_to[k])
                # DetTo is an absolute group index (0 = Outside, otherwise nliving+det_idx)
                if (
                    t >= (NUM_LIVING + 1)
                    and t <= (NUM_LIVING + NUM_DEAD)
                    and f >= 0
                    and f <= NUM_GROUPS
                ):
                    det_col = t - NUM_LIVING  # 1-based detritus column index
                    mat[f, det_col] += DetFrac[k]

            DetFrac = mat
        else:
            # Fallback: treat as single-column per-group values
            DetFrac = DetFrac.reshape((DetFrac.size, 1))
    else:
        # scalar/None or unexpected -> coerce to minimal matrix
        DetFrac = DetFrac.reshape((1, 1))

    # Universal application of fish-derived discard contributions (work for both
    # 2D DetFrac and link-list reconstructions). This centralizes the logic to
    # avoid duplication and eliminate discrepancies between formats.
    try:
        if isinstance(params, dict):
            fish_from = params.get("FishFrom", None)
            fish_to = params.get("FishTo", None)
            fish_q = params.get("FishQ", None)
        else:
            fish_from = getattr(params, "FishFrom", None)
            fish_to = getattr(params, "FishTo", None)
            fish_q = getattr(params, "FishQ", None)
        if fish_from is not None and fish_to is not None and fish_q is not None:
            fish_from = np.asarray(fish_from)
            fish_to = np.asarray(fish_to)
            fish_q = np.asarray(fish_q, dtype=float)

            # Ensure DetFrac has full row coverage for groups
            if DetFrac.shape[0] < NUM_GROUPS + 1:
                new_rows = NUM_GROUPS + 1
                new_cols = max(DetFrac.shape[1], NUM_DEAD + 1)
                new = np.zeros((new_rows, new_cols))
                new[: DetFrac.shape[0], : DetFrac.shape[1]] = DetFrac
                DetFrac = new

            for k in range(len(fish_from)):
                try:
                    f = int(fish_from[k])
                    t = int(fish_to[k])
                    if not (
                        t >= (NUM_LIVING + 1)
                        and t <= (NUM_LIVING + NUM_DEAD)
                        and f >= 0
                        and f <= NUM_GROUPS
                    ):
                        continue
                    det_col = t - NUM_LIVING
                    src_idx = f
                    fish_input = float(fish_q[k]) * float(BB[src_idx])
                    m0_arr = M0_arr if M0_arr is not None else np.zeros(NUM_GROUPS + 1)
                    qb_arr = QB
                    unassim_arr = Unassim

                    m0_pos = max(
                        0.0, float(m0_arr[src_idx]) if src_idx < len(m0_arr) else 0.0
                    )
                    qb_loss = (
                        float(qb_arr[src_idx])
                        if (src_idx < len(qb_arr) and not np.isnan(qb_arr[src_idx]))
                        else 0.0
                    )
                    unassim_val = (
                        float(unassim_arr[src_idx])
                        if src_idx < len(unassim_arr)
                        else 0.0
                    )
                    source_loss = (
                        m0_pos * float(BB[src_idx])
                        + float(BB[src_idx]) * qb_loss * unassim_val
                    )
                    frac = fish_input / (source_loss + 1e-30)
                    if frac > 0:
                        # Make sure DetFrac has enough columns
                        if DetFrac.shape[1] <= det_col:
                            # expand to required width
                            new = np.zeros((DetFrac.shape[0], det_col + 1))
                            new[:, : DetFrac.shape[1]] = DetFrac
                            DetFrac = new
                        DetFrac[src_idx, det_col] += frac
                        if params.get("VERBOSE_DEBUG", False):
                            logger.debug(
                                "DEBUG: added fish-derived DetFrac mat[%s,%s] += %.3e",
                                src_idx,
                                det_col,
                                frac,
                            )
                except Exception as e:
                    if params.get("VERBOSE_DEBUG", False):
                        logger.debug(
                            "DEBUG: failed to add fish-derived DetFrac (unified) for entry %s: %s",
                            k,
                            e,
                        )
                    continue
    except Exception as e:
        logger.debug("Fish-derived DetFrac computation error: %s", e)

    # Pre-compute total consumption by each predator once, avoiding redundant
    # np.sum(QQ[1:, pred]) calls inside the per-detritus-group loop.
    # Shape: (NUM_LIVING,) where index j corresponds to pred = j + 1.
    total_consump_by_pred = (
        np.sum(QQ[1:, 1 : NUM_LIVING + 1], axis=0) + import_q[1 : NUM_LIVING + 1]
    )

    # Pre-fetch detritus decay rates outside the loop
    decay_rate = params.get("DetDecay", np.zeros(NUM_DEAD + 1))
    _decay_rate = np.asarray(decay_rate, dtype=np.float64)

    # Ensure DetFrac is a contiguous 2D float64 array for the numba kernel
    _DetFrac = np.ascontiguousarray(DetFrac, dtype=np.float64)

    # Compute detritus derivatives via numba-accelerated (or pure-Python) kernel
    try:
        _compute_detritus_derivs(
            deriv,
            QQ,
            BB,
            total_consump_by_pred,
            Unassim,
            _DetFrac,
            _M0_detritus,
            _decay_rate,
            NUM_LIVING,
            NUM_DEAD,
        )
    except (IndexError, ValueError):
        # Fallback: rich debug information and re-raise for inspection
        logger.error(
            "ERROR in detritus kernel: QQ.shape=%s DetFrac.shape=%s Unassim.shape=%s "
            "NUM_LIVING=%s NUM_DEAD=%s BB.shape=%s params_keys_sample=%s",
            getattr(QQ, "shape", type(QQ)),
            getattr(_DetFrac, "shape", type(_DetFrac)),
            getattr(Unassim, "shape", type(Unassim)),
            NUM_LIVING,
            NUM_DEAD,
            getattr(BB, "shape", type(BB)),
            list(params.keys())[:10],
        )
        raise

    # Post-kernel detritus instrumentation / debug logging
    for d in range(NUM_LIVING + 1, NUM_LIVING + NUM_DEAD + 1):
        det_idx = d - NUM_LIVING
        try:
            logger.debug(
                "DEBUG DetFrac ndim=%s shape=%s NUM_LIVING=%s NUM_DEAD=%s d=%s det_idx=%s",
                _DetFrac.ndim,
                _DetFrac.shape,
                NUM_LIVING,
                NUM_DEAD,
                d,
                det_idx,
            )
        except (TypeError, ValueError, AttributeError):
            logger.debug("DEBUG DetFrac: unable to inspect shape/ndim")

        try:
            logger.debug(
                "TRACE DETRITUS d=%s det_idx=%s deriv=%.12e",
                d,
                det_idx,
                deriv[d],
            )
        except Exception as e:
            logger.debug("Detritus debug error: %s", e)

        # Instrumentation: print per-pred and per-grp contributions when requested
        try:
            if instrument_set and (d - 1) in instrument_set:
                logger.debug(
                    "INSTR DETRITUS d=%s det_idx=%s -- per-pred unas contributions:",
                    d,
                    det_idx,
                )
                for pred in range(1, NUM_LIVING + 1):
                    total_consump = total_consump_by_pred[pred - 1]
                    contrib = (
                        total_consump
                        * Unassim[pred]
                        * (
                            _DetFrac[pred, det_idx]
                            if _DetFrac.shape[1] > det_idx
                            else 0
                        )
                    )
                    if contrib != 0:
                        pname = spname_list[pred] if spname_list is not None else None
                        logger.debug(
                            "  pred=%s name=%s total_consump=%.12e unassim=%.12e DetFrac=%.12e contrib=%.12e",
                            pred,
                            pname,
                            total_consump,
                            Unassim[pred],
                            _DetFrac[pred, det_idx],
                            contrib,
                        )

                logger.debug(
                    "INSTR DETRITUS d=%s det_idx=%s -- per-grp mort contributions:",
                    d,
                    det_idx,
                )
                _m0_vals = M0_arr if M0_arr is not None else np.zeros(NUM_GROUPS + 1)
                for grp in range(1, NUM_LIVING + 1):
                    contrib = (
                        _m0_vals[grp]
                        * BB[grp]
                        * (_DetFrac[grp, det_idx] if _DetFrac.shape[1] > det_idx else 0)
                    )
                    if contrib != 0:
                        gname = spname_list[grp] if spname_list is not None else None
                        logger.debug(
                            "  grp=%s name=%s M0=%.12e BB=%.12e DetFrac=%.12e contrib=%.12e",
                            grp,
                            gname,
                            _m0_vals[grp],
                            BB[grp],
                            _DetFrac[grp, det_idx],
                            contrib,
                        )
        except Exception as e:
            logger.debug("Detritus instrumentation error: %s", e)

    return deriv

log_mean

log_mean(a, b)

(b - a) / ln(b / a) elementwise, the mean of an exponential path from a to b (Rpath 1.2.0's catch smoother); a where the two are within 1e-9 of a (Rpath's BIG_EPSILON) or either is not positive.

Source code in pypath/core/ecosim_deriv.py
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
def log_mean(a, b):
    """(b - a) / ln(b / a) elementwise, the mean of an exponential path from
    a to b (Rpath 1.2.0's catch smoother); a where the two are within 1e-9
    of a (Rpath's BIG_EPSILON) or either is not positive."""
    a, b = np.broadcast_arrays(np.asarray(a, dtype=float), np.asarray(b, dtype=float))
    flat_a, flat_b = a.ravel(), b.ravel()
    out = flat_a.copy()
    go = np.flatnonzero(
        (np.abs(flat_b - flat_a) >= flat_a * 1.0e-9) & (flat_a > 0) & (flat_b > 0)
    )
    # written a x / log1p(x), x = (b - a) / a: (b - a) / log(b / a) loses
    # about 1e-10 when b is within 1e-6 of a (rounding b / a), and would
    # magnify a last-bit difference of b; scalar math as the compiled loop
    for i in go:
        x = (flat_b[i] - flat_a[i]) / flat_a[i]
        if x <= -0.5:  # a large drop: log1p(x) would reach log1p(-1)
            out[i] = (flat_b[i] - flat_a[i]) / (
                math.log(flat_b[i]) - math.log(flat_a[i])
            )
        else:
            out[i] = flat_a[i] * x / math.log1p(x)
    return out.reshape(a.shape)

integrate_rk4

integrate_rk4(state: ndarray, params: dict, forcing: dict, fishing: dict, dt: float, n_steps: int = 1, stage_rates: Optional[dict] = None, catch_bio: Optional[ndarray] = None) -> np.ndarray

Runge-Kutta 4th order integration step.

catch_bio, when given (one value per state entry), receives per sub-step its length times the log mean of its start and end biomass (before the clamp): F times it is the step's catch as Rpath 1.2.0 books it (its cum_Catch).

Parameters:

Name Type Description Default
state ndarray

Current state vector

required
params dict

Model parameters

required
forcing dict

Forcing arrays

required
fishing dict

Fishing parameters

required
dt float

Time step

required
n_steps int

Number of RK4 sub-steps of dt / n_steps (Rpath RK4_STEPS).

1
stage_rates dict

Filled with the derivative's rates at the first stage of the first sub-step ("first", the start state) and at the last stage of the last sub-step ("last", y + h k3): what EwE6's monthly stanza update reads (rsim_run, STANZA_STAGE_RATES).

None

Returns:

Type Description
ndarray

Updated state vector

Source code in pypath/core/ecosim_deriv.py
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
def integrate_rk4(
    state: np.ndarray,
    params: dict,
    forcing: dict,
    fishing: dict,
    dt: float,
    n_steps: int = 1,
    stage_rates: Optional[dict] = None,
    catch_bio: Optional[np.ndarray] = None,
) -> np.ndarray:
    """
    Runge-Kutta 4th order integration step.

    ``catch_bio``, when given (one value per state entry), receives per
    sub-step its length times the log mean of its start and end biomass
    (before the clamp): F times it is the step's catch as Rpath 1.2.0
    books it (its ``cum_Catch``).

    Parameters
    ----------
    state : np.ndarray
        Current state vector
    params : dict
        Model parameters
    forcing : dict
        Forcing arrays
    fishing : dict
        Fishing parameters
    dt : float
        Time step
    n_steps : int, optional
        Number of RK4 sub-steps of ``dt / n_steps`` (Rpath ``RK4_STEPS``).
    stage_rates : dict, optional
        Filled with the derivative's ``rates`` at the first stage of the
        first sub-step (``"first"``, the start state) and at the last stage
        of the last sub-step (``"last"``, y + h k3): what EwE6's monthly
        stanza update reads (``rsim_run``, ``STANZA_STAGE_RATES``).

    Returns
    -------
    np.ndarray
        Updated state vector
    """
    # n_steps sub-steps of dt/n_steps (Rpath RK4_STEPS), biomass clamped per
    # step. Fast-equilibrium groups (NoIntegrate = 1) follow EwE6's rk4: at
    # every stage, and after the step, their value is
    # (1 - SorWt) * biomeq + SorWt * B with biomeq = gain / (loss / B) from
    # the derivative just evaluated, so a P/B of 200 or a detritus pool that
    # turns over thousands of times a year never meets an explicit sub-step.
    # Rpath's rk4_run integrates every group (RK4_FAST_EQUILIBRIUM False).
    n_steps = max(1, int(n_steps))
    hh = dt / n_steps
    new_state = np.asarray(state, dtype=float)
    fast_mask = _rk4_fast_mask(params, len(new_state))
    use_fast = bool(np.any(fast_mask))
    sorwt = float(params.get("SorWt", 0.5)) if isinstance(params, dict) else 0.5

    def _stage(y_base, y_eval, k, factor, rates):
        """Stage state y_base + factor * k, fast groups at their equilibrium."""
        yt = y_base + factor * k
        if use_fast:
            yt[fast_mask] = _rk4_fast_equilibrium(
                rates, y_eval, y_base, fast_mask, sorwt
            )
        return yt

    want_stages = stage_rates is not None
    for sub in range(n_steps):
        y0 = new_state
        r1 = {} if (use_fast or (want_stages and sub == 0)) else None
        k1 = deriv_vector(y0, params, forcing, fishing, rates=r1)
        if want_stages and sub == 0:
            stage_rates["first"] = r1
        y1 = _stage(y0, y0, k1, 0.5 * hh, r1)
        r2 = {} if use_fast else None
        k2 = deriv_vector(y1, params, forcing, fishing, rates=r2)
        y2 = _stage(y0, y1, k2, 0.5 * hh, r2)
        r3 = {} if use_fast else None
        k3 = deriv_vector(y2, params, forcing, fishing, rates=r3)
        y3 = _stage(y0, y2, k3, hh, r3)
        r4 = {} if (use_fast or want_stages) else None
        k4 = deriv_vector(y3, params, forcing, fishing, rates=r4)
        if want_stages:
            stage_rates["last"] = r4
        new_state = y0 + (hh / 6.0) * (k1 + 2 * k2 + 2 * k3 + k4)
        if use_fast:
            new_state[fast_mask] = _rk4_fast_equilibrium(r4, y3, y0, fast_mask, sorwt)
        if catch_bio is not None:
            catch_bio += hh * log_mean(y0, new_state)
        new_state = np.maximum(new_state, 0.0)
    dt = hh  # instrumentation below reports the last sub-step
    state = y0

    # Instrumentation: allow callers to obtain compact RK4 stage diagnostics via
    # params.instrument_callback (similar to AB instrumentation). Compute per-stage
    # QQ totals for requested groups and call the callback with a small payload.
    try:
        instr_groups = params.get("INSTRUMENT_GROUPS", None)
        cb = params.get("instrument_callback", None)
        if cb is None:
            cb = globals().get("_last_instrument_callback", None)
        if instr_groups is not None and cb is not None:
            # Resolve numeric or named groups to 0-based indices (reuse AB logic)
            idxs = set()
            spname = params.get("spname", None)
            if isinstance(instr_groups, (list, tuple)) and all(
                isinstance(x, (int, np.integer)) for x in instr_groups
            ):
                nums = [int(x) for x in instr_groups]
                max_idx = len(state) - 1
                try:
                    if (
                        nums
                        and any(v > max_idx for v in nums)
                        and all(1 <= v <= max_idx + 1 for v in nums)
                    ):
                        nums = [v - 1 for v in nums]
                except (TypeError, ValueError):
                    pass
                idxs.update(int(x) for x in nums)
            else:
                # Prefer mapping via model DataFrame when available for stable
                # group ordering; otherwise fallback to spname mapping.
                model_df = params.get("model", None)
                for g in instr_groups:
                    if isinstance(g, str):
                        if (
                            model_df is not None
                            and hasattr(model_df, "columns")
                            and "Group" in model_df.columns
                        ):
                            groups_list = list(model_df["Group"])
                            if g in groups_list:
                                idxs.add(groups_list.index(g))
                                continue
                        if spname is not None and g in spname:
                            sp_idx = spname.index(g)
                            if sp_idx > 0:
                                idxs.add(sp_idx - 1)
                    else:
                        try:
                            val = int(g)
                            idxs.add(val)
                        except (TypeError, ValueError):
                            pass
            if idxs:
                max_idx = len(state) - 1
                valid_idxs = sorted(i for i in idxs if 0 <= i <= max_idx)
                if valid_idxs:
                    # Compute QQ totals for each RK4 stage for the requested groups
                    try:
                        from pypath.core.ecosim import _compute_Q_matrix

                        stages = [
                            state,
                            state + 0.5 * dt * k1,
                            state + 0.5 * dt * k2,
                            state + dt * k3,
                        ]
                        stage_totals = []
                        for st in stages:
                            QQs = _compute_Q_matrix(
                                params, st, {"Ftime": np.ones_like(st)}
                            )
                            totals = [
                                float(np.nansum(QQs[:, i + 1])) for i in valid_idxs
                            ]
                            stage_totals.append(totals)

                        parent = (
                            params.get("_integration_parent_method")
                            if isinstance(params, dict)
                            else None
                        )
                        payload_method = parent if parent is not None else "RK4"
                        # Helpful debug: when used as a warmup for another method
                        # we may want to inspect resolved group indices to ensure
                        # name->index mapping matches caller expectations.

                        payload = {
                            "method": payload_method,
                            "groups": valid_idxs,
                            "stage_consumption_totals": stage_totals,
                            "dt": float(dt),
                        }
                        # If this RK4 call is being used solely as a warmup for
                        # another integrator (e.g., AB), skip invoking the
                        # instrumentation callback here to avoid confusing
                        # caller expectations about the payload contents
                        # (AB expects 'deriv_current' which RK4-stage payloads
                        # do not provide). This keeps the first instrumentation
                        # payload relevant to AB runs as the AB payload.
                        if parent is None:
                            cb(payload)
                        else:
                            logger.debug(
                                "INSTRUMENT-TRACE: skipping RK4-stage callback when used as warmup for parent=%s",
                                parent,
                            )
                    except Exception as e:
                        logger.debug("RK4 instrumentation error: %s", e)
    except Exception as e:
        logger.debug("RK4 outer instrumentation error: %s", e)

    return new_state

compute_biomeq

compute_biomeq(total_gain, total_loss, biomass, sorwt=0.5)

Compute fast-equilibrium biomass for NoIntegrate groups.

Rpath formula: biomeq = TotGain / (TotLoss / B) Then: new_B = (1-SORWT)biomeq + SORWTold_B

Source code in pypath/core/ecosim_deriv.py
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
def compute_biomeq(total_gain, total_loss, biomass, sorwt=0.5):
    """Compute fast-equilibrium biomass for NoIntegrate groups.

    Rpath formula: biomeq = TotGain / (TotLoss / B)
    Then: new_B = (1-SORWT)*biomeq + SORWT*old_B
    """
    if total_loss <= 0 or biomass <= 0:
        return biomass
    loss_rate = total_loss / biomass
    biomeq = total_gain / loss_rate
    return (1.0 - sorwt) * biomeq + sorwt * biomass

integrate_ab

integrate_ab(state: ndarray, derivs_history: list, params: dict, forcing: dict, fishing: dict, dt: float) -> Tuple[np.ndarray, np.ndarray]

Adams-Bashforth integration step.

Uses 2-step Adams-Bashforth method (matching Rpath) when history is available, falls back to Euler with no history.

Parameters:

Name Type Description Default
state ndarray

Current state vector

required
derivs_history list

List of previous derivative vectors (most recent first)

required
params dict

Model parameters

required
forcing dict

Forcing arrays

required
fishing dict

Fishing parameters

required
dt float

Time step

required

Returns:

Type Description
Tuple[ndarray, ndarray]

Updated state vector and new derivative

Source code in pypath/core/ecosim_deriv.py
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
def integrate_ab(
    state: np.ndarray,
    derivs_history: list,
    params: dict,
    forcing: dict,
    fishing: dict,
    dt: float,
) -> Tuple[np.ndarray, np.ndarray]:
    """
    Adams-Bashforth integration step.

    Uses 2-step Adams-Bashforth method (matching Rpath) when history is
    available, falls back to Euler with no history.

    Parameters
    ----------
    state : np.ndarray
        Current state vector
    derivs_history : list
        List of previous derivative vectors (most recent first)
    params : dict
        Model parameters
    forcing : dict
        Forcing arrays
    fishing : dict
        Fishing parameters
    dt : float
        Time step

    Returns
    -------
    Tuple[np.ndarray, np.ndarray]
        Updated state vector and new derivative
    """
    # Calculate current derivative
    deriv_current = deriv_vector(state, params, forcing, fishing)
    deriv_current = _sanitize_deriv(deriv_current)

    n_history = len(derivs_history)

    if n_history >= 1:
        # 2-step Adams-Bashforth (matches Rpath)
        # y_{n+1} = y_n + dt/2 * (3*f_n - f_{n-1})
        new_state = state + (dt / 2.0) * (
            3.0 * deriv_current - _sanitize_deriv(np.asarray(derivs_history[0]))
        )
    else:
        # Euler method (first step)
        new_state = state + dt * deriv_current

    # Rpath-style bounds: pmax(pmin(B, Bref*BIGNUM), Bref*EPSILON)
    Bbase = params.get("Bbase", state)
    EPSILON = 1e-15
    BIGNUM = 1e15
    pos_mask = Bbase[1:] > 0
    new_state[1:] = np.where(
        pos_mask,
        np.clip(new_state[1:], Bbase[1:] * EPSILON, Bbase[1:] * BIGNUM),
        np.maximum(new_state[1:], 0.0),
    )

    # Enforce NoIntegrate groups stay at baseline (if provided in params)
    try:
        no_integrate = (
            np.asarray(params.get("NoIntegrate", np.zeros(len(new_state)))) != 0
        )
        if np.any(no_integrate):
            Bbase_ni = params.get("Bbase")
            if Bbase_ni is not None:
                new_state[no_integrate] = Bbase_ni[no_integrate]
                deriv_current[no_integrate] = 0.0
    except (TypeError, ValueError, IndexError):
        pass

    # Instrumentation callback: if caller requested group-level instrumentation
    # (e.g., params.INSTRUMENT_GROUPS = ['Macrobenthos'] and provided
    # params.instrument_callback callable), call the callback with compact
    # numeric arrays to allow unit tests / debugging harnesses to inspect
    # intermediate AB behavior without parsing verbose logs.
    try:
        instr_groups = params.get("INSTRUMENT_GROUPS", None)
        # Prefer the original attribute-based INSTRUMENT_GROUPS (exported by rsim_run)
        # if present; this helps in cases where the params dict has been mutated
        # during warmup or other computations.
        # Ensure NUM_GROUPS is available for legacy numeric instrument group checks
        NUM_GROUPS = params.get("NUM_GROUPS", None)
        try:
            attr_ig = globals().get("_last_instrument_groups", None)
            if attr_ig is not None:
                # If attr_ig differs from the dict value, prefer the attribute
                # (it represents the caller's original intention).
                if instr_groups is None or instr_groups != attr_ig:
                    # If the attribute appears to be a numeric legacy 1-based
                    # list, convert it aggressively here so caller intent is
                    # preserved and a DeprecationWarning is emitted.
                    try:
                        if isinstance(attr_ig, (list, tuple)) and all(
                            isinstance(x, (int, float, np.integer)) for x in attr_ig
                        ):
                            nums = [int(x) for x in attr_ig]
                            # Convert numeric 1-based indices only when caller explicitly
                            # opts in via INSTRUMENT_ASSUME_1BASED or when numbers exceed
                            # the valid 0-based range but are within plausible 1-based
                            # bounds (1..NUM_GROUPS).
                            assume_flag = params.get("INSTRUMENT_ASSUME_1BASED", False)
                            if nums and (
                                assume_flag
                                or (
                                    any(v > NUM_GROUPS - 1 for v in nums)
                                    and all(1 <= v <= NUM_GROUPS for v in nums)
                                )
                            ):
                                import warnings as _warnings

                                _warnings.warn(
                                    "Numeric INSTRUMENT_GROUPS indices are expected to be 0-based. "
                                    "Detected probable 1-based indices — converting to 0-based for now. "
                                    "Please update your code to use 0-based indices.",
                                    DeprecationWarning,
                                    stacklevel=3,
                                )
                                nums = [v - 1 for v in nums]
                                instr_groups = nums
                                # write back normalization to params dict/attr if possible
                                try:
                                    params["INSTRUMENT_GROUPS"] = instr_groups
                                except (TypeError, KeyError):
                                    try:
                                        setattr(
                                            params, "INSTRUMENT_GROUPS", instr_groups
                                        )
                                    except (TypeError, AttributeError):
                                        pass
                            else:
                                instr_groups = attr_ig
                        else:
                            instr_groups = attr_ig
                    except (TypeError, ValueError):
                        instr_groups = attr_ig
        except (TypeError, ValueError):
            pass

        # Resolve instrumentation callback: prefer per-call params dict value, fallback
        # to module-level last-known callback (set by rsim_run) to handle callsites
        # that attach the callback as an attribute on the params object instead
        # of the params dict (legacy code paths).
        cb = params.get("instrument_callback", None)
        if cb is None:
            # Module-level fallback (set by rsim_run if available)
            try:
                cb = globals().get("_last_instrument_callback", None)
                if cb is not None:
                    logger.debug("INSTRUMENT: using module-level fallback callback")
            except (TypeError, AttributeError):
                cb = None
        # Print debug info without referencing undefined symbols
        try:
            logger.debug(
                "INSTRUMENT-DEBUG: instr_groups=%s cb_present=%s cb=%s",
                instr_groups,
                cb is not None,
                cb,
            )
        except (TypeError, ValueError):
            pass
        # Only proceed if caller requested instrumentation via instr_groups
        # and a callback is available.
        if instr_groups is not None and cb is not None:
            # Prefer a pre-normalized numeric list (0-based indices) when provided
            idxs = set()
            spname = params.get("spname", None)
            # If instr_groups is a list of numeric indices (possibly normalized),
            # use them directly; otherwise try to resolve names to indices.
            try:
                # treat as numeric list when all elements are ints
                if isinstance(instr_groups, (list, tuple)) and all(
                    isinstance(x, (int, np.integer)) for x in instr_groups
                ):
                    # Detailed tracing for numeric-based instrument group resolution
                    nums = [int(x) for x in instr_groups]
                    max_idx = len(state) - 1
                    try:
                        logger.debug(
                            "INSTRUMENT-TRACE: before conversion nums=%s max_idx=%s instr_groups_id=%s params_has=%s _last_instrument_groups=%s",
                            nums,
                            max_idx,
                            id(instr_groups),
                            (
                                "INSTRUMENT_GROUPS" in params
                                if isinstance(params, dict)
                                else hasattr(params, "INSTRUMENT_GROUPS")
                            ),
                            globals().get("_last_instrument_groups", None),
                        )
                    except (TypeError, ValueError):
                        pass

                    # Avoid double-conversion: assume numeric lists are already 0-based
                    # unless they contain values outside the valid 0-based range.
                    # Only convert if some values exceed the max 0-based index but are
                    # within the plausible 1-based range (1..max_idx+1).
                    try:
                        if (
                            nums
                            and any(v > max_idx for v in nums)
                            and all(1 <= v <= max_idx + 1 for v in nums)
                        ):
                            import warnings as _warnings

                            logger.debug(
                                "INSTRUMENT-TRACE: detected probable 1-based numeric indices %s; converting to 0-based",
                                nums,
                            )
                            _warnings.warn(
                                "Numeric INSTRUMENT_GROUPS indices are expected to be 0-based. "
                                "Detected probable 1-based indices — converting to 0-based for now. "
                                "Please update your code to use 0-based indices.",
                                DeprecationWarning,
                                stacklevel=3,
                            )
                            nums = [v - 1 for v in nums]
                    except (TypeError, ValueError):
                        pass

                    try:
                        logger.debug(
                            "INSTRUMENT-TRACE: after conversion (or no conversion) nums=%s",
                            nums,
                        )
                    except (TypeError, ValueError):
                        pass

                    # Update idxs with the resolved numeric values (assume normalized unless converted above)
                    idxs.update(int(x) for x in nums)
                    try:
                        logger.debug(
                            "INSTRUMENT-TRACE: idxs updated -> %s (raw), params['INSTRUMENT_GROUPS']=%s",
                            sorted(idxs),
                            (
                                params.get("INSTRUMENT_GROUPS", None)
                                if isinstance(params, dict)
                                else getattr(params, "INSTRUMENT_GROUPS", None)
                            ),
                        )
                    except (TypeError, ValueError):
                        pass
                else:
                    model_df = params.get("model", None)
                    for g in instr_groups:
                        if isinstance(g, str):
                            # Prefer model-defined ordering when available
                            if (
                                model_df is not None
                                and hasattr(model_df, "columns")
                                and "Group" in model_df.columns
                            ):
                                groups_list = list(model_df["Group"])
                                if g in groups_list:
                                    idxs.add(groups_list.index(g))
                                    continue
                            if spname is not None and g in spname:
                                sp_idx = spname.index(g)
                                if sp_idx > 0:
                                    idxs.add(sp_idx - 1)
                        else:
                            try:
                                val = int(g)
                                idxs.add(val)
                            except (TypeError, ValueError):
                                pass
            except (TypeError, ValueError):
                # Best-effort: if resolution fails, leave idxs empty
                idxs = set()
            # Filter indices to valid range and sort
            if idxs:
                max_idx = len(state) - 1
                valid_idxs = sorted(i for i in idxs if 0 <= i <= max_idx)

                # If we exported caller attribute INSTRUMENT_GROUPS earlier, use it
                # only as a fallback when dict-derived resolution failed. This avoids
                # preferring older caller attribute values that may be legacy 1-based
                # and lead to conflicting normalization choices.
                try:
                    attr_ig = globals().get("_last_instrument_groups", None)
                    if attr_ig is not None:
                        alt_idxs = set()
                        # Resolve attribute-provided groups similarly to dict ones
                        if isinstance(attr_ig, (list, tuple)):
                            if all(isinstance(x, (int, np.integer)) for x in attr_ig):
                                nums = [int(x) for x in attr_ig]
                                # Only convert attribute-provided numeric 1-based indices
                                # when caller explicitly opts in via INSTRUMENT_ASSUME_1BASED
                                if params.get("INSTRUMENT_ASSUME_1BASED", False):
                                    if (
                                        nums
                                        and any(v > max_idx for v in nums)
                                        and all(1 <= v <= max_idx + 1 for v in nums)
                                    ):
                                        import warnings as _warnings

                                        _warnings.warn(
                                            "Numeric INSTRUMENT_GROUPS indices are expected to be 0-based. "
                                            "Detected probable 1-based indices — converting to 0-based for now. "
                                            "Please update your code to use 0-based indices.",
                                            DeprecationWarning,
                                            stacklevel=3,
                                        )
                                        nums = [v - 1 for v in nums]
                                alt_idxs.update(int(x) for x in nums)
                            else:
                                for g in attr_ig:
                                    if (
                                        isinstance(g, str)
                                        and spname is not None
                                        and g in spname
                                    ):
                                        sp_idx = spname.index(g)
                                        if sp_idx > 0:
                                            alt_idxs.add(sp_idx - 1)
                                    else:
                                        try:
                                            val = int(g)
                                            alt_idxs.add(val)
                                        except (TypeError, ValueError):
                                            pass
                        elif isinstance(attr_ig, str) and spname is not None:
                            if attr_ig in spname:
                                sp_idx = spname.index(attr_ig)
                                if sp_idx > 0:
                                    alt_idxs.add(sp_idx - 1)

                        # Prefer attribute-derived indices when available (it represents
                        # the caller's original intent), falling back to dict-derived
                        # resolution only when attribute resolution fails.
                        alt_valid = sorted(i for i in alt_idxs if 0 <= i <= max_idx)
                        if alt_valid:
                            logger.debug(
                                "INSTRUMENT-TRACE: preferring attr_ig alt_valid=%s over dict-derived valid_idxs=%s",
                                alt_valid,
                                valid_idxs,
                            )
                            valid_idxs = alt_valid
                            # Also write back the normalized groups into params when possible
                            try:
                                normalized = list(valid_idxs)
                                try:
                                    params["INSTRUMENT_GROUPS"] = normalized
                                except (TypeError, KeyError):
                                    try:
                                        setattr(params, "INSTRUMENT_GROUPS", normalized)
                                    except (TypeError, AttributeError):
                                        pass
                                logger.debug(
                                    "INSTRUMENT-TRACE: wrote normalized attr_ig back to params: %s",
                                    normalized,
                                )
                            except (TypeError, ValueError):
                                pass
                except (TypeError, ValueError):
                    pass
                if valid_idxs:
                    idx_list = valid_idxs
                    # Collect history for these groups (may be empty)
                    hist = [np.asarray(h)[idx_list].tolist() for h in derivs_history]
                    payload = {
                        "method": "AB",
                        "groups": idx_list,
                        "deriv_current": np.asarray(deriv_current)[idx_list].tolist(),
                        "derivs_history": hist,
                        "new_state": np.asarray(new_state)[idx_list].tolist(),
                        "dt": float(dt),
                    }
                try:
                    try:
                        if (
                            isinstance(params, dict)
                            and params.get("VERBOSE_INSTRUMENTATION")
                        ) or getattr(params, "VERBOSE_INSTRUMENTATION", False):
                            logger.debug(
                                "INSTRUMENT-TRACE-PAYLOAD: idx_list=%s state_len=%s deriv_slice=%s new_state_slice=%s cb=%s params_INSTRUMENT_GROUPS=%s _last_instrument_groups=%s",
                                idx_list,
                                len(state),
                                np.asarray(deriv_current)[idx_list].tolist(),
                                np.asarray(new_state)[idx_list].tolist(),
                                cb,
                                (
                                    params.get("INSTRUMENT_GROUPS", None)
                                    if isinstance(params, dict)
                                    else getattr(params, "INSTRUMENT_GROUPS", None)
                                ),
                                globals().get("_last_instrument_groups", None),
                            )
                    except (TypeError, ValueError):
                        pass
                    logger.debug("INSTRUMENT: calling callback groups=%s", idx_list)
                    cb(payload)
                except Exception as e:
                    # Don't allow instrumentation failures to break integration
                    logger.debug("Instrumentation callback failed: %s", e)
    except Exception as e:
        logger.debug("AB outer instrumentation error: %s", e)

    return new_state, deriv_current

run_ecosim

run_ecosim(initial_state: ndarray, params: dict, forcing: dict, fishing: dict, years: float, dt: float = 1 / 12, method: str = 'ab', save_interval: int = 1) -> dict

Run Ecosim simulation.

Parameters:

Name Type Description Default
initial_state ndarray

Initial biomass vector

required
params dict

Model parameters

required
forcing dict

Forcing arrays

required
fishing dict

Fishing parameters

required
years float

Number of years to simulate

required
dt float

Time step (fraction of year)

1 / 12
method str

Integration method ('rk4' or 'ab')

'ab'
save_interval int

Save state every N steps

1

Returns:

Type Description
dict

Results containing: - time: Time points - biomass: Biomass time series [time, group] - catch: Catch time series [time, group]

Source code in pypath/core/ecosim_deriv.py
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
def run_ecosim(
    initial_state: np.ndarray,
    params: dict,
    forcing: dict,
    fishing: dict,
    years: float,
    dt: float = 1 / 12,  # Monthly time step
    method: str = "ab",  # 'rk4' or 'ab'
    save_interval: int = 1,
) -> dict:
    """
    Run Ecosim simulation.

    Parameters
    ----------
    initial_state : np.ndarray
        Initial biomass vector
    params : dict
        Model parameters
    forcing : dict
        Forcing arrays
    fishing : dict
        Fishing parameters
    years : float
        Number of years to simulate
    dt : float
        Time step (fraction of year)
    method : str
        Integration method ('rk4' or 'ab')
    save_interval : int
        Save state every N steps

    Returns
    -------
    dict
        Results containing:
        - time: Time points
        - biomass: Biomass time series [time, group]
        - catch: Catch time series [time, group]
    """
    n_steps = int(years / dt)
    n_groups = len(initial_state)

    # Initialize output arrays
    save_times = list(range(0, n_steps + 1, save_interval))
    n_saves = len(save_times)

    time_out = np.zeros(n_saves)
    biomass_out = np.zeros((n_saves, n_groups))

    # Initialize state
    state = initial_state.copy()
    derivs_history = []  # For Adams-Bashforth

    # Save initial state
    save_idx = 0
    time_out[save_idx] = 0.0
    biomass_out[save_idx] = state
    save_idx += 1

    # Main integration loop
    for step in range(1, n_steps + 1):
        t = step * dt

        # Update forcing for current time if time-varying
        # (This would interpolate forcing arrays to current time)

        if method == "rk4":
            state = integrate_rk4(state, params, forcing, fishing, dt)
        else:  # Adams-Bashforth
            state, new_deriv = integrate_ab(
                state, derivs_history, params, forcing, fishing, dt
            )
            # Update history (keep last 3)
            derivs_history.insert(0, new_deriv)
            if len(derivs_history) > 3:
                derivs_history.pop()

        # Save if at save interval
        if step in save_times:
            time_out[save_idx] = t
            biomass_out[save_idx] = state
            save_idx += 1

    return {
        "time": time_out,
        "biomass": biomass_out,
        "years": years,
        "dt": dt,
        "method": method,
    }

Continuous Integration Pathway

rsim_run(scenario, method="lsoda") (or "dop853", "radau", "bdf") solves the continuous Ecosim equations month by month with SciPy's solve_ivp. The month's forcing, effort, forced F or catch and forced biomass are held; feeding time is a state (dFt/dt = 12 (clip(target) - Ft) for groups with FtimeAdj > 0) and RiskTime is instantaneous. Stanza updates and fleet dynamics run at the month boundaries; the stanza update and the catch use the month's quadrature means (6-point Gauss-Legendre of the dense output); fleet dynamics does not. The pathway applies the defect corrections (R2, R4, R5, detritus fate applied once), solves handling time exactly from a recalibrated Hden0 on a vectorised kernel, and interpolates EwE's mediation lookup in float64, so it differs from EwE by design. Options go in solver_options (anything else raises ValueError naming the key): rtol, atol (the default follows rtol), corrections (False leaves out R2, R4, R5 and DF once), on_failure, hden_tol (the handling-time tolerance, default 1e-12, in (0, 1e-8]) and the options below.

  • jacobian: "reuse" (default) or "solver". LSODA, Radau and BDF reuse the finite-difference Jacobian across the monthly restarts, a fresh one costing n_state + 1 evaluations; with "reuse" LSODA's nfev no longer counts the Jacobian columns, so compare cost by rhs_evals. Per month jac_fresh and jac_reused.
  • forcing_interpolation: "constant" (default), "linear" or "smooth". Linear and smooth change the model: they replace the month-held forcing by a mean-preserving tent or quadratic. Effort stays held monthly.
  • positivity: "clip" (default) or "log" (log-transformed biomass states, the same equations).
  • fast_groups: "states" (default) or "quasi-steady", with qs_rate (per year, default 365). Quasi-steady changes the model: the selected fast groups are solved for their equilibrium instead of integrated, which suits DOP853; see qs_groups and qs_separation (a WARNING below 10) in solver_info.

Which method: LSODA is the default; use BDF for stiff models (LT2022: 11.3 x RK4 against 17.3 x on LSODA on the Python consumption loop (numba not installed, or PYPATH_NUMBA_CONSUMPTION=0); 32.5-33.3 x against 50.5-54.1 x with numba's consumption kernel, where RK4 runs about 2-3 x faster, measured 2026-11-17); DOP853 for non-stiff models and under quasi-steady groups.

RsimOutput.solver_info records the corrections that act, the EwE numerics switches ignored, atol (the biomass atol; atol_ftime lists the feeding-time states' atol, the tail of the solver's vector), rhs_evals, ftime_groups and per-month solver statistics: nfev, steps, degraded (a month whose means fell back to the start state), hden_passes_max, hden_residual_max (the largest relative residual of the solved handling time), kernel_check (the vectorised consumption pass against the link loop), ftime_range, last_step (the month's last full step; every month leaves its first step to the solver), and the mass budget: budget_residual and pool_budget_residual (None in a month with forced biomass, and under quasi-steady groups; the month residual has a floor of about 1e-9 from the quadrature, it is not a leak), nutrient_floor and negative_export. A failed month raises RuntimeError naming the month. out_Catch is the integral of F x B over the month; EwE's month-end booking is in out_Catch_month_end. Pooled models (ScrambleSelf > 0) now use Rpath's scramble weights on every method. docs/parity/continuous_path.md has the options, the corrections, the validation and the cost.

out = rsim_run(scenario, method="lsoda", solver_options={"rtol": 1e-8})
out.solver_info["corrections"]

pypath.core.ecosim_continuous

Continuous integration pathway for Ecosim (independent of the EwE pathway).

The pathway's pieces: the handling-time solver (solve_hden_kernel, with solve_hden its full-derivative reference), the pure right-hand side (ContinuousRHS) and the month integrator (integrate_month) that rsim_run calls for the continuous methods. Under EwE's rule the derivative scales each predator's search rate by Hden0 / Hden where Hden satisfies the disc-equation fixed point

Hden = 1 + Hden * q(Hden) / (CmCo * QB * index)

EwE takes one damped pass of that per derivative call; here it is solved exactly at each state, on the consumption kernel alone (HdenKernel), with a safeguarded Newton per predator on the kernel's analytic dq/dH (iterate_hden), or undamped passes where pooling couples the predators.

The package's modules, by responsibility: options (continuous_options, METHOD_NAMES, the option modes, default_atol), hden (handling time), forcing (neutral_forcing, ForcingInterpolant), feeding (feeding time), rhs (ContinuousRHS, exchange_rate), jacobian (JacobianReuse), quasi_steady (QuasiSteady) and month (integrate_month, MonthResult, month_budget). Every public name is re-exported here. A module global (solve_ivp, deriv_vector, root, solve_hden_kernel, _ATOL_Z_MAX) is read by the submodule that uses it, so a test that monkeypatches one patches that submodule: setting this package's attribute does not reach it.

ForcingInterpolant

Mean-preserving interpolation of monthly forcing inside each month.

monthly maps a forcing key to its monthly values, an array of shape (n_months, ...) (the same n_months for every key, else ValueError); the arrays are copied, never written. Months are 0-based: month k is row k, and s in [0, 1] (clipped) is the fraction of the month.

The boundary values: inside the series b_k = min((m_{k-1} + m_k) / 2, 2 m_{k-1}, 2 m_k) for a non-negative key and (m_{k-1} + m_k) / 2 for a key in signed; at the ends b_0 = m_0 and b_N = m_{N-1}, so nothing past the series is read. With kind="linear" month k is a continuous tent through (0, b_k), (1/2, c_k) and (1, b_{k+1}), c_k = 2 m_k - (b_k + b_{k+1}) / 2; it has a kink at mid-month. With kind="smooth" it is one quadratic, b_k (1 - s) + b_{k+1} s + 6 (m_k - (b_k + b_{k+1}) / 2) s (1 - s). Either way the month's mean is exactly m_k, the values are continuous at the month boundaries, a non-negative key (every key not in signed, whose monthly values are taken to be >= 0) stays >= 0 (0 <= b <= 2 m on both sides of every month), and a series constant in time gives exactly that constant.

Source code in pypath/core/ecosim_continuous/forcing.py
 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
class ForcingInterpolant:
    """Mean-preserving interpolation of monthly forcing inside each month.

    ``monthly`` maps a forcing key to its monthly values, an array of shape
    ``(n_months, ...)`` (the same ``n_months`` for every key, else
    ``ValueError``); the arrays are copied, never written. Months are
    0-based: month ``k`` is row ``k``, and ``s`` in ``[0, 1]`` (clipped) is
    the fraction of the month.

    The boundary values: inside the series ``b_k = min((m_{k-1} + m_k) / 2,
    2 m_{k-1}, 2 m_k)`` for a non-negative key and ``(m_{k-1} + m_k) / 2``
    for a key in ``signed``; at the ends ``b_0 = m_0`` and ``b_N =
    m_{N-1}``, so nothing past the series is read. With ``kind="linear"``
    month ``k`` is a continuous tent through ``(0, b_k)``, ``(1/2, c_k)``
    and ``(1, b_{k+1})``, ``c_k = 2 m_k - (b_k + b_{k+1}) / 2``; it has a
    kink at mid-month. With ``kind="smooth"`` it is one quadratic, ``b_k (1
    - s) + b_{k+1} s + 6 (m_k - (b_k + b_{k+1}) / 2) s (1 - s)``. Either way
    the month's mean is exactly ``m_k``, the values are continuous at the
    month boundaries, a non-negative key (every key not in ``signed``,
    whose monthly values are taken to be >= 0) stays >= 0 (``0 <= b <= 2
    m`` on both sides of every month), and a series constant in time gives
    exactly that constant.
    """

    def __init__(
        self,
        monthly: dict,
        signed: frozenset = SIGNED_KEYS,
        kind: str = "linear",
    ):
        if kind not in ("linear", "smooth"):
            raise ValueError(
                f"ForcingInterpolant kind must be 'linear' or 'smooth', got {kind!r}"
            )
        self.kind = kind
        self.signed = frozenset(signed)
        self._m: dict = {}
        self._b: dict = {}
        self._inner: dict = {}  # c (linear) or 6 (m - (b_k + b_{k+1}) / 2)
        n_months: Optional[int] = None
        for key, series in monthly.items():
            m = np.array(series, dtype=float, copy=True)
            if m.ndim == 0 or len(m) == 0:
                raise ValueError(f"ForcingInterpolant: {key!r} needs one row per month")
            if n_months is None:
                n_months = len(m)
            elif len(m) != n_months:
                raise ValueError(
                    f"ForcingInterpolant: {key!r} has {len(m)} months, "
                    f"another key {n_months}"
                )
            b = np.empty((len(m) + 1,) + m.shape[1:])
            b[0], b[-1] = m[0], m[-1]
            avg = 0.5 * (m[:-1] + m[1:])
            if key in self.signed:
                b[1:-1] = avg
            else:
                b[1:-1] = np.minimum(avg, np.minimum(2.0 * m[:-1], 2.0 * m[1:]))
            mid = 0.5 * (b[:-1] + b[1:])
            self._m[key] = m
            self._b[key] = b
            self._inner[key] = 2.0 * m - mid if kind == "linear" else 6.0 * (m - mid)
        self.n_months = 0 if n_months is None else n_months

    @property
    def keys(self) -> tuple:
        """The interpolated keys."""
        return tuple(self._m)

    def at(self, month: int, s: float) -> dict:
        """Every key's value at the fraction ``s`` of month ``month``.

        Each half of the month is written from its own end (the start for
        ``s <= 1/2``, the end beyond), so a month's ends are exactly its
        boundary values and a constant series is exactly constant.
        """
        k = int(month)
        if not 0 <= k < self.n_months:
            raise IndexError(f"month {k} outside 0..{self.n_months - 1}")
        s = min(max(float(s), 0.0), 1.0)
        out = {}
        for key, b in self._b.items():
            b0, b1, inner = b[k], b[k + 1], self._inner[key][k]
            if self.kind == "linear":  # inner = c, the mid-month value
                if s <= 0.5:
                    out[key] = b0 + (inner - b0) * (2.0 * s)
                else:
                    out[key] = b1 + (inner - b1) * (2.0 - 2.0 * s)
            else:
                if s <= 0.5:
                    line = b0 + (b1 - b0) * s
                else:
                    line = b1 - (b1 - b0) * (1.0 - s)
                out[key] = line + inner * (s * (1.0 - s))
        return out

    def mean(self, month: int, key: str) -> np.ndarray:
        """Month ``month``'s mean of ``key``: its monthly value, exactly."""
        return np.array(self._m[key][int(month)], copy=True)

    def for_month(self, month: int, dt: float) -> Callable[[float], dict]:
        """``forcing_at(t)`` for :meth:`ContinuousRHS.set_month`: the values at
        time ``t`` of a month of length ``dt`` (``s = t / dt``)."""
        k = int(month)
        if not 0 <= k < self.n_months:
            raise IndexError(f"month {k} outside 0..{self.n_months - 1}")
        dt = float(dt)

        def forcing_at(t: float) -> dict:
            return self.at(k, t / dt)

        return forcing_at
keys property
keys: tuple

The interpolated keys.

at
at(month: int, s: float) -> dict

Every key's value at the fraction s of month month.

Each half of the month is written from its own end (the start for s <= 1/2, the end beyond), so a month's ends are exactly its boundary values and a constant series is exactly constant.

Source code in pypath/core/ecosim_continuous/forcing.py
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
def at(self, month: int, s: float) -> dict:
    """Every key's value at the fraction ``s`` of month ``month``.

    Each half of the month is written from its own end (the start for
    ``s <= 1/2``, the end beyond), so a month's ends are exactly its
    boundary values and a constant series is exactly constant.
    """
    k = int(month)
    if not 0 <= k < self.n_months:
        raise IndexError(f"month {k} outside 0..{self.n_months - 1}")
    s = min(max(float(s), 0.0), 1.0)
    out = {}
    for key, b in self._b.items():
        b0, b1, inner = b[k], b[k + 1], self._inner[key][k]
        if self.kind == "linear":  # inner = c, the mid-month value
            if s <= 0.5:
                out[key] = b0 + (inner - b0) * (2.0 * s)
            else:
                out[key] = b1 + (inner - b1) * (2.0 - 2.0 * s)
        else:
            if s <= 0.5:
                line = b0 + (b1 - b0) * s
            else:
                line = b1 - (b1 - b0) * (1.0 - s)
            out[key] = line + inner * (s * (1.0 - s))
    return out
mean
mean(month: int, key: str) -> np.ndarray

Month month's mean of key: its monthly value, exactly.

Source code in pypath/core/ecosim_continuous/forcing.py
147
148
149
def mean(self, month: int, key: str) -> np.ndarray:
    """Month ``month``'s mean of ``key``: its monthly value, exactly."""
    return np.array(self._m[key][int(month)], copy=True)
for_month
for_month(month: int, dt: float) -> Callable[[float], dict]

forcing_at(t) for :meth:ContinuousRHS.set_month: the values at time t of a month of length dt (s = t / dt).

Source code in pypath/core/ecosim_continuous/forcing.py
151
152
153
154
155
156
157
158
159
160
161
162
def for_month(self, month: int, dt: float) -> Callable[[float], dict]:
    """``forcing_at(t)`` for :meth:`ContinuousRHS.set_month`: the values at
    time ``t`` of a month of length ``dt`` (``s = t / dt``)."""
    k = int(month)
    if not 0 <= k < self.n_months:
        raise IndexError(f"month {k} outside 0..{self.n_months - 1}")
    dt = float(dt)

    def forcing_at(t: float) -> dict:
        return self.at(k, t / dt)

    return forcing_at

FeedingTime dataclass

The groups whose feeding time is a state of the continuous path.

groups are the living groups with FtimeAdj > 0. The other arrays are full length (index 0 = Outside): adj (FtimeAdj), qbopt (FtimeQBOpt), cap (FtimeMax, 2.0 when the scenario has none), risk_time and risk0 (RiskTime and its base predation risk; zeros when RiskTime is off) and mo (MzeroMort). lower is ForagingTimeLowerLimit.

Source code in pypath/core/ecosim_continuous/feeding.py
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
@dataclass(frozen=True)
class FeedingTime:
    """The groups whose feeding time is a state of the continuous path.

    ``groups`` are the living groups with ``FtimeAdj > 0``. The other arrays
    are full length (index 0 = Outside): ``adj`` (FtimeAdj), ``qbopt``
    (FtimeQBOpt), ``cap`` (FtimeMax, 2.0 when the scenario has none),
    ``risk_time`` and ``risk0`` (RiskTime and its base predation risk; zeros
    when RiskTime is off) and ``mo`` (MzeroMort). ``lower`` is
    ForagingTimeLowerLimit.
    """

    groups: np.ndarray
    adj: np.ndarray
    qbopt: np.ndarray
    cap: np.ndarray
    risk_time: np.ndarray
    risk0: np.ndarray
    mo: np.ndarray
    lower: float

ContinuousRHS

Pure right-hand side dy/dt = f(t, y) of the continuous pathway.

y holds the biomass states of groups 1..n_bio, then (with feeding) the feeding times of feeding.groups. The month's forcing, the non-state slots of the full state vector (slot 0, gears) and the forced groups are held from :meth:set_month; with its forcing_at (a :class:ForcingInterpolant's month) the interpolated keys take their values at the evaluation's t, merged into a new dict over the held one, which is never written. Evaluation is a pure function of (t, y) and one deriv_vector call: handling time is solved inside it, on the consumption kernel, by the solver installed as the private params_dict's _hden_solver (:func:solve_hden_kernel at hden_tol), always from Hden0, so no evaluation depends on an earlier one. The private copy of params_dict is not changed after construction (its _hden array is its own and never read by the solve), and no array is written in place: _det_out is pre-filled at the unforced base state so deriv_vector has nothing left to set. The private copy also sets _KERNEL_VECTOR, so the final consumption pass is the link loop's vectorised twin; the first counted evaluation after :meth:set_month runs the link loop as well, in a second deriv_vector call that only checks the first (its derivative is not used).

With corrections True (the default) the defect corrections R2, R4, R5 and DF once are applied; with False none of them is, and the scenario's flags and emigration are kept. The recalibrated Hden0 and the exact Hden are not defect corrections and apply either way. Differences from the EwE pathway are listed in self.corrections; EwE numerics switches this pathway does not honour are in ignored_switches.

Feeding time obeys dFt/dt = 12 * (clip(target, L, FtimeMax) - Ft) per year, target being the monthly rule (_ftime_update_rpath) at the current state: one forward-Euler month equals the monthly update. Each evaluation writes clip(Ft, L, FtimeMax) into a copy of the month's Ftime (the held array is never written) and takes FoodGain and FoodLoss from the same deriv_vector call. Qopt is _risk_qopt at the current FoodLoss and biomass.

stats (reset by :meth:set_month) holds clips, min_state, hden_passes_max (kernel passes of the largest Hden solve), hden_residual_max, the largest relative residual of the solved Hden under the consumption of the final deriv_vector pass (the vectorised pass; the link loop at the checked evaluation), kernel_check, the month's check max |q_vector - q_loop| / max |q_loop| of the vectorised pass against the link loop, q being HdenConsumption (or FoodGain without handling time; NaN until the check has run), nutrient_floor, the number of evaluations with the free nutrient at its floor, and negative_export, the number of evaluations (under the EwE rule) where a pool's DetExport is below -NEGATIVE_EXPORT_TOL x DetritusOut x B.

evals counts every evaluation of the right-hand side over the object's life (solver, Jacobian columns, start checks, quadrature and :meth:rates calls alike; not reset by :meth:set_month).

:meth:exchange is the net external flux of the biomass states (:func:exchange_rate) at an evaluation's rates, under the forcing those rates were evaluated with (rates["_forcing"]).

Source code in pypath/core/ecosim_continuous/rhs.py
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
class ContinuousRHS:
    """Pure right-hand side ``dy/dt = f(t, y)`` of the continuous pathway.

    ``y`` holds the biomass states of groups ``1..n_bio``, then (with
    ``feeding``) the feeding times of ``feeding.groups``. The month's
    forcing, the non-state slots of the full state vector (slot 0, gears) and
    the forced groups are held from :meth:`set_month`; with its
    ``forcing_at`` (a :class:`ForcingInterpolant`'s month) the interpolated
    keys take their values at the evaluation's ``t``, merged into a new dict
    over the held one, which is never written. Evaluation is a pure
    function of ``(t, y)`` and one ``deriv_vector`` call: handling time is
    solved inside it, on the consumption kernel, by the solver installed as
    the private ``params_dict``'s ``_hden_solver`` (:func:`solve_hden_kernel`
    at ``hden_tol``), always from Hden0, so no evaluation depends on an
    earlier one. The private copy of ``params_dict`` is not changed after
    construction (its ``_hden`` array is its own and never read by the
    solve), and no array is written in place: ``_det_out`` is pre-filled at
    the unforced base state so ``deriv_vector`` has nothing left to set.
    The private copy also sets ``_KERNEL_VECTOR``, so the final consumption
    pass is the link loop's vectorised twin; the first counted evaluation
    after :meth:`set_month` runs the link loop as well, in a second
    ``deriv_vector`` call that only checks the first (its derivative is not
    used).

    With ``corrections`` True (the default) the defect corrections R2, R4, R5
    and DF once are applied; with False none of them is, and the scenario's
    flags and emigration are kept. The recalibrated Hden0 and the exact Hden
    are not defect corrections and apply either way. Differences from the EwE
    pathway are listed in ``self.corrections``; EwE numerics switches this
    pathway does not honour are in ``ignored_switches``.

    Feeding time obeys ``dFt/dt = 12 * (clip(target, L, FtimeMax) - Ft)``
    per year, ``target`` being the monthly rule (``_ftime_update_rpath``) at
    the current state: one forward-Euler month equals the monthly update.
    Each evaluation writes ``clip(Ft, L, FtimeMax)`` into a copy of the
    month's ``Ftime`` (the held array is never written) and takes FoodGain
    and FoodLoss from the same ``deriv_vector`` call. Qopt is ``_risk_qopt``
    at the current FoodLoss and biomass.

    ``stats`` (reset by :meth:`set_month`) holds ``clips``, ``min_state``,
    ``hden_passes_max`` (kernel passes of the largest Hden solve),
    ``hden_residual_max``, the largest relative residual of the solved Hden
    under the consumption of the final ``deriv_vector`` pass (the vectorised
    pass; the link loop at the checked evaluation), ``kernel_check``, the
    month's check ``max |q_vector - q_loop| / max |q_loop|`` of the
    vectorised pass against the link loop, ``q`` being HdenConsumption (or
    FoodGain without handling time; NaN until the check has run),
    ``nutrient_floor``, the number of evaluations with the free nutrient at
    its floor, and ``negative_export``, the number of evaluations (under the
    EwE rule) where a pool's DetExport is below ``-NEGATIVE_EXPORT_TOL x
    DetritusOut x B``.

    ``evals`` counts every evaluation of the right-hand side over the object's
    life (solver, Jacobian columns, start checks, quadrature and
    :meth:`rates` calls alike; not reset by :meth:`set_month`).

    :meth:`exchange` is the net external flux of the biomass states
    (:func:`exchange_rate`) at an evaluation's rates, under the forcing those
    rates were evaluated with (``rates["_forcing"]``).
    """

    def __init__(
        self,
        params_dict: dict,
        fishing_dict: dict,
        n_bio: int,
        b0: np.ndarray,
        switches: Optional[dict] = None,
        *,
        corrections: bool = True,
        hden_tol: float = 1e-12,
        feeding: Optional[FeedingTime] = None,
    ):
        self.n_bio = int(n_bio)
        self.feeding = feeding
        self.n_state = self.n_bio + (0 if feeding is None else len(feeding.groups))
        self.fishing = fishing_dict
        self.hden_tol = float(hden_tol)
        pd = dict(params_dict)
        pd["_hden_exact"] = True
        self.corrections = []
        if corrections:
            if pd.get("DETRITUS_MO_UNSCALED", False):
                self.corrections.append("R2")
            pd["DETRITUS_MO_UNSCALED"] = False
            pd["DETRITUS_MO_TOT"] = True
            pd["DETRITUS_DF_ONCE"] = True
            n_living = int(pd["NUM_LIVING"])
            emig = continuous_emig(pd.get("Emig"), pd.get("EmigRate"), n_living)
            old_emig = pd.get("Emig")
            if emig is not None and (
                old_emig is None
                or not np.array_equal(
                    np.asarray(old_emig, dtype=float)[1 : n_living + 1],
                    emig[1 : n_living + 1],
                )
            ):
                self.corrections.append("R4")
            pd["Emig"] = emig
            if pd.get("_mo_tot") is not None:
                self.corrections.append("R5")
            if pd.get("DetPassedProp") is not None:
                self.corrections.append("DF once")
        self.cmco_qb = None
        if pd.get("_hden") is not None and pd.get("_cmco_qb") is not None:
            self.cmco_qb = np.array(pd["_cmco_qb"], dtype=float, copy=True)
            pd["_hden0"] = recalibrated_hden0(pd, self.cmco_qb)
            pd["_hden"] = np.array(pd["_hden0"], copy=True)  # not the caller's
            self.corrections.append("Hden0 recalibrated")
        if pd.get("EweMediation") is not None:
            pd["MEDIATION_INTERPOLATE"] = True
            self.corrections.append("mediation interpolated")
        n_full = int(pd["NUM_GROUPS"]) + 1
        base = np.zeros(n_full)
        b0 = np.asarray(b0, dtype=float)
        base[: min(len(b0), n_full)] = b0[:n_full]
        self._pd = pd
        self._nutrient = pd.get("NutBaseFreeProp") is not None
        if pd.get("DetPassedProp") is not None:
            # fix DetritusOut at the unforced base state (EwE's FirstTime)
            pd["_det_out"] = np.full(n_full, np.nan)
            deriv_vector(base.copy(), pd, neutral_forcing(pd), fishing_dict)
        # the EwE rule's DetritusOut, fixed above (None under the Rpath rule)
        self._det_out = pd["_det_out"] if pd.get("DetPassedProp") is not None else None
        self._solved: Optional[tuple] = None  # (KernelInputs, passes)
        if self.cmco_qb is not None:
            pd["_hden_solver"] = self._solve_hden
        # the final consumption pass is vectorised (checked once a month)
        pd["_KERNEL_VECTOR"] = True
        self._check_pending = False  # armed by set_month
        self.ignored_switches = [
            name
            for name in SWITCH_NAMES
            if (switches or {}).get(name) is not None
            and (name == "RK4_STEPS" or bool((switches or {}).get(name)))
        ]
        logger.info(
            "continuous RHS: corrections %s; ignored EwE switches %s",
            self.corrections,
            self.ignored_switches,
        )
        self._forcing = neutral_forcing(pd)
        self._forcing_at: Optional[Callable[[float], dict]] = None
        # the compiled derivative (pypath.core.ecosim_fast) for the solver's
        # calls, where it covers the run; else None
        self._fast = _compiled_rhs(pd, fishing_dict)
        if self._fast is not None:
            from pypath.core.ecosim_fast import F_HTOL

            self._fast.fv[F_HTOL] = self.hden_tol
        self._fast_packed = None
        self._base = base.copy()  # the unforced base state (base_loss_rate)
        self._state_full = base
        self._forced = np.zeros(self.n_bio, dtype=bool)
        self._forced_values = np.zeros(self.n_bio)
        self.stats: dict = {}
        self.evals = 0
        self._reset_stats()

    def _reset_stats(self) -> None:
        self.stats = {
            "clips": 0,
            "min_state": np.inf,
            "hden_passes_max": 0,
            "hden_residual_max": 0.0,
            "kernel_check": float("nan"),
            "nutrient_floor": 0,
            "negative_export": 0,
        }

    def _solve_hden(self, inputs: KernelInputs) -> np.ndarray:
        """``deriv_vector``'s ``_hden_solver``: Hden on the kernel."""
        h, passes = solve_hden_kernel(inputs, tol=self.hden_tol)
        self._solved = (inputs, passes)
        return h

    def set_month(
        self,
        forcing_dict: dict,
        state_full: np.ndarray,
        forced_mask: np.ndarray,
        forced_values: np.ndarray,
        forcing_at: Optional[Callable[[float], dict]] = None,
    ) -> None:
        """Hold the month's forcing, non-state slots and forced groups.

        ``forced_mask`` and ``forced_values`` have one entry per group
        (``NUM_GROUPS + 1``, slot 0 included), else ``ValueError``.
        ``forcing_at(t)`` (None: the month's forcing is held) returns the
        interpolated keys at the time ``t`` into the month
        (:meth:`ForcingInterpolant.for_month`); each evaluation merges them
        over ``forcing_dict``.
        """
        n_full = int(self._pd["NUM_GROUPS"]) + 1
        mask = np.asarray(forced_mask, dtype=bool)
        vals = np.asarray(forced_values, dtype=float)
        if mask.shape != (n_full,) or vals.shape != (n_full,):
            raise ValueError(
                f"forced_mask and forced_values need {n_full} entries "
                f"(NUM_GROUPS + 1), got {mask.shape} and {vals.shape}"
            )
        self._forcing = forcing_dict
        self._forcing_at = forcing_at
        self._state_full = np.array(state_full, dtype=float, copy=True)
        sl = slice(1, self.n_bio + 1)
        self._forced = np.array(mask[sl], copy=True)
        self._forced_values = np.array(vals[sl], dtype=float, copy=True)
        self._reset_stats()
        self._check_pending = True
        self._fast_packed = None
        if (
            self._fast is not None
            and forcing_at is None
            and _hooks_intact()
            and not _switching_with_link_forcing(self._pd, forcing_dict)
        ):
            from pypath.core.ecosim_deriv import fishing_mortality

            f, lf = fishing_mortality(self._pd, forcing_dict, self.fishing)
            self._fast_f = f
            self._fast_link_f = lf
            self._fast_packed = self._fast.month(forcing_dict, f, lf, 1, 1.0)

    def _full_state(self, y: np.ndarray) -> np.ndarray:
        """The full state ``deriv_vector`` sees at the biomass states
        ``y[:n_bio]``: clipped at 0, forced groups at their values, the
        non-state slots held from :meth:`set_month`."""
        full: np.ndarray = self._state_full.copy()
        live = np.maximum(np.asarray(y, dtype=float)[: self.n_bio], 0.0)
        live[self._forced] = self._forced_values[self._forced]
        full[1 : self.n_bio + 1] = live
        return full

    def _forcing_at_time(self, t: float) -> dict:
        """The forcing at ``t``: the held dict itself, or (with
        ``forcing_at``) a new dict with the interpolated keys at ``t``."""
        if self._forcing_at is None:
            return self._forcing
        forcing = dict(self._forcing)
        forcing.update(self._forcing_at(t))
        return forcing

    def _ftime_of(self, forcing: dict) -> np.ndarray:
        """``forcing["Ftime"]``, or ones (``deriv_vector``'s default)."""
        ftime = forcing.get("Ftime")
        if ftime is None:
            return np.ones(int(self._pd["NUM_GROUPS"]) + 1)
        return np.array(ftime, dtype=float, copy=True)

    def _evaluate(
        self, y: np.ndarray, rates: Optional[dict], count: bool, t: float = 0.0
    ):
        self.evals += 1
        y = np.asarray(y, dtype=float)
        feeding = self.feeding
        forcing = self._forcing_at_time(t)
        ftime = ft = None
        if feeding is not None:
            # the feeding times held by this evaluation, in a copy
            ft = y[self.n_bio :]
            y = y[: self.n_bio]
            ftime = self._ftime_of(forcing)
            ftime[feeding.groups] = np.clip(
                ft, feeding.lower, feeding.cap[feeding.groups]
            )
            forcing = dict(forcing)
            forcing["Ftime"] = ftime
        if count:
            self.stats["clips"] += int(np.count_nonzero(y < 0))
            self.stats["min_state"] = min(self.stats["min_state"], float(y.min()))
        full = self._full_state(y)
        # rates carry the solved Hden and the loop's consumption at it,
        # whether the free nutrient is at its floor and the pools' export
        need_rates = (
            self.cmco_qb is not None
            or feeding is not None
            or self._nutrient
            or self._det_out is not None
        )
        check = count and self._check_pending
        out = {} if rates is None and (need_rates or check) else rates
        self._solved = None
        deriv = deriv_vector(full, self._pd, forcing, self.fishing, rates=out)
        if count and out is not None:
            if out.get("NutFloor", False):
                self.stats["nutrient_floor"] += 1
            if self._negative_export(out, full):
                self.stats["negative_export"] += 1
        h = None if out is None else out.get("Hden")
        q_final = None if out is None else out.get("HdenConsumption")
        if check and out is not None:
            self._check_pending = False
            # deriv_vector copies its state on entry, so ``full`` is unchanged
            q_final = self._kernel_check(full.copy(), forcing, out, h)
        if count and self._solved is not None and out is not None:
            inputs, passes = self._solved
            self.stats["hden_passes_max"] = max(self.stats["hden_passes_max"], passes)
            # the residual under the final pass's consumption at the solved H
            act = (inputs.cmco_qb > 0) & (inputs.index > 0)
            if act.any():
                g = 1.0 + h[act] * q_final[act] / (
                    inputs.cmco_qb[act] * inputs.index[act]
                )
                res = float(np.max(np.abs(g - h[act]) / h[act]))
                self.stats["hden_residual_max"] = float(
                    np.maximum(self.stats["hden_residual_max"], res)
                )
        dy = np.array(deriv[1 : self.n_bio + 1], dtype=float, copy=True)
        dy[self._forced] = 0.0
        if feeding is not None:
            dft = self._feeding_derivative(full, forcing, out, ft, ftime)
            dy = np.concatenate([dy, dft])
        if out is not None:
            out["Ftime"] = self._ftime_of(forcing)
            out["_forcing"] = forcing  # as applied; not to be written
        return dy, h

    def _kernel_check(
        self,
        full: np.ndarray,
        forcing: dict,
        rates: dict,
        h: Optional[np.ndarray],
    ) -> Optional[np.ndarray]:
        """The link loop's pass at an evaluation's state, against its
        vectorised pass (``rates``): sets ``stats["kernel_check"]`` and
        returns the loop's HdenConsumption (None without handling time).

        One ``deriv_vector`` call on a copy of the private params without
        ``_KERNEL_VECTOR``; with handling time, at the solved Hden ``h`` and
        without the solver (one kernel pass), comparing HdenConsumption,
        else comparing FoodGain.
        """
        pd = dict(self._pd)
        del pd["_KERNEL_VECTOR"]
        key = "FoodGain"
        if h is not None:
            pd.pop("_hden_solver", None)
            pd["_hden"] = np.array(h, dtype=float, copy=True)
            key = "HdenConsumption"
        loop: dict = {}
        deriv_vector(full, pd, forcing, self.fishing, rates=loop)
        ref = np.asarray(loop[key], dtype=float)
        diff = float(np.max(np.abs(np.asarray(rates[key], dtype=float) - ref)))
        scale = float(np.max(np.abs(ref)))
        if diff == 0.0:
            check = 0.0
        else:
            check = diff / scale if scale > 0.0 else float("inf")
        self.stats["kernel_check"] = check
        q_loop = loop.get("HdenConsumption")
        return None if q_loop is None else np.asarray(q_loop, dtype=float)

    def _negative_export(self, rates: dict, full: np.ndarray) -> bool:
        """Whether a pool's DetExport is below ``-NEGATIVE_EXPORT_TOL x
        DetritusOut x B`` (EwE rule only)."""
        if self._det_out is None or "DetExport" not in rates:
            return False
        dead = slice(int(self._pd["NUM_LIVING"]) + 1, self.n_bio + 1)
        export = np.asarray(rates["DetExport"], dtype=float)[dead]
        limit = -NEGATIVE_EXPORT_TOL * np.asarray(self._det_out)[dead] * full[dead]
        return bool(np.any(export < limit))

    def _feeding_derivative(self, full, forcing, rates, ft, ftime) -> np.ndarray:
        """``dFt/dt`` of the feeding-time states, from the evaluation's rates."""
        # imported here: ecosim imports this module (METHOD_NAMES) at load
        from pypath.core.ecosim import _risk_qopt

        fd = self.feeding
        g = fd.groups
        index = hden_index(full, self._pd, forcing)[g]
        food_loss = np.asarray(rates["FoodLoss"], dtype=float)
        qopt = fd.qbopt[g].copy()
        for k, i in enumerate(g):
            if fd.risk_time[i] > 0:
                qopt[k] = _risk_qopt(
                    float(fd.qbopt[i]),
                    float(fd.risk_time[i]),
                    float(fd.risk0[i]),
                    float(food_loss[i]),
                    float(full[i]),
                    float(fd.mo[i]),
                )
        target = ftime_target(
            ftime[g],
            fd.adj[g],
            qopt,
            np.asarray(rates["FoodGain"], dtype=float)[g],
            index,
            fd.lower,
            fd.cap[g],
        )
        return 12.0 * (target - ft)

    def __call__(self, t: float, y: np.ndarray) -> np.ndarray:
        if (
            self._fast_packed is not None
            and not self._check_pending
            and deriv_vector is _DERIV_VECTOR
        ):
            y = np.asarray(y, dtype=float)
            yb = y[: self.n_bio]
            full = self._full_state(yb)
            packed, forcing, ft, ftime = self._fast_inputs(y)
            d, r = self._fast.deriv(full, packed)
            if np.all(np.isfinite(d)):
                self.evals += 1
                self.stats["clips"] += int(np.count_nonzero(yb < 0))
                self.stats["min_state"] = min(self.stats["min_state"], float(yb.min()))
                if self._nutrient and self._nutrient_free(full, forcing)[1]:
                    self.stats["nutrient_floor"] += 1
                dy = np.array(d[1 : self.n_bio + 1], copy=True)
                dy[self._forced] = 0.0
                if self.feeding is not None:
                    rates = {"FoodGain": r[0], "FoodLoss": r[1]}
                    dft = self._feeding_derivative(full, forcing, rates, ft, ftime)
                    dy = np.concatenate([dy, dft])
                return dy
        return self._evaluate(y, None, True, t)[0]

    def rates(self, y: np.ndarray, t: float = 0.0) -> dict:
        """``deriv_vector``'s rates at ``(t, y)``, with ``"Hden"`` the solved
        Hden (None without handling time), ``"Ftime"`` the month's feeding
        time as the evaluation used it (full length) and ``"_forcing"`` the
        forcing dict it applied (not to be written); no stats."""
        if (
            self._fast_packed is not None
            and not self._check_pending
            and deriv_vector is _DERIV_VECTOR
        ):
            fast = self._fast_rates(np.asarray(y, dtype=float), t)
            if fast is not None:
                return fast
        out: dict = {}
        _, h = self._evaluate(y, out, False, t)
        out["Hden"] = h
        return out

    def _fast_inputs(self, y: np.ndarray):
        """The packed inputs of an evaluation at ``y``: the month's, or with
        feeding-time states a repack with their Ftime (as :meth:`_evaluate`
        sets it). Returns (packed, forcing, ft, ftime)."""
        if self.feeding is None:
            return self._fast_packed, self._forcing, None, None
        feeding = self.feeding
        ft = y[self.n_bio :]
        ftime = self._ftime_of(self._forcing)
        ftime[feeding.groups] = np.clip(ft, feeding.lower, feeding.cap[feeding.groups])
        forcing = dict(self._forcing)
        forcing["Ftime"] = ftime
        packed = self._fast.month(forcing, self._fast_f, self._fast_link_f, 1, 1.0)
        return packed, forcing, ft, ftime

    def _fast_rates(self, y: np.ndarray, t: float = 0.0) -> Optional[dict]:
        """:meth:`rates` from the compiled derivative (the keys the month
        budget reads), or None when it does not give finite numbers."""
        self.evals += 1
        full = self._full_state(y[: self.n_bio])
        packed, forcing, _, _ = self._fast_inputs(y)
        d, r = self._fast.budget(full, packed)
        if not np.all(np.isfinite(d)):
            self.evals -= 1
            return None
        nl = int(self._pd["NUM_LIVING"])
        n_bio = nl + int(self._pd["NUM_DEAD"])
        dead = slice(nl + 1, n_bio + 1)
        n = len(full)
        det_gain = np.zeros(n)
        det_loss = np.zeros(n)
        det_gain[dead] = r[8][dead]
        det_loss[dead] = r[9][dead]
        out = {
            "FoodGain": r[0].copy(),
            "FoodLoss": r[1].copy(),
            "LossPropToB": r[2].copy(),
            "TotGain": r[5].copy(),
            "TotLoss": r[6].copy(),
            "Production": r[7].copy(),
            "Import": r[12].copy(),
            "EmigLoss": r[13].copy(),
            "DetGain": det_gain,
            "DetLoss": det_loss,
            "DetExport": r[10].copy(),
            "Landed": self._landed(full),
            "Hden": None if self.cmco_qb is None else r[11].copy(),
            "Ftime": self._ftime_of(forcing),
            "_forcing": forcing,
        }
        out["NutFree"], out["NutFloor"] = self._nutrient_free(full, forcing)
        return out

    def _nutrient_free(self, full: np.ndarray, forcing: dict) -> tuple:
        """deriv_vector's NutFree and NutFloor at ``full``."""
        prop = self._pd.get("NutBaseFreeProp")
        if prop is None:
            return float("nan"), False
        from pypath.core.ecosim_deriv import _ewe_nutrient_free

        nb = slice(1, int(self._pd["NUM_LIVING"]) + int(self._pd["NUM_DEAD"]) + 1)
        base = self._pd.get("_nut_base")
        if base is None:
            base = self._pd["Bbase"]
        free, free0 = _ewe_nutrient_free(
            float(np.sum(full[nb])),
            float(np.sum(np.asarray(base)[nb])),
            prop,
            float(forcing.get("NutForcing", 1.0)),
        )
        return free, bool(free <= 0.00101 * free0)

    def _landed(self, full: np.ndarray) -> np.ndarray:
        """deriv_vector's Landed at ``full``: the catch of the fishing links
        to no detritus pool plus the forced F (none of a pool's catch under
        the EwE rule)."""
        pd = self._pd
        nl = int(pd["NUM_LIVING"])
        n_bio = nl + int(pd["NUM_DEAD"])
        landed = np.zeros(len(full))
        from pypath.core.ecosim_deriv import _fishing_links

        all_from = np.asarray(_fishing_links(self.fishing)[0], dtype=np.int64)
        fish_from = all_from[1:]
        fish_to = np.asarray(pd.get("FishTo", np.zeros(len(all_from))))
        dest = np.zeros(len(fish_from), dtype=np.int64)
        m = min(len(fish_to) - 1, len(dest))
        if m > 0:
            dest[:m] = np.asarray(fish_to[1 : m + 1], dtype=np.int64)
        off = ~((dest > nl) & (dest <= n_bio))
        np.add.at(
            landed,
            fish_from[off],
            np.asarray(self._fast_link_f, dtype=float)[1:][off] * full[fish_from[off]],
        )
        forced_f = self._forcing.get("ForcedF")
        if forced_f is not None:
            ff = np.asarray(forced_f, dtype=float)
            nf = min(len(ff), n_bio + 1)
            landed[1:nf] += ff[1:nf] * full[1:nf]
        if pd.get("DetPassedProp") is not None:
            landed[nl + 1 : n_bio + 1] = 0.0
        return landed

    def exchange(self, rates: dict, y: np.ndarray) -> float:
        """:func:`exchange_rate` of ``rates`` (from :meth:`rates` at ``y``),
        over the full state the evaluation saw and under the forcing it
        applied (``rates["_forcing"]``, else the held forcing); feeding times
        do not enter."""
        forcing = rates.get("_forcing", self._forcing)
        return exchange_rate(rates, self._full_state(y), self._pd, forcing)

    def base_loss_rate(self) -> np.ndarray:
        """``LossPropToB / B`` of groups ``1..n_bio`` at the unforced base:
        the base biomass, :func:`neutral_forcing` (feeding time 1, effort 1)
        and nothing forced, whatever month :meth:`set_month` holds. One
        evaluation, counted in ``evals`` (no stats); 0 where B0 = 0."""
        self.evals += 1
        base = self._base.copy()
        out: dict = {}
        deriv_vector(base, self._pd, neutral_forcing(self._pd), self.fishing, rates=out)
        sl = slice(1, self.n_bio + 1)
        loss = np.asarray(out["LossPropToB"], dtype=float)[sl]
        b = base[sl]
        rate: np.ndarray = np.divide(loss, b, out=np.zeros_like(loss), where=b > 0.0)
        return rate
set_month
set_month(forcing_dict: dict, state_full: ndarray, forced_mask: ndarray, forced_values: ndarray, forcing_at: Optional[Callable[[float], dict]] = None) -> None

Hold the month's forcing, non-state slots and forced groups.

forced_mask and forced_values have one entry per group (NUM_GROUPS + 1, slot 0 included), else ValueError. forcing_at(t) (None: the month's forcing is held) returns the interpolated keys at the time t into the month (:meth:ForcingInterpolant.for_month); each evaluation merges them over forcing_dict.

Source code in pypath/core/ecosim_continuous/rhs.py
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
def set_month(
    self,
    forcing_dict: dict,
    state_full: np.ndarray,
    forced_mask: np.ndarray,
    forced_values: np.ndarray,
    forcing_at: Optional[Callable[[float], dict]] = None,
) -> None:
    """Hold the month's forcing, non-state slots and forced groups.

    ``forced_mask`` and ``forced_values`` have one entry per group
    (``NUM_GROUPS + 1``, slot 0 included), else ``ValueError``.
    ``forcing_at(t)`` (None: the month's forcing is held) returns the
    interpolated keys at the time ``t`` into the month
    (:meth:`ForcingInterpolant.for_month`); each evaluation merges them
    over ``forcing_dict``.
    """
    n_full = int(self._pd["NUM_GROUPS"]) + 1
    mask = np.asarray(forced_mask, dtype=bool)
    vals = np.asarray(forced_values, dtype=float)
    if mask.shape != (n_full,) or vals.shape != (n_full,):
        raise ValueError(
            f"forced_mask and forced_values need {n_full} entries "
            f"(NUM_GROUPS + 1), got {mask.shape} and {vals.shape}"
        )
    self._forcing = forcing_dict
    self._forcing_at = forcing_at
    self._state_full = np.array(state_full, dtype=float, copy=True)
    sl = slice(1, self.n_bio + 1)
    self._forced = np.array(mask[sl], copy=True)
    self._forced_values = np.array(vals[sl], dtype=float, copy=True)
    self._reset_stats()
    self._check_pending = True
    self._fast_packed = None
    if (
        self._fast is not None
        and forcing_at is None
        and _hooks_intact()
        and not _switching_with_link_forcing(self._pd, forcing_dict)
    ):
        from pypath.core.ecosim_deriv import fishing_mortality

        f, lf = fishing_mortality(self._pd, forcing_dict, self.fishing)
        self._fast_f = f
        self._fast_link_f = lf
        self._fast_packed = self._fast.month(forcing_dict, f, lf, 1, 1.0)
rates
rates(y: ndarray, t: float = 0.0) -> dict

deriv_vector's rates at (t, y), with "Hden" the solved Hden (None without handling time), "Ftime" the month's feeding time as the evaluation used it (full length) and "_forcing" the forcing dict it applied (not to be written); no stats.

Source code in pypath/core/ecosim_continuous/rhs.py
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
def rates(self, y: np.ndarray, t: float = 0.0) -> dict:
    """``deriv_vector``'s rates at ``(t, y)``, with ``"Hden"`` the solved
    Hden (None without handling time), ``"Ftime"`` the month's feeding
    time as the evaluation used it (full length) and ``"_forcing"`` the
    forcing dict it applied (not to be written); no stats."""
    if (
        self._fast_packed is not None
        and not self._check_pending
        and deriv_vector is _DERIV_VECTOR
    ):
        fast = self._fast_rates(np.asarray(y, dtype=float), t)
        if fast is not None:
            return fast
    out: dict = {}
    _, h = self._evaluate(y, out, False, t)
    out["Hden"] = h
    return out
exchange
exchange(rates: dict, y: ndarray) -> float

:func:exchange_rate of rates (from :meth:rates at y), over the full state the evaluation saw and under the forcing it applied (rates["_forcing"], else the held forcing); feeding times do not enter.

Source code in pypath/core/ecosim_continuous/rhs.py
747
748
749
750
751
752
753
def exchange(self, rates: dict, y: np.ndarray) -> float:
    """:func:`exchange_rate` of ``rates`` (from :meth:`rates` at ``y``),
    over the full state the evaluation saw and under the forcing it
    applied (``rates["_forcing"]``, else the held forcing); feeding times
    do not enter."""
    forcing = rates.get("_forcing", self._forcing)
    return exchange_rate(rates, self._full_state(y), self._pd, forcing)
base_loss_rate
base_loss_rate() -> np.ndarray

LossPropToB / B of groups 1..n_bio at the unforced base: the base biomass, :func:neutral_forcing (feeding time 1, effort 1) and nothing forced, whatever month :meth:set_month holds. One evaluation, counted in evals (no stats); 0 where B0 = 0.

Source code in pypath/core/ecosim_continuous/rhs.py
755
756
757
758
759
760
761
762
763
764
765
766
767
768
def base_loss_rate(self) -> np.ndarray:
    """``LossPropToB / B`` of groups ``1..n_bio`` at the unforced base:
    the base biomass, :func:`neutral_forcing` (feeding time 1, effort 1)
    and nothing forced, whatever month :meth:`set_month` holds. One
    evaluation, counted in ``evals`` (no stats); 0 where B0 = 0."""
    self.evals += 1
    base = self._base.copy()
    out: dict = {}
    deriv_vector(base, self._pd, neutral_forcing(self._pd), self.fishing, rates=out)
    sl = slice(1, self.n_bio + 1)
    loss = np.asarray(out["LossPropToB"], dtype=float)[sl]
    b = base[sl]
    rate: np.ndarray = np.divide(loss, b, out=np.zeros_like(loss), where=b > 0.0)
    return rate

JacobianReuse

Finite-difference Jacobians for solve_ivp, reused across the monthly restarts of a run.

:meth:for_month returns the month's jac(t, y) callable, a new closure each month over the month's right-hand side fun. The object holds only the last Jacobian formed and the state y_J it was formed at; the right-hand side holds nothing of it.

The rule, per request:

  • a month's first request returns the run's last Jacobian when one of the right shape (len(y) square) is held;
  • later requests: BDF and Radau always form a fresh one (SciPy asks again only after a failed Newton iteration, or for Radau after a slowly converging step); LSODA reuses the held one only when t strictly advances past the previous request's and the state has not moved, max |y - y_J| / (|y_J| + 1e-12) <= move. A request at or before the previous t is a retry (after a corrector failure ODEPACK cuts the step and asks again at an earlier t) and gets a fresh one.

A fresh Jacobian is forward differences in every state, h_k = 1.49e-8 x max(|y_k|, floor_k), floor the month's step floor (:meth:for_month's step_floor, by default atol / rtol; > 0, so the step is too where y_k = 0): fun at y and once per column, len(y) + 1 evaluations (SciPy passes no f(t, y) to jac), each a call of fun and so counted in ContinuousRHS.evals. SciPy's nfev leaves them out, and its njev counts reused requests too. rsim_run passes atol / rtol with the biomass states' capped at the default atol's ratio, 0.01 x max(B0_k, 1e-6 x max B0) (so a large user atol does not make the step large; the default atol gives its own ratio), and :func:integrate_month gives log states a floor of 1, h_k = 1.49e-8 x max(|z_k|, 1). Only a finite fresh Jacobian is held: one with a non-finite entry goes to the solver, and the held one is dropped, so the next request forms a fresh one.

stats (reset by :meth:for_month) counts the month's requests: jac_fresh formed, jac_reused answered with the held Jacobian. Every request returns a copy, so a solver cannot change the held one.

Source code in pypath/core/ecosim_continuous/jacobian.py
 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
class JacobianReuse:
    """Finite-difference Jacobians for ``solve_ivp``, reused across the
    monthly restarts of a run.

    :meth:`for_month` returns the month's ``jac(t, y)`` callable, a new
    closure each month over the month's right-hand side ``fun``. The object
    holds only the last Jacobian formed and the state ``y_J`` it was formed
    at; the right-hand side holds nothing of it.

    The rule, per request:

    - a month's first request returns the run's last Jacobian when one of
      the right shape (``len(y)`` square) is held;
    - later requests: BDF and Radau always form a fresh one (SciPy asks
      again only after a failed Newton iteration, or for Radau after a slowly
      converging step); LSODA reuses the held one only when ``t`` strictly
      advances past the previous request's and the state has not moved,
      ``max |y - y_J| / (|y_J| + 1e-12) <= move``. A request at or before
      the previous ``t`` is a retry (after a corrector failure ODEPACK cuts
      the step and asks again at an earlier ``t``) and gets a fresh one.

    A fresh Jacobian is forward differences in every state, ``h_k = 1.49e-8
    x max(|y_k|, floor_k)``, ``floor`` the month's step floor
    (:meth:`for_month`'s ``step_floor``, by default ``atol / rtol``; > 0, so
    the step is too where ``y_k = 0``): ``fun`` at ``y`` and once per column,
    ``len(y) + 1`` evaluations (SciPy passes no ``f(t, y)`` to ``jac``), each
    a call of ``fun`` and so counted in ``ContinuousRHS.evals``. SciPy's
    ``nfev`` leaves them out, and its ``njev`` counts reused requests too.
    ``rsim_run`` passes ``atol / rtol`` with the biomass states' capped at
    the default atol's ratio, ``0.01 x max(B0_k, 1e-6 x max B0)`` (so a large
    user atol does not make the step large; the default atol gives its own
    ratio), and :func:`integrate_month` gives log states a floor of 1, ``h_k
    = 1.49e-8 x max(|z_k|, 1)``. Only a finite fresh Jacobian is held: one
    with a non-finite entry goes to the solver, and the held one is dropped,
    so the next request forms a fresh one.

    ``stats`` (reset by :meth:`for_month`) counts the month's requests:
    ``jac_fresh`` formed, ``jac_reused`` answered with the held Jacobian.
    Every request returns a copy, so a solver cannot change the held one.
    """

    def __init__(
        self, method: str, atol: np.ndarray, rtol: float, *, move: float = 0.1
    ):
        if not isinstance(method, str) or method.lower() not in METHOD_NAMES:
            raise ValueError(
                f"JacobianReuse: unknown method {method!r}: use "
                f"{', '.join(repr(m) for m in METHOD_NAMES)}"
            )
        self.method = method.lower()
        self.atol = np.asarray(atol, dtype=float)
        self.rtol = float(rtol)
        self.move = float(move)
        self._month_floor = self.atol / self.rtol
        # (the last Jacobian formed, when finite; the state y_J it was formed
        # at)
        self._held: Optional[tuple[np.ndarray, np.ndarray]] = None
        self.stats = {"jac_fresh": 0, "jac_reused": 0}

    def _fresh(self, fun, t: float, y: np.ndarray) -> np.ndarray:
        """Forward differences of ``fun`` at ``(t, y)``; held for reuse when
        finite."""
        n = len(y)
        f0 = np.asarray(fun(t, y), dtype=float)
        floor = np.broadcast_to(self._month_floor, (n,))
        jac = np.empty((n, n))
        for k in range(n):
            yk = y.copy()
            yk[k] = y[k] + 1.49e-8 * max(abs(y[k]), floor[k])
            h = yk[k] - y[k]  # the step as represented
            jac[:, k] = (np.asarray(fun(t, yk), dtype=float) - f0) / h
        # a non-finite matrix is not reused, and neither is the older one
        self._held = (jac, y.copy()) if np.all(np.isfinite(jac)) else None
        self.stats["jac_fresh"] += 1
        return jac.copy()

    def for_month(
        self, fun: Callable, step_floor: Optional[np.ndarray] = None
    ) -> Callable[[float, np.ndarray], np.ndarray]:
        """The month's ``jac(t, y)`` over ``fun``; resets ``stats``.

        ``step_floor`` (a scalar or one value > 0 per state ``fun`` takes;
        default: the object's ``atol / rtol``) is the floor of the difference
        step, ``h_k = 1.49e-8 x max(|y_k|, step_floor_k)``. ``rsim_run``
        passes its capped floor, and :func:`integrate_month`'s ``jac_factory``
        call the floor of the solver's states (1 for log states)."""
        self.stats = {"jac_fresh": 0, "jac_reused": 0}
        self._month_floor = (
            self.atol / self.rtol
            if step_floor is None
            else np.asarray(step_floor, dtype=float)
        )
        first = True
        t_prev: Optional[float] = None

        def jac(t: float, y: np.ndarray) -> np.ndarray:
            nonlocal first, t_prev
            y = np.array(y, dtype=float)
            held = self._held
            if held is not None and held[0].shape != (len(y), len(y)):
                held = None
            keep = held is not None and (
                first
                or (
                    self.method == "lsoda"
                    # a retry asks at or before the previous t
                    and t_prev is not None
                    and t > t_prev
                    and _moved(y, held[1]) <= self.move
                )
            )
            first = False
            t_prev = t
            if held is None or not keep:
                return self._fresh(fun, t, y)
            self.stats["jac_reused"] += 1
            return held[0].copy()

        return jac
for_month
for_month(fun: Callable, step_floor: Optional[ndarray] = None) -> Callable[[float, np.ndarray], np.ndarray]

The month's jac(t, y) over fun; resets stats.

step_floor (a scalar or one value > 0 per state fun takes; default: the object's atol / rtol) is the floor of the difference step, h_k = 1.49e-8 x max(|y_k|, step_floor_k). rsim_run passes its capped floor, and :func:integrate_month's jac_factory call the floor of the solver's states (1 for log states).

Source code in pypath/core/ecosim_continuous/jacobian.py
 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
def for_month(
    self, fun: Callable, step_floor: Optional[np.ndarray] = None
) -> Callable[[float, np.ndarray], np.ndarray]:
    """The month's ``jac(t, y)`` over ``fun``; resets ``stats``.

    ``step_floor`` (a scalar or one value > 0 per state ``fun`` takes;
    default: the object's ``atol / rtol``) is the floor of the difference
    step, ``h_k = 1.49e-8 x max(|y_k|, step_floor_k)``. ``rsim_run``
    passes its capped floor, and :func:`integrate_month`'s ``jac_factory``
    call the floor of the solver's states (1 for log states)."""
    self.stats = {"jac_fresh": 0, "jac_reused": 0}
    self._month_floor = (
        self.atol / self.rtol
        if step_floor is None
        else np.asarray(step_floor, dtype=float)
    )
    first = True
    t_prev: Optional[float] = None

    def jac(t: float, y: np.ndarray) -> np.ndarray:
        nonlocal first, t_prev
        y = np.array(y, dtype=float)
        held = self._held
        if held is not None and held[0].shape != (len(y), len(y)):
            held = None
        keep = held is not None and (
            first
            or (
                self.method == "lsoda"
                # a retry asks at or before the previous t
                and t_prev is not None
                and t > t_prev
                and _moved(y, held[1]) <= self.move
            )
        )
        first = False
        t_prev = t
        if held is None or not keep:
            return self._fresh(fun, t, y)
        self.stats["jac_reused"] += 1
        return held[0].copy()

    return jac

QuasiSteady

Quasi-steady fast groups: the reduced right-hand side of a :class:ContinuousRHS (a model option, solver_options["fast_groups"] = "quasi-steady").

groups (group numbers in 1..rhs.n_bio) leave the state. slow holds the indices of rhs's states that stay (the other biomass states, then any feeding times), n_state their number and n_bio the number of biomass states among them, which lead. An evaluation at (t, ys) solves dB_f/dt = 0 for the selected groups' biomass B_f with the slow states at ys and returns the slow states' derivative at the solution; :meth:expand returns the full state there.

The solve is a chord Newton from the month-start B_f with the month-start J_ff, forward differences of rhs in B_f formed by :meth:set_month. Each step is halved until every B_f > 0. It stops when |dB_f/dt| <= tol x TotGain_f for every selected group (TotGain from deriv_vector's rates at the same evaluation), in at most max_iter steps. When the residual (its largest |dB_f/dt| / TotGain_f) stops falling, J_ff is formed again, once, at the iterate, for the rest of that solve only.

A root is accepted only if it is finite, positive, within the tolerance above and attracting: every eigenvalue of J_ff there has a negative real part, so the fast dynamics relax to it. A producer has a second root near B = 1e-10, where a loss term that does not scale with B meets its production: the slope there is positive, an unstable branch that a root finder can walk into. The check forms J_ff by forward differences at the root (one evaluation per selected group). A chord root of a single group skips it when the chord's matrix (the month's, or the refreshed one) is negative: the chord converges only to a root whose slope has its matrix's sign. With several groups every chord root is checked (no such guarantee holds for matrices).

When the chord fails or its root is rejected (a month start far from the solution: the chord converges linearly at the ratio |1 - J*/J_ff|, and a producer whose quasi-steady value jumps 30 % can defeat it), a pseudo-transient continuation follows the fast dynamics, the slow states held, from the month-start B_f: each step solves (I / dtau - J_ff) delta = dB_f/dt with J_ff formed by forward differences at the iterate, halving delta to keep B_f > 0; dtau starts at 0.5 / max |diag J_ff| (half the fastest relaxation time, so that I / dtau - J_ff stays regular where a slope is positive) and grows by switched evolution relaxation, dtau x r_prev / r (r the largest |dB_f/dt| / TotGain_f), capped at 1e12 times its start, which ends as Newton's method; at most ptc_max_iter steps. It starts from the month-start B_f, not the chord's best iterate, which may be the unstable root, where the continuation would stall. If it fails too, scipy.optimize.root(method="hybr") runs in ln B_f (every iterate positive) from the continuation's best iterate, scaled by its TotGain_f, with the same acceptance. Otherwise RuntimeError names "quasi-steady" and the groups. The start B_f, J_ff and the groups are fixed by :meth:set_month, the fallback starts from them and the evaluation's own iterates, and an evaluation keeps nothing it computes, so each evaluation is a function of (t, ys) and the month's data, as rhs's own are.

tol defaults to 1e-10; rsim_run passes min(1e-10, max(1e-2 x rtol, 1e-13)), so that a user rtol below 1e-8 keeps the solve's error two orders under the solver's (the floor 1e-13 is about the roundoff of dB_f/dt relative to TotGain_f).

Every inner evaluation (residuals and difference columns, of every stage, hybr's own difference Jacobian included) is an evaluation of rhs and is counted in rhs.evals. Those of the solver's evaluations (:meth:__call__) and of :meth:set_month's J_ff also count in rhs.stats, as :class:JacobianReuse's columns do; those of :meth:expand (the quadrature, the month end) and of :meth:reduced_rate do not. stats["qs_inner_max"], reset by :meth:set_month, is the largest number of chord-Newton steps one solve of the month took (every solve counted; at most max_iter), and stats["qs_fallbacks"] counts the month's solves that fell back to the continuation ("ptc") and on to hybr ("hybr"), the roots rejected as not attracting ("unstable", every stage), and the evaluations the two fallback stages took ("evals", measured as rhs.evals across them; a chord root's check is the chord's).

A difference column k steps by 1.49e-8 x max(|y_k|, step_floor_k), step_floor being a scalar or one value per state of rhs (default 0; rsim_run passes atol / rtol, the floor :class:JacobianReuse uses). names (optional, one per group) label the groups in errors.

Source code in pypath/core/ecosim_continuous/quasi_steady.py
 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
class QuasiSteady:
    """Quasi-steady fast groups: the reduced right-hand side of a
    :class:`ContinuousRHS` (a model option, ``solver_options["fast_groups"]
    = "quasi-steady"``).

    ``groups`` (group numbers in ``1..rhs.n_bio``) leave the state.
    ``slow`` holds the indices of ``rhs``'s states that stay (the other
    biomass states, then any feeding times), ``n_state`` their number and
    ``n_bio`` the number of biomass states among them, which lead. An
    evaluation at ``(t, ys)`` solves ``dB_f/dt = 0`` for the selected
    groups' biomass ``B_f`` with the slow states at ``ys`` and returns the
    slow states' derivative at the solution; :meth:`expand` returns the full
    state there.

    The solve is a chord Newton from the month-start ``B_f`` with the
    month-start ``J_ff``, forward differences of ``rhs`` in ``B_f`` formed
    by :meth:`set_month`. Each step is halved until every ``B_f > 0``. It
    stops when ``|dB_f/dt| <= tol x TotGain_f`` for every selected group
    (``TotGain`` from ``deriv_vector``'s rates at the same evaluation), in
    at most ``max_iter`` steps. When the residual (its largest
    ``|dB_f/dt| / TotGain_f``) stops falling, ``J_ff`` is formed again,
    once, at the iterate, for the rest of that solve only.

    A root is accepted only if it is finite, positive, within the tolerance
    above and attracting: every eigenvalue of ``J_ff`` there has a negative
    real part, so the fast dynamics relax to it. A producer has a second
    root near ``B = 1e-10``, where a loss term that does not scale with B
    meets its production: the slope there is positive, an unstable branch
    that a root finder can walk into. The check forms ``J_ff`` by forward
    differences at the root (one evaluation per selected group). A chord
    root of a single group skips it when the chord's matrix (the month's, or
    the refreshed one) is negative: the chord converges only to a root
    whose slope has its matrix's sign. With several groups every chord root
    is checked (no such guarantee holds for matrices).

    When the chord fails or its root is rejected (a month start far from
    the solution: the chord converges linearly at the ratio
    ``|1 - J*/J_ff|``, and a producer whose quasi-steady value jumps 30 %
    can defeat it), a pseudo-transient continuation follows the fast
    dynamics, the slow states held, from the month-start ``B_f``: each step
    solves ``(I / dtau - J_ff) delta = dB_f/dt`` with ``J_ff`` formed by
    forward differences at the iterate, halving ``delta`` to keep
    ``B_f > 0``; ``dtau`` starts at ``0.5 / max |diag J_ff|`` (half the
    fastest relaxation time, so that ``I / dtau - J_ff`` stays regular where
    a slope is positive) and grows by switched evolution relaxation,
    ``dtau x r_prev / r`` (``r`` the largest ``|dB_f/dt| / TotGain_f``),
    capped at ``1e12`` times its start, which ends as Newton's method; at
    most ``ptc_max_iter`` steps. It starts from the month-start ``B_f``, not
    the chord's best iterate, which may be the unstable root, where the
    continuation would stall. If it fails too,
    ``scipy.optimize.root(method="hybr")`` runs in ``ln B_f`` (every
    iterate positive) from the continuation's best iterate, scaled by its
    ``TotGain_f``, with the same acceptance. Otherwise ``RuntimeError``
    names "quasi-steady" and the groups. The start ``B_f``, ``J_ff`` and
    the groups are fixed by :meth:`set_month`, the fallback starts from them
    and the evaluation's own iterates, and an evaluation keeps nothing it
    computes, so each evaluation is a function of ``(t, ys)`` and the
    month's data, as ``rhs``'s own are.

    ``tol`` defaults to 1e-10; ``rsim_run`` passes ``min(1e-10, max(1e-2 x
    rtol, 1e-13))``, so that a user ``rtol`` below 1e-8 keeps the solve's
    error two orders under the solver's (the floor 1e-13 is about the
    roundoff of ``dB_f/dt`` relative to ``TotGain_f``).

    Every inner evaluation (residuals and difference columns, of every
    stage, ``hybr``'s own difference Jacobian included) is an evaluation of
    ``rhs`` and is counted in ``rhs.evals``. Those of the
    solver's evaluations (:meth:`__call__`) and of :meth:`set_month`'s
    ``J_ff`` also count in ``rhs.stats``, as :class:`JacobianReuse`'s columns
    do; those of :meth:`expand` (the quadrature, the month end) and of
    :meth:`reduced_rate` do not. ``stats["qs_inner_max"]``, reset by
    :meth:`set_month`, is the largest number of chord-Newton steps one solve
    of the month took (every solve counted; at most ``max_iter``), and
    ``stats["qs_fallbacks"]`` counts the month's solves that fell back to
    the continuation (``"ptc"``) and on to ``hybr`` (``"hybr"``), the roots
    rejected as not attracting (``"unstable"``, every stage), and the
    evaluations the two fallback stages took (``"evals"``, measured as
    ``rhs.evals`` across them; a chord root's check is the chord's).

    A difference column ``k`` steps by ``1.49e-8 x max(|y_k|,
    step_floor_k)``, ``step_floor`` being a scalar or one value per state of
    ``rhs`` (default 0; ``rsim_run`` passes ``atol / rtol``, the floor
    :class:`JacobianReuse` uses). ``names`` (optional, one per group) label
    the groups in errors.
    """

    def __init__(
        self,
        groups,
        rhs: ContinuousRHS,
        *,
        step_floor=0.0,
        tol: float = QS_TOL,
        max_iter: int = QS_MAX_ITER,
        ptc_max_iter: int = QS_PTC_MAX_ITER,
        names=None,
    ):
        groups = np.unique(np.asarray(groups, dtype=int))
        if groups.size == 0 or groups[0] < 1 or groups[-1] > rhs.n_bio:
            raise ValueError(
                f"QuasiSteady: groups must be in 1..{rhs.n_bio}, got {groups.tolist()}"
            )
        self.rhs = rhs
        self.groups = groups
        self.fast = groups - 1  # their indices in rhs's state
        keep = np.ones(rhs.n_state, dtype=bool)
        keep[self.fast] = False
        self.slow = np.flatnonzero(keep)
        self.n_state = len(self.slow)
        self.n_bio = rhs.n_bio - len(groups)
        self.tol = float(tol)
        self.max_iter = int(max_iter)
        self.ptc_max_iter = int(ptc_max_iter)
        self._floor = np.array(
            np.broadcast_to(np.asarray(step_floor, dtype=float), (rhs.n_state,))
        )
        label = str(groups.tolist())
        if names is not None:
            label += f" ({', '.join(str(name) for name in names)})"
        self._label = label
        # month data, set by set_month
        self._ys0: Optional[np.ndarray] = None
        self._bf0: Optional[np.ndarray] = None
        self._jinv: Optional[np.ndarray] = None
        self.stats: dict = {}
        self._reset_stats()

    def _reset_stats(self) -> None:
        self.stats = {
            "qs_inner_max": 0,
            "qs_fallbacks": {"ptc": 0, "hybr": 0, "unstable": 0, "evals": 0},
        }

    def set_month(
        self,
        forcing_dict: dict,
        state_full: np.ndarray,
        forced_mask: np.ndarray,
        forced_values: np.ndarray,
        forcing_at: Optional[Callable[[float], dict]] = None,
        *,
        y0: np.ndarray,
    ) -> None:
        """:meth:`ContinuousRHS.set_month`, then the month's data at the
        month start ``y0`` (every state of ``rhs``): the start ``B_f``
        (``y0``'s, floored at 1e-20) and ``J_ff`` there at ``t = 0``.

        A selected group forced this month raises ``ValueError`` (the run
        excludes groups forced in any month); a singular or non-finite
        ``J_ff`` raises ``RuntimeError``."""
        rhs = self.rhs
        rhs.set_month(forcing_dict, state_full, forced_mask, forced_values, forcing_at)
        y0 = np.array(y0, dtype=float)
        if y0.shape != (rhs.n_state,):
            raise ValueError(
                f"QuasiSteady.set_month: y0 needs {rhs.n_state} states, got {y0.shape}"
            )
        if np.any(rhs._forced[self.fast]):
            raise ValueError(
                f"quasi-steady groups {self._label}: a forced group cannot be "
                "quasi-steady"
            )
        self._reset_stats()
        self._ys0 = y0[self.slow]
        self._bf0 = np.maximum(y0[self.fast], _Y_FLOOR)
        y = y0.copy()
        y[self.fast] = self._bf0
        r0 = rhs._evaluate(y, None, True, 0.0)[0][self.fast]
        self._jinv = self._chord(0.0, y, r0, True)

    def _jff(self, t: float, y: np.ndarray, r: np.ndarray, count: bool) -> np.ndarray:
        """``J_ff`` at ``(t, y)``, ``r`` being ``dB_f/dt`` there: forward
        differences, one evaluation per selected group."""
        nf = len(self.fast)
        jff = np.empty((nf, nf))
        for j, k in enumerate(self.fast):
            yk = y.copy()
            yk[k] = y[k] + 1.49e-8 * max(abs(y[k]), self._floor[k])
            h = yk[k] - y[k]  # the step as represented
            dyk = self.rhs._evaluate(yk, None, count, t)[0]
            jff[:, j] = (dyk[self.fast] - r) / h
        return jff

    def _chord(self, t: float, y: np.ndarray, r: np.ndarray, count: bool) -> np.ndarray:
        """The inverse of :meth:`_jff`; ``RuntimeError`` when ``J_ff`` is
        singular or not finite."""
        jff = self._jff(t, y, r, count)
        jinv = None
        if np.all(np.isfinite(jff)):
            try:
                jinv = np.linalg.inv(jff)
            except np.linalg.LinAlgError:
                jinv = None
        if jinv is None or not np.all(np.isfinite(jinv)):
            raise RuntimeError(
                f"quasi-steady groups {self._label}: J_ff is singular or not "
                f"finite at t={t:.6g}"
            )
        return jinv

    @staticmethod
    def _hurwitz(m: np.ndarray) -> bool:
        """Whether every eigenvalue of ``m`` has a negative real part (the
        same holds for its inverse)."""
        if not np.all(np.isfinite(m)):
            return False
        if m.shape == (1, 1):
            return bool(m[0, 0] < 0.0)
        try:
            return bool(np.all(np.linalg.eigvals(m).real < 0.0))
        except np.linalg.LinAlgError:
            return False

    def _attracting(self, t: float, y: np.ndarray, r: np.ndarray, count: bool) -> bool:
        """Whether the root at ``(t, y)`` (``r = dB_f/dt`` there) attracts
        the fast dynamics: :meth:`_hurwitz` of ``J_ff`` there (one evaluation
        per selected group). A rejected root counts in
        ``stats["qs_fallbacks"]["unstable"]``."""
        if self._hurwitz(self._jff(t, y, r, count)):
            return True
        self.stats["qs_fallbacks"]["unstable"] += 1
        return False

    @staticmethod
    def _positive_step(bf: np.ndarray, delta: np.ndarray) -> Optional[np.ndarray]:
        """``bf + s x delta`` for the first ``s`` in 1, 1/2, 1/4, ... that
        keeps every ``B_f > 0`` (None if none does, or ``delta`` is not
        finite)."""
        if not np.all(np.isfinite(delta)):
            return None
        step = 1.0
        for _ in range(_QS_MAX_HALVINGS):
            trial = bf + step * delta
            if np.all(trial > 0.0):
                return trial
            step *= 0.5
        return None

    def _solve(
        self, t: float, ys: np.ndarray, count: bool
    ) -> tuple[np.ndarray, np.ndarray]:
        """``(y, dy)``: the full state with ``B_f`` solved at ``(t, ys)`` and
        ``rhs``'s derivative there: the chord Newton, then (when it fails or
        its root does not attract) :meth:`_fallback`."""
        if self._bf0 is None or self._jinv is None:
            raise RuntimeError("QuasiSteady: set_month has not been called")
        rhs = self.rhs
        y = np.empty(rhs.n_state)
        y[self.slow] = np.asarray(ys, dtype=float)
        # the iterate with the smallest scaled residual (reset by the fallback)
        best: dict = {"score": np.inf, "bf": self._bf0.copy(), "gain": None}

        def residual(bf: np.ndarray):
            """``(dy, dB_f/dt, score, ok)`` at ``B_f = bf`` (``y`` holds it
            after the call): ``score`` is ``max |dB_f/dt| / TotGain_f`` (inf
            when not finite) and ``ok`` whether ``bf`` is a root (finite,
            positive, ``|dB_f/dt| <= tol x TotGain_f``; whether it attracts
            is checked apart)."""
            y[self.fast] = bf
            out: dict = {}
            dy: np.ndarray = rhs._evaluate(y, out, count, t)[0]
            r = dy[self.fast]
            gain = np.abs(np.asarray(out["TotGain"], dtype=float)[self.groups])
            finite = bool(
                np.all(np.isfinite(bf))
                and np.all(np.isfinite(r))
                and np.all(np.isfinite(gain))
            )
            score = np.inf
            if finite:
                score = float(np.max(np.abs(r) / np.maximum(gain, _TINY)))
            ok = finite and bool(
                np.all(bf > 0.0) and np.all(np.abs(r) <= self.tol * gain)
            )
            if score < best["score"]:
                best.update(score=score, bf=np.array(bf, copy=True), gain=gain)
            return dy, r, score, ok

        bf = self._bf0.copy()
        jinv = self._jinv
        refreshed = False
        prev = np.inf
        steps = 0
        dy, r, score, ok = residual(bf)
        while not ok and steps < self.max_iter and np.isfinite(score):
            if score >= prev and not refreshed:
                try:
                    jinv = self._chord(t, y, r, count)  # this solve's only
                except RuntimeError as e:
                    logger.debug("quasi-steady chord refresh failed: %s", e)
                    break
                refreshed = True
            prev = score
            trial = self._positive_step(bf, -(jinv @ r))
            if trial is None:
                break
            bf = trial
            steps += 1
            dy, r, score, ok = residual(bf)
        self.stats["qs_inner_max"] = max(self.stats["qs_inner_max"], steps)
        # a single group's chord converges only to a root whose slope has
        # the sign of the chord's matrix: a negative one needs no check
        if ok and (
            (len(self.fast) == 1 and self._hurwitz(jinv))
            or self._attracting(t, y, r, count)
        ):
            return y, dy
        return self._fallback(t, y, count, residual, best)

    def _ptc(
        self, t: float, y: np.ndarray, count: bool, residual: Callable
    ) -> Optional[tuple[np.ndarray, np.ndarray]]:
        """The pseudo-transient continuation from the month-start ``B_f``
        (see the class docstring): ``(y, dy)`` at an attracting root, or
        None."""
        nf = len(self.fast)
        bf = np.array(self._bf0, copy=True)
        dy, r, score, ok = residual(bf)
        dtau = dtau_max = 0.0
        prev = score
        for k in range(self.ptc_max_iter):
            if ok or not np.isfinite(score):
                break
            jff = self._jff(t, y, r, count)
            if not np.all(np.isfinite(jff)):
                break
            if k == 0:
                fastest = float(np.max(np.abs(np.diag(jff))))
                dtau = 0.5 / fastest if fastest > 0.0 else 1.0
                dtau_max = 1e12 * dtau
            else:
                dtau = min(dtau * prev / score, dtau_max)  # SER
            prev = score
            try:
                delta = np.linalg.solve(np.eye(nf) / dtau - jff, r)
            except np.linalg.LinAlgError as e:
                logger.debug("quasi-steady continuation: %s", e)
                break
            trial = self._positive_step(bf, delta)
            if trial is None:
                break
            bf = trial
            dy, r, score, ok = residual(bf)
        if ok and self._attracting(t, y, r, count):
            return y, dy
        return None

    def _fallback(
        self, t: float, y: np.ndarray, count: bool, residual: Callable, best: dict
    ) -> tuple[np.ndarray, np.ndarray]:
        """After the chord: :meth:`_ptc`, then ``hybr`` in ``ln B_f`` from the
        continuation's best iterate; the first attracting root is returned as
        ``(y, dy)``, else ``RuntimeError``."""
        rhs = self.rhs
        fallbacks = self.stats["qs_fallbacks"]
        evals0 = rhs.evals
        try:
            fallbacks["ptc"] += 1
            best.update(score=np.inf, bf=np.array(self._bf0, copy=True), gain=None)
            found = self._ptc(t, y, count, residual)
            if found is not None:
                return found
            if best["gain"] is not None:
                fallbacks["hybr"] += 1
                scale = np.maximum(best["gain"], _TINY)

                def f(z):
                    with np.errstate(over="ignore", invalid="ignore"):
                        b = np.exp(np.asarray(z, dtype=float))
                    return residual(b)[1] / scale

                with np.errstate(over="ignore", invalid="ignore"):
                    sol = root(
                        f, np.log(best["bf"]), method="hybr", options={"xtol": 1e-14}
                    )
                    candidates = [np.exp(np.asarray(sol.x, dtype=float))]
                # hybr may pass a root and go on
                if best["score"] <= self.tol and not np.array_equal(
                    best["bf"], candidates[0]
                ):
                    candidates.append(np.array(best["bf"], copy=True))
                for bf in candidates:
                    dy, r, score, ok = residual(bf)
                    if ok and self._attracting(t, y, r, count):
                        return y, dy
            raise RuntimeError(
                f"quasi-steady solve failed for groups {self._label} at "
                f"t={t:.6g}: the chord Newton, a pseudo-transient continuation "
                f"and hybr found no attracting B_f > 0 with |dB_f/dt| <= "
                f"{self.tol:g} x TotGain_f (best |dB_f/dt| / TotGain_f = "
                f"{best['score']:.3g}; {fallbacks['unstable']} unstable roots "
                "rejected this month)"
            )
        finally:
            fallbacks["evals"] += rhs.evals - evals0

    def __call__(self, t: float, ys: np.ndarray) -> np.ndarray:
        """The slow states' derivative at ``(t, ys)``, ``B_f`` solved."""
        _, dy = self._solve(t, ys, True)
        return dy[self.slow]

    def expand(self, t: float, ys: np.ndarray, count: bool = False) -> np.ndarray:
        """The full state of ``rhs`` at ``(t, ys)``: ``ys`` in the slow
        states, the solved ``B_f`` in the selected groups' (``count``: the
        inner evaluations count in ``rhs.stats``)."""
        y, _ = self._solve(t, ys, count)
        return y

    def reduced_rate(self) -> float:
        """The largest ``|Re lambda|`` (per year) of the reduced Jacobian at
        the month start (``t = 0``, the month-start slow states, ``B_f``
        solved): the Schur complement ``J_ss - J_sf J_ff^-1 J_fs`` of
        ``rhs``'s forward-difference Jacobian there, ``rhs.n_state + 1``
        evaluations after the solve's (no stats). 0 when no state stays."""
        if self._ys0 is None:
            raise RuntimeError("QuasiSteady: set_month has not been called")
        if self.n_state == 0:
            return 0.0
        rhs = self.rhs
        y = self.expand(0.0, self._ys0)
        f0 = rhs._evaluate(y, None, False, 0.0)[0]
        n = len(y)
        jac = np.empty((n, n))
        for k in range(n):
            yk = y.copy()
            yk[k] = y[k] + 1.49e-8 * max(abs(y[k]), self._floor[k])
            h = yk[k] - y[k]
            jac[:, k] = (rhs._evaluate(yk, None, False, 0.0)[0] - f0) / h
        s, f = self.slow, self.fast
        try:
            schur = jac[np.ix_(s, s)] - jac[np.ix_(s, f)] @ np.linalg.solve(
                jac[np.ix_(f, f)], jac[np.ix_(f, s)]
            )
            return float(np.max(np.abs(np.linalg.eigvals(schur).real)))
        except np.linalg.LinAlgError as e:
            raise RuntimeError(
                f"quasi-steady groups {self._label}: the reduced Jacobian at "
                f"the month start cannot be formed ({e})"
            ) from e
set_month
set_month(forcing_dict: dict, state_full: ndarray, forced_mask: ndarray, forced_values: ndarray, forcing_at: Optional[Callable[[float], dict]] = None, *, y0: ndarray) -> None

:meth:ContinuousRHS.set_month, then the month's data at the month start y0 (every state of rhs): the start B_f (y0's, floored at 1e-20) and J_ff there at t = 0.

A selected group forced this month raises ValueError (the run excludes groups forced in any month); a singular or non-finite J_ff raises RuntimeError.

Source code in pypath/core/ecosim_continuous/quasi_steady.py
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 set_month(
    self,
    forcing_dict: dict,
    state_full: np.ndarray,
    forced_mask: np.ndarray,
    forced_values: np.ndarray,
    forcing_at: Optional[Callable[[float], dict]] = None,
    *,
    y0: np.ndarray,
) -> None:
    """:meth:`ContinuousRHS.set_month`, then the month's data at the
    month start ``y0`` (every state of ``rhs``): the start ``B_f``
    (``y0``'s, floored at 1e-20) and ``J_ff`` there at ``t = 0``.

    A selected group forced this month raises ``ValueError`` (the run
    excludes groups forced in any month); a singular or non-finite
    ``J_ff`` raises ``RuntimeError``."""
    rhs = self.rhs
    rhs.set_month(forcing_dict, state_full, forced_mask, forced_values, forcing_at)
    y0 = np.array(y0, dtype=float)
    if y0.shape != (rhs.n_state,):
        raise ValueError(
            f"QuasiSteady.set_month: y0 needs {rhs.n_state} states, got {y0.shape}"
        )
    if np.any(rhs._forced[self.fast]):
        raise ValueError(
            f"quasi-steady groups {self._label}: a forced group cannot be "
            "quasi-steady"
        )
    self._reset_stats()
    self._ys0 = y0[self.slow]
    self._bf0 = np.maximum(y0[self.fast], _Y_FLOOR)
    y = y0.copy()
    y[self.fast] = self._bf0
    r0 = rhs._evaluate(y, None, True, 0.0)[0][self.fast]
    self._jinv = self._chord(0.0, y, r0, True)
__call__
__call__(t: float, ys: ndarray) -> np.ndarray

The slow states' derivative at (t, ys), B_f solved.

Source code in pypath/core/ecosim_continuous/quasi_steady.py
477
478
479
480
def __call__(self, t: float, ys: np.ndarray) -> np.ndarray:
    """The slow states' derivative at ``(t, ys)``, ``B_f`` solved."""
    _, dy = self._solve(t, ys, True)
    return dy[self.slow]
expand
expand(t: float, ys: ndarray, count: bool = False) -> np.ndarray

The full state of rhs at (t, ys): ys in the slow states, the solved B_f in the selected groups' (count: the inner evaluations count in rhs.stats).

Source code in pypath/core/ecosim_continuous/quasi_steady.py
482
483
484
485
486
487
def expand(self, t: float, ys: np.ndarray, count: bool = False) -> np.ndarray:
    """The full state of ``rhs`` at ``(t, ys)``: ``ys`` in the slow
    states, the solved ``B_f`` in the selected groups' (``count``: the
    inner evaluations count in ``rhs.stats``)."""
    y, _ = self._solve(t, ys, count)
    return y
reduced_rate
reduced_rate() -> float

The largest |Re lambda| (per year) of the reduced Jacobian at the month start (t = 0, the month-start slow states, B_f solved): the Schur complement J_ss - J_sf J_ff^-1 J_fs of rhs's forward-difference Jacobian there, rhs.n_state + 1 evaluations after the solve's (no stats). 0 when no state stays.

Source code in pypath/core/ecosim_continuous/quasi_steady.py
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
def reduced_rate(self) -> float:
    """The largest ``|Re lambda|`` (per year) of the reduced Jacobian at
    the month start (``t = 0``, the month-start slow states, ``B_f``
    solved): the Schur complement ``J_ss - J_sf J_ff^-1 J_fs`` of
    ``rhs``'s forward-difference Jacobian there, ``rhs.n_state + 1``
    evaluations after the solve's (no stats). 0 when no state stays."""
    if self._ys0 is None:
        raise RuntimeError("QuasiSteady: set_month has not been called")
    if self.n_state == 0:
        return 0.0
    rhs = self.rhs
    y = self.expand(0.0, self._ys0)
    f0 = rhs._evaluate(y, None, False, 0.0)[0]
    n = len(y)
    jac = np.empty((n, n))
    for k in range(n):
        yk = y.copy()
        yk[k] = y[k] + 1.49e-8 * max(abs(y[k]), self._floor[k])
        h = yk[k] - y[k]
        jac[:, k] = (rhs._evaluate(yk, None, False, 0.0)[0] - f0) / h
    s, f = self.slow, self.fast
    try:
        schur = jac[np.ix_(s, s)] - jac[np.ix_(s, f)] @ np.linalg.solve(
            jac[np.ix_(f, f)], jac[np.ix_(f, s)]
        )
        return float(np.max(np.abs(np.linalg.eigvals(schur).real)))
    except np.linalg.LinAlgError as e:
        raise RuntimeError(
            f"quasi-steady groups {self._label}: the reduced Jacobian at "
            f"the month start cannot be formed ({e})"
        ) from e

MonthResult dataclass

One integrated month.

y_end holds every state; y_mean only the biomass states (groups 1..n_bio; any states beyond them are feeding times, which rsim_run reads from y_end[n_bio:]). food_gain_mean and loss_rate_mean are full length, indexed by group like deriv_vector's rates (index 0 = Outside), so food_gain_mean[1:n_bio + 1] lines up with y_mean. A test double must follow the same convention: rates(y) returns full-length arrays whose entries 1..n_bio correspond to y.

y_end is floored at 1e-20; y_mean is the quadrature mean of the dense output clipped at 0 (not floored), so a group at the floor has a mean of 0, not a small negative number. loss_rate_mean is the time mean of LossPropToB / B (0 where B = 0 at a node).

exchange_mean is the time mean of rhs.exchange (NaN when rhs has none) and pool_net_mean that of DetGain - DetLoss, full length like food_gain_mean (None when the rates carry no DetGain). Both come from the quadrature's evaluations of the rates.

steps is the number of solver steps (len(sol.t) - 1). last_step is the last full step, a diagnostic only (no month starts from it): the second-to-last step (the last is truncated at dt), or the only step of a one-step month. status and message are as SciPy reports them; t_reached is the end of the interval reached (dt unless the solve failed). degraded is True when any of the means fell back to the start state: non-finite dense output, non-finite rates at a quadrature node, or no interval to average over. A failed solve whose means are taken over the interval reached is not degraded; status and t_reached show it.

Source code in pypath/core/ecosim_continuous/month.py
 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
@dataclass
class MonthResult:
    """One integrated month.

    ``y_end`` holds every state; ``y_mean`` only the biomass states (groups
    ``1..n_bio``; any states beyond them are feeding times, which
    ``rsim_run`` reads from ``y_end[n_bio:]``).
    ``food_gain_mean`` and ``loss_rate_mean`` are full length, indexed by group
    like ``deriv_vector``'s rates (index 0 = Outside), so
    ``food_gain_mean[1:n_bio + 1]`` lines up with ``y_mean``. A test double
    must follow the same convention: ``rates(y)`` returns full-length arrays
    whose entries ``1..n_bio`` correspond to ``y``.

    ``y_end`` is floored at 1e-20; ``y_mean`` is the quadrature mean of the
    dense output clipped at 0 (not floored), so a group at the floor has a
    mean of 0, not a small negative number. ``loss_rate_mean`` is the time
    mean of ``LossPropToB / B`` (0 where B = 0 at a node).

    ``exchange_mean`` is the time mean of ``rhs.exchange`` (NaN when ``rhs``
    has none) and ``pool_net_mean`` that of ``DetGain - DetLoss``, full
    length like ``food_gain_mean`` (None when the rates carry no
    ``DetGain``). Both come from the quadrature's evaluations of the rates.

    ``steps`` is the number of solver steps (``len(sol.t) - 1``).
    ``last_step`` is the last full step, a diagnostic only (no month starts
    from it): the second-to-last step (the last is truncated at ``dt``), or the only step
    of a one-step month. ``status``
    and ``message`` are as SciPy reports them; ``t_reached`` is the end of the
    interval reached (``dt`` unless the solve failed).
    ``degraded`` is True when any of the means fell back to the start state:
    non-finite dense output, non-finite rates at a quadrature node, or no
    interval to average over. A failed solve whose means are taken over the
    interval reached is not degraded; ``status`` and ``t_reached`` show it.
    """

    y_end: np.ndarray
    y_mean: np.ndarray
    food_gain_mean: np.ndarray
    loss_rate_mean: np.ndarray
    nfev: int
    njev: int
    nlu: int
    steps: int
    status: int
    message: str
    t_reached: float
    degraded: bool
    exchange_mean: float = float("nan")
    pool_net_mean: Optional[np.ndarray] = None
    last_step: Optional[float] = None

recalibrated_hden0

recalibrated_hden0(params_dict: dict, cmco_qb: ndarray) -> np.ndarray

Hden0 that makes the base state an exact fixed point of the kernel.

1 / (1 - q0 / cmco_qb) for groups with cmco_qb > 0, else 1, where q0_j = QQbase[1:, j].sum() / Bbase[j] (link flows only; diet import is row 0 and stays out). Raises ValueError naming the groups where q0 >= cmco_qb, which have no positive Hden0.

Source code in pypath/core/ecosim_continuous/hden.py
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
def recalibrated_hden0(params_dict: dict, cmco_qb: np.ndarray) -> np.ndarray:
    """Hden0 that makes the base state an exact fixed point of the kernel.

    ``1 / (1 - q0 / cmco_qb)`` for groups with ``cmco_qb > 0``, else 1, where
    ``q0_j = QQbase[1:, j].sum() / Bbase[j]`` (link flows only; diet import is
    row 0 and stays out). Raises ``ValueError`` naming the groups where
    ``q0 >= cmco_qb``, which have no positive Hden0.
    """
    cmco_qb = np.asarray(cmco_qb, dtype=float)
    qbase = np.asarray(params_dict["QQbase"], dtype=float)
    bbase = np.asarray(params_dict["Bbase"], dtype=float)
    out = np.ones_like(cmco_qb)
    ok = (cmco_qb > 0) & (bbase > 0)
    ratio = qbase[1:, :].sum(axis=0)[ok] / bbase[ok] / cmco_qb[ok]
    bad = np.flatnonzero(ok)[ratio >= 1.0]
    if bad.size:
        raise ValueError(
            "handling time: the base link consumption reaches CmCo x QB for "
            f"groups {bad.tolist()}, so they have no positive Hden0"
        )
    out[ok] = 1.0 / (1.0 - ratio)
    return out

hden_index

hden_index(y_full: ndarray, params_dict: dict, forcing: dict) -> np.ndarray

Predator abundance in biomass units, as deriv_vector's Hden block.

The state biomass, except for stanza groups where it is Bbase * StanzaPredRatio (ratio finite).

Source code in pypath/core/ecosim_continuous/hden.py
49
50
51
52
53
54
55
56
57
58
59
60
def hden_index(y_full: np.ndarray, params_dict: dict, forcing: dict) -> np.ndarray:
    """Predator abundance in biomass units, as ``deriv_vector``'s Hden block.

    The state biomass, except for stanza groups where it is
    ``Bbase * StanzaPredRatio`` (ratio finite).
    """
    index = np.array(y_full, dtype=float, copy=True)
    ratio = forcing.get("StanzaPredRatio")
    if ratio is not None:
        has = np.isfinite(ratio)
        index[has] = np.asarray(params_dict["Bbase"], dtype=float)[has] * ratio[has]
    return index

iterate_hden

iterate_hden(g: Callable[[ndarray], ndarray], h0: ndarray, active: ndarray, *, tol: float = 1e-12, max_iter: int = 30, fallback: bool = True, accel: str = 'bracketed', coupled: bool = False, dg: Optional[Callable[[ndarray], ndarray]] = None) -> tuple[np.ndarray, int]

Solve H = g(H) on the active components, from h0.

g maps a full-length H to a full-length array; the inactive components stay at h0. An iterate is accepted when its residual max |g(H) - H| / H over the active components is <= tol and every active H is finite and > 0; the accepted iterate is the one whose residual was measured.

accel="bracketed" (with coupled False, i.e. each component of g depending on its own H only) runs a secant per component inside a bracket, with the Illinois modification: the start a = h0, the second end 1e6 where F = g - H is > 0 at a, else 1. A component whose two ends do not straddle a sign change takes undamped passes (H <- g(H)) instead. A component that converges is held there, which is sound only because the components are independent. With accel="none" or coupled True every pass is the plain map H <- g(H) on every active component, none held: on a coupled map a converged component's residual moves with the others. After max_iter passes beyond the start (and the bracket end), fallback hands the active components to scipy.optimize.root(method="hybr").

accel="newton" needs dg (dg(H), full length: the diagonal dg_j / dH_j) and independent components (coupled False, else ValueError). It runs a safeguarded Newton per component, H <- H - F / (dg - 1), inside a bracket that starts as [1, 1e6) (F(1) >= 0 because g >= 1, so the end 1 may be the root) and narrows to the points where F was measured > 0 (lower, then open) or < 0 (upper, open); a step that is not finite or leaves the bracket bisects it. A converged component is held. After max_iter passes (the start included) the unconverged solve continues as the bracketed secant from the last iterate, then hybr as above; its passes add to the count.

Returns (H, passes), passes being the calls of g. Raises RuntimeError naming "handling time" and the unconverged components when nothing is accepted.

Source code in pypath/core/ecosim_continuous/hden.py
 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
def iterate_hden(
    g: Callable[[np.ndarray], np.ndarray],
    h0: np.ndarray,
    active: np.ndarray,
    *,
    tol: float = 1e-12,
    max_iter: int = 30,
    fallback: bool = True,
    accel: str = "bracketed",
    coupled: bool = False,
    dg: Optional[Callable[[np.ndarray], np.ndarray]] = None,
) -> tuple[np.ndarray, int]:
    """Solve ``H = g(H)`` on the ``active`` components, from ``h0``.

    ``g`` maps a full-length H to a full-length array; the inactive
    components stay at ``h0``. An iterate is accepted when its residual
    ``max |g(H) - H| / H`` over the active components is <= ``tol`` and
    every active H is finite and > 0; the accepted iterate is the one whose
    residual was measured.

    ``accel="bracketed"`` (with ``coupled`` False, i.e. each component of
    ``g`` depending on its own H only) runs a secant per component inside a
    bracket, with the Illinois modification: the start ``a = h0``, the
    second end 1e6 where ``F = g - H`` is > 0 at ``a``, else 1. A component
    whose two ends do not straddle a sign change takes undamped passes
    (``H <- g(H)``) instead. A component that converges is held there, which
    is sound only because the components are independent. With
    ``accel="none"`` or ``coupled`` True every pass is the plain map
    ``H <- g(H)`` on every active component, none held: on a coupled map a
    converged component's residual moves with the others. After ``max_iter``
    passes beyond the start (and the bracket end), ``fallback`` hands the
    active components to ``scipy.optimize.root(method="hybr")``.

    ``accel="newton"`` needs ``dg`` (``dg(H)``, full length: the diagonal
    ``dg_j / dH_j``) and independent components (``coupled`` False, else
    ``ValueError``). It runs a safeguarded Newton per component, ``H <- H -
    F / (dg - 1)``, inside a bracket that starts as ``[1, 1e6)`` (``F(1) >=
    0`` because ``g >= 1``, so the end 1 may be the root) and narrows to the
    points where ``F`` was measured > 0 (lower, then open) or < 0 (upper,
    open); a step that is not finite or leaves the bracket bisects it. A
    converged component is held. After ``max_iter`` passes (the start
    included) the unconverged solve continues as the bracketed secant from
    the last iterate, then ``hybr`` as above; its passes add to the count.

    Returns ``(H, passes)``, ``passes`` being the calls of ``g``. Raises
    ``RuntimeError`` naming "handling time" and the unconverged components
    when nothing is accepted.
    """
    if accel not in ("bracketed", "none", "newton"):
        raise ValueError(
            f"accel must be 'bracketed', 'none' or 'newton', got {accel!r}"
        )
    if accel == "newton" and dg is None:
        raise ValueError("accel='newton' needs dg, the diagonal of dg/dH")
    if accel == "newton" and coupled:
        raise ValueError(
            "accel='newton' needs independent components; the map is coupled"
        )
    active = np.asarray(active, dtype=bool)
    h_start = np.array(h0, dtype=float, copy=True)
    idx = np.flatnonzero(active)
    if idx.size == 0:
        return h_start, 0
    passes = 0

    def full(x):
        hv = h_start.copy()
        hv[idx] = x
        return hv

    def G(x):
        """``g`` on the active components; one pass."""
        nonlocal passes
        passes += 1
        return np.asarray(g(full(x)), dtype=float)[idx]

    def F(x):
        return G(x) - x

    def rel(x, fx):
        """Per-component residual; inf where H is not finite and > 0."""
        good = np.isfinite(x) & (x > 0.0) & np.isfinite(fx)
        out = np.full(x.shape, np.inf)
        out[good] = np.abs(fx[good]) / x[good]
        return out

    if accel == "newton":
        assert dg is not None  # checked above
        x = h_start[idx].copy()
        lo, hi = np.ones(idx.size), np.full(idx.size, 1e6)
        lo_measured = np.zeros(idx.size, dtype=bool)  # else the known end 1
        r = np.full(idx.size, np.inf)
        for _ in range(max_iter):
            hv = full(x)  # one array for g and dg (a caller may cache by it)
            passes += 1
            fx = np.asarray(g(hv), dtype=float)[idx] - x
            r = rel(x, fx)
            if np.all(r <= tol):
                return hv, passes
            slope = np.asarray(dg(hv), dtype=float)[idx] - 1.0
            up = fx > 0.0
            lo_measured |= up & (x >= lo)
            lo = np.where(up, np.maximum(lo, x), lo)
            hi = np.where(fx < 0.0, np.minimum(hi, x), hi)
            with np.errstate(divide="ignore", invalid="ignore"):
                step = x - fx / slope
            out = (
                ~np.isfinite(step)
                | (step < lo)
                | (lo_measured & (step == lo))
                | (step >= hi)
            )
            step = np.where(out, 0.5 * (lo + hi), step)
            x = np.where(r <= tol, x, step)
        logger.debug(
            "handling time: %d Newton passes left residual %.3e; the "
            "bracketed secant continues",
            passes,
            float(np.max(r)),
        )
        h, more = iterate_hden(
            g, full(x), active, tol=tol, max_iter=max_iter, fallback=fallback
        )
        return h, passes + more

    a = h_start[idx].copy()
    ga = G(a)  # g at the end a, kept with it
    fa = ga - a
    r = rel(a, fa)
    if np.all(r <= tol):
        return full(a), passes
    n = idx.size
    # the bracketed mode holds converged components (independent ones only)
    bracketed = accel == "bracketed" and not coupled
    held = (r <= tol) if bracketed else np.zeros(n, dtype=bool)
    x_held = a.copy()
    secant = np.zeros(n, dtype=bool)
    b, fb = a.copy(), fa.copy()
    side = np.zeros(n, dtype=int)  # -1: a was kept last pass; +1: b was
    x = a
    if bracketed:
        b = np.where(held, a, np.where(fa > 0.0, 1e6, 1.0))
        fb = F(b)
        r = rel(b, fb)
        if np.all(r <= tol):
            return full(b), passes
        new = ~held & (r <= tol)
        x_held[new] = b[new]
        held |= new
        secant = ~held & (np.sign(fa) * np.sign(fb) < 0.0)
    g_cur = ga  # undamped components: g at the last point they took
    for _ in range(max_iter):
        prop = g_cur  # the plain map, H <- g(H)
        if secant.any():
            with np.errstate(divide="ignore", invalid="ignore"):
                xs = (a * fb - b * fa) / (fb - fa)
            xs = np.where(np.isfinite(xs), xs, 0.5 * (a + b))
            prop = np.where(secant, xs, prop)
        x = np.where(held, x_held, prop)
        gx = G(x)
        fx = gx - x
        r = rel(x, fx)
        if np.all(r <= tol):
            return full(x), passes
        g_cur = np.where(secant, g_cur, gx)
        if bracketed:
            new = ~held & (r <= tol)
            x_held[new] = x[new]
            held |= new
        if secant.any():
            # a non-finite F leaves no bracket: undamped from the end a
            lost = secant & ~np.isfinite(fx)
            secant &= ~held & ~lost
            to_b = secant & (np.sign(fx) == np.sign(fb))
            to_a = secant & ~to_b
            # Illinois: halve the kept end's F when it is kept twice running
            fa = np.where(to_b & (side == -1), 0.5 * fa, fa)
            fb = np.where(to_a & (side == 1), 0.5 * fb, fb)
            b, fb = np.where(to_b, x, b), np.where(to_b, fx, fb)
            a, fa = np.where(to_a, x, a), np.where(to_a, fx, fa)
            ga = np.where(to_a, gx, ga)
            side = np.where(to_b, -1, np.where(to_a, 1, side))
            g_cur = np.where(lost, ga, g_cur)
    if fallback:
        logger.debug(
            "handling time: %d passes left residual %.3e; hybr finishes",
            passes,
            float(np.max(r)),
        )
        x0 = np.where(held, x_held, x)
        x0 = np.where(np.isfinite(x0) & (x0 > 0.0), x0, h_start[idx])
        sol = root(F, x0, method="hybr", tol=tol)
        x = np.asarray(sol.x, dtype=float)
        r = np.full(n, np.inf)
        if np.all(np.isfinite(x)):
            r = rel(x, F(x))
            if np.all(r <= tol):
                return full(x), passes
    bad = idx[~(r <= tol)]
    positive = bool(np.all(np.isfinite(x) & (x > 0.0)))
    what = "for a pooled (ScrambleSelf > 0) map " if coupled else ""
    raise RuntimeError(
        f"handling time did not converge {what}(residual {float(np.max(r)):.3e}"
        f"{'' if positive else '; an Hden is not finite and > 0'}) for groups "
        f"{bad.tolist()}"
    )

solve_hden

solve_hden(y_full, params_dict, forcing, fishing, index, cmco_qb, *, h0=None, tol=1e-12, max_iter=30, fallback=True)

Solve H = 1 + H * q(H) / (cmco_qb * index) at the state y_full.

The full-derivative reference of :func:solve_hden_kernel. Groups with cmco_qb > 0 and index > 0 are solved; the rest keep H = 1. q(H) is the link consumption of one deriv_vector call with _hden_exact (and no _hden_solver) on a shallow copy of params_dict; the caller's dict and arrays are never written. :func:iterate_hden iterates from h0 (default params_dict["_hden0"]) with tol, max_iter and fallback, as a coupled map when a link has ScrambleSelf > 0.

Returns (H, n_evaluations); raises RuntimeError naming the unconverged groups when no solution is found.

Source code in pypath/core/ecosim_continuous/hden.py
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
def solve_hden(
    y_full,
    params_dict,
    forcing,
    fishing,
    index,
    cmco_qb,
    *,
    h0=None,
    tol=1e-12,
    max_iter=30,
    fallback=True,
):
    """Solve ``H = 1 + H * q(H) / (cmco_qb * index)`` at the state ``y_full``.

    The full-derivative reference of :func:`solve_hden_kernel`. Groups with
    ``cmco_qb > 0`` and ``index > 0`` are solved; the rest keep H = 1.
    ``q(H)`` is the link consumption of one ``deriv_vector`` call with
    ``_hden_exact`` (and no ``_hden_solver``) on a shallow copy of
    ``params_dict``; the caller's dict and arrays are never written.
    :func:`iterate_hden` iterates from ``h0`` (default
    ``params_dict["_hden0"]``) with ``tol``, ``max_iter`` and ``fallback``,
    as a coupled map when a link has ``ScrambleSelf > 0``.

    Returns ``(H, n_evaluations)``; raises ``RuntimeError`` naming the
    unconverged groups when no solution is found.
    """
    cmco_qb = np.asarray(cmco_qb, dtype=float)
    index = np.asarray(index, dtype=float)
    active = (cmco_qb > 0) & (index > 0)
    h = np.ones(cmco_qb.shape, dtype=float)
    start = params_dict["_hden0"] if h0 is None else h0
    h[active] = np.asarray(start, dtype=float)[active]

    pd_local = dict(params_dict)
    pd_local["_hden_exact"] = True
    pd_local.pop("_hden_solver", None)  # iterate the given H, not a solve
    pd_local["_hden"] = h.copy()
    if pd_local.get("_det_out") is not None:  # output buffer deriv_vector writes
        pd_local["_det_out"] = np.array(pd_local["_det_out"], copy=True)
    state = np.array(y_full, dtype=float, copy=True)
    denom = np.where(active, cmco_qb * index, 1.0)
    coupled = _pooled_map(pd_local, state)

    def g(hv):
        pd_local["_hden"] = np.array(hv, dtype=float, copy=True)
        rates: dict = {}
        deriv_vector(state.copy(), pd_local, forcing, fishing, rates=rates)
        new = np.ones_like(hv)
        new[active] = (
            1.0 + hv[active] * rates["HdenConsumption"][active] / denom[active]
        )
        return new

    return iterate_hden(
        g, h, active, tol=tol, max_iter=max_iter, fallback=fallback, coupled=coupled
    )

solve_hden_kernel

solve_hden_kernel(inputs: KernelInputs, *, tol: float = 1e-12, max_iter: int = 30, fallback: bool = True) -> tuple[np.ndarray, int]

Solve Hden on the consumption kernel alone, at the state inputs describe (deriv_vector hands them to params["_hden_solver"]).

As :func:solve_hden with q(H) = HdenKernel(inputs).q(H), from inputs.hden0: groups with cmco_qb > 0 and index > 0 are solved, the rest keep H = 1. The map is coupled when a consuming link has ScrambleSelf > 0, and then takes undamped passes. Otherwise each predator is solved by Newton (iterate_hden(accel="newton")), g and dg = (q + H dq) / (cmco_qb * index) coming from one :meth:HdenKernel.q_and_dq per pass. Returns (H, passes); raises RuntimeError naming "handling time" and the groups when no solution is found.

Source code in pypath/core/ecosim_continuous/hden.py
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
def solve_hden_kernel(
    inputs: KernelInputs,
    *,
    tol: float = 1e-12,
    max_iter: int = 30,
    fallback: bool = True,
) -> tuple[np.ndarray, int]:
    """Solve Hden on the consumption kernel alone, at the state ``inputs``
    describe (``deriv_vector`` hands them to ``params["_hden_solver"]``).

    As :func:`solve_hden` with ``q(H) = HdenKernel(inputs).q(H)``, from
    ``inputs.hden0``: groups with ``cmco_qb > 0`` and ``index > 0`` are
    solved, the rest keep H = 1. The map is coupled when a consuming link has
    ``ScrambleSelf > 0``, and then takes undamped passes. Otherwise each
    predator is solved by Newton (``iterate_hden(accel="newton")``), ``g``
    and ``dg = (q + H dq) / (cmco_qb * index)`` coming from one
    :meth:`HdenKernel.q_and_dq` per pass. Returns ``(H, passes)``; raises
    ``RuntimeError`` naming "handling time" and the groups when no solution
    is found.
    """
    cmco_qb = np.asarray(inputs.cmco_qb, dtype=float)
    index = np.asarray(inputs.index, dtype=float)
    active = (cmco_qb > 0) & (index > 0)
    denom = np.where(active, cmco_qb * index, 1.0)
    kernel = HdenKernel(inputs)
    h0 = np.where(active, np.asarray(inputs.hden0, dtype=float), 1.0)

    if kernel.coupled():

        def g_coupled(hv):
            new = np.ones_like(hv)
            new[active] = 1.0 + hv[active] * kernel.q(hv)[active] / denom[active]
            return new

        return iterate_hden(
            g_coupled,
            h0,
            active,
            tol=tol,
            max_iter=max_iter,
            fallback=fallback,
            coupled=True,
        )

    # the latest q_and_dq, keyed by the H it was taken at: iterate_hden
    # passes g and dg the same array, so identity is checked first
    last: dict = {}

    def q_dq(hv):
        if last.get("ref") is not hv:
            if "h" not in last or not np.array_equal(last["h"], hv):
                q, dq = kernel.q_and_dq(hv)
                last.update(h=np.array(hv, copy=True), q=q, dq=dq)
            last["ref"] = hv
        return last["q"], last["dq"]

    def g(hv):
        q, _ = q_dq(hv)
        new = np.ones_like(hv)
        new[active] = 1.0 + hv[active] * q[active] / denom[active]
        return new

    def dg(hv):
        q, dq = q_dq(hv)
        out = np.zeros_like(hv)
        out[active] = (q[active] + hv[active] * dq[active]) / denom[active]
        return out

    return iterate_hden(
        g,
        h0,
        active,
        tol=tol,
        max_iter=max_iter,
        fallback=fallback,
        accel="newton",
        dg=dg,
    )

continuous_emig

continuous_emig(emig: Optional[ndarray], emig_rate: Optional[ndarray], n_living: int) -> Optional[np.ndarray]

R4: emigration rates of living groups for the continuous path.

EwE sets Emig = Emigration / B0 for living groups (so emig == 0 means no Emigration was entered) and never reads EmigRate for them. Here a living group with emig == 0 and emig_rate > 0 takes the rate; every other entry keeps emig. With emig None, the rates start from zeros. Returns a new array, or None when both inputs are None or the result is all zero.

Source code in pypath/core/ecosim_continuous/rhs.py
 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
def continuous_emig(
    emig: Optional[np.ndarray], emig_rate: Optional[np.ndarray], n_living: int
) -> Optional[np.ndarray]:
    """R4: emigration rates of living groups for the continuous path.

    EwE sets ``Emig = Emigration / B0`` for living groups (so ``emig == 0``
    means no Emigration was entered) and never reads ``EmigRate`` for them.
    Here a living group with ``emig == 0`` and ``emig_rate > 0`` takes the
    rate; every other entry keeps ``emig``. With ``emig`` None, the rates
    start from zeros. Returns a new array, or None when both inputs are None
    or the result is all zero.
    """
    if emig is None and emig_rate is None:
        return None
    rate = None if emig_rate is None else np.asarray(emig_rate, dtype=float)
    living = slice(1, n_living + 1)
    if emig is None:
        if rate is None or not np.any(rate[living] > 0):
            return None
        out = np.zeros(len(rate))
    else:
        out = np.array(emig, dtype=float, copy=True)
    if rate is not None:
        take = (out[living] == 0) & (rate[living] > 0)
        out[living] = np.where(take, rate[living], out[living])
    if not np.any(out != 0):
        return None
    return out

neutral_forcing

neutral_forcing(params_dict: dict) -> dict

Unforced monthly forcing: ones for time/prey/search/mortality/effort, zeros for forced biomass and migration.

Source code in pypath/core/ecosim_continuous/forcing.py
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
def neutral_forcing(params_dict: dict) -> dict:
    """Unforced monthly forcing: ones for time/prey/search/mortality/effort,
    zeros for forced biomass and migration."""
    n1 = int(params_dict["NUM_GROUPS"]) + 1
    ones = np.ones(n1)
    return {
        "Ftime": ones.copy(),
        "ForcedBio": np.zeros(n1),
        "ForcedMigrate": np.zeros(n1),
        "ForcedPrey": ones.copy(),
        "PP_forcing": ones.copy(),
        "ForcedSearch": ones.copy(),
        "ForcedMort": ones.copy(),
        "ForcedEffort": np.ones(int(params_dict.get("NUM_GEARS", 0)) + 1),
    }

feeding_time

feeding_time(params, risk0: Optional[ndarray]) -> Optional[FeedingTime]

The feeding-time states of a scenario's params, or None.

risk0 is the setup's base predation risk (None when RiskTime is off). None is returned when no living group has FtimeAdj > 0.

Source code in pypath/core/ecosim_continuous/feeding.py
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
def feeding_time(params, risk0: Optional[np.ndarray]) -> Optional[FeedingTime]:
    """The feeding-time states of a scenario's ``params``, or None.

    ``risk0`` is the setup's base predation risk (None when RiskTime is
    off). None is returned when no living group has ``FtimeAdj > 0``.
    """
    adj = np.asarray(params.FtimeAdj, dtype=float)
    n_full = len(adj)
    living = np.zeros(n_full, dtype=bool)
    living[1 : int(params.NUM_LIVING) + 1] = True
    groups = np.flatnonzero(living & (adj > 0))
    if groups.size == 0:
        return None
    cap_src = getattr(params, "FtimeMax", None)
    cap = (
        np.full(n_full, 2.0)
        if cap_src is None
        else np.array(cap_src, dtype=float, copy=True)
    )
    if risk0 is None:
        risk_time = np.zeros(n_full)
        risk = np.zeros(n_full)
    else:
        risk_time = np.array(params.RiskTime, dtype=float, copy=True)
        risk = np.array(risk0, dtype=float, copy=True)
    return FeedingTime(
        groups=groups,
        adj=adj.copy(),
        qbopt=np.array(params.FtimeQBOpt, dtype=float, copy=True),
        cap=cap,
        risk_time=risk_time,
        risk0=risk,
        mo=np.array(params.MzeroMort, dtype=float, copy=True),
        lower=float(getattr(params, "ForagingTimeLowerLimit", 0.1)),
    )

ftime_target

ftime_target(ft, adj, qopt, food_gain, index, lower, cap) -> np.ndarray

_ftime_update_rpath over arrays, clipped to [lower, cap].

lower + (1 - lower) * ft * ((1 - adj) + adj * qopt / (food_gain / index)), in the scalar rule's order of operations. Where food_gain, index or qopt is <= 0 the feeding time is kept (no division at a zero index).

Source code in pypath/core/ecosim_continuous/feeding.py
73
74
75
76
77
78
79
80
81
82
83
84
85
86
def ftime_target(ft, adj, qopt, food_gain, index, lower, cap) -> np.ndarray:
    """``_ftime_update_rpath`` over arrays, clipped to ``[lower, cap]``.

    ``lower + (1 - lower) * ft * ((1 - adj) + adj * qopt / (food_gain /
    index))``, in the scalar rule's order of operations. Where ``food_gain``,
    ``index`` or ``qopt`` is <= 0 the feeding time is kept (no division at a
    zero index).
    """
    ft = np.asarray(ft, dtype=float)
    ok = (food_gain > 0) & (index > 0) & (qopt > 0)
    safe_index = np.where(ok, index, 1.0)
    actual_qb = np.where(ok, food_gain, 1.0) / safe_index
    new = lower + (1.0 - lower) * ft * ((1.0 - adj) + adj * qopt / actual_qb)
    return np.clip(np.where(ok, new, ft), lower, cap)

exchange_rate

exchange_rate(rates: dict, y_full: ndarray, params_dict: dict, forcing: dict) -> float

The net external flux of groups 1..n_bio (per year), from one evaluation's rates at the full state y_full.

It uses exactly these terms:

  • in: rates["Production"] of the living groups that are not consumers (producers, and groups with QB 0, drawn from no food); rates["Import"]; params_dict["Immigration"] and forcing["ForcedMigrate"] of the living groups; and the pools' _det_inflow (params_dict["DetInput"] plus pool Immigration);
  • out: respiration (1 - Unassim) x rates["FoodGain"] of the living groups, less rates["Production"] for consumers; rates["Landed"] of groups 1..n_bio (the catch of the fishing links to no detritus pool, plus the forced F; under the EwE rule none from a pool, whose catch stays in it); rates["EmigLoss"] of the living groups; under the EwE rule (DetPassedProp set) a pool's params_dict["Emig"] x y_full; and rates["DetExport"] (link flows to outside and, under the EwE rule, (DetritusOut - DetPassedProp) x B, both from parameters).

Consumers are told apart as the living kernel does (PP_type as an int <= 0, then QB > 0). No flow between groups enters: not predation, other mortality, unassimilated food, the flows between pools, nor discards. A transfer the derivative does not close therefore leaves sum(dy) - exchange nonzero.

Source code in pypath/core/ecosim_continuous/rhs.py
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
def exchange_rate(
    rates: dict, y_full: np.ndarray, params_dict: dict, forcing: dict
) -> float:
    """The net external flux of groups ``1..n_bio`` (per year), from one
    evaluation's ``rates`` at the full state ``y_full``.

    It uses exactly these terms:

    - in: ``rates["Production"]`` of the living groups that are not
      consumers (producers, and groups with QB 0, drawn from no food);
      ``rates["Import"]``; ``params_dict["Immigration"]`` and
      ``forcing["ForcedMigrate"]`` of the living groups; and the pools'
      ``_det_inflow`` (``params_dict["DetInput"]`` plus pool Immigration);
    - out: respiration ``(1 - Unassim) x rates["FoodGain"]`` of the living
      groups, less ``rates["Production"]`` for consumers;
      ``rates["Landed"]`` of groups ``1..n_bio`` (the catch of the fishing
      links to no detritus pool, plus the forced F; under the EwE rule none
      from a pool, whose catch stays in it); ``rates["EmigLoss"]``
      of the living groups; under the EwE rule (``DetPassedProp`` set) a
      pool's ``params_dict["Emig"] x y_full``; and ``rates["DetExport"]``
      (link flows to outside and, under the EwE rule, (DetritusOut -
      DetPassedProp) x B, both from parameters).

    Consumers are told apart as the living kernel does (PP_type as an int
    <= 0, then QB > 0). No flow between groups enters: not predation, other
    mortality, unassimilated food, the flows between pools, nor discards. A
    transfer the derivative does not close therefore leaves
    ``sum(dy) - exchange`` nonzero.
    """
    nl = int(params_dict["NUM_LIVING"])
    n_bio = nl + int(params_dict["NUM_DEAD"])
    n_full = int(params_dict["NUM_GROUPS"]) + 1
    lv = slice(1, nl + 1)
    dead = slice(nl + 1, n_bio + 1)
    production = np.asarray(rates["Production"], dtype=float)[lv]
    food = np.asarray(rates["FoodGain"], dtype=float)[lv]
    pp_type = np.asarray(params_dict.get("PP_type", np.zeros(n_full)))
    qb = np.asarray(params_dict.get("QB", np.zeros(n_full)), dtype=float)
    unassim = np.asarray(params_dict.get("Unassim", np.zeros(n_full)), dtype=float)
    consumer = (pp_type[lv].astype(np.int64) <= 0) & (qb[lv] > 0.0)
    gain = float(production[~consumer].sum())
    gain += float(np.asarray(rates["Import"], dtype=float)[lv].sum())
    immigration = params_dict.get("Immigration")
    if immigration is not None:
        gain += float(np.asarray(immigration, dtype=float)[lv].sum())
    migrate = forcing.get("ForcedMigrate")
    if migrate is not None:
        gain += float(np.asarray(migrate, dtype=float)[lv].sum())
    det_in = _det_inflow(params_dict.get("DetInput"), immigration, nl, n_bio - nl)
    if det_in is not None:
        gain += float(np.asarray(det_in, dtype=float)[dead].sum())
    respiration = (1.0 - unassim[lv]) * food - np.where(consumer, production, 0.0)
    loss = float(respiration.sum())
    loss += float(np.asarray(rates["Landed"], dtype=float)[1 : n_bio + 1].sum())
    loss += float(np.asarray(rates["EmigLoss"], dtype=float)[lv].sum())
    loss += float(np.asarray(rates["DetExport"], dtype=float)[1 : n_bio + 1].sum())
    emig = params_dict.get("Emig")
    if emig is not None and params_dict.get("DetPassedProp") is not None:
        pool_b = np.asarray(y_full, dtype=float)[dead]
        loss += float((np.asarray(emig, dtype=float)[dead] * pool_b).sum())
    return gain - loss

continuous_options

continuous_options(method, solver_options: Optional[dict], n_bio: int) -> dict

rsim_run's checks of a continuous method and its solver_options.

method is a name in METHOD_NAMES, in any case; anything else, a non-string included, raises ValueError listing the methods (rsim_run calls this for every method but RK4 and AB). solver_options takes rtol (> 0, default 1e-6), atol (a scalar

0 or n_bio values > 0), corrections (True or False, default True), on_failure ("raise", the default, or "warn"), hden_tol (the handling-time tolerance, a number in (0, 1e-8], default 1e-12), jacobian ("reuse", the default: :class:JacobianReuse; or "solver": the solver's own Jacobians) and forcing_interpolation ("constant", the default, "linear" or "smooth": a model option, :class:ForcingInterpolant) and positivity ("clip", the default, or "log": a numerical option, the same equations with the biomass states integrated as ln B, see :func:integrate_month), fast_groups ("states", the default, or "quasi-steady": a model option, :class:QuasiSteady) and qs_rate (a number > 0 per year, default 365: the base loss rate above which a flagged group is quasi-steady; given with fast_groups="states" it is unused, which logs a WARNING); other keys and invalid values raise ValueError.

Returns a dict with keys method (lower case), rtol (float), atol (None when not given, else an ndarray, 0-d for a scalar), on_failure, corrections (bool), hden_tol (float), jacobian, forcing_interpolation, positivity, fast_groups and qs_rate (float).

Source code in pypath/core/ecosim_continuous/options.py
 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
def continuous_options(method, solver_options: Optional[dict], n_bio: int) -> dict:
    """``rsim_run``'s checks of a continuous method and its ``solver_options``.

    ``method`` is a name in ``METHOD_NAMES``, in any case; anything else, a
    non-string included, raises ``ValueError`` listing the methods
    (``rsim_run`` calls this for every method but RK4 and AB).
    ``solver_options`` takes ``rtol`` (> 0, default 1e-6), ``atol`` (a scalar
    > 0 or ``n_bio`` values > 0), ``corrections`` (True or False, default
    True), ``on_failure`` (``"raise"``, the default, or ``"warn"``),
    ``hden_tol`` (the handling-time tolerance, a number in (0, 1e-8],
    default 1e-12), ``jacobian`` (``"reuse"``, the default:
    :class:`JacobianReuse`; or ``"solver"``: the solver's own Jacobians) and
    ``forcing_interpolation`` (``"constant"``, the default, ``"linear"`` or
    ``"smooth"``: a model option, :class:`ForcingInterpolant`) and
    ``positivity`` (``"clip"``, the default, or ``"log"``: a numerical
    option, the same equations with the biomass states integrated as
    ``ln B``, see :func:`integrate_month`),
    ``fast_groups`` (``"states"``, the default, or ``"quasi-steady"``: a
    model option, :class:`QuasiSteady`) and ``qs_rate`` (a number > 0 per
    year, default 365: the base loss rate above which a flagged group is
    quasi-steady; given with ``fast_groups="states"`` it is unused, which
    logs a WARNING); other keys and invalid values raise ``ValueError``.

    Returns a dict with keys ``method`` (lower case), ``rtol`` (float),
    ``atol`` (None when not given, else an ndarray, 0-d for a scalar),
    ``on_failure``, ``corrections`` (bool), ``hden_tol`` (float),
    ``jacobian``, ``forcing_interpolation``, ``positivity``, ``fast_groups``
    and ``qs_rate`` (float).
    """
    if not isinstance(method, str) or method.lower() not in METHOD_NAMES:
        raise ValueError(
            f"Unknown integration method {method!r}: use "
            f"{', '.join(repr(m) for m in ('RK4', 'AB') + tuple(METHOD_NAMES))}"
        )
    _cont_opts = dict(solver_options or {})
    _known_opts = (
        "rtol",
        "atol",
        "corrections",
        "on_failure",
        "hden_tol",
        "jacobian",
        "forcing_interpolation",
        "positivity",
        "fast_groups",
        "qs_rate",
    )
    _unknown_opts = sorted(set(_cont_opts) - set(_known_opts))
    if _unknown_opts:
        raise ValueError(
            f"Unknown solver_options {_unknown_opts}: use "
            f"{', '.join(repr(k) for k in _known_opts)}"
        )
    _interp = _cont_opts.get("forcing_interpolation", "constant")
    if not isinstance(_interp, str) or _interp not in FORCING_INTERPOLATIONS:
        raise ValueError(
            "solver_options forcing_interpolation must be 'constant', 'linear' "
            f"or 'smooth', got {_interp!r}"
        )
    _positivity = _cont_opts.get("positivity", "clip")
    if not isinstance(_positivity, str) or _positivity not in POSITIVITY_MODES:
        raise ValueError(
            f"solver_options positivity must be 'clip' or 'log', got {_positivity!r}"
        )
    _fast_groups = _cont_opts.get("fast_groups", "states")
    if not isinstance(_fast_groups, str) or _fast_groups not in FAST_GROUP_MODES:
        raise ValueError(
            "solver_options fast_groups must be 'states' or 'quasi-steady', "
            f"got {_fast_groups!r}"
        )
    _qs_rate = _cont_opts.get("qs_rate", QS_RATE_DEFAULT)
    if not (
        isinstance(_qs_rate, numbers.Real)
        and not isinstance(_qs_rate, (bool, np.bool_))
        and np.isfinite(float(_qs_rate))
        and float(_qs_rate) > 0.0
    ):
        raise ValueError(
            f"solver_options qs_rate must be a number > 0 (per year), got {_qs_rate!r}"
        )
    if "qs_rate" in _cont_opts and _fast_groups == "states":
        logger.warning(
            "solver_options qs_rate=%r is unused: it selects quasi-steady "
            "groups, and fast_groups is 'states'",
            _qs_rate,
        )
    _jacobian = _cont_opts.get("jacobian", "reuse")
    if not isinstance(_jacobian, str) or _jacobian not in JACOBIAN_MODES:
        raise ValueError(
            f"solver_options jacobian must be 'reuse' or 'solver', got {_jacobian!r}"
        )
    _on_failure = _cont_opts.get("on_failure", "raise")
    if _on_failure not in ("raise", "warn"):
        raise ValueError(
            f"solver_options on_failure must be 'raise' or 'warn', got {_on_failure!r}"
        )
    _corrections = _cont_opts.get("corrections", True)
    if not isinstance(_corrections, (bool, np.bool_)):
        raise ValueError(
            f"solver_options corrections must be True or False, got {_corrections!r}"
        )
    _rtol_opt = _cont_opts.get("rtol", 1e-6)
    try:
        _rtol_ok = np.ndim(_rtol_opt) == 0 and float(_rtol_opt) > 0
    except (TypeError, ValueError):
        _rtol_ok = False
    if not _rtol_ok:  # NaN fails too
        raise ValueError(f"solver_options rtol must be > 0, got {_rtol_opt!r}")
    _atol_opt = _cont_opts.get("atol")
    _atol_arr: Optional[np.ndarray] = None
    if _atol_opt is not None:
        try:
            _atol_arr = np.asarray(_atol_opt, dtype=float)
        except (TypeError, ValueError):
            _atol_arr = np.array([np.nan])  # fails the check below
        if not (_atol_arr.ndim == 0 or _atol_arr.shape == (n_bio,)) or not np.all(
            _atol_arr > 0
        ):
            raise ValueError(
                "solver_options atol must be a scalar > 0 or "
                f"{n_bio} values > 0 (groups 1..NUM_LIVING + "
                f"NUM_DEAD), got {_atol_opt!r}"
            )
    # LSODA's finite-difference Jacobian perturbs states by about 1.5e-8
    # relative: a looser Hden would show in its columns
    _hden_tol = _cont_opts.get("hden_tol", 1e-12)
    if not (
        isinstance(_hden_tol, numbers.Real)
        and not isinstance(_hden_tol, (bool, np.bool_))
        and 0.0 < float(_hden_tol) <= 1e-8
    ):
        raise ValueError(
            f"solver_options hden_tol must be in (0, 1e-8], got {_hden_tol!r}"
        )
    return {
        "method": method.lower(),
        "rtol": float(_rtol_opt),
        "atol": _atol_arr,
        "on_failure": _on_failure,
        "corrections": bool(_corrections),
        "hden_tol": float(_hden_tol),
        "jacobian": _jacobian,
        "forcing_interpolation": _interp,
        "positivity": _positivity,
        "fast_groups": _fast_groups,
        "qs_rate": float(_qs_rate),
    }

default_atol

default_atol(b0_bio: ndarray, rtol: float = 1e-06) -> np.ndarray

Absolute tolerance per state, scaled to the base biomass and, so that a tighter rtol is not capped by atol, to rtol / 1e-6.

Source code in pypath/core/ecosim_continuous/options.py
203
204
205
206
207
def default_atol(b0_bio: np.ndarray, rtol: float = 1e-6) -> np.ndarray:
    """Absolute tolerance per state, scaled to the base biomass and, so that
    a tighter ``rtol`` is not capped by ``atol``, to ``rtol / 1e-6``."""
    b0_bio = np.asarray(b0_bio, dtype=float)
    return 1e-8 * (rtol / 1e-6) * np.maximum(b0_bio, 1e-6 * b0_bio.max())

quasi_steady_groups

quasi_steady_groups(base_rate: ndarray, no_integrate, qs_rate: float, *, forced: Optional[ndarray] = None, stanza=()) -> tuple[list[int], dict[str, list[int]]]

The run's quasi-steady groups (fast_groups="quasi-steady").

base_rate[i - 1] is group i's base loss rate, LossPropToB / B at the unforced base (:meth:ContinuousRHS.base_loss_rate), for groups 1..n; no_integrate holds the scenario's NoIntegrate flags, slot 0 first (RsimParams.NoIntegrate). A group qualifies when it is flagged and its base loss rate exceeds qs_rate (EwE's flag, 24 /yr, also flags groups that are not fast: LT2022's Zooplankton turns over at 25 /yr). A qualifying group that is forced in any month of the run (forced[i - 1]) or is a stanza group (in stanza) stays a state for the whole run.

Returns (selected, excluded): the selected group numbers, ascending, and {"forced": [...], "stanza": [...]}, the qualifying groups kept as states (a forced stanza group is listed as forced).

Source code in pypath/core/ecosim_continuous/quasi_steady.py
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
def quasi_steady_groups(
    base_rate: np.ndarray,
    no_integrate,
    qs_rate: float,
    *,
    forced: Optional[np.ndarray] = None,
    stanza=(),
) -> tuple[list[int], dict[str, list[int]]]:
    """The run's quasi-steady groups (``fast_groups="quasi-steady"``).

    ``base_rate[i - 1]`` is group ``i``'s base loss rate, ``LossPropToB /
    B`` at the unforced base (:meth:`ContinuousRHS.base_loss_rate`), for
    groups ``1..n``; ``no_integrate`` holds the scenario's ``NoIntegrate``
    flags, slot 0 first (``RsimParams.NoIntegrate``). A group qualifies when
    it is flagged and its base loss rate exceeds ``qs_rate`` (EwE's flag,
    24 /yr, also flags groups that are not fast: LT2022's Zooplankton turns
    over at 25 /yr). A qualifying group that is forced in any month of the
    run (``forced[i - 1]``) or is a stanza group (in ``stanza``) stays a
    state for the whole run.

    Returns ``(selected, excluded)``: the selected group numbers, ascending,
    and ``{"forced": [...], "stanza": [...]}``, the qualifying groups kept
    as states (a forced stanza group is listed as forced).
    """
    rate = np.asarray(base_rate, dtype=float)
    n = len(rate)
    flagged = np.asarray(no_integrate)[1 : n + 1] != 0
    is_forced = (
        np.zeros(n, dtype=bool) if forced is None else np.asarray(forced, dtype=bool)
    )
    stanza_set = {int(i) for i in stanza}
    selected: list[int] = []
    excluded: dict[str, list[int]] = {"forced": [], "stanza": []}
    for i in range(1, n + 1):
        if not (flagged[i - 1] and rate[i - 1] > qs_rate):
            continue
        if is_forced[i - 1]:
            excluded["forced"].append(i)
        elif i in stanza_set:
            excluded["stanza"].append(i)
        else:
            selected.append(i)
    return selected, excluded

integrate_month

integrate_month(rhs, y0: ndarray, dt: float, method: str, rtol: float, atol, *, on_failure: str = 'raise', label: Optional[str] = None, n_bio: Optional[int] = None, first_step: Optional[float] = None, jac: Optional[Callable] = None, forcing_interpolation: str = 'constant', positivity: str = 'clip', jac_factory: Optional[Callable] = None, quasi_steady: Optional[QuasiSteady] = None, step_floor: Optional[ndarray] = None) -> MonthResult

Solve one month with solve_ivp and average rates by quadrature.

The means are 6-point Gauss-Legendre quadrature of the dense output over the month (over the interval actually reached after a failure). With on_failure="warn" a failed solve logs a warning and returns the last state reached; otherwise it raises RuntimeError. Even with "warn", a non-finite derivative or non-finite rates at the start state raise, and so does any exception from rhs itself (such as a handling-time solve that fails inside the right-hand side). label (rsim_run passes "month m (year y)") prefixes the logged warnings; rsim_run adds the month to raised errors itself. n_bio (default len(y0)) is the number of leading biomass states: the rates, loss rates and y_mean use those, the rest are other states (feeding times). The quadrature nodes' biomass states are clipped at 0 before rhs.rates and the loss-rate division; when the rates fall back on the start state (with "warn"), y_mean does too. first_step (default: the solver's own choice) is passed to solve_ivp, and so is jac (a Jacobian callable, such as :meth:JacobianReuse.for_month's) unless it is None or the method is DOP853, which uses none.

forcing_interpolation (one of FORCING_INTERPOLATIONS, else ValueError) is the run's: with "linear" the tent's kink at mid-month splits the quadrature into 6-point Gauss-Legendre on each half (12 nodes; :func:_split_nodes), and with "linear" or "smooth" the rates are evaluated as rhs.rates(y, t) at the node times, so they see the forcing applied there. With "constant" the 6-point rule and rhs.rates(y) stay as they were (rsim_run passes "constant" when no forcing varies in time, so no kink).

positivity="log" (a numerical option: the same equations in other variables, so the same solution to the tolerance; "clip" is the default and is the code above unchanged) integrates z = ln max(B, 1e-20) for the n_bio biomass states and leaves the feeding times linear. The solver's function is B = exp(max(z, ln 1e-20)), dz = dB / B from rhs(t, [B, Ft]), with dz = max(dz, 0) where z <= ln 1e-20 (the floor absorbs: a group there can only grow). A forced group has dB = 0 and so a constant z. The log state's atol is min(max(atol_i / y0_i, rtol), 0.1) (the linear tolerance at the month-start biomass; atol is broadcast to y0's length first). sol.y and the dense output are transformed back to biomass before the means, y_end, the stats and the budget, so the quadrature means are of B and everything downstream sees biomass. rhs always sees B >= 1e-20, so rhs.stats["clips"] stays 0 and min_state is the smallest B evaluated. A Jacobian is differentiated in z: a linear-space jac with positivity="log" raises ValueError; jac_factory(fun, step_floor) (JacobianReuse.for_month) is called with the wrapped function and the difference step's floor in the solver's states instead: min(atol_z / rtol, 1) for a log state (1 unless rtol > 0.1, so h = 1.49e-8 x max(|z|, 1), a relative step in B), and step_floor's value for a feeding time.

quasi_steady (a :class:QuasiSteady over rhs, its month set by its set_month; a model option) reduces the solver's state: the solver integrates quasi_steady's slow states (from y0's, with atol broadcast to y0 and taken at them; "log" transforms the slow biomass states), and the state reached and every quadrature node are expanded to every state, the selected groups at their solved biomass (:meth:QuasiSteady.expand at the node's time), before the means, the rates, the exchange and y_end, so MonthResult keeps its layout. A Jacobian is differentiated in the slow states: a jac with quasi_steady raises ValueError, and jac_factory is called with the solver's function and the slow states' step_floor (as under "log"). A quasi-steady solve that fails raises, as any error from rhs does.

step_floor (a scalar or one value > 0 per state of y0, in biomass and feeding-time units; default atol / rtol) is the floor of jac_factory's difference step for the linear states (rsim_run passes its capped floor, see :class:JacobianReuse).

rhs.stats, when the right-hand side keeps one (ContinuousRHS, reset by its set_month), counts the solver's evaluations, the start check and jac's columns included; the quadrature's rhs.rates calls do not count.

Source code in pypath/core/ecosim_continuous/month.py
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
def integrate_month(
    rhs,
    y0: np.ndarray,
    dt: float,
    method: str,
    rtol: float,
    atol,
    *,
    on_failure: str = "raise",
    label: Optional[str] = None,
    n_bio: Optional[int] = None,
    first_step: Optional[float] = None,
    jac: Optional[Callable] = None,
    forcing_interpolation: str = "constant",
    positivity: str = "clip",
    jac_factory: Optional[Callable] = None,
    quasi_steady: Optional[QuasiSteady] = None,
    step_floor: Optional[np.ndarray] = None,
) -> MonthResult:
    """Solve one month with ``solve_ivp`` and average rates by quadrature.

    The means are 6-point Gauss-Legendre quadrature of the dense output over
    the month (over the interval actually reached after a failure). With
    ``on_failure="warn"`` a failed solve logs a warning and returns the last
    state reached; otherwise it raises ``RuntimeError``. Even with "warn", a
    non-finite derivative or non-finite rates at the start state raise, and
    so does any exception from ``rhs`` itself (such as a handling-time solve
    that fails inside the right-hand side). ``label`` (``rsim_run`` passes
    ``"month m (year y)"``) prefixes the logged warnings; ``rsim_run`` adds
    the month to raised errors itself. ``n_bio`` (default ``len(y0)``) is the
    number of leading biomass states: the rates, loss rates and ``y_mean``
    use those, the rest are other states (feeding times). The quadrature
    nodes' biomass states are clipped at 0 before ``rhs.rates`` and the
    loss-rate division; when the rates fall back on the start state (with
    "warn"), ``y_mean`` does too. ``first_step`` (default: the solver's own
    choice) is passed to ``solve_ivp``, and so is ``jac`` (a Jacobian callable,
    such as :meth:`JacobianReuse.for_month`'s) unless it is None or the method
    is DOP853, which uses none.

    ``forcing_interpolation`` (one of ``FORCING_INTERPOLATIONS``, else
    ``ValueError``) is the run's: with ``"linear"`` the tent's kink at
    mid-month splits the quadrature into 6-point Gauss-Legendre on each
    half (12 nodes; :func:`_split_nodes`), and with ``"linear"`` or
    ``"smooth"`` the rates are evaluated as ``rhs.rates(y, t)`` at the node
    times, so they see the forcing applied there. With ``"constant"`` the
    6-point rule and ``rhs.rates(y)`` stay as they were (``rsim_run``
    passes ``"constant"`` when no forcing varies in time, so no kink).

    ``positivity="log"`` (a numerical option: the same equations in other
    variables, so the same solution to the tolerance; ``"clip"`` is the
    default and is the code above unchanged) integrates ``z = ln max(B,
    1e-20)`` for the ``n_bio`` biomass states and leaves the feeding times
    linear. The solver's function is ``B = exp(max(z, ln 1e-20))``, ``dz =
    dB / B`` from ``rhs(t, [B, Ft])``, with ``dz = max(dz, 0)`` where ``z <= ln 1e-20``
    (the floor absorbs: a group there can only grow). A forced group has
    ``dB = 0`` and so a constant ``z``. The log state's ``atol`` is
    ``min(max(atol_i / y0_i, rtol), 0.1)`` (the linear tolerance at the month-start
    biomass; ``atol`` is broadcast to ``y0``'s length first). ``sol.y`` and
    the dense output are transformed back to biomass before the means,
    ``y_end``, the stats and the budget, so the quadrature means are of B and
    everything downstream sees biomass. ``rhs`` always sees ``B >= 1e-20``,
    so ``rhs.stats["clips"]`` stays 0 and ``min_state`` is the smallest B
    evaluated. A Jacobian is differentiated in z: a linear-space ``jac`` with
    ``positivity="log"`` raises ``ValueError``; ``jac_factory(fun,
    step_floor)`` (``JacobianReuse.for_month``) is called with the wrapped
    function and the difference step's floor in the solver's states instead:
    ``min(atol_z / rtol, 1)`` for a log state (1 unless ``rtol > 0.1``, so
    ``h = 1.49e-8 x max(|z|, 1)``, a relative step in B), and
    ``step_floor``'s value for a feeding time.

    ``quasi_steady`` (a :class:`QuasiSteady` over ``rhs``, its month set by
    its ``set_month``; a model option) reduces the solver's state: the
    solver integrates ``quasi_steady``'s slow states (from ``y0``'s, with
    ``atol`` broadcast to ``y0`` and taken at them; ``"log"`` transforms the
    slow biomass states), and the state reached and every quadrature node
    are expanded to every state, the selected groups at their solved
    biomass (:meth:`QuasiSteady.expand` at the node's time), before the
    means, the rates, the exchange and ``y_end``, so ``MonthResult`` keeps
    its layout. A Jacobian is differentiated in the slow states: a ``jac``
    with ``quasi_steady`` raises ``ValueError``, and ``jac_factory`` is
    called with the solver's function and the slow states' ``step_floor``
    (as under ``"log"``). A quasi-steady solve that fails raises, as any
    error from ``rhs`` does.

    ``step_floor`` (a scalar or one value > 0 per state of ``y0``, in
    biomass and feeding-time units; default ``atol / rtol``) is the floor of
    ``jac_factory``'s difference step for the linear states (``rsim_run``
    passes its capped floor, see :class:`JacobianReuse`).

    ``rhs.stats``, when the right-hand side keeps one (``ContinuousRHS``,
    reset by its ``set_month``), counts the solver's evaluations, the start
    check and ``jac``'s columns included; the quadrature's ``rhs.rates``
    calls do not count.
    """
    if forcing_interpolation not in FORCING_INTERPOLATIONS:
        raise ValueError(
            "forcing_interpolation must be 'constant', 'linear' or 'smooth', "
            f"got {forcing_interpolation!r}"
        )
    if positivity not in POSITIVITY_MODES:
        raise ValueError(f"positivity must be 'clip' or 'log', got {positivity!r}")
    log_states = positivity == "log"
    if log_states and jac is not None:
        raise ValueError(
            "positivity='log' differentiates in z: pass jac_factory, not jac"
        )
    qs = quasi_steady
    if qs is not None:
        if qs.rhs is not rhs:
            raise ValueError("quasi_steady must reduce rhs itself")
        if jac is not None:
            raise ValueError(
                "quasi_steady differentiates in the slow states: pass "
                "jac_factory, not jac"
            )
    timed = forcing_interpolation != "constant"  # rates at the node times
    y0 = np.asarray(y0, dtype=float)
    n = len(y0) if n_bio is None else int(n_bio)
    # the solver's states: y0's, or (quasi-steady) its slow states, of which
    # the leading n_s are biomass
    solver_rhs, y0_s, n_s, atol_s = rhs, y0, n, atol
    if qs is not None:
        solver_rhs, y0_s, n_s = qs, y0[qs.slow], n - len(qs.fast)
        atol_s = np.broadcast_to(np.asarray(atol, dtype=float), y0.shape)[qs.slow]

    def expand(t, y):
        """A solver state, as [biomass, feeding times], as every state."""
        return y if qs is None else qs.expand(float(t), y)

    fun, z0, atol_run = solver_rhs, y0_s, atol_s
    to_y = np.asarray  # solver state -> [biomass, feeding times]
    # the floor of jac_factory's difference step, per solver state
    floor_run = np.array(
        np.broadcast_to(
            np.asarray(atol, dtype=float) / rtol
            if step_floor is None
            else np.asarray(step_floor, dtype=float),
            y0.shape,
        ),
        dtype=float,
    )
    if qs is not None:
        floor_run = floor_run[qs.slow]
    if log_states:
        z0 = y0_s.copy()
        z0[:n_s] = np.log(np.maximum(y0_s[:n_s], _Y_FLOOR))
        atol_z = np.array(np.broadcast_to(atol_s, y0_s.shape), dtype=float)
        atol_z[:n_s] = np.minimum(
            np.maximum(atol_z[:n_s] / np.maximum(y0_s[:n_s], _Y_FLOOR), rtol),
            _ATOL_Z_MAX,
        )
        atol_run = atol_z
        # z is a relative measure of B: a step of 1.49e-8 x max(|z|, 1), not
        # of atol_z / rtol, up to 0.1 / rtol at the cap
        floor_run[:n_s] = np.minimum(atol_z[:n_s] / rtol, 1.0)

        def to_y(z):
            """The solver's z (any leading axes) as biomass (floored at
            1e-20) and linear feeding times."""
            out = np.array(z, dtype=float, copy=True)
            # exp(ln 1e-20) can round just below 1e-20
            out[..., :n_s] = np.maximum(
                np.exp(np.maximum(out[..., :n_s], _LOG_FLOOR)), _Y_FLOOR
            )
            return out

        def fun(t, z):
            z = np.asarray(z, dtype=float)
            y = to_y(z)
            dy = np.asarray(solver_rhs(t, y), dtype=float)
            dz = dy.copy()
            dz[:n_s] = dy[:n_s] / y[:n_s]
            floored = z[:n_s] <= _LOG_FLOOR
            dz[:n_s][floored] = np.maximum(dz[:n_s][floored], 0.0)
            return dz

    if (
        (log_states or qs is not None)
        and jac_factory is not None
        and method != "dop853"
    ):
        jac = jac_factory(fun, floor_run)
    if not np.all(np.isfinite(np.asarray(fun(0.0, z0), dtype=float))):
        raise RuntimeError(
            "month integration cannot start: non-finite start derivative"
        )
    extra = {} if jac is None or method == "dop853" else {"jac": jac}
    sol = solve_ivp(
        fun,
        (0.0, dt),
        z0,
        method=METHOD_NAMES[method],
        rtol=rtol,
        atol=atol_run,
        dense_output=True,
        max_step=dt,
        first_step=first_step,
        **extra,
    )
    warn = on_failure == "warn"
    prefix = f"{label}: " if label else ""
    degraded = False

    def _fail(reason: str, tail: str) -> None:
        if not warn:
            raise RuntimeError(f"month integration failed: {reason}")
        logger.warning("%smonth integration failed (%s); %s", prefix, reason, tail)

    failed = sol.status < 0
    if failed:
        _fail(str(sol.message), "continuing from the last state reached")
    cols = np.all(np.isfinite(sol.y), axis=0)
    if not cols[-1]:
        if not failed:
            failed = True
            _fail("non-finite final state", "continuing from the last finite state")
        good = np.flatnonzero(cols)
        last = int(good[-1]) if len(good) else 0
    else:
        last = len(sol.t) - 1
    t_reach = float(sol.t[last]) if failed else float(dt)
    y_last = expand(sol.t[last], to_y(np.array(sol.y[:, last], dtype=float)))

    dense = sol.sol
    weights = np.array([1.0])
    ys = y0[None, :]
    times = np.zeros(1)  # the start state's
    if dense is not None and t_reach > 0.0:
        if forcing_interpolation == "linear":
            nodes, w_nodes = _split_nodes(t_reach, dt)
        else:
            nodes, w_nodes = 0.5 * t_reach * (_GL_X + 1.0), 0.5 * _GL_W
        cand = to_y(np.array([np.asarray(dense(t), dtype=float) for t in nodes]))
        if np.all(np.isfinite(cand)):
            if qs is not None:
                cand = np.array([expand(t, y) for t, y in zip(nodes, cand)])
            weights, ys, times = w_nodes, cand, nodes
        else:
            _fail("non-finite dense output", "using the start state for the means")
            degraded = True
    else:
        logger.warning("%smonth means use the start state (no dense output)", prefix)
        degraded = True

    exchange = getattr(rhs, "exchange", None)

    def _clipped(y_nodes):
        """The nodes with their biomass states clipped at 0."""
        out = np.array(y_nodes, dtype=float, copy=True)
        out[:, :n] = np.maximum(out[:, :n], 0.0)
        return out

    def _mean_rates(w_nodes, y_nodes, t_nodes):
        food = loss = pool = None
        exch = 0.0 if exchange is not None else float("nan")
        for w, y, t in zip(w_nodes, y_nodes, t_nodes):
            r = rhs.rates(y, float(t)) if timed else rhs.rates(y)
            fg = np.asarray(r["FoodGain"], dtype=float)
            lp = np.asarray(r["LossPropToB"], dtype=float)
            if not (
                np.all(np.isfinite(fg[1 : n + 1]))
                and np.all(np.isfinite(lp[1 : n + 1]))
            ):
                return None
            b = np.zeros(len(lp))
            b[1 : n + 1] = y[:n]
            lr = np.divide(lp, b, out=np.zeros_like(lp), where=b != 0.0)
            food = w * fg if food is None else food + w * fg
            loss = w * lr if loss is None else loss + w * lr
            if exchange is not None:
                exch += w * float(exchange(r, y))
            if "DetGain" in r:
                net = np.asarray(r["DetGain"], dtype=float) - np.asarray(
                    r["DetLoss"], dtype=float
                )
                pool = w * net if pool is None else pool + w * net
        return food, loss, exch, pool

    ys = _clipped(ys)
    y_mean = weights @ ys[:, :n]
    means = _mean_rates(weights, ys, times)
    if means is None:
        _fail("non-finite rates at a quadrature node", "using the start state's rates")
        degraded = True
        weights, ys = np.array([1.0]), _clipped(y0[None, :])
        y_mean = weights @ ys[:, :n]
        means = _mean_rates(weights, ys, np.zeros(1))
        if means is None:
            raise RuntimeError("month integration failed: non-finite start rates")
    food, loss, exch_mean, pool_mean = means

    y_end = np.maximum(y_last, _Y_FLOOR)
    steps = np.diff(sol.t)
    last_step = (
        float(steps[-2]) if len(steps) >= 2 else float(steps[0]) if len(steps) else None
    )
    return MonthResult(
        y_end=y_end,
        y_mean=y_mean,
        food_gain_mean=food,
        loss_rate_mean=loss,
        nfev=int(sol.nfev),
        njev=int(getattr(sol, "njev", 0) or 0),
        nlu=int(getattr(sol, "nlu", 0) or 0),
        steps=len(sol.t) - 1,
        status=int(sol.status),
        message=str(sol.message),
        t_reached=t_reach,
        degraded=degraded,
        exchange_mean=exch_mean,
        pool_net_mean=pool_mean,
        last_step=last_step,
    )

month_budget

month_budget(y0: ndarray, res: MonthResult, n_living: int, n_bio: int, forced: bool, *, quasi_steady: bool = False) -> tuple[Optional[float], Optional[float]]

(budget_residual, pool_budget_residual) of an integrated month.

Over the biomass states y0[:n_bio] and res.y_end[:n_bio] (any states beyond them are feeding times), with t = res.t_reached: budget_residual = (sum(y_end) - sum(y0) - t * exchange_mean) / sum(y0) and pool_budget_residual the largest over the detritus pools of |y_end_d - y0_d - t * pool_net_mean_d| / y0_d. Both are None when forced (forced biomass: its flows are imposed), under quasi_steady groups (the reduction sets their dB_f/dt to 0 while B_f moves, so the budget does not close to the solver's tolerance) or when the month is degraded (its means are the start state's); the pool residual is None without pool_net_mean or pools, and skips pools starting at or below the 1e-20 floor (None if every pool is skipped).

Source code in pypath/core/ecosim_continuous/month.py
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
def month_budget(
    y0: np.ndarray,
    res: MonthResult,
    n_living: int,
    n_bio: int,
    forced: bool,
    *,
    quasi_steady: bool = False,
) -> tuple[Optional[float], Optional[float]]:
    """``(budget_residual, pool_budget_residual)`` of an integrated month.

    Over the biomass states ``y0[:n_bio]`` and ``res.y_end[:n_bio]`` (any
    states beyond them are feeding times), with ``t = res.t_reached``:
    ``budget_residual = (sum(y_end) - sum(y0) - t * exchange_mean) /
    sum(y0)`` and ``pool_budget_residual`` the largest over the detritus
    pools of ``|y_end_d - y0_d - t * pool_net_mean_d| / y0_d``. Both are None
    when ``forced`` (forced biomass: its flows are imposed), under
    ``quasi_steady`` groups (the reduction sets their ``dB_f/dt`` to 0 while
    ``B_f`` moves, so the budget does not close to the solver's tolerance)
    or when the month is ``degraded`` (its means are the start state's);
    the pool residual is None without ``pool_net_mean`` or pools, and skips
    pools starting at or below the 1e-20 floor (None if every pool is
    skipped).
    """
    if forced or quasi_steady or res.degraded:
        return None, None
    b0 = np.asarray(y0, dtype=float)[:n_bio]
    b1 = np.asarray(res.y_end, dtype=float)[:n_bio]
    t = res.t_reached
    total = float((b1.sum() - b0.sum() - t * res.exchange_mean) / b0.sum())
    pool = None
    if res.pool_net_mean is not None and n_bio > n_living:
        d = slice(n_living, n_bio)
        net = np.asarray(res.pool_net_mean, dtype=float)[n_living + 1 : n_bio + 1]
        b0d = b0[d]
        keep = b0d > _Y_FLOOR  # a pool at the floor has no relative residual
        if np.any(keep):
            pool = float(np.max(np.abs(b1[d] - b0d - t * net)[keep] / b0d[keep]))
    return total, pool

Advanced Ecosim (State Forcing & Diet Rewiring)

rsim_run_advanced runs rsim_run. State forcing and diet rewiring are not implemented in this version and raise NotImplementedError. Prey switching (EwE SwitchPower) is available instead of diet rewiring: set scenario.params.SwitchPower, or use the Prey Switching control on the app's Ecosim page.

pypath.core.ecosim_advanced

Advanced Ecosim entry point: state forcing and diet rewiring (not implemented).

rsim_run_advanced runs rsim_run. State forcing (StateForcing) and diet rewiring (DietRewiring) are not implemented in this version and raise NotImplementedError. Earlier versions ran a placeholder loop that never integrated, so they returned the start biomass in every month. Prey switching, EwE's per-predator SwitchPower, is available instead of diet rewiring: set scenario.params.SwitchPower, which rsim_run applies, or use the Prey Switching control on the app's Ecosim page.

apply_state_forcing and apply_diet_rewiring are standalone helpers that no simulation calls.

apply_state_forcing

apply_state_forcing(state: ndarray, year: float, state_forcing: Optional[StateForcing], variable: StateVariable = StateVariable.BIOMASS) -> np.ndarray

Apply state forcing to current state vector.

Parameters:

Name Type Description Default
state ndarray

Current state vector (biomass, catch, etc.)

required
year float

Current simulation year (fractional for monthly steps)

required
state_forcing StateForcing or None

Forcing configuration

required
variable StateVariable

Which variable is being forced

BIOMASS

Returns:

Type Description
ndarray

Modified state vector

Source code in pypath/core/ecosim_advanced.py
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
def apply_state_forcing(
    state: np.ndarray,
    year: float,
    state_forcing: Optional[StateForcing],
    variable: StateVariable = StateVariable.BIOMASS,
) -> np.ndarray:
    """Apply state forcing to current state vector.

    Parameters
    ----------
    state : np.ndarray
        Current state vector (biomass, catch, etc.)
    year : float
        Current simulation year (fractional for monthly steps)
    state_forcing : StateForcing or None
        Forcing configuration
    variable : StateVariable
        Which variable is being forced

    Returns
    -------
    np.ndarray
        Modified state vector
    """
    if state_forcing is None:
        return state

    state_modified = state.copy()

    # Get all active forcing for this variable
    forcing_list = state_forcing.get_forcing(year, variable)

    for func, forced_value in forcing_list:
        group_idx = func.group_idx

        if group_idx == -1:
            # Apply to all groups
            indices: range | list[int] = range(len(state))
        else:
            # Apply to specific group
            indices = [group_idx]

        for idx in indices:
            if func.mode == ForcingMode.REPLACE:
                # Replace computed value with forced value
                state_modified[idx] = forced_value

            elif func.mode == ForcingMode.ADD:
                # Add forced value to computed value
                state_modified[idx] += forced_value

            elif func.mode == ForcingMode.MULTIPLY:
                # Multiply computed value by forced value
                state_modified[idx] *= forced_value

            elif func.mode == ForcingMode.RESCALE:
                # Rescale to match forced value
                # (maintains relative proportions)
                if state[idx] > 0:
                    _scale = forced_value / state[idx]
                    state_modified[idx] = forced_value
                else:
                    state_modified[idx] = forced_value

    return state_modified

apply_diet_rewiring

apply_diet_rewiring(biomass: ndarray, diet_rewiring: Optional[DietRewiring], month: int) -> Optional[np.ndarray]

Update diet matrix based on current biomass.

Parameters:

Name Type Description Default
biomass ndarray

Current biomass values

required
diet_rewiring DietRewiring or None

Diet rewiring configuration

required
month int

Current month (for update interval check)

required

Returns:

Type Description
ndarray or None

Updated diet matrix, or None if no update

Source code in pypath/core/ecosim_advanced.py
 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 apply_diet_rewiring(
    biomass: np.ndarray, diet_rewiring: Optional[DietRewiring], month: int
) -> Optional[np.ndarray]:
    """Update diet matrix based on current biomass.

    Parameters
    ----------
    biomass : np.ndarray
        Current biomass values
    diet_rewiring : DietRewiring or None
        Diet rewiring configuration
    month : int
        Current month (for update interval check)

    Returns
    -------
    np.ndarray or None
        Updated diet matrix, or None if no update
    """
    if diet_rewiring is None or not diet_rewiring.enabled:
        return None

    # Check if it's time to update
    if month % diet_rewiring.update_interval != 0:
        return None

    # Update diet based on current biomass
    new_diet = diet_rewiring.update_diet(biomass)

    return new_diet

rsim_run_advanced

rsim_run_advanced(scenario: RsimScenario, state_forcing: Optional[StateForcing] = None, diet_rewiring: Optional[DietRewiring] = None, method: str = 'RK4', years: Optional[range] = None, verbose: bool = False, *, on_month: Optional[Callable[[int, int], Optional[bool]]] = None) -> RsimOutput

Run Ecosim with rsim_run. Diet rewiring and state forcing are refused.

Without diet rewiring or state forcing, this is rsim_run(scenario, method=method, years=years, on_month=on_month). Its output is returned unchanged. An unknown method, or a years range that does not start at scenario.start_year, raises rsim_run's ValueError.

Diet rewiring and state forcing are not implemented in this version. Either one raises NotImplementedError. Earlier versions ran a placeholder loop that never integrated: every method, even an unknown one, returned the start biomass of every unforced group in every month, and zero catch. The rewired diet was computed but never applied.

Parameters:

Name Type Description Default
scenario RsimScenario

Standard Ecosim scenario

required
state_forcing StateForcing

Must be None or empty (no forcing functions). Any forcing function raises NotImplementedError. rsim_run takes forced biomass from scenario.forcing.ForcedBio (values > 0 replace the biomass), a recruitment multiplier from scenario.forcing.ForcedRecs and forced catch from scenario.fishing.ForcedCatch.

None
diet_rewiring DietRewiring

Must be None or disabled (enabled=False). An enabled one raises NotImplementedError. Prey switching is available instead: set EwE's per-predator SwitchPower (scenario.params.SwitchPower), which rsim_run applies, or use the Prey Switching control on the app's Ecosim page.

None
method str

Integration method, passed to rsim_run: 'RK4', 'AB' or one of its continuous methods. Anything else raises ValueError.

'RK4'
years range

Years to simulate, passed to rsim_run. It must start at scenario.start_year (the first len(years) years are run), else ValueError.

None
verbose bool

Unused, kept for compatibility.

False
on_month callable

Passed to rsim_run: called as on_month(month, n_months) at the end of every simulated month; returning True stops the run with RunCancelled.

None

Returns:

Type Description
RsimOutput

rsim_run's output.

Raises:

Type Description
NotImplementedError

If diet_rewiring is enabled, or state_forcing has a forcing function.

ValueError

From rsim_run: an unknown method or an offset years.

RunCancelled

From rsim_run, when on_month returns True.

Source code in pypath/core/ecosim_advanced.py
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
def rsim_run_advanced(
    scenario: RsimScenario,
    state_forcing: Optional[StateForcing] = None,
    diet_rewiring: Optional[DietRewiring] = None,
    method: str = "RK4",
    years: Optional[range] = None,
    verbose: bool = False,
    *,
    on_month: Optional[Callable[[int, int], Optional[bool]]] = None,
) -> RsimOutput:
    """Run Ecosim with ``rsim_run``. Diet rewiring and state forcing are refused.

    Without diet rewiring or state forcing, this is
    ``rsim_run(scenario, method=method, years=years, on_month=on_month)``.
    Its output is returned unchanged. An unknown ``method``, or a ``years``
    range that does not start at ``scenario.start_year``, raises
    ``rsim_run``'s ``ValueError``.

    Diet rewiring and state forcing are not implemented in this version.
    Either one raises ``NotImplementedError``. Earlier versions ran a
    placeholder loop that never integrated: every ``method``, even an
    unknown one, returned the start biomass of every unforced group in
    every month, and zero catch. The rewired diet was computed but never
    applied.

    Parameters
    ----------
    scenario : RsimScenario
        Standard Ecosim scenario
    state_forcing : StateForcing, optional
        Must be None or empty (no forcing functions). Any forcing function
        raises ``NotImplementedError``. ``rsim_run`` takes forced biomass
        from ``scenario.forcing.ForcedBio`` (values > 0 replace the
        biomass), a recruitment multiplier from ``scenario.forcing.ForcedRecs``
        and forced catch from ``scenario.fishing.ForcedCatch``.
    diet_rewiring : DietRewiring, optional
        Must be None or disabled (``enabled=False``). An enabled one
        raises ``NotImplementedError``. Prey switching is available
        instead: set EwE's per-predator ``SwitchPower``
        (``scenario.params.SwitchPower``), which ``rsim_run`` applies, or
        use the Prey Switching control on the app's Ecosim page.
    method : str
        Integration method, passed to ``rsim_run``: ``'RK4'``, ``'AB'``
        or one of its continuous methods. Anything else raises
        ``ValueError``.
    years : range, optional
        Years to simulate, passed to ``rsim_run``. It must start at
        ``scenario.start_year`` (the first ``len(years)`` years are run),
        else ``ValueError``.
    verbose : bool
        Unused, kept for compatibility.
    on_month : callable, optional
        Passed to ``rsim_run``: called as ``on_month(month, n_months)`` at
        the end of every simulated month; returning True stops the run with
        ``RunCancelled``.

    Returns
    -------
    RsimOutput
        ``rsim_run``'s output.

    Raises
    ------
    NotImplementedError
        If ``diet_rewiring`` is enabled, or ``state_forcing`` has a forcing
        function.
    ValueError
        From ``rsim_run``: an unknown ``method`` or an offset ``years``.
    RunCancelled
        From ``rsim_run``, when ``on_month`` returns True.
    """
    if diet_rewiring is not None and diet_rewiring.enabled:
        raise NotImplementedError(
            "Diet rewiring is not implemented in this version: "
            "rsim_run_advanced never applied the rewired diet (it returned "
            "the start biomass). Prey switching is available instead: set "
            "EwE's per-predator SwitchPower (scenario.params.SwitchPower, "
            "applied by rsim_run), or use the Prey Switching control on the "
            "app's Ecosim page. Pass diet_rewiring=None, or "
            "DietRewiring(enabled=False), to run rsim_run."
        )
    if state_forcing is not None and state_forcing.functions:
        raise NotImplementedError(
            "State forcing is not implemented in rsim_run_advanced in this "
            "version: it never integrated the unforced groups. Force biomass "
            "with scenario.forcing.ForcedBio (values > 0 replace the "
            "biomass), recruitment with scenario.forcing.ForcedRecs or catch "
            "with scenario.fishing.ForcedCatch, and run rsim_run."
        )
    return rsim_run(scenario, method=method, years=years, on_month=on_month)

create_advanced_scenario

create_advanced_scenario(base_scenario: RsimScenario, state_forcing: Optional[StateForcing] = None, diet_rewiring: Optional[DietRewiring] = None) -> tuple[RsimScenario, StateForcing, DietRewiring]

Create advanced scenario with forcing and rewiring.

Parameters:

Name Type Description Default
base_scenario RsimScenario

Base Ecosim scenario

required
state_forcing StateForcing

State forcing configuration

None
diet_rewiring DietRewiring

Diet rewiring configuration

None

Returns:

Name Type Description
scenario RsimScenario

Base scenario (unchanged)

state_forcing StateForcing

State forcing (created if None)

diet_rewiring DietRewiring

Diet rewiring (created if None)

Source code in pypath/core/ecosim_advanced.py
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
def create_advanced_scenario(
    base_scenario: RsimScenario,
    state_forcing: Optional[StateForcing] = None,
    diet_rewiring: Optional[DietRewiring] = None,
) -> tuple[RsimScenario, StateForcing, DietRewiring]:
    """Create advanced scenario with forcing and rewiring.

    Parameters
    ----------
    base_scenario : RsimScenario
        Base Ecosim scenario
    state_forcing : StateForcing, optional
        State forcing configuration
    diet_rewiring : DietRewiring, optional
        Diet rewiring configuration

    Returns
    -------
    scenario : RsimScenario
        Base scenario (unchanged)
    state_forcing : StateForcing
        State forcing (created if None)
    diet_rewiring : DietRewiring
        Diet rewiring (created if None)
    """
    if state_forcing is None:
        state_forcing = StateForcing()

    if diet_rewiring is None:
        diet_rewiring = DietRewiring(enabled=False)

    return base_scenario, state_forcing, diet_rewiring

Stanzas (Multi-Stanza Groups)

pypath.core.stanzas

Multi-stanza (age-structured) groups for PyPath.

This module implements age-structured population dynamics using Von Bertalanffy growth and stage-based mortality rates.

Based on Rpath's rpath.stanzas() and rsim.stanzas() functions, and on the SplitUpdate / SplitSetPred routines of Rpath's ecosim.cpp.

In rsim_run the age structure is coupled to Ecosim as in Rpath: each month :func:split_update ages numbers and weights with the realised mortality and food intake of each stanza's group and adds recruits, and :func:split_set_pred sets the stanza groups' biomass to sum(N * W). The groups eat in proportion to sum(N * Q) relative to its base value.

EcosimStanzaParams dataclass

Container for all multi-stanza parameters.

Attributes: n_stanza_groups: Number of stanza groups stanza_groups: List of StanzaGroup objects stanza_individuals: List of StanzaIndividual objects st_groups: DataFrame with stanza calculations per age plus_group_rule: Age table :func:rpath_stanzas built ("rpath" or "ewe")

Source code in pypath/core/stanzas.py
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
@dataclass
class EcosimStanzaParams:
    """Container for all multi-stanza parameters.

    Attributes:
        n_stanza_groups: Number of stanza groups
        stanza_groups: List of StanzaGroup objects
        stanza_individuals: List of StanzaIndividual objects
        st_groups: DataFrame with stanza calculations per age
        plus_group_rule: Age table :func:`rpath_stanzas` built ("rpath" or
            "ewe")
    """

    n_stanza_groups: int = 0
    stanza_groups: List[StanzaGroup] = field(default_factory=list)
    stanza_individuals: List[StanzaIndividual] = field(default_factory=list)
    st_groups: Dict[int, pd.DataFrame] = field(default_factory=dict)
    plus_group_rule: str = "rpath"

RsimStanzaState dataclass

Live age structure of the multi-stanza groups during a run.

Rpath keeps these in the simulation state (NageS, WageS, QageS, StanzaPred, SpawnBio, EggsStanza) and leaves the base* arrays of :class:RsimStanzas untouched. Keeping them apart means a scenario can be run more than once from the same start.

Source code in pypath/core/stanzas.py
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
@dataclass
class RsimStanzaState:
    """Live age structure of the multi-stanza groups during a run.

    Rpath keeps these in the simulation state (``NageS``, ``WageS``,
    ``QageS``, ``StanzaPred``, ``SpawnBio``, ``EggsStanza``) and leaves the
    ``base*`` arrays of :class:`RsimStanzas` untouched. Keeping them apart
    means a scenario can be run more than once from the same start.
    """

    nage_s: np.ndarray
    wage_s: np.ndarray
    qage_s: np.ndarray
    stanza_pred: np.ndarray
    n: np.ndarray
    spawn_bio: np.ndarray
    eggs_stanza: np.ndarray
    # EwE RecStanzaScalar: recruits of a linked group over its source's, set
    # at the first update of the run (0 = not yet)
    rec_scalar: Optional[np.ndarray] = None

    @classmethod
    def from_base(cls, stanzas: RsimStanzas, n_groups: int) -> "RsimStanzaState":
        """Start state: copies of the base arrays (Rpath ``rsim.scenario``)."""
        stanza_pred = np.zeros(n_groups + 1)
        base_pred = np.asarray(stanzas.base_stanza_pred, dtype=float)
        k = min(len(base_pred), n_groups + 1)
        stanza_pred[:k] = base_pred[:k]
        return cls(
            nage_s=np.array(stanzas.base_nage_s, dtype=float, copy=True),
            wage_s=np.array(stanzas.base_wage_s, dtype=float, copy=True),
            qage_s=np.array(stanzas.base_qage_s, dtype=float, copy=True),
            stanza_pred=stanza_pred,
            n=np.zeros(n_groups + 1),
            spawn_bio=np.array(stanzas.base_spawn_bio, dtype=float, copy=True),
            eggs_stanza=np.array(stanzas.base_eggs_stanza, dtype=float, copy=True),
            rec_scalar=np.zeros(int(stanzas.n_split) + 1),
        )
from_base classmethod
from_base(stanzas: RsimStanzas, n_groups: int) -> 'RsimStanzaState'

Start state: copies of the base arrays (Rpath rsim.scenario).

Source code in pypath/core/stanzas.py
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
@classmethod
def from_base(cls, stanzas: RsimStanzas, n_groups: int) -> "RsimStanzaState":
    """Start state: copies of the base arrays (Rpath ``rsim.scenario``)."""
    stanza_pred = np.zeros(n_groups + 1)
    base_pred = np.asarray(stanzas.base_stanza_pred, dtype=float)
    k = min(len(base_pred), n_groups + 1)
    stanza_pred[:k] = base_pred[:k]
    return cls(
        nage_s=np.array(stanzas.base_nage_s, dtype=float, copy=True),
        wage_s=np.array(stanzas.base_wage_s, dtype=float, copy=True),
        qage_s=np.array(stanzas.base_qage_s, dtype=float, copy=True),
        stanza_pred=stanza_pred,
        n=np.zeros(n_groups + 1),
        spawn_bio=np.array(stanzas.base_spawn_bio, dtype=float, copy=True),
        eggs_stanza=np.array(stanzas.base_eggs_stanza, dtype=float, copy=True),
        rec_scalar=np.zeros(int(stanzas.n_split) + 1),
    )

RsimStanzas dataclass

Stanza parameters for Ecosim simulation.

Contains age-structured dynamics parameters needed by the simulation engine.

Source code in pypath/core/stanzas.py
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
@dataclass
class RsimStanzas:
    """Stanza parameters for Ecosim simulation.

    Contains age-structured dynamics parameters needed by
    the simulation engine.
    """

    n_split: int = 0
    n_stanzas: np.ndarray = field(default_factory=lambda: np.array([0]))
    ecopath_code: np.ndarray = field(default_factory=lambda: np.zeros((2, 2)))
    age1: np.ndarray = field(default_factory=lambda: np.zeros((2, 2)))
    age2: np.ndarray = field(default_factory=lambda: np.zeros((2, 2)))

    # Age-at-size arrays (rows=months, cols=species)
    base_wage_s: np.ndarray = field(default_factory=lambda: np.zeros((2, 2)))
    base_nage_s: np.ndarray = field(default_factory=lambda: np.zeros((2, 2)))
    base_qage_s: np.ndarray = field(default_factory=lambda: np.zeros((2, 2)))

    # Maturity and recruitment
    wmat: np.ndarray = field(default_factory=lambda: np.array([0.0, 0.0]))
    rec_power: np.ndarray = field(default_factory=lambda: np.array([0.0, 0.0]))
    recruits: np.ndarray = field(default_factory=lambda: np.array([0.0, 0.0]))
    vbgf_d: np.ndarray = field(default_factory=lambda: np.array([0.0, 0.0]))
    r_zero_s: np.ndarray = field(default_factory=lambda: np.array([0.0, 0.0]))
    vbm: np.ndarray = field(default_factory=lambda: np.array([0.0, 0.0]))

    # Growth coefficients
    split_alpha: np.ndarray = field(default_factory=lambda: np.zeros((2, 2)))

    # Spawning
    spawn_x: np.ndarray = field(default_factory=lambda: np.array([0.0, 0.0]))
    spawn_energy: np.ndarray = field(default_factory=lambda: np.array([0.0, 0.0]))
    base_eggs_stanza: np.ndarray = field(default_factory=lambda: np.array([0.0, 0.0]))
    base_spawn_bio: np.ndarray = field(default_factory=lambda: np.array([0.0, 0.0]))
    r_scale_split: np.ndarray = field(default_factory=lambda: np.array([0.0, 0.0]))
    base_stanza_pred: np.ndarray = field(default_factory=lambda: np.array([0.0, 0.0]))
    # Plus group: "rpath" merges the two oldest months by numbers; "ewe"
    # re-closes it each month on the Ford-Walford line (ahat, rhat) and keeps
    # the consumption weights of the setup (EwE6 SplitUpdate, SplitSetPred).
    plus_group_rule: str = "rpath"
    ahat: np.ndarray = field(default_factory=lambda: np.array([0.0, 0.0]))
    rhat: np.ndarray = field(default_factory=lambda: np.array([0.0, 0.0]))
    # EwE6 hatch-code shape by month (rows) and stanza group (columns, as
    # the other per-group arrays); NaN where a stanza has none. Under the EwE
    # rule a stanza with one recruits RscaleSplit x egg x RzeroS x hatch,
    # without the stock-recruitment term (split_update).
    hatch_forcing: Optional[np.ndarray] = None
    # Spawning (EwE6 SplitInitialize / SplitUpdate): SpawnProp and base eggs
    # per individual (EggsSplit) by month of age; per stanza group the
    # fixed-fecundity flag and the group whose recruits it follows
    # (RecStanza, rsim index, 0 = none). None = Rpath defaults.
    spawn_prop: Optional[np.ndarray] = None
    eggs_split: Optional[np.ndarray] = None
    fixed_fecundity: Optional[np.ndarray] = None
    rec_stanza: Optional[np.ndarray] = None

StanzaGroup dataclass

Parameters for a single multi-stanza species group.

Attributes: stanza_group_num: Index of this stanza group (1-based) n_stanzas: Number of age stanzas in this group vbgf_ksp: Von Bertalanffy K parameter (annual) vbgf_d: Von Bertalanffy d parameter (default 2/3) wmat: Weight at 50% maturity relative to Winf bab: Biomass accumulation / background mortality rec_power: Recruitment power parameter recruits: Base number of recruits (R) last_month: Final month of the oldest age class ahat, rhat: Ford-Walford intercept and slope of the plus group (EwE age table only; see :func:_ewe_age_table)

Source code in pypath/core/stanzas.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
@dataclass
class StanzaGroup:
    """Parameters for a single multi-stanza species group.

    Attributes:
        stanza_group_num: Index of this stanza group (1-based)
        n_stanzas: Number of age stanzas in this group
        vbgf_ksp: Von Bertalanffy K parameter (annual)
        vbgf_d: Von Bertalanffy d parameter (default 2/3)
        wmat: Weight at 50% maturity relative to Winf
        bab: Biomass accumulation / background mortality
        rec_power: Recruitment power parameter
        recruits: Base number of recruits (R)
        last_month: Final month of the oldest age class
        ahat, rhat: Ford-Walford intercept and slope of the plus group
            (EwE age table only; see :func:`_ewe_age_table`)
    """

    stanza_group_num: int
    n_stanzas: int
    vbgf_ksp: float
    vbgf_d: float = 0.66667
    wmat: float = 0.0
    bab: float = 0.0
    rec_power: float = 1.0
    recruits: float = 0.0
    # EwE Stanza.FixedFecundity: eggs per individual stay at their base value
    fixed_fecundity: bool = False
    # EwE Stanza.RecStanza: 1-based position of the stanza group whose
    # recruits this one follows (0 = its own)
    rec_stanza: int = 0
    last_month: int = 0
    ahat: float = 0.0
    rhat: float = 0.0

StanzaIndividual dataclass

Parameters for an individual stanza (age class) within a group.

Attributes: stanza_group_num: Index of parent stanza group stanza_num: Index of this stanza within group (1-based) group_num: Ecopath group number for this stanza group_name: Name of this stanza group in model first: First month of this age class last: Last month of this age class z: Total mortality rate (annual) leading: True if this is the leading (reference) stanza leading_cb: True if this stanza anchors the group's consumption (EwE's LeadingCB); when no stanza is marked, the leading one does biomass: Calculated biomass qb: Calculated Q/B

Source code in pypath/core/stanzas.py
 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
@dataclass
class StanzaIndividual:
    """Parameters for an individual stanza (age class) within a group.

    Attributes:
        stanza_group_num: Index of parent stanza group
        stanza_num: Index of this stanza within group (1-based)
        group_num: Ecopath group number for this stanza
        group_name: Name of this stanza group in model
        first: First month of this age class
        last: Last month of this age class
        z: Total mortality rate (annual)
        leading: True if this is the leading (reference) stanza
        leading_cb: True if this stanza anchors the group's consumption
            (EwE's LeadingCB); when no stanza is marked, the leading one
            does
        biomass: Calculated biomass
        qb: Calculated Q/B
    """

    stanza_group_num: int
    stanza_num: int
    group_num: int
    group_name: str
    first: int
    last: int
    z: float
    leading: bool = False
    leading_cb: bool = False
    # EwE StanzaLifeStage.SpawnProp: the stage's share of the spawning
    spawn_prop: float = 1.0
    biomass: float = 0.0
    qb: float = 0.0

calculate_survival

calculate_survival(z_by_month: ndarray, bab: float = 0.0) -> np.ndarray

Calculate cumulative survival to each age.

Parameters:

Name Type Description Default
z_by_month ndarray

Monthly mortality rate for each month

required
bab float

Background/accumulation mortality rate (annual)

0.0

Returns:

Type Description
ndarray

Cumulative survival probability to each age

Source code in pypath/core/stanzas.py
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
def calculate_survival(z_by_month: np.ndarray, bab: float = 0.0) -> np.ndarray:
    """Calculate cumulative survival to each age.

    Parameters
    ----------
    z_by_month : np.ndarray
        Monthly mortality rate for each month
    bab : float
        Background/accumulation mortality rate (annual)

    Returns
    -------
    np.ndarray
        Cumulative survival probability to each age
    """
    monthly_z = (z_by_month + bab) / 12.0
    monthly_survival = np.exp(-monthly_z)
    # Shift survival - first month survival is 1.0
    monthly_survival = np.concatenate([[1.0], monthly_survival[:-1]])
    return np.cumprod(monthly_survival)

check_stanza_arrays

check_stanza_arrays(stanzas: RsimStanzas, n_groups: int) -> List[str]

Return the problems that stop the age structure from being simulated.

An empty list means :func:split_update / :func:split_set_pred can run.

Source code in pypath/core/stanzas.py
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
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
def check_stanza_arrays(stanzas: RsimStanzas, n_groups: int) -> List[str]:
    """Return the problems that stop the age structure from being simulated.

    An empty list means :func:`split_update` / :func:`split_set_pred` can run.
    """
    problems: List[str] = []
    n_split = int(stanzas.n_split)
    if n_split <= 0:
        return ["no stanza groups"]
    if len(np.asarray(stanzas.base_stanza_pred)) < n_groups + 1:
        problems.append("base_stanza_pred is shorter than the number of groups")
    vectors = (
        "vbm",
        "vbgf_d",
        "wmat",
        "spawn_x",
        "spawn_energy",
        "base_eggs_stanza",
        "base_spawn_bio",
        "r_scale_split",
        "r_zero_s",
        "rec_power",
    )
    for name in vectors:
        if len(np.asarray(getattr(stanzas, name))) < n_split + 1:
            problems.append(f"{name} has fewer than n_split + 1 entries")
    for isp in range(1, n_split + 1):
        nst = int(stanzas.n_stanzas[isp])
        if nst < 1:
            problems.append(f"stanza group {isp} has no stanzas")
            continue
        last = int(stanzas.age2[isp, nst])
        first = int(stanzas.age1[isp, 1])
        if last - first < 1:
            problems.append(f"stanza group {isp} spans fewer than two months")
            continue
        for name in ("base_nage_s", "base_wage_s", "base_qage_s", "split_alpha"):
            arr = np.asarray(getattr(stanzas, name))
            if arr.ndim != 2 or arr.shape[0] <= last or arr.shape[1] <= isp:
                problems.append(
                    f"{name} does not cover months {first}..{last} of group {isp}"
                )
                continue
            if not np.all(np.isfinite(arr[first : last + 1, isp])):
                problems.append(
                    f"{name} has missing values in months {first}..{last} "
                    f"of group {isp}"
                )
        for ist in range(1, nst + 1):
            ieco = int(stanzas.ecopath_code[isp, ist])
            if not 1 <= ieco <= n_groups:
                problems.append(
                    f"stanza group {isp} stanza {ist} points to group {ieco}"
                )
    return problems

create_stanza_params

create_stanza_params(groups: List[Dict[str, Any]], individuals: List[Dict[str, Any]]) -> EcosimStanzaParams

Create EcosimStanzaParams from dictionaries.

Convenience function to create stanza parameters from dictionary inputs.

Parameters:

Name Type Description Default
groups List[Dict[str, Any]]

List of dictionaries with stanza group parameters. Required keys: stanza_group_num, n_stanzas, vbgf_ksp. Optional keys: vbgf_d, wmat, bab, rec_power.

required
individuals List[Dict[str, Any]]

List of dictionaries with individual stanza parameters. Required keys: stanza_group_num, stanza_num, group_num, group_name, first, last, z. Optional keys: leading, leading_cb (defaults to leading).

required

Returns:

Type Description
EcosimStanzaParams

EcosimStanzaParams object

Examples:

>>> groups = [{'stanza_group_num': 1, 'n_stanzas': 2, 'vbgf_ksp': 0.3}]
>>> individuals = [
...     {'stanza_group_num': 1, 'stanza_num': 1, 'group_num': 1,
...      'group_name': 'Fish_juv', 'first': 0, 'last': 11,
...      'z': 1.5, 'leading': False},
...     {'stanza_group_num': 1, 'stanza_num': 2, 'group_num': 2,
...      'group_name': 'Fish_adult', 'first': 12, 'last': 60,
...      'z': 0.5, 'leading': True}
... ]
>>> params = create_stanza_params(groups, individuals)
Source code in pypath/core/stanzas.py
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
def create_stanza_params(
    groups: List[Dict[str, Any]], individuals: List[Dict[str, Any]]
) -> EcosimStanzaParams:
    """Create EcosimStanzaParams from dictionaries.

    Convenience function to create stanza parameters from
    dictionary inputs.

    Parameters
    ----------
    groups : List[Dict[str, Any]]
        List of dictionaries with stanza group parameters.
        Required keys: stanza_group_num, n_stanzas, vbgf_ksp.
        Optional keys: vbgf_d, wmat, bab, rec_power.
    individuals : List[Dict[str, Any]]
        List of dictionaries with individual stanza parameters.
        Required keys: stanza_group_num, stanza_num, group_num,
        group_name, first, last, z.
        Optional keys: leading, leading_cb (defaults to leading).

    Returns
    -------
    EcosimStanzaParams
        EcosimStanzaParams object

    Examples
    --------
        >>> groups = [{'stanza_group_num': 1, 'n_stanzas': 2, 'vbgf_ksp': 0.3}]
        >>> individuals = [
        ...     {'stanza_group_num': 1, 'stanza_num': 1, 'group_num': 1,
        ...      'group_name': 'Fish_juv', 'first': 0, 'last': 11,
        ...      'z': 1.5, 'leading': False},
        ...     {'stanza_group_num': 1, 'stanza_num': 2, 'group_num': 2,
        ...      'group_name': 'Fish_adult', 'first': 12, 'last': 60,
        ...      'z': 0.5, 'leading': True}
        ... ]
        >>> params = create_stanza_params(groups, individuals)
    """
    stanza_groups = []
    for g in groups:
        sg = StanzaGroup(
            stanza_group_num=g["stanza_group_num"],
            n_stanzas=g["n_stanzas"],
            vbgf_ksp=g["vbgf_ksp"],
            vbgf_d=g.get("vbgf_d", 0.66667),
            wmat=g.get("wmat", 0.0),
            bab=g.get("bab", 0.0),
            rec_power=g.get("rec_power", 1.0),
            fixed_fecundity=bool(g.get("fixed_fecundity", False)),
            rec_stanza=int(g.get("rec_stanza", 0)),
        )
        stanza_groups.append(sg)

    stanza_individuals = []
    for ind in individuals:
        si = StanzaIndividual(
            stanza_group_num=ind["stanza_group_num"],
            stanza_num=ind["stanza_num"],
            group_num=ind["group_num"],
            group_name=ind["group_name"],
            first=ind["first"],
            last=ind["last"],
            z=ind["z"],
            leading=ind.get("leading", False),
            leading_cb=ind.get("leading_cb", ind.get("leading", False)),
            spawn_prop=float(ind.get("spawn_prop", 1.0)),
        )
        stanza_individuals.append(si)

    return EcosimStanzaParams(
        n_stanza_groups=len(groups),
        stanza_groups=stanza_groups,
        stanza_individuals=stanza_individuals,
    )

ecosim_stanza_params

ecosim_stanza_params(stanzas: Any, model: DataFrame | None = None) -> EcosimStanzaParams

Convert RpathParams.stanzas to the form the stanza engine uses.

RpathParams.stanzas keeps the stanza tables as DataFrames (stgroups and stindiv, Rpath's layout), while rpath_stanzas and rsim_stanzas work on :class:EcosimStanzaParams. An EcosimStanzaParams passed in is returned as it is.

Parameters:

Name Type Description Default
stanzas Any

RpathStanzaParams (DataFrame form) or EcosimStanzaParams.

required
model DataFrame | None

The model table. Used to look up the group number of each stanza when stindiv has no group-number column.

None

Raises:

Type Description
ValueError

If a stanza lacks a value the dynamics need (Z, first month, leading flag, or the VBGF K of its group), or names a group that is not in the model.

Source code in pypath/core/stanzas.py
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
def ecosim_stanza_params(
    stanzas: Any, model: pd.DataFrame | None = None
) -> EcosimStanzaParams:
    """Convert ``RpathParams.stanzas`` to the form the stanza engine uses.

    ``RpathParams.stanzas`` keeps the stanza tables as DataFrames
    (``stgroups`` and ``stindiv``, Rpath's layout), while ``rpath_stanzas``
    and ``rsim_stanzas`` work on :class:`EcosimStanzaParams`. An
    ``EcosimStanzaParams`` passed in is returned as it is.

    Parameters
    ----------
    stanzas
        ``RpathStanzaParams`` (DataFrame form) or ``EcosimStanzaParams``.
    model
        The model table. Used to look up the group number of each stanza
        when ``stindiv`` has no group-number column.

    Raises
    ------
    ValueError
        If a stanza lacks a value the dynamics need (Z, first month,
        leading flag, or the VBGF K of its group), or names a group that
        is not in the model.
    """
    if isinstance(stanzas, EcosimStanzaParams):
        return stanzas
    if not has_stanza_tables(stanzas):
        return EcosimStanzaParams()

    stgroups = stanzas.stgroups
    stindiv = stanzas.stindiv
    if not isinstance(stgroups, pd.DataFrame) or not isinstance(stindiv, pd.DataFrame):
        raise ValueError("stanza tables stgroups and stindiv must both be DataFrames")

    model_groups: List[str] = []
    if model is not None and "Group" in model.columns:
        model_groups = [str(g) for g in model["Group"].tolist()]

    # ---- individual stanzas -------------------------------------------------
    rows = []
    for _, row in stindiv.iterrows():
        rec = {key: _pick(row, cols) for key, cols in _INDIV_COLUMNS.items()}
        name = str(rec["group_name"])
        for key, label in (("z", "Z"), ("first", "First"), ("leading", "Leading")):
            if _is_missing(rec[key]):
                raise ValueError(f"stanza {name}: {label} is missing")
        if _is_missing(rec["stanza_group_num"]):
            raise ValueError(f"stanza {name}: stanza group number is missing")
        if model_groups and name not in model_groups:
            raise ValueError(f"stanza {name}: group is not in the model")
        if _is_missing(rec["group_num"]):
            if not model_groups:
                raise ValueError(f"stanza {name}: GroupNum is missing")
            rec["group_num"] = model_groups.index(name) + 1
        elif model_groups:
            gn = int(rec["group_num"])
            if not 1 <= gn <= len(model_groups) or model_groups[gn - 1] != name:
                raise ValueError(
                    f"stanza {name}: GroupNum {gn} is not that group's row in the "
                    "model (1-based)"
                )
        rec["leading"] = _as_bool(rec["leading"])
        rows.append(rec)

    by_group: Dict[int, List[dict]] = {}
    for rec in rows:
        by_group.setdefault(int(rec["stanza_group_num"]), []).append(rec)

    individuals: List[StanzaIndividual] = []
    for sg_num in sorted(by_group):
        members = by_group[sg_num]
        if any(
            _is_missing(r["stanza_num"]) or int(r["stanza_num"]) <= 0 for r in members
        ):
            # Placeholder numbering: order the stanzas by their first month.
            members.sort(key=lambda r: float(r["first"]))
            for i, rec in enumerate(members, start=1):
                rec["stanza_num"] = i
        else:
            members.sort(key=lambda r: int(r["stanza_num"]))
        # LeadingCB: where any is given, the marked stanza anchors the
        # consumption; with none given (Rpath tables), the leading one.
        if all(_is_missing(r["leading_cb"]) for r in members):
            cb_flags = [r["leading"] for r in members]
        else:
            cb_flags = [
                False if _is_missing(r["leading_cb"]) else _as_bool(r["leading_cb"])
                for r in members
            ]
            if sum(cb_flags) > 1:
                raise ValueError(
                    f"stanza group {sg_num}: more than one LeadingCB stanza"
                )
            if not any(cb_flags):
                cb_flags = [r["leading"] for r in members]
        for rec, flag in zip(members, cb_flags):
            rec["leading_cb"] = bool(flag)
        firsts = [float(r["first"]) for r in members]
        if firsts[0] != 0:
            # The age tables are indexed by absolute month from 0.
            raise ValueError(
                f"stanza {members[0]['group_name']}: the youngest stanza must "
                f"start at month 0, not {firsts[0]:g}"
            )
        if any(b <= a for a, b in zip(firsts, firsts[1:])):
            raise ValueError(
                f"stanza group {sg_num}: First must increase with StanzaNum, "
                f"got {[int(f) for f in firsts]}"
            )
        for i, rec in enumerate(members):
            last = rec["last"]
            if _is_missing(last):
                # Up to the month before the next stanza starts. The oldest
                # stanza's last month is computed by rpath_stanzas.
                last = (
                    float(members[i + 1]["first"]) - 1
                    if i + 1 < len(members)
                    else float(rec["first"])
                )
            individuals.append(
                StanzaIndividual(
                    stanza_group_num=sg_num,
                    stanza_num=int(rec["stanza_num"]),
                    group_num=int(rec["group_num"]),
                    group_name=str(rec["group_name"]),
                    first=int(rec["first"]),
                    last=int(last),
                    z=float(rec["z"]),
                    leading=rec["leading"],
                    leading_cb=rec["leading_cb"],
                    spawn_prop=_number(rec["spawn_prop"], 1.0),
                )
            )

    # ---- stanza groups ------------------------------------------------------
    groups: List[StanzaGroup] = []
    seen: set = set()
    for _, row in stgroups.iterrows():
        rec = {key: _pick(row, cols) for key, cols in _GROUP_COLUMNS.items()}
        if _is_missing(rec["stanza_group_num"]):
            raise ValueError("stanza group number is missing in stgroups")
        sg_num = int(rec["stanza_group_num"])
        if sg_num in seen:
            raise ValueError(f"stanza group number {sg_num} appears twice in stgroups")
        seen.add(sg_num)
        label = rec["name"] if not _is_missing(rec["name"]) else f"group {sg_num}"
        if _is_missing(rec["vbgf_ksp"]):
            raise ValueError(f"stanza group {label}: VBGF_Ksp is missing")
        if float(rec["vbgf_ksp"]) <= 0:
            raise ValueError(f"stanza group {label}: VBGF_Ksp must be positive")
        members = by_group.get(sg_num, [])
        if not members:
            raise ValueError(f"stanza group {label}: no stanzas in stindiv")
        if sum(1 for r in members if r["leading"]) != 1:
            raise ValueError(f"stanza group {label}: needs exactly one leading stanza")
        groups.append(
            StanzaGroup(
                stanza_group_num=sg_num,
                n_stanzas=len(members),
                vbgf_ksp=float(rec["vbgf_ksp"]),
                vbgf_d=_number(rec["vbgf_d"], 0.66667),
                wmat=_number(rec["wmat"], 0.0),
                bab=_number(rec["bab"], 0.0),
                rec_power=_number(rec["rec_power"], 1.0),
                fixed_fecundity=(
                    False
                    if _is_missing(rec["fixed_fecundity"])
                    else _as_bool(rec["fixed_fecundity"])
                ),
                rec_stanza=int(_number(rec["rec_stanza"], 0.0)),
            )
        )
    groups.sort(key=lambda g: g.stanza_group_num)

    missing = set(by_group) - {g.stanza_group_num for g in groups}
    if missing:
        raise ValueError(
            f"stanzas refer to stanza groups {sorted(missing)} that are not in stgroups"
        )
    # rpath_stanzas / rsim_stanzas index groups by position (isp + 1), while
    # EwE databases number them by their own IDs. Renumber 1..N in ID order.
    renumber = {g.stanza_group_num: i for i, g in enumerate(groups, start=1)}
    for g in groups:
        g.stanza_group_num = renumber[g.stanza_group_num]
    for st in individuals:
        st.stanza_group_num = renumber[st.stanza_group_num]

    return EcosimStanzaParams(
        n_stanza_groups=len(groups),
        stanza_groups=groups,
        stanza_individuals=individuals,
    )

has_stanza_tables

has_stanza_tables(stanzas: Any) -> bool

True if stanzas describes at least one stanza group.

Looks at the tables rather than n_stanza_groups alone, because code that assigns stgroups/stindiv directly often leaves the count at 0.

Source code in pypath/core/stanzas.py
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
def has_stanza_tables(stanzas: Any) -> bool:
    """True if ``stanzas`` describes at least one stanza group.

    Looks at the tables rather than ``n_stanza_groups`` alone, because code
    that assigns ``stgroups``/``stindiv`` directly often leaves the count at 0.
    """
    if stanzas is None:
        return False
    if isinstance(stanzas, EcosimStanzaParams):
        return stanzas.n_stanza_groups > 0
    for table in ("stgroups", "stindiv"):
        df = getattr(stanzas, table, None)
        if isinstance(df, pd.DataFrame) and len(df) > 0:
            return True
    return getattr(stanzas, "n_stanza_groups", 0) > 0

rpath_stanzas

rpath_stanzas(rpath_params: RpathParams, stanza_params: EcosimStanzaParams | None = None, rule: str = 'rpath') -> RpathParams

Calculate biomass and consumption for multi-stanza groups.

Uses the leading stanza to calculate biomass and consumption of trailing stanzas necessary to support the leading stanza.

This implements Von Bertalanffy growth to distribute biomass across age classes based on the leading stanza's biomass.

Parameters:

Name Type Description Default
rpath_params RpathParams

RpathParams object with stanza information

required
stanza_params EcosimStanzaParams

Stanza parameters to work on. Defaults to rpath_params.stanzas converted with :func:ecosim_stanza_params. The computed age structure is written to this object, so pass the same object on to :func:rsim_stanzas.

None
rule ('rpath', 'ewe')

The age table. "rpath" (default) runs it out to 99.999 % of the cumulative biomass, as Rpath's rpath.stanzas; "ewe" builds EwE6's table, ending where a cohort reaches 90 % of W_inf and closed by a plus group (:func:_ewe_age_table). :func:rsim_scenario uses "ewe" under fast_group_rule="ewe".

"rpath"

Returns:

Type Description
RpathParams

Updated RpathParams with calculated stanza biomass and Q/B

Source code in pypath/core/stanzas.py
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
def rpath_stanzas(
    rpath_params: RpathParams,
    stanza_params: EcosimStanzaParams | None = None,
    rule: str = "rpath",
) -> RpathParams:
    """Calculate biomass and consumption for multi-stanza groups.

    Uses the leading stanza to calculate biomass and consumption
    of trailing stanzas necessary to support the leading stanza.

    This implements Von Bertalanffy growth to distribute biomass
    across age classes based on the leading stanza's biomass.

    Parameters
    ----------
    rpath_params : RpathParams
        RpathParams object with stanza information
    stanza_params : EcosimStanzaParams, optional
        Stanza parameters to work on. Defaults to ``rpath_params.stanzas``
        converted with :func:`ecosim_stanza_params`. The computed age
        structure is written to this object, so pass the same object on to
        :func:`rsim_stanzas`.
    rule : {"rpath", "ewe"}
        The age table. "rpath" (default) runs it out to 99.999 % of the
        cumulative biomass, as Rpath's ``rpath.stanzas``; "ewe" builds EwE6's
        table, ending where a cohort reaches 90 % of W_inf and closed by a
        plus group (:func:`_ewe_age_table`). :func:`rsim_scenario` uses
        "ewe" under ``fast_group_rule="ewe"``.

    Returns
    -------
    RpathParams
        Updated RpathParams with calculated stanza biomass and Q/B
    """
    if rule not in ("rpath", "ewe"):
        raise ValueError(f"rule must be 'rpath' or 'ewe', got {rule!r}")
    if stanza_params is None:
        if not has_stanza_tables(rpath_params.stanzas):
            return rpath_params
        stanza_params = ecosim_stanza_params(rpath_params.stanzas, rpath_params.model)
    if stanza_params.n_stanza_groups == 0:
        return rpath_params

    n_split = stanza_params.n_stanza_groups
    stanza_params.plus_group_rule = rule

    # Process each stanza group
    for isp in range(n_split):
        stanza_group = stanza_params.stanza_groups[isp]

        # Get stanzas for this group
        group_stanzas = [
            s for s in stanza_params.stanza_individuals if s.stanza_group_num == isp + 1
        ]
        group_stanzas.sort(key=lambda x: x.stanza_num)

        _n_stanzas = len(group_stanzas)

        # Find the leading stanza
        leading_stanza = None
        for st in group_stanzas:
            if st.leading:
                leading_stanza = st
                break

        if leading_stanza is None:
            raise ValueError(f"No leading stanza found for stanza group {isp + 1}")

        if rule == "ewe":
            st_group = _ewe_age_table(stanza_group, group_stanzas)
        else:
            st_group = _rpath_age_table(stanza_group, group_stanzas)

        # Biomass and consumption relative values
        st_group["B"] = st_group["Survive"] * st_group["WageS"]
        st_group["Q"] = st_group["Survive"] * st_group["QageS"]

        # Calculate relative biomass/consumption for each stanza
        for st in group_stanzas:
            mask = (st_group["age"] >= st.first) & (st_group["age"] <= st.last)
            st.bs_num = st_group.loc[mask, "B"].sum()
            st.qs_num = st_group.loc[mask, "Q"].sum()

        # Total biomass and consumption denominators
        bs_denom = sum(st.bs_num for st in group_stanzas)
        qs_denom = sum(st.qs_num for st in group_stanzas)

        # Relative fractions
        for st in group_stanzas:
            st.bs = st.bs_num / bs_denom if bs_denom > 0 else 0
            st.qs = st.qs_num / qs_denom if qs_denom > 0 else 0

        # Get leading stanza biomass from model
        leading_idx = rpath_params.model[
            rpath_params.model["Group"] == leading_stanza.group_name
        ].index[0]
        leading_biomass = rpath_params.model.loc[leading_idx, "Biomass"]
        leading_qb = rpath_params.model.loc[leading_idx, "QB"]

        # Calculate total biomass and consumption from leading
        if leading_stanza.bs > 0:
            total_biomass = leading_biomass / leading_stanza.bs
        else:
            total_biomass = leading_biomass

        # Consumption is anchored on the LeadingCB stanza (EwE BaseStanzaCB,
        # cEcoSimModel.vb 4384-4398): its Q/B is kept, with its derived
        # biomass. Without one marked, the leading stanza anchors it.
        cb_stanza = next((st for st in group_stanzas if st.leading_cb), None)
        if cb_stanza is None or cb_stanza is leading_stanza:
            cb_stanza, cb_qb, cb_biomass = leading_stanza, leading_qb, leading_biomass
        else:
            cb_idx = rpath_params.model[
                rpath_params.model["Group"] == cb_stanza.group_name
            ].index[0]
            cb_qb = rpath_params.model.loc[cb_idx, "QB"]
            cb_biomass = cb_stanza.bs * total_biomass

        if cb_stanza.qs > 0:
            total_cons = cb_qb * cb_biomass / cb_stanza.qs
        else:
            total_cons = cb_qb * cb_biomass

        # Distribute to other stanzas
        for st in group_stanzas:
            st.biomass = st.bs * total_biomass
            st.qb = (st.qs * total_cons) / st.biomass if st.biomass > 0 else 0

        # Calculate recruits (numbers at age 0)
        bio_per_egg = st_group.loc[
            (st_group["age"] >= leading_stanza.first)
            & (st_group["age"] <= leading_stanza.last),
            "B",
        ].sum()

        if bio_per_egg > 0:
            recruits = leading_biomass / bio_per_egg
        else:
            recruits = 0

        stanza_group.recruits = recruits

        # Numbers at age
        st_group["NageS"] = st_group["Survive"] * recruits

        # Store in params
        stanza_params.st_groups[isp + 1] = st_group

        # Update model DataFrame with calculated values
        for st in group_stanzas:
            model_idx = rpath_params.model[
                rpath_params.model["Group"] == st.group_name
            ].index
            if len(model_idx) > 0:
                rpath_params.model.loc[model_idx[0], "Biomass"] = st.biomass
                rpath_params.model.loc[model_idx[0], "QB"] = st.qb

    return rpath_params

rsim_stanzas

rsim_stanzas(rpath_params: RpathParams, state: ndarray, params: dict, stanza_params: EcosimStanzaParams | None = None) -> RsimStanzas

Initialize stanza parameters for Ecosim simulation.

Creates the stanza parameter structure needed by rsim_run().

Parameters:

Name Type Description Default
rpath_params RpathParams

RpathParams object with stanza information

required
state ndarray

RsimState object with initial state

required
params dict

RsimParams object with simulation parameters

required
stanza_params EcosimStanzaParams

The object :func:rpath_stanzas filled in. If omitted, rpath_params.stanzas is converted and run through :func:rpath_stanzas here.

None

Returns:

Type Description
RsimStanzas

RsimStanzas object with simulation parameters

Source code in pypath/core/stanzas.py
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
def rsim_stanzas(
    rpath_params: RpathParams,
    state: np.ndarray,
    params: dict,
    stanza_params: EcosimStanzaParams | None = None,
) -> RsimStanzas:
    """Initialize stanza parameters for Ecosim simulation.

    Creates the stanza parameter structure needed by rsim_run().

    Parameters
    ----------
    rpath_params : RpathParams
        RpathParams object with stanza information
    state : np.ndarray
        RsimState object with initial state
    params : dict
        RsimParams object with simulation parameters
    stanza_params : EcosimStanzaParams, optional
        The object :func:`rpath_stanzas` filled in. If omitted,
        ``rpath_params.stanzas`` is converted and run through
        :func:`rpath_stanzas` here.

    Returns
    -------
    RsimStanzas
        RsimStanzas object with simulation parameters
    """
    rstan = RsimStanzas()

    if stanza_params is None and has_stanza_tables(rpath_params.stanzas):
        stanza_params = ecosim_stanza_params(rpath_params.stanzas, rpath_params.model)
        if not stanza_params.st_groups:
            rpath_stanzas(rpath_params, stanza_params=stanza_params)

    if stanza_params is None or stanza_params.n_stanza_groups == 0:
        # Return empty stanza structure
        rstan.n_split = 0
        rstan.n_stanzas = np.array([0, 0])
        rstan.ecopath_code = np.zeros((2, 2))
        rstan.age1 = np.zeros((2, 2))
        rstan.age2 = np.zeros((2, 2))
        rstan.base_wage_s = np.zeros((2, 2))
        rstan.base_nage_s = np.zeros((2, 2))
        rstan.base_qage_s = np.zeros((2, 2))
        rstan.wmat = np.array([0.0, 0.0])
        rstan.rec_power = np.array([0.0, 0.0])
        rstan.recruits = np.array([0.0, 0.0])
        rstan.vbgf_d = np.array([0.0, 0.0])
        rstan.r_zero_s = np.array([0.0, 0.0])
        rstan.vbm = np.array([0.0, 0.0])
        rstan.split_alpha = np.zeros((2, 2))
        rstan.spawn_x = np.array([0.0, 0.0])
        rstan.spawn_energy = np.array([0.0, 0.0])
        rstan.base_eggs_stanza = np.array([0.0, 0.0])
        rstan.base_spawn_bio = np.array([0.0, 0.0])
        rstan.r_scale_split = np.array([0.0, 0.0])
        rstan.base_stanza_pred = np.zeros(params.NUM_GROUPS + 1)
        return rstan

    n_split = stanza_params.n_stanza_groups

    rstan.n_split = n_split

    # Get max stanzas and max months
    max_stanzas = max(sg.n_stanzas for sg in stanza_params.stanza_groups)
    max_months = max(sg.last_month for sg in stanza_params.stanza_groups) + 1

    # Initialize arrays with leading zeros for C-style indexing
    rstan.n_stanzas = np.zeros(n_split + 1, dtype=int)
    rstan.ecopath_code = np.full((n_split + 1, max_stanzas + 1), np.nan)
    rstan.age1 = np.full((n_split + 1, max_stanzas + 1), np.nan)
    rstan.age2 = np.full((n_split + 1, max_stanzas + 1), np.nan)
    rstan.base_wage_s = np.full((max_months, n_split + 1), np.nan)
    rstan.base_nage_s = np.full((max_months, n_split + 1), np.nan)
    rstan.base_qage_s = np.full((max_months, n_split + 1), np.nan)
    rstan.split_alpha = np.full((max_months, n_split + 1), np.nan)

    # Stanza pred accumulator, indexed like the Rsim arrays (0 = Outside);
    # group_num is the 1-based model row, so it indexes directly.
    s_pred = np.zeros(params.NUM_GROUPS + 1)

    # Process each stanza group
    for isp in range(n_split):
        stanza_group = stanza_params.stanza_groups[isp]
        rstan.n_stanzas[isp + 1] = stanza_group.n_stanzas

        # Get stanzas for this group
        group_stanzas = [
            s for s in stanza_params.stanza_individuals if s.stanza_group_num == isp + 1
        ]
        group_stanzas.sort(key=lambda x: x.stanza_num)

        # Fill in age codes
        for ist, st in enumerate(group_stanzas):
            rstan.ecopath_code[isp + 1, ist + 1] = st.group_num
            rstan.age1[isp + 1, ist + 1] = st.first
            rstan.age2[isp + 1, ist + 1] = st.last

        # Get age-structured data
        if isp + 1 in stanza_params.st_groups:
            st_group = stanza_params.st_groups[isp + 1]
            n_rows = len(st_group)
            rstan.base_wage_s[:n_rows, isp + 1] = st_group["WageS"].values
            rstan.base_nage_s[:n_rows, isp + 1] = st_group["NageS"].values
            rstan.base_qage_s[:n_rows, isp + 1] = st_group["QageS"].values

    # Maturity and recruitment parameters
    rstan.wmat = np.zeros(n_split + 1)
    rstan.rec_power = np.zeros(n_split + 1)
    rstan.recruits = np.zeros(n_split + 1)
    rstan.vbgf_d = np.zeros(n_split + 1)
    rstan.r_zero_s = np.zeros(n_split + 1)
    rstan.vbm = np.zeros(n_split + 1)
    rstan.ahat = np.zeros(n_split + 1)
    rstan.rhat = np.zeros(n_split + 1)
    rstan.plus_group_rule = stanza_params.plus_group_rule

    for isp, sg in enumerate(stanza_params.stanza_groups):
        rstan.wmat[isp + 1] = sg.wmat
        rstan.rec_power[isp + 1] = sg.rec_power
        rstan.recruits[isp + 1] = sg.recruits
        rstan.vbgf_d[isp + 1] = sg.vbgf_d
        rstan.r_zero_s[isp + 1] = sg.recruits
        if stanza_params.plus_group_rule == "ewe":
            # EwE6: RzeroS = Recruits x exp(BaB / 12) (vb 4362); with the
            # stages losing Z the numbers then grow at the rate BaB.
            rstan.r_zero_s[isp + 1] *= np.exp(sg.bab / 12.0)
        # Energy required to grow a unit in weight (scaled to Winf=1)
        rstan.vbm[isp + 1] = 1.0 - 3.0 * sg.vbgf_ksp / 12.0
        rstan.ahat[isp + 1] = sg.ahat
        rstan.rhat[isp + 1] = sg.rhat

    # Spawning (EwE6 SplitInitialize, vb 3458-3466): each life stage's
    # SpawnProp share of N (W - Wmat) over the mature ages; EggsSplit is the
    # base eggs per individual, kept for fixed fecundity.
    rstan.spawn_prop = np.ones((max_months, n_split + 1))
    rstan.eggs_split = np.zeros((max_months, n_split + 1))
    rstan.fixed_fecundity = np.zeros(n_split + 1, dtype=bool)
    rstan.rec_stanza = np.zeros(n_split + 1, dtype=int)
    eggs = np.zeros(n_split + 1)
    for isp in range(n_split):
        stanza_group = stanza_params.stanza_groups[isp]
        rstan.fixed_fecundity[isp + 1] = bool(stanza_group.fixed_fecundity)
        if 1 <= int(stanza_group.rec_stanza) <= n_split:
            rstan.rec_stanza[isp + 1] = int(stanza_group.rec_stanza)
        group_stanzas = [
            s for s in stanza_params.stanza_individuals if s.stanza_group_num == isp + 1
        ]
        for st in group_stanzas:
            rstan.spawn_prop[int(st.first) : int(st.last) + 1, isp + 1] = st.spawn_prop
        if isp + 1 in stanza_params.st_groups:
            st_group = stanza_params.st_groups[isp + 1]
            n_rows = len(st_group)
            w = st_group["WageS"].to_numpy(dtype=float)
            mature = w > rstan.wmat[isp + 1]
            per_fish = np.where(
                mature,
                (w - rstan.wmat[isp + 1]) * rstan.spawn_prop[:n_rows, isp + 1],
                0.0,
            )
            rstan.eggs_split[:n_rows, isp + 1] = per_fish
            eggs[isp + 1] = float(np.sum(st_group["NageS"].to_numpy(float) * per_fish))

    # Initialize split alpha growth coefficients
    for isp in range(n_split):
        stanza_group = stanza_params.stanza_groups[isp]
        group_stanzas = [
            s for s in stanza_params.stanza_individuals if s.stanza_group_num == isp + 1
        ]
        group_stanzas.sort(key=lambda x: x.stanza_num)

        if isp + 1 not in stanza_params.st_groups:
            continue

        st_group = stanza_params.st_groups[isp + 1]

        for ist, st in enumerate(group_stanzas):
            ieco = st.group_num
            first = st.first
            last = st.last

            # Calculate predation for this stanza
            mask = (st_group["age"] >= first) & (st_group["age"] <= last)
            pred = (st_group.loc[mask, "NageS"] * st_group.loc[mask, "QageS"]).sum()

            # Get consumption
            start_eaten_by = st.qb * st.biomass

            if start_eaten_by > 0:
                # Calculate split alpha
                wage_s = st_group["WageS"].values
                wage_s_next = np.roll(wage_s, -1)
                wage_s_next[-1] = wage_s[-1]

                split_alpha = (
                    (wage_s_next - rstan.vbm[isp + 1] * wage_s) * pred / start_eaten_by
                )
                rstan.split_alpha[first : last + 1, isp + 1] = split_alpha[
                    first : last + 1
                ]

            s_pred[ieco] = pred

        # Carry over final split alpha to plus group
        last_stanza = group_stanzas[-1]
        final_age = last_stanza.last
        if final_age > 0 and final_age < max_months:
            rstan.split_alpha[final_age, isp + 1] = rstan.split_alpha[
                final_age - 1, isp + 1
            ]

    # Misc parameters
    # Spawn X is Beverton-Holt. 10000 = off, 2 = half saturation
    rstan.spawn_x = np.concatenate([[0.0], np.full(n_split, 10000.0)])
    rstan.spawn_energy = np.concatenate([[0.0], np.ones(n_split)])
    rstan.base_eggs_stanza = eggs
    rstan.base_spawn_bio = eggs.copy()
    rstan.r_scale_split = np.concatenate([[0.0], np.ones(n_split)])
    rstan.base_stanza_pred = s_pred

    return rstan

split_set_pred

split_set_pred(stanzas: RsimStanzas, sstate: RsimStanzaState, biomass: ndarray) -> None

Sum the age structure into group totals (Rpath SplitSetPred).

Sets each stanza group's biomass to sum(N * W) over its months, and its numbers and StanzaPred (sum(N * Q), the consumption index used by the functional response and :func:split_update). biomass is updated in place: this is what couples the age structure to Ecosim.

Source code in pypath/core/stanzas.py
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
def split_set_pred(
    stanzas: RsimStanzas, sstate: RsimStanzaState, biomass: np.ndarray
) -> None:
    """Sum the age structure into group totals (Rpath ``SplitSetPred``).

    Sets each stanza group's biomass to sum(N * W) over its months, and its
    numbers and ``StanzaPred`` (sum(N * Q), the consumption index used by the
    functional response and :func:`split_update`). ``biomass`` is updated in
    place: this is what couples the age structure to Ecosim.
    """
    for isp in range(1, int(stanzas.n_split) + 1):
        for ist in range(1, int(stanzas.n_stanzas[isp]) + 1):
            ieco = int(stanzas.ecopath_code[isp, ist])
            ages = slice(int(stanzas.age1[isp, ist]), int(stanzas.age2[isp, ist]) + 1)
            nage = sstate.nage_s[ages, isp]
            biomass[ieco] = 1e-30 + float(np.sum(nage * sstate.wage_s[ages, isp]))
            sstate.stanza_pred[ieco] = 1e-30 + float(
                np.sum(nage * sstate.qage_s[ages, isp])
            )
            sstate.n[ieco] = 1e-30 + float(np.sum(nage))

split_update

split_update(stanzas: RsimStanzas, sstate: RsimStanzaState, biomass: ndarray, food_gain: ndarray, loss_prop_to_b: ndarray, forced_recs: ndarray | None = None, month_index: int | None = None) -> None

Advance the stanza age structure by one month (Rpath SplitUpdate).

For every stanza the numbers at age are reduced by the month's realised mortality, exp(-LossPropToB / 12 / B), and weights grow by WageS = vBM * WageS + (FoodGain / StanzaPred) * SplitAlpha. Spawning biomass (weight above Wmat) sets the egg output, ages move up one month (the oldest two months merge into the plus group), and recruits enter at the first month as RscaleSplit * RzeroS * (eggs / baseEggs) ** RecPower.

With stanzas.plus_group_rule == "ewe" (EwE6 SplitUpdate) the plus group's weight is (Su * Ahat + (1 - Su) * W[n-1]) / (1 - Rhat * Su) instead of the numbers-weighted mean, and the consumption weights qage_s stay at the setup's W^(2/3), as EwE's SplitSetPred.

Parameters:

Name Type Description Default
stanzas RsimStanzas

Stanza parameters; not modified.

required
sstate RsimStanzaState

Live age structure; updated in place.

required
biomass ndarray

Group biomass (Rsim indexing, Outside = 0) the rates were taken at.

required
food_gain ndarray

Consumption by each group, and its losses proportional to biomass (predation + M0 + fishing), per year, from the derivative.

required
loss_prop_to_b ndarray

Consumption by each group, and its losses proportional to biomass (predation + M0 + fishing), per year, from the derivative.

required
forced_recs ndarray

Recruitment forcing by group for this month. Like Rpath, it is read at the group of the last stanza.

None
Source code in pypath/core/stanzas.py
 869
 870
 871
 872
 873
 874
 875
 876
 877
 878
 879
 880
 881
 882
 883
 884
 885
 886
 887
 888
 889
 890
 891
 892
 893
 894
 895
 896
 897
 898
 899
 900
 901
 902
 903
 904
 905
 906
 907
 908
 909
 910
 911
 912
 913
 914
 915
 916
 917
 918
 919
 920
 921
 922
 923
 924
 925
 926
 927
 928
 929
 930
 931
 932
 933
 934
 935
 936
 937
 938
 939
 940
 941
 942
 943
 944
 945
 946
 947
 948
 949
 950
 951
 952
 953
 954
 955
 956
 957
 958
 959
 960
 961
 962
 963
 964
 965
 966
 967
 968
 969
 970
 971
 972
 973
 974
 975
 976
 977
 978
 979
 980
 981
 982
 983
 984
 985
 986
 987
 988
 989
 990
 991
 992
 993
 994
 995
 996
 997
 998
 999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
def split_update(
    stanzas: RsimStanzas,
    sstate: RsimStanzaState,
    biomass: np.ndarray,
    food_gain: np.ndarray,
    loss_prop_to_b: np.ndarray,
    forced_recs: np.ndarray | None = None,
    month_index: int | None = None,
) -> None:
    """Advance the stanza age structure by one month (Rpath ``SplitUpdate``).

    For every stanza the numbers at age are reduced by the month's realised
    mortality, ``exp(-LossPropToB / 12 / B)``, and weights grow by
    ``WageS = vBM * WageS + (FoodGain / StanzaPred) * SplitAlpha``. Spawning
    biomass (weight above ``Wmat``) sets the egg output, ages move up one
    month (the oldest two months merge into the plus group), and recruits
    enter at the first month as
    ``RscaleSplit * RzeroS * (eggs / baseEggs) ** RecPower``.

    With ``stanzas.plus_group_rule == "ewe"`` (EwE6 SplitUpdate) the plus
    group's weight is ``(Su * Ahat + (1 - Su) * W[n-1]) / (1 - Rhat * Su)``
    instead of the numbers-weighted mean, and the consumption weights
    ``qage_s`` stay at the setup's ``W^(2/3)``, as EwE's SplitSetPred.

    Parameters
    ----------
    stanzas : RsimStanzas
        Stanza parameters; not modified.
    sstate : RsimStanzaState
        Live age structure; updated in place.
    biomass : np.ndarray
        Group biomass (Rsim indexing, Outside = 0) the rates were taken at.
    food_gain, loss_prop_to_b : np.ndarray
        Consumption by each group, and its losses proportional to biomass
        (predation + M0 + fishing), per year, from the derivative.
    forced_recs : np.ndarray, optional
        Recruitment forcing by group for this month. Like Rpath, it is read
        at the group of the last stanza.
    """
    ewe_plus = getattr(stanzas, "plus_group_rule", "rpath") == "ewe"
    for isp in range(1, int(stanzas.n_split) + 1):
        nst = int(stanzas.n_stanzas[isp])
        if nst < 1:
            continue
        nage = sstate.nage_s
        wage = sstate.wage_s
        wmat = stanzas.wmat[isp]
        spawn = 0.0
        ieco = 0
        for ist in range(1, nst + 1):
            ieco = int(stanzas.ecopath_code[isp, ist])
            ages = slice(int(stanzas.age1[isp, ist]), int(stanzas.age2[isp, ist]) + 1)
            b = biomass[ieco]
            su = np.exp(-loss_prop_to_b[ieco] / 12.0 / b) if b > 0 else 0.0
            pred = sstate.stanza_pred[ieco]
            gf = food_gain[ieco] / pred if pred > 0 else 0.0
            nage[ages, isp] *= su
            wage[ages, isp] = (
                stanzas.vbm[isp] * wage[ages, isp] + gf * stanzas.split_alpha[ages, isp]
            )
            w = wage[ages, isp]
            # SpawnProp of this life stage (EwE6 SplitUpdate, vb 1852-1861)
            sp = (
                stanzas.spawn_prop[ages, isp]
                if getattr(stanzas, "spawn_prop", None) is not None
                else 1.0
            )
            fixed = getattr(stanzas, "fixed_fecundity", None)
            if fixed is not None and bool(fixed[isp]):
                # Eggs per individual at their base value; EwE multiplies by
                # SpawnProp again (EggsSplit already holds it).
                spawn += float(
                    np.sum(nage[ages, isp] * stanzas.eggs_split[ages, isp] * sp)
                )
            else:
                mature = w > wmat
                spawn += float(np.sum((nage[ages, isp] * (w - wmat) * sp)[mature]))
        sstate.spawn_bio[isp] = spawn

        spawn_x = stanzas.spawn_x[isp]
        base_spawn = stanzas.base_spawn_bio[isp]
        egg_mult = (
            float(forced_recs[ieco])
            if forced_recs is not None and ieco < len(forced_recs)
            else 1.0
        )
        if ewe_plus:
            # EwE6: the eggs are the spawning biomass (no saturation); the
            # egg-production forcing multiplies the recruits below.
            eggs = spawn
        elif base_spawn > 0:
            eggs = (
                spawn
                * stanzas.spawn_energy[isp]
                * spawn_x
                / (spawn_x - 1.0 + spawn / base_spawn)
            )
        else:
            eggs = 0.0
        if not ewe_plus:
            eggs *= egg_mult  # Rpath: inside the RecPower exponent
        sstate.eggs_stanza[isp] = eggs

        last = int(stanzas.age2[isp, nst])
        first = int(stanzas.age1[isp, 1])
        nt = nage[last, isp] + nage[last - 1, isp]
        if nt == 0:
            nt = 1e-30
        if ewe_plus:
            # EwE6 SplitUpdate (vb 1866): the plus group's weight is the tail
            # mean on the Ford-Walford line, from the month below it after
            # growth and the oldest stanza's survival (su, from the loop).
            wage[last, isp] = (
                su * stanzas.ahat[isp] + (1.0 - su) * wage[last - 1, isp]
            ) / (1.0 - stanzas.rhat[isp] * su)
        else:
            wage[last, isp] = (
                wage[last, isp] * nage[last, isp]
                + wage[last - 1, isp] * nage[last - 1, isp]
            ) / nt
        nage[last, isp] = nt
        # Age everyone by one month (copy first: the slices overlap)
        nage[first + 1 : last, isp] = nage[first : last - 1, isp].copy()
        wage[first + 1 : last, isp] = wage[first : last - 1, isp].copy()

        base_eggs = stanzas.base_eggs_stanza[isp]
        if base_eggs > 0:
            recruits = stanzas.r_scale_split[isp] * stanzas.r_zero_s[isp]
            if ewe_plus:
                # EwE6 SplitUpdate (vb 1895-1902): RscaleSplit x egg x RzeroS
                # x hatch, times (Eggs / BaseEggs)^RecPower only without a
                # hatch-code shape.
                hatch = _hatch_value(stanzas, isp, month_index)
                recruits *= egg_mult
                if hatch is None:
                    recruits *= (eggs / base_eggs) ** stanzas.rec_power[isp]
                else:
                    recruits *= hatch
            else:
                recruits *= (eggs / base_eggs) ** stanzas.rec_power[isp]
            nage[first, isp] = recruits
        wage[first, isp] = 0.0
        if not ewe_plus:
            # EwE6's SplitSetPred keeps the setup's W^(2/3) (WWa) instead.
            sstate.qage_s[: last + 1, isp] = (
                wage[: last + 1, isp] ** stanzas.vbgf_d[isp]
            )

    # Linked recruitment (EwE6 SplitUpdate, vb 1905-1912): a group with a
    # RecStanza recruits as that group, times the ratio of the two at the
    # first update of the run.
    rec = getattr(stanzas, "rec_stanza", None)
    if rec is not None:
        n_split = int(stanzas.n_split)
        if sstate.rec_scalar is None:
            sstate.rec_scalar = np.zeros(n_split + 1)
        for isp in range(1, n_split + 1):
            src = int(rec[isp])
            if not 1 <= src <= n_split:
                continue
            first_src = int(stanzas.age1[src, 1])
            first = int(stanzas.age1[isp, 1])
            s_from = sstate.nage_s[first_src, src]
            if sstate.rec_scalar[isp] == 0 and s_from > 0:
                sstate.rec_scalar[isp] = sstate.nage_s[first, isp] / s_from
            sstate.nage_s[first, isp] = s_from * sstate.rec_scalar[isp]

stanza_group_indices

stanza_group_indices(stanzas: RsimStanzas) -> np.ndarray

Model group numbers (Rsim indexing, Outside = 0) of all stanza groups.

Source code in pypath/core/stanzas.py
803
804
805
806
807
808
809
def stanza_group_indices(stanzas: RsimStanzas) -> np.ndarray:
    """Model group numbers (Rsim indexing, Outside = 0) of all stanza groups."""
    out = []
    for isp in range(1, int(stanzas.n_split) + 1):
        for ist in range(1, int(stanzas.n_stanzas[isp]) + 1):
            out.append(int(stanzas.ecopath_code[isp, ist]))
    return np.asarray(out, dtype=int)

von_bertalanffy_consumption

von_bertalanffy_consumption(wage_s: ndarray, d: float = 0.66667) -> np.ndarray

Calculate consumption at age from weight.

Q(a) = W(a)^d

Parameters:

Name Type Description Default
wage_s ndarray

Weight at age relative to Winf

required
d float

Allometric exponent (default 2/3)

0.66667

Returns:

Type Description
ndarray

Consumption at each age

Source code in pypath/core/stanzas.py
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
def von_bertalanffy_consumption(wage_s: np.ndarray, d: float = 0.66667) -> np.ndarray:
    """Calculate consumption at age from weight.

    Q(a) = W(a)^d

    Parameters
    ----------
    wage_s : np.ndarray
        Weight at age relative to Winf
    d : float
        Allometric exponent (default 2/3)

    Returns
    -------
    np.ndarray
        Consumption at each age
    """
    return wage_s**d

von_bertalanffy_weight

von_bertalanffy_weight(age: ndarray, k: float, d: float = 0.66667) -> np.ndarray

Calculate weight at age using Von Bertalanffy growth model.

W(a) = (1 - exp(-K * (1-d) * a))^(1/(1-d))

Weight is relative to Winf (asymptotic weight = 1).

Parameters:

Name Type Description Default
age ndarray

Age in months

required
k float

Monthly K parameter (Ksp * 3 / 12)

required
d float

Allometric exponent (default 2/3)

0.66667

Returns:

Type Description
ndarray

Weight relative to Winf at each age

Raises:

Type Description
ValueError

If d is not in the open interval (0, 1).

Source code in pypath/core/stanzas.py
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
def von_bertalanffy_weight(age: np.ndarray, k: float, d: float = 0.66667) -> np.ndarray:
    """Calculate weight at age using Von Bertalanffy growth model.

    W(a) = (1 - exp(-K * (1-d) * a))^(1/(1-d))

    Weight is relative to Winf (asymptotic weight = 1).

    Parameters
    ----------
    age : np.ndarray
        Age in months
    k : float
        Monthly K parameter (Ksp * 3 / 12)
    d : float
        Allometric exponent (default 2/3)

    Returns
    -------
    np.ndarray
        Weight relative to Winf at each age

    Raises
    ------
    ValueError
        If d is not in the open interval (0, 1).
    """
    if not (0 < d < 1):
        raise ValueError(f"d must be in (0, 1), got {d}")
    return (1.0 - np.exp(-k * (1.0 - d) * age)) ** (1.0 / (1.0 - d))

Adjustments

pypath.core.adjustments

Adjustment functions for Ecosim scenarios.

This module provides functions to modify fishing rates, forcing functions, and other scenario parameters over time.

Based on Rpath's adjust.fishing(), adjust.forcing(), and adjust.scenario() functions.

adjust_fishing

adjust_fishing(scenario: RsimScenario, parameter: str, group: Union[str, int, List[Union[str, int]]], sim_year: Union[int, range, List[int]], value: Union[float, ndarray], sim_month: Optional[Union[int, range, List[int]]] = None) -> RsimScenario

Adjust fishing parameters in an Ecosim scenario.

Modifies fishing-related forcing matrices (ForcedEffort, ForcedFRate, or ForcedCatch) for specified groups and time periods.

Parameters:

Name Type Description Default
scenario RsimScenario

RsimScenario object to modify

required
parameter str

One of 'ForcedEffort', 'ForcedFRate', or 'ForcedCatch'

required
group Union[str, int, List[Union[str, int]]]

Group name(s) or index(es) to modify. Can be: - Single group name (str) or index (int) - List of group names or indices

required
sim_year Union[int, range, List[int]]

Year(s) to modify, counted from the scenario's first year (scenario.start_year, 1 by default). Can be: - Single year (int) - Range of years (range object) - List of years

required
value Union[float, ndarray]

New value(s) to set. Can be: - Single value applied to all specified cells - Array matching the shape of selected cells - For ForcedEffort, one value per year, held through that year's selected months

required
sim_month Optional[Union[int, range, List[int]]]

Optional month(s) to modify (1-12). Only used for ForcedEffort which is monthly. If None, modifies all months.

None

Returns:

Type Description
RsimScenario

Modified scenario object

Raises:

Type Description
ValueError

If a year lies outside the scenario or a month outside 1 to 12.

Examples:

>>> # Double fishing mortality for 'Fish' group in years 10-20
>>> scenario = adjust_fishing(
...     scenario,
...     parameter='ForcedFRate',
...     group='Fish',
...     sim_year=range(10, 21),
...     value=0.5
... )

>>> # Set catch quota
>>> scenario = adjust_fishing(
...     scenario,
...     parameter='ForcedCatch',
...     group=['Cod', 'Haddock'],
...     sim_year=2025,
...     value=100.0
... )
Source code in pypath/core/adjustments.py
 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
def adjust_fishing(
    scenario: RsimScenario,
    parameter: str,
    group: Union[str, int, List[Union[str, int]]],
    sim_year: Union[int, range, List[int]],
    value: Union[float, np.ndarray],
    sim_month: Optional[Union[int, range, List[int]]] = None,
) -> RsimScenario:
    """Adjust fishing parameters in an Ecosim scenario.

    Modifies fishing-related forcing matrices (ForcedEffort, ForcedFRate,
    or ForcedCatch) for specified groups and time periods.

    Parameters
    ----------
    scenario : RsimScenario
        RsimScenario object to modify
    parameter : str
        One of 'ForcedEffort', 'ForcedFRate', or 'ForcedCatch'
    group : Union[str, int, List[Union[str, int]]]
        Group name(s) or index(es) to modify. Can be:
        - Single group name (str) or index (int)
        - List of group names or indices
    sim_year : Union[int, range, List[int]]
        Year(s) to modify, counted from the scenario's first year
        (``scenario.start_year``, 1 by default). Can be:
        - Single year (int)
        - Range of years (range object)
        - List of years
    value : Union[float, np.ndarray]
        New value(s) to set. Can be:
        - Single value applied to all specified cells
        - Array matching the shape of selected cells
        - For ForcedEffort, one value per year, held through that year's
          selected months
    sim_month : Optional[Union[int, range, List[int]]]
        Optional month(s) to modify (1-12). Only used for
        ForcedEffort which is monthly. If None, modifies all months.

    Returns
    -------
    RsimScenario
        Modified scenario object

    Raises
    ------
    ValueError
        If a year lies outside the scenario or a month outside 1 to 12.

    Examples
    --------
        >>> # Double fishing mortality for 'Fish' group in years 10-20
        >>> scenario = adjust_fishing(
        ...     scenario,
        ...     parameter='ForcedFRate',
        ...     group='Fish',
        ...     sim_year=range(10, 21),
        ...     value=0.5
        ... )

        >>> # Set catch quota
        >>> scenario = adjust_fishing(
        ...     scenario,
        ...     parameter='ForcedCatch',
        ...     group=['Cod', 'Haddock'],
        ...     sim_year=2025,
        ...     value=100.0
        ... )
    """
    valid_params = ["ForcedEffort", "ForcedFRate", "ForcedCatch"]
    if parameter not in valid_params:
        raise ValueError(f"parameter must be one of {valid_params}")

    # Get the fishing matrix
    fishing_matrix = getattr(scenario.fishing, parameter)

    # Convert group to indices
    group_indices = _resolve_group_indices(scenario, group, parameter)

    # ForcedEffort has a row per month; the other two a row per year.
    monthly = parameter == "ForcedEffort"
    n_years = fishing_matrix.shape[0] // 12 if monthly else fishing_matrix.shape[0]
    year_indices = _resolve_year_indices(scenario, sim_year, n_years)

    if monthly:
        # No sim_month means every month of each year.
        row_indices = _resolve_month_indices(
            year_indices, sim_month, fishing_matrix.shape[0]
        )
        months_per_year = len(row_indices) // max(len(year_indices), 1)
        if (
            not np.isscalar(value)
            and months_per_year > 1
            and np.shape(value)[:1] == (len(year_indices),)
        ):
            # One value per year: hold it through that year's months.
            value = np.repeat(np.asarray(value), months_per_year, axis=0)
    else:
        row_indices = year_indices

    # Set values
    if np.isscalar(value):
        for gi in group_indices:
            for ri in row_indices:
                fishing_matrix[ri, gi] = value
    else:
        # Value is an array - must match shape
        value = np.asarray(value)
        if value.shape == (len(row_indices), len(group_indices)):
            for i, ri in enumerate(row_indices):
                for j, gi in enumerate(group_indices):
                    fishing_matrix[ri, gi] = value[i, j]
        elif value.shape == (len(row_indices),):
            # Broadcast across groups
            for gi in group_indices:
                for i, ri in enumerate(row_indices):
                    fishing_matrix[ri, gi] = value[i]
        else:
            raise ValueError(f"value shape {value.shape} doesn't match selection")

    return scenario

adjust_forcing

adjust_forcing(scenario: RsimScenario, parameter: str, group: Union[str, int, List[Union[str, int]]], sim_year: Union[int, range, List[int]], sim_month: Union[int, range, List[int]], value: Union[float, ndarray]) -> RsimScenario

Adjust forcing parameters in an Ecosim scenario.

Modifies environmental forcing matrices (ForcedPrey, ForcedMort, ForcedRecs, ForcedSearch, ForcedActresp, ForcedMigrate, ForcedBio) for specified groups and time periods.

Parameters:

Name Type Description Default
scenario RsimScenario

RsimScenario object to modify

required
parameter str

One of: - 'ForcedPrey': Prey availability multiplier - 'ForcedMort': Additional mortality multiplier - 'ForcedRecs': Recruitment multiplier - 'ForcedSearch': Search rate multiplier - 'ForcedActresp': Active respiration multiplier - 'ForcedMigrate': Migration rate (additive) - 'ForcedBio': Biomass forcing (-1 = off)

required
group Union[str, int, List[Union[str, int]]]

Group name(s) or index(es) to modify

required
sim_year Union[int, range, List[int]]

Year(s) to modify

required
sim_month Union[int, range, List[int]]

Month(s) to modify (1-12)

required
value Union[float, ndarray]

New value(s) to set

required

Returns:

Type Description
RsimScenario

Modified scenario object

Examples:

>>> # Reduce prey availability in summer
>>> scenario = adjust_forcing(
...     scenario,
...     parameter='ForcedPrey',
...     group='Zooplankton',
...     sim_year=range(1, 51),
...     sim_month=[6, 7, 8],
...     value=0.8
... )

>>> # Add pulse recruitment
>>> scenario = adjust_forcing(
...     scenario,
...     parameter='ForcedRecs',
...     group='Fish',
...     sim_year=15,
...     sim_month=3,
...     value=2.0
... )
Source code in pypath/core/adjustments.py
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
def adjust_forcing(
    scenario: RsimScenario,
    parameter: str,
    group: Union[str, int, List[Union[str, int]]],
    sim_year: Union[int, range, List[int]],
    sim_month: Union[int, range, List[int]],
    value: Union[float, np.ndarray],
) -> RsimScenario:
    """Adjust forcing parameters in an Ecosim scenario.

    Modifies environmental forcing matrices (ForcedPrey, ForcedMort,
    ForcedRecs, ForcedSearch, ForcedActresp, ForcedMigrate, ForcedBio)
    for specified groups and time periods.

    Parameters
    ----------
    scenario : RsimScenario
        RsimScenario object to modify
    parameter : str
        One of:
        - 'ForcedPrey': Prey availability multiplier
        - 'ForcedMort': Additional mortality multiplier
        - 'ForcedRecs': Recruitment multiplier
        - 'ForcedSearch': Search rate multiplier
        - 'ForcedActresp': Active respiration multiplier
        - 'ForcedMigrate': Migration rate (additive)
        - 'ForcedBio': Biomass forcing (-1 = off)
    group : Union[str, int, List[Union[str, int]]]
        Group name(s) or index(es) to modify
    sim_year : Union[int, range, List[int]]
        Year(s) to modify
    sim_month : Union[int, range, List[int]]
        Month(s) to modify (1-12)
    value : Union[float, np.ndarray]
        New value(s) to set

    Returns
    -------
    RsimScenario
        Modified scenario object

    Examples
    --------
        >>> # Reduce prey availability in summer
        >>> scenario = adjust_forcing(
        ...     scenario,
        ...     parameter='ForcedPrey',
        ...     group='Zooplankton',
        ...     sim_year=range(1, 51),
        ...     sim_month=[6, 7, 8],
        ...     value=0.8
        ... )

        >>> # Add pulse recruitment
        >>> scenario = adjust_forcing(
        ...     scenario,
        ...     parameter='ForcedRecs',
        ...     group='Fish',
        ...     sim_year=15,
        ...     sim_month=3,
        ...     value=2.0
        ... )
    """
    valid_params = [
        "ForcedPrey",
        "ForcedMort",
        "ForcedRecs",
        "ForcedSearch",
        "ForcedActresp",
        "ForcedMigrate",
        "ForcedBio",
    ]
    if parameter not in valid_params:
        raise ValueError(f"parameter must be one of {valid_params}")

    # Get the forcing matrix
    forcing_matrix = getattr(scenario.forcing, parameter)

    # Convert group to indices
    group_indices = _resolve_group_indices(scenario, group, parameter, is_forcing=True)

    # Convert years to row indices
    year_indices = _resolve_year_indices(
        scenario, sim_year, forcing_matrix.shape[0] // 12
    )

    # Convert to monthly row indices
    row_indices = _resolve_month_indices(
        year_indices, sim_month, forcing_matrix.shape[0]
    )

    # Set values
    if np.isscalar(value):
        for gi in group_indices:
            for ri in row_indices:
                forcing_matrix[ri, gi] = value
    else:
        value = np.asarray(value)
        if value.shape == (len(row_indices), len(group_indices)):
            for i, ri in enumerate(row_indices):
                for j, gi in enumerate(group_indices):
                    forcing_matrix[ri, gi] = value[i, j]
        elif value.shape == (len(row_indices),):
            for gi in group_indices:
                for i, ri in enumerate(row_indices):
                    forcing_matrix[ri, gi] = value[i]
        else:
            raise ValueError(f"value shape {value.shape} doesn't match selection")

    return scenario

adjust_group_parameter

adjust_group_parameter(scenario: RsimScenario, group: Union[str, int], parameter: str, value: float) -> RsimScenario

Adjust a parameter for a specific group.

Modifies group-level parameters in the scenario's params object.

Parameters:

Name Type Description Default
scenario RsimScenario

RsimScenario object to modify

required
group Union[str, int]

Group name or index

required
parameter str

Parameter name. Options include: - 'MzeroMort': Background mortality - 'UnassimRespFrac': Unassimilated fraction - 'ActiveRespFrac': Active respiration fraction - 'FtimeAdj': Feeding time adjustment - 'PBopt': Optimal P/B

required
value float

New value to set

required

Returns:

Type Description
RsimScenario

Modified scenario object

Source code in pypath/core/adjustments.py
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
def adjust_group_parameter(
    scenario: RsimScenario, group: Union[str, int], parameter: str, value: float
) -> RsimScenario:
    """Adjust a parameter for a specific group.

    Modifies group-level parameters in the scenario's params object.

    Parameters
    ----------
    scenario : RsimScenario
        RsimScenario object to modify
    group : Union[str, int]
        Group name or index
    parameter : str
        Parameter name. Options include:
        - 'MzeroMort': Background mortality
        - 'UnassimRespFrac': Unassimilated fraction
        - 'ActiveRespFrac': Active respiration fraction
        - 'FtimeAdj': Feeding time adjustment
        - 'PBopt': Optimal P/B
    value : float
        New value to set

    Returns
    -------
    RsimScenario
        Modified scenario object
    """
    group_idx = _get_group_index(scenario, group) + 1  # +1 for "Outside"

    if hasattr(scenario.params, parameter):
        param_array = getattr(scenario.params, parameter)
        if isinstance(param_array, np.ndarray) and len(param_array) > group_idx:
            param_array[group_idx] = value
        else:
            raise ValueError(
                f"Parameter '{parameter}' not accessible at index {group_idx}"
            )
    else:
        raise AttributeError(f"Parameter '{parameter}' not found in scenario.params")

    return scenario

adjust_scenario

adjust_scenario(scenario: RsimScenario, parameter: str, value: Union[float, int, ndarray]) -> RsimScenario

Adjust global scenario parameters.

Modifies simulation-wide parameters in the scenario's params object.

Parameters:

Name Type Description Default
scenario RsimScenario

RsimScenario object to modify

required
parameter str

Parameter name to modify. Common options: - 'BURN_YEARS': Number of burn-in years (-1 = off) - 'COUPLED': Coupling flag (0 = uncoupled, 1 = coupled) - 'RK4_STEPS': Integration steps per month - 'SENSE_LIMIT': Sensitivity limits [min, max]

required
value Union[float, int, ndarray]

New value to set

required

Returns:

Type Description
RsimScenario

Modified scenario object

Examples:

>>> # Enable burn-in period
>>> scenario = adjust_scenario(scenario, 'BURN_YEARS', 10)

>>> # Change integration precision
>>> scenario = adjust_scenario(scenario, 'RK4_STEPS', 8)
Source code in pypath/core/adjustments.py
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
def adjust_scenario(
    scenario: RsimScenario, parameter: str, value: Union[float, int, np.ndarray]
) -> RsimScenario:
    """Adjust global scenario parameters.

    Modifies simulation-wide parameters in the scenario's params object.

    Parameters
    ----------
    scenario : RsimScenario
        RsimScenario object to modify
    parameter : str
        Parameter name to modify. Common options:
        - 'BURN_YEARS': Number of burn-in years (-1 = off)
        - 'COUPLED': Coupling flag (0 = uncoupled, 1 = coupled)
        - 'RK4_STEPS': Integration steps per month
        - 'SENSE_LIMIT': Sensitivity limits [min, max]
    value : Union[float, int, np.ndarray]
        New value to set

    Returns
    -------
    RsimScenario
        Modified scenario object

    Examples
    --------
        >>> # Enable burn-in period
        >>> scenario = adjust_scenario(scenario, 'BURN_YEARS', 10)

        >>> # Change integration precision
        >>> scenario = adjust_scenario(scenario, 'RK4_STEPS', 8)
    """
    if hasattr(scenario.params, parameter):
        setattr(scenario.params, parameter, value)
    else:
        raise AttributeError(f"Parameter '{parameter}' not found in scenario.params")

    return scenario

create_fishing_ramp

create_fishing_ramp(scenario: RsimScenario, group: Union[str, int], start_year: int, end_year: int, start_value: float, end_value: float, parameter: str = 'ForcedFRate') -> RsimScenario

Create a linear ramp in fishing pressure.

Convenience function to linearly interpolate fishing between two values over a range of years.

Parameters:

Name Type Description Default
scenario RsimScenario

RsimScenario object to modify

required
group Union[str, int]

Group to modify

required
start_year int

First year of ramp

required
end_year int

Last year of ramp

required
start_value float

Value at start_year

required
end_value float

Value at end_year

required
parameter str

Fishing parameter to modify

'ForcedFRate'

Returns:

Type Description
RsimScenario

Modified scenario object

Source code in pypath/core/adjustments.py
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
def create_fishing_ramp(
    scenario: RsimScenario,
    group: Union[str, int],
    start_year: int,
    end_year: int,
    start_value: float,
    end_value: float,
    parameter: str = "ForcedFRate",
) -> RsimScenario:
    """Create a linear ramp in fishing pressure.

    Convenience function to linearly interpolate fishing between
    two values over a range of years.

    Parameters
    ----------
    scenario : RsimScenario
        RsimScenario object to modify
    group : Union[str, int]
        Group to modify
    start_year : int
        First year of ramp
    end_year : int
        Last year of ramp
    start_value : float
        Value at start_year
    end_value : float
        Value at end_year
    parameter : str
        Fishing parameter to modify

    Returns
    -------
    RsimScenario
        Modified scenario object
    """
    years = list(range(start_year, end_year + 1))
    values = np.linspace(start_value, end_value, len(years))

    return adjust_fishing(
        scenario, parameter=parameter, group=group, sim_year=years, value=values
    )

create_pulse_forcing

create_pulse_forcing(scenario: RsimScenario, group: Union[str, int], pulse_years: List[int], pulse_months: Union[int, List[int]], magnitude: float, parameter: str = 'ForcedRecs') -> RsimScenario

Create pulse forcing events.

Convenience function to add periodic pulse events (e.g., recruitment pulses, mortality events).

Parameters:

Name Type Description Default
scenario RsimScenario

RsimScenario object to modify

required
group Union[str, int]

Group to modify

required
pulse_years List[int]

List of years with pulse events

required
pulse_months Union[int, List[int]]

Month(s) when pulse occurs

required
magnitude float

Multiplier for pulse (>1 = increase, <1 = decrease)

required
parameter str

Forcing parameter to modify

'ForcedRecs'

Returns:

Type Description
RsimScenario

Modified scenario object

Source code in pypath/core/adjustments.py
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
def create_pulse_forcing(
    scenario: RsimScenario,
    group: Union[str, int],
    pulse_years: List[int],
    pulse_months: Union[int, List[int]],
    magnitude: float,
    parameter: str = "ForcedRecs",
) -> RsimScenario:
    """Create pulse forcing events.

    Convenience function to add periodic pulse events
    (e.g., recruitment pulses, mortality events).

    Parameters
    ----------
    scenario : RsimScenario
        RsimScenario object to modify
    group : Union[str, int]
        Group to modify
    pulse_years : List[int]
        List of years with pulse events
    pulse_months : Union[int, List[int]]
        Month(s) when pulse occurs
    magnitude : float
        Multiplier for pulse (>1 = increase, <1 = decrease)
    parameter : str
        Forcing parameter to modify

    Returns
    -------
    RsimScenario
        Modified scenario object
    """
    for year in pulse_years:
        scenario = adjust_forcing(
            scenario,
            parameter=parameter,
            group=group,
            sim_year=year,
            sim_month=pulse_months,
            value=magnitude,
        )

    return scenario

create_seasonal_forcing

create_seasonal_forcing(scenario: RsimScenario, group: Union[str, int], years: Union[range, List[int]], monthly_values: List[float], parameter: str = 'ForcedPrey') -> RsimScenario

Create seasonal forcing pattern.

Applies a repeating 12-month pattern of forcing values across multiple years.

Parameters:

Name Type Description Default
scenario RsimScenario

RsimScenario object to modify

required
group Union[str, int]

Group to modify

required
years Union[range, List[int]]

Years to apply pattern

required
monthly_values List[float]

List of 12 values, one per month

required
parameter str

Forcing parameter to modify

'ForcedPrey'

Returns:

Type Description
RsimScenario

Modified scenario object

Examples:

>>> # Higher prey availability in summer
>>> seasonal = [0.8, 0.9, 1.0, 1.1, 1.2, 1.3,
...             1.3, 1.2, 1.1, 1.0, 0.9, 0.8]
>>> scenario = create_seasonal_forcing(
...     scenario, 'Zooplankton', range(1, 51), seasonal
... )
Source code in pypath/core/adjustments.py
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
def create_seasonal_forcing(
    scenario: RsimScenario,
    group: Union[str, int],
    years: Union[range, List[int]],
    monthly_values: List[float],
    parameter: str = "ForcedPrey",
) -> RsimScenario:
    """Create seasonal forcing pattern.

    Applies a repeating 12-month pattern of forcing values
    across multiple years.

    Parameters
    ----------
    scenario : RsimScenario
        RsimScenario object to modify
    group : Union[str, int]
        Group to modify
    years : Union[range, List[int]]
        Years to apply pattern
    monthly_values : List[float]
        List of 12 values, one per month
    parameter : str
        Forcing parameter to modify

    Returns
    -------
    RsimScenario
        Modified scenario object

    Examples
    --------
        >>> # Higher prey availability in summer
        >>> seasonal = [0.8, 0.9, 1.0, 1.1, 1.2, 1.3,
        ...             1.3, 1.2, 1.1, 1.0, 0.9, 0.8]
        >>> scenario = create_seasonal_forcing(
        ...     scenario, 'Zooplankton', range(1, 51), seasonal
        ... )
    """
    if len(monthly_values) != 12:
        raise ValueError("monthly_values must have exactly 12 elements")

    if isinstance(years, range):
        years = list(years)

    for month in range(1, 13):
        scenario = adjust_forcing(
            scenario,
            parameter=parameter,
            group=group,
            sim_year=years,
            sim_month=month,
            value=monthly_values[month - 1],
        )

    return scenario

set_handling_time

set_handling_time(scenario: RsimScenario, predator: Union[str, int], prey: Union[str, int], value: float) -> RsimScenario

Set handling time (d) for a predator-prey link.

Handling time controls predator satiation: - d = 1000: Off (default) - d = 0: Maximum satiation effect

Parameters:

Name Type Description Default
scenario RsimScenario

RsimScenario object to modify

required
predator Union[str, int]

Predator group name or index

required
prey Union[str, int]

Prey group name or index

required
value float

New handling time value

required

Returns:

Type Description
RsimScenario

Modified scenario object

Source code in pypath/core/adjustments.py
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
def set_handling_time(
    scenario: RsimScenario,
    predator: Union[str, int],
    prey: Union[str, int],
    value: float,
) -> RsimScenario:
    """Set handling time (d) for a predator-prey link.

    Handling time controls predator satiation:
    - d = 1000: Off (default)
    - d = 0: Maximum satiation effect

    Parameters
    ----------
    scenario : RsimScenario
        RsimScenario object to modify
    predator : Union[str, int]
        Predator group name or index
    prey : Union[str, int]
        Prey group name or index
    value : float
        New handling time value

    Returns
    -------
    RsimScenario
        Modified scenario object
    """
    pred_idx = _get_group_index(scenario, predator)
    prey_idx = _get_group_index(scenario, prey)

    # Find the link
    params = scenario.params
    for i in range(1, params.NumPredPreyLinks + 1):
        if params.PreyTo[i] == pred_idx and params.PreyFrom[i] == prey_idx:
            params.DD[i] = value
            return scenario

    raise ValueError(f"No predator-prey link found between {predator} and {prey}")

set_vulnerability

set_vulnerability(scenario: RsimScenario, predator: Union[str, int], prey: Union[str, int], value: float) -> RsimScenario

Set vulnerability (v) for a predator-prey link.

Vulnerability controls the functional response shape: - v = 1: Linear (Type I) - v = 2: Holling Type II (default) - v > 2: Approaches Type III

Parameters:

Name Type Description Default
scenario RsimScenario

RsimScenario object to modify

required
predator Union[str, int]

Predator group name or index

required
prey Union[str, int]

Prey group name or index

required
value float

New vulnerability value

required

Returns:

Type Description
RsimScenario

Modified scenario object

Source code in pypath/core/adjustments.py
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
def set_vulnerability(
    scenario: RsimScenario,
    predator: Union[str, int],
    prey: Union[str, int],
    value: float,
) -> RsimScenario:
    """Set vulnerability (v) for a predator-prey link.

    Vulnerability controls the functional response shape:
    - v = 1: Linear (Type I)
    - v = 2: Holling Type II (default)
    - v > 2: Approaches Type III

    Parameters
    ----------
    scenario : RsimScenario
        RsimScenario object to modify
    predator : Union[str, int]
        Predator group name or index
    prey : Union[str, int]
        Prey group name or index
    value : float
        New vulnerability value

    Returns
    -------
    RsimScenario
        Modified scenario object
    """
    pred_idx = _get_group_index(scenario, predator)
    prey_idx = _get_group_index(scenario, prey)

    # Find the link
    params = scenario.params
    for i in range(1, params.NumPredPreyLinks + 1):
        if params.PreyTo[i] == pred_idx and params.PreyFrom[i] == prey_idx:
            params.VV[i] = value
            return scenario

    raise ValueError(f"No predator-prey link found between {predator} and {prey}")

Forcing

pypath.core.forcing

Advanced forcing mechanisms for Ecosim simulations.

This module provides: 1. State-variable forcing (biomass, catch, etc.) 2. Dynamic diet rewiring based on prey availability 3. Flexible forcing modes (replace, add, multiply) 4. Temporal interpolation for sub-annual time steps

DietRewiring dataclass

Dynamic diet matrix rewiring based on prey availability.

Allows predator diet preferences to change over time in response to changing prey abundance (prey switching, adaptive foraging).

Attributes:

Name Type Description
enabled bool

Whether diet rewiring is active

switching_power float

Prey switching exponent (higher = more switching)

min_proportion float

Minimum diet proportion to maintain (prevents division by zero)

update_interval int

How often to update diet (in months)

base_diet ndarray

Original diet matrix (n_prey x n_pred)

current_diet ndarray

Current diet matrix (updated each interval)

Source code in pypath/core/forcing.py
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
@dataclass
class DietRewiring:
    """Dynamic diet matrix rewiring based on prey availability.

    Allows predator diet preferences to change over time in response to
    changing prey abundance (prey switching, adaptive foraging).

    Attributes
    ----------
    enabled : bool
        Whether diet rewiring is active
    switching_power : float
        Prey switching exponent (higher = more switching)
    min_proportion : float
        Minimum diet proportion to maintain (prevents division by zero)
    update_interval : int
        How often to update diet (in months)
    base_diet : np.ndarray
        Original diet matrix (n_prey x n_pred)
    current_diet : np.ndarray
        Current diet matrix (updated each interval)
    """

    enabled: bool = False
    switching_power: float = 2.0
    min_proportion: float = 0.001
    update_interval: int = 12  # Monthly
    base_diet: Optional[np.ndarray] = None
    current_diet: Optional[np.ndarray] = None

    def __post_init__(self) -> None:
        if self.enabled:
            # stacklevel=3: __post_init__ -> __init__ -> the caller
            warnings.warn(_DIET_REWIRING_DEPRECATION, DeprecationWarning, stacklevel=3)

    def initialize(self, diet_matrix: np.ndarray):
        """Initialize with base diet matrix.

        Parameters
        ----------
        diet_matrix : np.ndarray
            Base diet proportions (n_prey x n_pred)
        """
        self.base_diet = diet_matrix.copy()
        self.current_diet = diet_matrix.copy()

    def update_diet(
        self, prey_biomass: np.ndarray, predator_idx: Optional[int] = None
    ) -> "np.ndarray | None":
        """Update diet preferences based on prey availability.

        Uses a prey switching model where diet preferences shift toward
        more abundant prey species.

        Parameters
        ----------
        prey_biomass : np.ndarray
            Current biomass of all prey groups
        predator_idx : int, optional
            Update only this predator (None = update all)

        Returns
        -------
        np.ndarray
            Updated diet matrix

        Notes
        -----
        The prey switching model:

        new_diet[prey, pred] = base_diet[prey, pred] * (biomass[prey] / B_ref[prey])^power

        Then normalize so sum of diet = 1 for each predator.

        Higher switching_power = stronger response to biomass changes.
        """
        if not self.enabled:
            return None

        if self.base_diet is None:
            return self.current_diet

        n_prey, n_pred = self.base_diet.shape
        new_diet = self.current_diet.copy()

        # Calculate relative prey availability
        # Only use first n_prey entries (matching diet matrix)
        prey_biomass_subset = prey_biomass[:n_prey]
        prey_availability = np.maximum(prey_biomass_subset, self.min_proportion)

        # Update diet for specified predator(s)
        pred_range = range(n_pred) if predator_idx is None else [predator_idx]

        for pred in pred_range:
            # Get base diet for this predator
            base_prefs = self.base_diet[:, pred]

            # Only update where there's a base preference
            active_prey = base_prefs > self.min_proportion

            if not np.any(active_prey):
                continue

            # Apply prey switching model
            # new_pref = base_pref * (availability)^power
            new_prefs = base_prefs.copy()
            new_prefs[active_prey] = base_prefs[active_prey] * np.power(
                prey_availability[active_prey]
                / np.mean(prey_availability[active_prey]),
                self.switching_power,
            )

            # Ensure minimum proportions
            new_prefs = np.maximum(new_prefs, self.min_proportion)

            # Normalize to sum to 1
            total = np.sum(new_prefs)
            if total > 0:
                new_diet[:, pred] = new_prefs / total

        self.current_diet = new_diet
        return new_diet

    def reset(self):
        """Reset diet to base values."""
        if self.base_diet is not None:
            self.current_diet = self.base_diet.copy()
initialize
initialize(diet_matrix: ndarray)

Initialize with base diet matrix.

Parameters:

Name Type Description Default
diet_matrix ndarray

Base diet proportions (n_prey x n_pred)

required
Source code in pypath/core/forcing.py
298
299
300
301
302
303
304
305
306
307
def initialize(self, diet_matrix: np.ndarray):
    """Initialize with base diet matrix.

    Parameters
    ----------
    diet_matrix : np.ndarray
        Base diet proportions (n_prey x n_pred)
    """
    self.base_diet = diet_matrix.copy()
    self.current_diet = diet_matrix.copy()
reset
reset()

Reset diet to base values.

Source code in pypath/core/forcing.py
386
387
388
389
def reset(self):
    """Reset diet to base values."""
    if self.base_diet is not None:
        self.current_diet = self.base_diet.copy()
update_diet
update_diet(prey_biomass: ndarray, predator_idx: Optional[int] = None) -> 'np.ndarray | None'

Update diet preferences based on prey availability.

Uses a prey switching model where diet preferences shift toward more abundant prey species.

Parameters:

Name Type Description Default
prey_biomass ndarray

Current biomass of all prey groups

required
predator_idx int

Update only this predator (None = update all)

None

Returns:

Type Description
ndarray

Updated diet matrix

Notes

The prey switching model:

new_diet[prey, pred] = base_diet[prey, pred] * (biomass[prey] / B_ref[prey])^power

Then normalize so sum of diet = 1 for each predator.

Higher switching_power = stronger response to biomass changes.

Source code in pypath/core/forcing.py
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
def update_diet(
    self, prey_biomass: np.ndarray, predator_idx: Optional[int] = None
) -> "np.ndarray | None":
    """Update diet preferences based on prey availability.

    Uses a prey switching model where diet preferences shift toward
    more abundant prey species.

    Parameters
    ----------
    prey_biomass : np.ndarray
        Current biomass of all prey groups
    predator_idx : int, optional
        Update only this predator (None = update all)

    Returns
    -------
    np.ndarray
        Updated diet matrix

    Notes
    -----
    The prey switching model:

    new_diet[prey, pred] = base_diet[prey, pred] * (biomass[prey] / B_ref[prey])^power

    Then normalize so sum of diet = 1 for each predator.

    Higher switching_power = stronger response to biomass changes.
    """
    if not self.enabled:
        return None

    if self.base_diet is None:
        return self.current_diet

    n_prey, n_pred = self.base_diet.shape
    new_diet = self.current_diet.copy()

    # Calculate relative prey availability
    # Only use first n_prey entries (matching diet matrix)
    prey_biomass_subset = prey_biomass[:n_prey]
    prey_availability = np.maximum(prey_biomass_subset, self.min_proportion)

    # Update diet for specified predator(s)
    pred_range = range(n_pred) if predator_idx is None else [predator_idx]

    for pred in pred_range:
        # Get base diet for this predator
        base_prefs = self.base_diet[:, pred]

        # Only update where there's a base preference
        active_prey = base_prefs > self.min_proportion

        if not np.any(active_prey):
            continue

        # Apply prey switching model
        # new_pref = base_pref * (availability)^power
        new_prefs = base_prefs.copy()
        new_prefs[active_prey] = base_prefs[active_prey] * np.power(
            prey_availability[active_prey]
            / np.mean(prey_availability[active_prey]),
            self.switching_power,
        )

        # Ensure minimum proportions
        new_prefs = np.maximum(new_prefs, self.min_proportion)

        # Normalize to sum to 1
        total = np.sum(new_prefs)
        if total > 0:
            new_diet[:, pred] = new_prefs / total

    self.current_diet = new_diet
    return new_diet

ForcingFunction dataclass

Single forcing function for a state variable.

Attributes:

Name Type Description
group_idx int

Index of group to force (-1 for all groups)

variable StateVariable

Which state variable to force

mode ForcingMode

How to apply the forcing

time_series ndarray

Time series of forced values (years)

years ndarray

Year indices corresponding to time_series

interpolate bool

Whether to interpolate between annual values

active bool

Whether this forcing is currently active

Source code in pypath/core/forcing.py
 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
@dataclass
class ForcingFunction:
    """Single forcing function for a state variable.

    Attributes
    ----------
    group_idx : int
        Index of group to force (-1 for all groups)
    variable : StateVariable
        Which state variable to force
    mode : ForcingMode
        How to apply the forcing
    time_series : np.ndarray
        Time series of forced values (years)
    years : np.ndarray
        Year indices corresponding to time_series
    interpolate : bool
        Whether to interpolate between annual values
    active : bool
        Whether this forcing is currently active
    """

    group_idx: int
    variable: StateVariable
    mode: ForcingMode
    time_series: np.ndarray
    years: np.ndarray
    interpolate: bool = True
    active: bool = True

    def get_value(self, year: float) -> float:
        """Get forced value at given year (with interpolation).

        Parameters
        ----------
        year : float
            Simulation year (can be fractional for monthly time steps)

        Returns
        -------
        float
            Forced value at this time
        """
        if not self.active:
            return np.nan

        # Check if year is in range
        if year < self.years[0] or year > self.years[-1]:
            # Outside range - return NaN (no forcing)
            return np.nan

        if self.interpolate:
            # Linear interpolation
            return np.interp(year, self.years, self.time_series)
        else:
            # Use nearest year
            idx = np.argmin(np.abs(self.years - year))
            return self.time_series[idx]
get_value
get_value(year: float) -> float

Get forced value at given year (with interpolation).

Parameters:

Name Type Description Default
year float

Simulation year (can be fractional for monthly time steps)

required

Returns:

Type Description
float

Forced value at this time

Source code in pypath/core/forcing.py
 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 get_value(self, year: float) -> float:
    """Get forced value at given year (with interpolation).

    Parameters
    ----------
    year : float
        Simulation year (can be fractional for monthly time steps)

    Returns
    -------
    float
        Forced value at this time
    """
    if not self.active:
        return np.nan

    # Check if year is in range
    if year < self.years[0] or year > self.years[-1]:
        # Outside range - return NaN (no forcing)
        return np.nan

    if self.interpolate:
        # Linear interpolation
        return np.interp(year, self.years, self.time_series)
    else:
        # Use nearest year
        idx = np.argmin(np.abs(self.years - year))
        return self.time_series[idx]

ForcingMode

Bases: Enum

Mode for applying forced values.

Source code in pypath/core/forcing.py
25
26
27
28
29
30
31
class ForcingMode(Enum):
    """Mode for applying forced values."""

    REPLACE = "replace"  # Replace state variable with forced value
    ADD = "add"  # Add forced value to computed value
    MULTIPLY = "multiply"  # Multiply computed value by forced value
    RESCALE = "rescale"  # Rescale to match forced value

StateForcing dataclass

Collection of forcing functions for state variables.

Attributes:

Name Type Description
functions list[ForcingFunction]

List of individual forcing functions

Source code in pypath/core/forcing.py
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
@dataclass
class StateForcing:
    """Collection of forcing functions for state variables.

    Attributes
    ----------
    functions : list[ForcingFunction]
        List of individual forcing functions
    """

    functions: List[ForcingFunction] = field(default_factory=list)

    def add_forcing(
        self,
        group_idx: int,
        variable: Union[str, StateVariable],
        time_series: Union[np.ndarray, pd.Series, Dict[int, float]],
        years: Optional[np.ndarray] = None,
        mode: Union[str, ForcingMode] = ForcingMode.REPLACE,
        interpolate: bool = True,
    ):
        """Add a forcing function.

        Parameters
        ----------
        group_idx : int
            Index of group to force
        variable : str or StateVariable
            Which state variable to force
        time_series : array-like or dict
            Time series of forced values
            If dict, keys are years and values are forced values
        years : array-like, optional
            Year indices (required if time_series is array)
        mode : str or ForcingMode
            How to apply forcing ("replace", "add", "multiply", "rescale")
        interpolate : bool
            Whether to interpolate between annual values

        Examples
        --------
        >>> forcing = StateForcing()
        >>> # Force phytoplankton biomass to observed series
        >>> forcing.add_forcing(
        ...     group_idx=0,
        ...     variable='biomass',
        ...     time_series={2000: 15.0, 2001: 18.0, 2002: 16.0},
        ...     mode='replace'
        ... )
        >>>
        >>> # Add recruitment pulse for herring in 2005
        >>> forcing.add_forcing(
        ...     group_idx=3,
        ...     variable='recruitment',
        ...     time_series={2005: 2.5},  # 2.5x normal recruitment
        ...     mode='multiply'
        ... )
        """
        # Convert variable to enum
        if isinstance(variable, str):
            variable = StateVariable(variable.lower())

        # Convert mode to enum
        if isinstance(mode, str):
            mode = ForcingMode(mode.lower())

        # Handle dict input
        if isinstance(time_series, dict):
            years = np.array(list(time_series.keys()))
            time_series = np.array(list(time_series.values()))
        elif isinstance(time_series, pd.Series):
            years = time_series.index.values
            time_series = time_series.values
        else:
            time_series = np.asarray(time_series)

        if years is None:
            raise ValueError("years must be provided if time_series is not a dict")

        years = np.asarray(years)

        # Create forcing function
        func = ForcingFunction(
            group_idx=group_idx,
            variable=variable,
            mode=mode,
            time_series=time_series,
            years=years,
            interpolate=interpolate,
            active=True,
        )

        self.functions.append(func)

    def get_forcing(
        self, year: float, variable: StateVariable, group_idx: Optional[int] = None
    ) -> List[Tuple[ForcingFunction, float]]:
        """Get all active forcing values for a variable at given time.

        Parameters
        ----------
        year : float
            Current simulation year
        variable : StateVariable
            Which state variable to query
        group_idx : int, optional
            Specific group index (None = all groups)

        Returns
        -------
        list of (ForcingFunction, float)
            List of (forcing function, forced value) tuples
        """
        results = []

        for func in self.functions:
            if not func.active or func.variable != variable:
                continue

            # Check if this forcing applies to the group
            if group_idx is not None:
                if func.group_idx != -1 and func.group_idx != group_idx:
                    continue

            value = func.get_value(year)
            if not np.isnan(value):
                results.append((func, value))

        return results

    def remove_forcing(self, group_idx: int, variable: Union[str, StateVariable]):
        """Remove forcing for a specific group and variable.

        Parameters
        ----------
        group_idx : int
            Index of group
        variable : str or StateVariable
            Which state variable
        """
        if isinstance(variable, str):
            variable = StateVariable(variable.lower())

        self.functions = [
            f
            for f in self.functions
            if not (f.group_idx == group_idx and f.variable == variable)
        ]
add_forcing
add_forcing(group_idx: int, variable: Union[str, StateVariable], time_series: Union[ndarray, Series, Dict[int, float]], years: Optional[ndarray] = None, mode: Union[str, ForcingMode] = ForcingMode.REPLACE, interpolate: bool = True)

Add a forcing function.

Parameters:

Name Type Description Default
group_idx int

Index of group to force

required
variable str or StateVariable

Which state variable to force

required
time_series array - like or dict

Time series of forced values If dict, keys are years and values are forced values

required
years array - like

Year indices (required if time_series is array)

None
mode str or ForcingMode

How to apply forcing ("replace", "add", "multiply", "rescale")

REPLACE
interpolate bool

Whether to interpolate between annual values

True

Examples:

>>> forcing = StateForcing()
>>> # Force phytoplankton biomass to observed series
>>> forcing.add_forcing(
...     group_idx=0,
...     variable='biomass',
...     time_series={2000: 15.0, 2001: 18.0, 2002: 16.0},
...     mode='replace'
... )
>>>
>>> # Add recruitment pulse for herring in 2005
>>> forcing.add_forcing(
...     group_idx=3,
...     variable='recruitment',
...     time_series={2005: 2.5},  # 2.5x normal recruitment
...     mode='multiply'
... )
Source code in pypath/core/forcing.py
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
def add_forcing(
    self,
    group_idx: int,
    variable: Union[str, StateVariable],
    time_series: Union[np.ndarray, pd.Series, Dict[int, float]],
    years: Optional[np.ndarray] = None,
    mode: Union[str, ForcingMode] = ForcingMode.REPLACE,
    interpolate: bool = True,
):
    """Add a forcing function.

    Parameters
    ----------
    group_idx : int
        Index of group to force
    variable : str or StateVariable
        Which state variable to force
    time_series : array-like or dict
        Time series of forced values
        If dict, keys are years and values are forced values
    years : array-like, optional
        Year indices (required if time_series is array)
    mode : str or ForcingMode
        How to apply forcing ("replace", "add", "multiply", "rescale")
    interpolate : bool
        Whether to interpolate between annual values

    Examples
    --------
    >>> forcing = StateForcing()
    >>> # Force phytoplankton biomass to observed series
    >>> forcing.add_forcing(
    ...     group_idx=0,
    ...     variable='biomass',
    ...     time_series={2000: 15.0, 2001: 18.0, 2002: 16.0},
    ...     mode='replace'
    ... )
    >>>
    >>> # Add recruitment pulse for herring in 2005
    >>> forcing.add_forcing(
    ...     group_idx=3,
    ...     variable='recruitment',
    ...     time_series={2005: 2.5},  # 2.5x normal recruitment
    ...     mode='multiply'
    ... )
    """
    # Convert variable to enum
    if isinstance(variable, str):
        variable = StateVariable(variable.lower())

    # Convert mode to enum
    if isinstance(mode, str):
        mode = ForcingMode(mode.lower())

    # Handle dict input
    if isinstance(time_series, dict):
        years = np.array(list(time_series.keys()))
        time_series = np.array(list(time_series.values()))
    elif isinstance(time_series, pd.Series):
        years = time_series.index.values
        time_series = time_series.values
    else:
        time_series = np.asarray(time_series)

    if years is None:
        raise ValueError("years must be provided if time_series is not a dict")

    years = np.asarray(years)

    # Create forcing function
    func = ForcingFunction(
        group_idx=group_idx,
        variable=variable,
        mode=mode,
        time_series=time_series,
        years=years,
        interpolate=interpolate,
        active=True,
    )

    self.functions.append(func)
get_forcing
get_forcing(year: float, variable: StateVariable, group_idx: Optional[int] = None) -> List[Tuple[ForcingFunction, float]]

Get all active forcing values for a variable at given time.

Parameters:

Name Type Description Default
year float

Current simulation year

required
variable StateVariable

Which state variable to query

required
group_idx int

Specific group index (None = all groups)

None

Returns:

Type Description
list of (ForcingFunction, float)

List of (forcing function, forced value) tuples

Source code in pypath/core/forcing.py
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
def get_forcing(
    self, year: float, variable: StateVariable, group_idx: Optional[int] = None
) -> List[Tuple[ForcingFunction, float]]:
    """Get all active forcing values for a variable at given time.

    Parameters
    ----------
    year : float
        Current simulation year
    variable : StateVariable
        Which state variable to query
    group_idx : int, optional
        Specific group index (None = all groups)

    Returns
    -------
    list of (ForcingFunction, float)
        List of (forcing function, forced value) tuples
    """
    results = []

    for func in self.functions:
        if not func.active or func.variable != variable:
            continue

        # Check if this forcing applies to the group
        if group_idx is not None:
            if func.group_idx != -1 and func.group_idx != group_idx:
                continue

        value = func.get_value(year)
        if not np.isnan(value):
            results.append((func, value))

    return results
remove_forcing
remove_forcing(group_idx: int, variable: Union[str, StateVariable])

Remove forcing for a specific group and variable.

Parameters:

Name Type Description Default
group_idx int

Index of group

required
variable str or StateVariable

Which state variable

required
Source code in pypath/core/forcing.py
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
def remove_forcing(self, group_idx: int, variable: Union[str, StateVariable]):
    """Remove forcing for a specific group and variable.

    Parameters
    ----------
    group_idx : int
        Index of group
    variable : str or StateVariable
        Which state variable
    """
    if isinstance(variable, str):
        variable = StateVariable(variable.lower())

    self.functions = [
        f
        for f in self.functions
        if not (f.group_idx == group_idx and f.variable == variable)
    ]

StateVariable

Bases: Enum

State variables that can be forced.

Source code in pypath/core/forcing.py
34
35
36
37
38
39
40
41
42
43
class StateVariable(Enum):
    """State variables that can be forced."""

    BIOMASS = "biomass"
    CATCH = "catch"
    FISHING_MORTALITY = "fishing_mortality"
    RECRUITMENT = "recruitment"
    MORTALITY = "mortality"
    MIGRATION = "migration"
    PRIMARY_PRODUCTION = "primary_production"

create_biomass_forcing

create_biomass_forcing(group_idx: int, observed_biomass: Union[ndarray, Series, Dict[int, float]], years: Optional[ndarray] = None, mode: str = 'replace', interpolate: bool = True) -> StateForcing

Convenience function to create biomass forcing.

Parameters:

Name Type Description Default
group_idx int

Index of group to force

required
observed_biomass array - like or dict

Observed biomass time series

required
years array - like

Year indices

None
mode str

Forcing mode ("replace", "add", "multiply")

'replace'
interpolate bool

Whether to interpolate monthly values

True

Returns:

Type Description
StateForcing

Forcing object ready to use

Examples:

>>> # Force phytoplankton to observed biomass
>>> forcing = create_biomass_forcing(
...     group_idx=0,
...     observed_biomass={2000: 15.0, 2005: 18.0, 2010: 16.0},
...     mode='replace'
... )
Source code in pypath/core/forcing.py
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
def create_biomass_forcing(
    group_idx: int,
    observed_biomass: Union[np.ndarray, pd.Series, Dict[int, float]],
    years: Optional[np.ndarray] = None,
    mode: str = "replace",
    interpolate: bool = True,
) -> StateForcing:
    """Convenience function to create biomass forcing.

    Parameters
    ----------
    group_idx : int
        Index of group to force
    observed_biomass : array-like or dict
        Observed biomass time series
    years : array-like, optional
        Year indices
    mode : str
        Forcing mode ("replace", "add", "multiply")
    interpolate : bool
        Whether to interpolate monthly values

    Returns
    -------
    StateForcing
        Forcing object ready to use

    Examples
    --------
    >>> # Force phytoplankton to observed biomass
    >>> forcing = create_biomass_forcing(
    ...     group_idx=0,
    ...     observed_biomass={2000: 15.0, 2005: 18.0, 2010: 16.0},
    ...     mode='replace'
    ... )
    """
    forcing = StateForcing()
    forcing.add_forcing(
        group_idx=group_idx,
        variable=StateVariable.BIOMASS,
        time_series=observed_biomass,
        years=years,
        mode=mode,
        interpolate=interpolate,
    )
    return forcing

create_diet_rewiring

create_diet_rewiring(switching_power: float = 2.0, min_proportion: float = 0.001, update_interval: int = 12) -> DietRewiring

Convenience function to create diet rewiring configuration.

Parameters:

Name Type Description Default
switching_power float

Prey switching exponent (1.0 = proportional, >1 = switching)

2.0
min_proportion float

Minimum diet proportion to maintain

0.001
update_interval int

How often to update diet (months)

12

Returns:

Type Description
DietRewiring

Diet rewiring object ready to use

Examples:

>>> # Enable strong prey switching
>>> rewiring = create_diet_rewiring(switching_power=3.0)
Source code in pypath/core/forcing.py
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
def create_diet_rewiring(
    switching_power: float = 2.0,
    min_proportion: float = 0.001,
    update_interval: int = 12,
) -> DietRewiring:
    """Convenience function to create diet rewiring configuration.

    Parameters
    ----------
    switching_power : float
        Prey switching exponent (1.0 = proportional, >1 = switching)
    min_proportion : float
        Minimum diet proportion to maintain
    update_interval : int
        How often to update diet (months)

    Returns
    -------
    DietRewiring
        Diet rewiring object ready to use

    Examples
    --------
    >>> # Enable strong prey switching
    >>> rewiring = create_diet_rewiring(switching_power=3.0)
    """
    with warnings.catch_warnings():
        warnings.simplefilter("ignore", DeprecationWarning)
        rewiring = DietRewiring(
            enabled=True,
            switching_power=switching_power,
            min_proportion=min_proportion,
            update_interval=update_interval,
        )
    warnings.warn(_DIET_REWIRING_DEPRECATION, DeprecationWarning, stacklevel=2)
    return rewiring

create_recruitment_forcing

create_recruitment_forcing(group_idx: int, recruitment_multiplier: Union[ndarray, Dict[int, float]], years: Optional[ndarray] = None, interpolate: bool = False) -> StateForcing

Convenience function to create recruitment forcing.

Parameters:

Name Type Description Default
group_idx int

Index of group to force

required
recruitment_multiplier array - like or dict

Recruitment multiplier (1.0 = normal, 2.0 = double, etc.)

required
years array - like

Year indices

None
interpolate bool

Whether to interpolate (usually False for recruitment pulses)

False

Returns:

Type Description
StateForcing

Forcing object ready to use

Examples:

>>> # Strong recruitment in 2005, weak in 2010
>>> forcing = create_recruitment_forcing(
...     group_idx=3,
...     recruitment_multiplier={2005: 3.0, 2010: 0.5}
... )
Source code in pypath/core/forcing.py
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
def create_recruitment_forcing(
    group_idx: int,
    recruitment_multiplier: Union[np.ndarray, Dict[int, float]],
    years: Optional[np.ndarray] = None,
    interpolate: bool = False,
) -> StateForcing:
    """Convenience function to create recruitment forcing.

    Parameters
    ----------
    group_idx : int
        Index of group to force
    recruitment_multiplier : array-like or dict
        Recruitment multiplier (1.0 = normal, 2.0 = double, etc.)
    years : array-like, optional
        Year indices
    interpolate : bool
        Whether to interpolate (usually False for recruitment pulses)

    Returns
    -------
    StateForcing
        Forcing object ready to use

    Examples
    --------
    >>> # Strong recruitment in 2005, weak in 2010
    >>> forcing = create_recruitment_forcing(
    ...     group_idx=3,
    ...     recruitment_multiplier={2005: 3.0, 2010: 0.5}
    ... )
    """
    forcing = StateForcing()
    forcing.add_forcing(
        group_idx=group_idx,
        variable=StateVariable.RECRUITMENT,
        time_series=recruitment_multiplier,
        years=years,
        mode=ForcingMode.MULTIPLY,
        interpolate=interpolate,
    )
    return forcing

Recruitment Models

Stock-recruitment relationships and larval connectivity helpers for advanced population replenishment dynamics.

pypath.core.recruitment

Advanced recruitment models for Ecosim scenarios.

This module provides a consistent API for stock-recruitment relationships that map spawning stock biomass (SSB) to a recruitment multiplier. The multiplier is intended to scale baseline recruitment processes in dynamic Ecosim simulations.

BevertonHoltRecruitment

Bases: RecruitmentModel

Beverton-Holt model: R = (alpha * SSB) / (1 + beta * SSB).

Source code in pypath/core/recruitment.py
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
class BevertonHoltRecruitment(RecruitmentModel):
    """Beverton-Holt model: ``R = (alpha * SSB) / (1 + beta * SSB)``."""

    def __init__(
        self,
        alpha: float,
        beta: float,
        rmax: float = 1.0,
        name: str = "BevertonHolt",
    ):
        super().__init__(name=name, rmax=rmax)
        if alpha <= 0:
            raise ValueError(f"alpha must be > 0, got {alpha}")
        if beta <= 0:
            raise ValueError(f"beta must be > 0, got {beta}")
        self.alpha = float(alpha)
        self.beta = float(beta)

    def get_recruitment(
        self, ssb: float, time: float = 0.0, env_factor: float = 1.0
    ) -> float:
        _ = time
        ssb_val = self._sanitize_ssb(ssb)
        env = self._sanitize_env_factor(env_factor)
        base = (self.alpha * ssb_val) / (1.0 + self.beta * ssb_val)
        scaled = min(self.rmax, base) * env
        return max(0.01, float(scaled))

    def get_recruitment_batch(
        self,
        ssb_array: np.ndarray,
        time_array: np.ndarray,
        env_factors: Optional[np.ndarray] = None,
    ) -> np.ndarray:
        ssb, _times, env = self._validate_array_lengths(
            ssb_array, time_array, env_factors
        )
        base = (self.alpha * ssb) / (1.0 + self.beta * ssb)
        scaled = np.minimum(self.rmax, base) * env
        return np.maximum(0.01, scaled)

LarvalConnectivity

Larval dispersal model linking source and sink recruitment pools.

Parameters:

Name Type Description Default
connectivity_matrix ndarray

Matrix with shape (n_targets, n_sources). Each column describes how recruits from one source distribute across target groups.

required
source_groups list[str]

Source group names aligned to matrix columns.

required
target_groups list[str]

Target group names aligned to matrix rows.

required
survival_rate float

Global larval survival applied after dispersal.

1.0
normalize_columns bool

If True, each source column is normalized to sum to 1 when positive.

True
Source code in pypath/core/recruitment.py
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
class LarvalConnectivity:
    """Larval dispersal model linking source and sink recruitment pools.

    Parameters
    ----------
    connectivity_matrix : np.ndarray
        Matrix with shape (n_targets, n_sources). Each column describes how
        recruits from one source distribute across target groups.
    source_groups : list[str]
        Source group names aligned to matrix columns.
    target_groups : list[str]
        Target group names aligned to matrix rows.
    survival_rate : float, optional
        Global larval survival applied after dispersal.
    normalize_columns : bool, optional
        If True, each source column is normalized to sum to 1 when positive.
    """

    def __init__(
        self,
        connectivity_matrix: np.ndarray,
        source_groups: list[str],
        target_groups: list[str],
        survival_rate: float = 1.0,
        normalize_columns: bool = True,
    ):
        matrix = np.asarray(connectivity_matrix, dtype=float)
        if matrix.ndim != 2:
            raise ValueError("connectivity_matrix must be 2D")
        if len(source_groups) != matrix.shape[1]:
            raise ValueError(
                "source_groups length must match connectivity_matrix columns"
            )
        if len(target_groups) != matrix.shape[0]:
            raise ValueError("target_groups length must match connectivity_matrix rows")
        if np.any(matrix < 0):
            raise ValueError("connectivity_matrix cannot contain negative values")

        self.source_groups = list(source_groups)
        self.target_groups = list(target_groups)
        self.connectivity_matrix = matrix.copy()
        if normalize_columns:
            col_sums = self.connectivity_matrix.sum(axis=0)
            positive = col_sums > 0
            self.connectivity_matrix[:, positive] = (
                self.connectivity_matrix[:, positive] / col_sums[positive]
            )

        self.set_survival_rate(survival_rate)

    def set_survival_rate(self, survival_rate: float) -> None:
        """Update larval survival rate."""
        survival = float(survival_rate)
        if survival < 0:
            raise ValueError("survival_rate must be >= 0")
        self.survival_rate = survival

    def get_connectivity(self, source_group: str, target_group: str) -> float:
        """Get dispersal proportion from source to target."""
        if source_group not in self.source_groups:
            raise ValueError(f"Unknown source_group: {source_group}")
        if target_group not in self.target_groups:
            raise ValueError(f"Unknown target_group: {target_group}")
        source_idx = self.source_groups.index(source_group)
        target_idx = self.target_groups.index(target_group)
        return float(self.connectivity_matrix[target_idx, source_idx])

    def apply_to_array(self, source_recruits: np.ndarray) -> np.ndarray:
        """Apply connectivity to source recruitment vector."""
        recruits = np.asarray(source_recruits, dtype=float).reshape(-1)
        if recruits.size != len(self.source_groups):
            raise ValueError(
                "source_recruits length must match number of source_groups"
            )
        recruits = np.where(np.isfinite(recruits), np.maximum(0.0, recruits), 0.0)
        dispersed = self.connectivity_matrix @ recruits
        return dispersed * self.survival_rate

    def disperse(self, source_recruitment: dict[str, float]) -> dict[str, float]:
        """Disperse recruitment dictionary into target-group recruitment."""
        source_array = np.array(
            [float(source_recruitment.get(g, 0.0)) for g in self.source_groups],
            dtype=float,
        )
        target_array = self.apply_to_array(source_array)
        return {
            group: float(target_array[idx])
            for idx, group in enumerate(self.target_groups)
        }

    def __repr__(self) -> str:
        return (
            "LarvalConnectivity("
            f"sources={len(self.source_groups)}, targets={len(self.target_groups)}, "
            f"survival_rate={self.survival_rate})"
        )
apply_to_array
apply_to_array(source_recruits: ndarray) -> np.ndarray

Apply connectivity to source recruitment vector.

Source code in pypath/core/recruitment.py
324
325
326
327
328
329
330
331
332
333
def apply_to_array(self, source_recruits: np.ndarray) -> np.ndarray:
    """Apply connectivity to source recruitment vector."""
    recruits = np.asarray(source_recruits, dtype=float).reshape(-1)
    if recruits.size != len(self.source_groups):
        raise ValueError(
            "source_recruits length must match number of source_groups"
        )
    recruits = np.where(np.isfinite(recruits), np.maximum(0.0, recruits), 0.0)
    dispersed = self.connectivity_matrix @ recruits
    return dispersed * self.survival_rate
disperse
disperse(source_recruitment: dict[str, float]) -> dict[str, float]

Disperse recruitment dictionary into target-group recruitment.

Source code in pypath/core/recruitment.py
335
336
337
338
339
340
341
342
343
344
345
def disperse(self, source_recruitment: dict[str, float]) -> dict[str, float]:
    """Disperse recruitment dictionary into target-group recruitment."""
    source_array = np.array(
        [float(source_recruitment.get(g, 0.0)) for g in self.source_groups],
        dtype=float,
    )
    target_array = self.apply_to_array(source_array)
    return {
        group: float(target_array[idx])
        for idx, group in enumerate(self.target_groups)
    }
get_connectivity
get_connectivity(source_group: str, target_group: str) -> float

Get dispersal proportion from source to target.

Source code in pypath/core/recruitment.py
314
315
316
317
318
319
320
321
322
def get_connectivity(self, source_group: str, target_group: str) -> float:
    """Get dispersal proportion from source to target."""
    if source_group not in self.source_groups:
        raise ValueError(f"Unknown source_group: {source_group}")
    if target_group not in self.target_groups:
        raise ValueError(f"Unknown target_group: {target_group}")
    source_idx = self.source_groups.index(source_group)
    target_idx = self.target_groups.index(target_group)
    return float(self.connectivity_matrix[target_idx, source_idx])
set_survival_rate
set_survival_rate(survival_rate: float) -> None

Update larval survival rate.

Source code in pypath/core/recruitment.py
307
308
309
310
311
312
def set_survival_rate(self, survival_rate: float) -> None:
    """Update larval survival rate."""
    survival = float(survival_rate)
    if survival < 0:
        raise ValueError("survival_rate must be >= 0")
    self.survival_rate = survival

MyersRecruitment

Bases: RecruitmentModel

Myers-style saturating model: R = rmax * SSB^p / (k^p + SSB^p).

Source code in pypath/core/recruitment.py
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
class MyersRecruitment(RecruitmentModel):
    """Myers-style saturating model: ``R = rmax * SSB^p / (k^p + SSB^p)``."""

    def __init__(
        self,
        rmax: float,
        k: float,
        power: float = 1.0,
        name: str = "Myers",
    ):
        super().__init__(name=name, rmax=rmax)
        if k <= 0:
            raise ValueError(f"k must be > 0, got {k}")
        if power <= 0:
            raise ValueError(f"power must be > 0, got {power}")
        self.k = float(k)
        self.power = float(power)

    def get_recruitment(
        self, ssb: float, time: float = 0.0, env_factor: float = 1.0
    ) -> float:
        _ = time
        ssb_val = self._sanitize_ssb(ssb)
        env = self._sanitize_env_factor(env_factor)
        ssb_pow = ssb_val**self.power
        k_pow = self.k**self.power
        base = self.rmax * ssb_pow / (k_pow + ssb_pow)
        scaled = base * env
        return max(0.01, float(scaled))

    def get_recruitment_batch(
        self,
        ssb_array: np.ndarray,
        time_array: np.ndarray,
        env_factors: Optional[np.ndarray] = None,
    ) -> np.ndarray:
        ssb, _times, env = self._validate_array_lengths(
            ssb_array, time_array, env_factors
        )
        ssb_pow = ssb**self.power
        k_pow = self.k**self.power
        base = self.rmax * ssb_pow / (k_pow + ssb_pow)
        scaled = base * env
        return np.maximum(0.01, scaled)

RecruitmentModel

Bases: ABC

Abstract base class for recruitment models.

Recruitment models return multiplicative factors that can be applied to baseline recruitment. A factor of 1.0 indicates baseline recruitment.

Source code in pypath/core/recruitment.py
 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
class RecruitmentModel(ABC):
    """Abstract base class for recruitment models.

    Recruitment models return multiplicative factors that can be applied to
    baseline recruitment. A factor of 1.0 indicates baseline recruitment.
    """

    def __init__(self, name: str = "RecruitmentModel", rmax: float = 1.0):
        """Initialize recruitment model.

        Parameters
        ----------
        name : str
            Human-readable model name.
        rmax : float
            Maximum scaling multiplier used by the model.
        """
        if rmax <= 0:
            raise ValueError(f"rmax must be > 0, got {rmax}")
        self.name = name
        self.rmax = float(rmax)

    @abstractmethod
    def get_recruitment(
        self, ssb: float, time: float = 0.0, env_factor: float = 1.0
    ) -> float:
        """Get recruitment multiplier for one state."""
        raise NotImplementedError

    @abstractmethod
    def get_recruitment_batch(
        self,
        ssb_array: np.ndarray,
        time_array: np.ndarray,
        env_factors: Optional[np.ndarray] = None,
    ) -> np.ndarray:
        """Get recruitment multipliers for arrays of states."""
        raise NotImplementedError

    def get_recruitment_trajectory(
        self, ssb_timeline: dict[float, float], times: np.ndarray
    ) -> np.ndarray:
        """Interpolate SSB across time and evaluate recruitment trajectory."""
        if not ssb_timeline:
            raise ValueError("ssb_timeline cannot be empty")

        times_arr = np.asarray(times, dtype=float)
        if times_arr.size == 0:
            raise ValueError("times cannot be empty")

        source_times = np.array(sorted(ssb_timeline.keys()), dtype=float)
        source_ssb = np.array([ssb_timeline[t] for t in source_times], dtype=float)

        if source_times.size == 1:
            ssb_values = np.full_like(times_arr, source_ssb[0], dtype=float)
        else:
            interp = interp1d(
                source_times,
                source_ssb,
                kind="linear",
                bounds_error=False,
                fill_value=(source_ssb[0], source_ssb[-1]),
            )
            ssb_values = np.asarray(interp(times_arr), dtype=float)

        return self.get_recruitment_batch(ssb_values, times_arr)

    @staticmethod
    def _sanitize_ssb(ssb: float) -> float:
        """Clamp invalid SSB values to a safe non-negative value."""
        if not np.isfinite(ssb):
            return 0.0
        return max(0.0, float(ssb))

    @staticmethod
    def _sanitize_env_factor(env_factor: float) -> float:
        """Use positive finite environmental factor or baseline fallback."""
        if not np.isfinite(env_factor) or env_factor <= 0:
            return 1.0
        return float(env_factor)

    @staticmethod
    def _validate_array_lengths(
        ssb_array: np.ndarray,
        time_array: np.ndarray,
        env_factors: Optional[np.ndarray] = None,
    ) -> tuple[np.ndarray, np.ndarray, np.ndarray]:
        """Validate and align vectorized recruitment inputs."""
        ssb = np.asarray(ssb_array, dtype=float).reshape(-1)
        times = np.asarray(time_array, dtype=float).reshape(-1)
        if ssb.size != times.size:
            raise ValueError(
                f"ssb_array (len {ssb.size}) and time_array (len {times.size}) "
                "must have same length"
            )

        if env_factors is None:
            env = np.ones_like(ssb, dtype=float)
        else:
            env = np.asarray(env_factors, dtype=float).reshape(-1)
            if env.size != ssb.size:
                raise ValueError(
                    f"env_factors (len {env.size}) must match ssb_array "
                    f"(len {ssb.size})"
                )

        ssb = np.where(np.isfinite(ssb), np.maximum(0.0, ssb), 0.0)
        env = np.where(np.isfinite(env) & (env > 0.0), env, 1.0)
        return ssb, times, env

    def __repr__(self) -> str:
        return f"{self.__class__.__name__}(name={self.name!r}, rmax={self.rmax})"
__init__
__init__(name: str = 'RecruitmentModel', rmax: float = 1.0)

Initialize recruitment model.

Parameters:

Name Type Description Default
name str

Human-readable model name.

'RecruitmentModel'
rmax float

Maximum scaling multiplier used by the model.

1.0
Source code in pypath/core/recruitment.py
24
25
26
27
28
29
30
31
32
33
34
35
36
37
def __init__(self, name: str = "RecruitmentModel", rmax: float = 1.0):
    """Initialize recruitment model.

    Parameters
    ----------
    name : str
        Human-readable model name.
    rmax : float
        Maximum scaling multiplier used by the model.
    """
    if rmax <= 0:
        raise ValueError(f"rmax must be > 0, got {rmax}")
    self.name = name
    self.rmax = float(rmax)
get_recruitment abstractmethod
get_recruitment(ssb: float, time: float = 0.0, env_factor: float = 1.0) -> float

Get recruitment multiplier for one state.

Source code in pypath/core/recruitment.py
39
40
41
42
43
44
@abstractmethod
def get_recruitment(
    self, ssb: float, time: float = 0.0, env_factor: float = 1.0
) -> float:
    """Get recruitment multiplier for one state."""
    raise NotImplementedError
get_recruitment_batch abstractmethod
get_recruitment_batch(ssb_array: ndarray, time_array: ndarray, env_factors: Optional[ndarray] = None) -> np.ndarray

Get recruitment multipliers for arrays of states.

Source code in pypath/core/recruitment.py
46
47
48
49
50
51
52
53
54
@abstractmethod
def get_recruitment_batch(
    self,
    ssb_array: np.ndarray,
    time_array: np.ndarray,
    env_factors: Optional[np.ndarray] = None,
) -> np.ndarray:
    """Get recruitment multipliers for arrays of states."""
    raise NotImplementedError
get_recruitment_trajectory
get_recruitment_trajectory(ssb_timeline: dict[float, float], times: ndarray) -> np.ndarray

Interpolate SSB across time and evaluate recruitment trajectory.

Source code in pypath/core/recruitment.py
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
def get_recruitment_trajectory(
    self, ssb_timeline: dict[float, float], times: np.ndarray
) -> np.ndarray:
    """Interpolate SSB across time and evaluate recruitment trajectory."""
    if not ssb_timeline:
        raise ValueError("ssb_timeline cannot be empty")

    times_arr = np.asarray(times, dtype=float)
    if times_arr.size == 0:
        raise ValueError("times cannot be empty")

    source_times = np.array(sorted(ssb_timeline.keys()), dtype=float)
    source_ssb = np.array([ssb_timeline[t] for t in source_times], dtype=float)

    if source_times.size == 1:
        ssb_values = np.full_like(times_arr, source_ssb[0], dtype=float)
    else:
        interp = interp1d(
            source_times,
            source_ssb,
            kind="linear",
            bounds_error=False,
            fill_value=(source_ssb[0], source_ssb[-1]),
        )
        ssb_values = np.asarray(interp(times_arr), dtype=float)

    return self.get_recruitment_batch(ssb_values, times_arr)

RickerRecruitment

Bases: RecruitmentModel

Ricker model: R = alpha * SSB * exp(-beta * SSB).

Source code in pypath/core/recruitment.py
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
class RickerRecruitment(RecruitmentModel):
    """Ricker model: ``R = alpha * SSB * exp(-beta * SSB)``."""

    def __init__(
        self, alpha: float, beta: float, rmax: float = 1.0, name: str = "Ricker"
    ):
        super().__init__(name=name, rmax=rmax)
        if alpha <= 0:
            raise ValueError(f"alpha must be > 0, got {alpha}")
        if beta <= 0:
            raise ValueError(f"beta must be > 0, got {beta}")
        self.alpha = float(alpha)
        self.beta = float(beta)

    def get_recruitment(
        self, ssb: float, time: float = 0.0, env_factor: float = 1.0
    ) -> float:
        _ = time
        ssb_val = self._sanitize_ssb(ssb)
        env = self._sanitize_env_factor(env_factor)
        base = self.alpha * ssb_val * np.exp(-self.beta * ssb_val)
        scaled = min(self.rmax, base) * env
        return max(0.01, float(scaled))

    def get_recruitment_batch(
        self,
        ssb_array: np.ndarray,
        time_array: np.ndarray,
        env_factors: Optional[np.ndarray] = None,
    ) -> np.ndarray:
        ssb, _times, env = self._validate_array_lengths(
            ssb_array, time_array, env_factors
        )
        base = self.alpha * ssb * np.exp(-self.beta * ssb)
        scaled = np.minimum(self.rmax, base) * env
        return np.maximum(0.01, scaled)

normalize_ssb_effect

normalize_ssb_effect(ssb: float | ndarray, reference_ssb: float, effect_magnitude: float = 1.0) -> float | np.ndarray

Normalize SSB relative to a reference stock biomass.

Source code in pypath/core/recruitment.py
396
397
398
399
400
401
402
403
404
405
406
407
408
409
def normalize_ssb_effect(
    ssb: float | np.ndarray, reference_ssb: float, effect_magnitude: float = 1.0
) -> float | np.ndarray:
    """Normalize SSB relative to a reference stock biomass."""
    if reference_ssb <= 0:
        raise ValueError(f"reference_ssb must be > 0, got {reference_ssb}")

    ssb_values = np.asarray(ssb, dtype=float)
    safe_ssb = np.where(np.isfinite(ssb_values), np.maximum(0.0, ssb_values), 0.0)
    normalized = np.power(safe_ssb / reference_ssb, effect_magnitude)
    clipped = np.maximum(0.01, normalized)
    if np.isscalar(ssb):
        return float(clipped)
    return clipped

validate_recruitment_params

validate_recruitment_params(model_type: str, **kwargs) -> dict[str, float | str]

Validate model parameters for recruitment model construction.

Source code in pypath/core/recruitment.py
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
def validate_recruitment_params(model_type: str, **kwargs) -> dict[str, float | str]:
    """Validate model parameters for recruitment model construction."""
    normalized = model_type.lower().replace("-", "").replace("_", "")
    if normalized == "ricker":
        required = {"alpha", "beta"}
        missing = required - set(kwargs)
        if missing:
            raise ValueError(f"Ricker requires {missing}, got {set(kwargs)}")
        alpha = float(kwargs["alpha"])
        beta = float(kwargs["beta"])
        if alpha <= 0 or beta <= 0:
            raise ValueError("Ricker alpha and beta must be > 0")
        allowed = {"alpha", "beta", "rmax", "name"}
    elif normalized == "bevertonholt":
        required = {"alpha", "beta"}
        missing = required - set(kwargs)
        if missing:
            raise ValueError(f"BevertonHolt requires {missing}, got {set(kwargs)}")
        alpha = float(kwargs["alpha"])
        beta = float(kwargs["beta"])
        if alpha <= 0 or beta <= 0:
            raise ValueError("BevertonHolt alpha and beta must be > 0")
        allowed = {"alpha", "beta", "rmax", "name"}
    elif normalized == "myers":
        required = {"rmax", "k"}
        missing = required - set(kwargs)
        if missing:
            raise ValueError(f"Myers requires {missing}, got {set(kwargs)}")
        rmax = float(kwargs["rmax"])
        k = float(kwargs["k"])
        if rmax <= 0 or k <= 0:
            raise ValueError("Myers rmax and k must be > 0")
        allowed = {"rmax", "k", "power", "name"}
    else:
        raise ValueError(
            f"Unknown recruitment model_type '{model_type}'. Must be "
            "'Ricker', 'BevertonHolt', or 'Myers'."
        )
    return {k: v for k, v in kwargs.items() if k in allowed}

Ecosim Recruitment Wiring

Runtime wiring that patches recruitment processes into RsimScenario and Ecosim time stepping.

pypath.core.ecosim_recruitment

Recruitment support for Ecosim scenarios.

Monkey-patches RsimScenario with recruitment model registration, trajectory helpers, and optional larval connectivity application.

add_recruitment_support

add_recruitment_support() -> None

Monkey-patch RsimScenario with recruitment methods.

Source code in pypath/core/ecosim_recruitment.py
 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
def add_recruitment_support() -> None:
    """Monkey-patch RsimScenario with recruitment methods."""
    if hasattr(RsimScenario, "set_recruitment_model"):
        return

    def _init_recruitment(self: RsimScenario) -> None:
        if not hasattr(self, "_recruitment_models"):
            self._recruitment_models: Dict[str, RecruitmentModel] = {}
        if not hasattr(self, "_larval_connectivity"):
            self._larval_connectivity: Optional[LarvalConnectivity] = None

    def set_recruitment_model(
        self: RsimScenario, group_name: str, model: RecruitmentModel
    ) -> None:
        from pypath.core.recruitment import RecruitmentModel

        _init_recruitment(self)
        if group_name not in self.params.spname:
            raise ValueError(f"Unknown group: {group_name}")
        if not isinstance(model, RecruitmentModel):
            raise TypeError(
                "model must be an instance of RecruitmentModel, "
                f"got {type(model).__name__}"
            )
        self._recruitment_models[group_name] = model

    def get_recruitment_model(
        self: RsimScenario, group_name: str
    ) -> Optional[RecruitmentModel]:
        _init_recruitment(self)
        return self._recruitment_models.get(group_name)

    def list_recruitment_models(self: RsimScenario) -> List[str]:
        _init_recruitment(self)
        return sorted(self._recruitment_models.keys())

    def set_larval_connectivity(
        self: RsimScenario, connectivity: Optional[LarvalConnectivity]
    ) -> None:
        from pypath.core.recruitment import LarvalConnectivity

        _init_recruitment(self)
        if connectivity is not None and not isinstance(
            connectivity, LarvalConnectivity
        ):
            raise TypeError(
                "connectivity must be LarvalConnectivity or None, "
                f"got {type(connectivity).__name__}"
            )
        self._larval_connectivity = connectivity

    def apply_recruitment(
        self: RsimScenario,
        time: float,
        ssb_by_group: Dict[str, float],
        env_factors: Optional[Dict[str, float]] = None,
    ) -> Dict[str, float]:
        _init_recruitment(self)

        time_val = float(time)
        outputs: Dict[str, float] = {}
        for group in self.params.spname:
            if group not in self._recruitment_models:
                outputs[group] = 1.0
                continue
            model = self._recruitment_models[group]
            ssb = float(ssb_by_group.get(group, 0.0))
            env = 1.0 if env_factors is None else float(env_factors.get(group, 1.0))
            outputs[group] = float(
                model.get_recruitment(ssb=ssb, time=time_val, env_factor=env)
            )

        if self._larval_connectivity is not None:
            dispersed = self._larval_connectivity.disperse(outputs)
            outputs.update(dispersed)

        return outputs

    def build_recruitment_vector(
        self: RsimScenario,
        time: float,
        ssb_by_group: Dict[str, float],
        env_factors: Optional[Dict[str, float]] = None,
    ) -> np.ndarray:
        """Build (NUM_GROUPS+1)-length recruitment multiplier vector."""
        outputs = apply_recruitment(self, time, ssb_by_group, env_factors)
        vector = np.ones(self.params.NUM_GROUPS + 1, dtype=float)
        for idx, group in enumerate(self.params.spname):
            if idx >= vector.size:
                break
            vector[idx] = float(outputs.get(group, 1.0))
        return vector

    def apply_recruitment_to_forcing(
        self: RsimScenario,
        month_index: int,
        time: float,
        ssb_by_group: Dict[str, float],
        env_factors: Optional[Dict[str, float]] = None,
    ) -> None:
        """Write recruitment multipliers into scenario.forcing.ForcedRecs."""
        _init_recruitment(self)
        if (
            not hasattr(self, "forcing")
            or getattr(self.forcing, "ForcedRecs", None) is None
        ):
            raise ValueError("Scenario forcing.ForcedRecs is not available")
        if month_index < 0 or month_index >= self.forcing.ForcedRecs.shape[0]:
            raise ValueError(f"month_index out of bounds: {month_index}")

        self.forcing.ForcedRecs[month_index, :] = build_recruitment_vector(
            self,
            time=time,
            ssb_by_group=ssb_by_group,
            env_factors=env_factors,
        )

    def get_recruitment_trajectory(
        self: RsimScenario,
        group_name: str,
        ssb_timeline: Dict[float, float],
        times: np.ndarray,
    ) -> np.ndarray:
        _init_recruitment(self)
        model = self._recruitment_models.get(group_name)
        if model is None:
            raise ValueError(f"No recruitment model registered for group: {group_name}")
        return model.get_recruitment_trajectory(
            ssb_timeline=ssb_timeline, times=np.asarray(times)
        )

    def batch_recruitment_evaluation(
        self: RsimScenario,
        groups: List[str],
        ssb_matrix: np.ndarray,
        time_array: np.ndarray,
        env_matrix: Optional[np.ndarray] = None,
    ) -> Dict[str, np.ndarray]:
        _init_recruitment(self)

        ssb = np.asarray(ssb_matrix, dtype=float)
        times = np.asarray(time_array, dtype=float).reshape(-1)
        if ssb.ndim != 2:
            raise ValueError("ssb_matrix must be a 2D array")
        if ssb.shape[0] != len(groups):
            raise ValueError("ssb_matrix row count must match number of groups")
        if ssb.shape[1] != len(times):
            raise ValueError("ssb_matrix column count must match time_array length")

        if env_matrix is not None:
            env = np.asarray(env_matrix, dtype=float)
            if env.shape != ssb.shape:
                raise ValueError("env_matrix must have same shape as ssb_matrix")
        else:
            env = None

        result: Dict[str, np.ndarray] = {}
        for i, group in enumerate(groups):
            model = self._recruitment_models.get(group)
            if model is None:
                result[group] = np.ones(len(times), dtype=float)
                continue

            group_env = None if env is None else env[i, :]
            result[group] = model.get_recruitment_batch(
                ssb_array=ssb[i, :],
                time_array=times,
                env_factors=group_env,
            )
        return result

    RsimScenario._init_recruitment = _init_recruitment
    RsimScenario.set_recruitment_model = set_recruitment_model
    RsimScenario.get_recruitment_model = get_recruitment_model
    RsimScenario.list_recruitment_models = list_recruitment_models
    RsimScenario.set_larval_connectivity = set_larval_connectivity
    RsimScenario.apply_recruitment = apply_recruitment
    RsimScenario.build_recruitment_vector = build_recruitment_vector
    RsimScenario.apply_recruitment_to_forcing = apply_recruitment_to_forcing
    RsimScenario.get_recruitment_trajectory = get_recruitment_trajectory
    RsimScenario.batch_recruitment_evaluation = batch_recruitment_evaluation

Metabolism

Temperature- and size-dependent metabolic scaling utilities.

pypath.core.metabolism

Metabolic scaling models for Ecosim dynamics.

This module provides temperature- and body-size-dependent metabolic scaling utilities used to modulate production and consumption processes.

MetabolicModel dataclass

Metabolic scaling model with allometric and thermal dependence.

Parameters:

Name Type Description Default
base_metabolism float

Baseline metabolic rate at reference mass and temperature.

required
mass_exponent float

Allometric exponent for body-mass scaling.

0.75
reference_mass float

Body mass where mass-scaling multiplier equals 1.0.

1.0
temperature_dependence TemperatureDependence

Temperature model (defaults to q10=2.0 at 10°C).

None
activity_budget float

Baseline activity multiplier.

1.0
Source code in pypath/core/metabolism.py
 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
@dataclass(frozen=True)
class MetabolicModel:
    """Metabolic scaling model with allometric and thermal dependence.

    Parameters
    ----------
    base_metabolism : float
        Baseline metabolic rate at reference mass and temperature.
    mass_exponent : float
        Allometric exponent for body-mass scaling.
    reference_mass : float
        Body mass where mass-scaling multiplier equals 1.0.
    temperature_dependence : TemperatureDependence, optional
        Temperature model (defaults to q10=2.0 at 10°C).
    activity_budget : float
        Baseline activity multiplier.
    """

    base_metabolism: float
    mass_exponent: float = 0.75
    reference_mass: float = 1.0
    temperature_dependence: Optional[TemperatureDependence] = None
    activity_budget: float = 1.0

    def __post_init__(self) -> None:
        if self.base_metabolism <= 0:
            raise ValueError(f"base_metabolism must be > 0, got {self.base_metabolism}")
        if self.reference_mass <= 0:
            raise ValueError(f"reference_mass must be > 0, got {self.reference_mass}")
        if self.activity_budget <= 0:
            raise ValueError(f"activity_budget must be > 0, got {self.activity_budget}")
        if self.temperature_dependence is None:
            object.__setattr__(
                self,
                "temperature_dependence",
                TemperatureDependence(),
            )

    def compute_mass_factor(self, body_mass: float | np.ndarray) -> float | np.ndarray:
        """Compute allometric mass scaling factor."""
        mass_arr = np.asarray(body_mass, dtype=float)
        mass_safe = np.where(np.isfinite(mass_arr), np.maximum(mass_arr, 0.0), 0.0)
        ratio = np.where(
            mass_safe > 0.0,
            mass_safe / self.reference_mass,
            0.0,
        )
        factor = np.power(ratio, self.mass_exponent)
        if np.isscalar(body_mass):
            return float(factor)
        return factor

    def compute_temperature_factor(
        self, temperature: float | np.ndarray
    ) -> float | np.ndarray:
        """Compute thermal scaling factor using configured Q10 model."""
        return self.temperature_dependence.compute_q10_factor(temperature)

    def compute_metabolic_rate(
        self,
        body_mass: float,
        temperature: float,
        activity_multiplier: float = 1.0,
    ) -> float:
        """Compute metabolic rate for a single body mass and temperature."""
        if activity_multiplier <= 0:
            raise ValueError(
                f"activity_multiplier must be > 0, got {activity_multiplier}"
            )
        mass_factor = self.compute_mass_factor(body_mass)
        temp_factor = self.compute_temperature_factor(temperature)
        return float(
            self.base_metabolism
            * mass_factor
            * temp_factor
            * self.activity_budget
            * activity_multiplier
        )

    def compute_metabolic_rate_batch(
        self,
        body_mass: np.ndarray,
        temperature: np.ndarray,
        activity_multiplier: Optional[np.ndarray] = None,
    ) -> np.ndarray:
        """Compute metabolic rates for vector inputs."""
        mass_arr = np.asarray(body_mass, dtype=float).reshape(-1)
        temp_arr = np.asarray(temperature, dtype=float).reshape(-1)
        if mass_arr.size != temp_arr.size:
            raise ValueError(
                f"body_mass length ({mass_arr.size}) must equal "
                f"temperature length ({temp_arr.size})"
            )

        if activity_multiplier is None:
            activity = np.ones_like(mass_arr)
        else:
            activity = np.asarray(activity_multiplier, dtype=float).reshape(-1)
            if activity.size != mass_arr.size:
                raise ValueError(
                    f"activity_multiplier length ({activity.size}) must equal "
                    f"body_mass length ({mass_arr.size})"
                )
            if np.any(activity <= 0):
                raise ValueError("activity_multiplier values must all be > 0")

        mass_factor = np.asarray(self.compute_mass_factor(mass_arr), dtype=float)
        temp_factor = np.asarray(self.compute_temperature_factor(temp_arr), dtype=float)

        return (
            self.base_metabolism
            * mass_factor
            * temp_factor
            * self.activity_budget
            * activity
        )
compute_mass_factor
compute_mass_factor(body_mass: float | ndarray) -> float | np.ndarray

Compute allometric mass scaling factor.

Source code in pypath/core/metabolism.py
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
def compute_mass_factor(self, body_mass: float | np.ndarray) -> float | np.ndarray:
    """Compute allometric mass scaling factor."""
    mass_arr = np.asarray(body_mass, dtype=float)
    mass_safe = np.where(np.isfinite(mass_arr), np.maximum(mass_arr, 0.0), 0.0)
    ratio = np.where(
        mass_safe > 0.0,
        mass_safe / self.reference_mass,
        0.0,
    )
    factor = np.power(ratio, self.mass_exponent)
    if np.isscalar(body_mass):
        return float(factor)
    return factor
compute_metabolic_rate
compute_metabolic_rate(body_mass: float, temperature: float, activity_multiplier: float = 1.0) -> float

Compute metabolic rate for a single body mass and temperature.

Source code in pypath/core/metabolism.py
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
def compute_metabolic_rate(
    self,
    body_mass: float,
    temperature: float,
    activity_multiplier: float = 1.0,
) -> float:
    """Compute metabolic rate for a single body mass and temperature."""
    if activity_multiplier <= 0:
        raise ValueError(
            f"activity_multiplier must be > 0, got {activity_multiplier}"
        )
    mass_factor = self.compute_mass_factor(body_mass)
    temp_factor = self.compute_temperature_factor(temperature)
    return float(
        self.base_metabolism
        * mass_factor
        * temp_factor
        * self.activity_budget
        * activity_multiplier
    )
compute_metabolic_rate_batch
compute_metabolic_rate_batch(body_mass: ndarray, temperature: ndarray, activity_multiplier: Optional[ndarray] = None) -> np.ndarray

Compute metabolic rates for vector inputs.

Source code in pypath/core/metabolism.py
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
def compute_metabolic_rate_batch(
    self,
    body_mass: np.ndarray,
    temperature: np.ndarray,
    activity_multiplier: Optional[np.ndarray] = None,
) -> np.ndarray:
    """Compute metabolic rates for vector inputs."""
    mass_arr = np.asarray(body_mass, dtype=float).reshape(-1)
    temp_arr = np.asarray(temperature, dtype=float).reshape(-1)
    if mass_arr.size != temp_arr.size:
        raise ValueError(
            f"body_mass length ({mass_arr.size}) must equal "
            f"temperature length ({temp_arr.size})"
        )

    if activity_multiplier is None:
        activity = np.ones_like(mass_arr)
    else:
        activity = np.asarray(activity_multiplier, dtype=float).reshape(-1)
        if activity.size != mass_arr.size:
            raise ValueError(
                f"activity_multiplier length ({activity.size}) must equal "
                f"body_mass length ({mass_arr.size})"
            )
        if np.any(activity <= 0):
            raise ValueError("activity_multiplier values must all be > 0")

    mass_factor = np.asarray(self.compute_mass_factor(mass_arr), dtype=float)
    temp_factor = np.asarray(self.compute_temperature_factor(temp_arr), dtype=float)

    return (
        self.base_metabolism
        * mass_factor
        * temp_factor
        * self.activity_budget
        * activity
    )
compute_temperature_factor
compute_temperature_factor(temperature: float | ndarray) -> float | np.ndarray

Compute thermal scaling factor using configured Q10 model.

Source code in pypath/core/metabolism.py
110
111
112
113
114
def compute_temperature_factor(
    self, temperature: float | np.ndarray
) -> float | np.ndarray:
    """Compute thermal scaling factor using configured Q10 model."""
    return self.temperature_dependence.compute_q10_factor(temperature)

TemperatureDependence dataclass

Q10-based temperature dependence model.

Parameters:

Name Type Description Default
q10_coefficient float

Multiplicative increase in rate per +10°C.

2.0
reference_temperature float

Reference temperature where factor equals 1.0.

10.0
min_factor float

Lower clamp for computed factors.

0.01
max_factor float

Upper clamp for computed factors.

100.0
Source code in pypath/core/metabolism.py
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
@dataclass(frozen=True)
class TemperatureDependence:
    """Q10-based temperature dependence model.

    Parameters
    ----------
    q10_coefficient : float
        Multiplicative increase in rate per +10°C.
    reference_temperature : float
        Reference temperature where factor equals 1.0.
    min_factor : float, optional
        Lower clamp for computed factors.
    max_factor : float, optional
        Upper clamp for computed factors.
    """

    q10_coefficient: float = 2.0
    reference_temperature: float = 10.0
    min_factor: float = 0.01
    max_factor: float = 100.0

    def __post_init__(self) -> None:
        if self.q10_coefficient <= 0:
            raise ValueError(f"q10_coefficient must be > 0, got {self.q10_coefficient}")
        if self.min_factor <= 0:
            raise ValueError(f"min_factor must be > 0, got {self.min_factor}")
        if self.max_factor < self.min_factor:
            raise ValueError(
                f"max_factor ({self.max_factor}) must be >= min_factor ({self.min_factor})"
            )

    def compute_q10_factor(self, temperature: float | np.ndarray) -> float | np.ndarray:
        """Compute temperature scaling factor using the Q10 formulation."""
        temp_arr = np.asarray(temperature, dtype=float)
        factor = self.q10_coefficient ** (
            (temp_arr - self.reference_temperature) / 10.0
        )
        factor = np.clip(factor, self.min_factor, self.max_factor)
        if np.isscalar(temperature):
            return float(factor)
        return factor
compute_q10_factor
compute_q10_factor(temperature: float | ndarray) -> float | np.ndarray

Compute temperature scaling factor using the Q10 formulation.

Source code in pypath/core/metabolism.py
46
47
48
49
50
51
52
53
54
55
def compute_q10_factor(self, temperature: float | np.ndarray) -> float | np.ndarray:
    """Compute temperature scaling factor using the Q10 formulation."""
    temp_arr = np.asarray(temperature, dtype=float)
    factor = self.q10_coefficient ** (
        (temp_arr - self.reference_temperature) / 10.0
    )
    factor = np.clip(factor, self.min_factor, self.max_factor)
    if np.isscalar(temperature):
        return float(factor)
    return factor

apply_size_dependent_rates

apply_size_dependent_rates(base_rates: ndarray, body_mass: ndarray, mass_exponent: float, reference_mass: float = 1.0) -> np.ndarray

Apply allometric mass scaling to an array of baseline rates.

Source code in pypath/core/metabolism.py
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
def apply_size_dependent_rates(
    base_rates: np.ndarray,
    body_mass: np.ndarray,
    mass_exponent: float,
    reference_mass: float = 1.0,
) -> np.ndarray:
    """Apply allometric mass scaling to an array of baseline rates."""
    if reference_mass <= 0:
        raise ValueError(f"reference_mass must be > 0, got {reference_mass}")
    rates = np.asarray(base_rates, dtype=float).reshape(-1)
    masses = np.asarray(body_mass, dtype=float).reshape(-1)
    if rates.size != masses.size:
        raise ValueError(
            f"base_rates length ({rates.size}) must equal body_mass length ({masses.size})"
        )

    masses = np.where(np.isfinite(masses), np.maximum(masses, 0.0), 0.0)
    factors = np.power(
        np.where(masses > 0.0, masses / reference_mass, 0.0), mass_exponent
    )
    return rates * factors

compute_temperature_adjusted_metabolism

compute_temperature_adjusted_metabolism(base_metabolism: float | ndarray, temperature: float | ndarray, temperature_model: TemperatureDependence) -> float | np.ndarray

Apply thermal scaling to baseline metabolism using a temperature model.

Source code in pypath/core/metabolism.py
199
200
201
202
203
204
205
206
207
208
209
210
def compute_temperature_adjusted_metabolism(
    base_metabolism: float | np.ndarray,
    temperature: float | np.ndarray,
    temperature_model: TemperatureDependence,
) -> float | np.ndarray:
    """Apply thermal scaling to baseline metabolism using a temperature model."""
    base = np.asarray(base_metabolism, dtype=float)
    factor = np.asarray(temperature_model.compute_q10_factor(temperature), dtype=float)
    adjusted = base * factor
    if np.isscalar(base_metabolism) and np.isscalar(temperature):
        return float(adjusted)
    return adjusted

Fishing Management

Selectivity and management strategy helpers for dynamic fishing controls.

pypath.core.fishing_management

Advanced fishing management models for dynamic selectivity and effort allocation.

DynamicLogisticSelectivity dataclass

Bases: SelectivityPattern

Logistic selectivity with optional time-varying L50.

S(L) = 1 / (1 + exp(-k * (L - L50_t))).

Source code in pypath/core/fishing_management.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
@dataclass
class DynamicLogisticSelectivity(SelectivityPattern):
    """Logistic selectivity with optional time-varying L50.

    S(L) = 1 / (1 + exp(-k * (L - L50_t))).
    """

    l50: float
    slope: float
    l50_time_series: Optional[Dict[float, float]] = None

    def __post_init__(self) -> None:
        if self.slope <= 0:
            raise ValueError(f"slope must be > 0, got {self.slope}")

    def _l50_at(self, time: Optional[float]) -> float:
        if not self.l50_time_series or time is None:
            return float(self.l50)
        xs = np.array(sorted(self.l50_time_series.keys()), dtype=float)
        ys = np.array([self.l50_time_series[x] for x in xs], dtype=float)
        if xs.size == 1:
            return float(ys[0])
        return float(np.interp(float(time), xs, ys, left=ys[0], right=ys[-1]))

    def evaluate(
        self,
        lengths: np.ndarray,
        time: Optional[float] = None,
        space: Optional[str] = None,
    ) -> np.ndarray:
        _ = space
        L = np.asarray(lengths, dtype=float)
        l50_t = self._l50_at(time)
        sel = 1.0 / (1.0 + np.exp(-self.slope * (L - l50_t)))
        return np.clip(sel, 0.0, 1.0)

FishingOptimization dataclass

Simple fishing optimization utility functions.

Source code in pypath/core/fishing_management.py
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
@dataclass
class FishingOptimization:
    """Simple fishing optimization utility functions."""

    min_effort: float = 0.0
    max_effort: float = 10.0

    def __post_init__(self) -> None:
        if self.max_effort < self.min_effort:
            raise ValueError("max_effort must be >= min_effort")

    def constrain_sustainability(
        self,
        effort: np.ndarray,
        biomass: np.ndarray,
        biomass_threshold: float,
        reduction_factor: float = 0.5,
    ) -> np.ndarray:
        """Reduce effort where biomass is below threshold."""
        eff = np.asarray(effort, dtype=float).reshape(-1)
        bio = np.asarray(biomass, dtype=float).reshape(-1)
        if eff.size != bio.size:
            raise ValueError("effort and biomass must have same length")
        if reduction_factor < 0 or reduction_factor > 1:
            raise ValueError("reduction_factor must be in [0, 1]")

        out = eff.copy()
        out[bio < biomass_threshold] *= reduction_factor
        return np.clip(out, self.min_effort, self.max_effort)

    def maximize_revenue(
        self,
        catchability: np.ndarray,
        biomass: np.ndarray,
        price: np.ndarray,
        effort_budget: float,
    ) -> np.ndarray:
        """Allocate effort proportional to marginal revenue potential."""
        q = np.asarray(catchability, dtype=float).reshape(-1)
        b = np.asarray(biomass, dtype=float).reshape(-1)
        p = np.asarray(price, dtype=float).reshape(-1)
        if not (q.size == b.size == p.size):
            raise ValueError("catchability, biomass, and price must have same length")
        if effort_budget < 0:
            raise ValueError("effort_budget must be >= 0")

        scores = np.maximum(0.0, q * b * p)
        if np.all(scores == 0):
            return np.zeros_like(scores)

        alloc = effort_budget * scores / np.sum(scores)
        return np.clip(alloc, self.min_effort, self.max_effort)

    def minimize_bycatch(
        self,
        effort: np.ndarray,
        bycatch_risk: np.ndarray,
        target_reduction: float,
    ) -> np.ndarray:
        """Reduce effort in high-bycatch-risk fleets first."""
        eff = np.asarray(effort, dtype=float).reshape(-1)
        risk = np.asarray(bycatch_risk, dtype=float).reshape(-1)
        if eff.size != risk.size:
            raise ValueError("effort and bycatch_risk must have same length")
        if target_reduction < 0:
            raise ValueError("target_reduction must be >= 0")

        remaining = target_reduction
        out = eff.copy()
        order = np.argsort(-risk)  # high risk first
        for idx in order:
            if remaining <= 0:
                break
            reducible = min(out[idx], remaining)
            out[idx] -= reducible
            remaining -= reducible

        return np.clip(out, self.min_effort, self.max_effort)
constrain_sustainability
constrain_sustainability(effort: ndarray, biomass: ndarray, biomass_threshold: float, reduction_factor: float = 0.5) -> np.ndarray

Reduce effort where biomass is below threshold.

Source code in pypath/core/fishing_management.py
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
def constrain_sustainability(
    self,
    effort: np.ndarray,
    biomass: np.ndarray,
    biomass_threshold: float,
    reduction_factor: float = 0.5,
) -> np.ndarray:
    """Reduce effort where biomass is below threshold."""
    eff = np.asarray(effort, dtype=float).reshape(-1)
    bio = np.asarray(biomass, dtype=float).reshape(-1)
    if eff.size != bio.size:
        raise ValueError("effort and biomass must have same length")
    if reduction_factor < 0 or reduction_factor > 1:
        raise ValueError("reduction_factor must be in [0, 1]")

    out = eff.copy()
    out[bio < biomass_threshold] *= reduction_factor
    return np.clip(out, self.min_effort, self.max_effort)
maximize_revenue
maximize_revenue(catchability: ndarray, biomass: ndarray, price: ndarray, effort_budget: float) -> np.ndarray

Allocate effort proportional to marginal revenue potential.

Source code in pypath/core/fishing_management.py
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
def maximize_revenue(
    self,
    catchability: np.ndarray,
    biomass: np.ndarray,
    price: np.ndarray,
    effort_budget: float,
) -> np.ndarray:
    """Allocate effort proportional to marginal revenue potential."""
    q = np.asarray(catchability, dtype=float).reshape(-1)
    b = np.asarray(biomass, dtype=float).reshape(-1)
    p = np.asarray(price, dtype=float).reshape(-1)
    if not (q.size == b.size == p.size):
        raise ValueError("catchability, biomass, and price must have same length")
    if effort_budget < 0:
        raise ValueError("effort_budget must be >= 0")

    scores = np.maximum(0.0, q * b * p)
    if np.all(scores == 0):
        return np.zeros_like(scores)

    alloc = effort_budget * scores / np.sum(scores)
    return np.clip(alloc, self.min_effort, self.max_effort)
minimize_bycatch
minimize_bycatch(effort: ndarray, bycatch_risk: ndarray, target_reduction: float) -> np.ndarray

Reduce effort in high-bycatch-risk fleets first.

Source code in pypath/core/fishing_management.py
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
def minimize_bycatch(
    self,
    effort: np.ndarray,
    bycatch_risk: np.ndarray,
    target_reduction: float,
) -> np.ndarray:
    """Reduce effort in high-bycatch-risk fleets first."""
    eff = np.asarray(effort, dtype=float).reshape(-1)
    risk = np.asarray(bycatch_risk, dtype=float).reshape(-1)
    if eff.size != risk.size:
        raise ValueError("effort and bycatch_risk must have same length")
    if target_reduction < 0:
        raise ValueError("target_reduction must be >= 0")

    remaining = target_reduction
    out = eff.copy()
    order = np.argsort(-risk)  # high risk first
    for idx in order:
        if remaining <= 0:
            break
        reducible = min(out[idx], remaining)
        out[idx] -= reducible
        remaining -= reducible

    return np.clip(out, self.min_effort, self.max_effort)

SelectivityPattern

Bases: ABC

Abstract selectivity pattern interface.

Source code in pypath/core/fishing_management.py
12
13
14
15
16
17
18
19
20
21
22
23
class SelectivityPattern(ABC):
    """Abstract selectivity pattern interface."""

    @abstractmethod
    def evaluate(
        self,
        lengths: np.ndarray,
        time: Optional[float] = None,
        space: Optional[str] = None,
    ) -> np.ndarray:
        """Evaluate selectivity for provided lengths."""
        raise NotImplementedError
evaluate abstractmethod
evaluate(lengths: ndarray, time: Optional[float] = None, space: Optional[str] = None) -> np.ndarray

Evaluate selectivity for provided lengths.

Source code in pypath/core/fishing_management.py
15
16
17
18
19
20
21
22
23
@abstractmethod
def evaluate(
    self,
    lengths: np.ndarray,
    time: Optional[float] = None,
    space: Optional[str] = None,
) -> np.ndarray:
    """Evaluate selectivity for provided lengths."""
    raise NotImplementedError

SpatialSelectivity dataclass

Bases: SelectivityPattern

Spatially varying selectivity using per-zone multipliers.

Source code in pypath/core/fishing_management.py
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
@dataclass
class SpatialSelectivity(SelectivityPattern):
    """Spatially varying selectivity using per-zone multipliers."""

    base_pattern: np.ndarray
    zone_multipliers: Dict[str, float]

    def __post_init__(self) -> None:
        base = np.asarray(self.base_pattern, dtype=float).reshape(-1)
        if base.size == 0:
            raise ValueError("base_pattern cannot be empty")
        self.base_pattern = base

    def evaluate(
        self,
        lengths: np.ndarray,
        time: Optional[float] = None,
        space: Optional[str] = None,
    ) -> np.ndarray:
        _ = time
        L = np.asarray(lengths, dtype=float).reshape(-1)
        if L.size != self.base_pattern.size:
            raise ValueError(
                f"lengths size ({L.size}) must match base_pattern size ({self.base_pattern.size})"
            )
        mult = 1.0 if space is None else float(self.zone_multipliers.get(space, 1.0))
        out = self.base_pattern * mult
        return np.clip(out, 0.0, 1.0)

TimeVaryingSelectivity dataclass

Bases: SelectivityPattern

Time-varying multiplicative selectivity profile.

Source code in pypath/core/fishing_management.py
 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
@dataclass
class TimeVaryingSelectivity(SelectivityPattern):
    """Time-varying multiplicative selectivity profile."""

    base_pattern: np.ndarray
    time_multipliers: Dict[float, float]

    def __post_init__(self) -> None:
        base = np.asarray(self.base_pattern, dtype=float).reshape(-1)
        if base.size == 0:
            raise ValueError("base_pattern cannot be empty")
        if np.any(base < 0):
            raise ValueError("base_pattern values must be >= 0")
        self.base_pattern = base

    def _time_multiplier(self, time: Optional[float]) -> float:
        if time is None or not self.time_multipliers:
            return 1.0
        xs = np.array(sorted(self.time_multipliers.keys()), dtype=float)
        ys = np.array([self.time_multipliers[x] for x in xs], dtype=float)
        if xs.size == 1:
            return float(ys[0])
        return float(np.interp(float(time), xs, ys, left=ys[0], right=ys[-1]))

    def evaluate(
        self,
        lengths: np.ndarray,
        time: Optional[float] = None,
        space: Optional[str] = None,
    ) -> np.ndarray:
        _ = space
        L = np.asarray(lengths, dtype=float).reshape(-1)
        if L.size != self.base_pattern.size:
            raise ValueError(
                f"lengths size ({L.size}) must match base_pattern size ({self.base_pattern.size})"
            )
        out = self.base_pattern * self._time_multiplier(time)
        return np.clip(out, 0.0, 1.0)

Sensitivity & Uncertainty Analysis

Screening, uncertainty propagation, and risk-assessment helpers for scenario robustness analysis.

pypath.core.sensitivity_analysis

Sensitivity and uncertainty analysis utilities for Ecosim-style models.

RiskAssessment dataclass

Risk metrics for extinction/collapse under uncertainty.

Source code in pypath/core/sensitivity_analysis.py
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
@dataclass
class RiskAssessment:
    """Risk metrics for extinction/collapse under uncertainty."""

    def compute_extinction_risk(self, biomass: ArrayLike, threshold: float) -> float:
        """Probability biomass falls below extinction threshold."""
        b = np.asarray(biomass, dtype=float).reshape(-1)
        if b.size == 0:
            raise ValueError("biomass cannot be empty")
        return float(np.mean(b < threshold))

    def compute_collapse_risk(
        self,
        biomass: ArrayLike,
        baseline_biomass: float,
        collapse_fraction: float = 0.2,
    ) -> float:
        """Probability biomass falls below collapse fraction of baseline."""
        if baseline_biomass <= 0:
            raise ValueError("baseline_biomass must be > 0")
        if not (0 < collapse_fraction < 1):
            raise ValueError("collapse_fraction must be in (0, 1)")
        threshold = baseline_biomass * collapse_fraction
        return self.compute_extinction_risk(biomass, threshold)

    def worst_case_analysis(self, outputs: ArrayLike) -> Dict[str, float]:
        """Summarize worst-case, best-case, and spread."""
        y = np.asarray(outputs, dtype=float).reshape(-1)
        if y.size == 0:
            raise ValueError("outputs cannot be empty")
        return {
            "min": float(np.min(y)),
            "max": float(np.max(y)),
            "range": float(np.max(y) - np.min(y)),
            "mean": float(np.mean(y)),
        }
compute_collapse_risk
compute_collapse_risk(biomass: ArrayLike, baseline_biomass: float, collapse_fraction: float = 0.2) -> float

Probability biomass falls below collapse fraction of baseline.

Source code in pypath/core/sensitivity_analysis.py
180
181
182
183
184
185
186
187
188
189
190
191
192
def compute_collapse_risk(
    self,
    biomass: ArrayLike,
    baseline_biomass: float,
    collapse_fraction: float = 0.2,
) -> float:
    """Probability biomass falls below collapse fraction of baseline."""
    if baseline_biomass <= 0:
        raise ValueError("baseline_biomass must be > 0")
    if not (0 < collapse_fraction < 1):
        raise ValueError("collapse_fraction must be in (0, 1)")
    threshold = baseline_biomass * collapse_fraction
    return self.compute_extinction_risk(biomass, threshold)
compute_extinction_risk
compute_extinction_risk(biomass: ArrayLike, threshold: float) -> float

Probability biomass falls below extinction threshold.

Source code in pypath/core/sensitivity_analysis.py
173
174
175
176
177
178
def compute_extinction_risk(self, biomass: ArrayLike, threshold: float) -> float:
    """Probability biomass falls below extinction threshold."""
    b = np.asarray(biomass, dtype=float).reshape(-1)
    if b.size == 0:
        raise ValueError("biomass cannot be empty")
    return float(np.mean(b < threshold))
worst_case_analysis
worst_case_analysis(outputs: ArrayLike) -> Dict[str, float]

Summarize worst-case, best-case, and spread.

Source code in pypath/core/sensitivity_analysis.py
194
195
196
197
198
199
200
201
202
203
204
def worst_case_analysis(self, outputs: ArrayLike) -> Dict[str, float]:
    """Summarize worst-case, best-case, and spread."""
    y = np.asarray(outputs, dtype=float).reshape(-1)
    if y.size == 0:
        raise ValueError("outputs cannot be empty")
    return {
        "min": float(np.min(y)),
        "max": float(np.max(y)),
        "range": float(np.max(y) - np.min(y)),
        "mean": float(np.mean(y)),
    }

SensitivityAnalyzer dataclass

Compute local/global sensitivity diagnostics for model outputs.

Source code in pypath/core/sensitivity_analysis.py
 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
@dataclass
class SensitivityAnalyzer:
    """Compute local/global sensitivity diagnostics for model outputs."""

    step_fraction: float = 0.01

    def __post_init__(self) -> None:
        if self.step_fraction <= 0:
            raise ValueError("step_fraction must be > 0")

    def compute_local_sensitivity(
        self,
        model_func: ModelFunc,
        baseline_params: ArrayLike,
    ) -> np.ndarray:
        """Finite-difference local sensitivity around baseline parameters."""
        x0 = np.asarray(baseline_params, dtype=float).reshape(-1)
        base = float(model_func(x0))
        out = np.zeros_like(x0)

        for i in range(x0.size):
            step = self.step_fraction * max(abs(x0[i]), 1.0)
            xp = x0.copy()
            xm = x0.copy()
            xp[i] += step
            xm[i] -= step
            fp = float(model_func(xp))
            fm = float(model_func(xm))
            derivative = (fp - fm) / (2.0 * step)
            out[i] = derivative * (x0[i] / base) if base != 0 else derivative
        return out

    def compute_global_sensitivity(
        self,
        samples: np.ndarray,
        outputs: np.ndarray,
    ) -> np.ndarray:
        """Approximate global sensitivity via absolute Pearson correlation."""
        X = np.asarray(samples, dtype=float)
        y = np.asarray(outputs, dtype=float).reshape(-1)
        if X.ndim != 2:
            raise ValueError("samples must be 2D")
        if X.shape[0] != y.size:
            raise ValueError("samples rows must equal outputs length")

        sens = np.zeros(X.shape[1], dtype=float)
        for j in range(X.shape[1]):
            xj = X[:, j]
            if np.std(xj) == 0 or np.std(y) == 0:
                sens[j] = 0.0
            else:
                sens[j] = abs(float(np.corrcoef(xj, y)[0, 1]))
        total = np.sum(sens)
        return sens / total if total > 0 else sens

    def morris_screening(
        self,
        model_func: ModelFunc,
        bounds: np.ndarray,
        n_trajectories: int = 20,
        delta: float = 0.1,
        random_seed: int | None = None,
    ) -> Dict[str, np.ndarray]:
        """Compute Morris elementary effects summary statistics."""
        b = np.asarray(bounds, dtype=float)
        if b.ndim != 2 or b.shape[1] != 2:
            raise ValueError("bounds must have shape (n_params, 2)")
        if n_trajectories <= 0:
            raise ValueError("n_trajectories must be > 0")
        if not (0 < delta < 1):
            raise ValueError("delta must be in (0, 1)")

        rng = np.random.default_rng(random_seed)
        n_params = b.shape[0]
        effects = [[] for _ in range(n_params)]

        for _ in range(n_trajectories):
            x = rng.uniform(b[:, 0], b[:, 1])
            f0 = float(model_func(x))
            for j in range(n_params):
                span = b[j, 1] - b[j, 0]
                step = delta * span
                if step == 0:
                    effects[j].append(0.0)
                    continue
                xj = x.copy()
                xj[j] = np.clip(xj[j] + step, b[j, 0], b[j, 1])
                fj = float(model_func(xj))
                ee = (fj - f0) / step
                effects[j].append(ee)

        ee_array = np.array([np.array(v) for v in effects], dtype=float)
        mu_star = np.mean(np.abs(ee_array), axis=1)
        sigma = np.std(ee_array, axis=1, ddof=0)
        return {"mu_star": mu_star, "sigma": sigma, "effects": ee_array}
compute_global_sensitivity
compute_global_sensitivity(samples: ndarray, outputs: ndarray) -> np.ndarray

Approximate global sensitivity via absolute Pearson correlation.

Source code in pypath/core/sensitivity_analysis.py
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
def compute_global_sensitivity(
    self,
    samples: np.ndarray,
    outputs: np.ndarray,
) -> np.ndarray:
    """Approximate global sensitivity via absolute Pearson correlation."""
    X = np.asarray(samples, dtype=float)
    y = np.asarray(outputs, dtype=float).reshape(-1)
    if X.ndim != 2:
        raise ValueError("samples must be 2D")
    if X.shape[0] != y.size:
        raise ValueError("samples rows must equal outputs length")

    sens = np.zeros(X.shape[1], dtype=float)
    for j in range(X.shape[1]):
        xj = X[:, j]
        if np.std(xj) == 0 or np.std(y) == 0:
            sens[j] = 0.0
        else:
            sens[j] = abs(float(np.corrcoef(xj, y)[0, 1]))
    total = np.sum(sens)
    return sens / total if total > 0 else sens
compute_local_sensitivity
compute_local_sensitivity(model_func: ModelFunc, baseline_params: ArrayLike) -> np.ndarray

Finite-difference local sensitivity around baseline parameters.

Source code in pypath/core/sensitivity_analysis.py
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
def compute_local_sensitivity(
    self,
    model_func: ModelFunc,
    baseline_params: ArrayLike,
) -> np.ndarray:
    """Finite-difference local sensitivity around baseline parameters."""
    x0 = np.asarray(baseline_params, dtype=float).reshape(-1)
    base = float(model_func(x0))
    out = np.zeros_like(x0)

    for i in range(x0.size):
        step = self.step_fraction * max(abs(x0[i]), 1.0)
        xp = x0.copy()
        xm = x0.copy()
        xp[i] += step
        xm[i] -= step
        fp = float(model_func(xp))
        fm = float(model_func(xm))
        derivative = (fp - fm) / (2.0 * step)
        out[i] = derivative * (x0[i] / base) if base != 0 else derivative
    return out
morris_screening
morris_screening(model_func: ModelFunc, bounds: ndarray, n_trajectories: int = 20, delta: float = 0.1, random_seed: int | None = None) -> Dict[str, np.ndarray]

Compute Morris elementary effects summary statistics.

Source code in pypath/core/sensitivity_analysis.py
 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
def morris_screening(
    self,
    model_func: ModelFunc,
    bounds: np.ndarray,
    n_trajectories: int = 20,
    delta: float = 0.1,
    random_seed: int | None = None,
) -> Dict[str, np.ndarray]:
    """Compute Morris elementary effects summary statistics."""
    b = np.asarray(bounds, dtype=float)
    if b.ndim != 2 or b.shape[1] != 2:
        raise ValueError("bounds must have shape (n_params, 2)")
    if n_trajectories <= 0:
        raise ValueError("n_trajectories must be > 0")
    if not (0 < delta < 1):
        raise ValueError("delta must be in (0, 1)")

    rng = np.random.default_rng(random_seed)
    n_params = b.shape[0]
    effects = [[] for _ in range(n_params)]

    for _ in range(n_trajectories):
        x = rng.uniform(b[:, 0], b[:, 1])
        f0 = float(model_func(x))
        for j in range(n_params):
            span = b[j, 1] - b[j, 0]
            step = delta * span
            if step == 0:
                effects[j].append(0.0)
                continue
            xj = x.copy()
            xj[j] = np.clip(xj[j] + step, b[j, 0], b[j, 1])
            fj = float(model_func(xj))
            ee = (fj - f0) / step
            effects[j].append(ee)

    ee_array = np.array([np.array(v) for v in effects], dtype=float)
    mu_star = np.mean(np.abs(ee_array), axis=1)
    sigma = np.std(ee_array, axis=1, ddof=0)
    return {"mu_star": mu_star, "sigma": sigma, "effects": ee_array}

UncertaintyPropagation dataclass

Monte Carlo and sampling helpers for output uncertainty.

Source code in pypath/core/sensitivity_analysis.py
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
@dataclass
class UncertaintyPropagation:
    """Monte Carlo and sampling helpers for output uncertainty."""

    def latin_hypercube_sampling(
        self,
        bounds: np.ndarray,
        n_samples: int,
        random_seed: int | None = None,
    ) -> np.ndarray:
        """Generate Latin Hypercube samples for bounded parameters."""
        b = np.asarray(bounds, dtype=float)
        if b.ndim != 2 or b.shape[1] != 2:
            raise ValueError("bounds must have shape (n_params, 2)")
        if n_samples <= 0:
            raise ValueError("n_samples must be > 0")

        rng = np.random.default_rng(random_seed)
        n_params = b.shape[0]
        out = np.zeros((n_samples, n_params), dtype=float)

        for j in range(n_params):
            low, high = b[j]
            if high < low:
                raise ValueError("each bounds row must satisfy high >= low")
            cut = np.linspace(0.0, 1.0, n_samples + 1)
            u = rng.uniform(cut[:-1], cut[1:])
            rng.shuffle(u)
            out[:, j] = low + u * (high - low)
        return out

    def monte_carlo_ensemble(
        self,
        model_func: ModelFunc,
        samples: np.ndarray,
    ) -> np.ndarray:
        """Evaluate model outputs for sample matrix."""
        X = np.asarray(samples, dtype=float)
        if X.ndim != 2:
            raise ValueError("samples must be 2D")
        return np.array([float(model_func(row)) for row in X], dtype=float)

    def quantile_analysis(
        self,
        outputs: ArrayLike,
        quantiles: Iterable[float] = (0.05, 0.5, 0.95),
    ) -> Dict[float, float]:
        """Compute quantiles for an output distribution."""
        y = np.asarray(outputs, dtype=float).reshape(-1)
        if y.size == 0:
            raise ValueError("outputs cannot be empty")
        q = np.array(list(quantiles), dtype=float)
        if np.any((q < 0) | (q > 1)):
            raise ValueError("quantiles must be within [0, 1]")
        vals = np.quantile(y, q)
        return {float(qq): float(vv) for qq, vv in zip(q, vals)}
latin_hypercube_sampling
latin_hypercube_sampling(bounds: ndarray, n_samples: int, random_seed: int | None = None) -> np.ndarray

Generate Latin Hypercube samples for bounded parameters.

Source code in pypath/core/sensitivity_analysis.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
def latin_hypercube_sampling(
    self,
    bounds: np.ndarray,
    n_samples: int,
    random_seed: int | None = None,
) -> np.ndarray:
    """Generate Latin Hypercube samples for bounded parameters."""
    b = np.asarray(bounds, dtype=float)
    if b.ndim != 2 or b.shape[1] != 2:
        raise ValueError("bounds must have shape (n_params, 2)")
    if n_samples <= 0:
        raise ValueError("n_samples must be > 0")

    rng = np.random.default_rng(random_seed)
    n_params = b.shape[0]
    out = np.zeros((n_samples, n_params), dtype=float)

    for j in range(n_params):
        low, high = b[j]
        if high < low:
            raise ValueError("each bounds row must satisfy high >= low")
        cut = np.linspace(0.0, 1.0, n_samples + 1)
        u = rng.uniform(cut[:-1], cut[1:])
        rng.shuffle(u)
        out[:, j] = low + u * (high - low)
    return out
monte_carlo_ensemble
monte_carlo_ensemble(model_func: ModelFunc, samples: ndarray) -> np.ndarray

Evaluate model outputs for sample matrix.

Source code in pypath/core/sensitivity_analysis.py
142
143
144
145
146
147
148
149
150
151
def monte_carlo_ensemble(
    self,
    model_func: ModelFunc,
    samples: np.ndarray,
) -> np.ndarray:
    """Evaluate model outputs for sample matrix."""
    X = np.asarray(samples, dtype=float)
    if X.ndim != 2:
        raise ValueError("samples must be 2D")
    return np.array([float(model_func(row)) for row in X], dtype=float)
quantile_analysis
quantile_analysis(outputs: ArrayLike, quantiles: Iterable[float] = (0.05, 0.5, 0.95)) -> Dict[float, float]

Compute quantiles for an output distribution.

Source code in pypath/core/sensitivity_analysis.py
153
154
155
156
157
158
159
160
161
162
163
164
165
166
def quantile_analysis(
    self,
    outputs: ArrayLike,
    quantiles: Iterable[float] = (0.05, 0.5, 0.95),
) -> Dict[float, float]:
    """Compute quantiles for an output distribution."""
    y = np.asarray(outputs, dtype=float).reshape(-1)
    if y.size == 0:
        raise ValueError("outputs cannot be empty")
    q = np.array(list(quantiles), dtype=float)
    if np.any((q < 0) | (q > 1)):
        raise ValueError("quantiles must be within [0, 1]")
    vals = np.quantile(y, q)
    return {float(qq): float(vv) for qq, vv in zip(q, vals)}

Optimization

Parameter-fitting and search utilities for core Ecosim calibration.

Scenario-level management optimization is documented in Analysis API: Scenario Optimization.

pypath.core.optimization

Bayesian optimization for Ecosim parameter calibration.

This module provides tools to optimize Ecosim parameters to match observed time series data using Bayesian optimization with Gaussian Processes.

EcosimOptimizer

Bayesian optimizer for Ecosim parameters.

Calibrates Ecosim parameters to match observed biomass time series using Bayesian optimization with Gaussian Processes.

Parameters:

Name Type Description Default
model Rpath

Balanced Ecopath model

required
params RpathParams

Model parameters

required
observed_data dict

Dictionary mapping group indices to observed biomass time series Example: {1: np.array([1.0, 1.2, 1.1, ...]), 2: np.array([0.5, 0.6, ...])}

required
years range

Years to simulate

required
objective str or callable

Objective function to minimize. Options: - 'mse': Mean squared error - 'mape': Mean absolute percentage error - 'nrmse': Normalized root mean squared error - 'loglik': Negative log-likelihood - callable: Custom function(y_true, y_pred) -> float

'mse'
verbose bool

Print optimization progress

True

Attributes:

Name Type Description
model Rpath

Ecopath model

params RpathParams

Model parameters

observed_data dict

Observed time series

years range

Simulation years

objective_func callable

Objective function

verbose bool

Verbosity flag

n_calls int

Number of function evaluations performed

Source code in pypath/core/optimization.py
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
class EcosimOptimizer:
    """Bayesian optimizer for Ecosim parameters.

    Calibrates Ecosim parameters to match observed biomass time series using
    Bayesian optimization with Gaussian Processes.

    Parameters
    ----------
    model : Rpath
        Balanced Ecopath model
    params : RpathParams
        Model parameters
    observed_data : dict
        Dictionary mapping group indices to observed biomass time series
        Example: {1: np.array([1.0, 1.2, 1.1, ...]), 2: np.array([0.5, 0.6, ...])}
    years : range
        Years to simulate
    objective : str or callable
        Objective function to minimize. Options:
        - 'mse': Mean squared error
        - 'mape': Mean absolute percentage error
        - 'nrmse': Normalized root mean squared error
        - 'loglik': Negative log-likelihood
        - callable: Custom function(y_true, y_pred) -> float
    verbose : bool
        Print optimization progress

    Attributes
    ----------
    model : Rpath
        Ecopath model
    params : RpathParams
        Model parameters
    observed_data : dict
        Observed time series
    years : range
        Simulation years
    objective_func : callable
        Objective function
    verbose : bool
        Verbosity flag
    n_calls : int
        Number of function evaluations performed
    """

    def __init__(
        self,
        model: Rpath,
        params: RpathParams,
        observed_data: Dict[int, np.ndarray],
        years: range,
        objective: str = "mse",
        verbose: bool = True,
    ):
        if not HAS_SKOPT:
            raise ImportError(
                "scikit-optimize is required for Bayesian optimization. "
                "Install with: pip install scikit-optimize"
            )

        self.model = model
        self.params = params
        self.observed_data = observed_data
        self.years = years
        self.verbose = verbose
        self.n_calls = 0

        # Set objective function
        if isinstance(objective, str):
            objective_funcs = {
                "mse": mean_squared_error,
                "mape": mean_absolute_percentage_error,
                "nrmse": normalized_root_mean_squared_error,
                "loglik": log_likelihood,
            }
            if objective not in objective_funcs:
                raise ValueError(
                    f"Unknown objective: {objective}. Choose from {list(objective_funcs.keys())}"
                )
            self.objective_func = objective_funcs[objective]
        else:
            self.objective_func = objective

        # Validate observed data
        self._validate_observed_data()

    def _validate_observed_data(self) -> None:
        """Validate observed data format and dimensions."""
        n_years = len(self.years)
        for group_idx, data in self.observed_data.items():
            if len(data) != n_years:
                raise ValueError(
                    f"Observed data for group {group_idx} has {len(data)} points "
                    f"but simulation has {n_years} years"
                )
            if group_idx < 1 or group_idx > self.model.NUM_LIVING:
                raise ValueError(
                    f"Group index {group_idx} out of range [1, {self.model.NUM_LIVING}]"
                )

    def _run_simulation(self, param_dict: Dict[str, float]) -> np.ndarray:
        """Run Ecosim simulation with given parameters.

        Parameters
        ----------
        param_dict : dict
            Dictionary of parameter values

        Returns
        -------
        np.ndarray
            Simulated biomass for observed groups
        """
        # Create scenario with parameters
        scenario = rsim_scenario(self.model, self.params, years=self.years)

        # Update parameters
        for param_name, value in param_dict.items():
            self._update_scenario_parameter(scenario, param_name, value)

        # Run simulation
        try:
            result = rsim_run(scenario, method="RK4")

            # Extract biomass for observed groups
            simulated = {}
            for group_idx in self.observed_data.keys():
                # Annual biomass: shape (n_years, n_groups+1)
                # Group indices start at 1 (0 is "Outside")
                simulated[group_idx] = result.annual_Biomass[:, group_idx]

            return simulated
        except Exception as e:
            if self.verbose:
                logger.error(f"Simulation failed with parameters {param_dict}: {e}")
            # Return high penalty for failed simulations
            return None

    def _update_scenario_parameter(
        self, scenario: RsimScenario, param_name: str, value: float
    ) -> None:
        """Update a parameter in the scenario.

        Parameters
        ----------
        scenario : RsimScenario
            Simulation scenario
        param_name : str
            Parameter name (e.g., 'VV_1', 'QQ_5', 'vulnerability')
        value : float
            Parameter value
        """
        if param_name == "vulnerability":
            # Update base vulnerability for all groups
            scenario.params.VV[:] = value
        elif param_name.startswith("VV_"):
            # Update specific group vulnerability
            group_idx = int(param_name.split("_")[1])
            scenario.params.VV[group_idx] = value
        elif param_name.startswith("QQ_"):
            # Update specific link QQ
            link_idx = int(param_name.split("_")[1])
            scenario.params.QQ[link_idx] = value
        elif param_name.startswith("DD_"):
            # Update specific link DD
            link_idx = int(param_name.split("_")[1])
            scenario.params.DD[link_idx] = value
        elif param_name.startswith("PB_"):
            # Update specific group PB
            group_idx = int(param_name.split("_")[1])
            scenario.params.PBopt[group_idx] = value
        elif param_name.startswith("QB_"):
            # Update specific group QB
            group_idx = int(param_name.split("_")[1])
            scenario.params.QBopt[group_idx] = value
        else:
            raise ValueError(f"Unknown parameter: {param_name}")

    def _calculate_objective(self, simulated: Dict[int, np.ndarray]) -> float:
        """Calculate objective function value.

        Parameters
        ----------
        simulated : dict
            Simulated biomass for each group

        Returns
        -------
        float
            Objective function value (lower is better)
        """
        if simulated is None:
            return 1e10  # High penalty for failed simulations

        total_error = 0.0
        n_groups = len(self.observed_data)

        for group_idx, observed in self.observed_data.items():
            predicted = simulated[group_idx]
            error = self.objective_func(observed, predicted)
            total_error += error

        # Average across groups
        return total_error / n_groups

    def optimize(
        self,
        param_bounds: Dict[str, Tuple[float, float]],
        n_calls: int = 50,
        n_initial_points: int = 10,
        random_state: int = 42,
    ) -> OptimizationResult:
        """Run Bayesian optimization.

        Parameters
        ----------
        param_bounds : dict
            Dictionary mapping parameter names to (min, max) bounds
            Example: {'vulnerability': (1.0, 5.0), 'VV_3': (1.0, 10.0)}
        n_calls : int
            Number of function evaluations
        n_initial_points : int
            Number of random initial points before Bayesian optimization
        random_state : int
            Random seed for reproducibility

        Returns
        -------
        OptimizationResult
            Optimization results including best parameters and convergence
        """
        import time

        start_time = time.time()

        # Define search space
        dimensions = []
        param_names = []
        for name, (low, high) in param_bounds.items():
            dimensions.append(Real(low, high, name=name))
            param_names.append(name)

        # Store all evaluations
        all_params_list = []
        all_scores = []

        # Define objective function for skopt
        @use_named_args(dimensions)
        def objective(**params):
            self.n_calls += 1

            if self.verbose:
                logger.info(f"=== Iteration {self.n_calls}/{n_calls} ===")
                logger.info(
                    "Parameters: %s", {k: f"{v:.4f}" for k, v in params.items()}
                )

            # Run simulation
            simulated = self._run_simulation(params)

            # Calculate objective
            score = self._calculate_objective(simulated)

            if self.verbose:
                logger.info(f"Objective: {score:.6f}")

            # Store results
            all_params_list.append(params.copy())
            all_scores.append(score)

            return score

        # Run optimization
        if self.verbose:
            logger.info(f"Starting Bayesian optimization with {n_calls} evaluations...")
            logger.info(f"Optimizing parameters: {list(param_bounds.keys())}")
            logger.info(f"Observed groups: {list(self.observed_data.keys())}")
            logger.info(f"Simulation years: {len(self.years)}")

        self.n_calls = 0
        result = gp_minimize(
            objective,
            dimensions,
            n_calls=n_calls,
            n_initial_points=n_initial_points,
            random_state=random_state,
            verbose=False,
        )

        optimization_time = time.time() - start_time

        # Extract results
        best_params = {name: value for name, value in zip(param_names, result.x)}
        best_score = result.fun
        convergence = [np.min(all_scores[: i + 1]) for i in range(len(all_scores))]

        if self.verbose:
            logger.info(f"{'=' * 60}")
            logger.info("OPTIMIZATION COMPLETE")
            logger.info(f"{'=' * 60}")
            logger.info(f"Best score: {best_score:.6f}")
            logger.info("Best parameters:")
            for name, value in best_params.items():
                logger.info(f"  {name}: {value:.4f}")
            logger.info(f"Total evaluations: {self.n_calls}")
            logger.info(f"Optimization time: {optimization_time:.2f} seconds")
            logger.info(f"{'=' * 60}")

        return OptimizationResult(
            best_params=best_params,
            best_score=best_score,
            n_iterations=self.n_calls,
            convergence=convergence,
            all_params=all_params_list,
            all_scores=all_scores,
            optimization_time=optimization_time,
        )

    def validate(
        self,
        params: Dict[str, float],
        test_data: Optional[Dict[int, np.ndarray]] = None,
    ) -> Dict[str, Any]:
        """Validate optimized parameters on test data.

        Parameters
        ----------
        params : dict
            Parameter values to validate
        test_data : dict, optional
            Test data. If None, uses training data (self.observed_data)

        Returns
        -------
        dict
            Validation metrics for each group and overall
        """
        if test_data is None:
            test_data = self.observed_data

        # Run simulation with optimized parameters
        simulated = self._run_simulation(params)

        if simulated is None:
            return {"error": "Simulation failed"}

        # Calculate metrics for each group
        results = {}
        for group_idx, observed in test_data.items():
            predicted = simulated[group_idx]

            results[f"group_{group_idx}"] = {
                "mse": mean_squared_error(observed, predicted),
                "mape": mean_absolute_percentage_error(observed, predicted),
                "nrmse": normalized_root_mean_squared_error(observed, predicted),
                "correlation": np.corrcoef(observed, predicted)[0, 1],
            }

        # Calculate overall metrics
        all_observed = np.concatenate([test_data[idx] for idx in test_data.keys()])
        all_predicted = np.concatenate([simulated[idx] for idx in test_data.keys()])

        results["overall"] = {
            "mse": mean_squared_error(all_observed, all_predicted),
            "mape": mean_absolute_percentage_error(all_observed, all_predicted),
            "nrmse": normalized_root_mean_squared_error(all_observed, all_predicted),
            "correlation": np.corrcoef(all_observed, all_predicted)[0, 1],
        }

        return results
optimize
optimize(param_bounds: Dict[str, Tuple[float, float]], n_calls: int = 50, n_initial_points: int = 10, random_state: int = 42) -> OptimizationResult

Run Bayesian optimization.

Parameters:

Name Type Description Default
param_bounds dict

Dictionary mapping parameter names to (min, max) bounds Example: {'vulnerability': (1.0, 5.0), 'VV_3': (1.0, 10.0)}

required
n_calls int

Number of function evaluations

50
n_initial_points int

Number of random initial points before Bayesian optimization

10
random_state int

Random seed for reproducibility

42

Returns:

Type Description
OptimizationResult

Optimization results including best parameters and convergence

Source code in pypath/core/optimization.py
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
def optimize(
    self,
    param_bounds: Dict[str, Tuple[float, float]],
    n_calls: int = 50,
    n_initial_points: int = 10,
    random_state: int = 42,
) -> OptimizationResult:
    """Run Bayesian optimization.

    Parameters
    ----------
    param_bounds : dict
        Dictionary mapping parameter names to (min, max) bounds
        Example: {'vulnerability': (1.0, 5.0), 'VV_3': (1.0, 10.0)}
    n_calls : int
        Number of function evaluations
    n_initial_points : int
        Number of random initial points before Bayesian optimization
    random_state : int
        Random seed for reproducibility

    Returns
    -------
    OptimizationResult
        Optimization results including best parameters and convergence
    """
    import time

    start_time = time.time()

    # Define search space
    dimensions = []
    param_names = []
    for name, (low, high) in param_bounds.items():
        dimensions.append(Real(low, high, name=name))
        param_names.append(name)

    # Store all evaluations
    all_params_list = []
    all_scores = []

    # Define objective function for skopt
    @use_named_args(dimensions)
    def objective(**params):
        self.n_calls += 1

        if self.verbose:
            logger.info(f"=== Iteration {self.n_calls}/{n_calls} ===")
            logger.info(
                "Parameters: %s", {k: f"{v:.4f}" for k, v in params.items()}
            )

        # Run simulation
        simulated = self._run_simulation(params)

        # Calculate objective
        score = self._calculate_objective(simulated)

        if self.verbose:
            logger.info(f"Objective: {score:.6f}")

        # Store results
        all_params_list.append(params.copy())
        all_scores.append(score)

        return score

    # Run optimization
    if self.verbose:
        logger.info(f"Starting Bayesian optimization with {n_calls} evaluations...")
        logger.info(f"Optimizing parameters: {list(param_bounds.keys())}")
        logger.info(f"Observed groups: {list(self.observed_data.keys())}")
        logger.info(f"Simulation years: {len(self.years)}")

    self.n_calls = 0
    result = gp_minimize(
        objective,
        dimensions,
        n_calls=n_calls,
        n_initial_points=n_initial_points,
        random_state=random_state,
        verbose=False,
    )

    optimization_time = time.time() - start_time

    # Extract results
    best_params = {name: value for name, value in zip(param_names, result.x)}
    best_score = result.fun
    convergence = [np.min(all_scores[: i + 1]) for i in range(len(all_scores))]

    if self.verbose:
        logger.info(f"{'=' * 60}")
        logger.info("OPTIMIZATION COMPLETE")
        logger.info(f"{'=' * 60}")
        logger.info(f"Best score: {best_score:.6f}")
        logger.info("Best parameters:")
        for name, value in best_params.items():
            logger.info(f"  {name}: {value:.4f}")
        logger.info(f"Total evaluations: {self.n_calls}")
        logger.info(f"Optimization time: {optimization_time:.2f} seconds")
        logger.info(f"{'=' * 60}")

    return OptimizationResult(
        best_params=best_params,
        best_score=best_score,
        n_iterations=self.n_calls,
        convergence=convergence,
        all_params=all_params_list,
        all_scores=all_scores,
        optimization_time=optimization_time,
    )
validate
validate(params: Dict[str, float], test_data: Optional[Dict[int, ndarray]] = None) -> Dict[str, Any]

Validate optimized parameters on test data.

Parameters:

Name Type Description Default
params dict

Parameter values to validate

required
test_data dict

Test data. If None, uses training data (self.observed_data)

None

Returns:

Type Description
dict

Validation metrics for each group and overall

Source code in pypath/core/optimization.py
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
def validate(
    self,
    params: Dict[str, float],
    test_data: Optional[Dict[int, np.ndarray]] = None,
) -> Dict[str, Any]:
    """Validate optimized parameters on test data.

    Parameters
    ----------
    params : dict
        Parameter values to validate
    test_data : dict, optional
        Test data. If None, uses training data (self.observed_data)

    Returns
    -------
    dict
        Validation metrics for each group and overall
    """
    if test_data is None:
        test_data = self.observed_data

    # Run simulation with optimized parameters
    simulated = self._run_simulation(params)

    if simulated is None:
        return {"error": "Simulation failed"}

    # Calculate metrics for each group
    results = {}
    for group_idx, observed in test_data.items():
        predicted = simulated[group_idx]

        results[f"group_{group_idx}"] = {
            "mse": mean_squared_error(observed, predicted),
            "mape": mean_absolute_percentage_error(observed, predicted),
            "nrmse": normalized_root_mean_squared_error(observed, predicted),
            "correlation": np.corrcoef(observed, predicted)[0, 1],
        }

    # Calculate overall metrics
    all_observed = np.concatenate([test_data[idx] for idx in test_data.keys()])
    all_predicted = np.concatenate([simulated[idx] for idx in test_data.keys()])

    results["overall"] = {
        "mse": mean_squared_error(all_observed, all_predicted),
        "mape": mean_absolute_percentage_error(all_observed, all_predicted),
        "nrmse": normalized_root_mean_squared_error(all_observed, all_predicted),
        "correlation": np.corrcoef(all_observed, all_predicted)[0, 1],
    }

    return results

OptimizationResult dataclass

Results from Bayesian optimization.

Attributes:

Name Type Description
best_params dict

Best parameter values found

best_score float

Best objective function value (lower is better)

n_iterations int

Number of optimization iterations

convergence list

Objective function values over iterations

all_params list

All parameter combinations tried

all_scores list

All objective function values

optimization_time float

Total optimization time in seconds

Source code in pypath/core/optimization.py
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
@dataclass
class OptimizationResult:
    """Results from Bayesian optimization.

    Attributes
    ----------
    best_params : dict
        Best parameter values found
    best_score : float
        Best objective function value (lower is better)
    n_iterations : int
        Number of optimization iterations
    convergence : list
        Objective function values over iterations
    all_params : list
        All parameter combinations tried
    all_scores : list
        All objective function values
    optimization_time : float
        Total optimization time in seconds
    """

    best_params: Dict[str, float]
    best_score: float
    n_iterations: int
    convergence: List[float]
    all_params: List[Dict[str, float]]
    all_scores: List[float]
    optimization_time: float

log_likelihood

log_likelihood(y_true: ndarray, y_pred: ndarray, sigma: float = 0.1) -> float

Calculate negative log-likelihood (Gaussian).

Parameters:

Name Type Description Default
y_true ndarray

Observed values

required
y_pred ndarray

Predicted values

required
sigma float

Standard deviation of measurement error

0.1

Returns:

Type Description
float

Negative log-likelihood

Source code in pypath/core/optimization.py
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
def log_likelihood(y_true: np.ndarray, y_pred: np.ndarray, sigma: float = 0.1) -> float:
    """Calculate negative log-likelihood (Gaussian).

    Parameters
    ----------
    y_true : np.ndarray
        Observed values
    y_pred : np.ndarray
        Predicted values
    sigma : float
        Standard deviation of measurement error

    Returns
    -------
    float
        Negative log-likelihood
    """
    n = len(y_true)
    return 0.5 * n * np.log(2 * np.pi * sigma**2) + np.sum((y_true - y_pred) ** 2) / (
        2 * sigma**2
    )

mean_absolute_percentage_error

mean_absolute_percentage_error(y_true: ndarray, y_pred: ndarray) -> float

Calculate mean absolute percentage error.

Parameters:

Name Type Description Default
y_true ndarray

Observed values

required
y_pred ndarray

Predicted values

required

Returns:

Type Description
float

Mean absolute percentage error

Source code in pypath/core/optimization.py
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
def mean_absolute_percentage_error(y_true: np.ndarray, y_pred: np.ndarray) -> float:
    """Calculate mean absolute percentage error.

    Parameters
    ----------
    y_true : np.ndarray
        Observed values
    y_pred : np.ndarray
        Predicted values

    Returns
    -------
    float
        Mean absolute percentage error
    """
    # Avoid division by zero
    mask = y_true != 0
    return np.mean(np.abs((y_true[mask] - y_pred[mask]) / y_true[mask])) * 100

mean_squared_error

mean_squared_error(y_true: ndarray, y_pred: ndarray) -> float

Calculate mean squared error between observed and predicted values.

Parameters:

Name Type Description Default
y_true ndarray

Observed values

required
y_pred ndarray

Predicted values

required

Returns:

Type Description
float

Mean squared error

Source code in pypath/core/optimization.py
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
def mean_squared_error(y_true: np.ndarray, y_pred: np.ndarray) -> float:
    """Calculate mean squared error between observed and predicted values.

    Parameters
    ----------
    y_true : np.ndarray
        Observed values
    y_pred : np.ndarray
        Predicted values

    Returns
    -------
    float
        Mean squared error
    """
    return np.mean((y_true - y_pred) ** 2)

normalized_root_mean_squared_error

normalized_root_mean_squared_error(y_true: ndarray, y_pred: ndarray) -> float

Calculate normalized root mean squared error.

Parameters:

Name Type Description Default
y_true ndarray

Observed values

required
y_pred ndarray

Predicted values

required

Returns:

Type Description
float

Normalized RMSE

Source code in pypath/core/optimization.py
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
def normalized_root_mean_squared_error(y_true: np.ndarray, y_pred: np.ndarray) -> float:
    """Calculate normalized root mean squared error.

    Parameters
    ----------
    y_true : np.ndarray
        Observed values
    y_pred : np.ndarray
        Predicted values

    Returns
    -------
    float
        Normalized RMSE
    """
    rmse = np.sqrt(np.mean((y_true - y_pred) ** 2))
    y_range = np.max(y_true) - np.min(y_true)
    if y_range <= 0:
        raise ValueError(
            "Cannot compute NRMSE: y_true has zero range (all values identical)"
        )
    return rmse / y_range

plot_fit

plot_fit(optimizer: EcosimOptimizer, params: Dict[str, float], save_path: Optional[str] = None)

Plot observed vs simulated biomass time series.

Parameters:

Name Type Description Default
optimizer EcosimOptimizer

Optimizer instance with observed data

required
params dict

Parameter values to simulate

required
save_path str

Path to save figure

None
Source code in pypath/core/optimization.py
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
def plot_fit(
    optimizer: EcosimOptimizer,
    params: Dict[str, float],
    save_path: Optional[str] = None,
):
    """Plot observed vs simulated biomass time series.

    Parameters
    ----------
    optimizer : EcosimOptimizer
        Optimizer instance with observed data
    params : dict
        Parameter values to simulate
    save_path : str, optional
        Path to save figure
    """
    import matplotlib.pyplot as plt

    # Run simulation
    simulated = optimizer._run_simulation(params)

    if simulated is None:
        logger.error("Simulation failed!")
        return None

    # Create figure
    n_groups = len(optimizer.observed_data)
    n_cols = min(3, n_groups)
    n_rows = (n_groups + n_cols - 1) // n_cols

    fig, axes = plt.subplots(n_rows, n_cols, figsize=(5 * n_cols, 4 * n_rows))
    if n_groups == 1:
        axes = np.array([axes])
    axes = axes.flatten()

    # Plot each group
    years = list(optimizer.years)
    for i, (group_idx, observed) in enumerate(optimizer.observed_data.items()):
        predicted = simulated[group_idx]
        group_name = optimizer.model.Group[group_idx]

        axes[i].plot(years, observed, "o-", label="Observed", linewidth=2, markersize=6)
        axes[i].plot(
            years, predicted, "s--", label="Simulated", linewidth=2, markersize=5
        )
        axes[i].set_xlabel("Year")
        axes[i].set_ylabel("Biomass")
        axes[i].set_title(f"{group_name} (Group {group_idx})")
        axes[i].legend()
        axes[i].grid(True, alpha=0.3)

        # Add metrics
        mse = mean_squared_error(observed, predicted)
        corr = np.corrcoef(observed, predicted)[0, 1]
        axes[i].text(
            0.05,
            0.95,
            f"MSE: {mse:.4f}\nCorr: {corr:.3f}",
            transform=axes[i].transAxes,
            verticalalignment="top",
            bbox=dict(boxstyle="round", facecolor="wheat", alpha=0.5),
        )

    # Hide unused subplots
    for i in range(n_groups, len(axes)):
        axes[i].axis("off")

    plt.tight_layout()

    if save_path:
        plt.savefig(save_path, dpi=300, bbox_inches="tight")

    return fig

plot_optimization_results

plot_optimization_results(result: OptimizationResult, save_path: Optional[str] = None)

Plot optimization convergence and parameter distributions.

Parameters:

Name Type Description Default
result OptimizationResult

Optimization results

required
save_path str

Path to save figure

None
Source code in pypath/core/optimization.py
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
def plot_optimization_results(
    result: OptimizationResult, save_path: Optional[str] = None
):
    """Plot optimization convergence and parameter distributions.

    Parameters
    ----------
    result : OptimizationResult
        Optimization results
    save_path : str, optional
        Path to save figure
    """
    import matplotlib.pyplot as plt

    fig, axes = plt.subplots(1, 2, figsize=(12, 4))

    # Convergence plot
    axes[0].plot(result.convergence, "b-", linewidth=2)
    axes[0].scatter(
        range(len(result.all_scores)),
        result.all_scores,
        c=result.all_scores,
        cmap="viridis",
        alpha=0.5,
        s=30,
    )
    axes[0].set_xlabel("Iteration")
    axes[0].set_ylabel("Best Objective Value")
    axes[0].set_title("Optimization Convergence")
    axes[0].grid(True, alpha=0.3)

    # Parameter evolution
    param_names = list(result.best_params.keys())
    n_params = len(param_names)

    if n_params <= 4:
        # Show all parameters if few enough
        for i, name in enumerate(param_names):
            values = [p[name] for p in result.all_params]
            axes[1].scatter(range(len(values)), values, label=name, alpha=0.6, s=30)
        axes[1].set_xlabel("Iteration")
        axes[1].set_ylabel("Parameter Value")
        axes[1].set_title("Parameter Evolution")
        axes[1].legend()
        axes[1].grid(True, alpha=0.3)
    else:
        # Show histogram of best parameters
        best_values = list(result.best_params.values())
        axes[1].barh(param_names, best_values, color="steelblue")
        axes[1].set_xlabel("Best Parameter Value")
        axes[1].set_title("Optimized Parameters")
        axes[1].grid(True, alpha=0.3, axis="x")

    plt.tight_layout()

    if save_path:
        plt.savefig(save_path, dpi=300, bbox_inches="tight")

    return fig

Plotting

pypath.core.plotting

Plotting module for PyPath.

This module provides visualization functions for Ecopath models and Ecosim simulation results using matplotlib and optionally plotly.

Functions include: - Food web network diagrams - Biomass time series - Catch time series - Trophic level distributions - Mixed Trophic Impacts heatmaps

Based on Rpath's plotting functions.

plot_biomass

plot_biomass(output: RsimOutput, groups: Optional[List[int]] = None, relative: bool = False, title: str = 'Biomass Time Series', figsize: Tuple[int, int] = (12, 6), legend_loc: str = 'best', ax: Optional[Axes] = None) -> plt.Figure

Plot biomass time series from Ecosim simulation.

Parameters:

Name Type Description Default
output RsimOutput

Simulation results

required
groups list of int

Group indices to plot (default: all living)

None
relative bool

If True, plot relative to initial biomass

False
title str

Plot title

'Biomass Time Series'
figsize tuple

Figure size

(12, 6)
legend_loc str

Legend location

'best'
ax Axes

Matplotlib axes

None

Returns:

Type Description
Figure
Source code in pypath/core/plotting.py
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
def plot_biomass(
    output: RsimOutput,
    groups: Optional[List[int]] = None,
    relative: bool = False,
    title: str = "Biomass Time Series",
    figsize: Tuple[int, int] = (12, 6),
    legend_loc: str = "best",
    ax: Optional[plt.Axes] = None,
) -> plt.Figure:
    """Plot biomass time series from Ecosim simulation.

    Parameters
    ----------
    output : RsimOutput
        Simulation results
    groups : list of int, optional
        Group indices to plot (default: all living)
    relative : bool
        If True, plot relative to initial biomass
    title : str
        Plot title
    figsize : tuple
        Figure size
    legend_loc : str
        Legend location
    ax : Axes, optional
        Matplotlib axes

    Returns
    -------
    matplotlib.Figure
    """
    biomass = _annual_biomass(output)
    n_years, n_groups = biomass.shape

    if groups is None:
        # Plot all groups with significant biomass
        groups = [i for i in range(1, n_groups) if biomass[0, i] > 0]

    if ax is None:
        fig, ax = plt.subplots(figsize=figsize)
    else:
        fig = ax.figure

    years = np.arange(1, n_years + 1)

    for grp in groups:
        y = biomass[:, grp]
        if relative and y[0] > 0:
            y = y / y[0]
        ax.plot(years, y, label=f"Group {grp}", linewidth=1.5)

    ax.set_xlabel("Year", fontsize=11)
    ylabel = "Relative Biomass (B/B₀)" if relative else "Biomass"
    ax.set_ylabel(ylabel, fontsize=11)
    ax.set_title(title, fontsize=12)

    if relative:
        ax.axhline(y=1, color="k", linestyle="--", alpha=0.5)

    ax.legend(loc=legend_loc, fontsize=9)
    ax.grid(True, alpha=0.3)

    plt.tight_layout()
    return fig

plot_biomass_grid

plot_biomass_grid(output: RsimOutput, groups: Optional[List[int]] = None, n_cols: int = 4, relative: bool = True, figsize: Optional[Tuple[int, int]] = None) -> plt.Figure

Plot biomass as a grid of subplots.

Parameters:

Name Type Description Default
output RsimOutput

Simulation results

required
groups list of int

Group indices to plot

None
n_cols int

Number of columns in grid

4
relative bool

Plot relative to initial biomass

True
figsize tuple

Figure size

None

Returns:

Type Description
Figure
Source code in pypath/core/plotting.py
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
def plot_biomass_grid(
    output: RsimOutput,
    groups: Optional[List[int]] = None,
    n_cols: int = 4,
    relative: bool = True,
    figsize: Optional[Tuple[int, int]] = None,
) -> plt.Figure:
    """Plot biomass as a grid of subplots.

    Parameters
    ----------
    output : RsimOutput
        Simulation results
    groups : list of int, optional
        Group indices to plot
    n_cols : int
        Number of columns in grid
    relative : bool
        Plot relative to initial biomass
    figsize : tuple, optional
        Figure size

    Returns
    -------
    matplotlib.Figure
    """
    biomass = _annual_biomass(output)
    n_years, n_groups = biomass.shape

    if groups is None:
        groups = [i for i in range(1, n_groups) if biomass[0, i] > 0]

    n_plots = len(groups)
    n_rows = (n_plots + n_cols - 1) // n_cols

    if figsize is None:
        figsize = (3 * n_cols, 2.5 * n_rows)

    fig, axes = plt.subplots(n_rows, n_cols, figsize=figsize, squeeze=False)
    axes = axes.flatten()

    years = np.arange(1, n_years + 1)

    for idx, grp in enumerate(groups):
        ax = axes[idx]
        y = biomass[:, grp]

        if relative and y[0] > 0:
            y = y / y[0]
            ax.axhline(y=1, color="k", linestyle="--", alpha=0.3)

        ax.plot(years, y, color="steelblue", linewidth=1.5)
        ax.set_title(f"Group {grp}", fontsize=10)
        ax.tick_params(labelsize=8)
        ax.grid(True, alpha=0.3)

    # Hide empty subplots
    for idx in range(len(groups), len(axes)):
        axes[idx].set_visible(False)

    plt.suptitle(
        "Biomass Time Series" + (" (Relative)" if relative else ""), fontsize=12
    )
    plt.tight_layout()
    return fig

plot_biomass_interactive

plot_biomass_interactive(output: RsimOutput, groups: Optional[List[int]] = None, relative: bool = False, title: str = 'Biomass Time Series') -> Any

Create interactive biomass plot with Plotly.

Parameters:

Name Type Description Default
output RsimOutput

Simulation results

required
groups list of int

Groups to plot

None
relative bool

Plot relative to initial

False
title str

Plot title

'Biomass Time Series'

Returns:

Type Description
Figure
Source code in pypath/core/plotting.py
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
def plot_biomass_interactive(
    output: RsimOutput,
    groups: Optional[List[int]] = None,
    relative: bool = False,
    title: str = "Biomass Time Series",
) -> Any:
    """Create interactive biomass plot with Plotly.

    Parameters
    ----------
    output : RsimOutput
        Simulation results
    groups : list of int, optional
        Groups to plot
    relative : bool
        Plot relative to initial
    title : str
        Plot title

    Returns
    -------
    plotly.graph_objects.Figure
    """
    if not HAS_PLOTLY:
        raise ImportError(
            "plotly is required for interactive plots. Install with: pip install plotly"
        )

    biomass = _annual_biomass(output)
    n_years, n_groups = biomass.shape

    if groups is None:
        groups = [i for i in range(1, n_groups) if biomass[0, i] > 0]

    fig = go.Figure()

    years = np.arange(1, n_years + 1)

    for grp in groups:
        y = biomass[:, grp]
        if relative and y[0] > 0:
            y = y / y[0]

        fig.add_trace(
            go.Scatter(
                x=years,
                y=y,
                mode="lines",
                name=f"Group {grp}",
                hovertemplate="Year: %{x}<br>Biomass: %{y:.4f}<extra></extra>",
            )
        )

    ylabel = "Relative Biomass (B/B₀)" if relative else "Biomass"

    fig.update_layout(
        title=title,
        xaxis_title="Year",
        yaxis_title=ylabel,
        hovermode="x unified",
        template="plotly_white",
    )

    if relative:
        fig.add_hline(y=1, line_dash="dash", line_color="gray", opacity=0.5)

    return fig

plot_catch

plot_catch(output: RsimOutput, groups: Optional[List[int]] = None, title: str = 'Catch Time Series', figsize: Tuple[int, int] = (12, 6), stacked: bool = False, ax: Optional[Axes] = None) -> plt.Figure

Plot catch time series from Ecosim simulation.

Parameters:

Name Type Description Default
output RsimOutput

Simulation results

required
groups list of int

Group indices to plot

None
title str

Plot title

'Catch Time Series'
figsize tuple

Figure size

(12, 6)
stacked bool

If True, create stacked area plot

False
ax Axes

Matplotlib axes

None

Returns:

Type Description
Figure
Source code in pypath/core/plotting.py
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
def plot_catch(
    output: RsimOutput,
    groups: Optional[List[int]] = None,
    title: str = "Catch Time Series",
    figsize: Tuple[int, int] = (12, 6),
    stacked: bool = False,
    ax: Optional[plt.Axes] = None,
) -> plt.Figure:
    """Plot catch time series from Ecosim simulation.

    Parameters
    ----------
    output : RsimOutput
        Simulation results
    groups : list of int, optional
        Group indices to plot
    title : str
        Plot title
    figsize : tuple
        Figure size
    stacked : bool
        If True, create stacked area plot
    ax : Axes, optional
        Matplotlib axes

    Returns
    -------
    matplotlib.Figure
    """
    catch = _annual_catch(output)
    n_years, n_groups = catch.shape

    if groups is None:
        # Plot groups with any catch
        groups = [i for i in range(1, n_groups) if np.sum(catch[:, i]) > 0]

    if not groups:
        # No catch - return empty plot
        fig, ax = plt.subplots(figsize=figsize)
        ax.text(
            0.5, 0.5, "No catch data", ha="center", va="center", transform=ax.transAxes
        )
        ax.set_title(title)
        return fig

    if ax is None:
        fig, ax = plt.subplots(figsize=figsize)
    else:
        fig = ax.figure

    years = np.arange(1, n_years + 1)

    if stacked:
        catch_data = [catch[:, grp] for grp in groups]
        labels = [f"Group {grp}" for grp in groups]
        ax.stackplot(years, catch_data, labels=labels, alpha=0.7)
    else:
        for grp in groups:
            ax.plot(years, catch[:, grp], label=f"Group {grp}", linewidth=1.5)

    ax.set_xlabel("Year", fontsize=11)
    ax.set_ylabel("Catch", fontsize=11)
    ax.set_title(title, fontsize=12)
    ax.legend(loc="best", fontsize=9)
    ax.grid(True, alpha=0.3)

    plt.tight_layout()
    return fig

plot_ecosim_summary

plot_ecosim_summary(output: RsimOutput, groups: Optional[List[int]] = None, figsize: Tuple[int, int] = (14, 10)) -> plt.Figure

Create summary plot with biomass, relative biomass, and catch.

Parameters:

Name Type Description Default
output RsimOutput

Simulation results

required
groups list of int

Groups to plot

None
figsize tuple

Figure size

(14, 10)

Returns:

Type Description
Figure
Source code in pypath/core/plotting.py
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
846
847
848
849
850
851
852
def plot_ecosim_summary(
    output: RsimOutput,
    groups: Optional[List[int]] = None,
    figsize: Tuple[int, int] = (14, 10),
) -> plt.Figure:
    """Create summary plot with biomass, relative biomass, and catch.

    Parameters
    ----------
    output : RsimOutput
        Simulation results
    groups : list of int, optional
        Groups to plot
    figsize : tuple
        Figure size

    Returns
    -------
    matplotlib.Figure
    """
    fig, axes = plt.subplots(2, 2, figsize=figsize)

    plot_biomass(output, groups=groups, ax=axes[0, 0], relative=False)
    axes[0, 0].set_title("Absolute Biomass")

    plot_biomass(output, groups=groups, ax=axes[0, 1], relative=True)
    axes[0, 1].set_title("Relative Biomass (B/B₀)")

    plot_catch(output, groups=groups, ax=axes[1, 0], stacked=False)
    axes[1, 0].set_title("Catch by Group")

    plot_catch(output, groups=groups, ax=axes[1, 1], stacked=True)
    axes[1, 1].set_title("Total Catch (Stacked)")

    plt.tight_layout()
    return fig

plot_foodweb

plot_foodweb(rpath: Rpath, title: str = 'Food Web', layout: str = 'trophic', node_size_by: str = 'biomass', edge_width_by: str = 'flow', show_labels: bool = True, min_flow: float = 0.01, figsize: Tuple[int, int] = (12, 10), cmap: str = 'viridis', ax: Optional[Axes] = None) -> plt.Figure

Plot food web network diagram.

Parameters:

Name Type Description Default
rpath Rpath

Balanced Ecopath model

required
title str

Plot title

'Food Web'
layout str

Node layout: 'trophic' (y=TL), 'spring', 'circular'

'trophic'
node_size_by str

What to scale node size by: 'biomass', 'production', 'equal'

'biomass'
edge_width_by str

What to scale edge width by: 'flow', 'diet', 'equal'

'flow'
show_labels bool

Show group labels

True
min_flow float

Minimum flow to show (relative to max)

0.01
figsize tuple

Figure size

(12, 10)
cmap str

Colormap for trophic levels

'viridis'
ax Axes

Matplotlib axes to plot on

None

Returns:

Type Description
Figure

The figure object

Source code in pypath/core/plotting.py
 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
def plot_foodweb(
    rpath: Rpath,
    title: str = "Food Web",
    layout: str = "trophic",
    node_size_by: str = "biomass",
    edge_width_by: str = "flow",
    show_labels: bool = True,
    min_flow: float = 0.01,
    figsize: Tuple[int, int] = (12, 10),
    cmap: str = "viridis",
    ax: Optional[plt.Axes] = None,
) -> plt.Figure:
    """Plot food web network diagram.

    Parameters
    ----------
    rpath : Rpath
        Balanced Ecopath model
    title : str
        Plot title
    layout : str
        Node layout: 'trophic' (y=TL), 'spring', 'circular'
    node_size_by : str
        What to scale node size by: 'biomass', 'production', 'equal'
    edge_width_by : str
        What to scale edge width by: 'flow', 'diet', 'equal'
    show_labels : bool
        Show group labels
    min_flow : float
        Minimum flow to show (relative to max)
    figsize : tuple
        Figure size
    cmap : str
        Colormap for trophic levels
    ax : Axes, optional
        Matplotlib axes to plot on

    Returns
    -------
    matplotlib.Figure
        The figure object
    """
    if not HAS_NETWORKX:
        raise ImportError(
            "networkx is required for food web plots. Install with: pip install networkx"
        )

    n_living = rpath.NUM_LIVING
    n_dead = rpath.NUM_DEAD
    n_total = n_living + n_dead

    # Create directed graph
    G = nx.DiGraph()

    # Add nodes
    # Rpath arrays are 0-based over NUM_GROUPS; groups 0..n_living-1 are
    # living and n_living..n_total-1 are detritus. DC is (NUM_GROUPS + 1,
    # NUM_LIVING), so its columns are predators and its rows are prey.
    for i in range(n_total):
        G.add_node(
            i, tl=rpath.TL[i], biomass=rpath.Biomass[i], is_detritus=i >= n_living
        )

    # Add edges (from prey to predator)
    max_flow = 0
    for pred in range(n_living):
        for prey in range(n_total):
            if rpath.DC[prey, pred] > 0:
                flow = rpath.DC[prey, pred] * rpath.QB[pred] * rpath.Biomass[pred]
                max_flow = max(max_flow, flow)
                G.add_edge(prey, pred, flow=flow, diet=rpath.DC[prey, pred])

    # Filter small flows
    edges_to_remove = []
    for u, v, data in G.edges(data=True):
        if data["flow"] < min_flow * max_flow:
            edges_to_remove.append((u, v))
    G.remove_edges_from(edges_to_remove)

    # Calculate layout
    if layout == "trophic":
        # Position by trophic level (y) and spread horizontally
        pos = {}
        tl_groups = {}
        for node in G.nodes():
            tl = round(G.nodes[node]["tl"], 1)
            if tl not in tl_groups:
                tl_groups[tl] = []
            tl_groups[tl].append(node)

        for tl, nodes in tl_groups.items():
            n = len(nodes)
            for i, node in enumerate(nodes):
                x = (i - (n - 1) / 2) * 0.8
                pos[node] = (x, tl)
    elif layout == "spring":
        pos = nx.spring_layout(G, seed=42)
    elif layout == "circular":
        pos = nx.circular_layout(G)
    else:
        pos = nx.spring_layout(G, seed=42)

    # Calculate node sizes
    if node_size_by == "biomass":
        max_bio = max(rpath.Biomass[:n_total])
        node_sizes = [500 + 2000 * (rpath.Biomass[i] / max_bio) for i in G.nodes()]
    elif node_size_by == "production":
        prods = [rpath.PB[i] * rpath.Biomass[i] for i in G.nodes()]
        max_prod = max(prods) if max(prods) > 0 else 1
        node_sizes = [500 + 2000 * (p / max_prod) for p in prods]
    else:
        node_sizes = [800] * len(G.nodes())

    # Calculate edge widths
    if edge_width_by == "flow":
        edge_widths = []
        for u, v in G.edges():
            w = G.edges[u, v]["flow"] / max_flow if max_flow > 0 else 0
            edge_widths.append(0.5 + 4 * w)
    elif edge_width_by == "diet":
        edge_widths = [0.5 + 4 * G.edges[u, v]["diet"] for u, v in G.edges()]
    else:
        edge_widths = [1.5] * len(G.edges())

    # Node colors by trophic level
    trophic_levels = [G.nodes[i]["tl"] for i in G.nodes()]

    # Create figure
    if ax is None:
        fig, ax = plt.subplots(figsize=figsize)
    else:
        fig = ax.figure

    # Draw network
    nx.draw_networkx_nodes(
        G,
        pos,
        node_size=node_sizes,
        node_color=trophic_levels,
        cmap=plt.colormaps[cmap],
        ax=ax,
        alpha=0.8,
    )

    nx.draw_networkx_edges(
        G,
        pos,
        width=edge_widths,
        edge_color="gray",
        alpha=0.5,
        arrows=True,
        arrowsize=15,
        connectionstyle="arc3,rad=0.1",
        ax=ax,
    )

    if show_labels:
        names = _group_labels(rpath, n_total)
        labels = {i: names[i] for i in G.nodes()}
        nx.draw_networkx_labels(G, pos, labels, font_size=8, ax=ax)

    # Add colorbar for trophic levels
    sm = plt.cm.ScalarMappable(
        cmap=plt.colormaps[cmap],
        norm=plt.Normalize(vmin=min(trophic_levels), vmax=max(trophic_levels)),
    )
    sm.set_array([])
    cbar = plt.colorbar(sm, ax=ax, shrink=0.6)
    cbar.set_label("Trophic Level")

    ax.set_title(title, fontsize=14)
    ax.axis("off")

    plt.tight_layout()
    return fig

plot_foodweb_interactive

plot_foodweb_interactive(rpath: Rpath, title: str = 'Food Web', min_flow: float = 0.01) -> Any

Create interactive food web plot with Plotly.

Parameters:

Name Type Description Default
rpath Rpath

Balanced model

required
title str

Plot title

'Food Web'
min_flow float

Minimum flow to show

0.01

Returns:

Type Description
Figure
Source code in pypath/core/plotting.py
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
def plot_foodweb_interactive(
    rpath: Rpath,
    title: str = "Food Web",
    min_flow: float = 0.01,
) -> Any:
    """Create interactive food web plot with Plotly.

    Parameters
    ----------
    rpath : Rpath
        Balanced model
    title : str
        Plot title
    min_flow : float
        Minimum flow to show

    Returns
    -------
    plotly.graph_objects.Figure
    """
    if not HAS_PLOTLY:
        raise ImportError(
            "plotly is required for interactive plots. Install with: pip install plotly"
        )
    if not HAS_NETWORKX:
        raise ImportError(
            "networkx is required for food web plots. Install with: pip install networkx"
        )

    n_living = rpath.NUM_LIVING
    n_dead = rpath.NUM_DEAD
    n_total = n_living + n_dead

    # Build graph for layout
    G = nx.DiGraph()
    for i in range(n_total):
        G.add_node(i, tl=rpath.TL[i], biomass=rpath.Biomass[i])

    max_flow = 0
    edges = []
    for pred in range(n_living):
        for prey in range(n_total):
            if rpath.DC[prey, pred] > 0:
                flow = rpath.DC[prey, pred] * rpath.QB[pred] * rpath.Biomass[pred]
                max_flow = max(max_flow, flow)
                G.add_edge(prey, pred)
                edges.append((prey, pred, flow))

    # Layout
    pos = {}
    tl_groups = {}
    for node in G.nodes():
        tl = round(rpath.TL[node], 1)
        if tl not in tl_groups:
            tl_groups[tl] = []
        tl_groups[tl].append(node)

    for tl, nodes in tl_groups.items():
        n = len(nodes)
        for i, node in enumerate(nodes):
            x = (i - (n - 1) / 2) * 0.8
            pos[node] = (x, tl)

    # Node trace
    node_x = [pos[node][0] for node in G.nodes()]
    node_y = [pos[node][1] for node in G.nodes()]
    labels = _group_labels(rpath, n_total)
    node_text = [
        f"{labels[n]}<br>TL: {rpath.TL[n]:.2f}<br>B: {rpath.Biomass[n]:.4f}"
        for n in G.nodes()
    ]
    node_size = [
        10 + 30 * rpath.Biomass[n] / max(rpath.Biomass[:n_total]) for n in G.nodes()
    ]

    node_trace = go.Scatter(
        x=node_x,
        y=node_y,
        mode="markers+text",
        hoverinfo="text",
        text=[labels[n] for n in G.nodes()],
        hovertext=node_text,
        textposition="top center",
        marker=dict(
            size=node_size,
            color=[rpath.TL[n] for n in G.nodes()],
            colorscale="Viridis",
            colorbar=dict(title="Trophic Level"),
            line_width=2,
        ),
    )

    # Edge traces
    edge_traces = []
    for prey, pred, flow in edges:
        if flow >= min_flow * max_flow:
            x0, y0 = pos[prey]
            x1, y1 = pos[pred]
            width = 1 + 4 * flow / max_flow

            edge_traces.append(
                go.Scatter(
                    x=[x0, x1, None],
                    y=[y0, y1, None],
                    mode="lines",
                    line=dict(width=width, color="gray"),
                    hoverinfo="none",
                    showlegend=False,
                )
            )

    fig = go.Figure(data=edge_traces + [node_trace])

    fig.update_layout(
        title=title,
        showlegend=False,
        hovermode="closest",
        xaxis=dict(showgrid=False, zeroline=False, showticklabels=False),
        yaxis=dict(
            showgrid=False, zeroline=False, showticklabels=False, title="Trophic Level"
        ),
        template="plotly_white",
    )

    return fig

plot_mti_heatmap

plot_mti_heatmap(mti: ndarray, group_names: Optional[List[str]] = None, title: str = 'Mixed Trophic Impacts', figsize: Tuple[int, int] = (10, 8), cmap: str = 'RdBu_r', ax: Optional[Axes] = None) -> plt.Figure

Plot Mixed Trophic Impacts as a heatmap.

Parameters:

Name Type Description Default
mti ndarray

MTI matrix from mixed_trophic_impacts()

required
group_names list of str

Names for groups

None
title str

Plot title

'Mixed Trophic Impacts'
figsize tuple

Figure size

(10, 8)
cmap str

Colormap

'RdBu_r'
ax Axes

Matplotlib axes

None

Returns:

Type Description
Figure
Source code in pypath/core/plotting.py
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
def plot_mti_heatmap(
    mti: np.ndarray,
    group_names: Optional[List[str]] = None,
    title: str = "Mixed Trophic Impacts",
    figsize: Tuple[int, int] = (10, 8),
    cmap: str = "RdBu_r",
    ax: Optional[plt.Axes] = None,
) -> plt.Figure:
    """Plot Mixed Trophic Impacts as a heatmap.

    Parameters
    ----------
    mti : np.ndarray
        MTI matrix from mixed_trophic_impacts()
    group_names : list of str, optional
        Names for groups
    title : str
        Plot title
    figsize : tuple
        Figure size
    cmap : str
        Colormap
    ax : Axes, optional
        Matplotlib axes

    Returns
    -------
    matplotlib.Figure
    """
    n = mti.shape[0]

    if group_names is None:
        group_names = [f"G{i}" for i in range(1, n + 1)]

    if ax is None:
        fig, ax = plt.subplots(figsize=figsize)
    else:
        fig = ax.figure

    # Symmetric colormap around zero
    vmax = np.max(np.abs(mti))
    vmin = -vmax

    im = ax.imshow(mti, cmap=cmap, vmin=vmin, vmax=vmax, aspect="auto")

    # Colorbar
    cbar = plt.colorbar(im, ax=ax, shrink=0.8)
    cbar.set_label("Impact")

    # Labels
    ax.set_xticks(range(n))
    ax.set_yticks(range(n))
    ax.set_xticklabels(group_names, rotation=45, ha="right", fontsize=8)
    ax.set_yticklabels(group_names, fontsize=8)

    ax.set_xlabel("Impacted", fontsize=11)
    ax.set_ylabel("Impacting", fontsize=11)
    ax.set_title(title, fontsize=12)

    plt.tight_layout()
    return fig

plot_trophic_spectrum

plot_trophic_spectrum(rpath: Rpath, by: str = 'biomass', n_bins: int = 10, title: str = 'Trophic Spectrum', figsize: Tuple[int, int] = (10, 6), ax: Optional[Axes] = None) -> plt.Figure

Plot trophic spectrum (biomass or production by trophic level).

Parameters:

Name Type Description Default
rpath Rpath

Balanced model

required
by str

What to aggregate: 'biomass', 'production', 'consumption'

'biomass'
n_bins int

Number of trophic level bins

10
title str

Plot title

'Trophic Spectrum'
figsize tuple

Figure size

(10, 6)
ax Axes

Matplotlib axes

None

Returns:

Type Description
Figure
Source code in pypath/core/plotting.py
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
def plot_trophic_spectrum(
    rpath: Rpath,
    by: str = "biomass",
    n_bins: int = 10,
    title: str = "Trophic Spectrum",
    figsize: Tuple[int, int] = (10, 6),
    ax: Optional[plt.Axes] = None,
) -> plt.Figure:
    """Plot trophic spectrum (biomass or production by trophic level).

    Parameters
    ----------
    rpath : Rpath
        Balanced model
    by : str
        What to aggregate: 'biomass', 'production', 'consumption'
    n_bins : int
        Number of trophic level bins
    title : str
        Plot title
    figsize : tuple
        Figure size
    ax : Axes, optional
        Matplotlib axes

    Returns
    -------
    matplotlib.Figure
    """
    n_living = rpath.NUM_LIVING

    # Get values and trophic levels
    # Living groups occupy indices 0..n_living-1 of the 0-based Rpath arrays.
    tl = rpath.TL[:n_living]

    if by == "biomass":
        values = rpath.Biomass[:n_living]
        ylabel = "Biomass"
    elif by == "production":
        values = rpath.PB[:n_living] * rpath.Biomass[:n_living]
        ylabel = "Production"
    elif by == "consumption":
        values = rpath.QB[:n_living] * rpath.Biomass[:n_living]
        ylabel = "Consumption"
    else:
        raise ValueError(f"Unknown 'by' value: {by}")

    # Create bins
    tl_min, tl_max = np.floor(np.min(tl)), np.ceil(np.max(tl))
    bins = np.linspace(tl_min, tl_max, n_bins + 1)
    bin_centers = (bins[:-1] + bins[1:]) / 2

    # Aggregate
    aggregated = np.zeros(n_bins)
    for i in range(len(tl)):
        bin_idx = np.digitize(tl[i], bins) - 1
        bin_idx = min(bin_idx, n_bins - 1)
        aggregated[bin_idx] += values[i]

    if ax is None:
        fig, ax = plt.subplots(figsize=figsize)
    else:
        fig = ax.figure

    ax.bar(
        bin_centers,
        aggregated,
        width=bins[1] - bins[0],
        color="steelblue",
        edgecolor="black",
        alpha=0.7,
    )

    ax.set_xlabel("Trophic Level", fontsize=11)
    ax.set_ylabel(ylabel, fontsize=11)
    ax.set_title(title, fontsize=12)
    ax.grid(True, alpha=0.3, axis="y")

    plt.tight_layout()
    return fig

save_plots

save_plots(figures: Union[Figure, List[Figure]], filename: str, dpi: int = 150, format: str = 'png') -> None

Save matplotlib figure(s) to file.

Parameters:

Name Type Description Default
figures Figure or list of Figure

Figure(s) to save

required
filename str

Output filename (without extension for multiple figures)

required
dpi int

Resolution

150
format str

Output format ('png', 'pdf', 'svg')

'png'
Source code in pypath/core/plotting.py
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
def save_plots(
    figures: Union[plt.Figure, List[plt.Figure]],
    filename: str,
    dpi: int = 150,
    format: str = "png",
) -> None:
    """Save matplotlib figure(s) to file.

    Parameters
    ----------
    figures : Figure or list of Figure
        Figure(s) to save
    filename : str
        Output filename (without extension for multiple figures)
    dpi : int
        Resolution
    format : str
        Output format ('png', 'pdf', 'svg')
    """
    if isinstance(figures, plt.Figure):
        figures = [figures]

    if len(figures) == 1:
        figures[0].savefig(f"{filename}.{format}", dpi=dpi, bbox_inches="tight")
    else:
        for i, fig in enumerate(figures):
            fig.savefig(f"{filename}_{i + 1}.{format}", dpi=dpi, bbox_inches="tight")

Analysis & Network Indices

Mixed Trophic Impacts, network indices (connectance, omnivory), and Ecosim output summary statistics.

pypath.core.analysis

Analysis and diagnostics module for PyPath.

This module provides functions for analyzing Ecopath models and Ecosim simulation results, including: - Mixed Trophic Impacts (MTI) - Network indices (connectance, omnivory index, etc.) - Ecosim output summary statistics - Model diagnostics and validation

Based on Rpath's analysis functions.

NetworkIndices dataclass

Container for food web network indices.

Attributes:

Name Type Description
n_groups int

Number of groups

n_living int

Number of living groups

n_links int

Number of trophic links (non-zero diet entries)

connectance float

Links / (living groups)^2

linkage_density float

Links / living groups

omnivory_index float

Mean variance of prey trophic levels

system_omnivory float

Total system omnivory

mean_trophic_level float

Biomass-weighted mean trophic level

max_trophic_level float

Maximum trophic level

total_biomass float

Sum of all biomass

total_throughput float

Sum of all flows

transfer_efficiency float

Mean trophic transfer efficiency

finn_cycling_index float

Fraction of throughput recycled

Source code in pypath/core/analysis.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
239
240
241
242
243
244
@dataclass
class NetworkIndices:
    """Container for food web network indices.

    Attributes
    ----------
    n_groups : int
        Number of groups
    n_living : int
        Number of living groups
    n_links : int
        Number of trophic links (non-zero diet entries)
    connectance : float
        Links / (living groups)^2
    linkage_density : float
        Links / living groups
    omnivory_index : float
        Mean variance of prey trophic levels
    system_omnivory : float
        Total system omnivory
    mean_trophic_level : float
        Biomass-weighted mean trophic level
    max_trophic_level : float
        Maximum trophic level
    total_biomass : float
        Sum of all biomass
    total_throughput : float
        Sum of all flows
    transfer_efficiency : float
        Mean trophic transfer efficiency
    finn_cycling_index : float
        Fraction of throughput recycled
    """

    n_groups: int = 0
    n_living: int = 0
    n_links: int = 0
    connectance: float = 0.0
    linkage_density: float = 0.0
    omnivory_index: float = 0.0
    system_omnivory: float = 0.0
    mean_trophic_level: float = 0.0
    max_trophic_level: float = 0.0
    total_biomass: float = 0.0
    total_throughput: float = 0.0
    transfer_efficiency: float = 0.0
    finn_cycling_index: float = 0.0

EcosimSummary dataclass

Summary statistics for Ecosim simulation results.

Attributes:

Name Type Description
group_names list

Names of groups

years int

Number of years simulated

Biomass statistics

biomass_start : np.ndarray Initial biomass biomass_end : np.ndarray Final biomass biomass_min : np.ndarray Minimum biomass over simulation biomass_max : np.ndarray Maximum biomass over simulation biomass_mean : np.ndarray Mean biomass over simulation biomass_cv : np.ndarray Coefficient of variation of biomass biomass_change : np.ndarray Relative change (end/start - 1)

Catch statistics

total_catch : np.ndarray Total catch over simulation mean_annual_catch : np.ndarray Mean annual catch catch_cv : np.ndarray Coefficient of variation of catch

Source code in pypath/core/analysis.py
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
@dataclass
class EcosimSummary:
    """Summary statistics for Ecosim simulation results.

    Attributes
    ----------
    group_names : list
        Names of groups
    years : int
        Number of years simulated

    Biomass statistics
    ------------------
    biomass_start : np.ndarray
        Initial biomass
    biomass_end : np.ndarray
        Final biomass
    biomass_min : np.ndarray
        Minimum biomass over simulation
    biomass_max : np.ndarray
        Maximum biomass over simulation
    biomass_mean : np.ndarray
        Mean biomass over simulation
    biomass_cv : np.ndarray
        Coefficient of variation of biomass
    biomass_change : np.ndarray
        Relative change (end/start - 1)

    Catch statistics
    ----------------
    total_catch : np.ndarray
        Total catch over simulation
    mean_annual_catch : np.ndarray
        Mean annual catch
    catch_cv : np.ndarray
        Coefficient of variation of catch
    """

    group_names: List[str] = field(default_factory=list)
    years: int = 0

    # Biomass
    biomass_start: np.ndarray = field(default_factory=lambda: np.array([]))
    biomass_end: np.ndarray = field(default_factory=lambda: np.array([]))
    biomass_min: np.ndarray = field(default_factory=lambda: np.array([]))
    biomass_max: np.ndarray = field(default_factory=lambda: np.array([]))
    biomass_mean: np.ndarray = field(default_factory=lambda: np.array([]))
    biomass_cv: np.ndarray = field(default_factory=lambda: np.array([]))
    biomass_change: np.ndarray = field(default_factory=lambda: np.array([]))

    # Catch
    total_catch: np.ndarray = field(default_factory=lambda: np.array([]))
    mean_annual_catch: np.ndarray = field(default_factory=lambda: np.array([]))
    catch_cv: np.ndarray = field(default_factory=lambda: np.array([]))

mixed_trophic_impacts

mixed_trophic_impacts(rpath: Rpath) -> np.ndarray

Mixed trophic impacts, as EwE and Rpath 1.2.0 compute them.

The direct impact of group i on group j is DC[i, j] - FC[j, i]: the share of j's diet that is i (a fleet's "diet" is its landings) less the share of j's outflow that i takes (consumption, and landings plus discards for a fleet). Detritus is not a predator. The total impact is pinv(I - direct) - I, with the detritus groups' own impact set to 0 (Ulanowicz and Puccia 1990; Rpath's MTI()).

Parameters:

Name Type Description Default
rpath Rpath

Balanced Ecopath model

required

Returns:

Type Description
ndarray

MTI matrix [impacting, impacted] over every group, fleets included, in model order.

Example

mti = mixed_trophic_impacts(rpath) impact = mti[1, 2] # of the second group on the third

Source code in pypath/core/analysis.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
 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
def mixed_trophic_impacts(rpath: Rpath) -> np.ndarray:
    """Mixed trophic impacts, as EwE and Rpath 1.2.0 compute them.

    The direct impact of group i on group j is ``DC[i, j] - FC[j, i]``:
    the share of j's diet that is i (a fleet's "diet" is its landings)
    less the share of j's outflow that i takes (consumption, and landings
    plus discards for a fleet). Detritus is not a predator. The total
    impact is ``pinv(I - direct) - I``, with the detritus groups' own
    impact set to 0 (Ulanowicz and Puccia 1990; Rpath's ``MTI()``).

    Parameters
    ----------
    rpath : Rpath
        Balanced Ecopath model

    Returns
    -------
    np.ndarray
        MTI matrix [impacting, impacted] over every group, fleets
        included, in model order.

    Example
    -------
    >>> mti = mixed_trophic_impacts(rpath)
    >>> impact = mti[1, 2]  # of the second group on the third
    """
    types = np.asarray(rpath.type, dtype=float)
    n = len(types)
    living, bio = _living_and_bio_groups(rpath)
    dead = np.flatnonzero(types == 2)
    fleets = np.flatnonzero(types == 3)
    biomass = np.asarray(rpath.Biomass, dtype=float)
    qb = np.asarray(rpath.QB, dtype=float)
    landings = np.asarray(rpath.Landings, dtype=float)[:n]
    discards = np.asarray(rpath.Discards, dtype=float)[:n]

    # Diet composition [prey, predator] over every group: the living
    # predators' diets without the import row, the fleets' landings;
    # each column then sums to 1
    dcc = np.zeros((n, n))
    diet = np.nan_to_num(np.asarray(rpath.DC, dtype=float))
    for col, pred in enumerate(living[: diet.shape[1]]):
        dcc[bio, pred] = diet[bio, col]
    for k, fleet in enumerate(fleets[: landings.shape[1]]):
        dcc[:, fleet] = landings[:, k]
    with np.errstate(divide="ignore", invalid="ignore"):
        dcc = dcc / dcc.sum(axis=0)
    dcc[~np.isfinite(dcc)] = 0.0

    # Flows [prey, predator]: consumption by the living groups, landings
    # plus discards by the fleets; none to detritus
    flows = np.zeros((n, n))
    for pred in living:
        flows[bio, pred] = biomass[pred] * qb[pred] * dcc[bio, pred]
    for k, fleet in enumerate(fleets[: landings.shape[1]]):
        flows[:, fleet] = landings[:, k] + discards[:, k]
    flows[:, dead] = 0.0
    with np.errstate(divide="ignore", invalid="ignore"):
        fc = flows / flows.sum(axis=1, keepdims=True)
    fc[~np.isfinite(fc)] = 0.0

    direct = dcc - fc.T
    eye = np.eye(n)
    # MASS::ginv's tolerance, as Rpath
    mti = np.linalg.pinv(eye - direct, rcond=np.sqrt(np.finfo(float).eps)) - eye
    mti[dead, dead] = 0.0
    return mti

keystoneness_index

keystoneness_index(rpath: Rpath, mti: Optional[ndarray] = None) -> np.ndarray

Keystoneness of each living group (Libralato et al. 2006; EwE's KS1).

KS_i = log10(eps_i * (1 - p_i)), where eps_i is the overall effect of group i, the square root of the sum of its squared mixed trophic impacts on the other living groups (its impact on itself, on detritus and on fleets left out), and p_i is its share of the total biomass of the living groups. A high value marks a group whose effect is large for its biomass. The paper's logarithm base was not checked; the base changes the scale only, not the ranking or the sign.

Parameters:

Name Type Description Default
rpath Rpath

Balanced Ecopath model

required
mti ndarray

Pre-computed MTI matrix (from :func:mixed_trophic_impacts). If None, it is calculated.

None

Returns:

Type Description
ndarray

One value per group, in model order (the order of the MTI matrix): NaN for detritus and fleets, and for a living group with no overall effect (its logarithm is undefined).

References

Valls, A., Coll, M., & Christensen, V. (2015). Keystone species: toward an operational concept for marine biodiversity conservation. Ecological Monographs, 85(1), 29-47. https://doi.org/10.1890/14-0306.1

Libralato, S., Christensen, V., & Pauly, D. (2006). A method for identifying keystone species in food web models. Ecological Modelling, 195(3-4), 153-171. https://doi.org/10.1016/j.ecolmodel.2005.11.029

Source code in pypath/core/analysis.py
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
def keystoneness_index(rpath: Rpath, mti: Optional[np.ndarray] = None) -> np.ndarray:
    """Keystoneness of each living group (Libralato et al. 2006; EwE's KS1).

    ``KS_i = log10(eps_i * (1 - p_i))``, where ``eps_i`` is the overall
    effect of group i, the square root of the sum of its squared mixed
    trophic impacts on the other living groups (its impact on itself, on
    detritus and on fleets left out), and ``p_i`` is its share of the total
    biomass of the living groups. A high value marks a group whose effect
    is large for its biomass. The paper's logarithm base was not checked;
    the base changes the scale only, not the ranking or the sign.

    Parameters
    ----------
    rpath : Rpath
        Balanced Ecopath model
    mti : np.ndarray, optional
        Pre-computed MTI matrix (from :func:`mixed_trophic_impacts`). If
        None, it is calculated.

    Returns
    -------
    np.ndarray
        One value per group, in model order (the order of the MTI matrix):
        NaN for detritus and fleets, and for a living group with no
        overall effect (its logarithm is undefined).

    References
    ----------
    Valls, A., Coll, M., & Christensen, V. (2015). Keystone species: toward
    an operational concept for marine biodiversity conservation. Ecological
    Monographs, 85(1), 29-47. https://doi.org/10.1890/14-0306.1

    Libralato, S., Christensen, V., & Pauly, D. (2006). A method for
    identifying keystone species in food web models. Ecological
    Modelling, 195(3-4), 153-171. https://doi.org/10.1016/j.ecolmodel.2005.11.029
    """
    if mti is None:
        mti = mixed_trophic_impacts(rpath)

    mti = np.asarray(mti, dtype=float)
    n_groups = mti.shape[0]
    types = np.asarray(rpath.type, dtype=float)[:n_groups]
    living = types < 2
    impacted = living  # the other living groups (Valls et al. 2015, eq. 1)
    biomass = np.where(living, np.asarray(rpath.Biomass, dtype=float)[:n_groups], 0)
    total = biomass.sum()

    keystoneness = np.full(n_groups, np.nan)
    for i in np.flatnonzero(living):
        others = impacted.copy()
        others[i] = False
        eps = np.sqrt(np.sum(mti[i, others] ** 2))
        p = biomass[i] / total if total > 0 else 0.0
        value = eps * (1.0 - p)
        if value > 0:
            keystoneness[i] = np.log10(value)
    return keystoneness

calculate_network_indices

calculate_network_indices(rpath: Rpath) -> NetworkIndices

Calculate food web network indices.

Parameters:

Name Type Description Default
rpath Rpath

Balanced Ecopath model

required

Returns:

Type Description
NetworkIndices

Container with all calculated indices

Source code in pypath/core/analysis.py
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
def calculate_network_indices(rpath: Rpath) -> NetworkIndices:
    """Calculate food web network indices.

    Parameters
    ----------
    rpath : Rpath
        Balanced Ecopath model

    Returns
    -------
    NetworkIndices
        Container with all calculated indices
    """
    # Living and detritus groups by type; DC's columns are the living groups
    living, bio = _living_and_bio_groups(rpath)
    n_living = len(living)
    n_total = len(bio)

    # Count trophic links
    n_links = 0
    for pred in range(n_living):
        for prey in bio:
            if rpath.DC[prey, pred] > 0:
                n_links += 1

    # Connectance (living groups only)
    connectance = n_links / (n_living**2) if n_living > 0 else 0

    # Linkage density
    linkage_density = n_links / n_living if n_living > 0 else 0

    # Omnivory index: variance of prey trophic levels per consumer
    omnivory_sum = 0.0
    n_consumers = 0

    for pred in range(n_living):
        prey_tls = []
        prey_fracs = []

        for prey in bio:
            if rpath.DC[prey, pred] > 0:
                prey_tls.append(rpath.TL[prey])
                prey_fracs.append(rpath.DC[prey, pred])

        if len(prey_tls) > 1:
            # Weighted mean TL
            mean_tl = np.average(prey_tls, weights=prey_fracs)
            # Weighted variance
            var_tl = np.average((np.array(prey_tls) - mean_tl) ** 2, weights=prey_fracs)
            omnivory_sum += var_tl
            n_consumers += 1

    omnivory_index = omnivory_sum / n_consumers if n_consumers > 0 else 0

    # System omnivory: weighted by consumption
    system_omni = 0.0
    total_consump = 0.0

    for pred, group in enumerate(living):
        if rpath.QB[group] > 0:
            consump = rpath.QB[group] * rpath.Biomass[group]
            total_consump += consump

            prey_tls = []
            prey_fracs = []
            for prey in bio:
                if rpath.DC[prey, pred] > 0:
                    prey_tls.append(rpath.TL[prey])
                    prey_fracs.append(rpath.DC[prey, pred])

            if len(prey_tls) > 1:
                mean_tl = np.average(prey_tls, weights=prey_fracs)
                var_tl = np.average(
                    (np.array(prey_tls) - mean_tl) ** 2, weights=prey_fracs
                )
                system_omni += var_tl * consump

    system_omnivory = system_omni / total_consump if total_consump > 0 else 0

    # Mean and max trophic level
    biomass = rpath.Biomass[living]
    tl = rpath.TL[living]

    mean_trophic_level = np.average(tl, weights=biomass) if np.sum(biomass) > 0 else 0
    max_trophic_level = np.max(tl) if len(tl) > 0 else 0

    # Total biomass and throughput
    total_biomass = np.sum(rpath.Biomass[bio])

    # Throughput: sum of consumption + respiration + flow to detritus
    total_throughput = 0.0
    for grp in living:
        if rpath.QB[grp] > 0:
            total_throughput += rpath.QB[grp] * rpath.Biomass[grp]
        total_throughput += rpath.PB[grp] * rpath.Biomass[grp]

    # Transfer efficiency (between adjacent trophic levels)
    from pypath.core.indicators import finn_cycling_index as _finn_cycling_index
    from pypath.core.indicators import transfer_efficiency as _transfer_efficiency

    try:
        _te_array = _transfer_efficiency(rpath)
        transfer_efficiency = (
            float(np.mean(_te_array[_te_array > 0])) if np.any(_te_array > 0) else 0.0
        )
    except (AttributeError, TypeError, IndexError, ValueError) as e:
        # pypath.core.indicators still assumes 1-indexed Rpath arrays
        logger.warning("transfer_efficiency unavailable: %s", e)
        transfer_efficiency = 0.0

    # Finn Cycling Index
    try:
        finn_cycling_index = _finn_cycling_index(rpath)
    except (AttributeError, TypeError, IndexError, ValueError) as e:
        # pypath.core.indicators still assumes 1-indexed Rpath arrays
        logger.warning("finn_cycling_index unavailable: %s", e)
        finn_cycling_index = 0.0

    return NetworkIndices(
        n_groups=n_total,
        n_living=n_living,
        n_links=n_links,
        connectance=connectance,
        linkage_density=linkage_density,
        omnivory_index=omnivory_index,
        system_omnivory=system_omnivory,
        mean_trophic_level=mean_trophic_level,
        max_trophic_level=max_trophic_level,
        total_biomass=total_biomass,
        total_throughput=total_throughput,
        transfer_efficiency=transfer_efficiency,
        finn_cycling_index=finn_cycling_index,
    )

summarize_ecosim_output

summarize_ecosim_output(output: RsimOutput, scenario: Optional[RsimScenario] = None) -> EcosimSummary

Calculate summary statistics for Ecosim output.

Parameters:

Name Type Description Default
output RsimOutput

Simulation results

required
scenario RsimScenario

Original scenario (for group names)

None

Returns:

Type Description
EcosimSummary

Summary statistics

Source code in pypath/core/analysis.py
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
def summarize_ecosim_output(
    output: RsimOutput, scenario: Optional[RsimScenario] = None
) -> EcosimSummary:
    """Calculate summary statistics for Ecosim output.

    Parameters
    ----------
    output : RsimOutput
        Simulation results
    scenario : RsimScenario, optional
        Original scenario (for group names)

    Returns
    -------
    EcosimSummary
        Summary statistics
    """
    biomass = _annual_biomass(output)
    catch = _annual_catch(output)

    n_years, n_groups = biomass.shape

    # Get group names
    if scenario is not None:
        group_names = scenario.params.spname[1:n_groups]
    else:
        group_names = [f"Group_{i}" for i in range(1, n_groups)]

    # Biomass statistics
    biomass_start = biomass[0, :]
    biomass_end = biomass[-1, :]
    biomass_min = np.min(biomass, axis=0)
    biomass_max = np.max(biomass, axis=0)
    biomass_mean = np.mean(biomass, axis=0)
    biomass_std = np.std(biomass, axis=0)

    # Coefficient of variation — safe division to avoid RuntimeWarning on zeros
    biomass_cv = np.divide(
        biomass_std,
        biomass_mean,
        out=np.zeros_like(biomass_std),
        where=biomass_mean > 0,
    )

    # Relative change — safe division
    biomass_change = np.divide(
        biomass_end,
        biomass_start,
        out=np.zeros_like(biomass_end),
        where=biomass_start > 0,
    )
    biomass_change = np.where(biomass_start > 0, biomass_change - 1, 0)

    # Catch statistics
    total_catch = np.sum(catch, axis=0)
    mean_annual_catch = np.mean(catch, axis=0)
    catch_std = np.std(catch, axis=0)
    catch_cv = np.divide(
        catch_std,
        mean_annual_catch,
        out=np.zeros_like(catch_std),
        where=mean_annual_catch > 0,
    )

    return EcosimSummary(
        group_names=list(group_names),
        years=n_years,
        biomass_start=biomass_start,
        biomass_end=biomass_end,
        biomass_min=biomass_min,
        biomass_max=biomass_max,
        biomass_mean=biomass_mean,
        biomass_cv=biomass_cv,
        biomass_change=biomass_change,
        total_catch=total_catch,
        mean_annual_catch=mean_annual_catch,
        catch_cv=catch_cv,
    )

compare_scenarios

compare_scenarios(outputs: List[RsimOutput], names: List[str], groups: Optional[List[int]] = None) -> pd.DataFrame

Compare multiple Ecosim scenarios.

Parameters:

Name Type Description Default
outputs list of RsimOutput

Simulation results to compare

required
names list of str

Names for each scenario

required
groups list of int

Group indices to compare (default: all living groups)

None

Returns:

Type Description
DataFrame

Comparison table with biomass changes per scenario

Source code in pypath/core/analysis.py
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
def compare_scenarios(
    outputs: List[RsimOutput], names: List[str], groups: Optional[List[int]] = None
) -> pd.DataFrame:
    """Compare multiple Ecosim scenarios.

    Parameters
    ----------
    outputs : list of RsimOutput
        Simulation results to compare
    names : list of str
        Names for each scenario
    groups : list of int, optional
        Group indices to compare (default: all living groups)

    Returns
    -------
    pd.DataFrame
        Comparison table with biomass changes per scenario
    """
    if len(outputs) != len(names):
        raise ValueError("Number of outputs must match number of names")

    n_groups = _annual_biomass(outputs[0]).shape[1]

    if groups is None:
        groups = list(range(1, n_groups))

    # Build comparison DataFrame
    data = {"Group": [f"Group_{g}" for g in groups]}

    for output, name in zip(outputs, names):
        annual = _annual_biomass(output)
        start = annual[0, groups]
        end = annual[-1, groups]
        change = np.where(start > 0, (end / start - 1) * 100, 0)
        data[f"{name}_pct_change"] = change
        data[f"{name}_final_bio"] = end

    return pd.DataFrame(data)

check_ecopath_balance

check_ecopath_balance(rpath: Rpath, tolerance: float = 0.01, allow_partial_diet: bool = False) -> Dict[str, Any]

Check Ecopath model balance.

Verifies that the model satisfies mass-balance constraints: - EE <= 1 for all groups - Consumption = Production + Respiration + Unassimilated for consumers, with a respiration of zero or more - Diet compositions sum to 1

Parameters:

Name Type Description Default
rpath Rpath

Balanced model to check

required
tolerance float

Acceptable deviation from balance

0.01
allow_partial_diet bool

If True, allow consumer diet columns to sum below 1.0 and treat the remainder as unresolved/other food instead of a hard issue.

False

Returns:

Type Description
dict

Diagnostics including: - is_balanced: bool - ee_issues: list of groups with EE > 1 - diet_issues: list of groups with diet sum != 1 - balance_issues: list of consumers with P/Q outside 0 to 1 - respiration_issues: list of consumers with a negative respiration, Q/B x (1 - Unassim) - (1 - producer share) x P/B per unit biomass. Like balance_issues, they do not change is_balanced. - messages: list of diagnostic messages

Source code in pypath/core/analysis.py
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
def check_ecopath_balance(
    rpath: Rpath, tolerance: float = 0.01, allow_partial_diet: bool = False
) -> Dict[str, Any]:
    """Check Ecopath model balance.

    Verifies that the model satisfies mass-balance constraints:
    - EE <= 1 for all groups
    - Consumption = Production + Respiration + Unassimilated for consumers,
      with a respiration of zero or more
    - Diet compositions sum to 1

    Parameters
    ----------
    rpath : Rpath
        Balanced model to check
    tolerance : float
        Acceptable deviation from balance
    allow_partial_diet : bool
        If True, allow consumer diet columns to sum below 1.0 and treat
        the remainder as unresolved/other food instead of a hard issue.

    Returns
    -------
    dict
        Diagnostics including:
        - is_balanced: bool
        - ee_issues: list of groups with EE > 1
        - diet_issues: list of groups with diet sum != 1
        - balance_issues: list of consumers with P/Q outside 0 to 1
        - respiration_issues: list of consumers with a negative respiration,
          Q/B x (1 - Unassim) - (1 - producer share) x P/B per unit biomass.
          Like balance_issues, they do not change is_balanced.
        - messages: list of diagnostic messages
    """
    results = {
        "is_balanced": True,
        "ee_issues": [],
        "diet_issues": [],
        "diet_warnings": [],
        "balance_issues": [],
        "respiration_issues": [],
        "messages": [],
    }

    def _name(i: int) -> str:
        try:
            return str(rpath.Group[i])
        except (AttributeError, IndexError, TypeError):
            return f"Group {i}"

    # Living groups by type, in model order; DC's columns follow them
    living = _living_and_bio_groups(rpath)[0]

    # Check EE (Rpath arrays are 0-indexed)
    for i in living:
        if rpath.EE[i] > 1.0 + tolerance:
            results["ee_issues"].append(i)
            results["is_balanced"] = False
            results["messages"].append(f"{_name(i)}: EE = {rpath.EE[i]:.4f} > 1")

    # Check diet sums (all prey rows incl. import for each living predator)
    for col, pred in enumerate(living):
        if rpath.QB[pred] > 0:  # Is a consumer
            diet_sum = np.sum(rpath.DC[:, col])
            if abs(diet_sum - 1.0) > tolerance:
                if allow_partial_diet and 0 <= diet_sum <= 1.0 + tolerance:
                    results["diet_warnings"].append(pred)
                    results["messages"].append(
                        f"{_name(pred)}: Diet sum = {diet_sum:.4f} < 1 (partial diet allowed)"
                    )
                else:
                    results["diet_issues"].append(pred)
                    results["is_balanced"] = False
                    results["messages"].append(
                        f"{_name(pred)}: Diet sum = {diet_sum:.4f} != 1"
                    )

    # Check production/consumption balance
    unassim = np.nan_to_num(np.asarray(rpath.Unassim, dtype=float))
    producer_share = np.clip(np.asarray(rpath.type, dtype=float), 0.0, 1.0)
    for i in living:
        if rpath.QB[i] > 0:
            _consumption = rpath.QB[i] * rpath.Biomass[i]
            _production = rpath.PB[i] * rpath.Biomass[i]

            # GE = P/Q should be reasonable (0 < GE < 1)
            ge = rpath.PB[i] / rpath.QB[i] if rpath.QB[i] > 0 else 0
            if ge > 1.0 + tolerance or ge < 0:
                results["balance_issues"].append(i)
                results["messages"].append(f"{_name(i)}: GE = {ge:.4f} (should be 0-1)")

            # Respiration is what is left of the assimilated food after the
            # production it pays for. A mixotroph's producer share of the
            # production needs no food.
            respiration = (
                rpath.QB[i] * (1.0 - unassim[i])
                - (1.0 - producer_share[i]) * rpath.PB[i]
            )
            if respiration < -tolerance:
                results["respiration_issues"].append(i)
                results["messages"].append(
                    f"{_name(i)}: respiration = {respiration:.4f} per unit "
                    "biomass is negative: production exceeds assimilated food"
                )

    if not results["messages"]:
        results["messages"].append("Model is properly balanced")

    return results

check_ecosim_stability

check_ecosim_stability(scenario: RsimScenario, burn_years: int = 10) -> Dict[str, Any]

Check Ecosim scenario stability.

Runs a short burn-in simulation to verify the model reaches equilibrium.

Parameters:

Name Type Description Default
scenario RsimScenario

Scenario to check

required
burn_years int

Years to run for stability check

10

Returns:

Type Description
dict

Stability diagnostics including: - is_stable: bool - crashed_groups: list of groups that crashed - unstable_groups: list of groups with > 50% change - messages: list of diagnostic messages

Source code in pypath/core/analysis.py
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
def check_ecosim_stability(
    scenario: RsimScenario, burn_years: int = 10
) -> Dict[str, Any]:
    """Check Ecosim scenario stability.

    Runs a short burn-in simulation to verify the model
    reaches equilibrium.

    Parameters
    ----------
    scenario : RsimScenario
        Scenario to check
    burn_years : int
        Years to run for stability check

    Returns
    -------
    dict
        Stability diagnostics including:
        - is_stable: bool
        - crashed_groups: list of groups that crashed
        - unstable_groups: list of groups with > 50% change
        - messages: list of diagnostic messages
    """
    # Run short simulation
    # Create a modified scenario for burn-in
    import copy

    from pypath.core.ecosim import rsim_run

    burn_scenario = copy.deepcopy(scenario)

    # Run simulation
    output = rsim_run(burn_scenario, method="RK4")

    results = {
        "is_stable": True,
        "crashed_groups": [],
        "unstable_groups": [],
        "messages": [],
    }

    biomass = _annual_biomass(output)
    n_groups = biomass.shape[1]

    for i in range(1, n_groups):
        start_bio = biomass[0, i]
        end_bio = biomass[-1, i]

        if start_bio > 0:
            # Check for crash
            if end_bio < 1e-6:
                results["crashed_groups"].append(i)
                results["is_stable"] = False
                results["messages"].append(f"Group {i}: Crashed to near zero")

            # Check for instability (> 50% change)
            change = abs(end_bio / start_bio - 1)
            if change > 0.5:
                results["unstable_groups"].append(i)
                results["messages"].append(
                    f"Group {i}: {change * 100:.1f}% change during burn-in"
                )

    if not results["messages"]:
        results["messages"].append("Model is stable at equilibrium")

    return results

export_ecopath_to_dataframe

export_ecopath_to_dataframe(rpath: Rpath) -> Dict[str, pd.DataFrame]

Export Ecopath model to DataFrames.

Parameters:

Name Type Description Default
rpath Rpath

Balanced model

required

Returns:

Type Description
dict

Dictionary of DataFrames: - 'groups': Group parameters - 'diet': Diet composition matrix - 'flows': Flow matrix

Source code in pypath/core/analysis.py
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
def export_ecopath_to_dataframe(rpath: Rpath) -> Dict[str, pd.DataFrame]:
    """Export Ecopath model to DataFrames.

    Parameters
    ----------
    rpath : Rpath
        Balanced model

    Returns
    -------
    dict
        Dictionary of DataFrames:
        - 'groups': Group parameters
        - 'diet': Diet composition matrix
        - 'flows': Flow matrix
    """
    # Living and detritus groups by type, in model order
    living, bio = _living_and_bio_groups(rpath)
    types = np.asarray(rpath.type, dtype=float)

    # Groups DataFrame
    names = [str(g) for g in rpath.Group[bio]]
    living_names = [str(g) for g in rpath.Group[living]]
    groups_data = {
        "Group": names,
        "Type": ["Living" if t < 2 else "Detritus" for t in types[bio]],
        "TL": rpath.TL[bio],
        "Biomass": rpath.Biomass[bio],
        "PB": rpath.PB[bio],
        "QB": rpath.QB[bio],
        "EE": rpath.EE[bio],
    }
    groups_df = pd.DataFrame(groups_data)

    # Diet matrix (rows = prey, columns = living predators)
    diet_df = pd.DataFrame(
        rpath.DC[bio, : len(living)],
        index=names,
        columns=living_names,
    )

    # Simplified flows
    flows_data = []
    for col, pred in enumerate(living):
        for row, prey in enumerate(bio):
            if rpath.DC[prey, col] > 0:
                flow = rpath.DC[prey, col] * rpath.QB[pred] * rpath.Biomass[pred]
                flows_data.append(
                    {
                        "From": names[row],
                        "To": living_names[col],
                        "Diet_Fraction": rpath.DC[prey, col],
                        "Flow": flow,
                    }
                )

    flows_df = pd.DataFrame(flows_data)

    return {"groups": groups_df, "diet": diet_df, "flows": flows_df}

export_ecosim_to_dataframe

export_ecosim_to_dataframe(output: RsimOutput, scenario: Optional[RsimScenario] = None) -> Dict[str, pd.DataFrame]

Export Ecosim results to DataFrames.

Parameters:

Name Type Description Default
output RsimOutput

Simulation results

required
scenario RsimScenario

Original scenario for metadata

None

Returns:

Type Description
dict

Dictionary of DataFrames: - 'biomass_annual': Annual biomass - 'catch_annual': Annual catch - 'biomass_monthly': Monthly biomass (if available)

Source code in pypath/core/analysis.py
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
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
def export_ecosim_to_dataframe(
    output: RsimOutput, scenario: Optional[RsimScenario] = None
) -> Dict[str, pd.DataFrame]:
    """Export Ecosim results to DataFrames.

    Parameters
    ----------
    output : RsimOutput
        Simulation results
    scenario : RsimScenario, optional
        Original scenario for metadata

    Returns
    -------
    dict
        Dictionary of DataFrames:
        - 'biomass_annual': Annual biomass
        - 'catch_annual': Annual catch
        - 'biomass_monthly': Monthly biomass (if available)
    """
    annual_biomass = _annual_biomass(output)
    annual_catch = _annual_catch(output)
    n_years, n_groups = annual_biomass.shape

    # Get group names
    if scenario is not None:
        names = scenario.params.spname[1:n_groups]
    else:
        names = [f"Group_{i}" for i in range(1, n_groups)]

    # Annual biomass
    biomass_df = pd.DataFrame(
        annual_biomass[:, 1:], columns=names, index=range(1, n_years + 1)
    )
    biomass_df.index.name = "Year"

    # Annual catch
    catch_df = pd.DataFrame(
        annual_catch[:, 1:], columns=names, index=range(1, n_years + 1)
    )
    catch_df.index.name = "Year"

    results = {"biomass_annual": biomass_df, "catch_annual": catch_df}

    # Monthly data if available
    if hasattr(output, "out_Biomass") and output.out_Biomass is not None:
        n_months = output.out_Biomass.shape[0]
        biomass_monthly = pd.DataFrame(
            output.out_Biomass[:, 1:], columns=names, index=range(n_months)
        )
        biomass_monthly.index.name = "Month"
        results["biomass_monthly"] = biomass_monthly

    return results

Autofix (Stability Diagnostics)

Automatic parameter diagnostics and repair routines to prevent Ecosim simulation crashes and improve model stability.

Key functions:

  • diagnose_crash_causes() — identify critical issues (EE > 1, incomplete diets) and warnings (low biomass, high vulnerability, extreme QQ)
  • autofix_parameters() — automatically cap vulnerabilities, enforce minimum biomass, reduce extreme density dependence
  • validate_and_fix_scenario() — combined validation and repair in one step
  • AutofixResult — dataclass with applied fixes and diagnostic info

See the Autofix Guide for practical usage.

pypath.core.autofix

Automatic parameter calibration and fixing for Ecosim stability.

This module provides diagnostic and automatic fixing routines to prevent simulation crashes and improve model stability.

AutofixResult dataclass

Results from automatic parameter fixing.

Attributes:

Name Type Description
success bool

Whether fixes were successful

fixes_applied list

List of fixes that were applied

warnings list

List of warnings about potential issues

original_params dict

Original parameter values before fixing

Source code in pypath/core/autofix.py
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
@dataclass
class AutofixResult:
    """Results from automatic parameter fixing.

    Attributes
    ----------
    success : bool
        Whether fixes were successful
    fixes_applied : list
        List of fixes that were applied
    warnings : list
        List of warnings about potential issues
    original_params : dict
        Original parameter values before fixing
    """

    success: bool
    fixes_applied: list
    warnings: list
    original_params: dict

diagnose_crash_causes

diagnose_crash_causes(rpath: Rpath, params: RsimParams) -> Dict[str, Any]

Diagnose potential causes of simulation crashes.

Parameters:

Name Type Description Default
rpath Rpath

Balanced Ecopath model

required
params RsimParams

Ecosim parameters

required

Returns:

Type Description
dict

Diagnostic results with issues and recommendations

Source code in pypath/core/autofix.py
 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
def diagnose_crash_causes(
    rpath: Rpath,
    params: RsimParams,
) -> Dict[str, Any]:
    """Diagnose potential causes of simulation crashes.

    Parameters
    ----------
    rpath : Rpath
        Balanced Ecopath model
    params : RsimParams
        Ecosim parameters

    Returns
    -------
    dict
        Diagnostic results with issues and recommendations
    """
    issues = {"critical": [], "warnings": [], "recommendations": []}

    # 1. Check for EE > 1 (overfishing/overconsumption)
    for i in range(1, rpath.NUM_LIVING + 1):
        if rpath.EE[i] > 1.0:
            issues["critical"].append(
                {
                    "type": "ee_too_high",
                    "group": i,
                    "value": rpath.EE[i],
                    "message": f"Group {i} ({rpath.Group[i]}): EE = {rpath.EE[i]:.3f} > 1.0",
                    "fix": "Reduce fishing mortality or consumption by predators",
                }
            )

    # 2. Check for very low initial biomass
    for i in range(1, rpath.NUM_LIVING + 1):
        if params.B_BaseRef[i] < 0.001:
            issues["warnings"].append(
                {
                    "type": "low_biomass",
                    "group": i,
                    "value": params.B_BaseRef[i],
                    "message": f"Group {i} ({rpath.Group[i]}): Very low biomass = {params.B_BaseRef[i]:.6f}",
                    "fix": "Increase initial biomass or remove group",
                }
            )

    # 3. Check for very high vulnerability (VV >> 2) - vectorized
    high_vv_mask = params.VV > MAX_VULNERABILITY_SAFE
    high_vv_indices = np.where(high_vv_mask)[0]
    for i in high_vv_indices:
        prey_idx = params.PreyFrom[i]
        pred_idx = params.PreyTo[i]
        issues["warnings"].append(
            {
                "type": "high_vulnerability",
                "link": i,
                "prey": prey_idx,
                "predator": pred_idx,
                "value": params.VV[i],
                "message": f"Link {i}: VV = {params.VV[i]:.2f} (very high vulnerability)",
                "fix": "Reduce vulnerability to prevent rapid depletion",
            }
        )

    # 4. Check for unrealistic QB/PB ratios - vectorized
    living_indices = np.arange(1, rpath.NUM_LIVING + 1)
    qb = np.array(rpath.QB[1 : rpath.NUM_LIVING + 1])
    pb = np.array(rpath.PB[1 : rpath.NUM_LIVING + 1])

    # Only check where both QB and PB are positive
    valid_mask = (qb > 0) & (pb > 0)
    qb_pb_ratio = np.divide(qb, pb, where=valid_mask, out=np.zeros_like(qb))

    # GE = PB/QB should be between 0.05 and 0.5 for most consumers
    unrealistic_mask = valid_mask & (
        (qb_pb_ratio < MIN_QB_PB_RATIO) | (qb_pb_ratio > MAX_QB_PB_RATIO)
    )
    unrealistic_indices = living_indices[unrealistic_mask]

    for idx, i in enumerate(unrealistic_indices):
        ratio = qb_pb_ratio[i - 1]  # Adjust index for 0-based array
        issues["warnings"].append(
            {
                "type": "unrealistic_qb_pb",
                "group": i,
                "qb": rpath.QB[i],
                "pb": rpath.PB[i],
                "ratio": ratio,
                "message": f"Group {i} ({rpath.Group[i]}): QB/PB = {ratio:.2f} (unusual)",
                "fix": "Check QB and PB values - GE should be 0.05-0.5",
            }
        )

    # 5. Check for very high QQ (density-dependent catchability) - vectorized
    high_qq_mask = params.QQ > MAX_QQ_SAFE
    high_qq_indices = np.where(high_qq_mask)[0]
    for i in high_qq_indices:
        prey_idx = params.PreyFrom[i]
        pred_idx = params.PreyTo[i]
        issues["recommendations"].append(
            {
                "type": "high_qq",
                "link": i,
                "value": params.QQ[i],
                "message": f"Link {i}: QQ = {params.QQ[i]:.2f} (strong density dependence)",
                "fix": "Consider reducing QQ to avoid rapid crashes",
            }
        )

    # 6. Check for missing prey (predator with no food) - vectorized
    # Identify consumers (QB > 0)
    consumer_mask = np.array([rpath.QB[i] > 0 for i in range(1, rpath.NUM_LIVING + 1)])
    consumer_indices = np.arange(1, rpath.NUM_LIVING + 1)[consumer_mask]

    # Calculate diet totals for all consumers at once
    for pred in consumer_indices:
        # Sum diet proportions (only living groups can be prey in DC)
        total_diet = np.sum(rpath.DC[pred, : rpath.NUM_LIVING])

        if total_diet < DIET_SUM_THRESHOLD:  # Diet should sum to ~1
            issues["critical"].append(
                {
                    "type": "incomplete_diet",
                    "group": pred,
                    "diet_sum": total_diet,
                    "message": f"Group {pred} ({rpath.Group[pred]}): Diet sums to {total_diet:.3f} < 1.0",
                    "fix": "Complete diet composition or add import",
                }
            )

    return issues

autofix_parameters

autofix_parameters(rpath: Rpath, params: RsimParams, aggressive: bool = False) -> Tuple[RsimParams, AutofixResult]

Automatically fix parameters to improve stability.

Parameters:

Name Type Description Default
rpath Rpath

Balanced Ecopath model

required
params RsimParams

Ecosim parameters to fix

required
aggressive bool

If True, apply more aggressive fixes

False

Returns:

Type Description
RsimParams

Fixed parameters

AutofixResult

Summary of fixes applied

Source code in pypath/core/autofix.py
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
def autofix_parameters(
    rpath: Rpath, params: RsimParams, aggressive: bool = False
) -> Tuple[RsimParams, AutofixResult]:
    """Automatically fix parameters to improve stability.

    Parameters
    ----------
    rpath : Rpath
        Balanced Ecopath model
    params : RsimParams
        Ecosim parameters to fix
    aggressive : bool
        If True, apply more aggressive fixes

    Returns
    -------
    RsimParams
        Fixed parameters
    AutofixResult
        Summary of fixes applied
    """
    fixes_applied = []
    warnings = []
    original = {}

    # Make a copy to modify
    import copy

    fixed_params = copy.deepcopy(params)

    # Fix 1: Cap vulnerability at reasonable values
    max_vv = 5.0 if not aggressive else 3.0
    for i in range(len(fixed_params.VV)):
        if fixed_params.VV[i] > max_vv:
            original[f"VV_{i}"] = fixed_params.VV[i]
            fixed_params.VV[i] = max_vv
            fixes_applied.append(
                f"Capped VV[{i}] from {original[f'VV_{i}']:.2f} to {max_vv}"
            )

    # Fix 2: Ensure minimum biomass
    for i in range(1, rpath.NUM_LIVING + 1):
        if (
            fixed_params.B_BaseRef[i] < MIN_BIOMASS_VIABLE
            and fixed_params.B_BaseRef[i] > 0
        ):
            original[f"B_{i}"] = fixed_params.B_BaseRef[i]
            fixed_params.B_BaseRef[i] = MIN_BIOMASS_VIABLE
            fixes_applied.append(
                f"Increased B[{i}] from {original[f'B_{i}']:.6f} to {MIN_BIOMASS_VIABLE}"
            )

    # Fix 3: Reduce QQ for very strong density dependence
    max_qq = 3.0 if not aggressive else 2.0
    for i in range(len(fixed_params.QQ)):
        if fixed_params.QQ[i] > max_qq:
            original[f"QQ_{i}"] = fixed_params.QQ[i]
            fixed_params.QQ[i] = max_qq
            fixes_applied.append(
                f"Capped QQ[{i}] from {original[f'QQ_{i}']:.2f} to {max_qq}"
            )

    # Fix 4: Adjust DD (prey switching) for extreme values
    for i in range(len(fixed_params.DD)):
        if fixed_params.DD[i] > MAX_PREY_SWITCHING_POWER:
            original[f"DD_{i}"] = fixed_params.DD[i]
            fixed_params.DD[i] = (
                DEFAULT_PREY_SWITCHING_POWER  # More moderate prey switching
            )
            fixes_applied.append(
                f"Reduced DD[{i}] from {original[f'DD_{i}']:.2f} to {DEFAULT_PREY_SWITCHING_POWER}"
            )
        elif fixed_params.DD[i] < MIN_PREY_SWITCHING_POWER:
            original[f"DD_{i}"] = fixed_params.DD[i]
            fixed_params.DD[i] = 1.0
            fixes_applied.append(
                f"Increased DD[{i}] from {original[f'DD_{i}']:.2f} to 1.0"
            )

    # Fix 5: Warn about EE > 1 (can't fix in Ecosim params)
    for i in range(1, rpath.NUM_LIVING + 1):
        if rpath.EE[i] > 1.0:
            warnings.append(
                f"Group {i} ({rpath.Group[i]}): EE = {rpath.EE[i]:.3f} > 1.0 "
                "(requires Ecopath rebalancing)"
            )

    result = AutofixResult(
        success=len(warnings) == 0,
        fixes_applied=fixes_applied,
        warnings=warnings,
        original_params=original,
    )

    return fixed_params, result

validate_and_fix_scenario

validate_and_fix_scenario(scenario: RsimScenario, rpath: Rpath, auto_fix: bool = True, verbose: bool = True) -> Tuple[RsimScenario, Dict[str, Any]]

Validate scenario and optionally apply automatic fixes.

Parameters:

Name Type Description Default
scenario RsimScenario

Ecosim scenario to validate

required
rpath Rpath

Original Ecopath model

required
auto_fix bool

Whether to automatically fix parameters

True
verbose bool

Whether to print diagnostic messages

True

Returns:

Type Description
RsimScenario

Validated (and potentially fixed) scenario

dict

Diagnostic report

Source code in pypath/core/autofix.py
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
def validate_and_fix_scenario(
    scenario: RsimScenario, rpath: Rpath, auto_fix: bool = True, verbose: bool = True
) -> Tuple[RsimScenario, Dict[str, Any]]:
    """Validate scenario and optionally apply automatic fixes.

    Parameters
    ----------
    scenario : RsimScenario
        Ecosim scenario to validate
    rpath : Rpath
        Original Ecopath model
    auto_fix : bool
        Whether to automatically fix parameters
    verbose : bool
        Whether to print diagnostic messages

    Returns
    -------
    RsimScenario
        Validated (and potentially fixed) scenario
    dict
        Diagnostic report
    """
    report = {"valid": True, "issues": [], "fixes": [], "warnings": []}

    # Diagnose issues
    diagnosis = diagnose_crash_causes(rpath, scenario.params)

    # Check for critical issues
    if diagnosis["critical"]:
        report["valid"] = False
        report["issues"] = diagnosis["critical"]

        if verbose:
            logger.warning("=" * 70)
            logger.warning("CRITICAL ISSUES DETECTED")
            logger.warning("=" * 70)
            for issue in diagnosis["critical"]:
                logger.warning(f"  • {issue['message']}")
                logger.warning(f"    Fix: {issue['fix']}")

    # Apply automatic fixes if requested
    if auto_fix and (diagnosis["critical"] or diagnosis["warnings"]):
        if verbose:
            logger.info("=" * 70)
            logger.info("APPLYING AUTOMATIC FIXES")
            logger.info("=" * 70)

        fixed_params, fix_result = autofix_parameters(rpath, scenario.params)

        if fix_result.fixes_applied:
            scenario.params = fixed_params
            report["fixes"] = fix_result.fixes_applied
            report["valid"] = fix_result.success

            if verbose:
                for fix in fix_result.fixes_applied:
                    logger.info(f"  ✓ {fix}")

        if fix_result.warnings:
            report["warnings"] = fix_result.warnings
            if verbose:
                logger.warning("WARNINGS:")
                for warning in fix_result.warnings:
                    logger.warning(f"  ⚠ {warning}")

    # Log recommendations
    if verbose and diagnosis["recommendations"]:
        logger.info("=" * 70)
        logger.info("RECOMMENDATIONS")
        logger.info("=" * 70)
        for rec in diagnosis["recommendations"]:
            logger.info(f"  • {rec['message']}")

    if verbose:
        logger.info("=" * 70)
        if report["valid"]:
            logger.info("VALIDATION: PASSED ✓")
        else:
            logger.warning("VALIDATION: FAILED - Manual fixes required")
        logger.info("=" * 70)

    return scenario, report

Compressed prey-predator link lists for efficient consumption kernel computation in sparse food webs.

Compressed link-list for sparse food webs.

Pre-computes arrays of active prey-predator link indices so that the consumption kernel can iterate only over active links instead of the full (NUM_GROUPS+1) x (NUM_GROUPS+1) matrix. For a 50-group model with 70% sparsity this eliminates 70% of iterations.

Pre-computed arrays of active prey-predator link indices.

Attributes:

Name Type Description
prey ndarray

1-D int64 array of prey indices for each active link.

pred ndarray

1-D int64 array of predator indices for each active link.

n_links int

Number of active links.

Source code in pypath/core/link_array.py
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
@dataclass
class ActiveLinkArray:
    """Pre-computed arrays of active prey-predator link indices.

    Attributes
    ----------
    prey : np.ndarray
        1-D int64 array of prey indices for each active link.
    pred : np.ndarray
        1-D int64 array of predator indices for each active link.
    n_links : int
        Number of active links.
    """

    prey: np.ndarray  # int64 shape (n_links,)
    pred: np.ndarray  # int64 shape (n_links,)
    n_links: int

    @classmethod
    def from_bool_matrix(cls, active: np.ndarray) -> "ActiveLinkArray":
        """Build an ActiveLinkArray from a boolean (or int) ActiveLink matrix.

        Parameters
        ----------
        active : np.ndarray
            Boolean or integer matrix of shape (N, N) where ``active[prey, pred]``
            is truthy when the link is active.

        Returns
        -------
        ActiveLinkArray
            Compressed representation containing only the active links.
        """
        prey, pred = np.nonzero(active)
        return cls(
            prey=prey.astype(np.int64),
            pred=pred.astype(np.int64),
            n_links=len(prey),
        )
from_bool_matrix(active: ndarray) -> ActiveLinkArray

Build an ActiveLinkArray from a boolean (or int) ActiveLink matrix.

Parameters:

Name Type Description Default
active ndarray

Boolean or integer matrix of shape (N, N) where active[prey, pred] is truthy when the link is active.

required

Returns:

Type Description
ActiveLinkArray

Compressed representation containing only the active links.

Source code in pypath/core/link_array.py
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
@classmethod
def from_bool_matrix(cls, active: np.ndarray) -> "ActiveLinkArray":
    """Build an ActiveLinkArray from a boolean (or int) ActiveLink matrix.

    Parameters
    ----------
    active : np.ndarray
        Boolean or integer matrix of shape (N, N) where ``active[prey, pred]``
        is truthy when the link is active.

    Returns
    -------
    ActiveLinkArray
        Compressed representation containing only the active links.
    """
    prey, pred = np.nonzero(active)
    return cls(
        prey=prey.astype(np.int64),
        pred=pred.astype(np.int64),
        n_links=len(prey),
    )

Constants

Physical and biological constants used throughout PyPath.

pypath.core.constants

Physical and biological constants for ecosystem modeling.

This module centralizes magic numbers and constants used throughout PyPath, improving maintainability and reducing errors from scattered hard-coded values.

Time Series & Calibration

Time series data structures for observed data and calibration against EwE reference series.

pypath.core.timeseries

EwE time series data structures and driver application.

Provides data classes for observed and forced time series used in Ecosim calibration and scenario forcing.

EweTimeSeries dataclass

A single EwE time series.

Parameters:

Name Type Description Default
series_id int

Unique identifier for this series.

required
name str

Human-readable name (e.g. "Cod biomass").

required
dat_type int

DatType constant indicating the series type.

required
group_idx int or None

0-based group index, or None for fleet-level series. Note: this differs from EcosimOptimizer which uses 1-based indices.

required
fleet_idx int or None

0-based fleet index, or None for group-level series.

required
values ndarray

Time series values, shape (n_timesteps,). NaN for missing.

required
weight float

Weighting factor for SS objective (default 1.0).

1.0
dataset_id int

Dataset grouping identifier (default 0).

0
Source code in pypath/core/timeseries.py
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
@dataclass
class EweTimeSeries:
    """A single EwE time series.

    Parameters
    ----------
    series_id : int
        Unique identifier for this series.
    name : str
        Human-readable name (e.g. "Cod biomass").
    dat_type : int
        DatType constant indicating the series type.
    group_idx : int or None
        **0-based** group index, or None for fleet-level series.
        Note: this differs from EcosimOptimizer which uses 1-based indices.
    fleet_idx : int or None
        **0-based** fleet index, or None for group-level series.
    values : np.ndarray
        Time series values, shape (n_timesteps,). NaN for missing.
    weight : float
        Weighting factor for SS objective (default 1.0).
    dataset_id : int
        Dataset grouping identifier (default 0).
    """

    series_id: int
    name: str
    dat_type: int
    group_idx: int | None
    fleet_idx: int | None
    values: np.ndarray
    weight: float = 1.0
    dataset_id: int = 0

EweTimeSeriesCollection dataclass

Container for multiple EwE time series with filtered views.

On construction, all series are NaN-padded to the length of the longest series, and n_timesteps is set to that uniform length.

Parameters:

Name Type Description Default
series list[EweTimeSeries]

List of time series to include.

list()
interval str

The dataset's data interval (EcosimTimeSeriesDataset.DataInterval, EwE6 eTSDataSetInterval): "annual" (one value per year, the default) or "timestep" (one value per monthly time step).

'annual'
Source code in pypath/core/timeseries.py
 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
@dataclass
class EweTimeSeriesCollection:
    """Container for multiple EwE time series with filtered views.

    On construction, all series are NaN-padded to the length of the longest
    series, and ``n_timesteps`` is set to that uniform length.

    Parameters
    ----------
    series : list[EweTimeSeries]
        List of time series to include.
    interval : str
        The dataset's data interval (``EcosimTimeSeriesDataset.DataInterval``,
        EwE6 ``eTSDataSetInterval``): ``"annual"`` (one value per year, the
        default) or ``"timestep"`` (one value per monthly time step).
    """

    series: list[EweTimeSeries] = field(default_factory=list)
    interval: str = "annual"
    n_timesteps: int = field(init=False, default=0)

    def __post_init__(self) -> None:
        if not self.series:
            self.n_timesteps = 0
            return
        max_len = max(len(s.values) for s in self.series)
        self.n_timesteps = max_len
        for s in self.series:
            if len(s.values) < max_len:
                padded = np.full(max_len, np.nan)
                padded[: len(s.values)] = s.values
                s.values = padded

    @property
    def observed_biomass(self) -> list[EweTimeSeries]:
        """Series with dat_type in {0 (relative), 1 (absolute)}."""
        return [
            s
            for s in self.series
            if s.dat_type in (DATTYPE_REL_BIOMASS, DATTYPE_ABS_BIOMASS)
        ]

    @property
    def observed_catch(self) -> list[EweTimeSeries]:
        """Series with dat_type == 6 (catch)."""
        return [s for s in self.series if s.dat_type == DATTYPE_CATCH]

    @property
    def forced_biomass(self) -> list[EweTimeSeries]:
        """Series with dat_type == -1 (forced biomass)."""
        return [s for s in self.series if s.dat_type == DATTYPE_FORCED_BIOMASS]

    @property
    def forced_effort(self) -> list[EweTimeSeries]:
        """Series with dat_type == 3 (effort)."""
        return [s for s in self.series if s.dat_type == DATTYPE_EFFORT]

    def to_observed_dict(self, n_timesteps: int) -> dict[int, np.ndarray]:
        """Convert observed biomass series to {group_idx: array} dict.

        Arrays are padded with NaN or truncated to ``n_timesteps``.
        Compatible with EcosimOptimizer's observed_data format (note:
        EcosimOptimizer uses 1-based group indices; this returns 0-based).
        """
        result: dict[int, np.ndarray] = {}
        for s in self.observed_biomass:
            if s.group_idx is None:
                continue
            vals = s.values
            if len(vals) >= n_timesteps:
                result[s.group_idx] = vals[:n_timesteps].copy()
            else:
                padded = np.full(n_timesteps, np.nan)
                padded[: len(vals)] = vals
                result[s.group_idx] = padded
        return result

    def to_dataframe(self) -> "pd.DataFrame":
        """Convert to a DataFrame in simple format (time, group, value, dat_type).

        Suitable for CSV export and round-tripping.
        """
        import pandas as pd

        rows = []
        for s in self.series:
            for t, v in enumerate(s.values):
                if not np.isnan(v):
                    rows.append(
                        {
                            "time": t + 1,
                            "group": s.group_idx
                            if s.group_idx is not None
                            else s.fleet_idx,
                            "value": v,
                            "dat_type": s.dat_type,
                        }
                    )
        return pd.DataFrame(rows)
observed_biomass property
observed_biomass: list[EweTimeSeries]

Series with dat_type in {0 (relative), 1 (absolute)}.

observed_catch property
observed_catch: list[EweTimeSeries]

Series with dat_type == 6 (catch).

forced_biomass property
forced_biomass: list[EweTimeSeries]

Series with dat_type == -1 (forced biomass).

forced_effort property
forced_effort: list[EweTimeSeries]

Series with dat_type == 3 (effort).

to_observed_dict
to_observed_dict(n_timesteps: int) -> dict[int, np.ndarray]

Convert observed biomass series to {group_idx: array} dict.

Arrays are padded with NaN or truncated to n_timesteps. Compatible with EcosimOptimizer's observed_data format (note: EcosimOptimizer uses 1-based group indices; this returns 0-based).

Source code in pypath/core/timeseries.py
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
def to_observed_dict(self, n_timesteps: int) -> dict[int, np.ndarray]:
    """Convert observed biomass series to {group_idx: array} dict.

    Arrays are padded with NaN or truncated to ``n_timesteps``.
    Compatible with EcosimOptimizer's observed_data format (note:
    EcosimOptimizer uses 1-based group indices; this returns 0-based).
    """
    result: dict[int, np.ndarray] = {}
    for s in self.observed_biomass:
        if s.group_idx is None:
            continue
        vals = s.values
        if len(vals) >= n_timesteps:
            result[s.group_idx] = vals[:n_timesteps].copy()
        else:
            padded = np.full(n_timesteps, np.nan)
            padded[: len(vals)] = vals
            result[s.group_idx] = padded
    return result
to_dataframe
to_dataframe() -> 'pd.DataFrame'

Convert to a DataFrame in simple format (time, group, value, dat_type).

Suitable for CSV export and round-tripping.

Source code in pypath/core/timeseries.py
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
def to_dataframe(self) -> "pd.DataFrame":
    """Convert to a DataFrame in simple format (time, group, value, dat_type).

    Suitable for CSV export and round-tripping.
    """
    import pandas as pd

    rows = []
    for s in self.series:
        for t, v in enumerate(s.values):
            if not np.isnan(v):
                rows.append(
                    {
                        "time": t + 1,
                        "group": s.group_idx
                        if s.group_idx is not None
                        else s.fleet_idx,
                        "value": v,
                        "dat_type": s.dat_type,
                    }
                )
    return pd.DataFrame(rows)

apply_timeseries_drivers

apply_timeseries_drivers(scenario: 'RsimScenario', collection: EweTimeSeriesCollection) -> None

Apply driver time series to an Ecosim scenario's forcing arrays.

Modifies scenario in place, the way EwE6 applies the dataset loaded in Ecosim: forced biomass (type -1, absolute biomass that replaces the group's state in every month of the data year), fishing effort (3, the fleet's effort multiplier by year) and fishing mortality (4, by year). Observed series are ignored. Yearly values hold for their twelve months; a missing year, or a year beyond the data, leaves the driver untouched.

Raises:

Type Description
ValueError

If any forced biomass values are negative (excluding NaN).

Source code in pypath/core/timeseries.py
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
def apply_timeseries_drivers(
    scenario: "RsimScenario",
    collection: EweTimeSeriesCollection,
) -> None:
    """Apply driver time series to an Ecosim scenario's forcing arrays.

    Modifies ``scenario`` in place, the way EwE6 applies the dataset loaded
    in Ecosim: forced biomass (type -1, absolute biomass that replaces the
    group's state in every month of the data year), fishing effort (3, the
    fleet's effort multiplier by year) and fishing mortality (4, by year).
    Observed series are ignored. Yearly values hold for their twelve months;
    a missing year, or a year beyond the data, leaves the driver untouched.

    Raises
    ------
    ValueError
        If any forced biomass values are negative (excluding NaN).
    """
    n_groups = scenario.params.NUM_GROUPS
    n_gears = scenario.params.NUM_GEARS

    driver_types = (
        DATTYPE_FORCED_BIOMASS,
        DATTYPE_EFFORT,
        DATTYPE_FISHING_MORTALITY,
        DATTYPE_CATCH_FORCING,
    )
    if getattr(collection, "interval", "annual") == "timestep" and any(
        s.dat_type in driver_types for s in collection.series
    ):
        warnings.warn(
            "The dataset has time-step (monthly) data, but its driver series "
            "are applied per year (value k holds for year k); monthly drivers "
            "are not supported yet",
            UserWarning,
            stacklevel=2,
        )

    for s in collection.forced_biomass:
        if s.group_idx is None:
            continue
        if s.group_idx >= n_groups:
            warnings.warn(
                f"Time series '{s.name}' references group index {s.group_idx} "
                f"but model only has {n_groups} groups. Skipping.",
                UserWarning,
                stacklevel=2,
            )
            continue
        valid_vals = s.values[~np.isnan(s.values)]
        if len(valid_vals) > 0 and np.any(valid_vals < 0):
            raise ValueError(
                f"Time series '{s.name}' contains negative forced biomass values."
            )
        col = s.group_idx + 1
        n_months = scenario.forcing.ForcedBio.shape[0]
        values = np.where(np.asarray(s.values, dtype=float) > 0, s.values, np.nan)
        steps = _yearly_steps(values, n_months, fill=np.nan)
        forced = ~np.isnan(steps)
        scenario.forcing.ForcedBio[forced, col] = steps[forced]

    for s in collection.forced_effort:
        if s.fleet_idx is None:
            continue
        if s.fleet_idx >= n_gears:
            warnings.warn(
                f"Time series '{s.name}' references fleet index {s.fleet_idx} "
                f"but model only has {n_gears} fleets. Skipping.",
                UserWarning,
                stacklevel=2,
            )
            continue
        col = s.fleet_idx + 1
        n_months = scenario.fishing.ForcedEffort.shape[0]
        steps = _yearly_steps(s.values, n_months, fill=np.nan)
        given = ~np.isnan(steps)
        scenario.fishing.ForcedEffort[given, col] = steps[given]

    def _mark_replace(col, given_years):
        fishing = scenario.fishing
        flags = getattr(fishing, "ForcedFReplace", None)
        if flags is None:
            flags = np.zeros(fishing.ForcedFRate.shape, dtype=bool)
        flags[given_years, col] = True
        fishing.ForcedFReplace = flags

    for s in collection.series:
        if s.dat_type != DATTYPE_CATCH_FORCING or s.group_idx is None:
            continue
        if s.group_idx >= n_groups:
            warnings.warn(
                f"Time series '{s.name}' references group index {s.group_idx} "
                f"but model only has {n_groups} groups. Skipping.",
                UserWarning,
                stacklevel=2,
            )
            continue
        col = s.group_idx + 1
        n_years = scenario.fishing.ForcedCatch.shape[0]
        values = np.asarray(s.values, dtype=float)
        n = min(n_years, len(values))
        given = np.where(~np.isnan(values[:n]))[0]
        scenario.fishing.ForcedCatch[given, col] = values[given]
        _mark_replace(col, given)

    fmort_series = [
        s for s in collection.series if s.dat_type == DATTYPE_FISHING_MORTALITY
    ]
    for s in fmort_series:
        if s.group_idx is None:
            continue
        if s.group_idx >= n_groups:
            warnings.warn(
                f"Time series '{s.name}' references group index {s.group_idx} "
                f"but model only has {n_groups} groups. Skipping.",
                UserWarning,
                stacklevel=2,
            )
            continue
        col = s.group_idx + 1
        n_years = scenario.fishing.ForcedFRate.shape[0]
        values = np.asarray(s.values, dtype=float)
        n = min(n_years, len(values))
        given = np.where(~np.isnan(values[:n]))[0]
        scenario.fishing.ForcedFRate[given, col] = values[given]
        _mark_replace(col, given)

load_timeseries

load_timeseries(path: str | Path) -> EweTimeSeriesCollection

Load time series from a file, dispatching by extension.

Supported extensions: - .csv -> CSV loader (simple format) - .eweaccdb, .ewemdb, .accdb -> EwE database reader

Parameters:

Name Type Description Default
path str or Path

Path to the time series file.

required

Returns:

Type Description
EweTimeSeriesCollection

Raises:

Type Description
ValueError

If the file extension is not recognized.

Source code in pypath/core/timeseries.py
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
def load_timeseries(path: str | Path) -> EweTimeSeriesCollection:
    """Load time series from a file, dispatching by extension.

    Supported extensions:
    - ``.csv`` -> CSV loader (simple format)
    - ``.eweaccdb``, ``.ewemdb``, ``.accdb`` -> EwE database reader

    Parameters
    ----------
    path : str or Path
        Path to the time series file.

    Returns
    -------
    EweTimeSeriesCollection

    Raises
    ------
    ValueError
        If the file extension is not recognized.
    """
    path = Path(path)
    ext = path.suffix.lower()
    if ext == ".csv":
        from pypath.io.timeseries_csv import load_timeseries_csv

        return load_timeseries_csv(path, format="simple")
    elif ext in (".eweaccdb", ".ewemdb", ".accdb", ".sqlite"):
        from pypath.io.ewemdb import read_timeseries

        return read_timeseries(str(path))
    else:
        raise ValueError(
            f"Unsupported file extension '{ext}'. "
            f"Use .csv, .eweaccdb, .ewemdb, .accdb, or .sqlite."
        )

Calibration

Sum-of-squares fitting against reference time series.

pypath.core.calibration

Ecosim calibration via sum-of-squares fitting to time series data.

Provides fit_to_timeseries() for optimizing Ecosim vulnerability (VV) and primary production (PP) parameters against observed time series.

CalibrationResult dataclass

Result of time series calibration.

Parameters:

Name Type Description Default
best_vv ndarray

Fitted vulnerability values, one per pred-prey link.

required
best_pp ndarray or None

Fitted primary production anomaly (if fit_pp was True).

required
ss float

Final sum-of-squares value.

required
ss_by_group dict[int, float]

SS contribution per group index (0-based).

required
n_iterations int

Number of optimizer iterations performed.

required
converged bool

Whether the optimizer converged.

required
fitted_scenario RsimScenario or None

Scenario with best-fit parameters applied.

required
link_map list[tuple[int, int]]

(prey_idx, pred_idx) 0-based for each entry in best_vv.

required
Source code in pypath/core/calibration.py
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
@dataclass
class CalibrationResult:
    """Result of time series calibration.

    Parameters
    ----------
    best_vv : np.ndarray
        Fitted vulnerability values, one per pred-prey link.
    best_pp : np.ndarray or None
        Fitted primary production anomaly (if fit_pp was True).
    ss : float
        Final sum-of-squares value.
    ss_by_group : dict[int, float]
        SS contribution per group index (0-based).
    n_iterations : int
        Number of optimizer iterations performed.
    converged : bool
        Whether the optimizer converged.
    fitted_scenario : RsimScenario or None
        Scenario with best-fit parameters applied.
    link_map : list[tuple[int, int]]
        (prey_idx, pred_idx) 0-based for each entry in best_vv.
    """

    best_vv: np.ndarray
    best_pp: np.ndarray | None
    ss: float
    ss_by_group: dict[int, float]
    n_iterations: int
    converged: bool
    fitted_scenario: RsimScenario | None
    link_map: list[tuple[int, int]]

EweSSResult dataclass

EwE6's sum of squares of a run against reference time series.

Parameters:

Name Type Description Default
total float

Sum over series of WtType x sum (Z - q)^2.

required
by_series dict[int, float]

Each series' weighted contribution, by series_id.

required
by_group dict[int, float]

Summed by the series' 0-based group (EwE's SS by group).

required
log_q dict[int, float]

ln q of each series: mean(Z) for relative series, 0 otherwise.

required
n_obs dict[int, int]

Observations compared, by series_id.

required
Source code in pypath/core/calibration.py
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
@dataclass
class EweSSResult:
    """EwE6's sum of squares of a run against reference time series.

    Parameters
    ----------
    total : float
        Sum over series of WtType x sum (Z - q)^2.
    by_series : dict[int, float]
        Each series' weighted contribution, by ``series_id``.
    by_group : dict[int, float]
        Summed by the series' 0-based group (EwE's SS by group).
    log_q : dict[int, float]
        ln q of each series: mean(Z) for relative series, 0 otherwise.
    n_obs : dict[int, int]
        Observations compared, by ``series_id``.
    """

    total: float
    by_series: dict[int, float]
    by_group: dict[int, float]
    log_q: dict[int, float]
    n_obs: dict[int, int]

ewe_sum_of_squares

ewe_sum_of_squares(output, timeseries, *, warn: bool = True) -> EweSSResult

EwE6's sum of squares of an Ecosim run against reference time series.

Follows cEcoSimModel.AccumulateDataInfo and PlotDataInfo (vb 2575-2735, 3849-3966):

  • Annual data (timeseries.interval == "annual") are compared once a year, at the start of month 6 before its integration: the biomass at the end of month (year - 1) x 12 + 5, i.e. out_Biomass row (year - 1) x 12 + 5. Time-step data compare value k with row k - 1 (the start of month k). Data years past the run are ignored.
  • Each observation gives Z = ln(obs / pred). Biomass series predict B; catch series predict B x F, F being the fishing mortality of the month before the sample (EwE sets FishTime after the comparison), from out_FishMort. An observation of an unfished group (F = 0) counts with Z = 0, as in EwE. Observations <= 0 or missing are skipped.
  • Relative series (types 0, 61) subtract q = mean(Z); absolute ones do not. Each series adds WtType x sum (Z - q)^2, and every series counts, several per group included.

Other reference types (total mortality, average weight, landings, discards, fishing mortality) are reported and left out; drivers (forced biomass, effort, ...) are not compared, as in EwE.

Parameters:

Name Type Description Default
output RsimOutput

The run; needs out_Biomass and, for catch series, out_FishMort.

required
timeseries EweTimeSeriesCollection

The dataset, with each series' weight (EwE's WtType).

required
warn bool

Report the weighted series left out (unsupported types, no group). fit_to_timeseries reports them once, not at every evaluation.

True

Returns:

Type Description
EweSSResult
Source code in pypath/core/calibration.py
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
def ewe_sum_of_squares(output, timeseries, *, warn: bool = True) -> EweSSResult:
    """EwE6's sum of squares of an Ecosim run against reference time series.

    Follows ``cEcoSimModel.AccumulateDataInfo`` and ``PlotDataInfo`` (vb
    2575-2735, 3849-3966):

    - Annual data (``timeseries.interval == "annual"``) are compared once a
      year, at the start of month 6 before its integration: the biomass at the
      end of month (year - 1) x 12 + 5, i.e. ``out_Biomass`` row
      (year - 1) x 12 + 5. Time-step data compare value k with row k - 1 (the
      start of month k). Data years past the run are ignored.
    - Each observation gives Z = ln(obs / pred). Biomass series predict B;
      catch series predict B x F, F being the fishing mortality of the month
      before the sample (EwE sets FishTime after the comparison), from
      ``out_FishMort``. An observation of an unfished group (F = 0) counts
      with Z = 0, as in EwE. Observations <= 0 or missing are skipped.
    - Relative series (types 0, 61) subtract q = mean(Z); absolute ones do
      not. Each series adds WtType x sum (Z - q)^2, and every series counts,
      several per group included.

    Other reference types (total mortality, average weight, landings,
    discards, fishing mortality) are reported and left out; drivers (forced
    biomass, effort, ...) are not compared, as in EwE.

    Parameters
    ----------
    output : RsimOutput
        The run; needs ``out_Biomass`` and, for catch series,
        ``out_FishMort``.
    timeseries : EweTimeSeriesCollection
        The dataset, with each series' ``weight`` (EwE's WtType).
    warn : bool
        Report the weighted series left out (unsupported types, no group).
        ``fit_to_timeseries`` reports them once, not at every evaluation.

    Returns
    -------
    EweSSResult
    """
    biomass = np.asarray(output.out_Biomass, dtype=float)
    fish_mort = getattr(output, "out_FishMort", None)
    n_months = biomass.shape[0] - 1
    annual = getattr(timeseries, "interval", "annual") != "timestep"
    n_points = n_months // 12 if annual else n_months

    result = EweSSResult(0.0, {}, {}, {}, {})
    for s in _compared_series(timeseries, warn):
        col = s.group_idx + 1
        is_catch = s.dat_type in _EWE_CATCH_TYPES
        if is_catch and fish_mort is None:
            raise ValueError(
                f"Catch series {s.name!r} needs the run's monthly fishing "
                "mortality (out_FishMort)"
            )

        z = []
        for k, obs in enumerate(np.asarray(s.values, dtype=float)[:n_points], 1):
            if not obs > 0:  # also skips NaN
                continue
            row = (k - 1) * 12 + _EWE_ANNUAL_DATA_MONTH - 1 if annual else k - 1
            pred = biomass[row, col]
            if is_catch:
                f = float(fish_mort[row, col])
                if not f > 0:
                    z.append(0.0)
                    continue
                pred = pred * f
            # A crashed group (B = 0) gives a large, finite error.
            z.append(np.log(obs / max(pred, np.finfo(float).tiny)))

        z_arr = np.asarray(z, dtype=float)
        log_q = (
            float(z_arr.mean())
            if len(z_arr) and s.dat_type in _EWE_RELATIVE_TYPES
            else 0.0
        )
        ss = float(s.weight * np.sum((z_arr - log_q) ** 2))
        result.by_series[s.series_id] = ss
        result.log_q[s.series_id] = log_q
        result.n_obs[s.series_id] = len(z_arr)
        result.by_group[s.group_idx] = result.by_group.get(s.group_idx, 0.0) + ss
        result.total += ss
    return result

fit_to_timeseries

fit_to_timeseries(rpath_model, params, timeseries, *, fit_vv: bool = True, fit_pp: bool = False, fit_groups: list[int] | None = None, vv_bounds: tuple = (1.0, 100.0), pp_bounds: tuple = (0.0, 2.0), method: str = 'differential_evolution', max_iterations: int = 1000, verbose: bool = False, workers: int = 1) -> CalibrationResult

Fit Ecosim parameters to observed time series data.

Parameters:

Name Type Description Default
rpath_model Rpath

Balanced Ecopath model.

required
params RpathParams

Model parameters.

required
timeseries EweTimeSeriesCollection or dict

Observed time series. If dict, treated as {group_idx: np.array} of relative biomass (0-based group indices).

required
fit_vv bool

Fit vulnerability (VV) parameters (default True).

True
fit_pp bool

Fit primary production anomaly. Not yet implemented.

False
fit_groups list[int] or None

0-based group indices to fit. None = all groups with observed data.

None
vv_bounds tuple

(min, max) bounds for VV parameters.

(1.0, 100.0)
pp_bounds tuple

(min, max) bounds for PP parameters (reserved).

(0.0, 2.0)
method str

"differential_evolution" or "minimize" (L-BFGS-B).

'differential_evolution'
max_iterations int

Maximum optimizer iterations.

1000
verbose bool

Print progress.

False
workers int

Processes used to evaluate differential evolution candidates in parallel (default 1: serial, exactly as before). -1 uses all CPU cores. Parallel evaluation switches SciPy to updating="deferred" (the population is updated once per generation), so the search follows a different, equally valid path: fitted values differ from a serial run, but are reproducible for a given seed whatever the number of workers. Ignored by method="minimize". On Windows, scripts that call this with workers != 1 need an if __name__ == "__main__": guard.

1

Returns:

Type Description
CalibrationResult
Source code in pypath/core/calibration.py
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
def fit_to_timeseries(
    rpath_model,
    params,
    timeseries,
    *,
    fit_vv: bool = True,
    fit_pp: bool = False,
    fit_groups: list[int] | None = None,
    vv_bounds: tuple = (1.0, 100.0),
    pp_bounds: tuple = (0.0, 2.0),
    method: str = "differential_evolution",
    max_iterations: int = 1000,
    verbose: bool = False,
    workers: int = 1,
) -> CalibrationResult:
    """Fit Ecosim parameters to observed time series data.

    Parameters
    ----------
    rpath_model : Rpath
        Balanced Ecopath model.
    params : RpathParams
        Model parameters.
    timeseries : EweTimeSeriesCollection or dict
        Observed time series. If dict, treated as {group_idx: np.array}
        of relative biomass (0-based group indices).
    fit_vv : bool
        Fit vulnerability (VV) parameters (default True).
    fit_pp : bool
        Fit primary production anomaly. Not yet implemented.
    fit_groups : list[int] or None
        0-based group indices to fit. None = all groups with observed data.
    vv_bounds : tuple
        (min, max) bounds for VV parameters.
    pp_bounds : tuple
        (min, max) bounds for PP parameters (reserved).
    method : str
        "differential_evolution" or "minimize" (L-BFGS-B).
    max_iterations : int
        Maximum optimizer iterations.
    verbose : bool
        Print progress.
    workers : int
        Processes used to evaluate differential evolution candidates in
        parallel (default 1: serial, exactly as before). ``-1`` uses all CPU
        cores. Parallel evaluation switches SciPy to ``updating="deferred"``
        (the population is updated once per generation), so the search
        follows a different, equally valid path: fitted values differ from a
        serial run, but are reproducible for a given seed whatever the number
        of workers. Ignored by ``method="minimize"``. On Windows, scripts that
        call this with ``workers != 1`` need an
        ``if __name__ == "__main__":`` guard.

    Returns
    -------
    CalibrationResult
    """
    from pypath.core.ecosim import rsim_run, rsim_scenario
    from pypath.core.timeseries import (
        DATTYPE_REL_BIOMASS,
        EweTimeSeries,
        EweTimeSeriesCollection,
        apply_timeseries_drivers,
    )

    if fit_pp:
        raise NotImplementedError(
            "Primary production fitting (fit_pp=True) is not yet implemented. "
            "It will be added in a future release."
        )

    # Convert dict input to EweTimeSeriesCollection
    if isinstance(timeseries, dict):
        series_list = []
        for grp_idx, values in timeseries.items():
            series_list.append(
                EweTimeSeries(
                    series_id=grp_idx,
                    name=f"Group_{grp_idx}",
                    dat_type=DATTYPE_REL_BIOMASS,
                    group_idx=grp_idx,
                    fleet_idx=None,
                    values=values,
                )
            )
        timeseries = EweTimeSeriesCollection(series_list)

    n_points = timeseries.n_timesteps
    if n_points < 2:
        raise ValueError("Need at least 2 observed timesteps for calibration.")
    annual = getattr(timeseries, "interval", "annual") != "timestep"
    n_years = n_points if annual else -(-n_points // 12)
    # rsim_scenario needs two years; only the supplied data are compared
    years = range(1, max(n_years, 2) + 1)

    # Build base scenario
    scenario = rsim_scenario(rpath_model, params, years=years)

    # Apply driver series
    apply_timeseries_drivers(scenario, timeseries)

    # The objective is EwE6's sum of squares (ewe_sum_of_squares): every
    # reference series counts, catch is compared with B x F, relative series
    # take q = mean ln(obs / pred), annual data are taken at the start of
    # month 6, each series weighted by its WtType.
    reference_groups = {
        s.group_idx for s in _compared_series(timeseries) if s.weight > 0
    }
    if not reference_groups:
        raise ValueError("No observed series found in timeseries collection.")

    if fit_groups is None:
        fit_groups = sorted(reference_groups)

    # Build link map: PreyFrom/PreyTo are 1-based
    link_indices = []
    link_map = []
    n_links = len(scenario.params.PreyFrom)
    for i in range(1, n_links):
        prey = scenario.params.PreyFrom[i] - 1  # to 0-based
        pred = scenario.params.PreyTo[i] - 1
        if prey in fit_groups or pred in fit_groups:
            link_indices.append(i)
            link_map.append((prey, pred))

    if not link_indices and fit_vv:
        raise ValueError("No pred-prey links found for the specified fit_groups.")

    bounds = []
    if fit_vv:
        bounds.extend([vv_bounds] * len(link_indices))

    n_vv = len(link_indices) if fit_vv else 0
    objective = _CalibrationObjective(
        scenario, timeseries, link_indices, fit_vv, verbose=verbose
    )
    n_workers = _resolve_workers(workers)
    worker_ok = [0]  # successful evaluations counted from worker results

    if method == "differential_evolution":
        from scipy.optimize import differential_evolution

        if n_workers == 1:
            result = differential_evolution(
                objective,
                bounds=bounds,
                maxiter=max_iterations,
                seed=42,
                tol=1e-6,
                polish=True,
            )
        else:
            import multiprocessing as mp

            # "spawn" everywhere: fork can deadlock when the parent has threads,
            # and it is what Windows uses anyway.
            with mp.get_context("spawn").Pool(
                n_workers, initializer=_init_worker, initargs=(objective,)
            ) as pool:

                def _parallel_map(_func, population):
                    # The workers hold their own copy of ``objective``;
                    # SciPy's ``_func`` wraps that same callable (no args).
                    population = list(population)
                    chunk = max(1, len(population) // (4 * n_workers))
                    values = pool.map(_worker_eval, population, chunksize=chunk)
                    worker_ok[0] += sum(1 for v in values if v != _FAILED_SS)
                    return values

                result = differential_evolution(
                    objective,
                    bounds=bounds,
                    maxiter=max_iterations,
                    seed=42,
                    tol=1e-6,
                    polish=True,
                    updating="deferred",
                    workers=_parallel_map,
                )
        best_params = result.x
        converged = result.success
        final_ss = result.fun
    elif method == "minimize":
        from scipy.optimize import minimize

        x0 = np.array([scenario.params.VV[i] for i in link_indices])
        result = minimize(
            objective,
            x0,
            method="L-BFGS-B",
            bounds=bounds,
            options={"maxiter": max_iterations},
        )
        best_params = result.x
        converged = result.success
        final_ss = result.fun

    else:
        raise ValueError(
            f"Unknown method: {method!r}. Use 'differential_evolution' or 'minimize'."
        )

    best_vv = best_params[:n_vv] if fit_vv else np.array([])

    if fit_vv:
        for j, link_idx in enumerate(link_indices):
            scenario.params.VV[link_idx] = best_vv[j]

    # SS by group of the fitted parameters
    try:
        ss_by_group = ewe_sum_of_squares(
            rsim_run(scenario), timeseries, warn=False
        ).by_group
    except (RuntimeError, ValueError, FloatingPointError) as e:
        logger.warning("Final run of the fitted parameters failed: %s", e)
        ss_by_group = {}

    return CalibrationResult(
        best_vv=best_vv,
        best_pp=None,
        ss=final_ss,
        ss_by_group=ss_by_group,
        n_iterations=objective.n_ok + worker_ok[0],
        converged=converged,
        fitted_scenario=scenario,
        link_map=link_map,
    )

Mediation Functions

Trophic mediation functions that modify predator-prey vulnerability based on the biomass of a mediating group.

pypath.core.mediation

Mediation functions for Ecosim predation modification.

Mediation allows a third species (mediator) to modify predator-prey interactions, fleet catchability, or landing proportions based on the mediator's relative biomass and a user-defined response shape.

MediationShape dataclass

A mediation response shape defined by X-Y point pairs.

Parameters:

Name Type Description Default
shape_id int

Unique identifier for this shape.

required
name str

Human-readable name.

required
x_points ndarray

Relative biomass values (mediator B / B_base).

required
y_points ndarray

Corresponding multiplier values.

required
Source code in pypath/core/mediation.py
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
@dataclass
class MediationShape:
    """A mediation response shape defined by X-Y point pairs.

    Parameters
    ----------
    shape_id : int
        Unique identifier for this shape.
    name : str
        Human-readable name.
    x_points : np.ndarray
        Relative biomass values (mediator B / B_base).
    y_points : np.ndarray
        Corresponding multiplier values.
    """

    shape_id: int
    name: str
    x_points: np.ndarray
    y_points: np.ndarray

    def evaluate(self, relative_biomass: float) -> float:
        """Evaluate the shape at a given relative biomass via linear interpolation.

        Values outside the x_points range are clamped to the nearest endpoint.
        """
        if len(self.x_points) <= 1:
            return float(self.y_points[0]) if len(self.y_points) > 0 else 1.0
        return float(np.interp(relative_biomass, self.x_points, self.y_points))
evaluate
evaluate(relative_biomass: float) -> float

Evaluate the shape at a given relative biomass via linear interpolation.

Values outside the x_points range are clamped to the nearest endpoint.

Source code in pypath/core/mediation.py
37
38
39
40
41
42
43
44
def evaluate(self, relative_biomass: float) -> float:
    """Evaluate the shape at a given relative biomass via linear interpolation.

    Values outside the x_points range are clamped to the nearest endpoint.
    """
    if len(self.x_points) <= 1:
        return float(self.y_points[0]) if len(self.y_points) > 0 else 1.0
    return float(np.interp(relative_biomass, self.x_points, self.y_points))

Maps a mediation shape to a specific interaction.

Exactly one target type should be specified: - Group: prey_idx and pred_idx both set - Fleet: fleet_idx set - Landings: landing_group_idx and landing_fleet_idx both set

All indices are 0-based.

Source code in pypath/core/mediation.py
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
@dataclass
class MediationLink:
    """Maps a mediation shape to a specific interaction.

    Exactly one target type should be specified:
    - Group: prey_idx and pred_idx both set
    - Fleet: fleet_idx set
    - Landings: landing_group_idx and landing_fleet_idx both set

    All indices are 0-based.
    """

    shape_id: int
    mediator_idx: int
    prey_idx: int | None = None
    pred_idx: int | None = None
    fleet_idx: int | None = None
    landing_group_idx: int | None = None
    landing_fleet_idx: int | None = None
    weight: float = 1.0

MediationCollection dataclass

Container for mediation shapes and their link assignments.

Source code in pypath/core/mediation.py
 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
@dataclass
class MediationCollection:
    """Container for mediation shapes and their link assignments."""

    shapes: list[MediationShape]
    links: list[MediationLink]

    @property
    def group_links(self) -> list[MediationLink]:
        return [
            link
            for link in self.links
            if link.prey_idx is not None and link.pred_idx is not None
        ]

    @property
    def fleet_links(self) -> list[MediationLink]:
        return [link for link in self.links if link.fleet_idx is not None]

    @property
    def landing_links(self) -> list[MediationLink]:
        return [link for link in self.links if link.landing_group_idx is not None]

    def _get_shape(self, shape_id: int) -> MediationShape | None:
        for s in self.shapes:
            if s.shape_id == shape_id:
                return s
        return None

    def compute_group_multipliers(
        self, BB: np.ndarray, Bbase: np.ndarray, ActiveLink: np.ndarray
    ) -> np.ndarray:
        """Compute 2D (n+1, n+1) multiplier matrix for group mediation.

        For each group link, evaluate the shape at BB[mediator+1]/Bbase[mediator+1]
        and set mult[prey+1, pred+1]. Multiple links on the same pair multiply together.
        """
        n_plus_1 = len(BB)
        mult = np.ones((n_plus_1, n_plus_1))
        for link in self.group_links:
            shape = self._get_shape(link.shape_id)
            if shape is None:
                continue
            med_col = link.mediator_idx + 1
            if med_col >= n_plus_1 or Bbase[med_col] == 0:
                continue
            rel_b = BB[med_col] / Bbase[med_col]
            val = shape.evaluate(rel_b) * link.weight
            prey_row = link.prey_idx + 1
            pred_col = link.pred_idx + 1
            if prey_row < n_plus_1 and pred_col < n_plus_1:
                mult[prey_row, pred_col] *= val
        return mult

    def compute_fleet_multipliers(
        self, BB: np.ndarray, Bbase: np.ndarray, n_fleets: int
    ) -> np.ndarray:
        """Compute per-fleet multiplier array.

        Each fleet link evaluates the shape at mediator relative biomass.
        Default 1.0 for unaffected fleets.
        """
        mult = np.ones(n_fleets)
        for link in self.fleet_links:
            shape = self._get_shape(link.shape_id)
            if shape is None:
                continue
            med_col = link.mediator_idx + 1
            if med_col >= len(BB) or Bbase[med_col] == 0:
                continue
            rel_b = BB[med_col] / Bbase[med_col]
            val = shape.evaluate(rel_b) * link.weight
            if link.fleet_idx is not None and link.fleet_idx < n_fleets:
                mult[link.fleet_idx] *= val
        return mult

    def compute_landing_multipliers(
        self, BB: np.ndarray, Bbase: np.ndarray, n_fleets: int, n_groups: int
    ) -> np.ndarray:
        """Compute (n_fleets, n_groups) multiplier matrix for landings.

        Default 1.0 for unaffected fleet-group combinations.
        """
        mult = np.ones((n_fleets, n_groups))
        for link in self.landing_links:
            shape = self._get_shape(link.shape_id)
            if shape is None:
                continue
            med_col = link.mediator_idx + 1
            if med_col >= len(BB) or Bbase[med_col] == 0:
                continue
            rel_b = BB[med_col] / Bbase[med_col]
            val = shape.evaluate(rel_b) * link.weight
            fi = link.landing_fleet_idx
            gi = link.landing_group_idx
            if fi is not None and gi is not None and fi < n_fleets and gi < n_groups:
                mult[fi, gi] *= val
        return mult
compute_group_multipliers
compute_group_multipliers(BB: ndarray, Bbase: ndarray, ActiveLink: ndarray) -> np.ndarray

Compute 2D (n+1, n+1) multiplier matrix for group mediation.

For each group link, evaluate the shape at BB[mediator+1]/Bbase[mediator+1] and set mult[prey+1, pred+1]. Multiple links on the same pair multiply together.

Source code in pypath/core/mediation.py
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
def compute_group_multipliers(
    self, BB: np.ndarray, Bbase: np.ndarray, ActiveLink: np.ndarray
) -> np.ndarray:
    """Compute 2D (n+1, n+1) multiplier matrix for group mediation.

    For each group link, evaluate the shape at BB[mediator+1]/Bbase[mediator+1]
    and set mult[prey+1, pred+1]. Multiple links on the same pair multiply together.
    """
    n_plus_1 = len(BB)
    mult = np.ones((n_plus_1, n_plus_1))
    for link in self.group_links:
        shape = self._get_shape(link.shape_id)
        if shape is None:
            continue
        med_col = link.mediator_idx + 1
        if med_col >= n_plus_1 or Bbase[med_col] == 0:
            continue
        rel_b = BB[med_col] / Bbase[med_col]
        val = shape.evaluate(rel_b) * link.weight
        prey_row = link.prey_idx + 1
        pred_col = link.pred_idx + 1
        if prey_row < n_plus_1 and pred_col < n_plus_1:
            mult[prey_row, pred_col] *= val
    return mult
compute_fleet_multipliers
compute_fleet_multipliers(BB: ndarray, Bbase: ndarray, n_fleets: int) -> np.ndarray

Compute per-fleet multiplier array.

Each fleet link evaluates the shape at mediator relative biomass. Default 1.0 for unaffected fleets.

Source code in pypath/core/mediation.py
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
def compute_fleet_multipliers(
    self, BB: np.ndarray, Bbase: np.ndarray, n_fleets: int
) -> np.ndarray:
    """Compute per-fleet multiplier array.

    Each fleet link evaluates the shape at mediator relative biomass.
    Default 1.0 for unaffected fleets.
    """
    mult = np.ones(n_fleets)
    for link in self.fleet_links:
        shape = self._get_shape(link.shape_id)
        if shape is None:
            continue
        med_col = link.mediator_idx + 1
        if med_col >= len(BB) or Bbase[med_col] == 0:
            continue
        rel_b = BB[med_col] / Bbase[med_col]
        val = shape.evaluate(rel_b) * link.weight
        if link.fleet_idx is not None and link.fleet_idx < n_fleets:
            mult[link.fleet_idx] *= val
    return mult
compute_landing_multipliers
compute_landing_multipliers(BB: ndarray, Bbase: ndarray, n_fleets: int, n_groups: int) -> np.ndarray

Compute (n_fleets, n_groups) multiplier matrix for landings.

Default 1.0 for unaffected fleet-group combinations.

Source code in pypath/core/mediation.py
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
def compute_landing_multipliers(
    self, BB: np.ndarray, Bbase: np.ndarray, n_fleets: int, n_groups: int
) -> np.ndarray:
    """Compute (n_fleets, n_groups) multiplier matrix for landings.

    Default 1.0 for unaffected fleet-group combinations.
    """
    mult = np.ones((n_fleets, n_groups))
    for link in self.landing_links:
        shape = self._get_shape(link.shape_id)
        if shape is None:
            continue
        med_col = link.mediator_idx + 1
        if med_col >= len(BB) or Bbase[med_col] == 0:
            continue
        rel_b = BB[med_col] / Bbase[med_col]
        val = shape.evaluate(rel_b) * link.weight
        fi = link.landing_fleet_idx
        gi = link.landing_group_idx
        if fi is not None and gi is not None and fi < n_fleets and gi < n_groups:
            mult[fi, gi] *= val
    return mult

EweMediation dataclass

EwE6's pred/prey mediation functions, as Ecosim applies them.

Each shape has 1200 points (points[s, ip - 1] is Medpoints(ip)) and a base point imedbase[s]. Its mediators are the groups with a weight

0 in weights[s] (rsim index) and the fleets with a weight > 0 in fleet_weights[s] (gear index, the column of ForcedEffort). Every derivative sets the shape's value from the current biomass and effort (SetMedFunctions, cEcoSimModel.vb:2851, cMediationDataStructures.vb:129): X = 1e-10 + sum(weight x B) + sum(fleet weight x effort), ip = Trunc(IMedBase x X / MedXbase + 0.01) clamped to 1..1200, value = Medpoints(ip) / MedYbase, with MedXbase = sum(weight x start biomass) + sum(fleet weight), as "Ecosim effort at Ecopath base effort is always one", and MedYbase = Medpoints(IMedBase) (InitializeMedFunctions, vb 3568-3650). Groups come first in both sums, then fleets, as in EwE. A shape without mediators, base X or base point value is unused and its value stays 1. EwE computes in single precision; so does this, so the point index truncates alike.

links are (prey, pred, shape, application) (rsim indices): a search-rate function multiplies the link's search rate, a vulnerability function its vulnerability (ApplyAVmodifiers, vb 4928-4970). Several functions on one link multiply.

Source code in pypath/core/mediation.py
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
@dataclass
class EweMediation:
    """EwE6's pred/prey mediation functions, as Ecosim applies them.

    Each shape has 1200 points (``points[s, ip - 1]`` is Medpoints(ip)) and
    a base point ``imedbase[s]``. Its mediators are the groups with a weight
    > 0 in ``weights[s]`` (rsim index) and the fleets with a weight > 0 in
    ``fleet_weights[s]`` (gear index, the column of ForcedEffort). Every
    derivative sets the shape's value from the current biomass and effort
    (SetMedFunctions, cEcoSimModel.vb:2851, cMediationDataStructures.vb:129):
    X = 1e-10 + sum(weight x B) + sum(fleet weight x effort), ip =
    Trunc(IMedBase x X / MedXbase + 0.01) clamped to 1..1200, value =
    Medpoints(ip) / MedYbase, with MedXbase = sum(weight x start biomass) +
    sum(fleet weight), as "Ecosim effort at Ecopath base effort is always
    one", and MedYbase = Medpoints(IMedBase) (InitializeMedFunctions, vb
    3568-3650). Groups come first in both sums, then fleets, as in EwE. A
    shape without mediators, base X or base point value is unused and its
    value stays 1. EwE computes in single precision; so does this, so the
    point index truncates alike.

    ``links`` are ``(prey, pred, shape, application)`` (rsim indices): a
    search-rate function multiplies the link's search rate, a vulnerability
    function its vulnerability (ApplyAVmodifiers, vb 4928-4970). Several
    functions on one link multiply.
    """

    points: np.ndarray
    imedbase: np.ndarray
    weights: np.ndarray
    links: list
    fleet_weights: np.ndarray | None = None
    xbase: np.ndarray | None = None
    xbase64: np.ndarray | None = None
    ybase: np.ndarray | None = None
    used: np.ndarray | None = None

    def setup(self, start_biomass: np.ndarray) -> None:
        """MedXbase, MedYbase and MedIsUsed from the start biomass."""
        pts = np.asarray(self.points, dtype=np.float32)
        imed = np.asarray(self.imedbase, dtype=int)
        n_shapes = pts.shape[0]
        self.xbase = np.zeros(n_shapes, dtype=np.float32)
        self.xbase64 = np.zeros(n_shapes, dtype=np.float64)
        self.ybase = np.zeros(n_shapes, dtype=np.float32)
        self.used = np.zeros(n_shapes, dtype=bool)
        b0 = np.asarray(start_biomass, dtype=np.float32)
        b64 = np.asarray(start_biomass, dtype=np.float64)
        for s in range(n_shapes):
            w = np.asarray(self.weights[s], dtype=np.float32)
            wf = self._fleet_row(s)
            x = np.float32(0.0)
            x64 = 0.0
            for j in np.nonzero(w > 0)[0]:
                x = np.float32(x + w[j] * b0[j])
                x64 += float(b64[j] * np.float64(self.weights[s][j]))
            for g in np.nonzero(wf > 0)[0]:
                x = np.float32(x + wf[g] * np.float32(1.0))  # base effort
                x64 += float(np.asarray(self._fleet_row(s), dtype=np.float64)[g])
            self.xbase[s] = x
            self.xbase64[s] = x64
            ip = min(max(int(imed[s]), 1), N_MED_POINTS)
            self.ybase[s] = pts[s, ip - 1]
            has_mediator = bool(np.any(w > 0) or np.any(wf > 0))
            self.used[s] = has_mediator and x != 0 and self.ybase[s] != 0

    def _fleet_row(self, s: int) -> np.ndarray:
        """The fleet weights of shape ``s`` (empty without fleet mediators)."""
        if self.fleet_weights is None:
            return np.zeros(0, dtype=np.float32)
        return np.asarray(self.fleet_weights[s], dtype=np.float32)

    def lookup(self, shape: int, x: float, *, interpolate: bool = False) -> float:
        """getMedValue: the shape's value at mediator sum ``x``.

        With ``interpolate`` (the continuous path) the value is linear in
        ``ratio = IMedBase x x / xbase64`` between the points, in float64 and
        clamped at the end points, so the base gives exactly 1 and the value
        is continuous in ``x``. EwE's truncating single-precision lookup is
        the default.
        """
        if interpolate:
            ip_base = min(max(int(self.imedbase[shape]), 1), N_MED_POINTS)
            pts = np.asarray(self.points[shape], dtype=np.float64)
            ratio = float(ip_base) * (float(x) / float(self.xbase64[shape]))
            grid = np.arange(1, N_MED_POINTS + 1, dtype=np.float64)
            return float(np.interp(ratio, grid, pts) / pts[ip_base - 1])
        ratio = np.float32(np.float32(self.imedbase[shape]) * np.float32(x))
        ratio = np.float32(ratio / self.xbase[shape])
        ip = int(math.trunc(float(ratio) + 0.01))
        ip = max(1, min(N_MED_POINTS, ip))
        return float(np.float32(self.points[shape][ip - 1]) / self.ybase[shape])

    def values(
        self,
        biomass: np.ndarray,
        effort: np.ndarray | None = None,
        *,
        interpolate: bool = False,
    ) -> np.ndarray:
        """MedVal of every shape at ``biomass`` and ``effort`` (by gear, as a
        row of ForcedEffort; None or a missing gear counts as the base effort,
        1). Unused shapes are 1. With ``interpolate`` the sum is in float64
        without EwE's 1e-10 (see :meth:`lookup`)."""
        out = np.ones(len(self.used))
        dt = np.float64 if interpolate else np.float32
        b = np.asarray(biomass, dtype=dt)
        e = None if effort is None else np.asarray(effort, dtype=dt)
        for s in np.nonzero(self.used)[0]:
            w = np.asarray(self.weights[s], dtype=dt)
            wf = np.asarray(self._fleet_row(s), dtype=dt)
            if interpolate:
                x = 0.0
                for j in np.nonzero(w > 0)[0]:
                    x += float(b[j] * w[j])
                for g in np.nonzero(wf > 0)[0]:
                    eff = float(e[g]) if e is not None and g < len(e) else 1.0
                    x += eff * float(wf[g])
                out[s] = self.lookup(s, x, interpolate=True)
                continue
            x = np.float32(1e-10)
            for j in np.nonzero(w > 0)[0]:
                x = np.float32(x + b[j] * w[j])
            for g in np.nonzero(wf > 0)[0]:
                eff = e[g] if e is not None and g < len(e) else np.float32(1.0)
                x = np.float32(x + eff * wf[g])
            out[s] = self.lookup(s, float(x))
        return out

    def link_factors(
        self,
        biomass: np.ndarray,
        n: int,
        effort: np.ndarray | None = None,
        *,
        interpolate: bool = False,
    ):
        """Search-rate and vulnerability multipliers by link, (n, n) arrays
        indexed [prey, pred], or None where no link has that application.
        ``effort`` is the fleets' effort by gear (see :meth:`values`)."""
        if not self.links:
            return None, None
        if interpolate:
            vals = self.values(biomass, effort, interpolate=True)
        else:
            vals = self.values(biomass, effort)
        search = vul = None
        for prey, pred, shape, application in self.links:
            if application == SEARCH_RATE:
                if search is None:
                    search = np.ones((n, n))
                search[prey, pred] *= vals[shape]
            elif application == VULNERABILITY:
                if vul is None:
                    vul = np.ones((n, n))
                vul[prey, pred] *= vals[shape]
        return search, vul
setup
setup(start_biomass: ndarray) -> None

MedXbase, MedYbase and MedIsUsed from the start biomass.

Source code in pypath/core/mediation.py
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
def setup(self, start_biomass: np.ndarray) -> None:
    """MedXbase, MedYbase and MedIsUsed from the start biomass."""
    pts = np.asarray(self.points, dtype=np.float32)
    imed = np.asarray(self.imedbase, dtype=int)
    n_shapes = pts.shape[0]
    self.xbase = np.zeros(n_shapes, dtype=np.float32)
    self.xbase64 = np.zeros(n_shapes, dtype=np.float64)
    self.ybase = np.zeros(n_shapes, dtype=np.float32)
    self.used = np.zeros(n_shapes, dtype=bool)
    b0 = np.asarray(start_biomass, dtype=np.float32)
    b64 = np.asarray(start_biomass, dtype=np.float64)
    for s in range(n_shapes):
        w = np.asarray(self.weights[s], dtype=np.float32)
        wf = self._fleet_row(s)
        x = np.float32(0.0)
        x64 = 0.0
        for j in np.nonzero(w > 0)[0]:
            x = np.float32(x + w[j] * b0[j])
            x64 += float(b64[j] * np.float64(self.weights[s][j]))
        for g in np.nonzero(wf > 0)[0]:
            x = np.float32(x + wf[g] * np.float32(1.0))  # base effort
            x64 += float(np.asarray(self._fleet_row(s), dtype=np.float64)[g])
        self.xbase[s] = x
        self.xbase64[s] = x64
        ip = min(max(int(imed[s]), 1), N_MED_POINTS)
        self.ybase[s] = pts[s, ip - 1]
        has_mediator = bool(np.any(w > 0) or np.any(wf > 0))
        self.used[s] = has_mediator and x != 0 and self.ybase[s] != 0
lookup
lookup(shape: int, x: float, *, interpolate: bool = False) -> float

getMedValue: the shape's value at mediator sum x.

With interpolate (the continuous path) the value is linear in ratio = IMedBase x x / xbase64 between the points, in float64 and clamped at the end points, so the base gives exactly 1 and the value is continuous in x. EwE's truncating single-precision lookup is the default.

Source code in pypath/core/mediation.py
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
def lookup(self, shape: int, x: float, *, interpolate: bool = False) -> float:
    """getMedValue: the shape's value at mediator sum ``x``.

    With ``interpolate`` (the continuous path) the value is linear in
    ``ratio = IMedBase x x / xbase64`` between the points, in float64 and
    clamped at the end points, so the base gives exactly 1 and the value
    is continuous in ``x``. EwE's truncating single-precision lookup is
    the default.
    """
    if interpolate:
        ip_base = min(max(int(self.imedbase[shape]), 1), N_MED_POINTS)
        pts = np.asarray(self.points[shape], dtype=np.float64)
        ratio = float(ip_base) * (float(x) / float(self.xbase64[shape]))
        grid = np.arange(1, N_MED_POINTS + 1, dtype=np.float64)
        return float(np.interp(ratio, grid, pts) / pts[ip_base - 1])
    ratio = np.float32(np.float32(self.imedbase[shape]) * np.float32(x))
    ratio = np.float32(ratio / self.xbase[shape])
    ip = int(math.trunc(float(ratio) + 0.01))
    ip = max(1, min(N_MED_POINTS, ip))
    return float(np.float32(self.points[shape][ip - 1]) / self.ybase[shape])
values
values(biomass: ndarray, effort: ndarray | None = None, *, interpolate: bool = False) -> np.ndarray

MedVal of every shape at biomass and effort (by gear, as a row of ForcedEffort; None or a missing gear counts as the base effort, 1). Unused shapes are 1. With interpolate the sum is in float64 without EwE's 1e-10 (see :meth:lookup).

Source code in pypath/core/mediation.py
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
def values(
    self,
    biomass: np.ndarray,
    effort: np.ndarray | None = None,
    *,
    interpolate: bool = False,
) -> np.ndarray:
    """MedVal of every shape at ``biomass`` and ``effort`` (by gear, as a
    row of ForcedEffort; None or a missing gear counts as the base effort,
    1). Unused shapes are 1. With ``interpolate`` the sum is in float64
    without EwE's 1e-10 (see :meth:`lookup`)."""
    out = np.ones(len(self.used))
    dt = np.float64 if interpolate else np.float32
    b = np.asarray(biomass, dtype=dt)
    e = None if effort is None else np.asarray(effort, dtype=dt)
    for s in np.nonzero(self.used)[0]:
        w = np.asarray(self.weights[s], dtype=dt)
        wf = np.asarray(self._fleet_row(s), dtype=dt)
        if interpolate:
            x = 0.0
            for j in np.nonzero(w > 0)[0]:
                x += float(b[j] * w[j])
            for g in np.nonzero(wf > 0)[0]:
                eff = float(e[g]) if e is not None and g < len(e) else 1.0
                x += eff * float(wf[g])
            out[s] = self.lookup(s, x, interpolate=True)
            continue
        x = np.float32(1e-10)
        for j in np.nonzero(w > 0)[0]:
            x = np.float32(x + b[j] * w[j])
        for g in np.nonzero(wf > 0)[0]:
            eff = e[g] if e is not None and g < len(e) else np.float32(1.0)
            x = np.float32(x + eff * wf[g])
        out[s] = self.lookup(s, float(x))
    return out
link_factors(biomass: ndarray, n: int, effort: ndarray | None = None, *, interpolate: bool = False)

Search-rate and vulnerability multipliers by link, (n, n) arrays indexed [prey, pred], or None where no link has that application. effort is the fleets' effort by gear (see :meth:values).

Source code in pypath/core/mediation.py
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
def link_factors(
    self,
    biomass: np.ndarray,
    n: int,
    effort: np.ndarray | None = None,
    *,
    interpolate: bool = False,
):
    """Search-rate and vulnerability multipliers by link, (n, n) arrays
    indexed [prey, pred], or None where no link has that application.
    ``effort`` is the fleets' effort by gear (see :meth:`values`)."""
    if not self.links:
        return None, None
    if interpolate:
        vals = self.values(biomass, effort, interpolate=True)
    else:
        vals = self.values(biomass, effort)
    search = vul = None
    for prey, pred, shape, application in self.links:
        if application == SEARCH_RATE:
            if search is None:
                search = np.ones((n, n))
            search[prey, pred] *= vals[shape]
        elif application == VULNERABILITY:
            if vul is None:
                vul = np.ones((n, n))
            vul[prey, pred] *= vals[shape]
    return search, vul

make_positive_shape

make_positive_shape(shape_id: int = 0, name: str = 'positive', low: float = 0.5, high: float = 2.0, shape: float = 1.0, n_points: int = 9) -> MediationShape

Create a positive (increasing) mediation shape.

y = low + (high - low) * x^shape / (1 + x^shape)

Source code in pypath/core/mediation.py
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
def make_positive_shape(
    shape_id: int = 0,
    name: str = "positive",
    low: float = 0.5,
    high: float = 2.0,
    shape: float = 1.0,
    n_points: int = 9,
) -> MediationShape:
    """Create a positive (increasing) mediation shape.

    y = low + (high - low) * x^shape / (1 + x^shape)
    """
    x = np.linspace(0.0, 2.0, n_points)
    y = low + (high - low) * x**shape / (1.0 + x**shape)
    return MediationShape(shape_id=shape_id, name=name, x_points=x, y_points=y)

make_negative_shape

make_negative_shape(shape_id: int = 0, name: str = 'negative', low: float = 0.5, high: float = 2.0, shape: float = 1.0, n_points: int = 9) -> MediationShape

Create a negative (decreasing) mediation shape.

y = high - (high - low) * x^shape / (1 + x^shape)

Source code in pypath/core/mediation.py
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
def make_negative_shape(
    shape_id: int = 0,
    name: str = "negative",
    low: float = 0.5,
    high: float = 2.0,
    shape: float = 1.0,
    n_points: int = 9,
) -> MediationShape:
    """Create a negative (decreasing) mediation shape.

    y = high - (high - low) * x^shape / (1 + x^shape)
    """
    x = np.linspace(0.0, 2.0, n_points)
    y = high - (high - low) * x**shape / (1.0 + x**shape)
    return MediationShape(shape_id=shape_id, name=name, x_points=x, y_points=y)

make_ushape

make_ushape(shape_id: int = 0, name: str = 'u-shaped', low: float = 0.5, high: float = 2.0, shape: float = 1.0, n_points: int = 9) -> MediationShape

Create a U-shaped mediation shape (peaks at x=1.0).

y = high - (high - low) * |x-1|^shape / (1 + |x-1|^shape)

Source code in pypath/core/mediation.py
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
def make_ushape(
    shape_id: int = 0,
    name: str = "u-shaped",
    low: float = 0.5,
    high: float = 2.0,
    shape: float = 1.0,
    n_points: int = 9,
) -> MediationShape:
    """Create a U-shaped mediation shape (peaks at x=1.0).

    y = high - (high - low) * |x-1|^shape / (1 + |x-1|^shape)
    """
    x = np.linspace(0.0, 2.0, n_points)
    abs_diff = np.abs(x - 1.0)
    y = high - (high - low) * abs_diff**shape / (1.0 + abs_diff**shape)
    return MediationShape(shape_id=shape_id, name=name, x_points=x, y_points=y)

Pedigree System (Phase 1B.1)

Data quality tracking using EwE pedigree indices (0-4 scale mapping to HIGH/MEDIUM/LOW confidence). Integrates with Monte Carlo sampling for uncertainty quantification.

pypath.core.pedigree

Pedigree-based parameter distributions and sampling.

Pedigree values (coefficients of variation) define parameter uncertainty. This module converts pedigree CVs to statistical distributions and generates parameter samples for Monte Carlo analysis.

ScalarDistribution dataclass

A single scalar parameter's sampling distribution (log-normal).

Parameters:

Name Type Description Default
param_name str

Parameter name (e.g. "Biomass", "PB", "QB").

required
group_idx int

0-based group index.

required
base_value float

Current Ecopath value.

required
cv float

Coefficient of variation from pedigree.

required
bounds tuple[float, float] | None

Optional hard bounds for rejection sampling.

None
Source code in pypath/core/pedigree.py
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
@dataclass
class ScalarDistribution:
    """A single scalar parameter's sampling distribution (log-normal).

    Parameters
    ----------
    param_name : str
        Parameter name (e.g. "Biomass", "PB", "QB").
    group_idx : int
        0-based group index.
    base_value : float
        Current Ecopath value.
    cv : float
        Coefficient of variation from pedigree.
    bounds : tuple[float, float] | None
        Optional hard bounds for rejection sampling.
    """

    param_name: str
    group_idx: int
    base_value: float
    cv: float
    bounds: tuple[float, float] | None = None

DietDistribution dataclass

A predator's diet composition distribution (Dirichlet).

Parameters:

Name Type Description Default
pred_idx int

0-based predator group index.

required
base_proportions ndarray

Current diet column (prey proportions, sum=1).

required
cv float

Controls Dirichlet concentration (higher CV = more spread).

required
Source code in pypath/core/pedigree.py
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
@dataclass
class DietDistribution:
    """A predator's diet composition distribution (Dirichlet).

    Parameters
    ----------
    pred_idx : int
        0-based predator group index.
    base_proportions : np.ndarray
        Current diet column (prey proportions, sum=1).
    cv : float
        Controls Dirichlet concentration (higher CV = more spread).
    """

    pred_idx: int
    base_proportions: np.ndarray
    cv: float

PedigreeConfig dataclass

Configuration for pedigree-to-CV mapping.

EwE 6 stores pedigree as (VarName, LevelID) pairs in the Pedigree table, where each VarName has its own set of levels with IndexValue (the CV).

In the Python API, params.pedigree values are treated as CVs directly. PedigreeConfig is only needed when importing from EwE databases.

Source code in pypath/core/pedigree.py
74
75
76
77
78
79
80
81
82
83
84
85
@dataclass
class PedigreeConfig:
    """Configuration for pedigree-to-CV mapping.

    EwE 6 stores pedigree as (VarName, LevelID) pairs in the Pedigree table,
    where each VarName has its own set of levels with IndexValue (the CV).

    In the Python API, params.pedigree values are treated as CVs directly.
    PedigreeConfig is only needed when importing from EwE databases.
    """

    level_to_cv: dict[str, dict[int, float]] = field(default_factory=dict)

PedigreeQuality

Bases: Enum

Pedigree quality classification (EwE standard).

Maps pedigree_index values (0-4) to quality levels.

Source code in pypath/core/pedigree.py
323
324
325
326
327
328
329
330
331
class PedigreeQuality(Enum):
    """Pedigree quality classification (EwE standard).

    Maps pedigree_index values (0-4) to quality levels.
    """

    HIGH = "high"  # pedigree_index 0-1
    MEDIUM = "medium"  # pedigree_index 2
    LOW = "low"  # pedigree_index 3-4

EwePedigreeConfig dataclass

Pedigree configuration for EwE quality tracking (Phase 1B.1).

Represents the quality and reliability of input data or derived values following the EwE pedigree index standard (0-4).

Parameters:

Name Type Description Default
pedigree_index int

Pedigree index in range [0, 4]. - 0-1: HIGH quality (well-documented, peer-reviewed) - 2: MEDIUM quality (literature values) - 3-4: LOW quality (expert guess, uncertain)

required
comment str

Human-readable description of data source or uncertainty.

''

Attributes:

Name Type Description
quality_flag PedigreeQuality

Auto-set from pedigree_index; not a constructor argument.

Raises:

Type Description
ValueError

If pedigree_index is not in [0, 4].

Examples:

>>> cfg = EwePedigreeConfig(pedigree_index=0, comment="Published literature")
>>> cfg.quality_flag
<PedigreeQuality.HIGH: 'high'>
>>> cfg.to_ewe_format()
0
Source code in pypath/core/pedigree.py
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
@dataclass
class EwePedigreeConfig:
    """Pedigree configuration for EwE quality tracking (Phase 1B.1).

    Represents the quality and reliability of input data or derived values
    following the EwE pedigree index standard (0-4).

    Parameters
    ----------
    pedigree_index : int
        Pedigree index in range [0, 4].
        - 0-1: HIGH quality (well-documented, peer-reviewed)
        - 2: MEDIUM quality (literature values)
        - 3-4: LOW quality (expert guess, uncertain)
    comment : str, optional
        Human-readable description of data source or uncertainty.

    Attributes
    ----------
    quality_flag : PedigreeQuality
        Auto-set from pedigree_index; not a constructor argument.

    Raises
    ------
    ValueError
        If pedigree_index is not in [0, 4].

    Examples
    --------
    >>> cfg = EwePedigreeConfig(pedigree_index=0, comment="Published literature")
    >>> cfg.quality_flag
    <PedigreeQuality.HIGH: 'high'>
    >>> cfg.to_ewe_format()
    0
    """

    pedigree_index: int
    quality_flag: PedigreeQuality = field(init=False)
    comment: str = ""

    def __post_init__(self) -> None:
        """Validate pedigree_index and auto-set quality_flag.

        Raises
        ------
        ValueError
            If pedigree_index not in [0, 4].
        """
        if not (0 <= self.pedigree_index <= 4):
            msg = f"pedigree_index must be in [0, 4], got {self.pedigree_index}"
            raise ValueError(msg)

        # Auto-set quality_flag based on index
        if self.pedigree_index <= 1:
            self.quality_flag = PedigreeQuality.HIGH
        elif self.pedigree_index == 2:
            self.quality_flag = PedigreeQuality.MEDIUM
        else:  # 3-4
            self.quality_flag = PedigreeQuality.LOW

    @classmethod
    def from_ewe_format(cls, index: int, comment: str = "") -> "EwePedigreeConfig":
        """Parse EwE pedigree index format.

        Parameters
        ----------
        index : int
            Pedigree index in range [0, 4].
        comment : str, optional
            Optional comment text.

        Returns
        -------
        EwePedigreeConfig
            Initialized config object.

        Raises
        ------
        ValueError
            If index not in [0, 4].
        """
        return cls(pedigree_index=index, comment=comment)

    def to_ewe_format(self) -> int:
        """Export to EwE format (pedigree index 0-4).

        Returns
        -------
        int
            Pedigree index value.
        """
        return self.pedigree_index
__post_init__
__post_init__() -> None

Validate pedigree_index and auto-set quality_flag.

Raises:

Type Description
ValueError

If pedigree_index not in [0, 4].

Source code in pypath/core/pedigree.py
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
def __post_init__(self) -> None:
    """Validate pedigree_index and auto-set quality_flag.

    Raises
    ------
    ValueError
        If pedigree_index not in [0, 4].
    """
    if not (0 <= self.pedigree_index <= 4):
        msg = f"pedigree_index must be in [0, 4], got {self.pedigree_index}"
        raise ValueError(msg)

    # Auto-set quality_flag based on index
    if self.pedigree_index <= 1:
        self.quality_flag = PedigreeQuality.HIGH
    elif self.pedigree_index == 2:
        self.quality_flag = PedigreeQuality.MEDIUM
    else:  # 3-4
        self.quality_flag = PedigreeQuality.LOW
from_ewe_format classmethod
from_ewe_format(index: int, comment: str = '') -> 'EwePedigreeConfig'

Parse EwE pedigree index format.

Parameters:

Name Type Description Default
index int

Pedigree index in range [0, 4].

required
comment str

Optional comment text.

''

Returns:

Type Description
EwePedigreeConfig

Initialized config object.

Raises:

Type Description
ValueError

If index not in [0, 4].

Source code in pypath/core/pedigree.py
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
@classmethod
def from_ewe_format(cls, index: int, comment: str = "") -> "EwePedigreeConfig":
    """Parse EwE pedigree index format.

    Parameters
    ----------
    index : int
        Pedigree index in range [0, 4].
    comment : str, optional
        Optional comment text.

    Returns
    -------
    EwePedigreeConfig
        Initialized config object.

    Raises
    ------
    ValueError
        If index not in [0, 4].
    """
    return cls(pedigree_index=index, comment=comment)
to_ewe_format
to_ewe_format() -> int

Export to EwE format (pedigree index 0-4).

Returns:

Type Description
int

Pedigree index value.

Source code in pypath/core/pedigree.py
417
418
419
420
421
422
423
424
425
def to_ewe_format(self) -> int:
    """Export to EwE format (pedigree index 0-4).

    Returns
    -------
    int
        Pedigree index value.
    """
    return self.pedigree_index

PedigreeContainer

Container for managing EwE pedigree data across groups (Phase 1B.1).

Holds pedigree configurations for each group/parameter and provides serialization, validation, and query methods.

Attributes:

Name Type Description
group_pedigree dict[str, EwePedigreeConfig]

Mapping of group name to its pedigree configuration.

metadata dict

Metadata (source, timestamp, notes, etc.).

Source code in pypath/core/pedigree.py
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
class PedigreeContainer:
    """Container for managing EwE pedigree data across groups (Phase 1B.1).

    Holds pedigree configurations for each group/parameter and provides
    serialization, validation, and query methods.

    Attributes
    ----------
    group_pedigree : dict[str, EwePedigreeConfig]
        Mapping of group name to its pedigree configuration.
    metadata : dict
        Metadata (source, timestamp, notes, etc.).
    """

    def __init__(self) -> None:
        """Initialize empty pedigree container."""
        self.group_pedigree: dict[str, EwePedigreeConfig] = {}
        self.metadata: dict = {}

    def get_pedigree(self, group_name: str) -> Optional[EwePedigreeConfig]:
        """Get pedigree configuration for a group.

        Parameters
        ----------
        group_name : str
            Name of the group.

        Returns
        -------
        EwePedigreeConfig or None
            Pedigree config if found, None otherwise.
        """
        return self.group_pedigree.get(group_name)

    def add_pedigree(self, group_name: str, config: EwePedigreeConfig) -> None:
        """Add or update pedigree configuration for a group.

        Parameters
        ----------
        group_name : str
            Name of the group.
        config : EwePedigreeConfig
            Pedigree configuration to add.
        """
        self.group_pedigree[group_name] = config
        logger.debug(
            f"Added pedigree for {group_name}: index={config.pedigree_index}, "
            f"quality={config.quality_flag.value}"
        )

    def validate(self) -> list[str]:
        """Validate all pedigree entries.

        Returns
        -------
        list[str]
            List of validation issues (empty if valid).
        """
        return validate_ewe_pedigree(self.group_pedigree)

    def to_dataframe(self) -> pd.DataFrame:
        """Export pedigree data as DataFrame.

        Returns
        -------
        pd.DataFrame
            Table with columns: group, pedigree_index, quality_flag, comment.
        """
        if not self.group_pedigree:
            return pd.DataFrame(
                columns=["group", "pedigree_index", "quality_flag", "comment"]
            )

        data = [
            {
                "group": group_name,
                "pedigree_index": config.pedigree_index,
                "quality_flag": config.quality_flag.value,
                "comment": config.comment,
            }
            for group_name, config in self.group_pedigree.items()
        ]
        return pd.DataFrame(data)

    @classmethod
    def from_dataframe(cls, df: pd.DataFrame) -> "PedigreeContainer":
        """Create PedigreeContainer from DataFrame.

        Parameters
        ----------
        df : pd.DataFrame
            DataFrame with columns: group, pedigree_index, quality_flag (optional).

        Returns
        -------
        PedigreeContainer
            Initialized container.

        Raises
        ------
        ValueError
            If required columns are missing.
        """
        if "group" not in df.columns or "pedigree_index" not in df.columns:
            msg = "DataFrame must have 'group' and 'pedigree_index' columns"
            raise ValueError(msg)

        container = cls()
        for _, row in df.iterrows():
            comment = row.get("comment", "")
            config = EwePedigreeConfig(
                pedigree_index=int(row["pedigree_index"]),
                comment=str(comment) if pd.notna(comment) else "",
            )
            container.add_pedigree(str(row["group"]), config)

        return container
__init__
__init__() -> None

Initialize empty pedigree container.

Source code in pypath/core/pedigree.py
501
502
503
504
def __init__(self) -> None:
    """Initialize empty pedigree container."""
    self.group_pedigree: dict[str, EwePedigreeConfig] = {}
    self.metadata: dict = {}
get_pedigree
get_pedigree(group_name: str) -> Optional[EwePedigreeConfig]

Get pedigree configuration for a group.

Parameters:

Name Type Description Default
group_name str

Name of the group.

required

Returns:

Type Description
EwePedigreeConfig or None

Pedigree config if found, None otherwise.

Source code in pypath/core/pedigree.py
506
507
508
509
510
511
512
513
514
515
516
517
518
519
def get_pedigree(self, group_name: str) -> Optional[EwePedigreeConfig]:
    """Get pedigree configuration for a group.

    Parameters
    ----------
    group_name : str
        Name of the group.

    Returns
    -------
    EwePedigreeConfig or None
        Pedigree config if found, None otherwise.
    """
    return self.group_pedigree.get(group_name)
add_pedigree
add_pedigree(group_name: str, config: EwePedigreeConfig) -> None

Add or update pedigree configuration for a group.

Parameters:

Name Type Description Default
group_name str

Name of the group.

required
config EwePedigreeConfig

Pedigree configuration to add.

required
Source code in pypath/core/pedigree.py
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
def add_pedigree(self, group_name: str, config: EwePedigreeConfig) -> None:
    """Add or update pedigree configuration for a group.

    Parameters
    ----------
    group_name : str
        Name of the group.
    config : EwePedigreeConfig
        Pedigree configuration to add.
    """
    self.group_pedigree[group_name] = config
    logger.debug(
        f"Added pedigree for {group_name}: index={config.pedigree_index}, "
        f"quality={config.quality_flag.value}"
    )
validate
validate() -> list[str]

Validate all pedigree entries.

Returns:

Type Description
list[str]

List of validation issues (empty if valid).

Source code in pypath/core/pedigree.py
537
538
539
540
541
542
543
544
545
def validate(self) -> list[str]:
    """Validate all pedigree entries.

    Returns
    -------
    list[str]
        List of validation issues (empty if valid).
    """
    return validate_ewe_pedigree(self.group_pedigree)
to_dataframe
to_dataframe() -> pd.DataFrame

Export pedigree data as DataFrame.

Returns:

Type Description
DataFrame

Table with columns: group, pedigree_index, quality_flag, comment.

Source code in pypath/core/pedigree.py
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
def to_dataframe(self) -> pd.DataFrame:
    """Export pedigree data as DataFrame.

    Returns
    -------
    pd.DataFrame
        Table with columns: group, pedigree_index, quality_flag, comment.
    """
    if not self.group_pedigree:
        return pd.DataFrame(
            columns=["group", "pedigree_index", "quality_flag", "comment"]
        )

    data = [
        {
            "group": group_name,
            "pedigree_index": config.pedigree_index,
            "quality_flag": config.quality_flag.value,
            "comment": config.comment,
        }
        for group_name, config in self.group_pedigree.items()
    ]
    return pd.DataFrame(data)
from_dataframe classmethod
from_dataframe(df: DataFrame) -> 'PedigreeContainer'

Create PedigreeContainer from DataFrame.

Parameters:

Name Type Description Default
df DataFrame

DataFrame with columns: group, pedigree_index, quality_flag (optional).

required

Returns:

Type Description
PedigreeContainer

Initialized container.

Raises:

Type Description
ValueError

If required columns are missing.

Source code in pypath/core/pedigree.py
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
@classmethod
def from_dataframe(cls, df: pd.DataFrame) -> "PedigreeContainer":
    """Create PedigreeContainer from DataFrame.

    Parameters
    ----------
    df : pd.DataFrame
        DataFrame with columns: group, pedigree_index, quality_flag (optional).

    Returns
    -------
    PedigreeContainer
        Initialized container.

    Raises
    ------
    ValueError
        If required columns are missing.
    """
    if "group" not in df.columns or "pedigree_index" not in df.columns:
        msg = "DataFrame must have 'group' and 'pedigree_index' columns"
        raise ValueError(msg)

    container = cls()
    for _, row in df.iterrows():
        comment = row.get("comment", "")
        config = EwePedigreeConfig(
            pedigree_index=int(row["pedigree_index"]),
            comment=str(comment) if pd.notna(comment) else "",
        )
        container.add_pedigree(str(row["group"]), config)

    return container

build_distributions

build_distributions(params: 'RpathParams', config: PedigreeConfig | None = None) -> list[ParameterDistribution]

Build parameter distributions from pedigree CVs.

Parameters:

Name Type Description Default
params RpathParams

Ecopath parameters with pedigree DataFrame.

required
config PedigreeConfig

EwE database pedigree mapping (for converting LevelIDs to CVs).

None

Returns:

Type Description
list[ParameterDistribution]

Distributions for all parameters with CV > 0.

Source code in pypath/core/pedigree.py
 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
def build_distributions(
    params: "RpathParams",
    config: PedigreeConfig | None = None,
) -> list[ParameterDistribution]:
    """Build parameter distributions from pedigree CVs.

    Parameters
    ----------
    params : RpathParams
        Ecopath parameters with pedigree DataFrame.
    config : PedigreeConfig, optional
        EwE database pedigree mapping (for converting LevelIDs to CVs).

    Returns
    -------
    list[ParameterDistribution]
        Distributions for all parameters with CV > 0.
    """

    pedigree = params.pedigree
    if pedigree is None:
        return []

    # Warn if all pedigree values are default 1.0
    numeric_cols = [c for c in pedigree.columns if c != "Group"]
    all_vals = pedigree[numeric_cols].values.flatten()
    all_vals = all_vals[~np.isnan(all_vals.astype(float))]
    if len(all_vals) > 0 and np.allclose(all_vals, 1.0):
        warnings.warn(
            "All pedigree values are 1.0 (default = 100% CV). "
            "Consider setting pedigree values before MC analysis.",
            UserWarning,
            stacklevel=2,
        )

    model = params.model
    distributions: list[ParameterDistribution] = []

    # Scalar parameters: Biomass, PB, QB
    scalar_params = ["Biomass", "PB", "QB"]
    for param_name in scalar_params:
        if param_name not in pedigree.columns:
            continue
        for idx in range(len(model)):
            group_type = model.loc[idx, "Type"]
            # Skip detritus (type=2) for PB/QB
            if group_type == 2 and param_name in ("PB", "QB"):
                continue
            # Skip fleets (type=3)
            if group_type == 3:
                continue
            # Producers don't have QB
            if group_type == 1 and param_name == "QB":
                continue

            cv = float(pedigree.loc[idx, param_name])
            if np.isnan(cv) or cv <= 0:
                continue

            base_val = model.loc[idx, param_name]
            if np.isnan(base_val) or base_val <= 0:
                continue

            distributions.append(
                ScalarDistribution(
                    param_name=param_name,
                    group_idx=idx,
                    base_value=float(base_val),
                    cv=cv,
                )
            )

    # Diet distributions: one per consumer with Diet CV > 0
    if "Diet" in pedigree.columns:
        consumer_mask = model["Type"] == 0
        for idx in range(len(model)):
            if not consumer_mask.iloc[idx]:
                continue
            cv = float(pedigree.loc[idx, "Diet"])
            if np.isnan(cv) or cv <= 0:
                continue

            group_name = model.loc[idx, "Group"]
            if group_name not in params.diet.columns:
                continue
            diet_col = params.diet[group_name].values.astype(float)
            # Only include if diet has non-zero entries
            if np.nansum(diet_col) <= 0:
                continue

            distributions.append(
                DietDistribution(
                    pred_idx=idx,
                    base_proportions=diet_col,
                    cv=cv,
                )
            )

    return distributions

sample_parameters

sample_parameters(distributions: list[ParameterDistribution], n_samples: int, method: str = 'lhs', rng: Generator | None = None) -> list[dict]

Generate parameter samples from distributions.

Parameters:

Name Type Description Default
distributions list[ParameterDistribution]

Parameter distributions from build_distributions().

required
n_samples int

Number of samples to generate.

required
method str

"lhs" for Latin Hypercube Sampling, "random" for direct sampling.

'lhs'
rng Generator

Random number generator for reproducibility.

None

Returns:

Type Description
list[dict]

N parameter sets. Keys are (param_name, group_idx) tuples.

Source code in pypath/core/pedigree.py
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
def sample_parameters(
    distributions: list[ParameterDistribution],
    n_samples: int,
    method: str = "lhs",
    rng: np.random.Generator | None = None,
) -> list[dict]:
    """Generate parameter samples from distributions.

    Parameters
    ----------
    distributions : list[ParameterDistribution]
        Parameter distributions from build_distributions().
    n_samples : int
        Number of samples to generate.
    method : str
        "lhs" for Latin Hypercube Sampling, "random" for direct sampling.
    rng : np.random.Generator, optional
        Random number generator for reproducibility.

    Returns
    -------
    list[dict]
        N parameter sets. Keys are (param_name, group_idx) tuples.
    """
    if rng is None:
        rng = np.random.default_rng()

    scalars = [d for d in distributions if isinstance(d, ScalarDistribution)]
    diets = [d for d in distributions if isinstance(d, DietDistribution)]

    # Generate scalar samples
    if method == "lhs" and len(scalars) > 0:
        from scipy.stats.qmc import LatinHypercube

        sampler = LatinHypercube(d=len(scalars), seed=rng)
        unit_samples = sampler.random(n=n_samples)  # (n_samples, n_scalars)
        scalar_samples = np.empty_like(unit_samples)
        for j, dist in enumerate(scalars):
            sigma = math.sqrt(math.log(1 + dist.cv**2))
            mu = math.log(dist.base_value) - sigma**2 / 2
            # Map uniform [0,1] to lognormal via inverse CDF
            from scipy.stats import lognorm

            scalar_samples[:, j] = lognorm.ppf(
                unit_samples[:, j],
                s=sigma,
                scale=math.exp(mu),
            )
    else:
        # Direct random sampling
        scalar_samples = np.empty((n_samples, len(scalars)))
        for j, dist in enumerate(scalars):
            sigma = math.sqrt(math.log(1 + dist.cv**2))
            mu = math.log(dist.base_value) - sigma**2 / 2
            scalar_samples[:, j] = rng.lognormal(mean=mu, sigma=sigma, size=n_samples)

    # Generate diet samples (always direct — no LHS for Dirichlet)
    # Note: the import row (last element) is included in Dirichlet sampling
    # if it has a non-zero proportion. This means import fraction varies
    # with other diet proportions. To fix import, set its proportion to 0.
    diet_samples: list[list[np.ndarray]] = []
    for dist in diets:
        nonzero_mask = dist.base_proportions > 0
        p_nonzero = dist.base_proportions[nonzero_mask]
        alpha = p_nonzero / dist.cv**2
        samples_for_diet = []
        for _ in range(n_samples):
            sampled = rng.dirichlet(alpha)
            full = np.zeros_like(dist.base_proportions)
            full[nonzero_mask] = sampled
            samples_for_diet.append(full)
        diet_samples.append(samples_for_diet)

    # Assemble into list of dicts
    result = []
    for i in range(n_samples):
        sample: dict = {}
        for j, dist in enumerate(scalars):
            sample[(dist.param_name, dist.group_idx)] = float(scalar_samples[i, j])
        for k, dist in enumerate(diets):
            sample[("Diet", dist.pred_idx)] = diet_samples[k][i]
        result.append(sample)

    return result

apply_sample

apply_sample(params: 'RpathParams', sample: dict) -> 'RpathParams'

Apply a parameter sample to a copy of RpathParams.

Parameters:

Name Type Description Default
params RpathParams

Original parameters (not modified).

required
sample dict

Parameter sample from sample_parameters().

required

Returns:

Type Description
RpathParams

New params with sampled values applied.

Source code in pypath/core/pedigree.py
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
def apply_sample(params: "RpathParams", sample: dict) -> "RpathParams":
    """Apply a parameter sample to a copy of RpathParams.

    Parameters
    ----------
    params : RpathParams
        Original parameters (not modified).
    sample : dict
        Parameter sample from sample_parameters().

    Returns
    -------
    RpathParams
        New params with sampled values applied.
    """
    from pypath.core.params import RpathParams

    new_model = params.model.copy()
    new_diet = params.diet.copy()

    # Deep copy stanzas if present
    new_stanzas = copy.deepcopy(params.stanzas)

    for key, value in sample.items():
        param_name, idx = key
        if param_name == "Diet":
            group_name = new_model.loc[idx, "Group"]
            if group_name in new_diet.columns:
                new_diet[group_name] = value
        else:
            new_model.loc[idx, param_name] = value

    return RpathParams(
        model=new_model,
        diet=new_diet,
        stanzas=new_stanzas,
        pedigree=params.pedigree,
        remarks=params.remarks,
        ecosim=params.ecosim,
        compat=params.compat,
    )

validate_ewe_pedigree

validate_ewe_pedigree(pedigree_dict: dict[str, EwePedigreeConfig]) -> list[str]

Validate EwE pedigree configuration dictionary.

Checks that all pedigree entries conform to EwE standards and internal consistency. Returns a list of validation issues; empty list means valid.

Parameters:

Name Type Description Default
pedigree_dict dict[str, EwePedigreeConfig]

Mapping of group name to EwePedigreeConfig.

required

Returns:

Type Description
list[str]

List of validation warning/error messages. Empty if all valid.

Examples:

>>> pedigree = {
...     "Cod": EwePedigreeConfig(0, comment="Published"),
...     "Herring": EwePedigreeConfig(2),
... }
>>> issues = validate_ewe_pedigree(pedigree)
>>> len(issues)
0
Source code in pypath/core/pedigree.py
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
def validate_ewe_pedigree(
    pedigree_dict: dict[str, EwePedigreeConfig],
) -> list[str]:
    """Validate EwE pedigree configuration dictionary.

    Checks that all pedigree entries conform to EwE standards and internal
    consistency. Returns a list of validation issues; empty list means valid.

    Parameters
    ----------
    pedigree_dict : dict[str, EwePedigreeConfig]
        Mapping of group name to EwePedigreeConfig.

    Returns
    -------
    list[str]
        List of validation warning/error messages. Empty if all valid.

    Examples
    --------
    >>> pedigree = {
    ...     "Cod": EwePedigreeConfig(0, comment="Published"),
    ...     "Herring": EwePedigreeConfig(2),
    ... }
    >>> issues = validate_ewe_pedigree(pedigree)
    >>> len(issues)
    0
    """
    issues: list[str] = []

    if not pedigree_dict:
        logger.warning("Pedigree dictionary is empty")
        return issues

    for group_name, config in pedigree_dict.items():
        # Check pedigree_index range
        if not (0 <= config.pedigree_index <= 4):
            issues.append(
                f"{group_name}: pedigree_index {config.pedigree_index} not in [0, 4]"
            )

        # Check quality_flag matches index
        expected_quality = None
        if config.pedigree_index <= 1:
            expected_quality = PedigreeQuality.HIGH
        elif config.pedigree_index == 2:
            expected_quality = PedigreeQuality.MEDIUM
        else:  # 3-4
            expected_quality = PedigreeQuality.LOW

        if config.quality_flag != expected_quality:
            issues.append(
                f"{group_name}: quality_flag {config.quality_flag.value} "
                f"does not match index {config.pedigree_index}"
            )

    return issues

Key Classes: - PedigreeQuality — Enum mapping EwE pedigree indices to quality levels - EwePedigreeConfig — Configuration for pedigree parameters (index, min, max) - PedigreeContainer — Multi-group pedigree management with validation

Monte Carlo Sampling

pypath.core.montecarlo

Monte Carlo uncertainty analysis for Ecopath/Ecosim.

Runs ensemble simulations with parameter sampling from pedigree-defined distributions. MCConfig.n_jobs runs the samples in worker processes; the results are the serial run's, sample for sample.

MCConfig dataclass

Monte Carlo run configuration.

Attributes:

Name Type Description
n_samples int

Number of parameter samples.

method str

Sampling method: "lhs" (Latin hypercube) or "random".

seed (int, optional)

Seed for drawing the samples; None draws fresh ones.

ecopath_only bool

Balance each sample with Ecopath only, without running Ecosim.

ecosim_years (range, optional)

Years of each sample's Ecosim run (default range(1, 11)).

store_runs bool

Keep every sample's Ecopath and Ecosim biomass in the result.

n_jobs int

Worker processes for the samples. 1 (the default) runs them serially in this process. A larger number runs that many processes, never more than there are samples; -1 uses one per CPU this process may use. The samples are drawn up front from seed, each one is evaluated with warnings ignored and numpy's default floating-point error handling, and the results come back in order, so a parallel run gives the serial run's results, bit for bit.

mediation (object, optional)

Mediation passed to every sample's Ecosim run.

ecosim_method str

Ecosim integration method (default "RK4").

eco_area float

Ecopath area passed to rpath.

mp_context (str, optional)

The multiprocessing start method for the workers: "forkserver", "spawn" or "fork". None uses forkserver on Linux and spawn on macOS and Windows, as CPython's own defaults do from Python 3.14.

forkserver and spawn start clean worker processes:

  • a script that calls run_montecarlo must do so under if __name__ == "__main__":;
  • params and mediation must be picklable, and a mediation class must be importable from a module (not defined in a notebook or in __main__);
  • workers do not see the caller's warning filters, logging configuration or later changes to os.environ;
  • starting the workers takes about 2 s per call when the caller is not a script that imports pypath (a notebook, for example).

"fork" starts workers fastest but is unsafe in a multi-threaded process (Python warns, and numpy's BLAS threads count), so ask for it only from a single-threaded script.

Source code in pypath/core/montecarlo.py
 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
@dataclass
class MCConfig:
    """Monte Carlo run configuration.

    Attributes
    ----------
    n_samples : int
        Number of parameter samples.
    method : str
        Sampling method: "lhs" (Latin hypercube) or "random".
    seed : int, optional
        Seed for drawing the samples; None draws fresh ones.
    ecopath_only : bool
        Balance each sample with Ecopath only, without running Ecosim.
    ecosim_years : range, optional
        Years of each sample's Ecosim run (default ``range(1, 11)``).
    store_runs : bool
        Keep every sample's Ecopath and Ecosim biomass in the result.
    n_jobs : int
        Worker processes for the samples. 1 (the default) runs them serially
        in this process. A larger number runs that many processes, never more
        than there are samples; -1 uses one per CPU this process may use. The
        samples are drawn up front from ``seed``, each one is evaluated with
        warnings ignored and numpy's default floating-point error handling,
        and the results come back in order, so a parallel run gives the
        serial run's results, bit for bit.
    mediation : object, optional
        Mediation passed to every sample's Ecosim run.
    ecosim_method : str
        Ecosim integration method (default "RK4").
    eco_area : float
        Ecopath area passed to ``rpath``.
    mp_context : str, optional
        The multiprocessing start method for the workers: "forkserver",
        "spawn" or "fork". None uses forkserver on Linux and spawn on macOS
        and Windows, as CPython's own defaults do from Python 3.14.

        forkserver and spawn start clean worker processes:

        - a script that calls ``run_montecarlo`` must do so under
          ``if __name__ == "__main__":``;
        - ``params`` and ``mediation`` must be picklable, and a mediation
          class must be importable from a module (not defined in a notebook
          or in ``__main__``);
        - workers do not see the caller's warning filters, logging
          configuration or later changes to ``os.environ``;
        - starting the workers takes about 2 s per call when the caller is
          not a script that imports pypath (a notebook, for example).

        "fork" starts workers fastest but is unsafe in a multi-threaded
        process (Python warns, and numpy's BLAS threads count), so ask for it
        only from a single-threaded script.
    """

    n_samples: int = 1000
    method: str = "lhs"
    seed: int | None = None
    ecopath_only: bool = False
    ecosim_years: range | None = None
    store_runs: bool = False
    n_jobs: int = 1
    mediation: Any = None
    ecosim_method: str = "RK4"
    eco_area: float = 1.0
    mp_context: str | None = None

MCResult dataclass

Monte Carlo ensemble results.

Source code in pypath/core/montecarlo.py
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
@dataclass
class MCResult:
    """Monte Carlo ensemble results."""

    n_total: int
    n_feasible: int
    n_ecosim: int
    ecopath_stats: dict[str, pd.DataFrame]
    ecosim_stats: dict[str, np.ndarray] | None
    ecopath_runs: list[dict] | None
    ecosim_runs: list[np.ndarray] | None
    feasibility_rate: float
    parameter_samples: pd.DataFrame | None

    def to_dataframe(self) -> pd.DataFrame:
        """Return ecopath_stats as a single flat DataFrame."""
        frames = []
        for param_name, df in self.ecopath_stats.items():
            df_copy = df.copy()
            df_copy.insert(0, "parameter", param_name)
            frames.append(df_copy)
        if frames:
            return pd.concat(frames, ignore_index=True)
        return pd.DataFrame()

    def to_dict(self) -> dict:
        """Return JSON-serializable summary dict."""
        return {
            "n_total": self.n_total,
            "n_feasible": self.n_feasible,
            "n_ecosim": self.n_ecosim,
            "feasibility_rate": self.feasibility_rate,
            "ecopath_stats": {
                k: v.to_dict(orient="list") for k, v in self.ecopath_stats.items()
            },
        }
to_dataframe
to_dataframe() -> pd.DataFrame

Return ecopath_stats as a single flat DataFrame.

Source code in pypath/core/montecarlo.py
121
122
123
124
125
126
127
128
129
130
def to_dataframe(self) -> pd.DataFrame:
    """Return ecopath_stats as a single flat DataFrame."""
    frames = []
    for param_name, df in self.ecopath_stats.items():
        df_copy = df.copy()
        df_copy.insert(0, "parameter", param_name)
        frames.append(df_copy)
    if frames:
        return pd.concat(frames, ignore_index=True)
    return pd.DataFrame()
to_dict
to_dict() -> dict

Return JSON-serializable summary dict.

Source code in pypath/core/montecarlo.py
132
133
134
135
136
137
138
139
140
141
142
def to_dict(self) -> dict:
    """Return JSON-serializable summary dict."""
    return {
        "n_total": self.n_total,
        "n_feasible": self.n_feasible,
        "n_ecosim": self.n_ecosim,
        "feasibility_rate": self.feasibility_rate,
        "ecopath_stats": {
            k: v.to_dict(orient="list") for k, v in self.ecopath_stats.items()
        },
    }

run_montecarlo

run_montecarlo(params: 'RpathParams', config: MCConfig | None = None, *, pedigree_config: 'PedigreeConfig | None' = None, progress_callback: Callable[[int, int], None] | None = None) -> MCResult

Run Monte Carlo uncertainty analysis.

Parameters:

Name Type Description Default
params RpathParams

Base Ecopath parameters.

required
config MCConfig

MC configuration. Defaults to MCConfig().

None
pedigree_config PedigreeConfig

EwE pedigree mapping.

None
progress_callback callable

Called with (current_sample, total_samples) after each run, in sample order, in this process (also when config.n_jobs runs workers).

None

Returns:

Type Description
MCResult
Source code in pypath/core/montecarlo.py
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
def run_montecarlo(
    params: "RpathParams",
    config: MCConfig | None = None,
    *,
    pedigree_config: "PedigreeConfig | None" = None,
    progress_callback: Callable[[int, int], None] | None = None,
) -> MCResult:
    """Run Monte Carlo uncertainty analysis.

    Parameters
    ----------
    params : RpathParams
        Base Ecopath parameters.
    config : MCConfig, optional
        MC configuration. Defaults to MCConfig().
    pedigree_config : PedigreeConfig, optional
        EwE pedigree mapping.
    progress_callback : callable, optional
        Called with (current_sample, total_samples) after each run, in sample
        order, in this process (also when ``config.n_jobs`` runs workers).

    Returns
    -------
    MCResult
    """
    from pypath.core.pedigree import (
        build_distributions,
        sample_parameters,
    )

    if config is None:
        config = MCConfig()
    n_workers = _resolve_n_jobs(config.n_jobs, config.n_samples)
    mp_context = _mp_context(config.mp_context)  # refuses an unknown method
    if not config.ecopath_only:
        # Each sample's Ecosim would refuse the model and count as failed
        _require_ecosim_groups(
            params.model["Group"],
            params.model["Type"],
            hint=" Or balance the samples with Ecopath only (ecopath_only=True).",
        )

    rng = np.random.default_rng(config.seed)
    distributions = build_distributions(params, pedigree_config)

    if len(distributions) == 0:
        warnings.warn("No distributions to sample (all CVs are 0).", UserWarning)

    samples = sample_parameters(distributions, config.n_samples, config.method, rng)

    # Collect results — exclude fleet groups (type=3) from biomass stats
    # Every group but the fleets, by type: Ecopath keeps the model's order
    bio_idx = np.flatnonzero(
        params.model["Type"].to_numpy(dtype=float, na_value=np.nan) != 3
    )
    n_groups = len(bio_idx)
    ecopath_biomass = []
    ecopath_runs_list = [] if config.store_runs else None
    ecosim_biomass_list = []
    ecosim_runs_list = [] if config.store_runs else None
    n_feasible = 0
    n_ecosim = 0

    with outputs_in_order(
        _evaluate_in_worker,
        samples,
        n_workers=n_workers,
        context=mp_context,
        serial=lambda sample: _evaluate_sample(params, sample, config, bio_idx),
        # Workers get the model and config once; each task carries a sample
        initializer=_init_worker,
        initargs=(params, config, bio_idx),
        broken_message=(
            "A Monte Carlo worker process died. It may have run out of memory, "
            "or failed to unpickle the model or the mediation: a mediation "
            "class must be importable from a module, not defined in a notebook "
            "or in __main__. Try n_jobs=1, or mp_context='fork' from a "
            "single-threaded script."
        ),
    ) as outcomes:
        for i, (feasible, bio, ecosim_bio) in enumerate(outcomes):
            if feasible:
                n_feasible += 1
                if bio is not None:
                    ecopath_biomass.append(bio)
                if config.store_runs:
                    ecopath_runs_list.append(
                        {
                            "Biomass": bio.copy() if bio is not None else None,
                        }
                    )
                if ecosim_bio is not None:
                    n_ecosim += 1
                    ecosim_biomass_list.append(ecosim_bio)
                    if config.store_runs:
                        ecosim_runs_list.append(ecosim_bio.copy())

            if progress_callback is not None:
                progress_callback(i + 1, config.n_samples)

    # Compute ecopath statistics
    ecopath_stats = {}
    if ecopath_biomass:
        bio_array = np.array(ecopath_biomass)  # (n_feasible, n_groups)
        ecopath_stats["Biomass"] = pd.DataFrame(
            {
                "mean": np.mean(bio_array, axis=0),
                "std": np.std(bio_array, axis=0),
                "p5": np.percentile(bio_array, 5, axis=0),
                "p25": np.percentile(bio_array, 25, axis=0),
                "p50": np.percentile(bio_array, 50, axis=0),
                "p75": np.percentile(bio_array, 75, axis=0),
                "p95": np.percentile(bio_array, 95, axis=0),
            }
        )

    # Compute ecosim statistics
    ecosim_stats = None
    if ecosim_biomass_list:
        # All arrays should have same shape; exclude padding col 0
        min_t = min(b.shape[0] for b in ecosim_biomass_list)
        stacked = np.array([b[:min_t, 1 : n_groups + 1] for b in ecosim_biomass_list])
        # stacked: (n_ecosim, timesteps, n_groups)
        ecosim_stats = {
            "Biomass": np.stack(
                [
                    np.mean(stacked, axis=0),
                    np.std(stacked, axis=0),
                    np.percentile(stacked, 5, axis=0),
                    np.percentile(stacked, 25, axis=0),
                    np.percentile(stacked, 50, axis=0),
                    np.percentile(stacked, 75, axis=0),
                    np.percentile(stacked, 95, axis=0),
                ],
                axis=-1,
            ),  # (timesteps, n_groups, 7)
        }

    feasibility_rate = n_feasible / config.n_samples if config.n_samples > 0 else 0.0

    return MCResult(
        n_total=config.n_samples,
        n_feasible=n_feasible,
        n_ecosim=n_ecosim,
        ecopath_stats=ecopath_stats,
        ecosim_stats=ecosim_stats,
        ecopath_runs=ecopath_runs_list,
        ecosim_runs=ecosim_runs_list,
        feasibility_rate=feasibility_rate,
        parameter_samples=None,
    )

Taxonomic Linkage System (Phase 1B.2)

Hierarchical taxonomic linking for species identification across external databases (WoRMS, ITIS, FishBase). Supports multi-level taxonomy assignment, validation, and integration with biodiversity data systems.

pypath.core.taxonomy

Taxonomic hierarchical linking with WoRMS/ITIS integration.

This module provides taxonomic classification and cross-referencing for food web groups, enabling integration with authoritative taxonomic databases (WoRMS, ITIS) and hierarchical validation.

Phase 1B.2: TG3.2 Taxonomic Linkage System

A single taxon with hierarchical classification and external IDs.

Represents a species or higher-order taxon with full taxonomic hierarchy, common names, and links to authoritative databases (WoRMS, ITIS).

Parameters:

Name Type Description Default
scientific_name str

Binomial scientific name (e.g., "Gadus morhua").

required
common_name str

Vernacular common name (e.g., "Atlantic cod").

None
worms_aphia_id int

WoRMS (World Register of Marine Species) AphiaID.

None
itis_tsn str

ITIS (Integrated Taxonomic Information System) Taxonomic Serial Number.

None
kingdom str

Kingdom (e.g., "Animalia").

''
phylum str

Phylum (e.g., "Chordata").

''
class_ str

Class (note: 'class' is reserved keyword, use 'class_').

''
order str

Order (e.g., "Gadiformes").

''
family str

Family (e.g., "Gadidae").

''
genus str

Genus (e.g., "Gadus").

''
species str

Species epithet (e.g., "morhua").

''
match_confidence float

Confidence score for database match (0.0-1.0). 1.0 = exact match, <0.5 = uncertain.

1.0

Attributes:

Name Type Description
kingdom, phylum, class_, order, family, genus, species str

Full taxonomic hierarchy.

Source code in pypath/core/taxonomy.py
 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
@dataclass
class TaxonLink:
    """A single taxon with hierarchical classification and external IDs.

    Represents a species or higher-order taxon with full taxonomic hierarchy,
    common names, and links to authoritative databases (WoRMS, ITIS).

    Parameters
    ----------
    scientific_name : str
        Binomial scientific name (e.g., "Gadus morhua").
    common_name : str, optional
        Vernacular common name (e.g., "Atlantic cod").
    worms_aphia_id : int, optional
        WoRMS (World Register of Marine Species) AphiaID.
    itis_tsn : str, optional
        ITIS (Integrated Taxonomic Information System) Taxonomic Serial Number.
    kingdom : str
        Kingdom (e.g., "Animalia").
    phylum : str
        Phylum (e.g., "Chordata").
    class_ : str
        Class (note: 'class' is reserved keyword, use 'class_').
    order : str
        Order (e.g., "Gadiformes").
    family : str
        Family (e.g., "Gadidae").
    genus : str
        Genus (e.g., "Gadus").
    species : str
        Species epithet (e.g., "morhua").
    match_confidence : float
        Confidence score for database match (0.0-1.0).
        1.0 = exact match, <0.5 = uncertain.

    Attributes
    ----------
    kingdom, phylum, class_, order, family, genus, species : str
        Full taxonomic hierarchy.
    """

    scientific_name: str
    common_name: Optional[str] = None
    worms_aphia_id: Optional[int] = None
    itis_tsn: Optional[str] = None
    kingdom: str = ""
    phylum: str = ""
    class_: str = ""
    order: str = ""
    family: str = ""
    genus: str = ""
    species: str = ""
    match_confidence: float = 1.0

    def is_valid(self) -> bool:
        """Validate taxon record for completeness and consistency.

        Checks that:
        - scientific_name is not empty
        - match_confidence is in [0.0, 1.0]
        - At least one external ID is present (worms_aphia_id or itis_tsn)
        - Hierarchy is at least partially filled

        Returns
        -------
        bool
            True if taxon is valid, False otherwise.
        """
        if not self.scientific_name or not self.scientific_name.strip():
            logger.warning("TaxonLink: scientific_name is empty")
            return False

        if not (0.0 <= self.match_confidence <= 1.0):
            logger.warning(
                f"TaxonLink {self.scientific_name}: match_confidence "
                f"{self.match_confidence} not in [0.0, 1.0]"
            )
            return False

        # At least one external ID should be present
        if self.worms_aphia_id is None and self.itis_tsn is None:
            logger.warning(
                f"TaxonLink {self.scientific_name}: no external ID (WoRMS or ITIS)"
            )
            return False

        # At least kingdom should be filled
        if not self.kingdom or not self.kingdom.strip():
            logger.warning(f"TaxonLink {self.scientific_name}: kingdom is empty")
            return False

        return True

    def to_dict(self) -> dict:
        """Export taxon to dictionary.

        Returns
        -------
        dict
            Dictionary with all fields.
        """
        return {
            "scientific_name": self.scientific_name,
            "common_name": self.common_name,
            "worms_aphia_id": self.worms_aphia_id,
            "itis_tsn": self.itis_tsn,
            "kingdom": self.kingdom,
            "phylum": self.phylum,
            "class_": self.class_,
            "order": self.order,
            "family": self.family,
            "genus": self.genus,
            "species": self.species,
            "match_confidence": self.match_confidence,
        }

    @classmethod
    def from_dict(cls, data: dict) -> "TaxonLink":
        """Create TaxonLink from dictionary.

        Parameters
        ----------
        data : dict
            Dictionary with TaxonLink fields.

        Returns
        -------
        TaxonLink
            Initialized taxon object.
        """
        return cls(**data)
is_valid
is_valid() -> bool

Validate taxon record for completeness and consistency.

Checks that: - scientific_name is not empty - match_confidence is in [0.0, 1.0] - At least one external ID is present (worms_aphia_id or itis_tsn) - Hierarchy is at least partially filled

Returns:

Type Description
bool

True if taxon is valid, False otherwise.

Source code in pypath/core/taxonomy.py
 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
def is_valid(self) -> bool:
    """Validate taxon record for completeness and consistency.

    Checks that:
    - scientific_name is not empty
    - match_confidence is in [0.0, 1.0]
    - At least one external ID is present (worms_aphia_id or itis_tsn)
    - Hierarchy is at least partially filled

    Returns
    -------
    bool
        True if taxon is valid, False otherwise.
    """
    if not self.scientific_name or not self.scientific_name.strip():
        logger.warning("TaxonLink: scientific_name is empty")
        return False

    if not (0.0 <= self.match_confidence <= 1.0):
        logger.warning(
            f"TaxonLink {self.scientific_name}: match_confidence "
            f"{self.match_confidence} not in [0.0, 1.0]"
        )
        return False

    # At least one external ID should be present
    if self.worms_aphia_id is None and self.itis_tsn is None:
        logger.warning(
            f"TaxonLink {self.scientific_name}: no external ID (WoRMS or ITIS)"
        )
        return False

    # At least kingdom should be filled
    if not self.kingdom or not self.kingdom.strip():
        logger.warning(f"TaxonLink {self.scientific_name}: kingdom is empty")
        return False

    return True
to_dict
to_dict() -> dict

Export taxon to dictionary.

Returns:

Type Description
dict

Dictionary with all fields.

Source code in pypath/core/taxonomy.py
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
def to_dict(self) -> dict:
    """Export taxon to dictionary.

    Returns
    -------
    dict
        Dictionary with all fields.
    """
    return {
        "scientific_name": self.scientific_name,
        "common_name": self.common_name,
        "worms_aphia_id": self.worms_aphia_id,
        "itis_tsn": self.itis_tsn,
        "kingdom": self.kingdom,
        "phylum": self.phylum,
        "class_": self.class_,
        "order": self.order,
        "family": self.family,
        "genus": self.genus,
        "species": self.species,
        "match_confidence": self.match_confidence,
    }
from_dict classmethod
from_dict(data: dict) -> 'TaxonLink'

Create TaxonLink from dictionary.

Parameters:

Name Type Description Default
data dict

Dictionary with TaxonLink fields.

required

Returns:

Type Description
TaxonLink

Initialized taxon object.

Source code in pypath/core/taxonomy.py
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
@classmethod
def from_dict(cls, data: dict) -> "TaxonLink":
    """Create TaxonLink from dictionary.

    Parameters
    ----------
    data : dict
        Dictionary with TaxonLink fields.

    Returns
    -------
    TaxonLink
        Initialized taxon object.
    """
    return cls(**data)

TaxonomyLinkage

Container for managing taxonomic classifications of food web groups.

Maintains a mapping of food web groups to taxa, validates consistency, and provides serialization for integration with ecological models.

Attributes:

Name Type Description
taxa dict[str, TaxonLink]

Mapping of scientific name to TaxonLink objects.

group_assignments dict[str, str]

Mapping of group name (from Ecopath model) to scientific name.

metadata dict

Metadata (source, timestamp, notes, etc.).

Source code in pypath/core/taxonomy.py
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
class TaxonomyLinkage:
    """Container for managing taxonomic classifications of food web groups.

    Maintains a mapping of food web groups to taxa, validates consistency,
    and provides serialization for integration with ecological models.

    Attributes
    ----------
    taxa : dict[str, TaxonLink]
        Mapping of scientific name to TaxonLink objects.
    group_assignments : dict[str, str]
        Mapping of group name (from Ecopath model) to scientific name.
    metadata : dict
        Metadata (source, timestamp, notes, etc.).
    """

    def __init__(self) -> None:
        """Initialize empty taxonomy container."""
        self.taxa: dict[str, TaxonLink] = {}
        self.group_assignments: dict[str, str] = {}
        self.metadata: dict = {}

    def add_taxon(self, taxon: TaxonLink) -> None:
        """Add or update a taxon.

        Parameters
        ----------
        taxon : TaxonLink
            Taxon to add.

        Raises
        ------
        ValueError
            If taxon is invalid.
        """
        if not taxon.is_valid():
            msg = f"Invalid taxon: {taxon.scientific_name}"
            raise ValueError(msg)

        self.taxa[taxon.scientific_name] = taxon
        logger.debug(f"Added taxon: {taxon.scientific_name}")

    def get_taxon(self, scientific_name: str) -> Optional[TaxonLink]:
        """Retrieve a taxon by scientific name.

        Parameters
        ----------
        scientific_name : str
            Scientific name to look up.

        Returns
        -------
        TaxonLink or None
            Taxon if found, None otherwise.
        """
        return self.taxa.get(scientific_name)

    def assign_group(self, group_name: str, scientific_name: str) -> None:
        """Assign a food web group to a taxon.

        Parameters
        ----------
        group_name : str
            Ecopath group name (e.g., "Cod").
        scientific_name : str
            Scientific name of taxon.

        Raises
        ------
        KeyError
            If scientific_name is not in taxa.
        """
        if scientific_name not in self.taxa:
            msg = (
                f"Scientific name '{scientific_name}' not in taxonomy. Add taxon first."
            )
            raise KeyError(msg)

        self.group_assignments[group_name] = scientific_name
        logger.debug(f"Assigned {group_name} -> {scientific_name}")

    def validate(self) -> tuple[bool, list[str]]:
        """Validate taxonomy consistency.

        Checks:
        - All taxa are valid (is_valid() == True)
        - No duplicate assignments
        - Assigned groups reference existing taxa
        - Hierarchical consistency (no orphaned ranks)

        Returns
        -------
        tuple[bool, list[str]]
            (is_valid, error_list). is_valid is True iff error_list is empty.
        """
        errors: list[str] = []

        # Check taxa validity
        for sci_name, taxon in self.taxa.items():
            if not taxon.is_valid():
                errors.append(f"Invalid taxon: {sci_name}")

        # Check assignments reference existing taxa
        for group_name, sci_name in self.group_assignments.items():
            if sci_name not in self.taxa:
                errors.append(
                    f"Group '{group_name}' assigned to non-existent taxon '{sci_name}'"
                )

        # Check for duplicate group assignments (groups should map 1:1 to taxa)
        assigned_taxa = list(self.group_assignments.values())
        if len(assigned_taxa) != len(set(assigned_taxa)):
            duplicates = [t for t in set(assigned_taxa) if assigned_taxa.count(t) > 1]
            for dup_taxon in duplicates:
                groups = [
                    g for g, t in self.group_assignments.items() if t == dup_taxon
                ]
                errors.append(
                    f"Taxon '{dup_taxon}' assigned to multiple groups: {groups}"
                )

        return (len(errors) == 0, errors)

    def to_dataframe(self) -> pd.DataFrame:
        """Export taxonomy to DataFrame.

        Returns
        -------
        pd.DataFrame
            Table with columns: group, scientific_name, common_name,
            worms_aphia_id, itis_tsn, kingdom, phylum, class_, order,
            family, genus, species, match_confidence.
        """
        if not self.group_assignments:
            return pd.DataFrame()

        data = []
        for group_name, sci_name in self.group_assignments.items():
            taxon = self.taxa.get(sci_name)
            if taxon is None:
                continue

            taxon_dict = taxon.to_dict()
            taxon_dict["group"] = group_name
            data.append(taxon_dict)

        if not data:
            return pd.DataFrame()

        df = pd.DataFrame(data)
        # Reorder columns: group first
        cols = ["group"] + [c for c in df.columns if c != "group"]
        return df[cols]

    @classmethod
    def from_dataframe(cls, df: pd.DataFrame) -> "TaxonomyLinkage":
        """Create TaxonomyLinkage from DataFrame.

        Parameters
        ----------
        df : pd.DataFrame
            DataFrame with columns: group, scientific_name, kingdom, etc.

        Returns
        -------
        TaxonomyLinkage
            Initialized taxonomy linkage.

        Raises
        ------
        ValueError
            If required columns are missing.
        """
        required_cols = {"group", "scientific_name", "kingdom"}
        if not required_cols.issubset(set(df.columns)):
            msg = (
                f"DataFrame must have columns: {required_cols}. "
                f"Found: {set(df.columns)}"
            )
            raise ValueError(msg)

        taxonomy = cls()

        for _, row in df.iterrows():
            # Build taxon
            taxon_data = {
                "scientific_name": str(row["scientific_name"]),
                "kingdom": str(row.get("kingdom", "")),
                "phylum": str(row.get("phylum", "")),
                "class_": str(row.get("class_", "")),
                "order": str(row.get("order", "")),
                "family": str(row.get("family", "")),
                "genus": str(row.get("genus", "")),
                "species": str(row.get("species", "")),
                "common_name": (
                    str(row["common_name"])
                    if pd.notna(row.get("common_name"))
                    else None
                ),
                "worms_aphia_id": (
                    int(row["worms_aphia_id"])
                    if pd.notna(row.get("worms_aphia_id"))
                    else None
                ),
                "itis_tsn": (
                    str(row["itis_tsn"]) if pd.notna(row.get("itis_tsn")) else None
                ),
                "match_confidence": float(row.get("match_confidence", 1.0)),
            }

            taxon = TaxonLink.from_dict(taxon_data)
            taxonomy.add_taxon(taxon)
            taxonomy.assign_group(str(row["group"]), taxon.scientific_name)

        return taxonomy
__init__
__init__() -> None

Initialize empty taxonomy container.

Source code in pypath/core/taxonomy.py
170
171
172
173
174
def __init__(self) -> None:
    """Initialize empty taxonomy container."""
    self.taxa: dict[str, TaxonLink] = {}
    self.group_assignments: dict[str, str] = {}
    self.metadata: dict = {}
add_taxon
add_taxon(taxon: TaxonLink) -> None

Add or update a taxon.

Parameters:

Name Type Description Default
taxon TaxonLink

Taxon to add.

required

Raises:

Type Description
ValueError

If taxon is invalid.

Source code in pypath/core/taxonomy.py
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
def add_taxon(self, taxon: TaxonLink) -> None:
    """Add or update a taxon.

    Parameters
    ----------
    taxon : TaxonLink
        Taxon to add.

    Raises
    ------
    ValueError
        If taxon is invalid.
    """
    if not taxon.is_valid():
        msg = f"Invalid taxon: {taxon.scientific_name}"
        raise ValueError(msg)

    self.taxa[taxon.scientific_name] = taxon
    logger.debug(f"Added taxon: {taxon.scientific_name}")
get_taxon
get_taxon(scientific_name: str) -> Optional[TaxonLink]

Retrieve a taxon by scientific name.

Parameters:

Name Type Description Default
scientific_name str

Scientific name to look up.

required

Returns:

Type Description
TaxonLink or None

Taxon if found, None otherwise.

Source code in pypath/core/taxonomy.py
196
197
198
199
200
201
202
203
204
205
206
207
208
209
def get_taxon(self, scientific_name: str) -> Optional[TaxonLink]:
    """Retrieve a taxon by scientific name.

    Parameters
    ----------
    scientific_name : str
        Scientific name to look up.

    Returns
    -------
    TaxonLink or None
        Taxon if found, None otherwise.
    """
    return self.taxa.get(scientific_name)
assign_group
assign_group(group_name: str, scientific_name: str) -> None

Assign a food web group to a taxon.

Parameters:

Name Type Description Default
group_name str

Ecopath group name (e.g., "Cod").

required
scientific_name str

Scientific name of taxon.

required

Raises:

Type Description
KeyError

If scientific_name is not in taxa.

Source code in pypath/core/taxonomy.py
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
def assign_group(self, group_name: str, scientific_name: str) -> None:
    """Assign a food web group to a taxon.

    Parameters
    ----------
    group_name : str
        Ecopath group name (e.g., "Cod").
    scientific_name : str
        Scientific name of taxon.

    Raises
    ------
    KeyError
        If scientific_name is not in taxa.
    """
    if scientific_name not in self.taxa:
        msg = (
            f"Scientific name '{scientific_name}' not in taxonomy. Add taxon first."
        )
        raise KeyError(msg)

    self.group_assignments[group_name] = scientific_name
    logger.debug(f"Assigned {group_name} -> {scientific_name}")
validate
validate() -> tuple[bool, list[str]]

Validate taxonomy consistency.

Checks: - All taxa are valid (is_valid() == True) - No duplicate assignments - Assigned groups reference existing taxa - Hierarchical consistency (no orphaned ranks)

Returns:

Type Description
tuple[bool, list[str]]

(is_valid, error_list). is_valid is True iff error_list is empty.

Source code in pypath/core/taxonomy.py
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
def validate(self) -> tuple[bool, list[str]]:
    """Validate taxonomy consistency.

    Checks:
    - All taxa are valid (is_valid() == True)
    - No duplicate assignments
    - Assigned groups reference existing taxa
    - Hierarchical consistency (no orphaned ranks)

    Returns
    -------
    tuple[bool, list[str]]
        (is_valid, error_list). is_valid is True iff error_list is empty.
    """
    errors: list[str] = []

    # Check taxa validity
    for sci_name, taxon in self.taxa.items():
        if not taxon.is_valid():
            errors.append(f"Invalid taxon: {sci_name}")

    # Check assignments reference existing taxa
    for group_name, sci_name in self.group_assignments.items():
        if sci_name not in self.taxa:
            errors.append(
                f"Group '{group_name}' assigned to non-existent taxon '{sci_name}'"
            )

    # Check for duplicate group assignments (groups should map 1:1 to taxa)
    assigned_taxa = list(self.group_assignments.values())
    if len(assigned_taxa) != len(set(assigned_taxa)):
        duplicates = [t for t in set(assigned_taxa) if assigned_taxa.count(t) > 1]
        for dup_taxon in duplicates:
            groups = [
                g for g, t in self.group_assignments.items() if t == dup_taxon
            ]
            errors.append(
                f"Taxon '{dup_taxon}' assigned to multiple groups: {groups}"
            )

    return (len(errors) == 0, errors)
to_dataframe
to_dataframe() -> pd.DataFrame

Export taxonomy to DataFrame.

Returns:

Type Description
DataFrame

Table with columns: group, scientific_name, common_name, worms_aphia_id, itis_tsn, kingdom, phylum, class_, order, family, genus, species, match_confidence.

Source code in pypath/core/taxonomy.py
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
def to_dataframe(self) -> pd.DataFrame:
    """Export taxonomy to DataFrame.

    Returns
    -------
    pd.DataFrame
        Table with columns: group, scientific_name, common_name,
        worms_aphia_id, itis_tsn, kingdom, phylum, class_, order,
        family, genus, species, match_confidence.
    """
    if not self.group_assignments:
        return pd.DataFrame()

    data = []
    for group_name, sci_name in self.group_assignments.items():
        taxon = self.taxa.get(sci_name)
        if taxon is None:
            continue

        taxon_dict = taxon.to_dict()
        taxon_dict["group"] = group_name
        data.append(taxon_dict)

    if not data:
        return pd.DataFrame()

    df = pd.DataFrame(data)
    # Reorder columns: group first
    cols = ["group"] + [c for c in df.columns if c != "group"]
    return df[cols]
from_dataframe classmethod
from_dataframe(df: DataFrame) -> 'TaxonomyLinkage'

Create TaxonomyLinkage from DataFrame.

Parameters:

Name Type Description Default
df DataFrame

DataFrame with columns: group, scientific_name, kingdom, etc.

required

Returns:

Type Description
TaxonomyLinkage

Initialized taxonomy linkage.

Raises:

Type Description
ValueError

If required columns are missing.

Source code in pypath/core/taxonomy.py
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
@classmethod
def from_dataframe(cls, df: pd.DataFrame) -> "TaxonomyLinkage":
    """Create TaxonomyLinkage from DataFrame.

    Parameters
    ----------
    df : pd.DataFrame
        DataFrame with columns: group, scientific_name, kingdom, etc.

    Returns
    -------
    TaxonomyLinkage
        Initialized taxonomy linkage.

    Raises
    ------
    ValueError
        If required columns are missing.
    """
    required_cols = {"group", "scientific_name", "kingdom"}
    if not required_cols.issubset(set(df.columns)):
        msg = (
            f"DataFrame must have columns: {required_cols}. "
            f"Found: {set(df.columns)}"
        )
        raise ValueError(msg)

    taxonomy = cls()

    for _, row in df.iterrows():
        # Build taxon
        taxon_data = {
            "scientific_name": str(row["scientific_name"]),
            "kingdom": str(row.get("kingdom", "")),
            "phylum": str(row.get("phylum", "")),
            "class_": str(row.get("class_", "")),
            "order": str(row.get("order", "")),
            "family": str(row.get("family", "")),
            "genus": str(row.get("genus", "")),
            "species": str(row.get("species", "")),
            "common_name": (
                str(row["common_name"])
                if pd.notna(row.get("common_name"))
                else None
            ),
            "worms_aphia_id": (
                int(row["worms_aphia_id"])
                if pd.notna(row.get("worms_aphia_id"))
                else None
            ),
            "itis_tsn": (
                str(row["itis_tsn"]) if pd.notna(row.get("itis_tsn")) else None
            ),
            "match_confidence": float(row.get("match_confidence", 1.0)),
        }

        taxon = TaxonLink.from_dict(taxon_data)
        taxonomy.add_taxon(taxon)
        taxonomy.assign_group(str(row["group"]), taxon.scientific_name)

    return taxonomy
validate_taxonomy_links(taxonomy: TaxonomyLinkage) -> tuple[bool, list[str]]

Validate taxonomy linkage for consistency and completeness.

Performs comprehensive checks: - All taxa are valid - No missing or orphaned groups - No duplicate assignments - Hierarchical consistency

Parameters:

Name Type Description Default
taxonomy TaxonomyLinkage

Taxonomy object to validate.

required

Returns:

Type Description
tuple[bool, list[str]]

(is_valid, error_list). is_valid is True iff error_list is empty.

Source code in pypath/core/taxonomy.py
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
def validate_taxonomy_links(
    taxonomy: TaxonomyLinkage,
) -> tuple[bool, list[str]]:
    """Validate taxonomy linkage for consistency and completeness.

    Performs comprehensive checks:
    - All taxa are valid
    - No missing or orphaned groups
    - No duplicate assignments
    - Hierarchical consistency

    Parameters
    ----------
    taxonomy : TaxonomyLinkage
        Taxonomy object to validate.

    Returns
    -------
    tuple[bool, list[str]]
        (is_valid, error_list). is_valid is True iff error_list is empty.
    """
    is_valid, errors = taxonomy.validate()
    return (is_valid, errors)
resolve_worms_link(scientific_name: str) -> Optional[TaxonLink]

Resolve a single species name to WoRMS database.

STUB: This is a placeholder for WoRMS API integration. In production, this would query the WoRMS REST API and return a TaxonLink with WoRMS metadata.

Parameters:

Name Type Description Default
scientific_name str

Scientific name to resolve (e.g., "Gadus morhua").

required

Returns:

Type Description
TaxonLink or None

Resolved taxon with WoRMS data, or None if not found.

Source code in pypath/core/taxonomy.py
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
def resolve_worms_link(
    scientific_name: str,
) -> Optional[TaxonLink]:
    """Resolve a single species name to WoRMS database.

    STUB: This is a placeholder for WoRMS API integration.
    In production, this would query the WoRMS REST API and return
    a TaxonLink with WoRMS metadata.

    Parameters
    ----------
    scientific_name : str
        Scientific name to resolve (e.g., "Gadus morhua").

    Returns
    -------
    TaxonLink or None
        Resolved taxon with WoRMS data, or None if not found.
    """
    logger.debug(f"WoRMS lookup stub for: {scientific_name} (API integration pending)")
    # TODO: Implement WoRMS REST API query
    # Expected workflow:
    # 1. Call WoRMS API: https://www.marinespecies.org/rest/AphiaNameByName
    # 2. Parse response JSON
    # 3. Extract AphiaID, taxonomy, common names
    # 4. Return TaxonLink with populated fields
    return None

batch_resolve_worms

batch_resolve_worms(scientific_names: list[str]) -> dict[str, Optional[TaxonLink]]

Batch resolve multiple species names to WoRMS.

STUB: This is a placeholder for batch WoRMS API integration. In production, this would efficiently query multiple species using WoRMS batch endpoints or caching.

Parameters:

Name Type Description Default
scientific_names list[str]

List of scientific names to resolve.

required

Returns:

Type Description
dict[str, Optional[TaxonLink]]

Mapping of scientific name to resolved TaxonLink (or None if unfound).

Source code in pypath/core/taxonomy.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
455
def batch_resolve_worms(
    scientific_names: list[str],
) -> dict[str, Optional[TaxonLink]]:
    """Batch resolve multiple species names to WoRMS.

    STUB: This is a placeholder for batch WoRMS API integration.
    In production, this would efficiently query multiple species
    using WoRMS batch endpoints or caching.

    Parameters
    ----------
    scientific_names : list[str]
        List of scientific names to resolve.

    Returns
    -------
    dict[str, Optional[TaxonLink]]
        Mapping of scientific name to resolved TaxonLink (or None if unfound).
    """
    logger.debug(
        f"Batch WoRMS lookup stub for {len(scientific_names)} species "
        "(API integration pending)"
    )
    # TODO: Implement batch WoRMS API query with caching
    # Expected workflow:
    # 1. Check cache for previously resolved names
    # 2. Query WoRMS for new names (batch or individual)
    # 3. Cache results
    # 4. Return mapping
    result = {name: None for name in scientific_names}
    return result

Key Classes: - TaxonLink — Full taxonomic hierarchy (kingdom through species) with external IDs - TaxonomyLinkage — Multi-group taxonomy container with WoRMS integration stubs - resolve_worms_link() — Look up WoRMS taxon by name (stub function) - batch_resolve_worms_taxonomy() — Batch resolution for multiple groups

Integration with biodata.py: - integrate_taxonomy_with_biodata() — Merge taxonomy with FishBase/WoRMS data - resolve_worms_taxonomy() — Fetch and store WoRMS records - sync_taxonomy_with_rpath() — Sync TaxonomyLinkage with RpathParams

Size Distribution System (Phase 1B.3)

Population size structure and age-size conversions for age-structured modeling and Individual-Based Model (IBM) frameworks.

pypath.core.size

Size-structured population analysis using EwE PSD tables.

Phase 1B.3: TG3.3 Size Distribution System

This module implements size-structured population analysis for aquatic groups, including size class definitions, population size distributions (PSD), and von Bertalanffy growth function integration for age-size conversions.

SizeClass dataclass

A single size interval for population structure analysis.

Parameters:

Name Type Description Default
size_min float

Minimum size of the interval.

required
size_max float

Maximum size of the interval.

required
size_unit str

Unit of size measurement ('cm' or 'mm').

'cm'

Attributes:

Name Type Description
size_min, size_max float

Interval boundaries (inclusive).

size_unit str

Unit (default 'cm').

Source code in pypath/core/size.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
@dataclass
class SizeClass:
    """A single size interval for population structure analysis.

    Parameters
    ----------
    size_min : float
        Minimum size of the interval.
    size_max : float
        Maximum size of the interval.
    size_unit : str
        Unit of size measurement ('cm' or 'mm').

    Attributes
    ----------
    size_min, size_max : float
        Interval boundaries (inclusive).
    size_unit : str
        Unit (default 'cm').
    """

    size_min: float
    size_max: float
    size_unit: str = "cm"

    def __post_init__(self) -> None:
        """Validate size_min, size_max, and size_unit after initialization."""
        if self.size_min >= self.size_max:
            raise ValueError(
                f"size_min ({self.size_min}) must be less than "
                f"size_max ({self.size_max})"
            )
        if self.size_unit not in ("cm", "mm"):
            raise ValueError(f"size_unit must be 'cm' or 'mm', got {self.size_unit}")

    def midpoint(self) -> float:
        """Return the midpoint of the size interval.

        Returns
        -------
        float
            Midpoint: (size_min + size_max) / 2.
        """
        return (self.size_min + self.size_max) / 2.0

    def width(self) -> float:
        """Return the width of the size interval.

        Returns
        -------
        float
            Width: size_max - size_min.
        """
        return self.size_max - self.size_min

    def contains(self, size: float) -> bool:
        """Check if a size value falls within this interval.

        Parameters
        ----------
        size : float
            Size value to check.

        Returns
        -------
        bool
            True if size_min <= size < size_max.
        """
        return self.size_min <= size < self.size_max
__post_init__
__post_init__() -> None

Validate size_min, size_max, and size_unit after initialization.

Source code in pypath/core/size.py
47
48
49
50
51
52
53
54
55
def __post_init__(self) -> None:
    """Validate size_min, size_max, and size_unit after initialization."""
    if self.size_min >= self.size_max:
        raise ValueError(
            f"size_min ({self.size_min}) must be less than "
            f"size_max ({self.size_max})"
        )
    if self.size_unit not in ("cm", "mm"):
        raise ValueError(f"size_unit must be 'cm' or 'mm', got {self.size_unit}")
midpoint
midpoint() -> float

Return the midpoint of the size interval.

Returns:

Type Description
float

Midpoint: (size_min + size_max) / 2.

Source code in pypath/core/size.py
57
58
59
60
61
62
63
64
65
def midpoint(self) -> float:
    """Return the midpoint of the size interval.

    Returns
    -------
    float
        Midpoint: (size_min + size_max) / 2.
    """
    return (self.size_min + self.size_max) / 2.0
width
width() -> float

Return the width of the size interval.

Returns:

Type Description
float

Width: size_max - size_min.

Source code in pypath/core/size.py
67
68
69
70
71
72
73
74
75
def width(self) -> float:
    """Return the width of the size interval.

    Returns
    -------
    float
        Width: size_max - size_min.
    """
    return self.size_max - self.size_min
contains
contains(size: float) -> bool

Check if a size value falls within this interval.

Parameters:

Name Type Description Default
size float

Size value to check.

required

Returns:

Type Description
bool

True if size_min <= size < size_max.

Source code in pypath/core/size.py
77
78
79
80
81
82
83
84
85
86
87
88
89
90
def contains(self, size: float) -> bool:
    """Check if a size value falls within this interval.

    Parameters
    ----------
    size : float
        Size value to check.

    Returns
    -------
    bool
        True if size_min <= size < size_max.
    """
    return self.size_min <= size < self.size_max

SizeDistribution dataclass

Population size distribution (PSD) for a group.

Represents the count or biomass distribution across size classes, typically imported from EwE PSD (Population Size Distribution) tables.

Parameters:

Name Type Description Default
group_name str

Name of the group (e.g., "Herring").

required
size_classes list[SizeClass]

Ordered list of size intervals.

list()
counts ndarray

Individual counts per size class (1D array, same length as size_classes).

(lambda: array([], dtype=float64))()

Attributes:

Name Type Description
group_name str

Unique identifier for the group.

size_classes list[SizeClass]

Size intervals (assumed to be non-overlapping and ordered).

counts ndarray

Count array (float64).

Source code in pypath/core/size.py
 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
@dataclass
class SizeDistribution:
    """Population size distribution (PSD) for a group.

    Represents the count or biomass distribution across size classes,
    typically imported from EwE PSD (Population Size Distribution) tables.

    Parameters
    ----------
    group_name : str
        Name of the group (e.g., "Herring").
    size_classes : list[SizeClass]
        Ordered list of size intervals.
    counts : np.ndarray
        Individual counts per size class (1D array, same length as size_classes).

    Attributes
    ----------
    group_name : str
        Unique identifier for the group.
    size_classes : list[SizeClass]
        Size intervals (assumed to be non-overlapping and ordered).
    counts : np.ndarray
        Count array (float64).
    """

    group_name: str
    size_classes: list[SizeClass] = field(default_factory=list)
    counts: np.ndarray = field(default_factory=lambda: np.array([], dtype=np.float64))

    def __post_init__(self) -> None:
        """Validate that size_classes and counts have matching lengths."""
        if len(self.size_classes) != len(self.counts):
            raise ValueError(
                f"Number of size classes ({len(self.size_classes)}) must "
                f"match number of counts ({len(self.counts)})"
            )

    def is_valid(self) -> bool:
        """Validate the size distribution for consistency.

        Checks that:
        - size_classes and counts have matching lengths
        - all counts are non-negative
        - size intervals are ordered and non-overlapping

        Returns
        -------
        bool
            True if valid.
        """
        if len(self.size_classes) == 0:
            logger.warning(f"Empty size distribution for {self.group_name}")
            return False

        if len(self.size_classes) != len(self.counts):
            logger.error(
                f"{self.group_name}: size_classes ({len(self.size_classes)}) "
                f"!= counts ({len(self.counts)})"
            )
            return False

        if np.any(self.counts < 0):
            logger.error(f"{self.group_name}: negative counts detected")
            return False

        for i, sc in enumerate(self.size_classes):
            if sc.size_min >= sc.size_max:
                logger.error(f"{self.group_name} class {i}: size_min >= size_max")
                return False

        for i in range(len(self.size_classes) - 1):
            if self.size_classes[i].size_max > self.size_classes[i + 1].size_min:
                logger.error(f"{self.group_name}: overlapping size classes at {i}")
                return False

        return True

    def total_count(self) -> float:
        """Return total individuals across all size classes.

        Returns
        -------
        float
            Sum of all counts.
        """
        return float(np.sum(self.counts))

    def mean_size(self) -> float:
        """Compute mean size (weighted by counts).

        Returns
        -------
        float
            Weighted mean midpoint across size classes.
        """
        if self.total_count() == 0:
            logger.warning(f"{self.group_name}: total_count is 0")
            return 0.0

        midpoints = np.array([sc.midpoint() for sc in self.size_classes])
        return float(np.average(midpoints, weights=self.counts))

    def to_dataframe(self) -> pd.DataFrame:
        """Export size distribution to DataFrame.

        Returns
        -------
        pd.DataFrame
            Columns: ['group_name', 'size_min', 'size_max', 'size_unit',
                     'midpoint', 'width', 'count'].
        """
        data = []
        for sc, count in zip(self.size_classes, self.counts):
            data.append(
                {
                    "group_name": self.group_name,
                    "size_min": sc.size_min,
                    "size_max": sc.size_max,
                    "size_unit": sc.size_unit,
                    "midpoint": sc.midpoint(),
                    "width": sc.width(),
                    "count": count,
                }
            )
        return pd.DataFrame(data)

    @classmethod
    def from_dataframe(cls, df: pd.DataFrame, group_name: str) -> SizeDistribution:
        """Load size distribution from DataFrame.

        Parameters
        ----------
        df : pd.DataFrame
            DataFrame with columns: size_min, size_max, size_unit, count.
            May also contain: midpoint, width (ignored).
        group_name : str
            Group identifier.

        Returns
        -------
        SizeDistribution
            Reconstructed distribution object.
        """
        required_cols = {"size_min", "size_max", "count"}
        if not required_cols.issubset(df.columns):
            raise ValueError(f"DataFrame missing required columns: {required_cols}")

        size_classes = []
        counts = []

        for _, row in df.iterrows():
            size_unit = row.get("size_unit", "cm")
            sc = SizeClass(
                size_min=float(row["size_min"]),
                size_max=float(row["size_max"]),
                size_unit=size_unit,
            )
            size_classes.append(sc)
            counts.append(float(row["count"]))

        return cls(
            group_name=group_name,
            size_classes=size_classes,
            counts=np.array(counts, dtype=np.float64),
        )
__post_init__
__post_init__() -> None

Validate that size_classes and counts have matching lengths.

Source code in pypath/core/size.py
123
124
125
126
127
128
129
def __post_init__(self) -> None:
    """Validate that size_classes and counts have matching lengths."""
    if len(self.size_classes) != len(self.counts):
        raise ValueError(
            f"Number of size classes ({len(self.size_classes)}) must "
            f"match number of counts ({len(self.counts)})"
        )
is_valid
is_valid() -> bool

Validate the size distribution for consistency.

Checks that: - size_classes and counts have matching lengths - all counts are non-negative - size intervals are ordered and non-overlapping

Returns:

Type Description
bool

True if valid.

Source code in pypath/core/size.py
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
def is_valid(self) -> bool:
    """Validate the size distribution for consistency.

    Checks that:
    - size_classes and counts have matching lengths
    - all counts are non-negative
    - size intervals are ordered and non-overlapping

    Returns
    -------
    bool
        True if valid.
    """
    if len(self.size_classes) == 0:
        logger.warning(f"Empty size distribution for {self.group_name}")
        return False

    if len(self.size_classes) != len(self.counts):
        logger.error(
            f"{self.group_name}: size_classes ({len(self.size_classes)}) "
            f"!= counts ({len(self.counts)})"
        )
        return False

    if np.any(self.counts < 0):
        logger.error(f"{self.group_name}: negative counts detected")
        return False

    for i, sc in enumerate(self.size_classes):
        if sc.size_min >= sc.size_max:
            logger.error(f"{self.group_name} class {i}: size_min >= size_max")
            return False

    for i in range(len(self.size_classes) - 1):
        if self.size_classes[i].size_max > self.size_classes[i + 1].size_min:
            logger.error(f"{self.group_name}: overlapping size classes at {i}")
            return False

    return True
total_count
total_count() -> float

Return total individuals across all size classes.

Returns:

Type Description
float

Sum of all counts.

Source code in pypath/core/size.py
171
172
173
174
175
176
177
178
179
def total_count(self) -> float:
    """Return total individuals across all size classes.

    Returns
    -------
    float
        Sum of all counts.
    """
    return float(np.sum(self.counts))
mean_size
mean_size() -> float

Compute mean size (weighted by counts).

Returns:

Type Description
float

Weighted mean midpoint across size classes.

Source code in pypath/core/size.py
181
182
183
184
185
186
187
188
189
190
191
192
193
194
def mean_size(self) -> float:
    """Compute mean size (weighted by counts).

    Returns
    -------
    float
        Weighted mean midpoint across size classes.
    """
    if self.total_count() == 0:
        logger.warning(f"{self.group_name}: total_count is 0")
        return 0.0

    midpoints = np.array([sc.midpoint() for sc in self.size_classes])
    return float(np.average(midpoints, weights=self.counts))
to_dataframe
to_dataframe() -> pd.DataFrame

Export size distribution to DataFrame.

Returns:

Type Description
DataFrame

Columns: ['group_name', 'size_min', 'size_max', 'size_unit', 'midpoint', 'width', 'count'].

Source code in pypath/core/size.py
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
def to_dataframe(self) -> pd.DataFrame:
    """Export size distribution to DataFrame.

    Returns
    -------
    pd.DataFrame
        Columns: ['group_name', 'size_min', 'size_max', 'size_unit',
                 'midpoint', 'width', 'count'].
    """
    data = []
    for sc, count in zip(self.size_classes, self.counts):
        data.append(
            {
                "group_name": self.group_name,
                "size_min": sc.size_min,
                "size_max": sc.size_max,
                "size_unit": sc.size_unit,
                "midpoint": sc.midpoint(),
                "width": sc.width(),
                "count": count,
            }
        )
    return pd.DataFrame(data)
from_dataframe classmethod
from_dataframe(df: DataFrame, group_name: str) -> SizeDistribution

Load size distribution from DataFrame.

Parameters:

Name Type Description Default
df DataFrame

DataFrame with columns: size_min, size_max, size_unit, count. May also contain: midpoint, width (ignored).

required
group_name str

Group identifier.

required

Returns:

Type Description
SizeDistribution

Reconstructed distribution object.

Source code in pypath/core/size.py
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
@classmethod
def from_dataframe(cls, df: pd.DataFrame, group_name: str) -> SizeDistribution:
    """Load size distribution from DataFrame.

    Parameters
    ----------
    df : pd.DataFrame
        DataFrame with columns: size_min, size_max, size_unit, count.
        May also contain: midpoint, width (ignored).
    group_name : str
        Group identifier.

    Returns
    -------
    SizeDistribution
        Reconstructed distribution object.
    """
    required_cols = {"size_min", "size_max", "count"}
    if not required_cols.issubset(df.columns):
        raise ValueError(f"DataFrame missing required columns: {required_cols}")

    size_classes = []
    counts = []

    for _, row in df.iterrows():
        size_unit = row.get("size_unit", "cm")
        sc = SizeClass(
            size_min=float(row["size_min"]),
            size_max=float(row["size_max"]),
            size_unit=size_unit,
        )
        size_classes.append(sc)
        counts.append(float(row["count"]))

    return cls(
        group_name=group_name,
        size_classes=size_classes,
        counts=np.array(counts, dtype=np.float64),
    )

SizeStructure dataclass

Container for size distributions across multiple groups.

Manages a collection of SizeDistribution objects and provides validation and export methods.

Parameters:

Name Type Description Default
distributions dict[str, SizeDistribution]

Mapping from group_name to SizeDistribution.

dict()

Attributes:

Name Type Description
distributions dict[str, SizeDistribution]

Collection of PSD data by group.

Source code in pypath/core/size.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
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
@dataclass
class SizeStructure:
    """Container for size distributions across multiple groups.

    Manages a collection of SizeDistribution objects and provides
    validation and export methods.

    Parameters
    ----------
    distributions : dict[str, SizeDistribution]
        Mapping from group_name to SizeDistribution.

    Attributes
    ----------
    distributions : dict[str, SizeDistribution]
        Collection of PSD data by group.
    """

    distributions: dict[str, SizeDistribution] = field(default_factory=dict)

    def add_distribution(self, distribution: SizeDistribution) -> None:
        """Add or replace a size distribution.

        Parameters
        ----------
        distribution : SizeDistribution
            Distribution object to add.
        """
        self.distributions[distribution.group_name] = distribution
        logger.debug(f"Added size distribution for {distribution.group_name}")

    def get_distribution(self, group_name: str) -> Optional[SizeDistribution]:
        """Retrieve a size distribution by group name.

        Parameters
        ----------
        group_name : str
            Name of the group.

        Returns
        -------
        SizeDistribution | None
            Distribution if found, else None.
        """
        return self.distributions.get(group_name)

    def validate(self) -> tuple[bool, list[str]]:
        """Validate all distributions for consistency.

        Returns
        -------
        tuple[bool, list[str]]
            (is_valid, error_messages). If is_valid is False, error_messages
            contains diagnostic details.
        """
        errors = []

        if len(self.distributions) == 0:
            errors.append("No distributions defined")
            return False, errors

        for group_name, dist in self.distributions.items():
            if not dist.is_valid():
                errors.append(f"{group_name}: distribution is invalid")

        return len(errors) == 0, errors

    def to_dataframe(self) -> pd.DataFrame:
        """Export all distributions to a single DataFrame.

        Returns
        -------
        pd.DataFrame
            Combined DataFrame with rows for all size classes across all groups.
            Columns: ['group_name', 'size_min', 'size_max', 'size_unit',
                     'midpoint', 'width', 'count'].
        """
        dfs = [dist.to_dataframe() for dist in self.distributions.values()]
        if not dfs:
            return pd.DataFrame()
        return pd.concat(dfs, ignore_index=True)

    @classmethod
    def from_dataframe(cls, df: pd.DataFrame) -> SizeStructure:
        """Load size distributions from DataFrame.

        Parameters
        ----------
        df : pd.DataFrame
            Combined DataFrame with a 'group_name' column grouping rows.
            Expected columns: group_name, size_min, size_max, size_unit, count.

        Returns
        -------
        SizeStructure
            Reconstructed structure with distributions for each unique group.
        """
        ss = cls()

        if "group_name" not in df.columns:
            raise ValueError("DataFrame must contain 'group_name' column")

        for group_name, group_df in df.groupby("group_name"):
            dist = SizeDistribution.from_dataframe(
                group_df.reset_index(drop=True), str(group_name)
            )
            ss.add_distribution(dist)

        return ss
add_distribution
add_distribution(distribution: SizeDistribution) -> None

Add or replace a size distribution.

Parameters:

Name Type Description Default
distribution SizeDistribution

Distribution object to add.

required
Source code in pypath/core/size.py
281
282
283
284
285
286
287
288
289
290
def add_distribution(self, distribution: SizeDistribution) -> None:
    """Add or replace a size distribution.

    Parameters
    ----------
    distribution : SizeDistribution
        Distribution object to add.
    """
    self.distributions[distribution.group_name] = distribution
    logger.debug(f"Added size distribution for {distribution.group_name}")
get_distribution
get_distribution(group_name: str) -> Optional[SizeDistribution]

Retrieve a size distribution by group name.

Parameters:

Name Type Description Default
group_name str

Name of the group.

required

Returns:

Type Description
SizeDistribution | None

Distribution if found, else None.

Source code in pypath/core/size.py
292
293
294
295
296
297
298
299
300
301
302
303
304
305
def get_distribution(self, group_name: str) -> Optional[SizeDistribution]:
    """Retrieve a size distribution by group name.

    Parameters
    ----------
    group_name : str
        Name of the group.

    Returns
    -------
    SizeDistribution | None
        Distribution if found, else None.
    """
    return self.distributions.get(group_name)
validate
validate() -> tuple[bool, list[str]]

Validate all distributions for consistency.

Returns:

Type Description
tuple[bool, list[str]]

(is_valid, error_messages). If is_valid is False, error_messages contains diagnostic details.

Source code in pypath/core/size.py
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
def validate(self) -> tuple[bool, list[str]]:
    """Validate all distributions for consistency.

    Returns
    -------
    tuple[bool, list[str]]
        (is_valid, error_messages). If is_valid is False, error_messages
        contains diagnostic details.
    """
    errors = []

    if len(self.distributions) == 0:
        errors.append("No distributions defined")
        return False, errors

    for group_name, dist in self.distributions.items():
        if not dist.is_valid():
            errors.append(f"{group_name}: distribution is invalid")

    return len(errors) == 0, errors
to_dataframe
to_dataframe() -> pd.DataFrame

Export all distributions to a single DataFrame.

Returns:

Type Description
DataFrame

Combined DataFrame with rows for all size classes across all groups. Columns: ['group_name', 'size_min', 'size_max', 'size_unit', 'midpoint', 'width', 'count'].

Source code in pypath/core/size.py
328
329
330
331
332
333
334
335
336
337
338
339
340
341
def to_dataframe(self) -> pd.DataFrame:
    """Export all distributions to a single DataFrame.

    Returns
    -------
    pd.DataFrame
        Combined DataFrame with rows for all size classes across all groups.
        Columns: ['group_name', 'size_min', 'size_max', 'size_unit',
                 'midpoint', 'width', 'count'].
    """
    dfs = [dist.to_dataframe() for dist in self.distributions.values()]
    if not dfs:
        return pd.DataFrame()
    return pd.concat(dfs, ignore_index=True)
from_dataframe classmethod
from_dataframe(df: DataFrame) -> SizeStructure

Load size distributions from DataFrame.

Parameters:

Name Type Description Default
df DataFrame

Combined DataFrame with a 'group_name' column grouping rows. Expected columns: group_name, size_min, size_max, size_unit, count.

required

Returns:

Type Description
SizeStructure

Reconstructed structure with distributions for each unique group.

Source code in pypath/core/size.py
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
@classmethod
def from_dataframe(cls, df: pd.DataFrame) -> SizeStructure:
    """Load size distributions from DataFrame.

    Parameters
    ----------
    df : pd.DataFrame
        Combined DataFrame with a 'group_name' column grouping rows.
        Expected columns: group_name, size_min, size_max, size_unit, count.

    Returns
    -------
    SizeStructure
        Reconstructed structure with distributions for each unique group.
    """
    ss = cls()

    if "group_name" not in df.columns:
        raise ValueError("DataFrame must contain 'group_name' column")

    for group_name, group_df in df.groupby("group_name"):
        dist = SizeDistribution.from_dataframe(
            group_df.reset_index(drop=True), str(group_name)
        )
        ss.add_distribution(dist)

    return ss

vb_length

vb_length(age: float, loo: float, k: float, t0: float = 0.0) -> float

Von Bertalanffy length at age.

Computes length given age using the von Bertalanffy growth function: L(t) = L∞ * (1 - exp(-k * (t - t₀)))

Parameters:

Name Type Description Default
age float

Age in years.

required
loo float

Asymptotic (maximum) length (same units as returned value).

required
k float

Growth constant (year⁻¹).

required
t0 float

Theoretical age at length 0 (years, default 0.0).

0.0

Returns:

Type Description
float

Length at the given age.

Source code in pypath/core/size.py
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
def vb_length(age: float, loo: float, k: float, t0: float = 0.0) -> float:
    """Von Bertalanffy length at age.

    Computes length given age using the von Bertalanffy growth function:
    L(t) = L∞ * (1 - exp(-k * (t - t₀)))

    Parameters
    ----------
    age : float
        Age in years.
    loo : float
        Asymptotic (maximum) length (same units as returned value).
    k : float
        Growth constant (year⁻¹).
    t0 : float, optional
        Theoretical age at length 0 (years, default 0.0).

    Returns
    -------
    float
        Length at the given age.
    """
    if k <= 0:
        raise ValueError("k must be positive")
    return loo * (1.0 - np.exp(-k * (age - t0)))

vb_age

vb_age(length: float, loo: float, k: float, t0: float = 0.0) -> float

Age from von Bertalanffy length.

Inverts the von Bertalanffy equation to compute age given length: t = t₀ - ln(1 - L / L∞) / k

Parameters:

Name Type Description Default
length float

Length in same units as loo.

required
loo float

Asymptotic length.

required
k float

Growth constant (year⁻¹).

required
t0 float

Theoretical age at length 0 (years, default 0.0).

0.0

Returns:

Type Description
float

Age in years corresponding to the given length.

Raises:

Type Description
ValueError

If length >= loo or k <= 0.

Source code in pypath/core/size.py
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
def vb_age(length: float, loo: float, k: float, t0: float = 0.0) -> float:
    """Age from von Bertalanffy length.

    Inverts the von Bertalanffy equation to compute age given length:
    t = t₀ - ln(1 - L / L∞) / k

    Parameters
    ----------
    length : float
        Length in same units as loo.
    loo : float
        Asymptotic length.
    k : float
        Growth constant (year⁻¹).
    t0 : float, optional
        Theoretical age at length 0 (years, default 0.0).

    Returns
    -------
    float
        Age in years corresponding to the given length.

    Raises
    ------
    ValueError
        If length >= loo or k <= 0.
    """
    if k <= 0:
        raise ValueError("k must be positive")
    if length >= loo:
        raise ValueError("length must be less than loo (L∞)")

    return t0 - np.log(1.0 - length / loo) / k

age_at_size_class

age_at_size_class(size_class: SizeClass, loo: float, k: float, t0: float = 0.0) -> tuple[float, float]

Compute age range for a size class using von Bertalanffy.

Given a size interval, computes the corresponding age interval using the inverse von Bertalanffy function.

Parameters:

Name Type Description Default
size_class SizeClass

Size interval (min, max).

required
loo float

Asymptotic length in same units as size_class.

required
k float

Growth constant (year⁻¹).

required
t0 float

Theoretical age at length 0 (default 0.0).

0.0

Returns:

Type Description
tuple[float, float]

(age_at_min, age_at_max) in years. age_at_max corresponds to size_min, age_at_min corresponds to size_max (inverse relationship).

Source code in pypath/core/size.py
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
def age_at_size_class(
    size_class: SizeClass, loo: float, k: float, t0: float = 0.0
) -> tuple[float, float]:
    """Compute age range for a size class using von Bertalanffy.

    Given a size interval, computes the corresponding age interval using
    the inverse von Bertalanffy function.

    Parameters
    ----------
    size_class : SizeClass
        Size interval (min, max).
    loo : float
        Asymptotic length in same units as size_class.
    k : float
        Growth constant (year⁻¹).
    t0 : float, optional
        Theoretical age at length 0 (default 0.0).

    Returns
    -------
    tuple[float, float]
        (age_at_min, age_at_max) in years. age_at_max corresponds to
        size_min, age_at_min corresponds to size_max (inverse relationship).
    """
    age_at_min = vb_age(size_class.size_min, loo, k, t0)
    age_at_max = vb_age(size_class.size_max, loo, k, t0)
    return (age_at_min, age_at_max)

validate_size_structure

validate_size_structure(structure: SizeStructure) -> tuple[bool, list[str]]

Comprehensive validation of a SizeStructure.

Checks for: - Missing or empty distributions - Overlapping or gapped size ranges - Negative or inconsistent counts - Size classes not ordered

Parameters:

Name Type Description Default
structure SizeStructure

Size structure to validate.

required

Returns:

Type Description
tuple[bool, list[str]]

(is_valid, error_messages).

Source code in pypath/core/size.py
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
def validate_size_structure(
    structure: SizeStructure,
) -> tuple[bool, list[str]]:
    """Comprehensive validation of a SizeStructure.

    Checks for:
    - Missing or empty distributions
    - Overlapping or gapped size ranges
    - Negative or inconsistent counts
    - Size classes not ordered

    Parameters
    ----------
    structure : SizeStructure
        Size structure to validate.

    Returns
    -------
    tuple[bool, list[str]]
        (is_valid, error_messages).
    """
    is_valid, errors = structure.validate()

    if not is_valid:
        return False, errors

    for group_name, dist in structure.distributions.items():
        if len(dist.size_classes) < 2:
            errors.append(f"{group_name}: fewer than 2 size classes")

        for i in range(len(dist.size_classes) - 1):
            curr = dist.size_classes[i]
            next_ = dist.size_classes[i + 1]

            if curr.size_max != next_.size_min:
                errors.append(
                    f"{group_name}: gap/overlap between classes {i} and {i + 1} "
                    f"({curr.size_max} vs {next_.size_min})"
                )

    return len(errors) == 0, errors

estimate_psd_from_vb

estimate_psd_from_vb(loo: float, k: float, t0: float, recruitment_rate: float, time_steps: int, n_size_classes: int, size_min: float = 0.1, size_max: float = 100.0, size_unit: str = 'cm', group_name: str = 'Group') -> SizeDistribution

Estimate PSD from von Bertalanffy growth parameters.

Generates a theoretical population size distribution by simulating cohorts of individuals aging under the von Bertalanffy growth function and applying recruitment. This is a simplified approach intended for initialization or sensitivity analysis.

Parameters:

Name Type Description Default
loo float

Asymptotic length.

required
k float

Growth constant (year⁻¹).

required
t0 float

Theoretical age at length 0 (years).

required
recruitment_rate float

Annual recruitment (new individuals per year).

required
time_steps int

Number of annual time steps to simulate.

required
n_size_classes int

Number of size classes to create.

required
size_min float

Minimum size (default 0.1, same units as loo).

0.1
size_max float

Maximum size (default 100.0).

100.0
size_unit str

Unit of measurement ('cm' or 'mm', default 'cm').

'cm'
group_name str

Group identifier (default 'Group').

'Group'

Returns:

Type Description
SizeDistribution

Theoretical PSD with uniform bin widths.

Notes

This function uses a simple discrete-age cohort model with no natural mortality. The distribution is for illustrative and initialization use; a full population model should include mortality and recruitment dynamics.

Source code in pypath/core/size.py
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
def estimate_psd_from_vb(
    loo: float,
    k: float,
    t0: float,
    recruitment_rate: float,
    time_steps: int,
    n_size_classes: int,
    size_min: float = 0.1,
    size_max: float = 100.0,
    size_unit: str = "cm",
    group_name: str = "Group",
) -> SizeDistribution:
    """Estimate PSD from von Bertalanffy growth parameters.

    Generates a theoretical population size distribution by simulating
    cohorts of individuals aging under the von Bertalanffy growth function
    and applying recruitment. This is a simplified approach intended for
    initialization or sensitivity analysis.

    Parameters
    ----------
    loo : float
        Asymptotic length.
    k : float
        Growth constant (year⁻¹).
    t0 : float
        Theoretical age at length 0 (years).
    recruitment_rate : float
        Annual recruitment (new individuals per year).
    time_steps : int
        Number of annual time steps to simulate.
    n_size_classes : int
        Number of size classes to create.
    size_min : float, optional
        Minimum size (default 0.1, same units as loo).
    size_max : float, optional
        Maximum size (default 100.0).
    size_unit : str, optional
        Unit of measurement ('cm' or 'mm', default 'cm').
    group_name : str, optional
        Group identifier (default 'Group').

    Returns
    -------
    SizeDistribution
        Theoretical PSD with uniform bin widths.

    Notes
    -----
    This function uses a simple discrete-age cohort model with no natural
    mortality. The distribution is for illustrative and initialization use;
    a full population model should include mortality and recruitment dynamics.
    """
    if k <= 0:
        raise ValueError("k must be positive")
    if n_size_classes < 1:
        raise ValueError("n_size_classes must be >= 1")

    bin_width = (size_max - size_min) / float(n_size_classes)
    size_classes = []
    for i in range(n_size_classes):
        sc = SizeClass(
            size_min=size_min + i * bin_width,
            size_max=size_min + (i + 1) * bin_width,
            size_unit=size_unit,
        )
        size_classes.append(sc)

    counts = np.zeros(n_size_classes, dtype=np.float64)

    for ts in range(time_steps):
        cohort_age = ts + 1
        cohort_size = vb_length(float(cohort_age), loo, k, t0)

        if cohort_size > size_max:
            cohort_size = size_max - 0.001

        for i, sc in enumerate(size_classes):
            if sc.contains(cohort_size):
                counts[i] += recruitment_rate
                break

    return SizeDistribution(
        group_name=group_name,
        size_classes=size_classes,
        counts=counts,
    )

Key Classes: - SizeClass — Size interval definition with midpoint, width, and contains logic - SizeDistribution — Population size distribution (PSD) container with statistics - SizeStructure — Multi-group size distributions with aggregation

Von Bertalanffy Functions: - vb_length(age, Loo, K, t0) — Age-to-length conversion - vb_age(length, Loo, K, t0) — Length-to-age conversion - age_at_size_class() — Estimate mean age from size interval - estimate_psd_from_vb() — Generate theoretical PSD from VBGF parameters

Fleet & Discard Dynamics (Phase 1B.4)

Dynamic fishing fleet management with gear types, catchability, effort allocation, and discard routing to multiple fates. Highest complexity Phase 1B module with integration to Ecosim fishing mortality.

pypath.core.fleet

Fishing fleet management, gear types, and discard routing.

This module implements fleet-based fishing dynamics, including gear classification, catchability by group, and discard fate allocation for Ecopath with Ecosim models.

Phase 1B.4: TG3.4 Fleet & Discard System

GearType

Bases: Enum

Fishing gear types with associated selectivity metadata.

Each gear type carries default bycatch rate and selectivity characteristics used in catch allocation and validation.

Attributes:

Name Type Description
SEINE GearType

Seine net (mid-water or bottom); moderate selectivity, low bycatch.

NET GearType

General net (gill, cast, etc.); moderate-high selectivity, variable bycatch.

TRAP GearType

Fish trap or pot; high selectivity, low bycatch.

TRAWL GearType

Trawl (bottom, mid-water, or pelagic); low selectivity, high bycatch.

HOOK GearType

Hook and line; very high selectivity, minimal bycatch.

OTHER GearType

Unspecified gear; assume moderate selectivity and bycatch.

Source code in pypath/core/fleet.py
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
class GearType(Enum):
    """Fishing gear types with associated selectivity metadata.

    Each gear type carries default bycatch rate and selectivity characteristics
    used in catch allocation and validation.

    Attributes
    ----------
    SEINE : GearType
        Seine net (mid-water or bottom); moderate selectivity, low bycatch.
    NET : GearType
        General net (gill, cast, etc.); moderate-high selectivity, variable bycatch.
    TRAP : GearType
        Fish trap or pot; high selectivity, low bycatch.
    TRAWL : GearType
        Trawl (bottom, mid-water, or pelagic); low selectivity, high bycatch.
    HOOK : GearType
        Hook and line; very high selectivity, minimal bycatch.
    OTHER : GearType
        Unspecified gear; assume moderate selectivity and bycatch.
    """

    SEINE = "Seine"
    NET = "Net"
    TRAP = "Trap"
    TRAWL = "Trawl"
    HOOK = "Hook"
    OTHER = "Other"

    def selectivity(self) -> float:
        """Return default selectivity for this gear type.

        Selectivity (0-1) represents how narrowly the gear targets intended species.
        Higher values = more selective (lower bycatch proportion).

        Returns
        -------
        float
            Selectivity coefficient (0.2-1.0).
        """
        selectivity_map = {
            GearType.SEINE: 0.65,
            GearType.NET: 0.60,
            GearType.TRAP: 0.85,
            GearType.TRAWL: 0.35,
            GearType.HOOK: 0.95,
            GearType.OTHER: 0.50,
        }
        return selectivity_map[self]

    def bycatch_rate(self) -> float:
        """Return default bycatch rate for this gear type.

        Bycatch rate (0-1) represents the proportion of non-target catch
        relative to target catch.

        Returns
        -------
        float
            Bycatch rate (0.0-0.8).
        """
        bycatch_map = {
            GearType.SEINE: 0.15,
            GearType.NET: 0.25,
            GearType.TRAP: 0.05,
            GearType.TRAWL: 0.60,
            GearType.HOOK: 0.02,
            GearType.OTHER: 0.30,
        }
        return bycatch_map[self]
selectivity
selectivity() -> float

Return default selectivity for this gear type.

Selectivity (0-1) represents how narrowly the gear targets intended species. Higher values = more selective (lower bycatch proportion).

Returns:

Type Description
float

Selectivity coefficient (0.2-1.0).

Source code in pypath/core/fleet.py
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
def selectivity(self) -> float:
    """Return default selectivity for this gear type.

    Selectivity (0-1) represents how narrowly the gear targets intended species.
    Higher values = more selective (lower bycatch proportion).

    Returns
    -------
    float
        Selectivity coefficient (0.2-1.0).
    """
    selectivity_map = {
        GearType.SEINE: 0.65,
        GearType.NET: 0.60,
        GearType.TRAP: 0.85,
        GearType.TRAWL: 0.35,
        GearType.HOOK: 0.95,
        GearType.OTHER: 0.50,
    }
    return selectivity_map[self]
bycatch_rate
bycatch_rate() -> float

Return default bycatch rate for this gear type.

Bycatch rate (0-1) represents the proportion of non-target catch relative to target catch.

Returns:

Type Description
float

Bycatch rate (0.0-0.8).

Source code in pypath/core/fleet.py
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
def bycatch_rate(self) -> float:
    """Return default bycatch rate for this gear type.

    Bycatch rate (0-1) represents the proportion of non-target catch
    relative to target catch.

    Returns
    -------
    float
        Bycatch rate (0.0-0.8).
    """
    bycatch_map = {
        GearType.SEINE: 0.15,
        GearType.NET: 0.25,
        GearType.TRAP: 0.05,
        GearType.TRAWL: 0.60,
        GearType.HOOK: 0.02,
        GearType.OTHER: 0.30,
    }
    return bycatch_map[self]

FleetGroup dataclass

A fishing fleet with effort, catchability, and gear composition.

Represents a commercial or subsistence fishing fleet targeting one or more groups. Effort is applied via catchability coefficients (q values) to compute catch from available biomass.

Parameters:

Name Type Description Default
name str

Fleet name (e.g., "Small-scale pelagic").

required
fleet_id int

Unique fleet identifier (0-based).

required
gears list[GearType]

List of gear types used by this fleet.

required
fuel_efficiency float

Fuel consumption (kg fuel per ton catch). Default 0.05.

0.05
base_effort float

Nominal effort (days or trips per year). Default 100.

100.0
catchability dict[str, float]

Catchability coefficients (q values) by group name. Maps group_name -> q.

dict()

Attributes:

Name Type Description
name str

Fleet name.

fleet_id int

Fleet identifier.

gears list[GearType]

Gear list.

fuel_efficiency float

Fuel per unit catch (0.01-0.20).

base_effort float

Baseline effort (>0).

catchability dict[str, float]

q values (0.0-1.0).

Raises:

Type Description
ValueError

If fleet_id < 0, base_effort <= 0, or catchability values out of bounds.

Source code in pypath/core/fleet.py
 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
@dataclass
class FleetGroup:
    """A fishing fleet with effort, catchability, and gear composition.

    Represents a commercial or subsistence fishing fleet targeting one or more
    groups. Effort is applied via catchability coefficients (q values) to
    compute catch from available biomass.

    Parameters
    ----------
    name : str
        Fleet name (e.g., "Small-scale pelagic").
    fleet_id : int
        Unique fleet identifier (0-based).
    gears : list[GearType]
        List of gear types used by this fleet.
    fuel_efficiency : float
        Fuel consumption (kg fuel per ton catch). Default 0.05.
    base_effort : float
        Nominal effort (days or trips per year). Default 100.
    catchability : dict[str, float]
        Catchability coefficients (q values) by group name. Maps group_name -> q.

    Attributes
    ----------
    name : str
        Fleet name.
    fleet_id : int
        Fleet identifier.
    gears : list[GearType]
        Gear list.
    fuel_efficiency : float
        Fuel per unit catch (0.01-0.20).
    base_effort : float
        Baseline effort (>0).
    catchability : dict[str, float]
        q values (0.0-1.0).

    Raises
    ------
    ValueError
        If fleet_id < 0, base_effort <= 0, or catchability values out of bounds.
    """

    name: str
    fleet_id: int
    gears: list[GearType]
    fuel_efficiency: float = 0.05
    base_effort: float = 100.0
    catchability: dict[str, float] = field(default_factory=dict)

    def __post_init__(self) -> None:
        """Validate fleet parameters after initialization."""
        if self.fleet_id < 0:
            raise ValueError(f"fleet_id must be >= 0, got {self.fleet_id}")
        if self.base_effort <= 0:
            raise ValueError(f"base_effort must be > 0, got {self.base_effort}")
        if self.fuel_efficiency < 0.01 or self.fuel_efficiency > 0.20:
            logger.warning(
                f"Fleet {self.name}: fuel_efficiency {self.fuel_efficiency} "
                "outside typical range [0.01, 0.20]"
            )
        if not self.gears:
            logger.warning(f"Fleet {self.name}: no gears specified")
        for group, q in self.catchability.items():
            if not (0.0 <= q <= 1.0):
                raise ValueError(f"Catchability for {group} must be in [0, 1], got {q}")

    def is_valid(self) -> bool:
        """Validate fleet definition for completeness.

        Checks that name, fleet_id, and at least one catchability value exist.

        Returns
        -------
        bool
            True if valid, False otherwise.
        """
        if not self.name or self.fleet_id < 0:
            return False
        if not self.catchability:
            return False
        return True

    def to_dict(self) -> dict:
        """Serialize fleet to dictionary.

        Returns
        -------
        dict
            Dictionary with keys: name, fleet_id, gears, fuel_efficiency,
            base_effort, catchability.
        """
        return {
            "name": self.name,
            "fleet_id": self.fleet_id,
            "gears": [g.value for g in self.gears],
            "fuel_efficiency": self.fuel_efficiency,
            "base_effort": self.base_effort,
            "catchability": self.catchability.copy(),
        }

    @classmethod
    def from_dict(cls, data: dict) -> FleetGroup:
        """Deserialize fleet from dictionary.

        Parameters
        ----------
        data : dict
            Dictionary with fleet parameters.

        Returns
        -------
        FleetGroup
            Reconstructed fleet instance.
        """
        gears = [GearType(g) for g in data.get("gears", [])]
        return cls(
            name=data["name"],
            fleet_id=data["fleet_id"],
            gears=gears,
            fuel_efficiency=data.get("fuel_efficiency", 0.05),
            base_effort=data.get("base_effort", 100.0),
            catchability=data.get("catchability", {}),
        )
__post_init__
__post_init__() -> None

Validate fleet parameters after initialization.

Source code in pypath/core/fleet.py
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
def __post_init__(self) -> None:
    """Validate fleet parameters after initialization."""
    if self.fleet_id < 0:
        raise ValueError(f"fleet_id must be >= 0, got {self.fleet_id}")
    if self.base_effort <= 0:
        raise ValueError(f"base_effort must be > 0, got {self.base_effort}")
    if self.fuel_efficiency < 0.01 or self.fuel_efficiency > 0.20:
        logger.warning(
            f"Fleet {self.name}: fuel_efficiency {self.fuel_efficiency} "
            "outside typical range [0.01, 0.20]"
        )
    if not self.gears:
        logger.warning(f"Fleet {self.name}: no gears specified")
    for group, q in self.catchability.items():
        if not (0.0 <= q <= 1.0):
            raise ValueError(f"Catchability for {group} must be in [0, 1], got {q}")
is_valid
is_valid() -> bool

Validate fleet definition for completeness.

Checks that name, fleet_id, and at least one catchability value exist.

Returns:

Type Description
bool

True if valid, False otherwise.

Source code in pypath/core/fleet.py
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
def is_valid(self) -> bool:
    """Validate fleet definition for completeness.

    Checks that name, fleet_id, and at least one catchability value exist.

    Returns
    -------
    bool
        True if valid, False otherwise.
    """
    if not self.name or self.fleet_id < 0:
        return False
    if not self.catchability:
        return False
    return True
to_dict
to_dict() -> dict

Serialize fleet to dictionary.

Returns:

Type Description
dict

Dictionary with keys: name, fleet_id, gears, fuel_efficiency, base_effort, catchability.

Source code in pypath/core/fleet.py
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
def to_dict(self) -> dict:
    """Serialize fleet to dictionary.

    Returns
    -------
    dict
        Dictionary with keys: name, fleet_id, gears, fuel_efficiency,
        base_effort, catchability.
    """
    return {
        "name": self.name,
        "fleet_id": self.fleet_id,
        "gears": [g.value for g in self.gears],
        "fuel_efficiency": self.fuel_efficiency,
        "base_effort": self.base_effort,
        "catchability": self.catchability.copy(),
    }
from_dict classmethod
from_dict(data: dict) -> FleetGroup

Deserialize fleet from dictionary.

Parameters:

Name Type Description Default
data dict

Dictionary with fleet parameters.

required

Returns:

Type Description
FleetGroup

Reconstructed fleet instance.

Source code in pypath/core/fleet.py
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
@classmethod
def from_dict(cls, data: dict) -> FleetGroup:
    """Deserialize fleet from dictionary.

    Parameters
    ----------
    data : dict
        Dictionary with fleet parameters.

    Returns
    -------
    FleetGroup
        Reconstructed fleet instance.
    """
    gears = [GearType(g) for g in data.get("gears", [])]
    return cls(
        name=data["name"],
        fleet_id=data["fleet_id"],
        gears=gears,
        fuel_efficiency=data.get("fuel_efficiency", 0.05),
        base_effort=data.get("base_effort", 100.0),
        catchability=data.get("catchability", {}),
    )

DiscardPath dataclass

Pathway for discarded catch to its fate.

Discards can be lost to the system (total mortality), routed to predators (as food), or deposited as detritus/benthos. Depth-dependent routing enables spatially-explicit discard fate in Ecospace.

Parameters:

Name Type Description Default
source_group str

Group name for the discarded catch (e.g., "Juvenile cod").

required
target_group str

Group that consumes discards (None for lost/detritus routing).

None
discard_rate float

Proportion discarded (0-1). Example: 0.15 = 15% discarded.

0.0
fate str

Discard fate ('lost', 'predation', 'detritus', 'benthos'). - 'lost': mortality (biomass removed from system) - 'predation': biomass routed to target_group - 'detritus': enters detritus pool - 'benthos': enters benthic organic matter pool

'lost'
depth_dependent bool

If True, discard fate depends on water column position (Ecospace).

False

Attributes:

Name Type Description
source_group str

Source group name.

target_group str | None

Target group name (or None).

discard_rate float

Proportion discarded (0.0-1.0).

fate str

Fate category.

depth_dependent bool

Spatially-explicit routing flag.

Raises:

Type Description
ValueError

If discard_rate not in [0, 1] or fate not in valid categories.

Source code in pypath/core/fleet.py
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
@dataclass
class DiscardPath:
    """Pathway for discarded catch to its fate.

    Discards can be lost to the system (total mortality), routed to predators
    (as food), or deposited as detritus/benthos. Depth-dependent routing
    enables spatially-explicit discard fate in Ecospace.

    Parameters
    ----------
    source_group : str
        Group name for the discarded catch (e.g., "Juvenile cod").
    target_group : str, optional
        Group that consumes discards (None for lost/detritus routing).
    discard_rate : float
        Proportion discarded (0-1). Example: 0.15 = 15% discarded.
    fate : str
        Discard fate ('lost', 'predation', 'detritus', 'benthos').
        - 'lost': mortality (biomass removed from system)
        - 'predation': biomass routed to target_group
        - 'detritus': enters detritus pool
        - 'benthos': enters benthic organic matter pool
    depth_dependent : bool
        If True, discard fate depends on water column position (Ecospace).

    Attributes
    ----------
    source_group : str
        Source group name.
    target_group : str | None
        Target group name (or None).
    discard_rate : float
        Proportion discarded (0.0-1.0).
    fate : str
        Fate category.
    depth_dependent : bool
        Spatially-explicit routing flag.

    Raises
    ------
    ValueError
        If discard_rate not in [0, 1] or fate not in valid categories.
    """

    source_group: str
    target_group: Optional[str] = None
    discard_rate: float = 0.0
    fate: str = "lost"
    depth_dependent: bool = False

    def __post_init__(self) -> None:
        """Validate discard path parameters after initialization."""
        if not (0.0 <= self.discard_rate <= 1.0):
            raise ValueError(f"discard_rate must be in [0, 1], got {self.discard_rate}")
        valid_fates = ("lost", "predation", "detritus", "benthos")
        if self.fate not in valid_fates:
            raise ValueError(f"fate must be one of {valid_fates}, got {self.fate}")
        if self.fate == "predation" and not self.target_group:
            raise ValueError("fate='predation' requires target_group to be specified")

    def is_valid(self) -> bool:
        """Validate discard path for consistency.

        Checks that source_group exists and fate-group combinations are valid.

        Returns
        -------
        bool
            True if valid, False otherwise.
        """
        if not self.source_group:
            return False
        if self.fate == "predation" and not self.target_group:
            return False
        if not (0.0 <= self.discard_rate <= 1.0):
            return False
        return True

    def apply_to_biomass(self, biomass: float) -> float:
        """Calculate discard biomass from total catch.

        Parameters
        ----------
        biomass : float
            Total catch biomass (tons).

        Returns
        -------
        float
            Discard biomass (tons).
        """
        return biomass * self.discard_rate

    def to_dict(self) -> dict:
        """Serialize discard path to dictionary.

        Returns
        -------
        dict
            Dictionary representation.
        """
        return {
            "source_group": self.source_group,
            "target_group": self.target_group,
            "discard_rate": self.discard_rate,
            "fate": self.fate,
            "depth_dependent": self.depth_dependent,
        }

    @classmethod
    def from_dict(cls, data: dict) -> DiscardPath:
        """Deserialize discard path from dictionary.

        Parameters
        ----------
        data : dict
            Dictionary with discard path parameters.

        Returns
        -------
        DiscardPath
            Reconstructed discard path instance.
        """
        return cls(
            source_group=data["source_group"],
            target_group=data.get("target_group"),
            discard_rate=data.get("discard_rate", 0.0),
            fate=data.get("fate", "lost"),
            depth_dependent=data.get("depth_dependent", False),
        )
__post_init__
__post_init__() -> None

Validate discard path parameters after initialization.

Source code in pypath/core/fleet.py
270
271
272
273
274
275
276
277
278
def __post_init__(self) -> None:
    """Validate discard path parameters after initialization."""
    if not (0.0 <= self.discard_rate <= 1.0):
        raise ValueError(f"discard_rate must be in [0, 1], got {self.discard_rate}")
    valid_fates = ("lost", "predation", "detritus", "benthos")
    if self.fate not in valid_fates:
        raise ValueError(f"fate must be one of {valid_fates}, got {self.fate}")
    if self.fate == "predation" and not self.target_group:
        raise ValueError("fate='predation' requires target_group to be specified")
is_valid
is_valid() -> bool

Validate discard path for consistency.

Checks that source_group exists and fate-group combinations are valid.

Returns:

Type Description
bool

True if valid, False otherwise.

Source code in pypath/core/fleet.py
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
def is_valid(self) -> bool:
    """Validate discard path for consistency.

    Checks that source_group exists and fate-group combinations are valid.

    Returns
    -------
    bool
        True if valid, False otherwise.
    """
    if not self.source_group:
        return False
    if self.fate == "predation" and not self.target_group:
        return False
    if not (0.0 <= self.discard_rate <= 1.0):
        return False
    return True
apply_to_biomass
apply_to_biomass(biomass: float) -> float

Calculate discard biomass from total catch.

Parameters:

Name Type Description Default
biomass float

Total catch biomass (tons).

required

Returns:

Type Description
float

Discard biomass (tons).

Source code in pypath/core/fleet.py
298
299
300
301
302
303
304
305
306
307
308
309
310
311
def apply_to_biomass(self, biomass: float) -> float:
    """Calculate discard biomass from total catch.

    Parameters
    ----------
    biomass : float
        Total catch biomass (tons).

    Returns
    -------
    float
        Discard biomass (tons).
    """
    return biomass * self.discard_rate
to_dict
to_dict() -> dict

Serialize discard path to dictionary.

Returns:

Type Description
dict

Dictionary representation.

Source code in pypath/core/fleet.py
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
def to_dict(self) -> dict:
    """Serialize discard path to dictionary.

    Returns
    -------
    dict
        Dictionary representation.
    """
    return {
        "source_group": self.source_group,
        "target_group": self.target_group,
        "discard_rate": self.discard_rate,
        "fate": self.fate,
        "depth_dependent": self.depth_dependent,
    }
from_dict classmethod
from_dict(data: dict) -> DiscardPath

Deserialize discard path from dictionary.

Parameters:

Name Type Description Default
data dict

Dictionary with discard path parameters.

required

Returns:

Type Description
DiscardPath

Reconstructed discard path instance.

Source code in pypath/core/fleet.py
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
@classmethod
def from_dict(cls, data: dict) -> DiscardPath:
    """Deserialize discard path from dictionary.

    Parameters
    ----------
    data : dict
        Dictionary with discard path parameters.

    Returns
    -------
    DiscardPath
        Reconstructed discard path instance.
    """
    return cls(
        source_group=data["source_group"],
        target_group=data.get("target_group"),
        discard_rate=data.get("discard_rate", 0.0),
        fate=data.get("fate", "lost"),
        depth_dependent=data.get("depth_dependent", False),
    )

FleetDynamics dataclass

Container for fleet groups and discard routing rules.

Manages collection of fleets and discard paths, with validation and application methods for catch allocation and discard fate routing.

Parameters:

Name Type Description Default
fleets dict[str, FleetGroup]

Fleet groups indexed by name. Default empty dict.

dict()
discard_paths dict[str, list[DiscardPath]]

Discard paths indexed by source_group. Default empty dict.

dict()

Attributes:

Name Type Description
fleets dict[str, FleetGroup]

Active fleets.

discard_paths dict[str, list[DiscardPath]]

Discard routing rules.

Source code in pypath/core/fleet.py
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
@dataclass
class FleetDynamics:
    """Container for fleet groups and discard routing rules.

    Manages collection of fleets and discard paths, with validation and
    application methods for catch allocation and discard fate routing.

    Parameters
    ----------
    fleets : dict[str, FleetGroup]
        Fleet groups indexed by name. Default empty dict.
    discard_paths : dict[str, list[DiscardPath]]
        Discard paths indexed by source_group. Default empty dict.

    Attributes
    ----------
    fleets : dict[str, FleetGroup]
        Active fleets.
    discard_paths : dict[str, list[DiscardPath]]
        Discard routing rules.
    """

    fleets: dict[str, FleetGroup] = field(default_factory=dict)
    discard_paths: dict[str, list[DiscardPath]] = field(default_factory=dict)

    def add_fleet(self, fleet: FleetGroup) -> None:
        """Add or replace a fleet.

        Parameters
        ----------
        fleet : FleetGroup
            Fleet to add. If a fleet with the same name exists, it is replaced.
        """
        if not fleet.is_valid():
            logger.warning(f"Fleet {fleet.name} is not valid; adding anyway")
        self.fleets[fleet.name] = fleet
        logger.debug(f"Added fleet: {fleet.name} (ID: {fleet.fleet_id})")

    def add_discard_path(self, path: DiscardPath) -> None:
        """Add a discard path.

        Parameters
        ----------
        path : DiscardPath
            Discard path to add.
        """
        if not path.is_valid():
            logger.warning(f"Discard path for {path.source_group} is not valid")
        if path.source_group not in self.discard_paths:
            self.discard_paths[path.source_group] = []
        self.discard_paths[path.source_group].append(path)
        logger.debug(
            f"Added discard path: {path.source_group} -> {path.target_group} "
            f"({path.fate})"
        )

    def get_fleet(self, name: str) -> Optional[FleetGroup]:
        """Retrieve a fleet by name.

        Parameters
        ----------
        name : str
            Fleet name.

        Returns
        -------
        FleetGroup | None
            Fleet if found, None otherwise.
        """
        return self.fleets.get(name)

    def validate(self) -> tuple[bool, list[str]]:
        """Validate fleet dynamics configuration.

        Checks that:
        - All fleets are valid
        - All discard paths are valid
        - Referenced groups exist (soft check: logged as warning, not error)

        Returns
        -------
        tuple[bool, list[str]]
            (is_valid, error_messages). is_valid=True only if all checks pass.
        """
        errors = []
        for fleet in self.fleets.values():
            if not fleet.is_valid():
                errors.append(f"Fleet {fleet.name} is not valid")
        for source, paths in self.discard_paths.items():
            for path in paths:
                if not path.is_valid():
                    errors.append(
                        f"Discard path {source} -> {path.target_group} is not valid"
                    )
        return len(errors) == 0, errors

    def to_dataframe(self) -> dict[str, pd.DataFrame]:
        """Convert fleet dynamics to DataFrame representation.

        Returns
        -------
        dict[str, pd.DataFrame]
            Dictionary with keys 'fleets' and 'discards', each a DataFrame.
            - fleets: columns [name, fleet_id, gears, fuel_efficiency,
              base_effort, catchability (dict column)]
            - discards: columns [source_group, target_group, discard_rate,
              fate, depth_dependent]
        """
        fleets_data = [f.to_dict() for f in self.fleets.values()]
        fleets_df = pd.DataFrame(fleets_data) if fleets_data else pd.DataFrame()

        discards_data = []
        for paths in self.discard_paths.values():
            discards_data.extend([p.to_dict() for p in paths])
        discards_df = pd.DataFrame(discards_data) if discards_data else pd.DataFrame()

        return {"fleets": fleets_df, "discards": discards_df}

    @classmethod
    def from_dataframe(
        cls, fleets_df: pd.DataFrame, discards_df: pd.DataFrame
    ) -> FleetDynamics:
        """Reconstruct fleet dynamics from DataFrames.

        Parameters
        ----------
        fleets_df : pd.DataFrame
            Fleet data (as returned by to_dataframe()['fleets']).
        discards_df : pd.DataFrame
            Discard data (as returned by to_dataframe()['discards']).

        Returns
        -------
        FleetDynamics
            Reconstructed fleet dynamics instance.
        """
        fd = cls()
        for _, row in fleets_df.iterrows():
            fleet_dict = row.to_dict()
            fd.add_fleet(FleetGroup.from_dict(fleet_dict))
        for _, row in discards_df.iterrows():
            path_dict = row.to_dict()
            fd.add_discard_path(DiscardPath.from_dict(path_dict))
        return fd
add_fleet
add_fleet(fleet: FleetGroup) -> None

Add or replace a fleet.

Parameters:

Name Type Description Default
fleet FleetGroup

Fleet to add. If a fleet with the same name exists, it is replaced.

required
Source code in pypath/core/fleet.py
377
378
379
380
381
382
383
384
385
386
387
388
def add_fleet(self, fleet: FleetGroup) -> None:
    """Add or replace a fleet.

    Parameters
    ----------
    fleet : FleetGroup
        Fleet to add. If a fleet with the same name exists, it is replaced.
    """
    if not fleet.is_valid():
        logger.warning(f"Fleet {fleet.name} is not valid; adding anyway")
    self.fleets[fleet.name] = fleet
    logger.debug(f"Added fleet: {fleet.name} (ID: {fleet.fleet_id})")
add_discard_path
add_discard_path(path: DiscardPath) -> None

Add a discard path.

Parameters:

Name Type Description Default
path DiscardPath

Discard path to add.

required
Source code in pypath/core/fleet.py
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
def add_discard_path(self, path: DiscardPath) -> None:
    """Add a discard path.

    Parameters
    ----------
    path : DiscardPath
        Discard path to add.
    """
    if not path.is_valid():
        logger.warning(f"Discard path for {path.source_group} is not valid")
    if path.source_group not in self.discard_paths:
        self.discard_paths[path.source_group] = []
    self.discard_paths[path.source_group].append(path)
    logger.debug(
        f"Added discard path: {path.source_group} -> {path.target_group} "
        f"({path.fate})"
    )
get_fleet
get_fleet(name: str) -> Optional[FleetGroup]

Retrieve a fleet by name.

Parameters:

Name Type Description Default
name str

Fleet name.

required

Returns:

Type Description
FleetGroup | None

Fleet if found, None otherwise.

Source code in pypath/core/fleet.py
408
409
410
411
412
413
414
415
416
417
418
419
420
421
def get_fleet(self, name: str) -> Optional[FleetGroup]:
    """Retrieve a fleet by name.

    Parameters
    ----------
    name : str
        Fleet name.

    Returns
    -------
    FleetGroup | None
        Fleet if found, None otherwise.
    """
    return self.fleets.get(name)
validate
validate() -> tuple[bool, list[str]]

Validate fleet dynamics configuration.

Checks that: - All fleets are valid - All discard paths are valid - Referenced groups exist (soft check: logged as warning, not error)

Returns:

Type Description
tuple[bool, list[str]]

(is_valid, error_messages). is_valid=True only if all checks pass.

Source code in pypath/core/fleet.py
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
def validate(self) -> tuple[bool, list[str]]:
    """Validate fleet dynamics configuration.

    Checks that:
    - All fleets are valid
    - All discard paths are valid
    - Referenced groups exist (soft check: logged as warning, not error)

    Returns
    -------
    tuple[bool, list[str]]
        (is_valid, error_messages). is_valid=True only if all checks pass.
    """
    errors = []
    for fleet in self.fleets.values():
        if not fleet.is_valid():
            errors.append(f"Fleet {fleet.name} is not valid")
    for source, paths in self.discard_paths.items():
        for path in paths:
            if not path.is_valid():
                errors.append(
                    f"Discard path {source} -> {path.target_group} is not valid"
                )
    return len(errors) == 0, errors
to_dataframe
to_dataframe() -> dict[str, pd.DataFrame]

Convert fleet dynamics to DataFrame representation.

Returns:

Type Description
dict[str, DataFrame]

Dictionary with keys 'fleets' and 'discards', each a DataFrame. - fleets: columns [name, fleet_id, gears, fuel_efficiency, base_effort, catchability (dict column)] - discards: columns [source_group, target_group, discard_rate, fate, depth_dependent]

Source code in pypath/core/fleet.py
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
def to_dataframe(self) -> dict[str, pd.DataFrame]:
    """Convert fleet dynamics to DataFrame representation.

    Returns
    -------
    dict[str, pd.DataFrame]
        Dictionary with keys 'fleets' and 'discards', each a DataFrame.
        - fleets: columns [name, fleet_id, gears, fuel_efficiency,
          base_effort, catchability (dict column)]
        - discards: columns [source_group, target_group, discard_rate,
          fate, depth_dependent]
    """
    fleets_data = [f.to_dict() for f in self.fleets.values()]
    fleets_df = pd.DataFrame(fleets_data) if fleets_data else pd.DataFrame()

    discards_data = []
    for paths in self.discard_paths.values():
        discards_data.extend([p.to_dict() for p in paths])
    discards_df = pd.DataFrame(discards_data) if discards_data else pd.DataFrame()

    return {"fleets": fleets_df, "discards": discards_df}
from_dataframe classmethod
from_dataframe(fleets_df: DataFrame, discards_df: DataFrame) -> FleetDynamics

Reconstruct fleet dynamics from DataFrames.

Parameters:

Name Type Description Default
fleets_df DataFrame

Fleet data (as returned by to_dataframe()['fleets']).

required
discards_df DataFrame

Discard data (as returned by to_dataframe()['discards']).

required

Returns:

Type Description
FleetDynamics

Reconstructed fleet dynamics instance.

Source code in pypath/core/fleet.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
@classmethod
def from_dataframe(
    cls, fleets_df: pd.DataFrame, discards_df: pd.DataFrame
) -> FleetDynamics:
    """Reconstruct fleet dynamics from DataFrames.

    Parameters
    ----------
    fleets_df : pd.DataFrame
        Fleet data (as returned by to_dataframe()['fleets']).
    discards_df : pd.DataFrame
        Discard data (as returned by to_dataframe()['discards']).

    Returns
    -------
    FleetDynamics
        Reconstructed fleet dynamics instance.
    """
    fd = cls()
    for _, row in fleets_df.iterrows():
        fleet_dict = row.to_dict()
        fd.add_fleet(FleetGroup.from_dict(fleet_dict))
    for _, row in discards_df.iterrows():
        path_dict = row.to_dict()
        fd.add_discard_path(DiscardPath.from_dict(path_dict))
    return fd

allocate_catch

allocate_catch(total_catch: float, catchability: dict[str, float]) -> dict[str, float]

Allocate catch across groups based on catchability.

Distributes total catch proportionally to catchability coefficients (q values) for each group.

Parameters:

Name Type Description Default
total_catch float

Total catch biomass (tons).

required
catchability dict[str, float]

Catchability by group name. Values should be normalized (sum to ~1) for intuitive interpretation.

required

Returns:

Type Description
dict[str, float]

Allocated catch per group.

Examples:

>>> catchability = {"Cod": 0.6, "Haddock": 0.4}
>>> catch = allocate_catch(100.0, catchability)
>>> catch["Cod"]
60.0
Source code in pypath/core/fleet.py
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
def allocate_catch(
    total_catch: float, catchability: dict[str, float]
) -> dict[str, float]:
    """Allocate catch across groups based on catchability.

    Distributes total catch proportionally to catchability coefficients
    (q values) for each group.

    Parameters
    ----------
    total_catch : float
        Total catch biomass (tons).
    catchability : dict[str, float]
        Catchability by group name. Values should be normalized (sum to ~1)
        for intuitive interpretation.

    Returns
    -------
    dict[str, float]
        Allocated catch per group.

    Examples
    --------
    >>> catchability = {"Cod": 0.6, "Haddock": 0.4}
    >>> catch = allocate_catch(100.0, catchability)
    >>> catch["Cod"]
    60.0
    """
    if not catchability:
        return {}
    total_q = sum(catchability.values())
    if total_q <= 0:
        logger.warning("Total catchability is zero or negative")
        return {g: 0.0 for g in catchability}
    return {g: total_catch * (q / total_q) for g, q in catchability.items()}

allocate_discards

allocate_discards(discard_rate: float, source_group: str) -> dict[str, float]

Allocate discard biomass from a source group.

Computes discard proportion and residual landed proportion from a discard rate. Used to split catch into landed and discarded components.

Parameters:

Name Type Description Default
discard_rate float

Proportion discarded (0-1).

required
source_group str

Source group name (for logging).

required

Returns:

Type Description
dict[str, float]

Dictionary with 'landed' and 'discarded' proportions.

Raises:

Type Description
ValueError

If discard_rate not in [0, 1].

Source code in pypath/core/fleet.py
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
def allocate_discards(discard_rate: float, source_group: str) -> dict[str, float]:
    """Allocate discard biomass from a source group.

    Computes discard proportion and residual landed proportion from a
    discard rate. Used to split catch into landed and discarded components.

    Parameters
    ----------
    discard_rate : float
        Proportion discarded (0-1).
    source_group : str
        Source group name (for logging).

    Returns
    -------
    dict[str, float]
        Dictionary with 'landed' and 'discarded' proportions.

    Raises
    ------
    ValueError
        If discard_rate not in [0, 1].
    """
    if not (0.0 <= discard_rate <= 1.0):
        raise ValueError(f"discard_rate must be in [0, 1], got {discard_rate}")
    return {
        "discarded": discard_rate,
        "landed": 1.0 - discard_rate,
    }

validate_allocation

validate_allocation(allocation: dict[str, float], tolerance: float = 0.01) -> bool

Validate that allocation sums to approximately 1.0.

Parameters:

Name Type Description Default
allocation dict[str, float]

Allocation dictionary (e.g., from allocate_catch or allocate_discards).

required
tolerance float

Acceptable deviation from 1.0. Default 0.01 (1%).

0.01

Returns:

Type Description
bool

True if allocation sums to 1.0 ± tolerance, False otherwise.

Source code in pypath/core/fleet.py
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
def validate_allocation(
    allocation: dict[str, float],
    tolerance: float = 0.01,
) -> bool:
    """Validate that allocation sums to approximately 1.0.

    Parameters
    ----------
    allocation : dict[str, float]
        Allocation dictionary (e.g., from allocate_catch or allocate_discards).
    tolerance : float
        Acceptable deviation from 1.0. Default 0.01 (1%).

    Returns
    -------
    bool
        True if allocation sums to 1.0 ± tolerance, False otherwise.
    """
    if not allocation:
        logger.warning("Empty allocation")
        return False
    total = sum(allocation.values())
    is_valid = abs(total - 1.0) <= tolerance
    if not is_valid:
        logger.warning(
            f"Allocation sum {total} deviates from 1.0 by {abs(total - 1.0)}"
        )
    return is_valid

estimate_catch_value

estimate_catch_value(catch: dict[str, float], prices: dict[str, float]) -> float

Estimate total economic value of catch.

Multiplies catch biomass by price per unit (e.g., $/kg) for each group and sums the total value.

Parameters:

Name Type Description Default
catch dict[str, float]

Catch biomass per group (tons).

required
prices dict[str, float]

Price per unit (e.g., $/kg) by group name.

required

Returns:

Type Description
float

Total catch value (in same currency units as prices).

Notes

This is a stub function for economic analysis. Price data and units ($/kg, $/ton, etc.) should be externally documented.

Source code in pypath/core/fleet.py
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
def estimate_catch_value(catch: dict[str, float], prices: dict[str, float]) -> float:
    """Estimate total economic value of catch.

    Multiplies catch biomass by price per unit (e.g., $/kg) for each group
    and sums the total value.

    Parameters
    ----------
    catch : dict[str, float]
        Catch biomass per group (tons).
    prices : dict[str, float]
        Price per unit (e.g., $/kg) by group name.

    Returns
    -------
    float
        Total catch value (in same currency units as prices).

    Notes
    -----
    This is a stub function for economic analysis. Price data and units
    ($/kg, $/ton, etc.) should be externally documented.
    """
    total_value = 0.0
    for group, catch_biomass in catch.items():
        if group in prices:
            price_per_unit = prices[group]
            value = catch_biomass * 1000 * price_per_unit
            total_value += value
    return total_value

estimate_fuel_cost

estimate_fuel_cost(effort: float, fuel_price: float) -> float

Estimate fuel cost for fishing effort.

Computes cost based on effort (days/trips) and fuel price per unit. Assumes a default fuel consumption profile per effort unit.

Parameters:

Name Type Description Default
effort float

Effort (days or trips).

required
fuel_price float

Price per unit fuel (e.g., $/liter).

required

Returns:

Type Description
float

Total fuel cost (same currency units as fuel_price).

Notes

This is a stub function. Actual fuel consumption profiles should be calibrated to specific fleet characteristics or regional data.

Source code in pypath/core/fleet.py
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
def estimate_fuel_cost(effort: float, fuel_price: float) -> float:
    """Estimate fuel cost for fishing effort.

    Computes cost based on effort (days/trips) and fuel price per unit.
    Assumes a default fuel consumption profile per effort unit.

    Parameters
    ----------
    effort : float
        Effort (days or trips).
    fuel_price : float
        Price per unit fuel (e.g., $/liter).

    Returns
    -------
    float
        Total fuel cost (same currency units as fuel_price).

    Notes
    -----
    This is a stub function. Actual fuel consumption profiles should be
    calibrated to specific fleet characteristics or regional data.
    """
    fuel_consumption_per_day = 100.0
    return effort * fuel_consumption_per_day * fuel_price

Key Classes: - GearType — Enum for 6 gear types (SEINE, NET, TRAP, TRAWL, HOOK, OTHER) - FleetGroup — Fleet definition with catchability matrix, fuel efficiency, base effort - DiscardPath — Discard routing with 4 fates (lost, predation, detritus, benthos) - FleetDynamics — Multi-fleet container with allocation and validation

Allocation Functions: - allocate_catch() — Distribute catch among prey based on catchability - allocate_discards() — Route discards to specified fates - estimate_catch_value() — Economic value estimation (stub) - estimate_fuel_cost() — Fuel cost calculation (stub)

Nutrient Cycling System (Phase 1B.5)

Ecosystem-level nutrient cycling (N, P, C) with excretion, uptake kinetics, and stoichiometric relationships. Implements Monod saturation for producer nutrient limitation.

pypath.core.nutrients

Nutrient cycling (N, P, C) system for Ecopath groups.

This module implements nutrient content, excretion, and uptake calculations following standard aquatic biogeochemistry conventions.

NutrientElement

Bases: str, Enum

Nutrient elements tracked in food web models.

Attributes:

Name Type Description
NITROGEN str

Nitrogen (N), molecular weight 14.01 g/mol

PHOSPHORUS str

Phosphorus (P), molecular weight 30.97 g/mol

CARBON str

Carbon (C), molecular weight 12.01 g/mol

Source code in pypath/core/nutrients.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
class NutrientElement(str, Enum):
    """Nutrient elements tracked in food web models.

    Attributes
    ----------
    NITROGEN : str
        Nitrogen (N), molecular weight 14.01 g/mol
    PHOSPHORUS : str
        Phosphorus (P), molecular weight 30.97 g/mol
    CARBON : str
        Carbon (C), molecular weight 12.01 g/mol
    """

    NITROGEN = "nitrogen"
    PHOSPHORUS = "phosphorus"
    CARBON = "carbon"

    @property
    def molecular_weight(self) -> float:
        """Molecular weight in g/mol.

        Returns
        -------
        float
            Molecular weight of the element.
        """
        weights = {
            NutrientElement.NITROGEN: 14.01,
            NutrientElement.PHOSPHORUS: 30.97,
            NutrientElement.CARBON: 12.01,
        }
        return weights[self]
molecular_weight property
molecular_weight: float

Molecular weight in g/mol.

Returns:

Type Description
float

Molecular weight of the element.

NutrientContent dataclass

Nutrient elemental composition of a biomass group.

Attributes:

Name Type Description
group_name str

Name of the functional group

nitrogen_percent float

Nitrogen as % dry weight (typical: 7-15%)

phosphorus_percent float

Phosphorus as % dry weight (typical: 1-2%)

carbon_percent float

Carbon as % dry weight (typical: 45-50%)

ash_percent float

Ash (mineral) as % dry weight (typical: 5-15%)

Source code in pypath/core/nutrients.py
 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
@dataclass
class NutrientContent:
    """Nutrient elemental composition of a biomass group.

    Attributes
    ----------
    group_name : str
        Name of the functional group
    nitrogen_percent : float
        Nitrogen as % dry weight (typical: 7-15%)
    phosphorus_percent : float
        Phosphorus as % dry weight (typical: 1-2%)
    carbon_percent : float
        Carbon as % dry weight (typical: 45-50%)
    ash_percent : float
        Ash (mineral) as % dry weight (typical: 5-15%)
    """

    group_name: str
    nitrogen_percent: float
    phosphorus_percent: float
    carbon_percent: float
    ash_percent: float

    def __post_init__(self) -> None:
        """Validate nutrient composition ranges."""
        if not (0 <= self.nitrogen_percent <= 20):
            raise ValueError(
                f"{self.group_name}: nitrogen_percent must be 0-20%, "
                f"got {self.nitrogen_percent}"
            )
        if not (0 <= self.phosphorus_percent <= 5):
            raise ValueError(
                f"{self.group_name}: phosphorus_percent must be 0-5%, "
                f"got {self.phosphorus_percent}"
            )
        if not (40 <= self.carbon_percent <= 55):
            raise ValueError(
                f"{self.group_name}: carbon_percent must be 40-55%, "
                f"got {self.carbon_percent}"
            )
        if not (0 <= self.ash_percent <= 20):
            raise ValueError(
                f"{self.group_name}: ash_percent must be 0-20%, got {self.ash_percent}"
            )

    def is_valid(self) -> bool:
        """Check if nutrient composition is valid.

        Returns
        -------
        bool
            True if all constraints are satisfied, False otherwise.
        """
        try:
            self.__post_init__()
            return True
        except ValueError:
            return False

    def to_dict(self) -> Dict[str, float]:
        """Convert to dictionary representation.

        Returns
        -------
        dict
            Dictionary with nutrient percentages.
        """
        return {
            "group_name": self.group_name,
            "nitrogen_percent": self.nitrogen_percent,
            "phosphorus_percent": self.phosphorus_percent,
            "carbon_percent": self.carbon_percent,
            "ash_percent": self.ash_percent,
        }

    @classmethod
    def from_dict(cls, data: Dict[str, float]) -> NutrientContent:
        """Create from dictionary representation.

        Parameters
        ----------
        data : dict
            Dictionary with required keys: group_name, nitrogen_percent,
            phosphorus_percent, carbon_percent, ash_percent.

        Returns
        -------
        NutrientContent
            Instantiated object.
        """
        return cls(
            group_name=data["group_name"],
            nitrogen_percent=data["nitrogen_percent"],
            phosphorus_percent=data["phosphorus_percent"],
            carbon_percent=data["carbon_percent"],
            ash_percent=data["ash_percent"],
        )
__post_init__
__post_init__() -> None

Validate nutrient composition ranges.

Source code in pypath/core/nutrients.py
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
def __post_init__(self) -> None:
    """Validate nutrient composition ranges."""
    if not (0 <= self.nitrogen_percent <= 20):
        raise ValueError(
            f"{self.group_name}: nitrogen_percent must be 0-20%, "
            f"got {self.nitrogen_percent}"
        )
    if not (0 <= self.phosphorus_percent <= 5):
        raise ValueError(
            f"{self.group_name}: phosphorus_percent must be 0-5%, "
            f"got {self.phosphorus_percent}"
        )
    if not (40 <= self.carbon_percent <= 55):
        raise ValueError(
            f"{self.group_name}: carbon_percent must be 40-55%, "
            f"got {self.carbon_percent}"
        )
    if not (0 <= self.ash_percent <= 20):
        raise ValueError(
            f"{self.group_name}: ash_percent must be 0-20%, got {self.ash_percent}"
        )
is_valid
is_valid() -> bool

Check if nutrient composition is valid.

Returns:

Type Description
bool

True if all constraints are satisfied, False otherwise.

Source code in pypath/core/nutrients.py
102
103
104
105
106
107
108
109
110
111
112
113
114
def is_valid(self) -> bool:
    """Check if nutrient composition is valid.

    Returns
    -------
    bool
        True if all constraints are satisfied, False otherwise.
    """
    try:
        self.__post_init__()
        return True
    except ValueError:
        return False
to_dict
to_dict() -> Dict[str, float]

Convert to dictionary representation.

Returns:

Type Description
dict

Dictionary with nutrient percentages.

Source code in pypath/core/nutrients.py
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
def to_dict(self) -> Dict[str, float]:
    """Convert to dictionary representation.

    Returns
    -------
    dict
        Dictionary with nutrient percentages.
    """
    return {
        "group_name": self.group_name,
        "nitrogen_percent": self.nitrogen_percent,
        "phosphorus_percent": self.phosphorus_percent,
        "carbon_percent": self.carbon_percent,
        "ash_percent": self.ash_percent,
    }
from_dict classmethod
from_dict(data: Dict[str, float]) -> NutrientContent

Create from dictionary representation.

Parameters:

Name Type Description Default
data dict

Dictionary with required keys: group_name, nitrogen_percent, phosphorus_percent, carbon_percent, ash_percent.

required

Returns:

Type Description
NutrientContent

Instantiated object.

Source code in pypath/core/nutrients.py
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
@classmethod
def from_dict(cls, data: Dict[str, float]) -> NutrientContent:
    """Create from dictionary representation.

    Parameters
    ----------
    data : dict
        Dictionary with required keys: group_name, nitrogen_percent,
        phosphorus_percent, carbon_percent, ash_percent.

    Returns
    -------
    NutrientContent
        Instantiated object.
    """
    return cls(
        group_name=data["group_name"],
        nitrogen_percent=data["nitrogen_percent"],
        phosphorus_percent=data["phosphorus_percent"],
        carbon_percent=data["carbon_percent"],
        ash_percent=data["ash_percent"],
    )

NutrientExcretion dataclass

Excretion rates and fecal composition for a group.

Attributes:

Name Type Description
group_name str

Name of the functional group

n_excretion_rate float

Nitrogen excretion as % of daily consumption (typical: 5-15%)

p_excretion_rate float

Phosphorus excretion as % of daily consumption (typical: 1-3%)

fecal_n_fraction float

Fraction of excretion that is fecal vs. dissolved (0-1)

fecal_p_fraction float

Fraction of phosphorus excretion that is fecal (0-1)

Source code in pypath/core/nutrients.py
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
@dataclass
class NutrientExcretion:
    """Excretion rates and fecal composition for a group.

    Attributes
    ----------
    group_name : str
        Name of the functional group
    n_excretion_rate : float
        Nitrogen excretion as % of daily consumption (typical: 5-15%)
    p_excretion_rate : float
        Phosphorus excretion as % of daily consumption (typical: 1-3%)
    fecal_n_fraction : float
        Fraction of excretion that is fecal vs. dissolved (0-1)
    fecal_p_fraction : float
        Fraction of phosphorus excretion that is fecal (0-1)
    """

    group_name: str
    n_excretion_rate: float
    p_excretion_rate: float
    fecal_n_fraction: float
    fecal_p_fraction: float

    def __post_init__(self) -> None:
        """Validate excretion rates."""
        if not (0 <= self.n_excretion_rate <= 50):
            raise ValueError(
                f"{self.group_name}: n_excretion_rate must be 0-50%, "
                f"got {self.n_excretion_rate}"
            )
        if not (0 <= self.p_excretion_rate <= 20):
            raise ValueError(
                f"{self.group_name}: p_excretion_rate must be 0-20%, "
                f"got {self.p_excretion_rate}"
            )
        if not (0 <= self.fecal_n_fraction <= 1):
            raise ValueError(
                f"{self.group_name}: fecal_n_fraction must be 0-1, "
                f"got {self.fecal_n_fraction}"
            )
        if not (0 <= self.fecal_p_fraction <= 1):
            raise ValueError(
                f"{self.group_name}: fecal_p_fraction must be 0-1, "
                f"got {self.fecal_p_fraction}"
            )

    def calculate_excretion(self, consumption: float, element: str) -> float:
        """Calculate excretion of a nutrient element.

        Parameters
        ----------
        consumption : float
            Daily consumption rate (mass units, e.g., kg/day)
        element : str
            Element name ('nitrogen' or 'phosphorus')

        Returns
        -------
        float
            Daily excretion rate (same units as consumption)

        Raises
        ------
        ValueError
            If element is not 'nitrogen' or 'phosphorus'.
        """
        if element.lower() == "nitrogen":
            return consumption * (self.n_excretion_rate / 100.0)
        elif element.lower() == "phosphorus":
            return consumption * (self.p_excretion_rate / 100.0)
        else:
            raise ValueError(
                f"Unknown element: {element}. Must be 'nitrogen' or 'phosphorus'."
            )

    def to_dict(self) -> Dict[str, float]:
        """Convert to dictionary representation.

        Returns
        -------
        dict
            Dictionary with excretion parameters.
        """
        return {
            "group_name": self.group_name,
            "n_excretion_rate": self.n_excretion_rate,
            "p_excretion_rate": self.p_excretion_rate,
            "fecal_n_fraction": self.fecal_n_fraction,
            "fecal_p_fraction": self.fecal_p_fraction,
        }
__post_init__
__post_init__() -> None

Validate excretion rates.

Source code in pypath/core/nutrients.py
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
def __post_init__(self) -> None:
    """Validate excretion rates."""
    if not (0 <= self.n_excretion_rate <= 50):
        raise ValueError(
            f"{self.group_name}: n_excretion_rate must be 0-50%, "
            f"got {self.n_excretion_rate}"
        )
    if not (0 <= self.p_excretion_rate <= 20):
        raise ValueError(
            f"{self.group_name}: p_excretion_rate must be 0-20%, "
            f"got {self.p_excretion_rate}"
        )
    if not (0 <= self.fecal_n_fraction <= 1):
        raise ValueError(
            f"{self.group_name}: fecal_n_fraction must be 0-1, "
            f"got {self.fecal_n_fraction}"
        )
    if not (0 <= self.fecal_p_fraction <= 1):
        raise ValueError(
            f"{self.group_name}: fecal_p_fraction must be 0-1, "
            f"got {self.fecal_p_fraction}"
        )
calculate_excretion
calculate_excretion(consumption: float, element: str) -> float

Calculate excretion of a nutrient element.

Parameters:

Name Type Description Default
consumption float

Daily consumption rate (mass units, e.g., kg/day)

required
element str

Element name ('nitrogen' or 'phosphorus')

required

Returns:

Type Description
float

Daily excretion rate (same units as consumption)

Raises:

Type Description
ValueError

If element is not 'nitrogen' or 'phosphorus'.

Source code in pypath/core/nutrients.py
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
def calculate_excretion(self, consumption: float, element: str) -> float:
    """Calculate excretion of a nutrient element.

    Parameters
    ----------
    consumption : float
        Daily consumption rate (mass units, e.g., kg/day)
    element : str
        Element name ('nitrogen' or 'phosphorus')

    Returns
    -------
    float
        Daily excretion rate (same units as consumption)

    Raises
    ------
    ValueError
        If element is not 'nitrogen' or 'phosphorus'.
    """
    if element.lower() == "nitrogen":
        return consumption * (self.n_excretion_rate / 100.0)
    elif element.lower() == "phosphorus":
        return consumption * (self.p_excretion_rate / 100.0)
    else:
        raise ValueError(
            f"Unknown element: {element}. Must be 'nitrogen' or 'phosphorus'."
        )
to_dict
to_dict() -> Dict[str, float]

Convert to dictionary representation.

Returns:

Type Description
dict

Dictionary with excretion parameters.

Source code in pypath/core/nutrients.py
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
def to_dict(self) -> Dict[str, float]:
    """Convert to dictionary representation.

    Returns
    -------
    dict
        Dictionary with excretion parameters.
    """
    return {
        "group_name": self.group_name,
        "n_excretion_rate": self.n_excretion_rate,
        "p_excretion_rate": self.p_excretion_rate,
        "fecal_n_fraction": self.fecal_n_fraction,
        "fecal_p_fraction": self.fecal_p_fraction,
    }

NutrientUptake dataclass

Nutrient uptake kinetics for primary producers.

Attributes:

Name Type Description
group_name str

Name of the functional group (typically a primary producer)

n_uptake_rate float

Maximum nitrogen uptake rate (mg N / mg biomass / day)

p_uptake_rate float

Maximum phosphorus uptake rate (mg P / mg biomass / day)

half_saturation_n float

Half-saturation constant for nitrogen (mg N/L)

half_saturation_p float

Half-saturation constant for phosphorus (mg P/L)

Source code in pypath/core/nutrients.py
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
@dataclass
class NutrientUptake:
    """Nutrient uptake kinetics for primary producers.

    Attributes
    ----------
    group_name : str
        Name of the functional group (typically a primary producer)
    n_uptake_rate : float
        Maximum nitrogen uptake rate (mg N / mg biomass / day)
    p_uptake_rate : float
        Maximum phosphorus uptake rate (mg P / mg biomass / day)
    half_saturation_n : float
        Half-saturation constant for nitrogen (mg N/L)
    half_saturation_p : float
        Half-saturation constant for phosphorus (mg P/L)
    """

    group_name: str
    n_uptake_rate: float
    p_uptake_rate: float
    half_saturation_n: float
    half_saturation_p: float

    def __post_init__(self) -> None:
        """Validate uptake parameters."""
        if self.n_uptake_rate < 0:
            raise ValueError(
                f"{self.group_name}: n_uptake_rate must be >= 0, "
                f"got {self.n_uptake_rate}"
            )
        if self.p_uptake_rate < 0:
            raise ValueError(
                f"{self.group_name}: p_uptake_rate must be >= 0, "
                f"got {self.p_uptake_rate}"
            )
        if self.half_saturation_n < 0:
            raise ValueError(
                f"{self.group_name}: half_saturation_n must be >= 0, "
                f"got {self.half_saturation_n}"
            )
        if self.half_saturation_p < 0:
            raise ValueError(
                f"{self.group_name}: half_saturation_p must be >= 0, "
                f"got {self.half_saturation_p}"
            )

    def calculate_uptake(self, nutrient_level: float, rate: float) -> float:
        """Calculate uptake using Monod (Michaelis-Menten) kinetics.

        Parameters
        ----------
        nutrient_level : float
            Ambient nutrient concentration (mg/L)
        rate : float
            Maximum uptake rate (Vmax)

        Returns
        -------
        float
            Uptake rate under Monod kinetics (mg/L/day or similar)

        Notes
        -----
        Uses the Monod equation: v = (Vmax * [S]) / (Km + [S])
        where Km is the appropriate half-saturation constant.
        """
        if nutrient_level < 0:
            raise ValueError(f"nutrient_level must be >= 0, got {nutrient_level}")
        if rate < 0:
            raise ValueError(f"rate must be >= 0, got {rate}")

        return (rate * nutrient_level) / (rate + nutrient_level)

    def to_dict(self) -> Dict[str, float]:
        """Convert to dictionary representation.

        Returns
        -------
        dict
            Dictionary with uptake parameters.
        """
        return {
            "group_name": self.group_name,
            "n_uptake_rate": self.n_uptake_rate,
            "p_uptake_rate": self.p_uptake_rate,
            "half_saturation_n": self.half_saturation_n,
            "half_saturation_p": self.half_saturation_p,
        }
__post_init__
__post_init__() -> None

Validate uptake parameters.

Source code in pypath/core/nutrients.py
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
def __post_init__(self) -> None:
    """Validate uptake parameters."""
    if self.n_uptake_rate < 0:
        raise ValueError(
            f"{self.group_name}: n_uptake_rate must be >= 0, "
            f"got {self.n_uptake_rate}"
        )
    if self.p_uptake_rate < 0:
        raise ValueError(
            f"{self.group_name}: p_uptake_rate must be >= 0, "
            f"got {self.p_uptake_rate}"
        )
    if self.half_saturation_n < 0:
        raise ValueError(
            f"{self.group_name}: half_saturation_n must be >= 0, "
            f"got {self.half_saturation_n}"
        )
    if self.half_saturation_p < 0:
        raise ValueError(
            f"{self.group_name}: half_saturation_p must be >= 0, "
            f"got {self.half_saturation_p}"
        )
calculate_uptake
calculate_uptake(nutrient_level: float, rate: float) -> float

Calculate uptake using Monod (Michaelis-Menten) kinetics.

Parameters:

Name Type Description Default
nutrient_level float

Ambient nutrient concentration (mg/L)

required
rate float

Maximum uptake rate (Vmax)

required

Returns:

Type Description
float

Uptake rate under Monod kinetics (mg/L/day or similar)

Notes

Uses the Monod equation: v = (Vmax * [S]) / (Km + [S]) where Km is the appropriate half-saturation constant.

Source code in pypath/core/nutrients.py
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
def calculate_uptake(self, nutrient_level: float, rate: float) -> float:
    """Calculate uptake using Monod (Michaelis-Menten) kinetics.

    Parameters
    ----------
    nutrient_level : float
        Ambient nutrient concentration (mg/L)
    rate : float
        Maximum uptake rate (Vmax)

    Returns
    -------
    float
        Uptake rate under Monod kinetics (mg/L/day or similar)

    Notes
    -----
    Uses the Monod equation: v = (Vmax * [S]) / (Km + [S])
    where Km is the appropriate half-saturation constant.
    """
    if nutrient_level < 0:
        raise ValueError(f"nutrient_level must be >= 0, got {nutrient_level}")
    if rate < 0:
        raise ValueError(f"rate must be >= 0, got {rate}")

    return (rate * nutrient_level) / (rate + nutrient_level)
to_dict
to_dict() -> Dict[str, float]

Convert to dictionary representation.

Returns:

Type Description
dict

Dictionary with uptake parameters.

Source code in pypath/core/nutrients.py
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
def to_dict(self) -> Dict[str, float]:
    """Convert to dictionary representation.

    Returns
    -------
    dict
        Dictionary with uptake parameters.
    """
    return {
        "group_name": self.group_name,
        "n_uptake_rate": self.n_uptake_rate,
        "p_uptake_rate": self.p_uptake_rate,
        "half_saturation_n": self.half_saturation_n,
        "half_saturation_p": self.half_saturation_p,
    }

NutrientCycle dataclass

Container for nutrient cycling parameters across all groups.

Attributes:

Name Type Description
contents dict

Mapping of group_name -> NutrientContent

excretions dict

Mapping of group_name -> NutrientExcretion

uptakes dict

Mapping of group_name -> NutrientUptake (typically producers only)

Source code in pypath/core/nutrients.py
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
@dataclass
class NutrientCycle:
    """Container for nutrient cycling parameters across all groups.

    Attributes
    ----------
    contents : dict
        Mapping of group_name -> NutrientContent
    excretions : dict
        Mapping of group_name -> NutrientExcretion
    uptakes : dict
        Mapping of group_name -> NutrientUptake (typically producers only)
    """

    contents: Dict[str, NutrientContent] = field(default_factory=dict)
    excretions: Dict[str, NutrientExcretion] = field(default_factory=dict)
    uptakes: Dict[str, NutrientUptake] = field(default_factory=dict)

    def add_content(self, content: NutrientContent) -> None:
        """Add or update nutrient content for a group.

        Parameters
        ----------
        content : NutrientContent
            Nutrient composition parameters.
        """
        if not content.is_valid():
            raise ValueError(f"Invalid nutrient content for {content.group_name}")
        self.contents[content.group_name] = content
        logger.debug(f"Added nutrient content for {content.group_name}")

    def add_excretion(self, excretion: NutrientExcretion) -> None:
        """Add or update excretion parameters for a group.

        Parameters
        ----------
        excretion : NutrientExcretion
            Excretion and fecal composition parameters.
        """
        self.excretions[excretion.group_name] = excretion
        logger.debug(f"Added excretion parameters for {excretion.group_name}")

    def add_uptake(self, uptake: NutrientUptake) -> None:
        """Add or update uptake parameters for a group.

        Parameters
        ----------
        uptake : NutrientUptake
            Nutrient uptake kinetics (typically for producers).
        """
        self.uptakes[uptake.group_name] = uptake
        logger.debug(f"Added uptake parameters for {uptake.group_name}")

    def validate(self) -> Tuple[bool, List[str]]:
        """Validate nutrient cycle consistency.

        Returns
        -------
        tuple[bool, list[str]]
            (is_valid, list of error/warning messages)
        """
        messages = []

        if not self.contents and not self.excretions and not self.uptakes:
            messages.append("NutrientCycle is empty")
            return len(messages) == 0, messages

        for name, content in self.contents.items():
            if not content.is_valid():
                messages.append(f"Invalid content for {name}")

        for name, excretion in self.excretions.items():
            if name not in self.contents:
                messages.append(f"Excretion defined for {name} but no content")

        for name, uptake in self.uptakes.items():
            if name not in self.contents:
                messages.append(f"Uptake defined for {name} but no content")

        is_valid = len(messages) == 0
        return is_valid, messages

    def calculate_mass_balance(self, rpath_params: RpathParams) -> Dict[str, float]:
        """Calculate nutrient mass balance across groups.

        Parameters
        ----------
        rpath_params : RpathParams
            Ecopath model parameters with biomass and flow information.

        Returns
        -------
        dict
            Mass balance summary with keys like 'total_n_biomass',
            'total_p_biomass', 'balance_status'.
        """
        balance = {
            "total_n_biomass": 0.0,
            "total_p_biomass": 0.0,
            "total_c_biomass": 0.0,
            "groups_with_content": 0,
        }

        if not rpath_params.model.empty and "Biomass" in rpath_params.model.columns:
            for idx, row in rpath_params.model.iterrows():
                group = row.get("Group", "")
                biomass = row.get("Biomass", 0.0)

                if group in self.contents and biomass > 0:
                    content = self.contents[group]
                    balance["total_n_biomass"] += biomass * (
                        content.nitrogen_percent / 100.0
                    )
                    balance["total_p_biomass"] += biomass * (
                        content.phosphorus_percent / 100.0
                    )
                    balance["total_c_biomass"] += biomass * (
                        content.carbon_percent / 100.0
                    )
                    balance["groups_with_content"] += 1

        balance["balance_status"] = (
            "partial" if balance["groups_with_content"] > 0 else "undefined"
        )
        return balance

    def to_dataframe(self) -> pd.DataFrame:
        """Convert to pandas DataFrame representation.

        Returns
        -------
        pd.DataFrame
            DataFrame with one row per group, containing nutrient
            content, excretion, and uptake parameters.
        """
        rows = []
        all_groups = (
            set(self.contents.keys())
            | set(self.excretions.keys())
            | set(self.uptakes.keys())
        )

        for group_name in sorted(all_groups):
            row = {"Group": group_name}

            if group_name in self.contents:
                content = self.contents[group_name]
                row.update(
                    {
                        "N_percent": content.nitrogen_percent,
                        "P_percent": content.phosphorus_percent,
                        "C_percent": content.carbon_percent,
                        "Ash_percent": content.ash_percent,
                    }
                )

            if group_name in self.excretions:
                excretion = self.excretions[group_name]
                row.update(
                    {
                        "N_excretion_rate": excretion.n_excretion_rate,
                        "P_excretion_rate": excretion.p_excretion_rate,
                        "Fecal_N_frac": excretion.fecal_n_fraction,
                        "Fecal_P_frac": excretion.fecal_p_fraction,
                    }
                )

            if group_name in self.uptakes:
                uptake = self.uptakes[group_name]
                row.update(
                    {
                        "N_uptake_rate": uptake.n_uptake_rate,
                        "P_uptake_rate": uptake.p_uptake_rate,
                        "Ks_N": uptake.half_saturation_n,
                        "Ks_P": uptake.half_saturation_p,
                    }
                )

            rows.append(row)

        return pd.DataFrame(rows) if rows else pd.DataFrame()

    @classmethod
    def from_dataframe(cls, df: pd.DataFrame) -> NutrientCycle:
        """Create from pandas DataFrame representation.

        Parameters
        ----------
        df : pd.DataFrame
            DataFrame with nutrient parameters, one row per group.

        Returns
        -------
        NutrientCycle
            Instantiated NutrientCycle object.
        """
        cycle = cls()

        for _, row in df.iterrows():
            group_name = row.get("Group", "")
            if not group_name:
                continue

            content_cols = ["N_percent", "P_percent", "C_percent", "Ash_percent"]
            if all(col in df.columns for col in content_cols):
                try:
                    content = NutrientContent(
                        group_name=group_name,
                        nitrogen_percent=float(row["N_percent"]),
                        phosphorus_percent=float(row["P_percent"]),
                        carbon_percent=float(row["C_percent"]),
                        ash_percent=float(row["Ash_percent"]),
                    )
                    cycle.add_content(content)
                except (ValueError, KeyError) as e:
                    logger.warning(f"Could not create content for {group_name}: {e}")

            excretion_cols = [
                "N_excretion_rate",
                "P_excretion_rate",
                "Fecal_N_frac",
                "Fecal_P_frac",
            ]
            if all(col in df.columns for col in excretion_cols):
                try:
                    excretion = NutrientExcretion(
                        group_name=group_name,
                        n_excretion_rate=float(row["N_excretion_rate"]),
                        p_excretion_rate=float(row["P_excretion_rate"]),
                        fecal_n_fraction=float(row["Fecal_N_frac"]),
                        fecal_p_fraction=float(row["Fecal_P_frac"]),
                    )
                    cycle.add_excretion(excretion)
                except (ValueError, KeyError) as e:
                    logger.warning(f"Could not create excretion for {group_name}: {e}")

            uptake_cols = ["N_uptake_rate", "P_uptake_rate", "Ks_N", "Ks_P"]
            if all(col in df.columns for col in uptake_cols):
                try:
                    uptake = NutrientUptake(
                        group_name=group_name,
                        n_uptake_rate=float(row["N_uptake_rate"]),
                        p_uptake_rate=float(row["P_uptake_rate"]),
                        half_saturation_n=float(row["Ks_N"]),
                        half_saturation_p=float(row["Ks_P"]),
                    )
                    cycle.add_uptake(uptake)
                except (ValueError, KeyError) as e:
                    logger.warning(f"Could not create uptake for {group_name}: {e}")

        return cycle
add_content
add_content(content: NutrientContent) -> None

Add or update nutrient content for a group.

Parameters:

Name Type Description Default
content NutrientContent

Nutrient composition parameters.

required
Source code in pypath/core/nutrients.py
358
359
360
361
362
363
364
365
366
367
368
369
def add_content(self, content: NutrientContent) -> None:
    """Add or update nutrient content for a group.

    Parameters
    ----------
    content : NutrientContent
        Nutrient composition parameters.
    """
    if not content.is_valid():
        raise ValueError(f"Invalid nutrient content for {content.group_name}")
    self.contents[content.group_name] = content
    logger.debug(f"Added nutrient content for {content.group_name}")
add_excretion
add_excretion(excretion: NutrientExcretion) -> None

Add or update excretion parameters for a group.

Parameters:

Name Type Description Default
excretion NutrientExcretion

Excretion and fecal composition parameters.

required
Source code in pypath/core/nutrients.py
371
372
373
374
375
376
377
378
379
380
def add_excretion(self, excretion: NutrientExcretion) -> None:
    """Add or update excretion parameters for a group.

    Parameters
    ----------
    excretion : NutrientExcretion
        Excretion and fecal composition parameters.
    """
    self.excretions[excretion.group_name] = excretion
    logger.debug(f"Added excretion parameters for {excretion.group_name}")
add_uptake
add_uptake(uptake: NutrientUptake) -> None

Add or update uptake parameters for a group.

Parameters:

Name Type Description Default
uptake NutrientUptake

Nutrient uptake kinetics (typically for producers).

required
Source code in pypath/core/nutrients.py
382
383
384
385
386
387
388
389
390
391
def add_uptake(self, uptake: NutrientUptake) -> None:
    """Add or update uptake parameters for a group.

    Parameters
    ----------
    uptake : NutrientUptake
        Nutrient uptake kinetics (typically for producers).
    """
    self.uptakes[uptake.group_name] = uptake
    logger.debug(f"Added uptake parameters for {uptake.group_name}")
validate
validate() -> Tuple[bool, List[str]]

Validate nutrient cycle consistency.

Returns:

Type Description
tuple[bool, list[str]]

(is_valid, list of error/warning messages)

Source code in pypath/core/nutrients.py
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
def validate(self) -> Tuple[bool, List[str]]:
    """Validate nutrient cycle consistency.

    Returns
    -------
    tuple[bool, list[str]]
        (is_valid, list of error/warning messages)
    """
    messages = []

    if not self.contents and not self.excretions and not self.uptakes:
        messages.append("NutrientCycle is empty")
        return len(messages) == 0, messages

    for name, content in self.contents.items():
        if not content.is_valid():
            messages.append(f"Invalid content for {name}")

    for name, excretion in self.excretions.items():
        if name not in self.contents:
            messages.append(f"Excretion defined for {name} but no content")

    for name, uptake in self.uptakes.items():
        if name not in self.contents:
            messages.append(f"Uptake defined for {name} but no content")

    is_valid = len(messages) == 0
    return is_valid, messages
calculate_mass_balance
calculate_mass_balance(rpath_params: RpathParams) -> Dict[str, float]

Calculate nutrient mass balance across groups.

Parameters:

Name Type Description Default
rpath_params RpathParams

Ecopath model parameters with biomass and flow information.

required

Returns:

Type Description
dict

Mass balance summary with keys like 'total_n_biomass', 'total_p_biomass', 'balance_status'.

Source code in pypath/core/nutrients.py
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
def calculate_mass_balance(self, rpath_params: RpathParams) -> Dict[str, float]:
    """Calculate nutrient mass balance across groups.

    Parameters
    ----------
    rpath_params : RpathParams
        Ecopath model parameters with biomass and flow information.

    Returns
    -------
    dict
        Mass balance summary with keys like 'total_n_biomass',
        'total_p_biomass', 'balance_status'.
    """
    balance = {
        "total_n_biomass": 0.0,
        "total_p_biomass": 0.0,
        "total_c_biomass": 0.0,
        "groups_with_content": 0,
    }

    if not rpath_params.model.empty and "Biomass" in rpath_params.model.columns:
        for idx, row in rpath_params.model.iterrows():
            group = row.get("Group", "")
            biomass = row.get("Biomass", 0.0)

            if group in self.contents and biomass > 0:
                content = self.contents[group]
                balance["total_n_biomass"] += biomass * (
                    content.nitrogen_percent / 100.0
                )
                balance["total_p_biomass"] += biomass * (
                    content.phosphorus_percent / 100.0
                )
                balance["total_c_biomass"] += biomass * (
                    content.carbon_percent / 100.0
                )
                balance["groups_with_content"] += 1

    balance["balance_status"] = (
        "partial" if balance["groups_with_content"] > 0 else "undefined"
    )
    return balance
to_dataframe
to_dataframe() -> pd.DataFrame

Convert to pandas DataFrame representation.

Returns:

Type Description
DataFrame

DataFrame with one row per group, containing nutrient content, excretion, and uptake parameters.

Source code in pypath/core/nutrients.py
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
def to_dataframe(self) -> pd.DataFrame:
    """Convert to pandas DataFrame representation.

    Returns
    -------
    pd.DataFrame
        DataFrame with one row per group, containing nutrient
        content, excretion, and uptake parameters.
    """
    rows = []
    all_groups = (
        set(self.contents.keys())
        | set(self.excretions.keys())
        | set(self.uptakes.keys())
    )

    for group_name in sorted(all_groups):
        row = {"Group": group_name}

        if group_name in self.contents:
            content = self.contents[group_name]
            row.update(
                {
                    "N_percent": content.nitrogen_percent,
                    "P_percent": content.phosphorus_percent,
                    "C_percent": content.carbon_percent,
                    "Ash_percent": content.ash_percent,
                }
            )

        if group_name in self.excretions:
            excretion = self.excretions[group_name]
            row.update(
                {
                    "N_excretion_rate": excretion.n_excretion_rate,
                    "P_excretion_rate": excretion.p_excretion_rate,
                    "Fecal_N_frac": excretion.fecal_n_fraction,
                    "Fecal_P_frac": excretion.fecal_p_fraction,
                }
            )

        if group_name in self.uptakes:
            uptake = self.uptakes[group_name]
            row.update(
                {
                    "N_uptake_rate": uptake.n_uptake_rate,
                    "P_uptake_rate": uptake.p_uptake_rate,
                    "Ks_N": uptake.half_saturation_n,
                    "Ks_P": uptake.half_saturation_p,
                }
            )

        rows.append(row)

    return pd.DataFrame(rows) if rows else pd.DataFrame()
from_dataframe classmethod
from_dataframe(df: DataFrame) -> NutrientCycle

Create from pandas DataFrame representation.

Parameters:

Name Type Description Default
df DataFrame

DataFrame with nutrient parameters, one row per group.

required

Returns:

Type Description
NutrientCycle

Instantiated NutrientCycle object.

Source code in pypath/core/nutrients.py
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
@classmethod
def from_dataframe(cls, df: pd.DataFrame) -> NutrientCycle:
    """Create from pandas DataFrame representation.

    Parameters
    ----------
    df : pd.DataFrame
        DataFrame with nutrient parameters, one row per group.

    Returns
    -------
    NutrientCycle
        Instantiated NutrientCycle object.
    """
    cycle = cls()

    for _, row in df.iterrows():
        group_name = row.get("Group", "")
        if not group_name:
            continue

        content_cols = ["N_percent", "P_percent", "C_percent", "Ash_percent"]
        if all(col in df.columns for col in content_cols):
            try:
                content = NutrientContent(
                    group_name=group_name,
                    nitrogen_percent=float(row["N_percent"]),
                    phosphorus_percent=float(row["P_percent"]),
                    carbon_percent=float(row["C_percent"]),
                    ash_percent=float(row["Ash_percent"]),
                )
                cycle.add_content(content)
            except (ValueError, KeyError) as e:
                logger.warning(f"Could not create content for {group_name}: {e}")

        excretion_cols = [
            "N_excretion_rate",
            "P_excretion_rate",
            "Fecal_N_frac",
            "Fecal_P_frac",
        ]
        if all(col in df.columns for col in excretion_cols):
            try:
                excretion = NutrientExcretion(
                    group_name=group_name,
                    n_excretion_rate=float(row["N_excretion_rate"]),
                    p_excretion_rate=float(row["P_excretion_rate"]),
                    fecal_n_fraction=float(row["Fecal_N_frac"]),
                    fecal_p_fraction=float(row["Fecal_P_frac"]),
                )
                cycle.add_excretion(excretion)
            except (ValueError, KeyError) as e:
                logger.warning(f"Could not create excretion for {group_name}: {e}")

        uptake_cols = ["N_uptake_rate", "P_uptake_rate", "Ks_N", "Ks_P"]
        if all(col in df.columns for col in uptake_cols):
            try:
                uptake = NutrientUptake(
                    group_name=group_name,
                    n_uptake_rate=float(row["N_uptake_rate"]),
                    p_uptake_rate=float(row["P_uptake_rate"]),
                    half_saturation_n=float(row["Ks_N"]),
                    half_saturation_p=float(row["Ks_P"]),
                )
                cycle.add_uptake(uptake)
            except (ValueError, KeyError) as e:
                logger.warning(f"Could not create uptake for {group_name}: {e}")

    return cycle

validate_nutrient_cycle

validate_nutrient_cycle(cycle: NutrientCycle) -> Tuple[bool, List[str]]

Validate a complete nutrient cycling system.

Parameters:

Name Type Description Default
cycle NutrientCycle

Nutrient cycle to validate.

required

Returns:

Type Description
tuple[bool, list[str]]

(is_valid, list of error/warning messages)

Notes

This function performs comprehensive validation including: - Individual data integrity - Consistency across content, excretion, and uptake - Reasonable biological ranges

Source code in pypath/core/nutrients.py
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
def validate_nutrient_cycle(cycle: NutrientCycle) -> Tuple[bool, List[str]]:
    """Validate a complete nutrient cycling system.

    Parameters
    ----------
    cycle : NutrientCycle
        Nutrient cycle to validate.

    Returns
    -------
    tuple[bool, list[str]]
        (is_valid, list of error/warning messages)

    Notes
    -----
    This function performs comprehensive validation including:
    - Individual data integrity
    - Consistency across content, excretion, and uptake
    - Reasonable biological ranges
    """
    return cycle.validate()

estimate_excretion_from_pb

estimate_excretion_from_pb(pb_ratio: float, group_type: str = 'consumer') -> Dict[str, float]

Estimate excretion rates from Production/Biomass ratio.

Parameters:

Name Type Description Default
pb_ratio float

Production/Biomass ratio (1/year)

required
group_type str

Type of group ('consumer', 'producer', or 'detritus')

'consumer'

Returns:

Type Description
dict

Estimated excretion parameters with keys: - n_excretion_rate (% of consumption per day) - p_excretion_rate (% of consumption per day) - fecal_n_fraction - fecal_p_fraction

Notes

This is a heuristic based on typical aquatic food web stoichiometry. Empirical calibration may be required for specific systems.

Source code in pypath/core/nutrients.py
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
def estimate_excretion_from_pb(
    pb_ratio: float, group_type: str = "consumer"
) -> Dict[str, float]:
    """Estimate excretion rates from Production/Biomass ratio.

    Parameters
    ----------
    pb_ratio : float
        Production/Biomass ratio (1/year)
    group_type : str, default 'consumer'
        Type of group ('consumer', 'producer', or 'detritus')

    Returns
    -------
    dict
        Estimated excretion parameters with keys:
        - n_excretion_rate (% of consumption per day)
        - p_excretion_rate (% of consumption per day)
        - fecal_n_fraction
        - fecal_p_fraction

    Notes
    -----
    This is a heuristic based on typical aquatic food web stoichiometry.
    Empirical calibration may be required for specific systems.
    """
    if pb_ratio <= 0:
        raise ValueError(f"pb_ratio must be > 0, got {pb_ratio}")

    estimates = {}

    if group_type.lower() == "consumer":
        estimates["n_excretion_rate"] = min(15.0, pb_ratio * 100)
        estimates["p_excretion_rate"] = min(3.0, pb_ratio * 20)
        estimates["fecal_n_fraction"] = 0.4
        estimates["fecal_p_fraction"] = 0.6

    elif group_type.lower() == "producer":
        estimates["n_excretion_rate"] = 2.0
        estimates["p_excretion_rate"] = 0.5
        estimates["fecal_n_fraction"] = 0.1
        estimates["fecal_p_fraction"] = 0.1

    elif group_type.lower() == "detritus":
        estimates["n_excretion_rate"] = 0.0
        estimates["p_excretion_rate"] = 0.0
        estimates["fecal_n_fraction"] = 0.0
        estimates["fecal_p_fraction"] = 0.0

    else:
        raise ValueError(
            f"Unknown group_type: {group_type}. "
            f"Must be 'consumer', 'producer', or 'detritus'."
        )

    return estimates

Key Classes: - NutrientElement — Enum for N, P, C with molecular weights - NutrientContent — Elemental composition (%) with validation - NutrientExcretion — Excretion rates with fecal/dissolved partitioning - NutrientUptake — Producer kinetics (half-saturation, max rate) - NutrientCycle — Ecosystem-level cycling with mass balance

Key Functions: - uptake_rate_monod() — Monod saturation function for producer uptake - validate_nutrient_cycle() — Consistency checks across groups - estimate_excretion_from_pb() — Heuristic excretion estimation from P/B

Enhanced Landings System (Phase 1B.6)

Catch and landings tracking with temporal (seasonal) distribution, landing types, and aggregation. Interfaces with dynamic Ecosim monthly dispatch.

pypath.core.landings

Landings system for catch/landings tracking with temporal distribution.

This module implements catch and landings data management for fisheries, including support for multiple landing types, temporal distribution (seasonality), and validation of catch data.

Classes:

Name Description
LandingType

Enum defining types of catch/landings.

LandingRecord

Dataclass representing a single catch record.

LandingSeasonality

Dataclass for monthly catch distribution patterns.

LandingsData

Container for managing collections of landing records and seasonality patterns.

Functions:

Name Description
validate_landings

Validate a LandingsData collection.

estimate_seasonality_from_records

Infer monthly seasonality from historical records.

aggregate_landings

Sum catches by group, year, and/or landing type.

LandingType

Bases: Enum

Enumeration of catch/landings types.

Attributes:

Name Type Description
COMMERCIAL

Commercial fishing catch.

SUBSISTENCE

Subsistence/artisanal fishing.

RECREATIONAL

Recreational fishing catch.

UNREPORTED

Unreported or illegal fishing catch.

DISCARDS

Discarded bycatch.

Source code in pypath/core/landings.py
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
class LandingType(Enum):
    """Enumeration of catch/landings types.

    Attributes
    ----------
    COMMERCIAL
        Commercial fishing catch.
    SUBSISTENCE
        Subsistence/artisanal fishing.
    RECREATIONAL
        Recreational fishing catch.
    UNREPORTED
        Unreported or illegal fishing catch.
    DISCARDS
        Discarded bycatch.
    """

    COMMERCIAL = "commercial"
    SUBSISTENCE = "subsistence"
    RECREATIONAL = "recreational"
    UNREPORTED = "unreported"
    DISCARDS = "discards"

LandingRecord dataclass

A single catch/landings record.

Parameters:

Name Type Description Default
group_name str

Name of the functional group (e.g., "Cod", "Herring").

required
year int

Year of the landing.

required
month Optional[int]

Month of landing (1-12), or None if annual.

required
landing_type LandingType

Type of catch/landing.

required
catch_tons float

Catch in metric tons, must be >= 0.

required
value_usd Optional[float]

Economic value in USD, optional.

None
fleet_id Optional[str]

Identifier for the fleet (e.g., "Baltic_Demersal_Fleet").

None

Raises:

Type Description
ValueError

During validation if data is inconsistent.

Source code in pypath/core/landings.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
 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
@dataclass
class LandingRecord:
    """A single catch/landings record.

    Parameters
    ----------
    group_name : str
        Name of the functional group (e.g., "Cod", "Herring").
    year : int
        Year of the landing.
    month : Optional[int]
        Month of landing (1-12), or None if annual.
    landing_type : LandingType
        Type of catch/landing.
    catch_tons : float
        Catch in metric tons, must be >= 0.
    value_usd : Optional[float]
        Economic value in USD, optional.
    fleet_id : Optional[str]
        Identifier for the fleet (e.g., "Baltic_Demersal_Fleet").

    Raises
    ------
    ValueError
        During validation if data is inconsistent.
    """

    group_name: str
    year: int
    month: Optional[int]
    landing_type: LandingType
    catch_tons: float
    value_usd: Optional[float] = None
    fleet_id: Optional[str] = None

    def __post_init__(self) -> None:
        """Validate record on instantiation."""
        if not self.is_valid():
            raise ValueError(f"Invalid LandingRecord: {self}")

    def is_valid(self) -> bool:
        """Check if the record is valid.

        Returns
        -------
        bool
            True if group_name is non-empty, year is positive, month (if present)
            is in 1-12, catch_tons >= 0, and value_usd (if present) >= 0.
        """
        if not self.group_name:
            logger.warning("LandingRecord has empty group_name")
            return False
        if self.year <= 0:
            logger.warning(f"LandingRecord has invalid year: {self.year}")
            return False
        if self.month is not None and (self.month < 1 or self.month > 12):
            logger.warning(f"LandingRecord has invalid month: {self.month}")
            return False
        if self.catch_tons < 0:
            logger.warning(f"LandingRecord has negative catch: {self.catch_tons}")
            return False
        if self.value_usd is not None and self.value_usd < 0:
            logger.warning(f"LandingRecord has negative value: {self.value_usd}")
            return False
        return True

    def is_seasonal(self) -> bool:
        """Check if this record has seasonal (monthly) resolution.

        Returns
        -------
        bool
            True if month is specified.
        """
        return self.month is not None

    def to_dict(self) -> dict:
        """Convert to dictionary representation.

        Returns
        -------
        dict
            Dictionary with all fields; LandingType converted to string value.
        """
        return {
            "group_name": self.group_name,
            "year": self.year,
            "month": self.month,
            "landing_type": self.landing_type.value,
            "catch_tons": self.catch_tons,
            "value_usd": self.value_usd,
            "fleet_id": self.fleet_id,
        }

    @classmethod
    def from_dict(cls, data: dict) -> LandingRecord:
        """Create from dictionary representation.

        Parameters
        ----------
        data : dict
            Dictionary with record fields. landing_type can be string (enum value)
            or LandingType instance.

        Returns
        -------
        LandingRecord
            Reconstructed record.
        """
        data_copy = data.copy()
        if isinstance(data_copy["landing_type"], str):
            data_copy["landing_type"] = LandingType(data_copy["landing_type"])
        return cls(**data_copy)
__post_init__
__post_init__() -> None

Validate record on instantiation.

Source code in pypath/core/landings.py
101
102
103
104
def __post_init__(self) -> None:
    """Validate record on instantiation."""
    if not self.is_valid():
        raise ValueError(f"Invalid LandingRecord: {self}")
is_valid
is_valid() -> bool

Check if the record is valid.

Returns:

Type Description
bool

True if group_name is non-empty, year is positive, month (if present) is in 1-12, catch_tons >= 0, and value_usd (if present) >= 0.

Source code in pypath/core/landings.py
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
def is_valid(self) -> bool:
    """Check if the record is valid.

    Returns
    -------
    bool
        True if group_name is non-empty, year is positive, month (if present)
        is in 1-12, catch_tons >= 0, and value_usd (if present) >= 0.
    """
    if not self.group_name:
        logger.warning("LandingRecord has empty group_name")
        return False
    if self.year <= 0:
        logger.warning(f"LandingRecord has invalid year: {self.year}")
        return False
    if self.month is not None and (self.month < 1 or self.month > 12):
        logger.warning(f"LandingRecord has invalid month: {self.month}")
        return False
    if self.catch_tons < 0:
        logger.warning(f"LandingRecord has negative catch: {self.catch_tons}")
        return False
    if self.value_usd is not None and self.value_usd < 0:
        logger.warning(f"LandingRecord has negative value: {self.value_usd}")
        return False
    return True
is_seasonal
is_seasonal() -> bool

Check if this record has seasonal (monthly) resolution.

Returns:

Type Description
bool

True if month is specified.

Source code in pypath/core/landings.py
132
133
134
135
136
137
138
139
140
def is_seasonal(self) -> bool:
    """Check if this record has seasonal (monthly) resolution.

    Returns
    -------
    bool
        True if month is specified.
    """
    return self.month is not None
to_dict
to_dict() -> dict

Convert to dictionary representation.

Returns:

Type Description
dict

Dictionary with all fields; LandingType converted to string value.

Source code in pypath/core/landings.py
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
def to_dict(self) -> dict:
    """Convert to dictionary representation.

    Returns
    -------
    dict
        Dictionary with all fields; LandingType converted to string value.
    """
    return {
        "group_name": self.group_name,
        "year": self.year,
        "month": self.month,
        "landing_type": self.landing_type.value,
        "catch_tons": self.catch_tons,
        "value_usd": self.value_usd,
        "fleet_id": self.fleet_id,
    }
from_dict classmethod
from_dict(data: dict) -> LandingRecord

Create from dictionary representation.

Parameters:

Name Type Description Default
data dict

Dictionary with record fields. landing_type can be string (enum value) or LandingType instance.

required

Returns:

Type Description
LandingRecord

Reconstructed record.

Source code in pypath/core/landings.py
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
@classmethod
def from_dict(cls, data: dict) -> LandingRecord:
    """Create from dictionary representation.

    Parameters
    ----------
    data : dict
        Dictionary with record fields. landing_type can be string (enum value)
        or LandingType instance.

    Returns
    -------
    LandingRecord
        Reconstructed record.
    """
    data_copy = data.copy()
    if isinstance(data_copy["landing_type"], str):
        data_copy["landing_type"] = LandingType(data_copy["landing_type"])
    return cls(**data_copy)

LandingSeasonality dataclass

Temporal (monthly) distribution of catch for a functional group.

Parameters:

Name Type Description Default
group_name str

Name of the functional group.

required
monthly_proportions ndarray

Array of shape (12,) with monthly fractions summing to 1.0.

required

Raises:

Type Description
ValueError

If monthly_proportions does not sum to ~1.0 or has incorrect shape.

Source code in pypath/core/landings.py
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
@dataclass
class LandingSeasonality:
    """Temporal (monthly) distribution of catch for a functional group.

    Parameters
    ----------
    group_name : str
        Name of the functional group.
    monthly_proportions : np.ndarray
        Array of shape (12,) with monthly fractions summing to 1.0.

    Raises
    ------
    ValueError
        If monthly_proportions does not sum to ~1.0 or has incorrect shape.
    """

    group_name: str
    monthly_proportions: np.ndarray

    def __post_init__(self) -> None:
        """Validate seasonality on instantiation."""
        if not self.is_valid():
            raise ValueError(f"Invalid LandingSeasonality: {self.group_name}")
        self.monthly_proportions = np.asarray(self.monthly_proportions, dtype=float)

    def is_valid(self) -> bool:
        """Check if seasonality is valid.

        Returns
        -------
        bool
            True if proportions has length 12, all values >= 0, and sum ≈ 1.0.
        """
        if not isinstance(self.monthly_proportions, (np.ndarray, list)):
            return False
        props = np.asarray(self.monthly_proportions, dtype=float)
        if props.shape != (12,):
            logger.warning(
                f"LandingSeasonality has incorrect shape: {props.shape}, expected (12,)"
            )
            return False
        if np.any(props < 0):
            logger.warning("LandingSeasonality has negative proportions")
            return False
        if not np.isclose(np.sum(props), 1.0, atol=1e-6):
            logger.warning(
                f"LandingSeasonality proportions do not sum to 1.0: {np.sum(props)}"
            )
            return False
        return True

    def get_monthly_catch(self, annual_catch: float) -> np.ndarray:
        """Distribute annual catch across months using seasonality.

        Parameters
        ----------
        annual_catch : float
            Total annual catch in metric tons.

        Returns
        -------
        np.ndarray
            Array of shape (12,) with monthly catch values.
        """
        return np.asarray(self.monthly_proportions, dtype=float) * annual_catch

    def to_dict(self) -> dict:
        """Convert to dictionary representation.

        Returns
        -------
        dict
            Dictionary with group_name and monthly_proportions (as list).
        """
        return {
            "group_name": self.group_name,
            "monthly_proportions": self.monthly_proportions.tolist(),
        }

    @classmethod
    def from_dict(cls, data: dict) -> LandingSeasonality:
        """Create from dictionary representation.

        Parameters
        ----------
        data : dict
            Dictionary with group_name and monthly_proportions.

        Returns
        -------
        LandingSeasonality
            Reconstructed seasonality pattern.
        """
        return cls(
            group_name=data["group_name"],
            monthly_proportions=np.asarray(data["monthly_proportions"], dtype=float),
        )
__post_init__
__post_init__() -> None

Validate seasonality on instantiation.

Source code in pypath/core/landings.py
201
202
203
204
205
def __post_init__(self) -> None:
    """Validate seasonality on instantiation."""
    if not self.is_valid():
        raise ValueError(f"Invalid LandingSeasonality: {self.group_name}")
    self.monthly_proportions = np.asarray(self.monthly_proportions, dtype=float)
is_valid
is_valid() -> bool

Check if seasonality is valid.

Returns:

Type Description
bool

True if proportions has length 12, all values >= 0, and sum ≈ 1.0.

Source code in pypath/core/landings.py
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
def is_valid(self) -> bool:
    """Check if seasonality is valid.

    Returns
    -------
    bool
        True if proportions has length 12, all values >= 0, and sum ≈ 1.0.
    """
    if not isinstance(self.monthly_proportions, (np.ndarray, list)):
        return False
    props = np.asarray(self.monthly_proportions, dtype=float)
    if props.shape != (12,):
        logger.warning(
            f"LandingSeasonality has incorrect shape: {props.shape}, expected (12,)"
        )
        return False
    if np.any(props < 0):
        logger.warning("LandingSeasonality has negative proportions")
        return False
    if not np.isclose(np.sum(props), 1.0, atol=1e-6):
        logger.warning(
            f"LandingSeasonality proportions do not sum to 1.0: {np.sum(props)}"
        )
        return False
    return True
get_monthly_catch
get_monthly_catch(annual_catch: float) -> np.ndarray

Distribute annual catch across months using seasonality.

Parameters:

Name Type Description Default
annual_catch float

Total annual catch in metric tons.

required

Returns:

Type Description
ndarray

Array of shape (12,) with monthly catch values.

Source code in pypath/core/landings.py
233
234
235
236
237
238
239
240
241
242
243
244
245
246
def get_monthly_catch(self, annual_catch: float) -> np.ndarray:
    """Distribute annual catch across months using seasonality.

    Parameters
    ----------
    annual_catch : float
        Total annual catch in metric tons.

    Returns
    -------
    np.ndarray
        Array of shape (12,) with monthly catch values.
    """
    return np.asarray(self.monthly_proportions, dtype=float) * annual_catch
to_dict
to_dict() -> dict

Convert to dictionary representation.

Returns:

Type Description
dict

Dictionary with group_name and monthly_proportions (as list).

Source code in pypath/core/landings.py
248
249
250
251
252
253
254
255
256
257
258
259
def to_dict(self) -> dict:
    """Convert to dictionary representation.

    Returns
    -------
    dict
        Dictionary with group_name and monthly_proportions (as list).
    """
    return {
        "group_name": self.group_name,
        "monthly_proportions": self.monthly_proportions.tolist(),
    }
from_dict classmethod
from_dict(data: dict) -> LandingSeasonality

Create from dictionary representation.

Parameters:

Name Type Description Default
data dict

Dictionary with group_name and monthly_proportions.

required

Returns:

Type Description
LandingSeasonality

Reconstructed seasonality pattern.

Source code in pypath/core/landings.py
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
@classmethod
def from_dict(cls, data: dict) -> LandingSeasonality:
    """Create from dictionary representation.

    Parameters
    ----------
    data : dict
        Dictionary with group_name and monthly_proportions.

    Returns
    -------
    LandingSeasonality
        Reconstructed seasonality pattern.
    """
    return cls(
        group_name=data["group_name"],
        monthly_proportions=np.asarray(data["monthly_proportions"], dtype=float),
    )

LandingsData dataclass

Container for landing records and seasonality patterns.

Attributes:

Name Type Description
records List[LandingRecord]

Collection of landing records.

seasonality Dict[str, LandingSeasonality]

Seasonality patterns indexed by group name.

Source code in pypath/core/landings.py
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
@dataclass
class LandingsData:
    """Container for landing records and seasonality patterns.

    Attributes
    ----------
    records : List[LandingRecord]
        Collection of landing records.
    seasonality : Dict[str, LandingSeasonality]
        Seasonality patterns indexed by group name.
    """

    records: List[LandingRecord] = field(default_factory=list)
    seasonality: Dict[str, LandingSeasonality] = field(default_factory=dict)

    def add_record(self, record: LandingRecord) -> None:
        """Add a landing record.

        Parameters
        ----------
        record : LandingRecord
            Record to add. Must be valid.

        Raises
        ------
        ValueError
            If record is not valid.
        """
        if not record.is_valid():
            raise ValueError(f"Cannot add invalid record: {record}")
        self.records.append(record)
        logger.debug(
            f"Added landing record: {record.group_name} "
            f"({record.year}{'m' + str(record.month) if record.month else 'Y'}): "
            f"{record.catch_tons} tons"
        )

    def add_seasonality(self, seasonality: LandingSeasonality) -> None:
        """Add or update a seasonality pattern.

        Parameters
        ----------
        seasonality : LandingSeasonality
            Seasonality pattern. Must be valid.

        Raises
        ------
        ValueError
            If seasonality is not valid.
        """
        if not seasonality.is_valid():
            raise ValueError(f"Cannot add invalid seasonality: {seasonality}")
        self.seasonality[seasonality.group_name] = seasonality
        logger.debug(f"Added seasonality pattern for {seasonality.group_name}")

    def get_annual_catch(self, group_name: str, year: int) -> float:
        """Get total annual catch for a group and year.

        Aggregates across all landing types and seasons.

        Parameters
        ----------
        group_name : str
            Name of the functional group.
        year : int
            Year to query.

        Returns
        -------
        float
            Total catch in metric tons.
        """
        total = 0.0
        for record in self.records:
            if record.group_name == group_name and record.year == year:
                total += record.catch_tons
        return total

    def get_monthly_catch(self, group_name: str, year: int, month: int) -> float:
        """Get catch for a specific month.

        First checks for exact monthly records; if not found and seasonality
        exists, estimates from annual data using seasonality pattern.

        Parameters
        ----------
        group_name : str
            Name of the functional group.
        year : int
            Year to query.
        month : int
            Month (1-12).

        Returns
        -------
        float
            Monthly catch in metric tons.
        """
        if month < 1 or month > 12:
            raise ValueError(f"Invalid month: {month}")

        monthly_total = 0.0
        for record in self.records:
            if (
                record.group_name == group_name
                and record.year == year
                and record.month == month
            ):
                monthly_total += record.catch_tons

        if monthly_total > 0:
            return monthly_total

        if group_name in self.seasonality:
            annual = self.get_annual_catch(group_name, year)
            if annual > 0:
                seasonality = self.seasonality[group_name]
                monthly_dist = seasonality.get_monthly_catch(annual)
                return float(monthly_dist[month - 1])

        return 0.0

    def validate(self) -> Tuple[bool, List[str]]:
        """Validate all records and seasonality patterns.

        Returns
        -------
        Tuple[bool, List[str]]
            (is_valid, list_of_error_messages). is_valid is True if all
            records and seasonality patterns are valid and consistent.
        """
        errors: List[str] = []

        for i, record in enumerate(self.records):
            if not record.is_valid():
                errors.append(f"Record {i} is invalid: {record}")

        for name, season in self.seasonality.items():
            if not season.is_valid():
                errors.append(f"Seasonality for {name} is invalid")

        if errors:
            logger.warning(f"Validation found {len(errors)} error(s)")

        return len(errors) == 0, errors

    def to_dataframe(self) -> pd.DataFrame:
        """Convert records to DataFrame.

        Returns
        -------
        pd.DataFrame
            DataFrame with columns: group_name, year, month, landing_type,
            catch_tons, value_usd, fleet_id.
        """
        data = [record.to_dict() for record in self.records]
        if not data:
            return pd.DataFrame()
        return pd.DataFrame(data)

    @classmethod
    def from_dataframe(cls, df: pd.DataFrame) -> LandingsData:
        """Create LandingsData from DataFrame.

        Parameters
        ----------
        df : pd.DataFrame
            DataFrame with columns matching LandingRecord fields.

        Returns
        -------
        LandingsData
            Reconstructed container.
        """
        landings = cls()
        for _, row in df.iterrows():
            record = LandingRecord.from_dict(row.to_dict())
            landings.add_record(record)
        return landings
add_record
add_record(record: LandingRecord) -> None

Add a landing record.

Parameters:

Name Type Description Default
record LandingRecord

Record to add. Must be valid.

required

Raises:

Type Description
ValueError

If record is not valid.

Source code in pypath/core/landings.py
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
def add_record(self, record: LandingRecord) -> None:
    """Add a landing record.

    Parameters
    ----------
    record : LandingRecord
        Record to add. Must be valid.

    Raises
    ------
    ValueError
        If record is not valid.
    """
    if not record.is_valid():
        raise ValueError(f"Cannot add invalid record: {record}")
    self.records.append(record)
    logger.debug(
        f"Added landing record: {record.group_name} "
        f"({record.year}{'m' + str(record.month) if record.month else 'Y'}): "
        f"{record.catch_tons} tons"
    )
add_seasonality
add_seasonality(seasonality: LandingSeasonality) -> None

Add or update a seasonality pattern.

Parameters:

Name Type Description Default
seasonality LandingSeasonality

Seasonality pattern. Must be valid.

required

Raises:

Type Description
ValueError

If seasonality is not valid.

Source code in pypath/core/landings.py
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
def add_seasonality(self, seasonality: LandingSeasonality) -> None:
    """Add or update a seasonality pattern.

    Parameters
    ----------
    seasonality : LandingSeasonality
        Seasonality pattern. Must be valid.

    Raises
    ------
    ValueError
        If seasonality is not valid.
    """
    if not seasonality.is_valid():
        raise ValueError(f"Cannot add invalid seasonality: {seasonality}")
    self.seasonality[seasonality.group_name] = seasonality
    logger.debug(f"Added seasonality pattern for {seasonality.group_name}")
get_annual_catch
get_annual_catch(group_name: str, year: int) -> float

Get total annual catch for a group and year.

Aggregates across all landing types and seasons.

Parameters:

Name Type Description Default
group_name str

Name of the functional group.

required
year int

Year to query.

required

Returns:

Type Description
float

Total catch in metric tons.

Source code in pypath/core/landings.py
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
def get_annual_catch(self, group_name: str, year: int) -> float:
    """Get total annual catch for a group and year.

    Aggregates across all landing types and seasons.

    Parameters
    ----------
    group_name : str
        Name of the functional group.
    year : int
        Year to query.

    Returns
    -------
    float
        Total catch in metric tons.
    """
    total = 0.0
    for record in self.records:
        if record.group_name == group_name and record.year == year:
            total += record.catch_tons
    return total
get_monthly_catch
get_monthly_catch(group_name: str, year: int, month: int) -> float

Get catch for a specific month.

First checks for exact monthly records; if not found and seasonality exists, estimates from annual data using seasonality pattern.

Parameters:

Name Type Description Default
group_name str

Name of the functional group.

required
year int

Year to query.

required
month int

Month (1-12).

required

Returns:

Type Description
float

Monthly catch in metric tons.

Source code in pypath/core/landings.py
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_monthly_catch(self, group_name: str, year: int, month: int) -> float:
    """Get catch for a specific month.

    First checks for exact monthly records; if not found and seasonality
    exists, estimates from annual data using seasonality pattern.

    Parameters
    ----------
    group_name : str
        Name of the functional group.
    year : int
        Year to query.
    month : int
        Month (1-12).

    Returns
    -------
    float
        Monthly catch in metric tons.
    """
    if month < 1 or month > 12:
        raise ValueError(f"Invalid month: {month}")

    monthly_total = 0.0
    for record in self.records:
        if (
            record.group_name == group_name
            and record.year == year
            and record.month == month
        ):
            monthly_total += record.catch_tons

    if monthly_total > 0:
        return monthly_total

    if group_name in self.seasonality:
        annual = self.get_annual_catch(group_name, year)
        if annual > 0:
            seasonality = self.seasonality[group_name]
            monthly_dist = seasonality.get_monthly_catch(annual)
            return float(monthly_dist[month - 1])

    return 0.0
validate
validate() -> Tuple[bool, List[str]]

Validate all records and seasonality patterns.

Returns:

Type Description
Tuple[bool, List[str]]

(is_valid, list_of_error_messages). is_valid is True if all records and seasonality patterns are valid and consistent.

Source code in pypath/core/landings.py
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
def validate(self) -> Tuple[bool, List[str]]:
    """Validate all records and seasonality patterns.

    Returns
    -------
    Tuple[bool, List[str]]
        (is_valid, list_of_error_messages). is_valid is True if all
        records and seasonality patterns are valid and consistent.
    """
    errors: List[str] = []

    for i, record in enumerate(self.records):
        if not record.is_valid():
            errors.append(f"Record {i} is invalid: {record}")

    for name, season in self.seasonality.items():
        if not season.is_valid():
            errors.append(f"Seasonality for {name} is invalid")

    if errors:
        logger.warning(f"Validation found {len(errors)} error(s)")

    return len(errors) == 0, errors
to_dataframe
to_dataframe() -> pd.DataFrame

Convert records to DataFrame.

Returns:

Type Description
DataFrame

DataFrame with columns: group_name, year, month, landing_type, catch_tons, value_usd, fleet_id.

Source code in pypath/core/landings.py
427
428
429
430
431
432
433
434
435
436
437
438
439
def to_dataframe(self) -> pd.DataFrame:
    """Convert records to DataFrame.

    Returns
    -------
    pd.DataFrame
        DataFrame with columns: group_name, year, month, landing_type,
        catch_tons, value_usd, fleet_id.
    """
    data = [record.to_dict() for record in self.records]
    if not data:
        return pd.DataFrame()
    return pd.DataFrame(data)
from_dataframe classmethod
from_dataframe(df: DataFrame) -> LandingsData

Create LandingsData from DataFrame.

Parameters:

Name Type Description Default
df DataFrame

DataFrame with columns matching LandingRecord fields.

required

Returns:

Type Description
LandingsData

Reconstructed container.

Source code in pypath/core/landings.py
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
@classmethod
def from_dataframe(cls, df: pd.DataFrame) -> LandingsData:
    """Create LandingsData from DataFrame.

    Parameters
    ----------
    df : pd.DataFrame
        DataFrame with columns matching LandingRecord fields.

    Returns
    -------
    LandingsData
        Reconstructed container.
    """
    landings = cls()
    for _, row in df.iterrows():
        record = LandingRecord.from_dict(row.to_dict())
        landings.add_record(record)
    return landings

validate_landings

validate_landings(landings: LandingsData) -> Tuple[bool, List[str]]

Validate a LandingsData collection.

Parameters:

Name Type Description Default
landings LandingsData

Collection to validate.

required

Returns:

Type Description
Tuple[bool, List[str]]

(is_valid, error_messages).

Source code in pypath/core/landings.py
462
463
464
465
466
467
468
469
470
471
472
473
474
475
def validate_landings(landings: LandingsData) -> Tuple[bool, List[str]]:
    """Validate a LandingsData collection.

    Parameters
    ----------
    landings : LandingsData
        Collection to validate.

    Returns
    -------
    Tuple[bool, List[str]]
        (is_valid, error_messages).
    """
    return landings.validate()

estimate_seasonality_from_records

estimate_seasonality_from_records(records: List[LandingRecord], group_name: str) -> Optional[LandingSeasonality]

Estimate monthly seasonality from historical records.

Computes the proportion of catch in each month across all available records for a given group.

Parameters:

Name Type Description Default
records List[LandingRecord]

List of landing records with monthly resolution.

required
group_name str

Name of the functional group.

required

Returns:

Type Description
Optional[LandingSeasonality]

Seasonality pattern, or None if no monthly data available.

Source code in pypath/core/landings.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
def estimate_seasonality_from_records(
    records: List[LandingRecord], group_name: str
) -> Optional[LandingSeasonality]:
    """Estimate monthly seasonality from historical records.

    Computes the proportion of catch in each month across all available
    records for a given group.

    Parameters
    ----------
    records : List[LandingRecord]
        List of landing records with monthly resolution.
    group_name : str
        Name of the functional group.

    Returns
    -------
    Optional[LandingSeasonality]
        Seasonality pattern, or None if no monthly data available.
    """
    monthly_catch = np.zeros(12)
    total_catch = 0.0

    for record in records:
        if record.group_name == group_name and record.is_seasonal():
            month_idx = record.month - 1  # type: ignore
            monthly_catch[month_idx] += record.catch_tons
            total_catch += record.catch_tons

    if total_catch <= 0:
        logger.warning(
            f"No monthly catch data available for {group_name} to estimate seasonality"
        )
        return None

    proportions = monthly_catch / total_catch
    logger.debug(f"Estimated seasonality for {group_name} from {len(records)} records")

    return LandingSeasonality(group_name=group_name, monthly_proportions=proportions)

aggregate_landings

aggregate_landings(records: List[LandingRecord], group_name: Optional[str] = None, year: Optional[int] = None, landing_type: Optional[LandingType] = None) -> float

Aggregate landing records by filters.

Sum catch across records matching specified criteria. All filters are optional; if omitted, matches all records.

Parameters:

Name Type Description Default
records List[LandingRecord]

Records to aggregate.

required
group_name Optional[str]

Filter by functional group name.

None
year Optional[int]

Filter by year.

None
landing_type Optional[LandingType]

Filter by landing type.

None

Returns:

Type Description
float

Sum of catch_tons for matching records.

Source code in pypath/core/landings.py
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
def aggregate_landings(
    records: List[LandingRecord],
    group_name: Optional[str] = None,
    year: Optional[int] = None,
    landing_type: Optional[LandingType] = None,
) -> float:
    """Aggregate landing records by filters.

    Sum catch across records matching specified criteria. All filters are
    optional; if omitted, matches all records.

    Parameters
    ----------
    records : List[LandingRecord]
        Records to aggregate.
    group_name : Optional[str]
        Filter by functional group name.
    year : Optional[int]
        Filter by year.
    landing_type : Optional[LandingType]
        Filter by landing type.

    Returns
    -------
    float
        Sum of catch_tons for matching records.
    """
    total = 0.0
    for record in records:
        if group_name is not None and record.group_name != group_name:
            continue
        if year is not None and record.year != year:
            continue
        if landing_type is not None and record.landing_type != landing_type:
            continue
        total += record.catch_tons
    return total

Key Classes: - LandingType — Enum for 5 catch categories (COMMERCIAL, SUBSISTENCE, RECREATIONAL, UNREPORTED, DISCARDS) - LandingRecord — Month-level catch tracking with optional value and fleet ID - LandingSeasonality — Monthly catch distribution patterns (12-element array) - LandingsData — Multi-record container with aggregation and validation

Key Functions: - estimate_seasonality_from_records() — Infer monthly patterns from data - aggregate_landings() — Flexible aggregation (by group, year, type, season) - dispatch_to_monthly_steps() — Convert annual landings to monthly for Ecosim

Sensitivity Analysis

Morris OAT screening and Sobol variance-based sensitivity analysis.

pypath.core.sensitivity

Sensitivity analysis for Ecopath/Ecosim models.

Morris elementary effects screening and optional Sobol variance-based sensitivity analysis (requires SALib). SensitivityConfig.n_jobs runs the evaluations in worker processes; the results are the serial run's, bit for bit.

MorrisResult dataclass

Morris elementary effects screening results.

Source code in pypath/core/sensitivity.py
39
40
41
42
43
44
45
46
47
@dataclass
class MorrisResult:
    """Morris elementary effects screening results."""

    parameter_names: list[str]
    mu_star: np.ndarray
    sigma: np.ndarray
    mu: np.ndarray
    output_name: str = "Biomass"

SobolResult dataclass

Sobol variance-based sensitivity indices.

Source code in pypath/core/sensitivity.py
50
51
52
53
54
55
56
57
58
59
@dataclass
class SobolResult:
    """Sobol variance-based sensitivity indices."""

    parameter_names: list[str]
    S1: np.ndarray
    ST: np.ndarray
    S1_conf: np.ndarray
    ST_conf: np.ndarray
    output_name: str = "Biomass"

SensitivityConfig dataclass

Sensitivity analysis configuration.

Every evaluation balances the model with Ecopath and reads its biomass.

Attributes:

Name Type Description
method str

"morris" (elementary effects screening) or "sobol" (variance-based indices, needs SALib).

n_trajectories int

Morris trajectories; each costs one evaluation per parameter, plus one.

n_levels int

Morris grid levels p. The unit grid maps linearly onto each parameter's quantiles 1/(2p) to 1 - 1/(2p), the centres of the outermost of p equally likely bins.

n_samples int

Sobol base sample size N, best a power of 2. The analysis costs N * (2k + 2) evaluations for k parameters.

seed (int, optional)

Seed for the design and for Sobol's bootstrap confidence intervals; None draws fresh ones.

n_jobs int

Worker processes for the evaluations. 1 (the default) runs them serially in this process. A larger number runs that many processes, never more than there are evaluations; -1 uses one per CPU this process may use. The design is drawn up front from seed, each point is evaluated with warnings ignored and numpy's default floating-point error handling, and the outputs come back in order, so a parallel run gives the serial run's results, bit for bit. Starting workers takes from a fraction of a second to about 2 s, so they pay off on long designs (Sobol, or Morris on a large model).

output_variable str

Name stored as the result's output_name.

output_group_idx (int, optional)

Group whose biomass is the output; None sums the biomass of every group that is not a fleet.

ecopath_only bool

Not used: every evaluation is an Ecopath balance.

ecosim_years (range, optional)

Not used: every evaluation is an Ecopath balance.

mp_context (str, optional)

The multiprocessing start method for the workers: "forkserver", "spawn" or "fork". None uses forkserver on Linux and spawn on macOS and Windows, as CPython's own defaults do from Python 3.14.

forkserver and spawn start clean worker processes:

  • a script that calls run_sensitivity must do so under if __name__ == "__main__":;
  • params must be picklable;
  • workers do not see the caller's warning filters, logging configuration or later changes to os.environ;
  • starting the workers takes about 2 s per call when the caller is not a script that imports pypath (a notebook, for example).

"fork" starts workers fastest but is unsafe in a multi-threaded process (Python warns, and numpy's BLAS threads count), so ask for it only from a single-threaded script.

Source code in pypath/core/sensitivity.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
127
128
129
130
131
132
133
134
135
@dataclass
class SensitivityConfig:
    """Sensitivity analysis configuration.

    Every evaluation balances the model with Ecopath and reads its biomass.

    Attributes
    ----------
    method : str
        "morris" (elementary effects screening) or "sobol" (variance-based
        indices, needs SALib).
    n_trajectories : int
        Morris trajectories; each costs one evaluation per parameter, plus
        one.
    n_levels : int
        Morris grid levels ``p``. The unit grid maps linearly onto each
        parameter's quantiles ``1/(2p)`` to ``1 - 1/(2p)``, the centres of
        the outermost of ``p`` equally likely bins.
    n_samples : int
        Sobol base sample size ``N``, best a power of 2. The analysis costs
        ``N * (2k + 2)`` evaluations for ``k`` parameters.
    seed : int, optional
        Seed for the design and for Sobol's bootstrap confidence intervals;
        None draws fresh ones.
    n_jobs : int
        Worker processes for the evaluations. 1 (the default) runs them
        serially in this process. A larger number runs that many processes,
        never more than there are evaluations; -1 uses one per CPU this
        process may use. The design is drawn up front from ``seed``, each
        point is evaluated with warnings ignored and numpy's default
        floating-point error handling, and the outputs come back in order,
        so a parallel run gives the serial run's results, bit for bit.
        Starting workers takes from a fraction of a second to about 2 s, so
        they pay off on long designs (Sobol, or Morris on a large model).
    output_variable : str
        Name stored as the result's ``output_name``.
    output_group_idx : int, optional
        Group whose biomass is the output; None sums the biomass of every
        group that is not a fleet.
    ecopath_only : bool
        Not used: every evaluation is an Ecopath balance.
    ecosim_years : range, optional
        Not used: every evaluation is an Ecopath balance.
    mp_context : str, optional
        The multiprocessing start method for the workers: "forkserver",
        "spawn" or "fork". None uses forkserver on Linux and spawn on macOS
        and Windows, as CPython's own defaults do from Python 3.14.

        forkserver and spawn start clean worker processes:

        - a script that calls ``run_sensitivity`` must do so under
          ``if __name__ == "__main__":``;
        - ``params`` must be picklable;
        - workers do not see the caller's warning filters, logging
          configuration or later changes to ``os.environ``;
        - starting the workers takes about 2 s per call when the caller is
          not a script that imports pypath (a notebook, for example).

        "fork" starts workers fastest but is unsafe in a multi-threaded
        process (Python warns, and numpy's BLAS threads count), so ask for it
        only from a single-threaded script.
    """

    method: str = "morris"
    n_trajectories: int = 10
    n_levels: int = 4
    n_samples: int = 1024
    seed: int | None = None
    n_jobs: int = 1
    output_variable: str = "Biomass"
    output_group_idx: int | None = None
    ecopath_only: bool = False
    ecosim_years: range | None = None
    mp_context: str | None = None

run_sensitivity

run_sensitivity(params: 'RpathParams', config: SensitivityConfig | None = None, *, pedigree_config: 'PedigreeConfig | None' = None, progress_callback: Callable[[int, int], None] | None = None) -> MorrisResult | SobolResult

Run sensitivity analysis on Ecopath/Ecosim model.

Parameters:

Name Type Description Default
params RpathParams

Base Ecopath parameters.

required
config SensitivityConfig

Sensitivity configuration.

None
pedigree_config PedigreeConfig

EwE pedigree mapping.

None
progress_callback callable

Called with (current, total) after each model evaluation, in order, in this process (also when config.n_jobs runs workers).

None

Returns:

Type Description
MorrisResult or SobolResult
Source code in pypath/core/sensitivity.py
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
def run_sensitivity(
    params: "RpathParams",
    config: SensitivityConfig | None = None,
    *,
    pedigree_config: "PedigreeConfig | None" = None,
    progress_callback: Callable[[int, int], None] | None = None,
) -> MorrisResult | SobolResult:
    """Run sensitivity analysis on Ecopath/Ecosim model.

    Parameters
    ----------
    params : RpathParams
        Base Ecopath parameters.
    config : SensitivityConfig, optional
        Sensitivity configuration.
    pedigree_config : PedigreeConfig, optional
        EwE pedigree mapping.
    progress_callback : callable, optional
        Called with (current, total) after each model evaluation, in order,
        in this process (also when ``config.n_jobs`` runs workers).

    Returns
    -------
    MorrisResult or SobolResult
    """
    from pypath.core.pedigree import ScalarDistribution, build_distributions

    if config is None:
        config = SensitivityConfig()

    if config.method not in ("morris", "sobol"):
        raise ValueError(f"Unknown method: {config.method}")
    if config.method == "sobol" and not HAS_SALIB:
        raise ImportError("Install SALib for Sobol analysis: pip install SALib")
    context = mp_context(config.mp_context)  # refuses an unknown method

    rng = np.random.default_rng(config.seed)
    distributions = build_distributions(params, pedigree_config)
    scalars = [d for d in distributions if isinstance(d, ScalarDistribution)]

    if len(scalars) == 0:
        raise ValueError("No scalar distributions to analyze (all CVs are 0).")

    k = len(scalars)
    param_names = [f"{d.param_name}_{d.group_idx}" for d in scalars]
    keys = [(d.param_name, d.group_idx) for d in scalars]
    shapes = [_lognormal_shape(d.cv, d.base_value) for d in scalars]
    sigmas = np.array([sigma for sigma, _ in shapes])
    scales = np.array([scale for _, scale in shapes])
    # Every group but the fleets, by type: Ecopath keeps the model's order
    bio_idx = np.flatnonzero(
        params.model["Type"].to_numpy(dtype=float, na_value=np.nan) != 3
    )

    if config.method == "morris":
        trajectories = _generate_morris_trajectories(
            k,
            config.n_trajectories,
            config.n_levels,
            rng,
        )
        points = _morris_quantiles(trajectories, config.n_levels)
    else:
        n_runs = config.n_samples * (2 * k + 2)
        if n_runs > 10000:
            warnings.warn(
                f"Sobol analysis requires {n_runs} model evaluations.",
                UserWarning,
            )
        problem = {
            "num_vars": k,
            "names": param_names,
            "bounds": [[0.0, 1.0]] * k,
        }
        # Scrambled Sobol' points, reproducible from the seed
        points = sobol_sampler.sample(problem, config.n_samples, seed=config.seed)

    # Every point's parameter values in one vectorised call; it gives the
    # same values, bit for bit, as the quantile function point by point
    from scipy.stats import lognorm  # here: a sixth of the package's import time

    values = lognorm.ppf(points, s=sigmas, scale=scales)
    n_evals = len(values)
    n_workers = resolve_n_jobs(config.n_jobs, n_evals)

    y_values = np.empty(n_evals)
    with outputs_in_order(
        _evaluate_in_worker,
        values,
        n_workers=n_workers,
        context=context,
        serial=lambda row: _evaluate_point(
            params, keys, row, config.output_group_idx, bio_idx
        ),
        # Workers get the model once; each task carries a point's values
        initializer=_init_worker,
        initargs=(params, keys, config.output_group_idx, bio_idx),
        broken_message=(
            "A sensitivity worker process died. It may have run out of "
            "memory, or failed to unpickle the model. Try n_jobs=1, or "
            "mp_context='fork' from a single-threaded script."
        ),
    ) as outputs:
        for i, y in enumerate(outputs):
            y_values[i] = y
            if progress_callback:
                progress_callback(i + 1, n_evals)

    if config.method == "morris":
        result = _compute_elementary_effects(
            trajectories,
            y_values,
            k,
            config.n_trajectories,
            config.n_levels,
        )
        result.parameter_names = param_names
        result.output_name = config.output_variable
        return result

    # Impute NaN with mean (SALib requires exact N*(2k+2) rows)
    nan_mask = np.isnan(y_values)
    n_nan = np.sum(nan_mask)
    if n_nan > len(y_values) * 0.5:
        raise RuntimeError("More than 50% of model evaluations failed.")
    if n_nan > 0:
        y_values[nan_mask] = np.nanmean(y_values)
        logger.warning("Imputed %d NaN evaluations with mean for Sobol.", n_nan)

    # The seed also fixes the bootstrap behind the confidence intervals. SALib
    # reads a seed of 0 as no seed, so hand it a generator: for any other
    # seed it draws the same numbers as SALib's own default_rng(seed)
    bootstrap_rng = None if config.seed is None else np.random.default_rng(config.seed)
    Si = salib_sobol.analyze(problem, y_values, seed=bootstrap_rng)
    return SobolResult(
        parameter_names=param_names,
        S1=Si["S1"],
        ST=Si["ST"],
        S1_conf=Si["S1_conf"],
        ST_conf=Si["ST_conf"],
        output_name=config.output_variable,
    )

Simplified contaminant tracer (ecotracer)

Track contaminant concentrations through the food web coupled to Ecosim biomass dynamics. This is PyPath's own simplified tracer, not a port of EwE's Ecotracer: it has no environment pool, and its uptake and loss terms differ, so its results are not EwE Ecotracer output.

pypath.core.ecotracer

Simplified contaminant tracer, coupled to Ecosim.

Tracks contaminant concentrations alongside Ecosim biomass dynamics. Each group has initial concentration, environmental/immigration inputs, decay, assimilation, and metabolism rates.

This is PyPath's own simplified tracer, not a port of EwE's Ecotracer: it has no environment pool, and its uptake and loss terms differ. Its results should not be read as EwE Ecotracer output (deviation F in docs/parity/deviations.md).

EcotracerParams dataclass

Per-group tracer parameters.

All arrays are 0-based, length n_groups = NUM_LIVING + NUM_DEAD. No fleets, no padding column.

Parameters:

Name Type Description Default
czero ndarray

Initial concentration per group (n_groups,).

required
cenv ndarray

Environmental input concentration (n_groups,).

required
cimmig ndarray

Immigration input concentration (n_groups,).

required
cdecay ndarray

Decay rate (n_groups,).

required
cassim ndarray

Assimilation proportion, 0-1 (n_groups,).

required
cmetab ndarray

Metabolism loss rate (n_groups,).

required
Source code in pypath/core/ecotracer.py
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
@dataclass
class EcotracerParams:
    """Per-group tracer parameters.

    All arrays are 0-based, length n_groups = NUM_LIVING + NUM_DEAD.
    No fleets, no padding column.

    Parameters
    ----------
    czero : np.ndarray
        Initial concentration per group (n_groups,).
    cenv : np.ndarray
        Environmental input concentration (n_groups,).
    cimmig : np.ndarray
        Immigration input concentration (n_groups,).
    cdecay : np.ndarray
        Decay rate (n_groups,).
    cassim : np.ndarray
        Assimilation proportion, 0-1 (n_groups,).
    cmetab : np.ndarray
        Metabolism loss rate (n_groups,).
    """

    czero: np.ndarray
    cenv: np.ndarray
    cimmig: np.ndarray
    cdecay: np.ndarray
    cassim: np.ndarray
    cmetab: np.ndarray

EcotracerResult dataclass

Output time series from Ecotracer simulation.

Parameters:

Name Type Description Default
out_Conc ndarray

Monthly concentrations (n_months+1, n_groups). Index 0 is initial state.

required
annual_Conc ndarray

Annual average concentrations (n_years, n_groups).

required
group_names list[str]

Group name labels.

required
Source code in pypath/core/ecotracer.py
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
@dataclass
class EcotracerResult:
    """Output time series from Ecotracer simulation.

    Parameters
    ----------
    out_Conc : np.ndarray
        Monthly concentrations (n_months+1, n_groups). Index 0 is initial state.
    annual_Conc : np.ndarray
        Annual average concentrations (n_years, n_groups).
    group_names : list[str]
        Group name labels.
    """

    out_Conc: np.ndarray
    annual_Conc: np.ndarray
    group_names: list[str]

create_ecotracer_params

create_ecotracer_params(n_groups: int) -> EcotracerParams

Create EcotracerParams with sensible defaults.

Defaults: czero=0, cenv=0, cimmig=0, cdecay=0, cassim=1.0, cmetab=0.

Source code in pypath/core/ecotracer.py
74
75
76
77
78
79
80
81
82
83
84
85
86
def create_ecotracer_params(n_groups: int) -> EcotracerParams:
    """Create EcotracerParams with sensible defaults.

    Defaults: czero=0, cenv=0, cimmig=0, cdecay=0, cassim=1.0, cmetab=0.
    """
    return EcotracerParams(
        czero=np.zeros(n_groups),
        cenv=np.zeros(n_groups),
        cimmig=np.zeros(n_groups),
        cdecay=np.zeros(n_groups),
        cassim=np.ones(n_groups),
        cmetab=np.zeros(n_groups),
    )

ecotracer_deriv

ecotracer_deriv(conc: ndarray, biomass: ndarray, Q_matrix: ndarray, params: EcotracerParams, detritus_fate: ndarray | None = None, n_living: int = 0) -> np.ndarray

Compute dC/dt for all groups.

Parameters:

Name Type Description Default
conc ndarray

Current concentrations (n_groups,).

required
biomass ndarray

Current biomass (n_groups,).

required
Q_matrix ndarray

Consumption matrix Q[prey, pred] (n_groups, n_groups), 0-based.

required
params EcotracerParams

Tracer parameters.

required
detritus_fate ndarray

Detritus fate fractions (n_living, n_detritus). When None, detritus only decays.

None
n_living int

Number of living groups (groups 0..n_living-1 are living, n_living..n_groups-1 are detritus).

0

Returns:

Type Description
ndarray

dC/dt for each group (n_groups,).

Source code in pypath/core/ecotracer.py
 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
def ecotracer_deriv(
    conc: np.ndarray,
    biomass: np.ndarray,
    Q_matrix: np.ndarray,
    params: EcotracerParams,
    detritus_fate: np.ndarray | None = None,
    n_living: int = 0,
) -> np.ndarray:
    """Compute dC/dt for all groups.

    Parameters
    ----------
    conc : np.ndarray
        Current concentrations (n_groups,).
    biomass : np.ndarray
        Current biomass (n_groups,).
    Q_matrix : np.ndarray
        Consumption matrix Q[prey, pred] (n_groups, n_groups), 0-based.
    params : EcotracerParams
        Tracer parameters.
    detritus_fate : np.ndarray, optional
        Detritus fate fractions (n_living, n_detritus). When None, detritus
        only decays.
    n_living : int
        Number of living groups (groups 0..n_living-1 are living,
        n_living..n_groups-1 are detritus).

    Returns
    -------
    np.ndarray
        dC/dt for each group (n_groups,).
    """
    n_groups = len(conc)
    deriv = np.zeros(n_groups)

    # Living groups: dietary intake + environmental inputs - losses
    for i in range(n_living):
        # Dietary intake: cassim_i * sum_j(Q[j, i] * C[j]) / B_i
        if biomass[i] > _BIOMASS_THRESHOLD:
            dietary_intake = (
                params.cassim[i] * np.dot(Q_matrix[:, i], conc) / biomass[i]
            )
        else:
            dietary_intake = 0.0

        deriv[i] = (
            dietary_intake
            + params.cenv[i]
            + params.cimmig[i]
            - (params.cdecay[i] + params.cmetab[i]) * conc[i]
        )

    # Detritus groups: contaminant from dead matter + cenv - decay
    for i in range(n_living, n_groups):
        det_input = 0.0
        if detritus_fate is not None:
            det_idx = i - n_living
            if det_idx < detritus_fate.shape[1]:
                # Weighted average of contributor concentrations
                for j in range(n_living):
                    det_input += detritus_fate[j, det_idx] * conc[j]

        deriv[i] = (
            det_input
            + params.cenv[i]
            + params.cimmig[i]
            - (params.cdecay[i] + params.cmetab[i]) * conc[i]
        )

    return deriv

ecotracer_step

ecotracer_step(conc: ndarray, biomass: ndarray, Q_matrix: ndarray, params: EcotracerParams, dt: float, detritus_fate: ndarray | None = None, n_living: int = 0) -> np.ndarray

Analytic update for tracer concentration (unconditionally stable).

For each group i: input_i = dietary_intake_i + cenv_i + cimmig_i loss_rate_i = cdecay_i + cmetab_i if loss_rate_i > 0: C_i(t+dt) = input_i/loss_rate_i + (C_i - input_i/loss_rate_i) * exp(-loss_rate_i*dt) else: C_i(t+dt) = C_i + input_i * dt

Parameters:

Name Type Description Default
conc ndarray

Current concentrations (n_groups,).

required
biomass ndarray

Current biomass (n_groups,).

required
Q_matrix ndarray

Consumption matrix Q[prey, pred] (n_groups, n_groups), 0-based.

required
params EcotracerParams

Tracer parameters.

required
dt float

Timestep (typically 1/12 for monthly).

required
detritus_fate ndarray

Detritus fate fractions (n_living, n_detritus).

None
n_living int

Number of living groups.

0

Returns:

Type Description
ndarray

Updated concentrations (n_groups,), clamped to >= 0.

Source code in pypath/core/ecotracer.py
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
def ecotracer_step(
    conc: np.ndarray,
    biomass: np.ndarray,
    Q_matrix: np.ndarray,
    params: EcotracerParams,
    dt: float,
    detritus_fate: np.ndarray | None = None,
    n_living: int = 0,
) -> np.ndarray:
    """Analytic update for tracer concentration (unconditionally stable).

    For each group i:
      input_i = dietary_intake_i + cenv_i + cimmig_i
      loss_rate_i = cdecay_i + cmetab_i
      if loss_rate_i > 0:
          C_i(t+dt) = input_i/loss_rate_i + (C_i - input_i/loss_rate_i) * exp(-loss_rate_i*dt)
      else:
          C_i(t+dt) = C_i + input_i * dt

    Parameters
    ----------
    conc : np.ndarray
        Current concentrations (n_groups,).
    biomass : np.ndarray
        Current biomass (n_groups,).
    Q_matrix : np.ndarray
        Consumption matrix Q[prey, pred] (n_groups, n_groups), 0-based.
    params : EcotracerParams
        Tracer parameters.
    dt : float
        Timestep (typically 1/12 for monthly).
    detritus_fate : np.ndarray, optional
        Detritus fate fractions (n_living, n_detritus).
    n_living : int
        Number of living groups.

    Returns
    -------
    np.ndarray
        Updated concentrations (n_groups,), clamped to >= 0.
    """
    n_groups = len(conc)
    new_conc = np.zeros(n_groups)

    # Compute instantaneous inputs for each group
    for i in range(n_groups):
        # Dietary intake (living groups only)
        if i < n_living and biomass[i] > _BIOMASS_THRESHOLD:
            dietary_intake = (
                params.cassim[i] * np.dot(Q_matrix[:, i], conc) / biomass[i]
            )
        elif i >= n_living:
            # Detritus input
            dietary_intake = 0.0
            if detritus_fate is not None:
                det_idx = i - n_living
                if det_idx < detritus_fate.shape[1]:
                    for j in range(n_living):
                        dietary_intake += detritus_fate[j, det_idx] * conc[j]
        else:
            dietary_intake = 0.0

        total_input = dietary_intake + params.cenv[i] + params.cimmig[i]
        loss_rate = params.cdecay[i] + params.cmetab[i]

        if loss_rate > 0:
            # Analytic solution: exact for constant input within timestep
            equilibrium = total_input / loss_rate
            new_conc[i] = equilibrium + (conc[i] - equilibrium) * math.exp(
                -loss_rate * dt
            )
        else:
            # No loss: simple linear accumulation
            new_conc[i] = conc[i] + total_input * dt

    # Clamp to non-negative
    np.clip(new_conc, 0.0, None, out=new_conc)
    return new_conc

Fleet Dynamics

Dynamic fleet effort response to profitability with quota management.

pypath.core.fleet_dynamics

Fleet Dynamics: profit-responsive effort and TAC quota management.

Models fleet capacity dynamics where effort responds to economic profit signals, and total allowable catch (TAC) quotas can cap fishing activity.

Each fleet has capacity that grows when profitable and depreciates otherwise. Effort is derived from capacity via an efficiency power relationship.

FleetEconParams dataclass

Economic parameters for fleet dynamics.

All cost/price arrays are indexed by fishing link (1-based externally, but stored as 0-based arrays here).

Parameters:

Name Type Description Default
fixed_cost ndarray

Fixed annual cost per fleet (n_fleets,). Does not depend on effort.

required
variable_cost ndarray

Variable cost per fleet per unit capacity (n_fleets,).

required
sailing_cost ndarray

Sailing cost per fleet per unit capacity (n_fleets,).

required
price ndarray

Price per unit catch per fishing link (n_links,).

required
cap_depreciate ndarray

Capacity depreciation rate per fleet (n_fleets,).

required
cap_base_growth ndarray

Base capacity growth rate per fleet when profitable (n_fleets,).

required
eff_power ndarray

Efficiency power: effort = capacity ** eff_power (n_fleets,).

required
tac ndarray or None

Total allowable catch (n_fleets, n_groups). None means no TAC limits.

None
Source code in pypath/core/fleet_dynamics.py
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
@dataclass
class FleetEconParams:
    """Economic parameters for fleet dynamics.

    All cost/price arrays are indexed by fishing link (1-based externally,
    but stored as 0-based arrays here).

    Parameters
    ----------
    fixed_cost : np.ndarray
        Fixed annual cost per fleet (n_fleets,). Does not depend on effort.
    variable_cost : np.ndarray
        Variable cost per fleet per unit capacity (n_fleets,).
    sailing_cost : np.ndarray
        Sailing cost per fleet per unit capacity (n_fleets,).
    price : np.ndarray
        Price per unit catch per fishing link (n_links,).
    cap_depreciate : np.ndarray
        Capacity depreciation rate per fleet (n_fleets,).
    cap_base_growth : np.ndarray
        Base capacity growth rate per fleet when profitable (n_fleets,).
    eff_power : np.ndarray
        Efficiency power: effort = capacity ** eff_power (n_fleets,).
    tac : np.ndarray or None
        Total allowable catch (n_fleets, n_groups). None means no TAC limits.
    """

    fixed_cost: np.ndarray
    variable_cost: np.ndarray
    sailing_cost: np.ndarray
    price: np.ndarray
    cap_depreciate: np.ndarray
    cap_base_growth: np.ndarray
    eff_power: np.ndarray
    tac: np.ndarray | None = None

FleetDynamicsResult dataclass

Output time series from fleet dynamics simulation.

Parameters:

Name Type Description Default
out_Effort ndarray

Monthly effort per fleet (n_months, n_fleets).

required
out_Revenue ndarray

Monthly revenue per fleet (n_months, n_fleets).

required
out_Cost ndarray

Monthly cost per fleet (n_months, n_fleets).

required
out_Profit ndarray

Monthly profit per fleet (n_months, n_fleets).

required
annual_Effort ndarray

Annual average effort per fleet (n_years, n_fleets).

required
annual_Profit ndarray

Annual total profit per fleet (n_years, n_fleets).

required
fleet_names list[str]

Fleet name labels.

required
Source code in pypath/core/fleet_dynamics.py
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
@dataclass
class FleetDynamicsResult:
    """Output time series from fleet dynamics simulation.

    Parameters
    ----------
    out_Effort : np.ndarray
        Monthly effort per fleet (n_months, n_fleets).
    out_Revenue : np.ndarray
        Monthly revenue per fleet (n_months, n_fleets).
    out_Cost : np.ndarray
        Monthly cost per fleet (n_months, n_fleets).
    out_Profit : np.ndarray
        Monthly profit per fleet (n_months, n_fleets).
    annual_Effort : np.ndarray
        Annual average effort per fleet (n_years, n_fleets).
    annual_Profit : np.ndarray
        Annual total profit per fleet (n_years, n_fleets).
    fleet_names : list[str]
        Fleet name labels.
    """

    out_Effort: np.ndarray
    out_Revenue: np.ndarray
    out_Cost: np.ndarray
    out_Profit: np.ndarray
    annual_Effort: np.ndarray
    annual_Profit: np.ndarray
    fleet_names: list[str]

create_fleet_econ_params

create_fleet_econ_params(n_fleets: int, n_links: int) -> FleetEconParams

Create FleetEconParams with sensible defaults.

Defaults: all cost/depreciation rates zero, eff_power=1.0, tac=None.

Parameters:

Name Type Description Default
n_fleets int

Number of fleets.

required
n_links int

Number of fishing links (fleet-group combinations).

required

Returns:

Type Description
FleetEconParams

Parameter object with zero arrays and eff_power=1.0.

Source code in pypath/core/fleet_dynamics.py
 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
def create_fleet_econ_params(n_fleets: int, n_links: int) -> FleetEconParams:
    """Create FleetEconParams with sensible defaults.

    Defaults: all cost/depreciation rates zero, eff_power=1.0, tac=None.

    Parameters
    ----------
    n_fleets : int
        Number of fleets.
    n_links : int
        Number of fishing links (fleet-group combinations).

    Returns
    -------
    FleetEconParams
        Parameter object with zero arrays and eff_power=1.0.
    """
    return FleetEconParams(
        fixed_cost=np.zeros(n_fleets),
        variable_cost=np.zeros(n_fleets),
        sailing_cost=np.zeros(n_fleets),
        price=np.zeros(n_links),
        cap_depreciate=np.zeros(n_fleets),
        cap_base_growth=np.zeros(n_fleets),
        eff_power=np.ones(n_fleets),
        tac=None,
    )

fleet_dynamics_step

fleet_dynamics_step(capacity: ndarray, monthly_catch: ndarray, cumulative_catch: ndarray, params: FleetEconParams, fish_through: ndarray, fish_from: ndarray, fleet_lookup: dict, n_fleets: int, dt: float = 1.0 / 12) -> tuple[np.ndarray, np.ndarray]

Advance fleet capacity and effort by one time step.

Computes revenue from catches, costs from capacity, a profit signal, then updates capacity using a logistic-style ODE.

Parameters:

Name Type Description Default
capacity ndarray

Current fleet capacities (n_fleets,). Modified in place via copy.

required
monthly_catch ndarray

Catch from this month's fishing links (n_links,). 1-based index 0 unused.

required
cumulative_catch ndarray

Cumulative annual catch per fleet per group (n_fleets, n_groups). Not modified here; used externally.

required
params FleetEconParams

Economic parameters.

required
fish_through ndarray

Fleet group index per fishing link (1-based, length n_links+1, index 0 unused).

required
fish_from ndarray

Prey group index per fishing link (1-based, length n_links+1, index 0 unused).

required
fleet_lookup dict

Maps gear_0based (int) -> 1-based gear array index (int).

required
n_fleets int

Number of fleets.

required
dt float

Time step in years (default 1/12 for monthly).

1.0 / 12

Returns:

Name Type Description
new_capacity ndarray

Updated fleet capacities (n_fleets,).

effort ndarray

Fleet effort this step (n_fleets,), effort = capacity ** eff_power.

Source code in pypath/core/fleet_dynamics.py
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
def fleet_dynamics_step(
    capacity: np.ndarray,
    monthly_catch: np.ndarray,
    cumulative_catch: np.ndarray,
    params: FleetEconParams,
    fish_through: np.ndarray,
    fish_from: np.ndarray,
    fleet_lookup: dict,
    n_fleets: int,
    dt: float = 1.0 / 12,
) -> tuple[np.ndarray, np.ndarray]:
    """Advance fleet capacity and effort by one time step.

    Computes revenue from catches, costs from capacity, a profit signal,
    then updates capacity using a logistic-style ODE.

    Parameters
    ----------
    capacity : np.ndarray
        Current fleet capacities (n_fleets,). Modified in place via copy.
    monthly_catch : np.ndarray
        Catch from this month's fishing links (n_links,). 1-based index 0 unused.
    cumulative_catch : np.ndarray
        Cumulative annual catch per fleet per group (n_fleets, n_groups).
        Not modified here; used externally.
    params : FleetEconParams
        Economic parameters.
    fish_through : np.ndarray
        Fleet group index per fishing link (1-based, length n_links+1,
        index 0 unused).
    fish_from : np.ndarray
        Prey group index per fishing link (1-based, length n_links+1,
        index 0 unused).
    fleet_lookup : dict
        Maps gear_0based (int) -> 1-based gear array index (int).
    n_fleets : int
        Number of fleets.
    dt : float
        Time step in years (default 1/12 for monthly).

    Returns
    -------
    new_capacity : np.ndarray
        Updated fleet capacities (n_fleets,).
    effort : np.ndarray
        Fleet effort this step (n_fleets,), effort = capacity ** eff_power.
    """
    new_capacity = capacity.copy()
    revenue = np.zeros(n_fleets)
    cost = np.zeros(n_fleets)

    # Step 1: Compute revenue per fleet from fishing links
    # price array has same length as FishFrom (index 0 unused, like FishFrom[0])
    for i in range(1, len(monthly_catch)):
        gear_0based = int(fish_through[i]) - 1
        gear_idx = fleet_lookup.get(gear_0based, 0)
        if gear_idx == 0:
            continue
        fleet_0 = gear_idx - 1
        if fleet_0 < 0 or fleet_0 >= n_fleets:
            continue
        price_i = params.price[i] if i < len(params.price) else 0.0
        revenue[fleet_0] += monthly_catch[i] * price_i

    # Step 2: Compute cost per fleet
    for g in range(n_fleets):
        cost[g] = (
            params.fixed_cost[g] / 12.0
            + (params.variable_cost[g] + params.sailing_cost[g]) * new_capacity[g]
        )

    # Step 3: Compute profit
    profit = revenue - cost

    # Step 4–6: Update capacity
    for g in range(n_fleets):
        denom = max(revenue[g], cost[g])
        if denom <= _EPSILON:
            denom = _EPSILON
        profit_signal = profit[g] / denom

        # Capacity ODE: dC/dt = (cap_base_growth * max(signal, 0) - cap_depreciate) * C
        growth_term = params.cap_base_growth[g] * max(profit_signal, 0.0)
        decay_term = params.cap_depreciate[g]
        new_capacity[g] += (growth_term - decay_term) * new_capacity[g] * dt
        new_capacity[g] = max(new_capacity[g], _CAPACITY_FLOOR)

    # Step 7: Effort from capacity
    effort = new_capacity**params.eff_power

    return new_capacity, effort

apply_quota_caps

apply_quota_caps(fish_q: ndarray, cumulative_catch: ndarray, tac: ndarray, fish_through: ndarray, fish_from: ndarray, fleet_lookup: dict) -> np.ndarray

Zero out fishing catchability for links that have reached their TAC.

Parameters:

Name Type Description Default
fish_q ndarray

Current FishQ values per fishing link (n_links+1,), index 0 unused.

required
cumulative_catch ndarray

Cumulative annual catch (n_fleets, n_groups), 0-based indices.

required
tac ndarray

Total allowable catch allocation (n_fleets, n_groups), 0-based.

required
fish_through ndarray

Fleet group index per fishing link (1-based, length n_links+1).

required
fish_from ndarray

Prey group index per fishing link (1-based, length n_links+1).

required
fleet_lookup dict

Maps gear_0based (int) -> 1-based gear array index (int).

required

Returns:

Type Description
ndarray

Copy of fish_q with zeroed entries for TAC-exhausted links.

Source code in pypath/core/fleet_dynamics.py
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
def apply_quota_caps(
    fish_q: np.ndarray,
    cumulative_catch: np.ndarray,
    tac: np.ndarray,
    fish_through: np.ndarray,
    fish_from: np.ndarray,
    fleet_lookup: dict,
) -> np.ndarray:
    """Zero out fishing catchability for links that have reached their TAC.

    Parameters
    ----------
    fish_q : np.ndarray
        Current FishQ values per fishing link (n_links+1,), index 0 unused.
    cumulative_catch : np.ndarray
        Cumulative annual catch (n_fleets, n_groups), 0-based indices.
    tac : np.ndarray
        Total allowable catch allocation (n_fleets, n_groups), 0-based.
    fish_through : np.ndarray
        Fleet group index per fishing link (1-based, length n_links+1).
    fish_from : np.ndarray
        Prey group index per fishing link (1-based, length n_links+1).
    fleet_lookup : dict
        Maps gear_0based (int) -> 1-based gear array index (int).

    Returns
    -------
    np.ndarray
        Copy of fish_q with zeroed entries for TAC-exhausted links.
    """
    new_fish_q = fish_q.copy()
    n_links = len(fish_q) - 1  # index 0 is unused padding

    for i in range(1, n_links + 1):
        gear_0based = int(fish_through[i]) - 1
        gear_idx = fleet_lookup.get(gear_0based, 0)
        if gear_idx == 0:
            continue
        fleet_0 = gear_idx - 1

        group_0 = int(fish_from[i]) - 1
        if group_0 < 0:
            continue

        n_fleets, n_groups = tac.shape
        if fleet_0 < 0 or fleet_0 >= n_fleets:
            continue
        if group_0 >= n_groups:
            continue

        if cumulative_catch[fleet_0, group_0] >= tac[fleet_0, group_0]:
            new_fish_q[i] = 0.0

    return new_fish_q

Ecological Indicators

Ecosystem-level indicators including Ulanowicz flow analysis, Finn Cycling Index, transfer efficiency, and system maturity indices.

pypath.core.indicators

Ecological indicators: flow analysis and ecosystem summary metrics.

Provides Ulanowicz ascendency framework (TST, ascendency, capacity, overhead, Finn cycling index) and ecosystem summary indicators (MTL catch, Marine Trophic Index, Shannon diversity, Kempton Q, gross efficiency).

FlowAnalysis dataclass

Results of Ulanowicz flow analysis.

Attributes:

Name Type Description
total_system_throughput float

TST: sum of all flows through the system.

ascendency float

System organization (bits x flow).

capacity float

Development capacity (upper bound for ascendency).

overhead float

Capacity - Ascendency (resilience reserve).

relative_ascendency float

Ascendency / Capacity [0-1].

finn_cycling_index float

Fraction of TST recycled [0-1].

transfer_efficiency ndarray

Per-trophic-level transfer efficiency array.

Source code in pypath/core/indicators.py
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
@dataclass
class FlowAnalysis:
    """Results of Ulanowicz flow analysis.

    Attributes
    ----------
    total_system_throughput : float
        TST: sum of all flows through the system.
    ascendency : float
        System organization (bits x flow).
    capacity : float
        Development capacity (upper bound for ascendency).
    overhead : float
        Capacity - Ascendency (resilience reserve).
    relative_ascendency : float
        Ascendency / Capacity [0-1].
    finn_cycling_index : float
        Fraction of TST recycled [0-1].
    transfer_efficiency : np.ndarray
        Per-trophic-level transfer efficiency array.
    """

    total_system_throughput: float
    ascendency: float
    capacity: float
    overhead: float
    relative_ascendency: float
    finn_cycling_index: float
    transfer_efficiency: np.ndarray

EcosystemIndicators dataclass

Ecosystem summary indicators from balanced Ecopath model.

Attributes:

Name Type Description
mtl_catch float

Mean trophic level of catch.

marine_trophic_index float

MTL of catch excluding groups with TL < 3.25.

catch_biomass_ratio float

Total catch / total living biomass.

gross_efficiency float

Total catch / net primary production.

shannon_diversity float

Shannon H' of biomass (living groups), natural log.

kempton_q float

Biomass evenness in TL 3-4 range.

Source code in pypath/core/indicators.py
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
@dataclass
class EcosystemIndicators:
    """Ecosystem summary indicators from balanced Ecopath model.

    Attributes
    ----------
    mtl_catch : float
        Mean trophic level of catch.
    marine_trophic_index : float
        MTL of catch excluding groups with TL < 3.25.
    catch_biomass_ratio : float
        Total catch / total living biomass.
    gross_efficiency : float
        Total catch / net primary production.
    shannon_diversity : float
        Shannon H' of biomass (living groups), natural log.
    kempton_q : float
        Biomass evenness in TL 3-4 range.
    """

    mtl_catch: float
    marine_trophic_index: float
    catch_biomass_ratio: float
    gross_efficiency: float
    shannon_diversity: float
    kempton_q: float

SystemMaturityIndices dataclass

Odum's ecosystem development / maturity indicators.

Attributes:

Name Type Description
total_production float

Sum of production across all living groups (P = Σ PB×B).

total_respiration float

Sum of respiration across all living groups (R = Σ QB×B×Unassim + metabolism).

total_biomass float

Sum of biomass across all living groups.

net_production float

Total production minus total respiration (P - R).

pr_ratio float

Production / Respiration ratio. Mature ecosystems approach 1.0.

b_tst_ratio float

Total biomass / total system throughput. Higher in mature ecosystems.

mean_path_length float

Average number of trophic transfers per unit of energy. Computed as TST / total consumption at TL 1.

Source code in pypath/core/indicators.py
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
@dataclass
class SystemMaturityIndices:
    """Odum's ecosystem development / maturity indicators.

    Attributes
    ----------
    total_production : float
        Sum of production across all living groups (P = Σ PB×B).
    total_respiration : float
        Sum of respiration across all living groups (R = Σ QB×B×Unassim + metabolism).
    total_biomass : float
        Sum of biomass across all living groups.
    net_production : float
        Total production minus total respiration (P - R).
    pr_ratio : float
        Production / Respiration ratio. Mature ecosystems approach 1.0.
    b_tst_ratio : float
        Total biomass / total system throughput. Higher in mature ecosystems.
    mean_path_length : float
        Average number of trophic transfers per unit of energy.
        Computed as TST / total consumption at TL 1.
    """

    total_production: float
    total_respiration: float
    total_biomass: float
    net_production: float
    pr_ratio: float
    b_tst_ratio: float
    mean_path_length: float

flow_analysis

flow_analysis(rpath: Rpath) -> FlowAnalysis

Compute Ulanowicz flow analysis for a balanced Ecopath model.

Parameters:

Name Type Description Default
rpath Rpath

Balanced Ecopath model with computed trophic levels.

required

Returns:

Type Description
FlowAnalysis

TST, ascendency, capacity, overhead, relative ascendency, Finn cycling index, and per-level transfer efficiency.

Source code in pypath/core/indicators.py
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
def flow_analysis(rpath: Rpath) -> FlowAnalysis:
    """Compute Ulanowicz flow analysis for a balanced Ecopath model.

    Parameters
    ----------
    rpath : Rpath
        Balanced Ecopath model with computed trophic levels.

    Returns
    -------
    FlowAnalysis
        TST, ascendency, capacity, overhead, relative ascendency,
        Finn cycling index, and per-level transfer efficiency.
    """
    T, n_internal = _build_flow_matrix(rpath)
    n_total = T.shape[0]

    # Total System Throughput
    tst = np.sum(T)

    if tst == 0:
        return FlowAnalysis(
            total_system_throughput=0.0,
            ascendency=0.0,
            capacity=0.0,
            overhead=0.0,
            relative_ascendency=0.0,
            finn_cycling_index=0.0,
            transfer_efficiency=np.array([]),
        )

    # Marginal totals (T[receiver, sender] convention)
    t_row = np.sum(T, axis=1)  # row sums: total inflow to each destination
    t_col = np.sum(T, axis=0)  # col sums: total outflow from each source

    # Ascendency: A = Σ T[i,j] * log2(T[i,j] * TST / (T_in[i] * T_out[j]))
    # T_in[i] = t_row[i], T_out[j] = t_col[j]
    ascendency = 0.0
    for i in range(n_total):
        for j in range(n_total):
            if T[i, j] > 0 and t_row[i] > 0 and t_col[j] > 0:
                ascendency += T[i, j] * np.log2(T[i, j] * tst / (t_row[i] * t_col[j]))

    # Capacity: C = -Σ T[i,j] * log2(T[i,j] / TST)
    capacity = 0.0
    for i in range(n_total):
        for j in range(n_total):
            if T[i, j] > 0:
                capacity -= T[i, j] * np.log2(T[i, j] / tst)

    overhead = capacity - ascendency
    relative_ascendency = ascendency / capacity if capacity > 0 else 0.0

    # Finn Cycling Index (stub - implemented in Task 2)
    fci = _finn_cycling_index_from_matrix(T, n_internal)

    # Transfer Efficiency (stub - implemented in Task 3)
    te = _transfer_efficiency_from_rpath(rpath)

    return FlowAnalysis(
        total_system_throughput=tst,
        ascendency=ascendency,
        capacity=capacity,
        overhead=overhead,
        relative_ascendency=relative_ascendency,
        finn_cycling_index=fci,
        transfer_efficiency=te,
    )

finn_cycling_index

finn_cycling_index(rpath: Rpath) -> float

Compute Finn Cycling Index for a balanced Ecopath model.

The Finn Cycling Index (FCI) measures the fraction of total system throughput that is recycled. Values near 0 indicate linear flow; values near 1 indicate high recycling.

Parameters:

Name Type Description Default
rpath Rpath

Balanced Ecopath model.

required

Returns:

Type Description
float

Finn Cycling Index in [0, 1].

Source code in pypath/core/indicators.py
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
def finn_cycling_index(rpath: Rpath) -> float:
    """Compute Finn Cycling Index for a balanced Ecopath model.

    The Finn Cycling Index (FCI) measures the fraction of total system
    throughput that is recycled. Values near 0 indicate linear flow;
    values near 1 indicate high recycling.

    Parameters
    ----------
    rpath : Rpath
        Balanced Ecopath model.

    Returns
    -------
    float
        Finn Cycling Index in [0, 1].
    """
    T, n_internal = _build_flow_matrix(rpath)
    return _finn_cycling_index_from_matrix(T, n_internal)

transfer_efficiency

transfer_efficiency(rpath: Rpath) -> np.ndarray

Compute per-trophic-level transfer efficiency.

Uses simplified integer-bin approach: groups are binned by floor(TL), and efficiency is computed as the ratio of flow from level L to level L+1 divided by total input to level L.

Parameters:

Name Type Description Default
rpath Rpath

Balanced Ecopath model.

required

Returns:

Type Description
ndarray

Transfer efficiency per TL bin (starting from TL 2). Empty array if no groups at TL >= 2.

Source code in pypath/core/indicators.py
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
def transfer_efficiency(rpath: Rpath) -> np.ndarray:
    """Compute per-trophic-level transfer efficiency.

    Uses simplified integer-bin approach: groups are binned by
    floor(TL), and efficiency is computed as the ratio of flow
    from level L to level L+1 divided by total input to level L.

    Parameters
    ----------
    rpath : Rpath
        Balanced Ecopath model.

    Returns
    -------
    np.ndarray
        Transfer efficiency per TL bin (starting from TL 2).
        Empty array if no groups at TL >= 2.
    """
    return _transfer_efficiency_from_rpath(rpath)

ecosystem_indicators

ecosystem_indicators(rpath: Rpath) -> EcosystemIndicators

Compute ecosystem summary indicators from a balanced Ecopath model.

Parameters:

Name Type Description Default
rpath Rpath

Balanced Ecopath model.

required

Returns:

Type Description
EcosystemIndicators

Static ecosystem summary metrics.

Source code in pypath/core/indicators.py
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
def ecosystem_indicators(rpath: Rpath) -> EcosystemIndicators:
    """Compute ecosystem summary indicators from a balanced Ecopath model.

    Parameters
    ----------
    rpath : Rpath
        Balanced Ecopath model.

    Returns
    -------
    EcosystemIndicators
        Static ecosystem summary metrics.
    """
    n_living = rpath.NUM_LIVING
    n_dead = rpath.NUM_DEAD
    n_internal = n_living + n_dead

    # Compute catch per group
    # Landings/Discards are (NUM_GROUPS, NUM_GEARS), 0-based: sum all gears.
    catch = np.zeros(n_internal)
    for i in range(n_internal):
        catch[i] = np.sum(rpath.Landings[i, :]) + np.sum(rpath.Discards[i, :])

    total_catch = np.sum(catch)
    tl_internal = rpath.TL[:n_internal]

    # --- MTL catch ---
    if total_catch > 0:
        mtl_catch = np.sum(tl_internal * catch) / total_catch
    else:
        mtl_catch = np.nan

    # --- Marine Trophic Index (TL >= 3.25 only) ---
    mti_mask = (catch > 0) & (tl_internal >= 3.25)
    mti_catch = catch[mti_mask]
    mti_tl = tl_internal[mti_mask]
    if np.sum(mti_catch) > 0:
        marine_trophic_index = np.sum(mti_tl * mti_catch) / np.sum(mti_catch)
    else:
        marine_trophic_index = np.nan

    # --- Catch/Biomass ratio (living groups only) ---
    living_biomass = np.sum(rpath.Biomass[:n_living])
    catch_biomass_ratio = total_catch / living_biomass if living_biomass > 0 else np.nan

    # --- Gross efficiency (catch / NPP) ---
    npp = 0.0
    for i in range(n_living):
        if rpath.type[i] == 1:  # producer
            npp += rpath.PB[i] * rpath.Biomass[i]
    gross_efficiency = total_catch / npp if npp > 0 else np.nan

    # --- Shannon diversity (living groups with B > 0) ---
    living_b = []
    for i in range(n_living):
        if rpath.type[i] in (0, 1) and rpath.Biomass[i] > 0:
            living_b.append(rpath.Biomass[i])

    if len(living_b) > 0:
        living_b = np.array(living_b)
        total_b = np.sum(living_b)
        p = living_b / total_b
        shannon_diversity = -np.sum(p * np.log(p))
    else:
        shannon_diversity = np.nan

    # --- Kempton Q (TL in [3, 4)) ---
    q_biomasses = []
    for i in range(n_living):
        if rpath.type[i] in (0, 1) and 3.0 <= rpath.TL[i] < 4.0:
            q_biomasses.append(rpath.Biomass[i])

    if len(q_biomasses) >= 4:
        q_biomasses = np.sort(q_biomasses)
        b25 = np.percentile(q_biomasses, 25)
        b75 = np.percentile(q_biomasses, 75)
        s = len(q_biomasses)
        if b75 > b25 and b25 > 0:
            kempton_q = 0.5 * s / (np.log(b75) - np.log(b25))
        else:
            kempton_q = np.nan
    else:
        kempton_q = np.nan

    return EcosystemIndicators(
        mtl_catch=mtl_catch,
        marine_trophic_index=marine_trophic_index,
        catch_biomass_ratio=catch_biomass_ratio,
        gross_efficiency=gross_efficiency,
        shannon_diversity=shannon_diversity,
        kempton_q=kempton_q,
    )

system_maturity

system_maturity(rpath: Rpath) -> SystemMaturityIndices

Compute Odum's ecosystem maturity indicators.

Parameters:

Name Type Description Default
rpath Rpath

Balanced Ecopath model.

required

Returns:

Type Description
SystemMaturityIndices
Source code in pypath/core/indicators.py
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
def system_maturity(rpath: Rpath) -> SystemMaturityIndices:
    """Compute Odum's ecosystem maturity indicators.

    Parameters
    ----------
    rpath : Rpath
        Balanced Ecopath model.

    Returns
    -------
    SystemMaturityIndices
    """
    n_living = rpath.NUM_LIVING
    n_dead = rpath.NUM_DEAD
    n_internal = n_living + n_dead

    # Total production: Σ PB[i] × B[i] for all living groups
    total_production = 0.0
    for i in range(n_living):
        total_production += rpath.PB[i] * rpath.Biomass[i]

    # Total respiration: for each consumer, R = QB×B×(1-Unassim) - PB×B
    # For producers, R = PB×B - net primary production exported
    # Simplified: R = Σ (QB×B - PB×B) for consumers, PB×B×(1-EE) for producers
    # EwE approach: respiration = assimilated consumption - production
    total_respiration = 0.0
    for i in range(n_living):
        if rpath.type[i] == 1:  # producer
            # Producer respiration = production - what's consumed by others
            # Simplification: R = P × (1 - EE) for producers
            total_respiration += rpath.PB[i] * rpath.Biomass[i] * (1.0 - rpath.EE[i])
        else:  # consumer
            # R = assimilated food - production = QB×B×(1-Unassim) - PB×B
            assimilated = rpath.QB[i] * rpath.Biomass[i] * (1.0 - rpath.Unassim[i])
            production = rpath.PB[i] * rpath.Biomass[i]
            resp = assimilated - production
            total_respiration += max(0.0, resp)

    total_biomass = float(np.sum(rpath.Biomass[:n_living]))
    net_production = total_production - total_respiration
    pr_ratio = total_production / total_respiration if total_respiration > 0 else np.nan

    # B/TST ratio
    T, _ = _build_flow_matrix(rpath)
    tst = float(np.sum(T))
    b_tst_ratio = total_biomass / tst if tst > 0 else np.nan

    # Mean path length: TST / total input at base level
    # Base input = total consumption at TL 1 (primary production + detrital input)
    base_input = 0.0
    for i in range(n_internal):
        if rpath.type[i] == 1:  # producer
            base_input += rpath.PB[i] * rpath.Biomass[i]
        elif rpath.type[i] == 2:  # detritus
            # Detrital input from outside
            det_input = getattr(rpath, "DetInput", None)
            if det_input is not None and i < len(det_input):
                base_input += det_input[i]
    mean_path_length = tst / base_input if base_input > 0 else np.nan

    return SystemMaturityIndices(
        total_production=total_production,
        total_respiration=total_respiration,
        total_biomass=total_biomass,
        net_production=net_production,
        pr_ratio=pr_ratio,
        b_tst_ratio=b_tst_ratio,
        mean_path_length=mean_path_length,
    )

ecosystem_indicators_timeseries

ecosystem_indicators_timeseries(output: RsimOutput, scenario: RsimScenario, rpath: Rpath) -> pd.DataFrame

Compute ecosystem indicators per year from Ecosim output.

Parameters:

Name Type Description Default
output RsimOutput

Ecosim simulation output with annual_Biomass and annual_Catch.

required
scenario RsimScenario

Ecosim scenario for group count validation.

required
rpath Rpath

Balanced Ecopath model for trophic levels and group types.

required

Returns:

Type Description
DataFrame

Columns: year, mtl_catch, marine_trophic_index, catch_biomass_ratio, gross_efficiency, shannon_diversity. One row per year.

Source code in pypath/core/indicators.py
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
def ecosystem_indicators_timeseries(
    output: RsimOutput,
    scenario: RsimScenario,
    rpath: Rpath,
) -> pd.DataFrame:
    """Compute ecosystem indicators per year from Ecosim output.

    Parameters
    ----------
    output : RsimOutput
        Ecosim simulation output with annual_Biomass and annual_Catch.
    scenario : RsimScenario
        Ecosim scenario for group count validation.
    rpath : Rpath
        Balanced Ecopath model for trophic levels and group types.

    Returns
    -------
    pd.DataFrame
        Columns: year, mtl_catch, marine_trophic_index,
        catch_biomass_ratio, gross_efficiency, shannon_diversity.
        One row per year.
    """
    import pandas as pd

    n_years = output.annual_Biomass.shape[0]
    n_living = rpath.NUM_LIVING
    n_dead = rpath.NUM_DEAD
    n_internal = n_living + n_dead

    # Validate array dimensions match scenario
    if output.annual_Biomass.shape[1] < n_internal + 1:
        logger.warning(
            "annual_Biomass has %d columns but need %d for %d groups",
            output.annual_Biomass.shape[1],
            n_internal + 1,
            n_internal,
        )

    rows = []
    for yr in range(n_years):
        # Two indexing conventions meet here. Ecosim output arrays are
        # 1-based with index 0 = "Outside", while Rpath arrays are 0-based
        # over NUM_GROUPS. Ecopath group g therefore sits at Ecosim index
        # g + 1, and the two are sliced separately rather than together.
        biomass = output.annual_Biomass[yr]  # 1-based (0 = Outside)
        catch_arr = output.annual_Catch[yr]  # 1-based (0 = Outside)

        catch_internal = catch_arr[1 : n_internal + 1]
        tl_internal = rpath.TL[:n_internal]
        total_catch = np.sum(catch_internal)

        # MTL catch
        if total_catch > 0:
            mtl_catch = np.sum(tl_internal * catch_internal) / total_catch
        else:
            mtl_catch = np.nan

        # Marine Trophic Index (TL >= 3.25)
        mti_mask = (catch_internal > 0) & (tl_internal >= 3.25)
        mti_c = catch_internal[mti_mask]
        mti_t = tl_internal[mti_mask]
        if np.sum(mti_c) > 0:
            marine_trophic_index = np.sum(mti_t * mti_c) / np.sum(mti_c)
        else:
            marine_trophic_index = np.nan

        # Catch/Biomass ratio (living groups)
        living_b = np.sum(biomass[1 : n_living + 1])
        catch_biomass_ratio = total_catch / living_b if living_b > 0 else np.nan

        # Gross efficiency (catch / NPP using dynamic biomass)
        # PB is static (from Ecopath); biomass is dynamic (from Ecosim)
        npp = 0.0
        for i in range(n_living):
            if rpath.type[i] == 1:  # producer
                npp += rpath.PB[i] * biomass[i + 1]
        gross_efficiency = total_catch / npp if npp > 0 else np.nan

        # Shannon diversity (living groups with B > 0)
        living_bio = []
        for i in range(n_living):
            if rpath.type[i] in (0, 1) and biomass[i + 1] > 0:
                living_bio.append(biomass[i + 1])

        if len(living_bio) > 0:
            living_bio = np.array(living_bio)
            total_b = np.sum(living_bio)
            p = living_bio / total_b
            shannon_diversity = -np.sum(p * np.log(p))
        else:
            shannon_diversity = np.nan

        rows.append(
            {
                "year": yr,
                "mtl_catch": mtl_catch,
                "marine_trophic_index": marine_trophic_index,
                "catch_biomass_ratio": catch_biomass_ratio,
                "gross_efficiency": gross_efficiency,
                "shannon_diversity": shannon_diversity,
            }
        )

    return pd.DataFrame(rows)