Skip to content

Analysis API Reference

Pre-Balance Diagnostics

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_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
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
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_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
 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
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_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
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
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()

    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 model.diet.columns:
            diet = model.diet[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
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
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()

    # 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 model.diet.columns:
            diet = model.diet[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)

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
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
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

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
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
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
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
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

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
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
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)