Update app.py
Browse files
app.py
CHANGED
|
@@ -33,7 +33,7 @@ def optimize_energy_system(city_code, solar_cost, onshore_wind_cost, offshore_wi
|
|
| 33 |
data, error = get_renewable_energy_data(city_code)
|
| 34 |
if error:
|
| 35 |
st.error(error)
|
| 36 |
-
return None
|
| 37 |
|
| 38 |
for col in data.columns[1:]:
|
| 39 |
data[col] = pd.to_numeric(data[col], errors='coerce')
|
|
@@ -105,7 +105,6 @@ def optimize_energy_system(city_code, solar_cost, onshore_wind_cost, offshore_wi
|
|
| 105 |
optimal_cost = pulp.value(model.objective)
|
| 106 |
|
| 107 |
# MGA: Generate alternative solutions for selected technologies only
|
| 108 |
-
mga_models = []
|
| 109 |
alternative_solutions = []
|
| 110 |
for threshold in thresholds:
|
| 111 |
relaxed_cost = optimal_cost * (1 + threshold)
|
|
@@ -156,6 +155,27 @@ def optimize_energy_system(city_code, solar_cost, onshore_wind_cost, offshore_wi
|
|
| 156 |
|
| 157 |
return alternative_solutions
|
| 158 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 159 |
# Streamlit UI setup
|
| 160 |
st.set_page_config(page_title='Renewable Energy System Optimization with MGA', layout='wide')
|
| 161 |
st.title('Modeling to Generate Alternatives (MGA) in Renewable Energy System Optimization')
|
|
@@ -174,153 +194,24 @@ with st.sidebar:
|
|
| 174 |
wind_range = st.slider("Onshore Wind Capacity Range (MW)", 0, 10000, (0, 10000))
|
| 175 |
offshore_wind_range = st.slider("Offshore Wind Capacity Range (MW)", 0, 10000, (0, 10000))
|
| 176 |
river_range = st.slider("River Capacity Range (MW)", 0, 10000, (0, 10000))
|
| 177 |
-
# 0.1の刻みで0から1までの値を生成し、小数点以下3桁に丸める
|
| 178 |
thresholds = st.multiselect(
|
| 179 |
"Select MGA Cost Deviation Thresholds (%)",
|
| 180 |
list(np.arange(0, 11, 0.5)),
|
| 181 |
default=[0, 5, 10]
|
| 182 |
)
|
| 183 |
-
# 技術の選択オプション
|
| 184 |
selected_technologies = st.multiselect("Select Technologies to Optimize", ['solar', 'onshore_wind', 'offshore_wind', 'river'], default=['solar', 'onshore_wind', 'offshore_wind', 'river'])
|
| 185 |
|
| 186 |
if st.button("Run MGA Optimization"):
|
| 187 |
-
# 実行して alternative_solutions を取得
|
| 188 |
alternative_solutions = optimize_energy_system(city_code, solar_cost, onshore_wind_cost, offshore_wind_cost, river_cost, battery_cost, yearly_demand, solar_range, wind_range, river_range, offshore_wind_range, [t / 100 for t in thresholds], selected_technologies)
|
| 189 |
|
| 190 |
if alternative_solutions:
|
| 191 |
-
#
|
| 192 |
-
cost_data = []
|
| 193 |
-
for sol in alternative_solutions:
|
| 194 |
-
cost_data.append({
|
| 195 |
-
'threshold': sol['threshold'] * 100,
|
| 196 |
-
'type': sol['type'],
|
| 197 |
-
'technology': sol['technology'],
|
| 198 |
-
'total_cost': sol['total_cost']
|
| 199 |
-
})
|
| 200 |
-
|
| 201 |
-
# コスト積み上げグラフのプロット
|
| 202 |
cost_df = pd.DataFrame(cost_data)
|
| 203 |
fig_cost = px.bar(cost_df, x='threshold', y='total_cost', color='technology', title="Cost Breakdown by Technology and Threshold")
|
| 204 |
fig_cost.update_layout(xaxis_title='Threshold (%)', yaxis_title='Total Cost (¥)')
|
| 205 |
-
|
| 206 |
-
# Streamlitでコスト積み上げグラフを表示
|
| 207 |
st.plotly_chart(fig_cost, use_container_width=True)
|
| 208 |
|
| 209 |
-
#
|
| 210 |
-
|
| 211 |
-
|
| 212 |
-
'onshore_wind': 'skyblue',
|
| 213 |
-
'offshore_wind': 'lightgreen',
|
| 214 |
-
'river': 'salmon'
|
| 215 |
-
}
|
| 216 |
-
|
| 217 |
-
# 各技術の容量範囲を個別のグラフで表示
|
| 218 |
-
epsilon_values = sorted(list(set(sol['threshold'] * 100 for sol in alternative_solutions)))
|
| 219 |
-
|
| 220 |
-
for tech in selected_technologies:
|
| 221 |
-
storage_min = []
|
| 222 |
-
storage_max = []
|
| 223 |
-
for epsilon in epsilon_values:
|
| 224 |
-
capacities = [sol['solution'][tech] for sol in alternative_solutions if sol['technology'] == tech and sol['threshold'] * 100 == epsilon]
|
| 225 |
-
storage_min.append(min(capacities))
|
| 226 |
-
storage_max.append(max(capacities))
|
| 227 |
-
|
| 228 |
-
# 各技術ごとにグラフ作成
|
| 229 |
-
fig, ax = plt.subplots()
|
| 230 |
-
ax.fill_between(epsilon_values, storage_min, storage_max, color=colors[tech], alpha=0.3, label=f"{tech} range")
|
| 231 |
-
ax.plot(epsilon_values, storage_min, marker='o', color=colors[tech], linestyle='-', linewidth=1.5, label=f"{tech} Min")
|
| 232 |
-
ax.plot(epsilon_values, storage_max, marker='o', color=colors[tech], linestyle='-', linewidth=1.5, label=f"{tech} Max")
|
| 233 |
-
|
| 234 |
-
# ラベルとタイトル
|
| 235 |
-
ax.set_xlabel(r'$\epsilon$ [%]')
|
| 236 |
-
ax.set_ylabel(f'{tech.capitalize()} Capacity [GW]')
|
| 237 |
-
ax.set_title(f'Capacity Range for {tech.capitalize()}')
|
| 238 |
-
ax.legend()
|
| 239 |
-
ax.grid(True, linestyle='--', alpha=0.7)
|
| 240 |
-
|
| 241 |
-
# Streamlitに各技術のプロットを表示
|
| 242 |
-
st.pyplot(fig)
|
| 243 |
-
|
| 244 |
-
|
| 245 |
-
st.markdown("""
|
| 246 |
-
|
| 247 |
-
This application uses **Modeling to Generate Alternatives (MGA)** to explore near-optimal solutions in a renewable energy system model. MGA helps to identify alternative configurations that are close to the optimal solution but vary in their specific technological composition, providing flexibility for policy makers and stakeholders who might prioritize factors beyond cost minimization, such as social acceptance or regional preferences.
|
| 248 |
-
""")
|
| 249 |
-
|
| 250 |
-
st.write("## Objective Function and Cost Minimization")
|
| 251 |
-
st.markdown("""
|
| 252 |
-
In our renewable energy model, the **objective function** is to minimize the total annual cost of the system, which includes the costs of installing renewable generation capacities (such as solar, wind, and hydroelectric) and storage (batteries). The objective function is defined as:
|
| 253 |
-
""")
|
| 254 |
-
st.latex(r"""
|
| 255 |
-
\text{Minimize } \quad \sum_{r, g} \text{Cost}_{g} \times \text{Capacity}_{r, g} + \text{Battery Cost} \times \text{Battery Capacity}
|
| 256 |
-
""")
|
| 257 |
-
st.markdown("""
|
| 258 |
-
where:
|
| 259 |
-
- \( r \) represents the region (in this case, a single region),
|
| 260 |
-
- \( g \) represents the generation technology (solar, onshore wind, offshore wind, river),
|
| 261 |
-
- \( \text{Cost}_{g} \) is the per-MW cost of technology \( g \),
|
| 262 |
-
- \( \text{Capacity}_{r, g} \) is the installed capacity of technology \( g \) in region \( r \),
|
| 263 |
-
- \( \text{Battery Cost} \) represents the cost per MWh of battery storage,
|
| 264 |
-
- \( \text{Battery Capacity} \) is the total installed battery capacity.
|
| 265 |
-
""")
|
| 266 |
-
|
| 267 |
-
st.markdown("""
|
| 268 |
-
## What is MGA and Why is it Important?
|
| 269 |
-
|
| 270 |
-
Typically, optimization models produce a **single optimal solution** that minimizes the cost under a given set of constraints. However, in many real-world applications, there are **multiple near-optimal solutions** that achieve similar costs but vary in other characteristics. This diversity is valuable because:
|
| 271 |
-
- **Flexibility**: Different solutions might be preferable depending on policy objectives, geographic constraints, or social preferences.
|
| 272 |
-
- **Robustness**: Exploring near-optimal solutions reveals which elements (e.g., specific technologies or infrastructure investments) are consistently essential, regardless of slight variations in cost.
|
| 273 |
-
|
| 274 |
-
MGA addresses this need by generating **alternative solutions** that are close to the optimal cost but differ in technological composition.
|
| 275 |
-
""")
|
| 276 |
-
|
| 277 |
-
st.write("## How MGA Works: Adding a Cost Constraint")
|
| 278 |
-
st.markdown("""
|
| 279 |
-
To generate alternatives, MGA introduces a **cost tolerance** parameter \\( \\epsilon \\), which represents the acceptable increase in total cost relative to the optimal solution. The cost constraint for alternative solutions is expressed as:
|
| 280 |
-
""")
|
| 281 |
-
st.latex(r"""
|
| 282 |
-
\text{Total Cost} \leq (1 + \epsilon) \times \text{Optimal Cost}
|
| 283 |
-
""")
|
| 284 |
-
st.markdown("""
|
| 285 |
-
where:
|
| 286 |
-
- \\( \\epsilon \\) is the cost deviation percentage (e.g., if \\( \\epsilon = 0.05 \\), then the solution can be up to 5% more expensive than the optimal cost),
|
| 287 |
-
- \\( \\text{Optimal Cost} \\) is the minimum cost obtained from the initial optimization.
|
| 288 |
-
|
| 289 |
-
This constraint allows for flexibility in cost, enabling the exploration of solutions that are **near-optimal** but differ in terms of installed capacities for each technology.
|
| 290 |
-
""")
|
| 291 |
-
|
| 292 |
-
st.markdown("""
|
| 293 |
-
### MGA Process in This Application
|
| 294 |
-
|
| 295 |
-
1. **Initial Optimization**: First, we solve for the optimal solution to obtain the minimal total cost, referred to as \\( \\text{Optimal Cost} \\).
|
| 296 |
-
2. **Setting the Cost Threshold**: We introduce a range of \\( \\epsilon \\) values (0%, 5%, 10%, etc.) to explore how alternative solutions differ as we allow for higher costs.
|
| 297 |
-
3. **Minimizing and Maximizing Capacities**: For each selected technology (e.g., solar, wind, hydro), we attempt to:
|
| 298 |
-
- **Minimize the installed capacity** within the allowed cost threshold, identifying configurations with the lowest feasible capacity for that technology.
|
| 299 |
-
- **Maximize the installed capacity** under the same conditions, exploring configurations with higher reliance on that technology.
|
| 300 |
-
|
| 301 |
-
These steps generate a set of **alternative solutions** that are close in cost but vary significantly in their reliance on each technology, revealing **flexibility** and **trade-offs** in the renewable energy system configuration.
|
| 302 |
-
""")
|
| 303 |
-
|
| 304 |
-
st.write("## Interpreting the Cost Threshold (\\( \\epsilon \\))")
|
| 305 |
-
st.markdown("""
|
| 306 |
-
The cost threshold parameter \\( \\epsilon \\) is crucial in MGA, as it determines the range within which we consider solutions to be "near-optimal." For example:
|
| 307 |
-
- **\\( \\epsilon = 0 \\%**: Only the exact optimal solution is considered.
|
| 308 |
-
- **\\( \\epsilon = 5 \\%**: Solutions within 5% of the optimal cost are considered acceptable, allowing for slightly more flexibility in technology choice.
|
| 309 |
-
- **\\( \\epsilon = 10 \\%**: Solutions within 10% of the optimal cost are allowed, providing even greater flexibility.
|
| 310 |
-
|
| 311 |
-
By exploring a range of \\( \\epsilon \\) values, we can see how the system configuration changes as we relax the cost constraint, offering a broader view of feasible solutions.
|
| 312 |
-
""")
|
| 313 |
-
|
| 314 |
-
st.markdown("""
|
| 315 |
-
## Visualization of Results
|
| 316 |
-
|
| 317 |
-
- **Cost Breakdown**: The total cost of each solution, broken down by technology, helps us see the contribution of each technology to the total cost.
|
| 318 |
-
- **Capacity Ranges**: For each technology, we plot the minimum and maximum capacities across different \\( \\epsilon \\) values, showing the flexibility in system design as cost thresholds change.
|
| 319 |
-
|
| 320 |
-
This visualization provides insights into:
|
| 321 |
-
- Which technologies are essential (appear consistently in solutions across all \\( \\epsilon \\) values),
|
| 322 |
-
- Which technologies offer flexibility (capacities vary widely as \\( \\epsilon \\) increases),
|
| 323 |
-
- The cost impact of relying more or less on specific technologies.
|
| 324 |
-
|
| 325 |
-
Through MGA, we can make more **informed decisions** about the renewable energy mix and identify robust, flexible strategies that align with broader goals beyond cost minimization.
|
| 326 |
-
""")
|
|
|
|
| 33 |
data, error = get_renewable_energy_data(city_code)
|
| 34 |
if error:
|
| 35 |
st.error(error)
|
| 36 |
+
return None
|
| 37 |
|
| 38 |
for col in data.columns[1:]:
|
| 39 |
data[col] = pd.to_numeric(data[col], errors='coerce')
|
|
|
|
| 105 |
optimal_cost = pulp.value(model.objective)
|
| 106 |
|
| 107 |
# MGA: Generate alternative solutions for selected technologies only
|
|
|
|
| 108 |
alternative_solutions = []
|
| 109 |
for threshold in thresholds:
|
| 110 |
relaxed_cost = optimal_cost * (1 + threshold)
|
|
|
|
| 155 |
|
| 156 |
return alternative_solutions
|
| 157 |
|
| 158 |
+
# Violin plot for each technology’s capacity distribution across alternative solutions
|
| 159 |
+
def plot_capacity_distribution(alternative_solutions, selected_technologies):
|
| 160 |
+
# Collect capacity data for each technology at each threshold level
|
| 161 |
+
capacity_data = []
|
| 162 |
+
for sol in alternative_solutions:
|
| 163 |
+
for tech in selected_technologies:
|
| 164 |
+
capacity_data.append({
|
| 165 |
+
'Threshold (%)': sol['threshold'] * 100,
|
| 166 |
+
'Technology': tech,
|
| 167 |
+
'Capacity (MW)': sol['solution'][tech]
|
| 168 |
+
})
|
| 169 |
+
|
| 170 |
+
capacity_df = pd.DataFrame(capacity_data)
|
| 171 |
+
|
| 172 |
+
# Create violin plot with Plotly Express
|
| 173 |
+
fig_violin = px.violin(capacity_df, x="Threshold (%)", y="Capacity (MW)", color="Technology",
|
| 174 |
+
box=True, points="all", title="Capacity Distribution by Technology and Threshold")
|
| 175 |
+
fig_violin.update_layout(xaxis_title="Cost Deviation Threshold (%)", yaxis_title="Installed Capacity (MW)")
|
| 176 |
+
|
| 177 |
+
return fig_violin
|
| 178 |
+
|
| 179 |
# Streamlit UI setup
|
| 180 |
st.set_page_config(page_title='Renewable Energy System Optimization with MGA', layout='wide')
|
| 181 |
st.title('Modeling to Generate Alternatives (MGA) in Renewable Energy System Optimization')
|
|
|
|
| 194 |
wind_range = st.slider("Onshore Wind Capacity Range (MW)", 0, 10000, (0, 10000))
|
| 195 |
offshore_wind_range = st.slider("Offshore Wind Capacity Range (MW)", 0, 10000, (0, 10000))
|
| 196 |
river_range = st.slider("River Capacity Range (MW)", 0, 10000, (0, 10000))
|
|
|
|
| 197 |
thresholds = st.multiselect(
|
| 198 |
"Select MGA Cost Deviation Thresholds (%)",
|
| 199 |
list(np.arange(0, 11, 0.5)),
|
| 200 |
default=[0, 5, 10]
|
| 201 |
)
|
|
|
|
| 202 |
selected_technologies = st.multiselect("Select Technologies to Optimize", ['solar', 'onshore_wind', 'offshore_wind', 'river'], default=['solar', 'onshore_wind', 'offshore_wind', 'river'])
|
| 203 |
|
| 204 |
if st.button("Run MGA Optimization"):
|
|
|
|
| 205 |
alternative_solutions = optimize_energy_system(city_code, solar_cost, onshore_wind_cost, offshore_wind_cost, river_cost, battery_cost, yearly_demand, solar_range, wind_range, river_range, offshore_wind_range, [t / 100 for t in thresholds], selected_technologies)
|
| 206 |
|
| 207 |
if alternative_solutions:
|
| 208 |
+
# Cost breakdown visualization
|
| 209 |
+
cost_data = [{'threshold': sol['threshold'] * 100, 'type': sol['type'], 'technology': sol['technology'], 'total_cost': sol['total_cost']} for sol in alternative_solutions]
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 210 |
cost_df = pd.DataFrame(cost_data)
|
| 211 |
fig_cost = px.bar(cost_df, x='threshold', y='total_cost', color='technology', title="Cost Breakdown by Technology and Threshold")
|
| 212 |
fig_cost.update_layout(xaxis_title='Threshold (%)', yaxis_title='Total Cost (¥)')
|
|
|
|
|
|
|
| 213 |
st.plotly_chart(fig_cost, use_container_width=True)
|
| 214 |
|
| 215 |
+
# Display capacity distribution using violin plots
|
| 216 |
+
fig_violin = plot_capacity_distribution(alternative_solutions, selected_technologies)
|
| 217 |
+
st.plotly_chart(fig_violin, use_container_width=True)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|