Skip to content

Analysis API Reference

Tools for model diagnostics, pre-balance checks, and post-simulation analysis.

Functional Development Workflows

Workflow Primary API Entry Points Typical Outcome
Pre-run plausibility gate generate_prebalance_report(), print_prebalance_summary() Early detection of trophic/parameter inconsistencies before Ecopath balancing
Management scenario ranking ObjectiveSpec, ScenarioCandidate, ScenarioOptimizer Weighted multi-objective ranking with feasibility penalties and risk tie-breaking
Coupled scenario evaluator wiring make_spatial_management_evaluator() Reusable evaluator that runs coupled simulations and returns objective metrics

Scenario optimization pattern

from pypath.analysis import (
    ObjectiveSpec,
    ScenarioOptimizer,
    make_spatial_management_evaluator,
)

evaluator = make_spatial_management_evaluator(base_scenario, ecospace, years=range(1, 31))
optimizer = ScenarioOptimizer(
    objectives=[
        ObjectiveSpec("catch_total", weight=0.5, goal="maximize"),
        ObjectiveSpec("mean_biomass", weight=0.3, goal="maximize"),
        ObjectiveSpec("collapse_risk", weight=0.2, goal="minimize", max_value=0.25),
    ],
    evaluator=evaluator,
)

ranked = optimizer.optimize_grid(
    {
        "effort_scale": [0.8, 1.0, 1.2],
        "vulnerability_scale": [0.9, 1.0, 1.1],
    }
)

Pre-Balance Diagnostics

Pre-balance diagnostics help identify parameter issues before running the Ecopath mass-balance solver. Checks include biomass ratios, ecotrophic efficiency bounds, and diet composition consistency.

pypath.analysis.prebalance

Pre-balance diagnostic analysis for Ecopath models.

This module provides functions to analyze and visualize model parameters before balancing, helping identify potential issues with biomasses, vital rates, and predator-prey relationships.

Based on the Prebal routine by Barbara Bauer (SU, 2016).

calculate_biomass_slope

calculate_biomass_slope(model: RpathParams) -> float

Calculate the biomass decline slope across trophic levels.

A steep negative slope indicates strong top-down control. Typical values: -0.5 to -1.5

Parameters:

Name Type Description Default
model RpathParams

Unbalanced Rpath parameters

required

Returns:

Type Description
float

Slope of log10(biomass) vs ordered groups

Examples:

>>> slope = calculate_biomass_slope(params)
>>> print(f"Biomass slope: {slope:.3f}")
Source code in pypath/analysis/prebalance.py
 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
def calculate_biomass_slope(model: RpathParams) -> float:
    """Calculate the biomass decline slope across trophic levels.

    A steep negative slope indicates strong top-down control.
    Typical values: -0.5 to -1.5

    Parameters
    ----------
    model : RpathParams
        Unbalanced Rpath parameters

    Returns
    -------
    float
        Slope of log10(biomass) vs ordered groups

    Examples
    --------
    >>> slope = calculate_biomass_slope(params)
    >>> print(f"Biomass slope: {slope:.3f}")
    """
    # Get groups with biomass data (exclude detritus and fleets)
    df = model.model[model.model["Type"].isin([0, 1, 2])].copy()

    # Calculate TL if not present
    if "TL" not in df.columns:
        tl_series = _calculate_trophic_levels(model)
        df = df.merge(
            tl_series.to_frame(), left_on="Group", right_index=True, how="left"
        )

    df = df[df["Biomass"] > 0].sort_values("TL")

    if len(df) < 2:
        return 0.0

    # Fit linear regression: log10(biomass) vs index
    biomass = df["Biomass"].values
    x = np.arange(len(biomass))
    slope, _ = np.polyfit(x, np.log10(biomass), 1)

    return float(slope)

calculate_biomass_range

calculate_biomass_range(model: RpathParams) -> float

Calculate the range of biomasses (log10 scale).

Large ranges (>6) may indicate missing groups or unrealistic values.

Parameters:

Name Type Description Default
model RpathParams

Unbalanced Rpath parameters

required

Returns:

Type Description
float

Log10 of (max_biomass / min_biomass)

Source code in pypath/analysis/prebalance.py
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
def calculate_biomass_range(model: RpathParams) -> float:
    """Calculate the range of biomasses (log10 scale).

    Large ranges (>6) may indicate missing groups or unrealistic values.

    Parameters
    ----------
    model : RpathParams
        Unbalanced Rpath parameters

    Returns
    -------
    float
        Log10 of (max_biomass / min_biomass)
    """
    df = model.model[model.model["Type"].isin([0, 1, 2])].copy()
    biomass = df[df["Biomass"] > 0]["Biomass"]

    if len(biomass) < 2:
        return 0.0

    return float(np.log10(biomass.max() / biomass.min()))

calculate_predator_prey_ratios

calculate_predator_prey_ratios(model: RpathParams) -> pd.DataFrame

Calculate biomass ratios between predators and their prey.

High ratios (>1) suggest insufficient prey biomass to support predator consumption. Typical ratios: 0.01 to 0.5.

Parameters:

Name Type Description Default
model RpathParams

Unbalanced Rpath parameters

required

Returns:

Type Description
DataFrame

Columns: ['Predator', 'Prey_Biomass', 'Predator_Biomass', 'Ratio']

Source code in pypath/analysis/prebalance.py
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
def calculate_predator_prey_ratios(model: RpathParams) -> pd.DataFrame:
    """Calculate biomass ratios between predators and their prey.

    High ratios (>1) suggest insufficient prey biomass to support predator
    consumption. Typical ratios: 0.01 to 0.5.

    Parameters
    ----------
    model : RpathParams
        Unbalanced Rpath parameters

    Returns
    -------
    pd.DataFrame
        Columns: ['Predator', 'Prey_Biomass', 'Predator_Biomass', 'Ratio']
    """
    results = []

    # Get living groups (exclude detritus and fleets)
    living = model.model[model.model["Type"].isin([0, 1])].copy()
    diet_by_prey = _diet_by_prey(model)

    for pred_idx, pred_row in living.iterrows():
        predator = pred_row["Group"]
        pred_biomass = pred_row["Biomass"]

        if pred_biomass <= 0:
            continue

        # Get diet for this predator
        if predator in diet_by_prey.columns:
            diet = diet_by_prey[predator]
            prey_with_diet = diet[diet > 0]

            if len(prey_with_diet) == 0:
                continue

            # Sum biomass of all prey
            prey_biomass = 0.0
            for prey_name in prey_with_diet.index:
                if prey_name in model.model["Group"].values:
                    prey_biom = model.model[model.model["Group"] == prey_name][
                        "Biomass"
                    ]
                    if not prey_biom.empty and prey_biom.iloc[0] > 0:
                        prey_biomass += prey_biom.iloc[0]

            if prey_biomass > 0:
                ratio = pred_biomass / prey_biomass
                results.append(
                    {
                        "Predator": predator,
                        "Prey_Biomass": prey_biomass,
                        "Predator_Biomass": pred_biomass,
                        "Ratio": ratio,
                    }
                )

    return pd.DataFrame(results)

calculate_vital_rate_ratios

calculate_vital_rate_ratios(model: RpathParams, rate_name: str = 'PB') -> pd.DataFrame

Calculate vital rate ratios between predators and prey.

Examines if predator rates are appropriately lower than prey rates (metabolic theory prediction).

Parameters:

Name Type Description Default
model RpathParams

Unbalanced Rpath parameters

required
rate_name str

Rate to analyze: 'PB', 'QB', or custom column name

'PB'

Returns:

Type Description
DataFrame

Columns: ['Predator', 'Prey_Rate_Mean', 'Predator_Rate', 'Ratio']

Source code in pypath/analysis/prebalance.py
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
def calculate_vital_rate_ratios(
    model: RpathParams, rate_name: str = "PB"
) -> pd.DataFrame:
    """Calculate vital rate ratios between predators and prey.

    Examines if predator rates are appropriately lower than prey rates
    (metabolic theory prediction).

    Parameters
    ----------
    model : RpathParams
        Unbalanced Rpath parameters
    rate_name : str, default 'PB'
        Rate to analyze: 'PB', 'QB', or custom column name

    Returns
    -------
    pd.DataFrame
        Columns: ['Predator', 'Prey_Rate_Mean', 'Predator_Rate', 'Ratio']
    """
    results = []

    living = model.model[model.model["Type"].isin([0, 1])].copy()
    diet_by_prey = _diet_by_prey(model)

    # Check if rate column exists
    if rate_name not in living.columns:
        return pd.DataFrame(
            columns=["Predator", "Prey_Rate_Mean", "Predator_Rate", "Ratio"]
        )

    for pred_idx, pred_row in living.iterrows():
        predator = pred_row["Group"]
        pred_rate = pred_row[rate_name]

        if pd.isna(pred_rate) or pred_rate <= 0:
            continue

        # Get prey rates
        if predator in diet_by_prey.columns:
            diet = diet_by_prey[predator]
            prey_with_diet = diet[diet > 0]

            if len(prey_with_diet) == 0:
                continue

            prey_rates = []
            for prey_name in prey_with_diet.index:
                if prey_name in model.model["Group"].values:
                    prey_rate_val = model.model[model.model["Group"] == prey_name][
                        rate_name
                    ]
                    if (
                        not prey_rate_val.empty
                        and not pd.isna(prey_rate_val.iloc[0])
                        and prey_rate_val.iloc[0] > 0
                    ):
                        prey_rates.append(prey_rate_val.iloc[0])

            if len(prey_rates) > 0:
                prey_mean = np.mean(prey_rates)
                ratio = pred_rate / prey_mean
                results.append(
                    {
                        "Predator": predator,
                        "Prey_Rate_Mean": prey_mean,
                        "Predator_Rate": pred_rate,
                        "Ratio": ratio,
                    }
                )

    return pd.DataFrame(results)

plot_biomass_vs_trophic_level

plot_biomass_vs_trophic_level(model: RpathParams, exclude_groups: Optional[List[str]] = None, figsize: Tuple[int, int] = (8, 6)) -> Figure

Plot biomass vs trophic level with group labels.

Parameters:

Name Type Description Default
model RpathParams

Unbalanced Rpath parameters

required
exclude_groups list of str

Groups to exclude (e.g., homeotherms, detritus)

None
figsize tuple

Figure size

(8, 6)

Returns:

Type Description
Figure

Matplotlib figure object

Source code in pypath/analysis/prebalance.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
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
def plot_biomass_vs_trophic_level(
    model: RpathParams,
    exclude_groups: Optional[List[str]] = None,
    figsize: Tuple[int, int] = (8, 6),
) -> Figure:
    """Plot biomass vs trophic level with group labels.

    Parameters
    ----------
    model : RpathParams
        Unbalanced Rpath parameters
    exclude_groups : list of str, optional
        Groups to exclude (e.g., homeotherms, detritus)
    figsize : tuple, default (8, 6)
        Figure size

    Returns
    -------
    Figure
        Matplotlib figure object
    """
    # Prepare data
    df = model.model[model.model["Type"].isin([0, 1, 2])].copy()
    df = df[df["Biomass"] > 0]

    # Calculate TL if not present
    if "TL" not in df.columns:
        tl_series = _calculate_trophic_levels(model)
        df = df.merge(
            tl_series.to_frame(), left_on="Group", right_index=True, how="left"
        )

    if exclude_groups:
        df = df[~df["Group"].isin(exclude_groups)]

    # Create plot
    fig, ax = plt.subplots(figsize=figsize)

    # Scatter plot
    ax.scatter(df["TL"], df["Biomass"], alpha=0.6, s=50)
    ax.set_yscale("log")
    ax.set_xlabel("Trophic Level", fontsize=12)
    ax.set_ylabel("Biomass (t/km²)", fontsize=12)
    ax.set_title("Biomass vs Trophic Level", fontsize=14, fontweight="bold")
    ax.grid(True, alpha=0.3)

    # Add group labels (sample if too many)
    if len(df) <= 30:
        for _idx, row in df.iterrows():
            ax.annotate(
                row["Group"],
                (row["TL"], row["Biomass"]),
                fontsize=8,
                alpha=0.7,
                xytext=(5, 5),
                textcoords="offset points",
            )

    plt.tight_layout()
    return fig

plot_vital_rate_vs_trophic_level

plot_vital_rate_vs_trophic_level(model: RpathParams, rate_name: str = 'PB', exclude_groups: Optional[List[str]] = None, figsize: Tuple[int, int] = (8, 6)) -> Figure

Plot vital rate vs trophic level.

Parameters:

Name Type Description Default
model RpathParams

Unbalanced Rpath parameters

required
rate_name str

Rate to plot: 'PB', 'QB', etc.

'PB'
exclude_groups list of str

Groups to exclude

None
figsize tuple

Figure size

(8, 6)

Returns:

Type Description
Figure

Matplotlib figure object

Source code in pypath/analysis/prebalance.py
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
def plot_vital_rate_vs_trophic_level(
    model: RpathParams,
    rate_name: str = "PB",
    exclude_groups: Optional[List[str]] = None,
    figsize: Tuple[int, int] = (8, 6),
) -> Figure:
    """Plot vital rate vs trophic level.

    Parameters
    ----------
    model : RpathParams
        Unbalanced Rpath parameters
    rate_name : str, default 'PB'
        Rate to plot: 'PB', 'QB', etc.
    exclude_groups : list of str, optional
        Groups to exclude
    figsize : tuple, default (8, 6)
        Figure size

    Returns
    -------
    Figure
        Matplotlib figure object
    """
    # Prepare data
    df = model.model[model.model["Type"].isin([0, 1])].copy()

    if rate_name not in df.columns:
        raise ValueError(f"Rate '{rate_name}' not found in model")

    df = df[df[rate_name] > 0]

    # Calculate TL if not present
    if "TL" not in df.columns:
        tl_series = _calculate_trophic_levels(model)
        df = df.merge(
            tl_series.to_frame(), left_on="Group", right_index=True, how="left"
        )

    if exclude_groups:
        df = df[~df["Group"].isin(exclude_groups)]

    # Create plot
    fig, ax = plt.subplots(figsize=figsize)

    ax.scatter(df["TL"], df[rate_name], alpha=0.6, s=50, c="steelblue")
    ax.set_yscale("log")
    ax.set_xlabel("Trophic Level", fontsize=12)
    ax.set_ylabel(f"{rate_name} (per year)", fontsize=12)
    ax.set_title(f"{rate_name} vs Trophic Level", fontsize=14, fontweight="bold")
    ax.grid(True, alpha=0.3)

    # Add labels for interesting points
    if len(df) <= 20:
        for _idx, row in df.iterrows():
            ax.annotate(
                row["Group"],
                (row["TL"], row[rate_name]),
                fontsize=8,
                alpha=0.7,
                xytext=(5, 5),
                textcoords="offset points",
            )

    plt.tight_layout()
    return fig

generate_prebalance_report

generate_prebalance_report(model: RpathParams) -> Dict

Generate comprehensive pre-balance diagnostic report.

Parameters:

Name Type Description Default
model RpathParams

Unbalanced Rpath parameters

required

Returns:

Type Description
dict

Dictionary with diagnostic results: - 'biomass_slope': float - 'biomass_range': float - 'predator_prey_ratios': DataFrame - 'pb_ratios': DataFrame - 'qb_ratios': DataFrame - 'warnings': list of str

Source code in pypath/analysis/prebalance.py
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
def generate_prebalance_report(model: RpathParams) -> Dict:
    """Generate comprehensive pre-balance diagnostic report.

    Parameters
    ----------
    model : RpathParams
        Unbalanced Rpath parameters

    Returns
    -------
    dict
        Dictionary with diagnostic results:
        - 'biomass_slope': float
        - 'biomass_range': float
        - 'predator_prey_ratios': DataFrame
        - 'pb_ratios': DataFrame
        - 'qb_ratios': DataFrame
        - 'warnings': list of str
    """
    report = {}
    warnings = []

    # Biomass diagnostics
    report["biomass_slope"] = calculate_biomass_slope(model)
    report["biomass_range"] = calculate_biomass_range(model)

    if report["biomass_range"] > 6:
        warnings.append(
            f"Large biomass range ({report['biomass_range']:.1f} orders of magnitude) - check for missing groups or unrealistic values"
        )

    if abs(report["biomass_slope"]) > 2:
        warnings.append(
            f"Steep biomass slope ({report['biomass_slope']:.2f}) - unusual trophic structure"
        )

    # Predator-prey ratios
    report["predator_prey_ratios"] = calculate_predator_prey_ratios(model)

    if len(report["predator_prey_ratios"]) > 0:
        high_ratios = report["predator_prey_ratios"][
            report["predator_prey_ratios"]["Ratio"] > 1.0
        ]
        if len(high_ratios) > 0:
            for _, row in high_ratios.iterrows():
                warnings.append(
                    f"{row['Predator']}: predator/prey ratio = {row['Ratio']:.2f} (>1, may be unsustainable)"
                )

    # Vital rate ratios
    if "PB" in model.model.columns:
        report["pb_ratios"] = calculate_vital_rate_ratios(model, "PB")
    else:
        report["pb_ratios"] = pd.DataFrame()

    if "QB" in model.model.columns:
        report["qb_ratios"] = calculate_vital_rate_ratios(model, "QB")
    else:
        report["qb_ratios"] = pd.DataFrame()

    report["warnings"] = warnings

    return report

print_prebalance_summary

print_prebalance_summary(report: Dict) -> None

Print formatted pre-balance diagnostic summary.

Parameters:

Name Type Description Default
report dict

Report from generate_prebalance_report()

required
Source code in pypath/analysis/prebalance.py
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
def print_prebalance_summary(report: Dict) -> None:
    """Print formatted pre-balance diagnostic summary.

    Parameters
    ----------
    report : dict
        Report from generate_prebalance_report()
    """
    logger.info("=" * 60)
    logger.info("PRE-BALANCE DIAGNOSTIC REPORT")
    logger.info("=" * 60)
    logger.info("")

    logger.info("BIOMASS DIAGNOSTICS:")
    logger.info(f"  Biomass range: {report['biomass_range']:.2f} orders of magnitude")
    logger.info(f"  Biomass slope: {report['biomass_slope']:.3f}")
    logger.info("")

    if len(report["predator_prey_ratios"]) > 0:
        logger.info("PREDATOR-PREY BIOMASS RATIOS:")
        logger.info("  Top 5 highest ratios:")
        top5 = report["predator_prey_ratios"].nlargest(5, "Ratio")
        for _, row in top5.iterrows():
            logger.info(f"    {row['Predator']}: {row['Ratio']:.3f}")
        logger.info("")

    if len(report.get("pb_ratios", [])) > 0:
        logger.info("P/B RATE RATIOS (Predator/Prey):")
        logger.info(f"  Mean ratio: {report['pb_ratios']['Ratio'].mean():.2f}")
        logger.info("")

    if len(report["warnings"]) > 0:
        logger.info("WARNINGS:")
        for i, warning in enumerate(report["warnings"], 1):
            logger.info(f"  {i}. {warning}")
    else:
        logger.info("No major issues detected!")

    logger.info("")
    logger.info("=" * 60)

Network Indices

Network analysis functions for food web structure: connectance, omnivory index, mean trophic level, and system throughput.

See also Core API: Analysis & Network Indices for mixed_trophic_impact() and summarize_ecosim_output().

Scenario Optimization

Risk-aware multi-objective scenario ranking helpers for coupled Ecosim-Ecospace management experiments.

pypath.analysis.scenario_optimizer

Scenario optimization utilities for coupled Ecosim-Ecospace management runs.

ObjectiveSpec dataclass

Definition of a scalar objective used in scenario ranking.

Parameters:

Name Type Description Default
name str

Objective key expected from an evaluator.

required
weight float

Objective weight in aggregate score.

1.0
goal str

Either "maximize" or "minimize".

'maximize'
min_value float

Feasibility lower bound.

None
max_value float

Feasibility upper bound.

None
Source code in pypath/analysis/scenario_optimizer.py
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
@dataclass(frozen=True)
class ObjectiveSpec:
    """Definition of a scalar objective used in scenario ranking.

    Parameters
    ----------
    name : str
        Objective key expected from an evaluator.
    weight : float
        Objective weight in aggregate score.
    goal : str
        Either ``"maximize"`` or ``"minimize"``.
    min_value : float, optional
        Feasibility lower bound.
    max_value : float, optional
        Feasibility upper bound.
    """

    name: str
    weight: float = 1.0
    goal: str = "maximize"
    min_value: float | None = None
    max_value: float | None = None

    def __post_init__(self):
        if self.goal not in {"maximize", "minimize"}:
            raise ValueError(f"Unsupported goal '{self.goal}'")

ScenarioCandidate dataclass

Candidate management scenario controls.

Source code in pypath/analysis/scenario_optimizer.py
42
43
44
45
46
47
48
@dataclass(frozen=True)
class ScenarioCandidate:
    """Candidate management scenario controls."""

    name: str
    controls: Dict[str, float]
    metadata: Dict[str, str] = field(default_factory=dict)

ScenarioScore dataclass

Evaluated scenario with objective values and aggregate score.

Source code in pypath/analysis/scenario_optimizer.py
51
52
53
54
55
56
57
58
59
60
@dataclass
class ScenarioScore:
    """Evaluated scenario with objective values and aggregate score."""

    name: str
    controls: Dict[str, float]
    objectives: Dict[str, float]
    aggregate_score: float
    feasible: bool
    risk_score: float

ScenarioOptimizer

Multi-objective scenario optimizer with risk-aware ranking.

Source code in pypath/analysis/scenario_optimizer.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
class ScenarioOptimizer:
    """Multi-objective scenario optimizer with risk-aware ranking."""

    def __init__(
        self,
        objectives: Iterable[ObjectiveSpec],
        evaluator: Callable[[ScenarioCandidate], Dict[str, float]],
        *,
        risk_objective: str = "collapse_risk",
        infeasible_penalty: float = 1e9,
    ):
        self.objectives = list(objectives)
        self.evaluator = evaluator
        self.risk_objective = risk_objective
        self.infeasible_penalty = float(infeasible_penalty)
        if not self.objectives:
            raise ValueError("At least one objective is required")

    def evaluate(self, candidate: ScenarioCandidate) -> ScenarioScore:
        """Evaluate one candidate scenario."""
        values = self.evaluator(candidate)
        missing = [obj.name for obj in self.objectives if obj.name not in values]
        if missing:
            raise KeyError(f"Evaluator missing objective(s): {missing}")

        feasible = True
        aggregate = 0.0

        for obj in self.objectives:
            value = float(values[obj.name])
            if obj.min_value is not None and value < obj.min_value:
                feasible = False
            if obj.max_value is not None and value > obj.max_value:
                feasible = False

            direction = 1.0 if obj.goal == "maximize" else -1.0
            aggregate += obj.weight * direction * value

        if not feasible:
            aggregate -= self.infeasible_penalty

        risk = float(values.get(self.risk_objective, 0.0))
        return ScenarioScore(
            name=candidate.name,
            controls=dict(candidate.controls),
            objectives={k: float(v) for k, v in values.items()},
            aggregate_score=aggregate,
            feasible=feasible,
            risk_score=risk,
        )

    def rank(self, candidates: Iterable[ScenarioCandidate]) -> list[ScenarioScore]:
        """Evaluate and rank candidates by aggregate score, then risk."""
        scores = [self.evaluate(c) for c in candidates]
        return sorted(
            scores, key=lambda s: (s.aggregate_score, -s.risk_score), reverse=True
        )

    def optimize_grid(
        self,
        control_grid: Dict[str, Iterable[float]],
        *,
        name_prefix: str = "scenario",
    ) -> list[ScenarioScore]:
        """Enumerate a Cartesian grid of controls and rank all combinations."""
        if not control_grid:
            raise ValueError("control_grid must not be empty")

        keys = list(control_grid.keys())
        value_lists = [list(control_grid[k]) for k in keys]
        for key, vals in zip(keys, value_lists):
            if not vals:
                raise ValueError(f"control grid for '{key}' is empty")

        candidates = []
        for idx, combo in enumerate(itertools.product(*value_lists), start=1):
            controls = {k: float(v) for k, v in zip(keys, combo)}
            candidates.append(
                ScenarioCandidate(name=f"{name_prefix}_{idx}", controls=controls)
            )

        return self.rank(candidates)
evaluate
evaluate(candidate: ScenarioCandidate) -> ScenarioScore

Evaluate one candidate scenario.

Source code in pypath/analysis/scenario_optimizer.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
def evaluate(self, candidate: ScenarioCandidate) -> ScenarioScore:
    """Evaluate one candidate scenario."""
    values = self.evaluator(candidate)
    missing = [obj.name for obj in self.objectives if obj.name not in values]
    if missing:
        raise KeyError(f"Evaluator missing objective(s): {missing}")

    feasible = True
    aggregate = 0.0

    for obj in self.objectives:
        value = float(values[obj.name])
        if obj.min_value is not None and value < obj.min_value:
            feasible = False
        if obj.max_value is not None and value > obj.max_value:
            feasible = False

        direction = 1.0 if obj.goal == "maximize" else -1.0
        aggregate += obj.weight * direction * value

    if not feasible:
        aggregate -= self.infeasible_penalty

    risk = float(values.get(self.risk_objective, 0.0))
    return ScenarioScore(
        name=candidate.name,
        controls=dict(candidate.controls),
        objectives={k: float(v) for k, v in values.items()},
        aggregate_score=aggregate,
        feasible=feasible,
        risk_score=risk,
    )
rank
rank(candidates: Iterable[ScenarioCandidate]) -> list[ScenarioScore]

Evaluate and rank candidates by aggregate score, then risk.

Source code in pypath/analysis/scenario_optimizer.py
114
115
116
117
118
119
def rank(self, candidates: Iterable[ScenarioCandidate]) -> list[ScenarioScore]:
    """Evaluate and rank candidates by aggregate score, then risk."""
    scores = [self.evaluate(c) for c in candidates]
    return sorted(
        scores, key=lambda s: (s.aggregate_score, -s.risk_score), reverse=True
    )
optimize_grid
optimize_grid(control_grid: Dict[str, Iterable[float]], *, name_prefix: str = 'scenario') -> list[ScenarioScore]

Enumerate a Cartesian grid of controls and rank all combinations.

Source code in pypath/analysis/scenario_optimizer.py
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
def optimize_grid(
    self,
    control_grid: Dict[str, Iterable[float]],
    *,
    name_prefix: str = "scenario",
) -> list[ScenarioScore]:
    """Enumerate a Cartesian grid of controls and rank all combinations."""
    if not control_grid:
        raise ValueError("control_grid must not be empty")

    keys = list(control_grid.keys())
    value_lists = [list(control_grid[k]) for k in keys]
    for key, vals in zip(keys, value_lists):
        if not vals:
            raise ValueError(f"control grid for '{key}' is empty")

    candidates = []
    for idx, combo in enumerate(itertools.product(*value_lists), start=1):
        controls = {k: float(v) for k, v in zip(keys, combo)}
        candidates.append(
            ScenarioCandidate(name=f"{name_prefix}_{idx}", controls=controls)
        )

    return self.rank(candidates)

make_spatial_management_evaluator

make_spatial_management_evaluator(base_scenario, ecospace, *, years: Optional[range] = None, collapse_threshold: float = 0.2, apply_controls: Optional[Callable[[object, dict[str, float]], None]] = None) -> Callable[[ScenarioCandidate], Dict[str, float]]

Create an evaluator that runs coupled simulations for controls.

The default control semantics are: - effort_scale: multiply all fleet effort values. - vulnerability_scale: scale non-zero vulnerability entries.

Source code in pypath/analysis/scenario_optimizer.py
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 make_spatial_management_evaluator(
    base_scenario,
    ecospace,
    *,
    years: Optional[range] = None,
    collapse_threshold: float = 0.2,
    apply_controls: Optional[Callable[[object, dict[str, float]], None]] = None,
) -> Callable[[ScenarioCandidate], Dict[str, float]]:
    """Create an evaluator that runs coupled simulations for controls.

    The default control semantics are:
    - ``effort_scale``: multiply all fleet effort values.
    - ``vulnerability_scale``: scale non-zero vulnerability entries.
    """

    from pypath.spatial.integration import rsim_run_spatial

    def _default_apply_controls(scenario_copy, controls: dict[str, float]) -> None:
        if "effort_scale" in controls:
            scenario_copy.fishing.ForcedEffort *= controls["effort_scale"]
        if "vulnerability_scale" in controls:
            vv = scenario_copy.params.VV
            mask = vv > 0
            vv[mask] *= controls["vulnerability_scale"]

    _apply = apply_controls or _default_apply_controls

    def evaluator(candidate: ScenarioCandidate) -> Dict[str, float]:
        scenario_copy = copy.deepcopy(base_scenario)
        ecospace_copy = copy.deepcopy(ecospace)

        _apply(scenario_copy, candidate.controls)

        result = rsim_run_spatial(scenario_copy, ecospace=ecospace_copy, years=years)

        # Group 0 is "Outside".
        start = result.out_Biomass[0, 1:]
        final = result.out_Biomass[-1, 1:]

        safe_start = np.where(start > 0, start, np.nan)
        ratio = final / safe_start
        ratio = np.nan_to_num(ratio, nan=1.0, posinf=1.0, neginf=0.0)

        collapse_risk = float(np.mean(ratio < collapse_threshold))
        final_total = float(np.sum(final))
        mean_total = float(np.mean(result.out_Biomass[:, 1:].sum(axis=1)))
        catch_total = float(np.sum(result.annual_Catch[:, 1:]))

        return {
            "final_biomass": final_total,
            "mean_biomass": mean_total,
            "catch_total": catch_total,
            "collapse_risk": collapse_risk,
        }

    return evaluator