naohiro701 commited on
Commit
d00a54b
·
verified ·
1 Parent(s): 1dd074a

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +53 -155
app.py CHANGED
@@ -27,34 +27,22 @@ def get_renewable_energy_data(city_code):
27
  return result_df, None
28
 
29
  # Optimize energy system and use MGA
30
- def optimize_energy_system(data, technologies, solar_cost, onshore_wind_cost, offshore_wind_cost, river_cost, battery_cost, yearly_demand, solar_range, wind_range, river_range, offshore_wind_range, thresholds, selected_tech):
31
  for col in data.columns[1:]:
32
  data[col] = pd.to_numeric(data[col], errors='coerce')
33
  data = data.fillna(0)
34
 
35
  time_steps = range(len(data['Time']))
36
- solar_cf = data['solar hourly capacity factor']
37
- onshore_wind_cf = data['onshore_wind hourly capacity factor']
38
- offshore_wind_cf = data['offshore_wind hourly capacity factor']
39
- river_cf = data['river hourly capacity factor']
40
  demand_cf = data['demand hourly capacity factor']
41
-
42
- demand = demand_cf * yearly_demand * 1e6 / demand_cf.sum() # MW
43
 
44
  regions = ['region1']
45
- capacity_factor = {
46
- 'solar': solar_cf,
47
- 'onshore_wind': onshore_wind_cf,
48
- 'offshore_wind': offshore_wind_cf,
49
- 'river': river_cf
50
- }
51
 
52
- renewable_capacity_cost = {'solar': solar_cost, 'onshore_wind': onshore_wind_cost, 'offshore_wind': offshore_wind_cost, 'river': river_cost}
53
- battery_cost_per_mwh = battery_cost
54
  battery_efficiency = 0.9
55
 
56
  # Create the model
57
- model = pulp.LpProblem("EnergySystemOptimizationWithBattery", pulp.LpMinimize)
58
 
59
  # Variables
60
  renewable_capacity = pulp.LpVariable.dicts("renewable_capacity",
@@ -73,8 +61,8 @@ def optimize_energy_system(data, technologies, solar_cost, onshore_wind_cost, of
73
  time_steps, lowBound=0, cat='Continuous')
74
 
75
  # Objective: minimize total cost
76
- model += pulp.lpSum([renewable_capacity[('region1', g)] * renewable_capacity_cost[g] for g in technologies]) + \
77
- battery_capacity * battery_cost_per_mwh, "TotalCost"
78
 
79
  # Constraints
80
 
@@ -98,17 +86,9 @@ def optimize_energy_system(data, technologies, solar_cost, onshore_wind_cost, of
98
  model += battery_storage[t] >= 0, f"StorageNonNegative_{t}"
99
 
100
  # Renewable capacity constraints (within specified ranges)
101
- model += renewable_capacity[('region1', 'solar')] >= solar_range[0], "SolarCapMin"
102
- model += renewable_capacity[('region1', 'solar')] <= solar_range[1], "SolarCapMax"
103
-
104
- model += renewable_capacity[('region1', 'onshore_wind')] >= wind_range[0], "WindCapMin"
105
- model += renewable_capacity[('region1', 'onshore_wind')] <= wind_range[1], "WindCapMax"
106
-
107
- model += renewable_capacity[('region1', 'offshore_wind')] >= offshore_wind_range[0], "OffshoreWindCapMin"
108
- model += renewable_capacity[('region1', 'offshore_wind')] <= offshore_wind_range[1], "OffshoreWindCapMax"
109
-
110
- model += renewable_capacity[('region1', 'river')] >= river_range[0], "RiverCapMin"
111
- model += renewable_capacity[('region1', 'river')] <= river_range[1], "RiverCapMax"
112
 
113
  # Solve the initial model to find the optimal solution
114
  model.solve()
@@ -155,8 +135,8 @@ def optimize_energy_system(data, technologies, solar_cost, onshore_wind_cost, of
155
  alt_model += -alt_renewable_capacity[('region1', tech)], f"Maximize_{tech}_Capacity"
156
 
157
  # Add the cost constraint
158
- alt_model += pulp.lpSum([alt_renewable_capacity[('region1', g)] * renewable_capacity_cost[g] for g in technologies]) + \
159
- alt_battery_capacity * battery_cost_per_mwh <= relaxed_cost, "CostConstraint"
160
 
161
  # Constraints
162
 
@@ -180,17 +160,9 @@ def optimize_energy_system(data, technologies, solar_cost, onshore_wind_cost, of
180
  alt_model += alt_battery_storage[t] >= 0, f"StorageNonNegative_{t}"
181
 
182
  # Renewable capacity constraints (within specified ranges)
183
- alt_model += alt_renewable_capacity[('region1', 'solar')] >= solar_range[0], "SolarCapMin"
184
- alt_model += alt_renewable_capacity[('region1', 'solar')] <= solar_range[1], "SolarCapMax"
185
-
186
- alt_model += alt_renewable_capacity[('region1', 'onshore_wind')] >= wind_range[0], "WindCapMin"
187
- alt_model += alt_renewable_capacity[('region1', 'onshore_wind')] <= wind_range[1], "WindCapMax"
188
-
189
- alt_model += alt_renewable_capacity[('region1', 'offshore_wind')] >= offshore_wind_range[0], "OffshoreWindCapMin"
190
- alt_model += alt_renewable_capacity[('region1', 'offshore_wind')] <= offshore_wind_range[1], "OffshoreWindCapMax"
191
-
192
- alt_model += alt_renewable_capacity[('region1', 'river')] >= river_range[0], "RiverCapMin"
193
- alt_model += alt_renewable_capacity[('region1', 'river')] <= river_range[1], "RiverCapMax"
194
 
195
  # Solve the alternative model
196
  alt_model.solve()
@@ -207,103 +179,37 @@ def optimize_energy_system(data, technologies, solar_cost, onshore_wind_cost, of
207
 
208
  return alternative_solutions
209
 
210
- # Violin plot for each technology’s capacity distribution across alternative solutions
211
- def plot_capacity_distribution(alternative_solutions, selected_technologies):
212
- # Collect capacity data for each technology at each threshold level
213
- capacity_data = []
214
- for sol in alternative_solutions:
215
- for tech in selected_technologies:
216
- capacity_data.append({
217
- 'Threshold (%)': sol['threshold'] * 100,
218
- 'Technology': tech,
219
- 'Capacity (MW)': sol['solution'][tech],
220
- 'Type': sol['type'],
221
- 'Varied Technology': sol['technology']
222
- })
223
-
224
- capacity_df = pd.DataFrame(capacity_data)
225
-
226
- # Create line plot to show capacity changes over thresholds
227
- fig_line = px.line(capacity_df, x="Threshold (%)", y="Capacity (MW)", color="Technology",
228
- line_dash="Varied Technology", markers=True,
229
- title="Technology Capacity Changes Over Thresholds")
230
- st.plotly_chart(fig_line, use_container_width=True)
231
-
232
- # Function to create cost breakdown stacked bar plot for each threshold and technology type
233
- def plot_cost_breakdown(alternative_solutions, selected_technologies, renewable_capacity_cost, battery_cost_per_mwh):
234
- for idx, sol in enumerate(alternative_solutions):
235
- cost_data = {
236
- 'Technology': selected_technologies + ['Battery'],
237
- 'Cost': [sol['solution'][tech] * renewable_capacity_cost[tech] for tech in selected_technologies] + [sol['battery_capacity'] * battery_cost_per_mwh]
238
- }
239
- cost_df = pd.DataFrame(cost_data)
240
-
241
- # Create stacked bar chart with unique key to avoid StreamlitDuplicateElementId error
242
- fig_bar = px.bar(cost_df, x='Technology', y='Cost', title=f"Cost Breakdown (Threshold: {sol['threshold'] * 100}%, Technology Varied: {sol['technology']})",
243
- labels={'Cost': 'Cost (¥)'})
244
- st.plotly_chart(fig_bar, use_container_width=True, key=f"cost_plot_{idx}")
245
-
246
- # Function to plot generation and demand over time
247
- def plot_generation_demand(data, alternative_solution, time_steps, technologies):
248
- total_generation = np.zeros(len(time_steps))
249
- for g in technologies:
250
- gen = np.array(data[f'{g} hourly capacity factor']) * alternative_solution['solution'][g]
251
- total_generation += gen
252
- demand = data['demand hourly capacity factor'] * data['demand hourly capacity factor'].sum()
253
- fig = px.line(x=time_steps, y=[total_generation, demand],
254
- labels={'x': 'Time', 'value': 'Power (MW)', 'variable': 'Legend'},
255
- title='Total Generation and Demand Over Time')
256
- fig.update_traces(mode='lines')
257
- st.plotly_chart(fig, use_container_width=True)
258
-
259
- # Function to plot battery storage levels over time
260
- def plot_battery_storage(data, alternative_solution, time_steps):
261
- # For simplicity, re-calculate battery storage levels
262
- battery_storage = np.zeros(len(time_steps))
263
- battery_capacity = alternative_solution['battery_capacity']
264
- battery_charge = data['battery_charge'] if 'battery_charge' in data else np.zeros(len(time_steps))
265
- battery_discharge = data['battery_discharge'] if 'battery_discharge' in data else np.zeros(len(time_steps))
266
- battery_efficiency = 0.9
267
-
268
- for t in range(len(time_steps)):
269
- if t == 0:
270
- battery_storage[t] = battery_capacity * 0.5 + battery_charge[t] * battery_efficiency - battery_discharge[t] * (1 / battery_efficiency)
271
- else:
272
- battery_storage[t] = battery_storage[t - 1] + battery_charge[t] * battery_efficiency - battery_discharge[t] * (1 / battery_efficiency)
273
-
274
- fig = px.line(x=time_steps, y=battery_storage,
275
- labels={'x': 'Time', 'y': 'Battery Storage Level (MWh)'},
276
- title='Battery Storage Level Over Time')
277
- st.plotly_chart(fig, use_container_width=True)
278
 
279
  # Streamlit UI setup
280
  st.set_page_config(page_title='Renewable Energy System Optimization with MGA', layout='wide')
281
- st.title('Modeling to Generate Alternatives (MGA) in Renewable Energy System Optimization')
282
 
283
  # Sidebar Inputs
284
  with st.sidebar:
285
- st.header('Input Parameters')
286
- city_code = st.text_input("Enter City Code", value="999999")
287
- solar_cost = st.number_input("Solar Capacity Cost (¥/MW)", value=80.0)
288
- onshore_wind_cost = st.number_input("Onshore Wind Capacity Cost (¥/MW)", value=120.0)
289
- offshore_wind_cost = st.number_input("Offshore Wind Capacity Cost (¥/MW)", value=180.0)
290
- river_cost = st.number_input("River Capacity Cost (¥/MW)", value=1000.0)
291
- battery_cost = st.number_input("Battery Cost (¥/MWh)", value=80.0)
292
- yearly_demand = st.number_input("Yearly Power Demand (TWh/year)", value=15.0)
293
- solar_range = st.slider("Solar Capacity Range (MW)", 0, 10000, (0, 10000))
294
- wind_range = st.slider("Onshore Wind Capacity Range (MW)", 0, 10000, (0, 10000))
295
- offshore_wind_range = st.slider("Offshore Wind Capacity Range (MW)", 0, 10000, (0, 10000))
296
- river_range = st.slider("River Capacity Range (MW)", 0, 10000, (0, 10000))
297
  threshold_options = list(np.arange(0, 11, 0.5))
298
  threshold_default = [0, 5, 10]
299
  thresholds = st.multiselect(
300
- "Select MGA Cost Deviation Thresholds (%)",
301
  threshold_options,
302
  default=threshold_default
303
  )
304
- selected_technologies = st.multiselect("Select Technologies to Optimize", ['solar', 'onshore_wind', 'offshore_wind', 'river'], default=['solar'])
305
 
306
- if st.button("Run MGA Optimization"):
307
  thresholds = [t / 100 for t in thresholds] # Convert percentages to decimals
308
 
309
  # Fetch data
@@ -315,36 +221,28 @@ if st.button("Run MGA Optimization"):
315
  # Define technologies
316
  technologies = ['solar', 'onshore_wind', 'offshore_wind', 'river']
317
 
318
- # Run optimization
319
- alternative_solutions = optimize_energy_system(data, technologies, solar_cost, onshore_wind_cost, offshore_wind_cost, river_cost, battery_cost, yearly_demand, solar_range, wind_range, river_range, offshore_wind_range, thresholds, selected_technologies)
320
-
321
- if alternative_solutions:
322
- # Display capacity distribution using line plots
323
- plot_capacity_distribution(alternative_solutions, technologies)
324
-
325
- # Display cost breakdown stacked bar plots for each case
326
- plot_cost_breakdown(alternative_solutions, technologies, {
327
  'solar': solar_cost,
328
  'onshore_wind': onshore_wind_cost,
329
  'offshore_wind': offshore_wind_cost,
330
  'river': river_cost
331
- }, battery_cost)
332
-
333
- # Plot generation and demand over time for the first alternative solution
334
- st.header("Generation and Demand Over Time")
335
- plot_generation_demand(data, alternative_solutions[0], data['Time'], technologies)
336
-
337
- # Plot battery storage levels over time
338
- st.header("Battery Storage Level Over Time")
339
- plot_battery_storage(data, alternative_solutions[0], data['Time'])
340
-
341
- # Display alternative solutions in a table
342
- st.header("Alternative Solutions Summary")
343
- summary_data = []
344
- for sol in alternative_solutions:
345
- row = {'Threshold (%)': sol['threshold'] * 100, 'Type': sol['type'], 'Varied Technology': sol['technology'], 'Battery Capacity (MWh)': sol['battery_capacity'], 'Total Cost (¥)': sol['total_cost']}
346
- for tech in technologies:
347
- row[f"{tech.capitalize()} Capacity (MW)"] = sol['solution'][tech]
348
- summary_data.append(row)
349
- summary_df = pd.DataFrame(summary_data)
350
- st.dataframe(summary_df)
 
27
  return result_df, None
28
 
29
  # Optimize energy system and use MGA
30
+ def optimize_energy_system(data, technologies, cost_params, demand_params, capacity_ranges, thresholds, selected_tech):
31
  for col in data.columns[1:]:
32
  data[col] = pd.to_numeric(data[col], errors='coerce')
33
  data = data.fillna(0)
34
 
35
  time_steps = range(len(data['Time']))
 
 
 
 
36
  demand_cf = data['demand hourly capacity factor']
37
+ demand = demand_cf * demand_params['yearly_demand'] * 1e6 / demand_cf.sum() # MW
 
38
 
39
  regions = ['region1']
40
+ capacity_factor = {tech: data[f'{tech} hourly capacity factor'] for tech in technologies}
 
 
 
 
 
41
 
 
 
42
  battery_efficiency = 0.9
43
 
44
  # Create the model
45
+ model = pulp.LpProblem("EnergySystemOptimizationWithMGA", pulp.LpMinimize)
46
 
47
  # Variables
48
  renewable_capacity = pulp.LpVariable.dicts("renewable_capacity",
 
61
  time_steps, lowBound=0, cat='Continuous')
62
 
63
  # Objective: minimize total cost
64
+ model += pulp.lpSum([renewable_capacity[('region1', g)] * cost_params['renewable_capacity_cost'][g] for g in technologies]) + \
65
+ battery_capacity * cost_params['battery_cost_per_mwh'], "TotalCost"
66
 
67
  # Constraints
68
 
 
86
  model += battery_storage[t] >= 0, f"StorageNonNegative_{t}"
87
 
88
  # Renewable capacity constraints (within specified ranges)
89
+ for g in technologies:
90
+ model += renewable_capacity[('region1', g)] >= capacity_ranges[g][0], f"{g.capitalize()}CapMin"
91
+ model += renewable_capacity[('region1', g)] <= capacity_ranges[g][1], f"{g.capitalize()}CapMax"
 
 
 
 
 
 
 
 
92
 
93
  # Solve the initial model to find the optimal solution
94
  model.solve()
 
135
  alt_model += -alt_renewable_capacity[('region1', tech)], f"Maximize_{tech}_Capacity"
136
 
137
  # Add the cost constraint
138
+ alt_model += pulp.lpSum([alt_renewable_capacity[('region1', g)] * cost_params['renewable_capacity_cost'][g] for g in technologies]) + \
139
+ alt_battery_capacity * cost_params['battery_cost_per_mwh'] <= relaxed_cost, "CostConstraint"
140
 
141
  # Constraints
142
 
 
160
  alt_model += alt_battery_storage[t] >= 0, f"StorageNonNegative_{t}"
161
 
162
  # Renewable capacity constraints (within specified ranges)
163
+ for g in technologies:
164
+ alt_model += alt_renewable_capacity[('region1', g)] >= capacity_ranges[g][0], f"{g.capitalize()}CapMin"
165
+ alt_model += alt_renewable_capacity[('region1', g)] <= capacity_ranges[g][1], f"{g.capitalize()}CapMax"
 
 
 
 
 
 
 
 
166
 
167
  # Solve the alternative model
168
  alt_model.solve()
 
179
 
180
  return alternative_solutions
181
 
182
+ # Additional plotting functions and analysis code...
183
+ # (ここに追加のプロット関数と分析コードを挿入します)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
184
 
185
  # Streamlit UI setup
186
  st.set_page_config(page_title='Renewable Energy System Optimization with MGA', layout='wide')
187
+ st.title('再生可能エネルギーシステム最適化におけるMGA手法の活用')
188
 
189
  # Sidebar Inputs
190
  with st.sidebar:
191
+ st.header('入力パラメータ')
192
+ city_code = st.text_input("市区町村コードを入力してください", value="999999")
193
+ solar_cost = st.number_input("太陽光の設備コスト (¥/MW)", value=80.0)
194
+ onshore_wind_cost = st.number_input("陸上風力の設備コスト (¥/MW)", value=120.0)
195
+ offshore_wind_cost = st.number_input("洋上風力の設備コスト (¥/MW)", value=180.0)
196
+ river_cost = st.number_input("水力の設備コスト (¥/MW)", value=1000.0)
197
+ battery_cost = st.number_input("バッテリーコスト (¥/MWh)", value=80.0)
198
+ yearly_demand = st.number_input("年間電力需要 (TWh/年)", value=15.0)
199
+ solar_range = st.slider("太陽光の設備容量範囲 (MW)", 0, 10000, (0, 10000))
200
+ wind_range = st.slider("陸上風力の設備容量範囲 (MW)", 0, 10000, (0, 10000))
201
+ offshore_wind_range = st.slider("洋上風力の設備容量範囲 (MW)", 0, 10000, (0, 10000))
202
+ river_range = st.slider("水力の設備容量範囲 (MW)", 0, 10000, (0, 10000))
203
  threshold_options = list(np.arange(0, 11, 0.5))
204
  threshold_default = [0, 5, 10]
205
  thresholds = st.multiselect(
206
+ "MGAのコスト逸脱閾値を選択してください (%)",
207
  threshold_options,
208
  default=threshold_default
209
  )
210
+ selected_technologies = st.multiselect("感度解析を行う技術を選択してください", ['solar', 'onshore_wind', 'offshore_wind', 'river'], default=['solar'])
211
 
212
+ if st.button("MGA最適化を実行"):
213
  thresholds = [t / 100 for t in thresholds] # Convert percentages to decimals
214
 
215
  # Fetch data
 
221
  # Define technologies
222
  technologies = ['solar', 'onshore_wind', 'offshore_wind', 'river']
223
 
224
+ # Parameters
225
+ cost_params = {
226
+ 'renewable_capacity_cost': {
 
 
 
 
 
 
227
  'solar': solar_cost,
228
  'onshore_wind': onshore_wind_cost,
229
  'offshore_wind': offshore_wind_cost,
230
  'river': river_cost
231
+ },
232
+ 'battery_cost_per_mwh': battery_cost
233
+ }
234
+ demand_params = {'yearly_demand': yearly_demand}
235
+ capacity_ranges = {
236
+ 'solar': solar_range,
237
+ 'onshore_wind': wind_range,
238
+ 'offshore_wind': offshore_wind_range,
239
+ 'river': river_range
240
+ }
241
+
242
+ # Run optimization
243
+ alternative_solutions = optimize_energy_system(data, technologies, cost_params, demand_params, capacity_ranges, thresholds, selected_technologies)
244
+
245
+ if alternative_solutions:
246
+ # Additional analysis and plotting
247
+ # (ここに追加の分析とプロットのコードを挿入します)
248
+ pass