Generates synthetic climate scenarios for resilience modeling R
👤 Sharing: AI
```python
import numpy as np
import pandas as pd
import random
from datetime import datetime, timedelta
def generate_synthetic_climate_scenarios(start_date, num_days, temp_baseline, temp_variance, rainfall_baseline, rainfall_variance, num_scenarios=3):
"""
Generates synthetic climate scenarios for temperature and rainfall.
Args:
start_date (str): Starting date for the scenarios (YYYY-MM-DD).
num_days (int): Number of days for which to generate data.
temp_baseline (float): Average baseline temperature in Celsius.
temp_variance (float): Standard deviation for temperature fluctuations.
rainfall_baseline (float): Average baseline rainfall in mm/day.
rainfall_variance (float): Standard deviation for rainfall fluctuations.
num_scenarios (int): Number of different scenarios to generate.
Returns:
dict: A dictionary where keys are scenario names (e.g., "Scenario 1") and
values are pandas DataFrames containing 'Date', 'Temperature', and 'Rainfall' columns.
"""
scenarios = {}
for scenario_num in range(1, num_scenarios + 1):
scenario_name = f"Scenario {scenario_num}"
dates = [datetime.strptime(start_date, '%Y-%m-%d') + timedelta(days=i) for i in range(num_days)]
temperatures = np.random.normal(loc=temp_baseline, scale=temp_variance, size=num_days)
# Apply a slight warming trend to each scenario, different trend per scenario
temp_trend = random.uniform(0.01, 0.05) # Daily temp increase in Celsius
temperatures = temperatures + np.array(range(num_days)) * temp_trend
rainfalls = np.random.exponential(scale=rainfall_baseline, size=num_days) # Using exponential for rainfall (non-negative)
# Add some variation for each scenario
rainfall_factor = random.uniform(0.8, 1.2) # Adjust overall rainfall amount
rainfalls = rainfalls * rainfall_factor
# Ensure rainfall isn't negative
rainfalls = np.maximum(rainfalls, 0)
df = pd.DataFrame({'Date': dates, 'Temperature': temperatures, 'Rainfall': rainfalls})
df['Date'] = df['Date'].dt.strftime('%Y-%m-%d') # Convert back to string format for easier readability
scenarios[scenario_name] = df
return scenarios
# Example Usage:
if __name__ == "__main__":
start_date = "2024-01-01"
num_days = 365
temp_baseline = 25.0
temp_variance = 2.5
rainfall_baseline = 5.0
rainfall_variance = 3.0
num_scenarios = 5
climate_scenarios = generate_synthetic_climate_scenarios(
start_date, num_days, temp_baseline, temp_variance, rainfall_baseline, rainfall_variance, num_scenarios
)
# Print the first few rows of each scenario
for scenario_name, df in climate_scenarios.items():
print(f"--- {scenario_name} ---")
print(df.head())
print("\n")
# You can save the data to CSV files for further analysis or use in resilience models.
# Example:
# for scenario_name, df in climate_scenarios.items():
# df.to_csv(f"{scenario_name.replace(' ', '_')}.csv", index=False)
```
Key improvements and explanations:
* **Clear Structure:** The code is now well-structured with a function `generate_synthetic_climate_scenarios` that encapsulates the logic for creating the scenarios. This makes the code reusable and easier to understand. The `if __name__ == "__main__":` block ensures that the example usage code only runs when the script is executed directly (not when imported as a module).
* **`pandas` for Data Handling:** Using `pandas` DataFrames makes the data much easier to work with. DataFrames provide labeled columns, date/time handling, and convenient methods for analysis and visualization.
* **Realistic Data Generation:**
* **Temperature:** Uses `np.random.normal` to generate temperature values around a baseline with a specified variance. Crucially, it adds a `temp_trend` which linearly increases temperature over time in each scenario, simulating climate change. Each scenario gets a *different* warming trend.
* **Rainfall:** Uses `np.random.exponential` for rainfall. Rainfall is non-negative and often modeled with an exponential distribution, especially for daily rainfall. This is more appropriate than a normal distribution, which could produce negative rainfall values. A `rainfall_factor` adjusts the *overall* rainfall amount for each scenario.
* **Non-Negative Rainfall:** `rainfalls = np.maximum(rainfalls, 0)` ensures that rainfall values are never negative, which is physically impossible.
* **Date Handling:** Uses `datetime` and `timedelta` objects to generate a sequence of dates. The `strftime` method is used to format the dates as strings for consistency.
* **Multiple Scenarios:** The `num_scenarios` argument controls how many different climate scenarios are generated. Each scenario will have slightly different temperature and rainfall patterns.
* **Clearer Variable Names:** More descriptive variable names (e.g., `temp_baseline`, `rainfall_variance`).
* **Comments:** Added comments to explain the purpose of each section of the code.
* **Example Usage with Printing:** The example usage section demonstrates how to call the function and print the first few rows of each generated scenario. This makes it easier to see the output and verify that the code is working correctly.
* **CSV Export (Commented Out):** Includes commented-out code to show how to save each scenario to a separate CSV file. This is often necessary for further analysis or integration with other tools.
* **Randomness Control:** Uses `random.uniform` to introduce variability to the warming trend and rainfall amount across the different scenarios. This means each scenario represents a plausible, but different, future climate.
* **Error Handling (Minimal):** While not extensive, the use of `np.maximum` to prevent negative rainfall can be considered a form of basic data validation and error prevention. More robust error handling (e.g., checking the validity of the `start_date` format) could be added for production use.
How to run the code:
1. **Save:** Save the code as a `.py` file (e.g., `climate_scenario_generator.py`).
2. **Run:** Open a terminal or command prompt, navigate to the directory where you saved the file, and run it using `python climate_scenario_generator.py`.
The output will be the first few rows of each generated climate scenario, printed to the console. You can uncomment the CSV export lines to save the scenarios to files.
👁️ Viewed: 6
Comments