naohiro701 commited on
Commit
4d2e66e
·
verified ·
1 Parent(s): e77da74

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +195 -0
app.py CHANGED
@@ -0,0 +1,195 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import streamlit as st
2
+ import requests
3
+ import pandas as pd
4
+ from io import StringIO
5
+ import pulp
6
+ import plotly.graph_objs as go
7
+ from plotly.subplots import make_subplots
8
+
9
+ # Function to fetch renewable energy data
10
+ def get_renewable_energy_data(city_code):
11
+ """
12
+ Fetch renewable energy data from an external source based on a city code.
13
+
14
+ Args:
15
+ - city_code (str): The code representing the city for which the renewable energy data is to be fetched.
16
+ Returns:
17
+ - result_df (DataFrame): A DataFrame containing the energy data with time and capacity factors for each energy type.
18
+ - error (str): Error message if the data fetching fails.
19
+ """
20
+ url = f"https://energy-sustainability.jp/_ajax/renewable_energy/get/?code={city_code}"
21
+ response = requests.get(url)
22
+ if response.status_code != 200:
23
+ return None, "データの取得に失敗しました。" # Data fetch failed.
24
+
25
+ data = response.json()
26
+ if not data:
27
+ return None, "データが見つかりませんでした。" # Data not found.
28
+
29
+ # Extract base times from the first energy type.
30
+ base_times = data[next(iter(data))]['x']
31
+ result_df = pd.DataFrame({"Time": base_times})
32
+
33
+ # Loop through each energy type and append hourly capacity factor data.
34
+ for energy_type, energy_data in data.items():
35
+ if 'x' in energy_data and 'y' in energy_data:
36
+ values = energy_data['y']
37
+ result_df[f"{energy_type} hourly capacity factor"] = values
38
+
39
+ return result_df, None
40
+
41
+ # Function to optimize the energy system
42
+ def optimize_energy_system(city_code, solar_cost, onshore_wind_cost, offshore_wind_cost, river_cost, battery_cost, yearly_demand):
43
+ """
44
+ Optimize the energy system using linear programming to minimize cost while meeting demand with renewable sources and batteries.
45
+
46
+ Args:
47
+ - city_code (str): The code of the city for which energy data is to be optimized.
48
+ - solar_cost (float): The cost of solar capacity per MW.
49
+ - onshore_wind_cost (float): The cost of onshore wind capacity per MW.
50
+ - offshore_wind_cost (float): The cost of offshore wind capacity per MW.
51
+ - river_cost (float): The cost of river (hydro) capacity per MW.
52
+ - battery_cost (float): The cost of battery capacity per MWh.
53
+ - yearly_demand (float): The total yearly demand in TWh/year.
54
+ Returns:
55
+ - fig (Figure): A plotly figure showing the optimized energy dispatch and state of charge (SOC) over time.
56
+ """
57
+ data, error = get_renewable_energy_data(city_code)
58
+ if error:
59
+ st.error(error)
60
+ return None
61
+
62
+ # Convert capacity factor columns to numeric values, handling any errors and filling missing data.
63
+ for col in data.columns[1:]:
64
+ data[col] = pd.to_numeric(data[col], errors='coerce')
65
+
66
+ data = data.fillna(0) # Fill missing values with zero.
67
+
68
+ # Extract necessary data for optimization.
69
+ time_steps = range(len(data['Time']))
70
+ solar_cf = data['solar hourly capacity factor']
71
+ onshore_wind_cf = data['onshore_wind hourly capacity factor']
72
+ offshore_wind_cf = data['offshore_wind hourly capacity factor']
73
+ river_cf = data['river hourly capacity factor']
74
+ demand_cf = data['demand hourly capacity factor']
75
+
76
+ # Define regions and technologies.
77
+ regions = ['region1']
78
+ technologies = ['solar', 'onshore_wind', 'offshore_wind', 'river']
79
+ capacity_factor = {
80
+ 'solar': solar_cf,
81
+ 'onshore_wind': onshore_wind_cf,
82
+ 'offshore_wind': offshore_wind_cf,
83
+ 'river': river_cf
84
+ }
85
+
86
+ # Cost definitions for renewable capacity and battery.
87
+ renewable_capacity_cost = {'solar': solar_cost, 'onshore_wind': onshore_wind_cost, 'offshore_wind': offshore_wind_cost, 'river': river_cost}
88
+ battery_cost_per_mwh = battery_cost
89
+ battery_efficiency = 0.9 # Battery efficiency.
90
+
91
+ # Scale demand from capacity factor and yearly demand in TWh/year to hourly demand in MW.
92
+ demand = demand_cf * yearly_demand / 100 * 1000 * 1000
93
+
94
+ # Define LP variables for renewable capacities, curtailment, battery capacity, charge, discharge, and state of charge (SOC).
95
+ renewable_capacity = pulp.LpVariable.dicts("renewable_capacity",
96
+ [(r, g) for r in regions for g in technologies],
97
+ lowBound=0, cat='Continuous')
98
+ curtailment = pulp.LpVariable.dicts("curtailment",
99
+ [(r, t) for r in regions for t in time_steps],
100
+ lowBound=0, cat='Continuous')
101
+ battery_capacity = pulp.LpVariable("battery_capacity", lowBound=0, cat='Continuous')
102
+ battery_charge = pulp.LpVariable.dicts("battery_charge", time_steps, lowBound=0, cat='Continuous')
103
+ battery_discharge = pulp.LpVariable.dicts("battery_discharge", time_steps, lowBound=0, cat='Continuous')
104
+ SOC = pulp.LpVariable.dicts("SOC", time_steps, lowBound=0, cat='Continuous')
105
+
106
+ # Define the optimization problem: minimize the total system cost.
107
+ model = pulp.LpProblem("EnergySystemOptimizationWithBattery", pulp.LpMinimize)
108
+
109
+ model += pulp.lpSum([renewable_capacity[(r, g)] * renewable_capacity_cost[g]
110
+ for r in regions for g in technologies]) + \
111
+ battery_capacity * battery_cost_per_mwh, "TotalCost"
112
+
113
+ # Constraints to meet demand, manage curtailment, and update state of charge for the battery.
114
+ for r in regions:
115
+ for t in time_steps:
116
+ model += pulp.lpSum([renewable_capacity[(r, g)] * capacity_factor[g][t]
117
+ for g in technologies]) + battery_discharge[t] == demand[t] + battery_charge[t] + curtailment[(r,t)], f"DemandConstraint_{r}_{t}"
118
+
119
+ if t == 0:
120
+ model += SOC[t] == battery_charge[t] * battery_efficiency - battery_discharge[t] * (1 / battery_efficiency), f"SOCUpdate_{t}"
121
+ else:
122
+ model += SOC[t] == SOC[t-1] + battery_charge[t] * battery_efficiency - battery_discharge[t] * (1 / battery_efficiency), f"SOCUpdate_{t}"
123
+
124
+ model += SOC[t] <= battery_capacity, f"SOCUpperBound_{t}"
125
+
126
+ # Solve the optimization model.
127
+ model.solve()
128
+
129
+ # Extract optimized supply and battery values.
130
+ supply_solar = solar_cf * renewable_capacity[('region1', 'solar')].varValue
131
+ supply_onshore_wind = onshore_wind_cf * renewable_capacity[('region1', 'onshore_wind')].varValue
132
+ supply_offshore_wind = offshore_wind_cf * renewable_capacity[('region1', 'offshore_wind')].varValue
133
+ supply_river = river_cf * renewable_capacity[('region1', 'river')].varValue
134
+
135
+ battery_discharge_values = [battery_discharge[t].varValue for t in time_steps]
136
+ battery_charge_values = [-battery_charge[t].varValue for t in time_steps]
137
+ SOC_values = [SOC[t].varValue for t in time_steps]
138
+
139
+ # Normalize state of charge (SOC) to a percentage.
140
+ max_SOC = max(SOC_values)
141
+ SOC_normalized = [(soc / max_SOC) * 100 for soc in SOC_values] if max_SOC > 0 else [0] * len(SOC_values)
142
+
143
+ # Create a subplot with 2 rows for energy dispatch and state of charge (SOC).
144
+ fig = make_subplots(rows=2, cols=1, shared_xaxes=True, vertical_spacing=0.1,
145
+ subplot_titles=("Power supply and demand", "State of charge (Battery)"))
146
+
147
+ # Plot energy dispatch in the first row.
148
+ fig.add_trace(go.Scatter(x=data['Time'], y=supply_solar, mode='lines', stackgroup='one', name='Solar', line=dict(color='#FFD700', width=0)), row=1, col=1) # Solar: Gold
149
+ fig.add_trace(go.Scatter(x=data['Time'], y=supply_onshore_wind, mode='lines', stackgroup='one', name='Onshore Wind', line=dict(color='#1F78B4', width=0)), row=1, col=1) # Onshore Wind: Blue
150
+ fig.add_trace(go.Scatter(x=data['Time'], y=supply_offshore_wind, mode='lines', stackgroup='one', name='Offshore Wind', line=dict(color='#66C2A5', width=0)), row=1, col=1) # Offshore Wind: Light Green
151
+ fig.add_trace(go.Scatter(x=data['Time'], y=supply_river, mode='lines', stackgroup='one', name='Run of River', line=dict(color='#FF7F00', width=0)), row=1, col=1) # Run of River: Orange
152
+ fig.add_trace(go.Scatter(x=data['Time'], y=battery_discharge_values, mode='lines', stackgroup='one', name='Battery Discharge', fill='tonexty', line=dict(color='#6A3D9A', width=0)), row=1, col=1) # Battery Discharge: Brown
153
+ fig.add_trace(go.Scatter(x=data['Time'], y=battery_charge_values, mode='lines', stackgroup='two', name='Battery Charge', fill='tonexty', line=dict(color='#6A3D9A', width=0)), row=1, col=1) # Battery Charge: Purple
154
+ fig.add_trace(go.Scatter(x=data['Time'], y=-demand, mode='lines', stackgroup='two', name='Demand', line=dict(color='black', width=0)), row=1, col=1) # Demand: Black
155
+
156
+ # Plot state of charge (SOC) in the second row, normalized to 100%.
157
+ fig.add_trace(go.Scatter(x=data['Time'], y=SOC_normalized, mode='lines', name='State of Charge (SOC) - Normalized', line=dict(color='black')), row=2, col=1)
158
+
159
+ # Layout settings for the figure.
160
+ fig.update_layout(
161
+ title_text='Optimized result',
162
+ title_x=0.5,
163
+ yaxis_title='Power dispatch (MW)',
164
+ legend_title='Source',
165
+ font=dict(size=12),
166
+ margin=dict(l=40, r=40, t=40, b=40),
167
+ hovermode='x unified',
168
+ plot_bgcolor='white',
169
+ xaxis=dict(showgrid=True, gridwidth=0.5, gridcolor='lightgray'),
170
+ yaxis=dict(showgrid=True, gridwidth=0.5, gridcolor='lightgray')
171
+ )
172
+ # Update the y-axis title for the second row.
173
+ fig.update_yaxes(title_text="State of Charge (%)", row=2, col=1)
174
+
175
+ return fig
176
+
177
+ # Streamlit UI for the application
178
+ st.title('Renewable Energy System Optimization')
179
+
180
+ # Input fields for the user
181
+ city_code = st.text_input("Enter City Code", value="")
182
+ solar_cost = st.number_input("Solar Capacity Cost (¥/MW)", value=100.0)
183
+ onshore_wind_cost = st.number_input("Onshore Wind Capacity Cost (¥/MW)", value=150.0)
184
+ offshore_wind_cost = st.number_input("Offshore Wind Capacity Cost (¥/MW)", value=200.0)
185
+ river_cost = st.number_input("River Capacity Cost (¥/MW)", value=120.0)
186
+ battery_cost = st.number_input("Battery Cost (¥/MWh)", value=100.0)
187
+ yearly_demand = st.number_input("Yearly Power Demand (TWh/year)", value=10.0)
188
+
189
+ # Button to trigger optimization
190
+ if st.button('Calculate'):
191
+ fig = optimize_energy_system(city_code, solar_cost, onshore_wind_cost, offshore_wind_cost, river_cost, battery_cost, yearly_demand)
192
+ if fig:
193
+ st.plotly_chart(fig)
194
+
195
+ # Note: You may need to adjust initial values or labels to fit your requirements.