Develop a climate-aware fisheries harvest control rule simulator that integrates…
- User
Develop a climate-aware fisheries harvest control rule simulator that integrates ecological models, socioeconomics, and adaptive management.
Assistant
Develop a climate-aware fisheries harvest control rule simulator that integrates ecological models, socioeconomics, and adaptive management.
The user wants a comprehensive fisheries harvest control rule (HCR) simulator that integrates:
Let me design a sophisticated simulator that includes:
Ecological Model Components:
Climate Effects:
Harvest Control Rules:
Socioeconomic Components:
Adaptive Management:
Visualization:
Let me create a comprehensive GUI-based simulator using tkinter and matplotlib.
Key features to implement:
I'll structure this as:
Let me write this comprehensive code:
This is a comprehensive simulator integrating ecological dynamics, climate effects, socioeconomic factors, and adaptive management strategies.
pip install numpy matplotlib scipy
Then run the script directly with Python 3.7+.
"""
Climate-Aware Fisheries Harvest Control Rule Simulator
======================================================
Integrates ecological models, climate impacts, socioeconomic factors,
and adaptive management for sustainable fisheries governance.
"""
import numpy as np
import tkinter as tk
from tkinter import ttk, messagebox
import matplotlib.pyplot as plt
from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg
from matplotlib.figure import Figure
from dataclasses import dataclass, field
from typing import Dict, List, Tuple, Optional, Callable
from enum import Enum
import json
from scipy import stats
from collections import deque
# =============================================================================
# Data Classes and Enums
# =============================================================================
class ClimateScenario(Enum):
STABLE = "Stable"
MODERATE_WARMING = "Moderate Warming (+1.5°C)"
SEVERE_WARMING = "Severe Warming (+3°C)"
ACIDIFICATION = "Ocean Acidification"
REGIME_SHIFT = "Regime Shift"
EXTREME_EVENTS = "Extreme Events"
class HCRType(Enum):
CONSTANT_CATCH = "Constant Catch"
CONSTANT_F = "Constant Fishing Mortality"
HOCKEY_STICK = "Hockey Stick"
CLIMATE_ADAPTIVE = "Climate-Adaptive"
PRECAUTIONARY = "Precautionary Approach"
MULTI_OBJECTIVE = "Multi-Objective"
@dataclass
class StockParameters:
"""Biological parameters for fish stock"""
name: str = "Target Species"
carrying_capacity: float = 1000.0 # K (thousand tonnes)
intrinsic_growth: float = 0.3 # r (per year)
current_biomass: float = 600.0 # B0
biomass_at_bmsy: float = 500.0 # B_MSY
f_msy: float = 0.15 # F_MSY
blim: float = 200.0 # Limit reference point
bpa: float = 300.0 # Precautionary reference point
steepness: float = 0.7 # Stock-recruitment steepness
age_at_maturity: float = 3.0 # years
max_age: float = 20.0 # years
natural_mortality: float = 0.2 # M
@dataclass
class ClimateParameters:
"""Climate forcing parameters"""
temperature_sensitivity: float = -0.05 # Effect on r per °C
current_anomaly: float = 0.0 # Current temperature anomaly
warming_rate: float = 0.02 # °C per year
acidification_rate: float = 0.001 # pH units per year
current_ph: float = 8.1
recruitment_impact: float = -0.03 # Effect on recruitment per pH unit
regime_shift_probability: float = 0.02 # Per year
regime_shift_magnitude: float = 0.3 # K reduction fraction
extreme_event_probability: float = 0.05 # Per year
extreme_event_mortality: float = 0.2 # Additional mortality
@dataclass
class EconomicParameters:
"""Socioeconomic parameters"""
price_per_tonne: float = 1000.0 # USD
cost_per_unit_effort: float = 100.0 # USD
catchability: float = 0.001 # q
elasticity_demand: float = -0.5
employment_per_vessel: float = 5.0
vessels_current: float = 100.0
discount_rate: float = 0.05
min_profit_ratio: float = 0.1 # Minimum profit/cost ratio to stay in fishery
# =============================================================================
# Climate Model
# =============================================================================
class ClimateModel:
"""Simulates climate impacts on marine ecosystems"""
def __init__(self, params: ClimateParameters, scenario: ClimateScenario):
self.params = params
self.scenario = scenario
self.current_anomaly = params.current_anomaly
self.current_ph = params.current_ph
self.regime_shifted = False
self.regime_shift_year = None
self.extreme_event_active = False
# Historical tracking
self.temperature_history = []
self.ph_history = []
self.productivity_history = []
def update(self, year: int) -> Dict:
"""Update climate state for given year"""
# Temperature trajectory based on scenario
if self.scenario == ClimateScenario.STABLE:
self.current_anomaly = 0.0
elif self.scenario == ClimateScenario.MODERATE_WARMING:
self.current_anomaly = min(1.5, self.params.warming_rate * year)
elif self.scenario == ClimateScenario.SEVERE_WARMING:
self.current_anomaly = min(3.0, 2 * self.params.warming_rate * year)
elif self.scenario == ClimateScenario.REGIME_SHIFT:
self.current_anomaly = min(1.5, self.params.warming_rate * year)
# Check for regime shift
if not self.regime_shifted and np.random.random() < self.params.regime_shift_probability:
self.regime_shifted = True
self.regime_shift_year = year
elif self.scenario == ClimateScenario.ACIDIFICATION:
self.current_anomaly = min(1.0, self.params.warming_rate * year)
self.current_ph -= self.params.acidification_rate
elif self.scenario == ClimateScenario.EXTREME_EVENTS:
self.current_anomaly = min(1.5, self.params.warming_rate * year)
self.extreme_event_active = np.random.random() < self.params.extreme_event_probability
# Store history
self.temperature_history.append(self.current_anomaly)
self.ph_history.append(self.current_ph)
return self.get_state()
def get_state(self) -> Dict:
"""Get current climate state"""
return {
'temperature_anomaly': self.current_anomaly,
'ph': self.current_ph,
'regime_shifted': self.regime_shifted,
'regime_shift_year': self.regime_shift_year,
'extreme_event': self.extreme_event_active
}
def calculate_productivity_multiplier(self) -> float:
"""Calculate multiplier for stock productivity"""
multiplier = 1.0
# Temperature effect
temp_effect = np.exp(self.params.temperature_sensitivity * self.current_anomaly)
multiplier *= temp_effect
# Acidification effect
ph_change = 8.1 - self.current_ph
acid_effect = np.exp(self.params.recruitment_impact * ph_change)
multiplier *= acid_effect
# Regime shift effect
if self.regime_shifted:
multiplier *= (1 - self.params.regime_shift_magnitude)
return multiplier
def calculate_mortality_multiplier(self) -> float:
"""Calculate additional mortality from extreme events"""
if self.extreme_event_active:
return 1 + self.params.extreme_event_mortality
return 1.0
# =============================================================================
# Population Dynamics Model
# =============================================================================
class PopulationModel:
"""Age-structured population dynamics model"""
def __init__(self, bio_params: StockParameters):
self.params = bio_params
self.biomass = bio_params.current_biomass
self.recruitment = 0.0
self.fishing_mortality = 0.0
# Age structure
self.n_ages = int(bio_params.max_age)
self.age_structure = np.zeros(self.n_ages)
self._initialize_age_structure()
# History tracking
self.biomass_history = [self.biomass]
self.recruitment_history = []
self.catch_history = []
self.f_history = []
self.ssb_history = [] # Spawning stock biomass
# Derived quantities
self._update_derived_quantities()
def _initialize_age_structure(self):
"""Initialize age structure based on equilibrium assumptions"""
total_biomass = self.biomass
survivorship = np.exp(-self.params.natural_mortality * np.arange(self.n_ages))
survivorship /= survivorship.sum()
weights = self._get_weights_at_age()
self.age_structure = (survivorship * total_biomass) / (weights * survivorship).sum()
def _get_weights_at_age(self) -> np.ndarray:
"""Get weight at age (von Bertalanffy-like)"""
ages = np.arange(self.n_ages)
w_inf = 1.0 # Asymptotic weight
k = 0.2 # Growth coefficient
t0 = -1.0 # Age at zero length
weights = w_inf * (1 - np.exp(-k * (ages - t0))) ** 3
weights[weights < 0] = 0.01
return weights
def _get_maturity_at_age(self) -> np.ndarray:
"""Get maturity at age (logistic)"""
ages = np.arange(self.n_ages)
mat50 = self.params.age_at_maturity
mat_slope = 0.5
maturity = 1 / (1 + np.exp(-(ages - mat50) / mat_slope))
return maturity
def _update_derived_quantities(self):
"""Update spawning stock biomass and other quantities"""
weights = self._get_weights_at_age()
maturity = self._get_maturity_at_age()
self.ssb = (self.age_structure * weights * maturity).sum()
self.ssb_history.append(self.ssb)
def calculate_recruitment(self, climate_productivity: float = 1.0) -> float:
"""Calculate recruitment using Beverton-Holt with climate effects"""
ssb = max(self.ssb, 1.0)
h = self.params.steepness
r0 = self.params.carrying_capacity * 0.5
ssb0 = self.params.carrying_capacity * 0.5
# Beverton-Holt
recruitment = (4 * h * r0 * ssb) / (ssb0 * (1 - h) + ssb * (5 * h - 1))
# Climate effect
recruitment *= climate_productivity
# Add stochasticity
recruitment *= np.exp(np.random.normal(0, 0.3))
return max(recruitment, 0)
def project(self, catch: float, climate_productivity: float = 1.0,
climate_mortality: float = 1.0) -> float:
"""Project population one year forward"""
# Calculate recruitment
self.recruitment = self.calculate_recruitment(climate_productivity)
self.recruitment_history.append(self.recruitment)
# Update age structure
weights = self._get_weights_at_age()
maturity = self._get_maturity_at_age()
# Calculate total and fishing mortality
current_biomass = (self.age_structure * weights).sum()
if current_biomass > 0 and catch > 0:
self.fishing_mortality = min(0.99, catch / current_biomass)
else:
self.fishing_mortality = 0
self.f_history.append(self.fishing_mortality)
# Survive and age
total_mortality = self.params.natural_mortality * climate_mortality + self.fishing_mortality
survival = np.exp(-total_mortality)
new_age_structure = np.zeros(self.n_ages)
new_age_structure[0] = self.recruitment
new_age_structure[1:] = self.age_structure[:-1] * survival
new_age_structure[-1] += self.age_structure[-1] * survival # Plus group
self.age_structure = new_age_structure
# Update biomass
self.biomass = (self.age_structure * weights).sum()
self.biomass_history.append(self.biomass)
self._update_derived_quantities()
# Actual catch (limited by available biomass)
actual_catch = min(catch, current_biomass * 0.8)
self.catch_history.append(actual_catch)
return actual_catch
def get_status(self) -> Dict:
"""Get current stock status"""
bmsy = self.params.biomass_at_bmsy
fmsy = self.params.f_msy
return {
'biomass': self.biomass,
'ssb': self.ssb,
'recruitment': self.recruitment,
'fishing_mortality': self.fishing_mortality,
'b_bmsy': self.biomass / bmsy if bmsy > 0 else 0,
'f_fmsy': self.fishing_mortality / fmsy if fmsy > 0 else 0,
'b_blim': self.biomass / self.params.blim,
'is_overfished': self.biomass < self.params.blim,
'is_overfishing': self.fishing_mortality > fmsy
}
# =============================================================================
# Economic Model
# =============================================================================
class EconomicModel:
"""Socioeconomic dynamics of the fishery"""
def __init__(self, params: EconomicParameters):
self.params = params
self.vessels = params.vessels_current
self.effort = self.vessels * 100 # Standard effort units
# History
self.revenue_history = []
self.cost_history = []
self.profit_history = []
self.employment_history = []
self.vessel_history = [self.vessels]
self.price_history = [params.price_per_tonne]
self.npv = 0
self.npv_history = []
def calculate_catch_from_hcr(self, hcr_catch: float, biomass: float) -> float:
"""Calculate actual catch based on effort and biomass"""
# Catch = q * E * B
potential_catch = self.params.catchability * self.effort * biomass
return min(hcr_catch, potential_catch)
def calculate_economics(self, catch: float, biomass: float, year: int) -> Dict:
"""Calculate economic outcomes"""
# Price with demand elasticity
base_price = self.params.price_per_tonne
price = base_price * (catch / 100) ** self.params.elasticity_demand
price = max(price, base_price * 0.5) # Floor price
self.price_history.append(price)
# Revenue
revenue = price * catch
self.revenue_history.append(revenue)
# Costs
cost = self.params.cost_per_unit_effort * self.effort
self.cost_history.append(cost)
# Profit
profit = revenue - cost
self.profit_history.append(profit)
# Employment
employment = self.vessels * self.params.employment_per_vessel
self.employment_history.append(employment)
# Fleet dynamics - entry/exit based on profitability
if len(self.profit_history) > 1:
avg_profit = np.mean(self.profit_history[-3:]) if len(self.profit_history) >= 3 else profit
profit_ratio = avg_profit / cost if cost > 0 else 0
if profit_ratio > self.params.min_profit_ratio * 2:
# Entry
entry_rate = min(0.1, profit_ratio * 0.05)
self.vessels *= (1 + entry_rate)
elif profit_ratio < self.params.min_profit_ratio:
# Exit
exit_rate = min(0.2, (self.params.min_profit_ratio - profit_ratio) * 0.5)
self.vessels *= (1 - exit_rate)
self.vessels = max(10, self.vessels) # Minimum fleet size
self.effort = self.vessels * 100
self.vessel_history.append(self.vessels)
# NPV calculation
discount_factor = 1 / (1 + self.params.discount_rate) ** year
self.npv += profit * discount_factor
self.npv_history.append(self.npv)
return {
'revenue': revenue,
'cost': cost,
'profit': profit,
'price': price,
'employment': employment,
'vessels': self.vessels,
'effort': self.effort,
'npv': self.npv
}
# =============================================================================
# Harvest Control Rules
# =============================================================================
class HarvestControlRule:
"""Base class for harvest control rules"""
def __init__(self, hcr_type: HCRType):
self.hcr_type = hcr_type
self.tac_history = []
def calculate_tac(self, population: PopulationModel,
climate: ClimateModel,
economics: EconomicModel,
**kwargs) -> float:
"""Calculate Total Allowable Catch"""
raise NotImplementedError
class ConstantCatchHCR(HarvestControlRule):
"""Fixed TAC regardless of stock status"""
def __init__(self, tac: float = 80.0):
super().__init__(HCRType.CONSTANT_CATCH)
self.tac = tac
def calculate_tac(self, population, climate, economics, **kwargs):
return min(self.tac, population.biomass * 0.8)
class ConstantFHCR(HarvestControlRule):
"""Constant fishing mortality rate"""
def __init__(self, f_target: float = 0.15):
super().__init__(HCRType.CONSTANT_F)
self.f_target = f_target
def calculate_tac(self, population, climate, economics, **kwargs):
return self.f_target * population.biomass
class HockeyStickHCR(HarvestControlRule):
"""Hockey stick HCR with biomass thresholds"""
def __init__(self, f_max: float = 0.2, b_trigger: float = 300.0,
b_limit: float = 150.0):
super().__init__(HCRType.HOCKEY_STICK)
self.f_max = f_max
self.b_trigger = b_trigger
self.b_limit = b_limit
def calculate_tac(self, population, climate, economics, **kwargs):
b = population.biomass
if b <= self.b_limit:
f = 0
elif b <= self.b_trigger:
f = self.f_max * (b - self.b_limit) / (self.b_trigger - self.b_limit)
else:
f = self.f_max
return f * b
class ClimateAdaptiveHCR(HarvestControlRule):
"""HCR that adapts to climate conditions"""
def __init__(self, base_f: float = 0.15, climate_sensitivity: float = 0.5,
productivity_threshold: float = 0.8):
super().__init__(HCRType.CLIMATE_ADAPTIVE)
self.base_f = base_f
self.climate_sensitivity = climate_sensitivity
self.productivity_threshold = productivity_threshold
self.learning_rate = 0.1
self.estimated_productivity = 1.0
def calculate_tac(self, population, climate, economics, **kwargs):
# Get climate productivity
current_productivity = climate.calculate_productivity_multiplier()
# Update estimate with learning
self.estimated_productivity = (self.learning_rate * current_productivity +
(1 - self.learning_rate) * self.estimated_productivity)
# Adjust F based on productivity
if self.estimated_productivity < self.productivity_threshold:
# Reduce F when productivity is low
f_adjustment = self.estimated_productivity ** self.climate_sensitivity
else:
f_adjustment = 1.0
# Also consider temperature trend
temp_trend = np.mean(climate.temperature_history[-5:]) if len(climate.temperature_history) >= 5 else 0
if temp_trend > 1.0: # Warming trend
f_adjustment *= 0.9
# Biomass precautionary reduction
b_bmsy = population.biomass / population.params.biomass_at_bmsy
if b_bmsy < 1.0:
f_adjustment *= b_bmsy
adjusted_f = self.base_f * f_adjustment
return adjusted_f * population.biomass
class PrecautionaryHCR(HarvestControlRule):
"""Precautionary approach with uncertainty buffers"""
def __init__(self, f_msy: float = 0.15, buffer: float = 0.2,
b_pa: float = 300.0, b_lim: float = 200.0):
super().__init__(HCRType.PRECAUTIONARY)
self.f_msy = f_msy
self.buffer = buffer # Precautionary buffer (reduction from F_MSY)
self.b_pa = b_pa
self.b_lim = b_lim
self.uncertainty_estimate = 0.2
def calculate_tac(self, population, climate, economics, **kwargs):
b = population.biomass
# Uncertainty increases with climate variability
if len(climate.temperature_history) > 5:
temp_var = np.std(climate.temperature_history[-5:])
self.uncertainty_estimate = 0.2 + temp_var * 0.5
# Precautionary F
f_papy = self.f_msy * (1 - self.buffer - self.uncertainty_estimate * 0.5)
f_papy = max(0, f_papy)
# Reduce F below B_PA
if b < self.b_pa:
reduction = (self.b_pa - b) / (self.b_pa - self.b_lim)
reduction = min(1, max(0, reduction))
f_papy *= (1 - reduction)
return f_papy * b
class MultiObjectiveHCR(HarvestControlRule):
"""HCR balancing multiple objectives"""
def __init__(self, weight_biomass: float = 0.4, weight_catch: float = 0.3,
weight_profit: float = 0.3, f_range: Tuple = (0.05, 0.25)):
super().__init__(HCRType.MULTI_OBJECTIVE)
self.weight_biomass = weight_biomass
self.weight_catch = weight_catch
self.weight_profit = weight_profit
self.f_range = f_range
self.target_biomass = 500.0
def calculate_tac(self, population, climate, economics, **kwargs):
# Evaluate objective function for different F values
f_values = np.linspace(self.f_range[0], self.f_range[1], 20)
best_f = self.f_range[0]
best_score = -np.inf
for f in f_values:
# Project short-term outcomes
projected_catch = f * population.biomass
projected_biomass = population.biomass * (1 - f +
population.params.intrinsic_growth *
(1 - population.biomass / population.params.carrying_capacity))
# Economic projection
price = economics.params.price_per_tonne * (projected_catch / 100) ** economics.params.elasticity_demand
revenue = price * projected_catch
cost = economics.params.cost_per_unit_effort * economics.effort
profit = revenue - cost
# Normalize objectives
biomass_score = projected_biomass / self.target_biomass
biomass_score = min(1, biomass_score) # Saturate at 1
catch_score = projected_catch / 100 # Normalize to ~100kt target
catch_score = min(1, catch_score)
profit_score = profit / 100000 if profit > 0 else profit / 100000
profit_score = max(-1, min(1, profit_score))
# Weighted score
score = (self.weight_biomass * biomass_score +
self.weight_catch * catch_score +
self.weight_profit * profit_score)
if score > best_score:
best_score = score
best_f = f
return best_f * population.biomass
# =============================================================================
# Main Simulator
# =============================================================================
class FisheriesSimulator:
"""Main simulation engine"""
def __init__(self, stock_params: StockParameters,
climate_params: ClimateParameters,
economic_params: EconomicParameters,
climate_scenario: ClimateScenario,
hcr_type: HCRType,
simulation_years: int = 50):
# Initialize components
self.stock_params = stock_params
self.climate_params = climate_params
self.economic_params = economic_params
self.population = PopulationModel(stock_params)
self.climate = ClimateModel(climate_params, climate_scenario)
self.economics = EconomicModel(economic_params)
# Set up HCR
self.hcr = self._create_hcr(hcr_type)
self.simulation_years = simulation_years
self.current_year = 0
# Results storage
self.results = {
'biomass': [],
'ssb': [],
'recruitment': [],
'catch': [],
'fishing_mortality': [],
'temperature': [],
'productivity': [],
'revenue': [],
'profit': [],
'employment': [],
'vessels': [],
'b_bmsy': [],
'f_fmsy': [],
'npv': [],
'climate_state': []
}
def _create_hcr(self, hcr_type: HCRType, **kwargs) -> HarvestControlRule:
"""Factory method for HCR creation"""
hcr_classes = {
HCRType.CONSTANT_CATCH: ConstantCatchHCR,
HCRType.CONSTANT_F: ConstantFHCR,
HCRType.HOCKEY_STICK: HockeyStickHCR,
HCRType.CLIMATE_ADAPTIVE: ClimateAdaptiveHCR,
HCRType.PRECAUTIONARY: PrecautionaryHCR,
HCRType.MULTI_OBJECTIVE: MultiObjectiveHCR
}
hcr_class = hcr_classes.get(hcr_type, HockeyStickHCR)
return hcr_class(**kwargs)
def run_simulation(self, progress_callback: Optional[Callable] = None) -> Dict:
"""Run the full simulation"""
for year in range(self.simulation_years):
self.current_year = year
# Update climate
climate_state = self.climate.update(year)
productivity = self.climate.calculate_productivity_multiplier()
mortality_mult = self.climate.calculate_mortality_multiplier()
# Calculate TAC from HCR
tac = self.hcr.calculate_tac(self.population, self.climate, self.economics)
# Apply catch
actual_catch = self.population.project(tac, productivity, mortality_mult)
# Calculate economics
econ_results = self.economics.calculate_economics(actual_catch,
self.population.biomass, year)
# Store results
stock_status = self.population.get_status()
self.results['biomass'].append(self.population.biomass)
self.results['ssb'].append(self.population.ssb)
self.results['recruitment'].append(self.population.recruitment)
self.results['catch'].append(actual_catch)
self.results['fishing_mortality'].append(self.population.fishing_mortality)
self.results['temperature'].append(climate_state['temperature_anomaly'])
self.results['productivity'].append(productivity)
self.results['revenue'].append(econ_results['revenue'])
self.results['profit'].append(econ_results['profit'])
self.results['employment'].append(econ_results['employment'])
self.results['vessels'].append(econ_results['vessels'])
self.results['b_bmsy'].append(stock_status['b_bmsy'])
self.results['f_fmsy'].append(stock_status['f_fmsy'])
self.results['npv'].append(econ_results['npv'])
self.results['climate_state'].append(climate_state)
# Progress callback
if progress_callback:
progress_callback(year + 1, self.simulation_years)
return self.results
def get_summary_statistics(self) -> Dict:
"""Calculate summary statistics from simulation"""
if not self.results['biomass']:
return {}
return {
'final_biomass': self.results['biomass'][-1],
'avg_catch': np.mean(self.results['catch']),
'total_catch': np.sum(self.results['catch']),
'avg_profit': np.mean(self.results['profit']),
'final_npv': self.results['npv'][-1],
'avg_employment': np.mean(self.results['employment']),
'collapse_probability': np.mean([1 if b < self.stock_params.blim * 0.5
else 0 for b in self.results['biomass']]),
'overfishing_years': np.sum([1 if f > self.stock_params.f_msy
else 0 for f in self.results['fishing_mortality']]),
'final_temperature': self.results['temperature'][-1],
'b_bmsy_final': self.results['b_bmsy'][-1],
'f_fmsy_final': self.results['f_fmsy'][-1]
}
# =============================================================================
# GUI Application
# =============================================================================
class FisheriesSimulatorGUI:
"""Main GUI application"""
def __init__(self, root: tk.Tk):
self.root = root
self.root.title("Climate-Aware Fisheries Harvest Control Rule Simulator")
self.root.geometry("1400x900")
# Default parameters
self.stock_params = StockParameters()
self.climate_params = ClimateParameters()
self.economic_params = EconomicParameters()
# Simulation state
self.simulator = None
self.results = None
# Build GUI
self._create_menu()
self._create_main_layout()
self._create_parameter_panels()
self._create_visualization_panels()
self._create_status_bar()
def _create_menu(self):
"""Create menu bar"""
menubar = tk.Menu(self.root)
# File menu
file_menu = tk.Menu(menubar, tearoff=0)
file_menu.add_command(label="Run Simulation", command=self.run_simulation)
file_menu.add_command(label="Export Results", command=self.export_results)
file_menu.add_separator()
file_menu.add_command(label="Exit", command=self.root.quit)
menubar.add_cascade(label="File", menu=file_menu)
# Scenarios menu
scenario_menu = tk.Menu(menubar, tearoff=0)
for scenario in ClimateScenario:
scenario_menu.add_command(
label=scenario.value,
command=lambda s=scenario: self._set_climate_scenario(s)
)
menubar.add_cascade(label="Climate Scenarios", menu=scenario_menu)
# HCR menu
hcr_menu = tk.Menu(menubar, tearoff=0)
for hcr_type in HCRType:
hcr_menu.add_command(
label=hcr_type.value,
command=lambda h=hcr_type: self._set_hcr_type(h)
)
menubar.add_cascade(label="Harvest Control Rules", menu=hcr_menu)
# Help menu
help_menu = tk.Menu(menubar, tearoff=0)
help_menu.add_command(label="About", command=self.show_about)
help_menu.add_command(label="Documentation", command=self.show_documentation)
menubar.add_cascade(label="Help", menu=help_menu)
self.root.config(menu=menubar)
# Track current selections
self.current_scenario = ClimateScenario.MODERATE_WARMING
self.current_hcr = HCRType.HOCKEY_STICK
def _create_main_layout(self):
"""Create main layout structure"""
# Main container
self.main_frame = ttk.Frame(self.root)
self.main_frame.pack(fill=tk.BOTH, expand=True, padx=5, pady=5)
# Left panel for parameters
self.param_frame = ttk.Frame(self.main_frame, width=350)
self.param_frame.pack(side=tk.LEFT, fill=tk.Y, padx=5)
self.param_frame.pack_propagate(False)
# Right panel for visualizations
self.viz_frame = ttk.Frame(self.main_frame)
self.viz_frame.pack(side=tk.RIGHT, fill=tk.BOTH, expand=True, padx=5)
def _create_parameter_panels(self):
"""Create parameter input panels"""
# Notebook for parameter categories
self.param_notebook = ttk.Notebook(self.param_frame)
self.param_notebook.pack(fill=tk.BOTH, expand=True)
# Biological parameters tab
self.bio_frame = ttk.Frame(self.param_notebook)
self._create_biological_params()
self.param_notebook.add(self.bio_frame, text="Biological")
# Climate parameters tab
self.climate_frame = ttk.Frame(self.param_notebook)
self._create_climate_params()
self.param_notebook.add(self.climate_frame, text="Climate")
# Economic parameters tab
self.econ_frame = ttk.Frame(self.param_notebook)
self._create_economic_params()
self.param_notebook.add(self.econ_frame, text="Economic")
# HCR parameters tab
self.hcr_frame = ttk.Frame(self.param_notebook)
self._create_hcr_params()
self.param_notebook.add(self.hcr_frame, text="HCR Settings")
# Control buttons
self.control_frame = ttk.Frame(self.param_frame)
self.control_frame.pack(fill=tk.X, pady=10)
self.run_button = ttk.Button(self.control_frame, text="Run Simulation",
command=self.run_simulation)
self.run_button.pack(fill=tk.X, padx=5, pady=2)
self.compare_button = ttk.Button(self.control_frame, text="Compare HCRs",
command=self.compare_hcrs)
self.compare_button.pack(fill=tk.X, padx=5, pady=2)
self.reset_button = ttk.Button(self.control_frame, text="Reset Parameters",
command=self.reset_parameters)
self.reset_button.pack(fill=tk.X, padx=5, pady=2)
def _create_biological_params(self):
"""Create biological parameter inputs"""
# Stock parameters
bio_params_frame = ttk.LabelFrame(self.bio_frame, text="Stock Parameters")
bio_params_frame.pack(fill=tk.X, padx=5, pady=5)
params = [
("Carrying Capacity (K)", "carrying_capacity", 100, 2000, self.stock_params.carrying_capacity),
("Intrinsic Growth (r)", "intrinsic_growth", 0.1, 0.8, self.stock_params.intrinsic_growth),
("Initial Biomass", "current_biomass", 100, 1500, self.stock_params.current_biomass),
("B_MSY", "biomass_at_bmsy", 100, 1000, self.stock_params.biomass_at_bmsy),
("F_MSY", "f_msy", 0.05, 0.4, self.stock_params.f_msy),
("B_Limit", "blim", 50, 500, self.stock_params.blim),
("B_Precautionary", "bpa", 100, 500, self.stock_params.bpa),
("Steepness (h)", "steepness", 0.3, 0.95, self.stock_params.steepness),
("Natural Mortality (M)", "natural_mortality", 0.05, 0.5, self.stock_params.natural_mortality),
]
self.bio_vars = {}
for i, (label, attr, min_val, max_val, default) in enumerate(params):
frame = ttk.Frame(bio_params_frame)
frame.pack(fill=tk.X, padx=5, pady=2)
ttk.Label(frame, text=label, width=22).pack(side=tk.LEFT)
var = tk.DoubleVar(value=default)
self.bio_vars[attr] = var
scale = ttk.Scale(frame, from_=min_val, to=max_val, variable=var,
orient=tk.HORIZONTAL, length=120)
scale.pack(side=tk.LEFT, padx=5)
entry = ttk.Entry(frame, textvariable=var, width=8)
entry.pack(side=tk.LEFT)
def _create_climate_params(self):
"""Create climate parameter inputs"""
# Scenario selection
scenario_frame = ttk.LabelFrame(self.climate_frame, text="Climate Scenario")
scenario_frame.pack(fill=tk.X, padx=5, pady=5)
self.scenario_var = tk.StringVar(value=self.current_scenario.value)
for scenario in ClimateScenario:
ttk.Radiobutton(scenario_frame, text=scenario.value,
variable=self.scenario_var, value=scenario.value,
command=lambda s=scenario: self._set_climate_scenario(s)
).pack(anchor=tk.W, padx=5)
# Climate sensitivity parameters
climate_params_frame = ttk.LabelFrame(self.climate_frame, text="Climate Sensitivity")
climate_params_frame.pack(fill=tk.X, padx=5, pady=5)
params = [
("Temp. Effect on Growth", "temperature_sensitivity", -0.2, 0.0, -0.05),
("Warming Rate (°C/yr)", "warming_rate", 0.0, 0.1, 0.02),
("Acidification Rate", "acidification_rate", 0.0, 0.01, 0.001),
("Recruitment pH Impact", "recruitment_impact", -0.1, 0.0, -0.03),
("Regime Shift Prob.", "regime_shift_probability", 0.0, 0.1, 0.02),
("Extreme Event Prob.", "extreme_event_probability", 0.0, 0.2, 0.05),
]
self.climate_vars = {}
for i, (label, attr, min_val, max_val, default) in enumerate(params):
frame = ttk.Frame(climate_params_frame)
frame.pack(fill=tk.X, padx=5, pady=2)
ttk.Label(frame, text=label, width=20).pack(side=tk.LEFT)
var = tk.DoubleVar(value=default)
self.climate_vars[attr] = var
scale = ttk.Scale(frame, from_=min_val, to=max_val, variable=var,
orient=tk.HORIZONTAL, length=100)
scale.pack(side=tk.LEFT, padx=5)
entry = ttk.Entry(frame, textvariable=var, width=8)
entry.pack(side=tk.LEFT)
def _create_economic_params(self):
"""Create economic parameter inputs"""
# Economic parameters
econ_params_frame = ttk.LabelFrame(self.econ_frame, text="Economic Parameters")
econ_params_frame.pack(fill=tk.X, padx=5, pady=5)
params = [
("Price ($/tonne)", "price_per_tonne", 100, 5000, self.economic_params.price_per_tonne),
("Cost per Unit Effort", "cost_per_unit_effort", 10, 500, self.economic_params.cost_per_unit_effort),
("Catchability (q)", "catchability", 0.0001, 0.01, self.economic_params.catchability),
("Demand Elasticity", "elasticity_demand", -1.0, -0.1, self.economic_params.elasticity_demand),
("Employment/Vessel", "employment_per_vessel", 1, 20, self.economic_params.employment_per_vessel),
("Initial Vessels", "vessels_current", 10, 500, self.economic_params.vessels_current),
("Discount Rate", "discount_rate", 0.01, 0.15, self.economic_params.discount_rate),
]
self.econ_vars = {}
for i, (label, attr, min_val, max_val, default) in enumerate(params):
frame = ttk.Frame(econ_params_frame)
frame.pack(fill=tk.X, padx=5, pady=2)
ttk.Label(frame, text=label, width=20).pack(side=tk.LEFT)
var = tk.DoubleVar(value=default)
self.econ_vars[attr] = var
scale = ttk.Scale(frame, from_=min_val, to=max_val, variable=var,
orient=tk.HORIZONTAL, length=100)
scale.pack(side=tk.LEFT, padx=5)
entry = ttk.Entry(frame, textvariable=var, width=8)
entry.pack(side=tk.LEFT)
# Simulation settings
sim_frame = ttk.LabelFrame(self.econ_frame, text="Simulation Settings")
sim_frame.pack(fill=tk.X, padx=5, pady=5)
ttk.Label(sim_frame, text="Simulation Years:").pack(side=tk.LEFT, padx=5)
self.years_var = tk.IntVar(value=50)
ttk.Spinbox(sim_frame, from_=10, to=200, textvariable=self.years_var,
width=8).pack(side=tk.LEFT, padx=5)
def _create_hcr_params(self):
"""Create HCR parameter inputs"""
# HCR type selection
hcr_type_frame = ttk.LabelFrame(self.hcr_frame, text="HCR Type")
hcr_type_frame.pack(fill=tk.X, padx=5, pady=5)
self.hcr_var = tk.StringVar(value=self.current_hcr.value)
for hcr_type in HCRType:
ttk.Radiobutton(hcr_type_frame, text=hcr_type.value,
variable=self.hcr_var, value=hcr_type.value,
command=lambda h=hcr_type: self._set_hcr_type(h)
).pack(anchor=tk.W, padx=5)
# HCR-specific parameters
self.hcr_params_frame = ttk.LabelFrame(self.hcr_frame, text="HCR Parameters")
self.hcr_params_frame.pack(fill=tk.X, padx=5, pady=5)
self.hcr_specific_vars = {}
self._update_hcr_params()
def _update_hcr_params(self):
"""Update HCR-specific parameters based on selection"""
# Clear existing widgets
for widget in self.hcr_params_frame.winfo_children():
widget.destroy()
self.hcr_specific_vars = {}
if self.current_hcr == HCRType.CONSTANT_CATCH:
params = [("TAC", "tac", 10, 200, 80)]
elif self.current_hcr == HCRType.CONSTANT_F:
params = [("Target F", "f_target", 0.05, 0.4, 0.15)]
elif self.current_hcr == HCRType.HOCKEY_STICK:
params = [
("F_max", "f_max", 0.1, 0.4, 0.2),
("B_trigger", "b_trigger", 100, 500, 300),
("B_limit", "b_limit", 50, 300, 150),
]
elif self.current_hcr == HCRType.CLIMATE_ADAPTIVE:
params = [
("Base F", "base_f", 0.05, 0.3, 0.15),
("Climate Sensitivity", "climate_sensitivity", 0.1, 1.0, 0.5),
("Productivity Threshold", "productivity_threshold", 0.5, 1.0, 0.8),
]
elif self.current_hcr == HCRType.PRECAUTIONARY:
params = [
("F_MSY", "f_msy", 0.1, 0.3, 0.15),
("Precautionary Buffer", "buffer", 0.05, 0.4, 0.2),
("B_PA", "b_pa", 100, 500, 300),
]
else: # Multi-objective
params = [
("Biomass Weight", "weight_biomass", 0.0, 1.0, 0.4),
("Catch Weight", "weight_catch", 0.0, 1.0, 0.3),
("Profit Weight", "weight_profit", 0.0, 1.0, 0.3),
]
for label, attr, min_val, max_val, default in params:
frame = ttk.Frame(self.hcr_params_frame)
frame.pack(fill=tk.X, padx=5, pady=2)
ttk.Label(frame, text=label, width=18).pack(side=tk.LEFT)
var = tk.DoubleVar(value=default)
self.hcr_specific_vars[attr] = var
scale = ttk.Scale(frame, from_=min_val, to=max_val, variable=var,
orient=tk.HORIZONTAL, length=100)
scale.pack(side=tk.LEFT, padx=5)
entry = ttk.Entry(frame, textvariable=var, width=8)
entry.pack(side=tk.LEFT)
def _create_visualization_panels(self):
"""Create visualization panels"""
# Notebook for different visualization views
self.viz_notebook = ttk.Notebook(self.viz_frame)
self.viz_notebook.pack(fill=tk.BOTH, expand=True)
# Main results tab
self.results_frame = ttk.Frame(self.viz_notebook)
self.viz_notebook.add(self.results_frame, text="Main Results")
# Kobe plot tab
self.kobe_frame = ttk.Frame(self.viz_notebook)
self.viz_notebook.add(self.kobe_frame, text="Kobe Plot")
# Economics tab
self.econ_viz_frame = ttk.Frame(self.viz_notebook)
self.viz_notebook.add(self.econ_viz_frame, text="Economics")
# Climate impacts tab
self.climate_viz_frame = ttk.Frame(self.viz_notebook)
self.viz_notebook.add(self.climate_viz_frame, text="Climate Impacts")
# Comparison tab
self.compare_frame = ttk.Frame(self.viz_notebook)
self.viz_notebook.add(self.compare_frame, text="HCR Comparison")
# Create matplotlib figures
self._create_main_results_figure()
self._create_kobe_figure()
self._create_economics_figure()
self._create_climate_figure()
def _create_main_results_figure(self):
"""Create main results visualization"""
self.fig_main = Figure(figsize=(10, 8), dpi=100)
self.fig_main.set_facecolor('#f0f0f0')
# Create subplots
self.ax_biomass = self.fig_main.add_subplot(221)
self.ax_catch = self.fig_main.add_subplot(222)
self.ax_fishing = self.fig_main.add_subplot(223)
self.ax_recruitment = self.fig_main.add_subplot(224)
self.canvas_main = FigureCanvasTkAgg(self.fig_main, self.results_frame)
self.canvas_main.get_tk_widget().pack(fill=tk.BOTH, expand=True)
def _create_kobe_figure(self):
"""Create Kobe plot visualization"""
self.fig_kobe = Figure(figsize=(8, 8), dpi=100)
self.ax_kobe = self.fig_kobe.add_subplot(111)
self.canvas_kobe = FigureCanvasTkAgg(self.fig_kobe, self.kobe_frame)
self.canvas_kobe.get_tk_widget().pack(fill=tk.BOTH, expand=True)
def _create_economics_figure(self):
"""Create economics visualization"""
self.fig_econ = Figure(figsize=(10, 8), dpi=100)
self.ax_profit = self.fig_econ.add_subplot(221)
self.ax_employment = self.fig_econ.add_subplot(222)
self.ax_price = self.fig_econ.add_subplot(223)
self.ax_npv = self.fig_econ.add_subplot(224)
self.canvas_econ = FigureCanvasTkAgg(self.fig_econ, self.econ_viz_frame)
self.canvas_econ.get_tk_widget().pack(fill=tk.BOTH, expand=True)
def _create_climate_figure(self):
"""Create climate impacts visualization"""
self.fig_climate = Figure(figsize=(10, 8), dpi=100)
self.ax_temp = self.fig_climate.add_subplot(221)
self.ax_productivity = self.fig_climate.add_subplot(222)
self.ax_climate_bio = self.fig_climate.add_subplot(223)
self.ax_regime = self.fig_climate.add_subplot(224)
self.canvas_climate = FigureCanvasTkAgg(self.fig_climate, self.climate_viz_frame)
self.canvas_climate.get_tk_widget().pack(fill=tk.BOTH, expand=True)
def _create_status_bar(self):
"""Create status bar"""
self.status_frame = ttk.Frame(self.root)
self.status_frame.pack(fill=tk.X, side=tk.BOTTOM)
self.status_label = ttk.Label(self.status_frame, text="Ready")
self.status_label.pack(side=tk.LEFT, padx=5)
self.progress_var = tk.DoubleVar()
self.progress_bar = ttk.Progressbar(self.status_frame, variable=self.progress_var,
maximum=100)
self.progress_bar.pack(side=tk.RIGHT, fill=tk.X, expand=True, padx=5)
def _set_climate_scenario(self, scenario: ClimateScenario):
"""Set climate scenario"""
self.current_scenario = scenario
self.scenario_var.set(scenario.value)
self.status_label.config(text=f"Scenario: {scenario.value}")
def _set_hcr_type(self, hcr_type: HCRType):
"""Set HCR type"""
self.current_hcr = hcr_type
self.hcr_var.set(hcr_type.value)
self._update_hcr_params()
self.status_label.config(text=f"HCR: {hcr_type.value}")
def _get_parameters_from_gui(self) -> Tuple:
"""Extract parameters from GUI inputs"""
# Update stock parameters
for attr, var in self.bio_vars.items():
setattr(self.stock_params, attr, var.get())
# Update climate parameters
for attr, var in self.climate_vars.items():
setattr(self.climate_params, attr, var.get())
# Update economic parameters
for attr, var in self.econ_vars.items():
setattr(self.economic_params, attr, var.get())
return self.stock_params, self.climate_params, self.economic_params
def run_simulation(self):
"""Run the simulation with current parameters"""
try:
# Get parameters
stock_params, climate_params, economic_params = self._get_parameters_from_gui()
# Create simulator
self.simulator = FisheriesSimulator(
stock_params=stock_params,
climate_params=climate_params,
economic_params=economic_params,
climate_scenario=self.current_scenario,
hcr_type=self.current_hcr,
simulation_years=self.years_var.get()
)
# Configure HCR with specific parameters
self._configure_hcr()
# Run with progress callback
self.status_label.config(text="Running simulation...")
def progress_callback(current, total):
self.progress_var.set(current / total * 100)
self.root.update()
self.results = self.simulator.run_simulation(progress_callback)
# Update visualizations
self._update_main_results()
self._update_kobe_plot()
self._update_economics_plot()
self._update_climate_plot()
# Show summary
self._show_summary()
self.status_label.config(text="Simulation complete")
self.progress_var.set(0)
except Exception as e:
messagebox.showerror("Error", f"Simulation failed: {str(e)}")
self.status_label.config(text="Error in simulation")
def _configure_hcr(self):
"""Configure HCR with GUI parameters"""
hcr = self.simulator.hcr
for attr, var in self.hcr_specific_vars.items():
if hasattr(hcr, attr):
setattr(hcr, attr, var.get())
def _update_main_results(self):
"""Update main results plots"""
if not self.results:
return
years = range(len(self.results['biomass']))
# Clear axes
for ax in [self.ax_biomass, self.ax_catch, self.ax_fishing, self.ax_recruitment]:
ax.clear()
# Biomass plot
self.ax_biomass.plot(years, self.results['biomass'], 'b-', linewidth=2, label='Biomass')
self.ax_biomass.axhline(y=self.stock_params.biomass_at_bmsy, color='g', linestyle='--',
label='B_MSY')
self.ax_biomass.axhline(y=self.stock_params.blim, color='r', linestyle='--',
label='B_Limit')
self.ax_biomass.fill_between(years, 0, self.stock_params.blim, alpha=0.2, color='red')
self.ax_biomass.set_xlabel('Year')
self.ax_biomass.set_ylabel('Biomass (kt)')
self.ax_biomass.set_title('Stock Biomass')
self.ax_biomass.legend(loc='upper right')
self.ax_biomass.grid(True, alpha=0.3)
# Catch plot
self.ax_catch.plot(years, self.results['catch'], 'g-', linewidth=2)
self.ax_catch.set_xlabel('Year')
self.ax_catch.set_ylabel('Catch (kt)')
self.ax_catch.set_title('Annual Catch')
self.ax_catch.grid(True, alpha=0.3)
# Fishing mortality plot
self.ax_fishing.plot(years, self.results['fishing_mortality'], 'r-', linewidth=2,
label='F')
self.ax_fishing.axhline(y=self.stock_params.f_msy, color='k', linestyle='--',
label='F_MSY')
self.ax_fishing.set_xlabel('Year')
self.ax_fishing.set_ylabel('Fishing Mortality')
self.ax_fishing.set_title('Fishing Mortality')
self.ax_fishing.legend()
self.ax_fishing.grid(True, alpha=0.3)
# Recruitment plot
self.ax_recruitment.plot(years, self.results['recruitment'], 'm-', linewidth=2)
self.ax_recruitment.set_xlabel('Year')
self.ax_recruitment.set_ylabel('Recruitment')
self.ax_recruitment.set_title('Recruitment')
self.ax_recruitment.grid(True, alpha=0.3)
self.fig_main.tight_layout()
self.canvas_main.draw()
def _update_kobe_plot(self):
"""Update Kobe plot"""
if not self.results:
return
self.ax_kobe.clear()
b_bmsy = np.array(self.results['b_bmsy'])
f_fmsy = np.array(self.results['f_fmsy'])
# Color regions
self.ax_kobe.axhspan(1, 3, xmin=0, xmax=0.5, alpha=0.3, color='red',
label='Overfishing')
self.ax_kobe.axhspan(0, 1, xmin=0.5, xmax=1, alpha=0.3, color='yellow',
label='Recovery')
self.ax_kobe.axhspan(1, 3, xmin=0.5, xmax=1, alpha=0.3, color='green',
label='Sustainable')
self.ax_kobe.axhspan(0, 1, xmin=0, xmax=0.5, alpha=0.3, color='orange',
label='Overfished')
# Trajectory
scatter = self.ax_kobe.scatter(b_bmsy, f_fmsy, c=range(len(b_bmsy)),
cmap='viridis', s=30, alpha=0.7)
self.ax_kobe.plot(b_bmsy, f_fmsy, 'k-', alpha=0.3, linewidth=0.5)
# Start and end points
self.ax_kobe.scatter(b_bmsy[0], f_fmsy[0], c='green', s=100, marker='^',
label='Start', zorder=5)
self.ax_kobe.scatter(b_bmsy[-1], f_fmsy[-1], c='red', s=100, marker='v',
label='End', zorder=5)
# Reference lines
self.ax_kobe.axhline(y=1, color='k', linestyle='-', linewidth=1)
self.ax_kobe.axvline(x=1, color='k', linestyle='-', linewidth=1)
self.ax_kobe.set_xlabel('B/B_MSY')
self.ax_kobe.set_ylabel('F/F_MSY')
self.ax_kobe.set_title(f'Kobe Plot - {self.current_hcr.value}')
self.ax_kobe.set_xlim(0, max(2.5, max(b_bmsy) * 1.1))
self.ax_kobe.set_ylim(0, max(2, max(f_fmsy) * 1.1))
self.ax_kobe.legend(loc='upper right')
self.ax_kobe.grid(True, alpha=0.3)
# Add colorbar
cbar = self.fig_kobe.colorbar(scatter, ax=self.ax_kobe, label='Year')
self.fig_kobe.tight_layout()
self.canvas_kobe.draw()
def _update_economics_plot(self):
"""Update economics plots"""
if not self.results:
return
years = range(len(self.results['profit']))
# Clear axes
for ax in [self.ax_profit, self.ax_employment, self.ax_price, self.ax_npv]:
ax.clear()
# Profit plot
profits = self.results['profit']
colors = ['g' if p > 0 else 'r' for p in profits]
self.ax_profit.bar(years, profits, color=colors, alpha=0.7)
self.ax_profit.axhline(y=0, color='k', linestyle='-', linewidth=0.5)
self.ax_profit.set_xlabel('Year')
self.ax_profit.set_ylabel('Profit ($)')
self.ax_profit.set_title('Annual Profit')
self.ax_profit.grid(True, alpha=0.3)
# Employment plot
self.ax_employment.plot(years, self.results['employment'], 'b-', linewidth=2)
self.ax_employment.fill_between(years, 0, self.results['employment'], alpha=0.3)
self.ax_employment.set_xlabel('Year')
self.ax_employment.set_ylabel('Employment (jobs)')
self.ax_employment.set_title('Fishery Employment')
self.ax_employment.grid(True, alpha=0.3)
# Vessels plot (using price axis)
self.ax_price.plot(years, self.results['vessels'], 'purple', linewidth=2)
self.ax_price.set_xlabel('Year')
self.ax_price.set_ylabel('Number of Vessels')
self.ax_price.set_title('Fleet Size')
self.ax_price.grid(True, alpha=0.3)
# NPV plot
self.ax_npv.plot(years, self.results['npv'], 'g-', linewidth=2)
self.ax_npv.set_xlabel('Year')
self.ax_npv.set_ylabel('NPV ($)')
self.ax_npv.set_title('Net Present Value')
self.ax_npv.grid(True, alpha=0.3)
self.fig_econ.tight_layout()
self.canvas_econ.draw()
def _update_climate_plot(self):
"""Update climate impacts plots"""
if not self.results:
return
years = range(len(self.results['temperature']))
# Clear axes
for ax in [self.ax_temp, self.ax_productivity, self.ax_climate_bio, self.ax_regime]:
ax.clear()
# Temperature anomaly plot
self.ax_temp.plot(years, self.results['temperature'], 'r-', linewidth=2)
self.ax_temp.axhline(y=1.5, color='orange', linestyle='--', label='+1.5°C threshold')
self.ax_temp.axhline(y=2.0, color='red', linestyle='--', label='+2.0°C threshold')
self.ax_temp.set_xlabel('Year')
self.ax_temp.set_ylabel('Temperature Anomaly (°C)')
self.ax_temp.set_title(f'Climate Scenario: {self.current_scenario.value}')
self.ax_temp.legend()
self.ax_temp.grid(True, alpha=0.3)
# Productivity multiplier plot
self.ax_productivity.plot(years, self.results['productivity'], 'g-', linewidth=2)
self.ax_productivity.axhline(y=1.0, color='k', linestyle='--', label='Baseline')
self.ax_productivity.set_xlabel('Year')
self.ax_productivity.set_ylabel('Productivity Multiplier')
self.ax_productivity.set_title('Stock Productivity (Climate Effect)')
self.ax_productivity.legend()
self.ax_productivity.grid(True, alpha=0.3)
# Climate vs biomass
ax2 = self.ax_climate_bio.twinx()
line1, = self.ax_climate_bio.plot(years, self.results['temperature'], 'r-',
linewidth=2, label='Temperature')
line2, = ax2.plot(years, self.results['biomass'], 'b-',
linewidth=2, label='Biomass')
self.ax_climate_bio.set_xlabel('Year')
self.ax_climate_bio.set_ylabel('Temperature Anomaly (°C)', color='r')
ax2.set_ylabel('Biomass (kt)', color='b')
self.ax_climate_bio.set_title('Climate-Biomass Relationship')
self.ax_climate_bio.legend([line1, line2], ['Temperature', 'Biomass'])
self.ax_climate_bio.grid(True, alpha=0.3)
# Climate state tracking
regime_shifts = [cs['regime_shift_year'] for cs in self.results['climate_state']
if cs['regime_shifted'] and cs['regime_shift_year']]
self.ax_regime.plot(years, self.results['productivity'], 'g-', linewidth=2)
for rs_year in regime_shifts:
if rs_year < len(years):
self.ax_regime.axvline(x=rs_year, color='red', linestyle='--',
label='Regime Shift' if rs_year == regime_shifts[0] else '')
self.ax_regime.set_xlabel('Year')
self.ax_regime.set_ylabel('Productivity')
self.ax_regime.set_title('Regime Shifts and Productivity')
self.ax_regime.legend()
self.ax_regime.grid(True, alpha=0.3)
self.fig_climate.tight_layout()
self.canvas_climate.draw()
def _show_summary(self):
"""Show summary statistics"""
if not self.simulator:
return
stats = self.simulator.get_summary_statistics()
# Create summary window
summary_window = tk.Toplevel(self.root)
summary_window.title("Simulation Summary")
summary_window.geometry("400x400")
ttk.Label(summary_window, text="Simulation Results Summary",
font=('Arial', 14, 'bold')).pack(pady=10)
frame = ttk.Frame(summary_window)
frame.pack(fill=tk.BOTH, expand=True, padx=20)
labels = [
f"Final Biomass: {stats.get('final_biomass', 0):.1f} kt",
f"Average Annual Catch: {stats.get('avg_catch', 0):.1f} kt",
f"Total Catch: {stats.get('total_catch', 0):.1f} kt",
f"Average Annual Profit: ${stats.get('avg_profit', 0):,.0f}",
f"Final NPV: ${stats.get('final_npv', 0):,.0f}",
f"Average Employment: {stats.get('avg_employment', 0):.0f} jobs",
f"Collapse Risk: {stats.get('collapse_probability', 0)*100:.1f}%",
f"Years of Overfishing: {stats.get('overfishing_years', 0)}",
f"Final Temperature: +{stats.get('final_temperature', 0):.2f}°C",
f"Final B/B_MSY: {stats.get('b_bmsy_final', 0):.2f}",
f"Final F/F_MSY: {stats.get('f_fmsy_final', 0):.2f}",
]
for label in labels:
ttk.Label(frame, text=label, font=('Arial', 10)).pack(anchor=tk.W, pady=2)
def compare_hcrs(self):
"""Compare different HCRs under current conditions"""
# Create comparison window
compare_window = tk.Toplevel(self.root)
compare_window.title("HCR Comparison")
compare_window.geometry("1000x700")
# Get parameters
stock_params, climate_params, economic_params = self._get_parameters_from_gui()
# Run simulations for each HCR type
results_dict = {}
def run_comparisons():
progress_var = tk.DoubleVar()
progress_bar = ttk.Progressbar(compare_window, variable=progress_var,
maximum=len(HCRType))
progress_bar.pack(fill=tk.X, padx=10, pady=5)
for i, hcr_type in enumerate(HCRType):
sim = FisheriesSimulator(
stock_params=stock_params,
climate_params=climate_params,
economic_params=economic_params,
climate_scenario=self.current_scenario,
hcr_type=hcr_type,
simulation_years=self.years_var.get()
)
results = sim.run_simulation()
results_dict[hcr_type] = {
'results': results,
'stats': sim.get_summary_statistics()
}
progress_var.set(i + 1)
compare_window.update()
progress_bar.destroy()
_plot_comparisons()
def _plot_comparisons():
fig = Figure(figsize=(12, 8), dpi=100)
# Biomass comparison
ax1 = fig.add_subplot(221)
for hcr_type, data in results_dict.items():
ax1.plot(data['results']['biomass'], label=hcr_type.value, linewidth=2)
ax1.set_xlabel('Year')
ax1.set_ylabel('Biomass (kt)')
ax1.set_title('Biomass Trajectories')
ax1.legend(fontsize=8)
ax1.grid(True, alpha=0.3)
# Catch comparison
ax2 = fig.add_subplot(222)
for hcr_type, data in results_dict.items():
ax2.plot(data['results']['catch'], label=hcr_type.value, linewidth=2)
ax2.set_xlabel('Year')
ax2.set_ylabel('Catch (kt)')
ax2.set_title('Catch Trajectories')
ax2.legend(fontsize=8)
ax2.grid(True, alpha=0.3)
# NPV comparison
ax3 = fig.add_subplot(223)
for hcr_type, data in results_dict.items():
ax3.plot(data['results']['npv'], label=hcr_type.value, linewidth=2)
ax3.set_xlabel('Year')
ax3.set_ylabel('NPV ($)')
ax3.set_title('Net Present Value')
ax3.legend(fontsize=8)
ax3.grid(True, alpha=0.3)
# Summary bar chart
ax4 = fig.add_subplot(224)
metrics = ['final_biomass', 'total_catch', 'final_npv']
x = np.arange(len(metrics))
width = 0.1
for i, (hcr_type, data) in enumerate(results_dict.items()):
values = [data['stats'].get(m, 0) for m in metrics]
# Normalize for visualization
values_norm = [v / max(1, max([results_dict[h][stats].get(m, 1)
for h in results_dict]))
for v, m in zip(values, metrics)]
ax4.bar(x + i * width, values_norm, width, label=hcr_type.value[:10])
ax4.set_xlabel('Metric')
ax4.set_ylabel('Normalized Value')
ax4.set_title('Performance Comparison')
ax4.set_xticks(x + width * 2.5)
ax4.set_xticklabels(['Biomass', 'Catch', 'NPV'])
ax4.legend(fontsize=7, loc='upper right')
ax4.grid(True, alpha=0.3)
fig.tight_layout()
canvas = FigureCanvasTkAgg(fig, compare_window)
canvas.get_tk_widget().pack(fill=tk.BOTH, expand=True)
canvas.draw()
# Run comparisons
compare_window.after(100, run_comparisons)
def export_results(self):
"""Export results to file"""
if not self.results:
messagebox.showwarning("Warning", "No results to export. Run simulation first.")
return
import tkinter.filedialog as fd
filename = fd.asksaveasfilename(
defaultextension=".json",
filetypes=[("JSON files", "*.json"), ("CSV files", "*.csv")]
)
if filename:
if filename.endswith('.json'):
with open(filename, 'w') as f:
json.dump(self.results, f, indent=2)
else:
import csv
with open(filename, 'w', newline='') as f:
writer = csv.writer(f)
writer.writerow(['Year'] + list(self.results.keys()))
for i in range(len(self.results['biomass'])):
row = [i] + [self.results[k][i] for k in self.results.keys()]
writer.writerow(row)
messagebox.showinfo("Success", f"Results exported to {filename}")
def reset_parameters(self):
"""Reset all parameters to defaults"""
self.stock_params = StockParameters()
self.climate_params = ClimateParameters()
self.economic_params = EconomicParameters()
# Update GUI
for attr, var in self.bio_vars.items():
var.set(getattr(self.stock_params, attr))
for attr, var in self.climate_vars.items():
var.set(getattr(self.climate_params, attr))
for attr, var in self.econ_vars.items():
var.set(getattr(self.economic_params, attr))
self.status_label.config(text="Parameters reset to defaults")
def show_about(self):
"""Show about dialog"""
messagebox.showinfo("About",
"Climate-Aware Fisheries Harvest Control Rule Simulator\n\n"
"Version 1.0\n\n"
"This simulator integrates:\n"
"• Ecological population dynamics\n"
"• Climate impact modeling\n"
"• Socioeconomic analysis\n"
"• Adaptive management strategies\n\n"
"Developed for fisheries management research and education.")
def show_documentation(self):
"""Show documentation"""
doc_window = tk.Toplevel(self.root)
doc_window.title("Documentation")
doc_window.geometry("600x500")
text = tk.Text(doc_window, wrap=tk.WORD, padx=10, pady=10)
text.pack(fill=tk.BOTH, expand=True)
documentation = """
CLIMATE-AWARE FISHERIES HARVEST CONTROL RULE SIMULATOR
=======================================================
OVERVIEW
--------
This simulator models the interactions between fish stock dynamics,
climate change, and fishing management strategies. It allows
exploration of different harvest control rules (HCRs) under
various climate scenarios.
BIOLOGICAL MODEL
----------------
The model uses an age-structured population with:
- Beverton-Holt stock-recruitment relationship
- Climate-affected productivity
- Natural and fishing mortality
- Spawning stock biomass tracking
CLIMATE MODEL
-------------
Climate effects include:
- Temperature effects on growth and recruitment
- Ocean acidification impacts
- Potential regime shifts
- Extreme mortality events
HARVEST CONTROL RULES
---------------------
1. Constant Catch: Fixed TAC regardless of stock status
2. Constant F: Fixed fishing mortality rate
3. Hockey Stick: F varies with biomass thresholds
4. Climate-Adaptive: Adjusts F based on climate indicators
5. Precautionary: Includes uncertainty buffers
6. Multi-Objective: Balances biomass, catch, and profit
ECONOMIC MODEL
--------------
Tracks:
- Revenue and costs
- Profit and NPV
- Fleet dynamics (entry/exit)
- Employment
HOW TO USE
----------
1. Set biological parameters in the Biological tab
2. Choose climate scenario and parameters
3. Set economic parameters
4. Select HCR type and configure parameters
5. Click "Run Simulation"
6. Explore results in different visualization tabs
7. Use "Compare HCRs" to evaluate different strategies
INDICATORS
----------
- B/B_MSY: Biomass relative to maximum sustainable yield
- F/F_MSY: Fishing mortality relative to F_MSY
- Kobe Plot: Shows stock status over time
- NPV: Net present value of the fishery
For more information, refer to the source code documentation.
"""
text.insert(tk.END, documentation)
text.config(state=tk.DISABLED)
# =============================================================================
# Main Entry Point
# =============================================================================
def main():
"""Main entry point"""
root = tk.Tk()
# Set style
style = ttk.Style()
style.theme_use('clam')
app = FisheriesSimulatorGUI(root)
root.mainloop()
if __name__ == "__main__":
main()