Spaces:
Sleeping
Sleeping
File size: 8,603 Bytes
4545835 801e506 4545835 801e506 4545835 801e506 4545835 801e506 897d11b 801e506 4545835 801e506 4545835 801e506 4545835 801e506 4545835 cc0102a 4545835 801e506 4545835 801e506 4545835 801e506 cc0102a 4545835 801e506 cc0102a 801e506 cc0102a 801e506 4545835 cc0102a 4545835 cc0102a 4545835 cc0102a 4545835 cc0102a 4545835 cc0102a 4545835 801e506 4545835 801e506 4545835 801e506 cc0102a 4545835 cc0102a 4545835 cc0102a 801e506 cc0102a 801e506 cc0102a 4545835 cc0102a 4545835 801e506 cc0102a 801e506 cc0102a 801e506 cc0102a 801e506 cc0102a 4545835 cc0102a 4545835 cc0102a 4545835 801e506 cc0102a 4545835 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 | import marimo
__generated_with = "0.15.2"
app = marimo.App(width="columns")
@app.cell(column=0)
def _(mo):
mo.md(
"""
# Energy System Modeling with Flixopt
This notebook demonstrates how to use the flixopt framework to model a minimalistic energy system
with a boiler, heat demand, and natural gas supply.
THis has been updated again, again, and again.
"""
)
return
@app.cell
def _(mo):
"""
## System Configuration
Define the basic parameters for our energy system simulation.
"""
mo.md("""
**Configure your energy system parameters:**
""")
return
@app.cell
def _(solve_button):
solve_button
return
@app.cell(hide_code=True)
def _(
boiler_efficiency,
calculations,
fx,
gas_price,
mo,
solve_button,
thermal_load_profile,
time,
timesteps,
):
"""
## Create and solve FLowSystem
"""
solve_status = mo.md('')
flow_system_status = mo.md('Click the button to build the FLow System and solve the Optimization')
if not hasattr(solve_button, '_last_processed'):
solve_button._last_processed = 0
# Only run if button value has changed (new click)
if solve_button.value > solve_button._last_processed:
try:
solve_button._last_processed = solve_button.value
_sleep = 0.2
with mo.status.spinner(title="Creating and Solving Model ...") as _spinner:
_spinner.update(subtitle="Creating FLowSystem and adding Components ...")
time.sleep(_sleep)
_fs = fx.FlowSystem(timesteps)
_fs.add_elements(
fx.Effect('costs', 'β¬', 'Cost', is_standard=True, is_objective=True),
fx.Source(
'Natural Gas Tariff',
source=fx.Flow(
label='Gas Flow',
bus='Natural Gas',
size=1000,
effects_per_flow_hour=gas_price.value
),
),
fx.Sink(
'Heat Demand',
sink=fx.Flow(
label='Thermal Load',
bus='District Heating',
size=1,
fixed_relative_profile=thermal_load_profile
),
),
fx.linear_converters.Boiler(
'Boiler',
eta=boiler_efficiency.value,
Q_th=fx.Flow(label='Thermal Output', bus='District Heating', size=50),
Q_fu=fx.Flow(label='Fuel Input', bus='Natural Gas'),
),
fx.Bus('District Heating'),
fx.Bus('Natural Gas'),
)
# Create and solve the calculation
_spinner.update(subtitle="Creating Calculation ...")
time.sleep(_sleep)
_calculation = fx.FullCalculation('Simulation1', _fs)
_spinner.update(subtitle="Modeling Variables and Constraints ...")
time.sleep(_sleep)
_calculation.do_modeling()
_spinner.update(subtitle="Solving the Model ...")
time.sleep(_sleep)
_calculation.solve(fx.solvers.HighsSolver(0.01, 60))
solve_status = mo.callout(
mo.md(f"β
**Optimization completed successfully!** (Run #{solve_button.value})"),
kind="success"
)
flow_system_status = mo.md(f"""
β Flow system built successfully
- Total elements: {len(_fs.all_elements)}
""")
calculations.append(_calculation)
except Exception as e:
solve_status = mo.callout(
mo.md(f"β **Optimization failed:** {str(e)}"),
kind="danger"
)
return (solve_status,)
@app.cell
def _(boiler_efficiency, gas_price, mo, num_timesteps):
mo.hstack([num_timesteps, boiler_efficiency, gas_price], justify="space-around")
return
@app.cell
def _(mo, solve_status, total_costs):
# Display current parameter values in a callout
mo.hstack(
[solve_status,total_costs],
align='center',
widths='equal',
justify='center'
)
return
@app.cell
def _(results_overview):
results_overview
return
@app.cell
def _(dh_analysis):
dh_analysis
return
@app.cell(column=1)
def _():
# Import required libraries
import marimo as mo
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
from rich.pretty import pprint
import time
import flixopt as fx
calculations = []
return calculations, fx, mo, np, pd, time
@app.cell
def _():
return
@app.cell
def _(calculations, solve_button):
"""Refresh to latest"""
solve_button
if len(calculations) == 0:
calculation = None
results = None
else:
calculation = calculations[-1]
results = calculation.results
return calculation, results
@app.cell
def _(mo):
solve_button = mo.ui.button(
label="π Run Optimization",
on_click=lambda value: value + 1,
value = 0,
kind="success",
)
return (solve_button,)
@app.cell
def _(calculation, mo, results):
results
if calculation is not None:
results_overview = mo.vstack([
mo.md("### π° Cost Analysis"),
calculation.results.solution['costs(operation)|total_per_timestep'].round(3).to_pandas()[:-1],
])
else:
results_overview = None
return (results_overview,)
@app.cell
def _(mo):
# Interactive parameter controls using latest Marimo UI elements
boiler_efficiency = mo.ui.slider(
start=0.3,
stop=0.9,
value=0.5,
step=0.05,
label="Boiler efficiency",
show_value=True
)
gas_price = mo.ui.slider(
start=0.02,
stop=0.08,
value=0.04,
step=0.01,
label="Gas price (β¬/kWh)",
show_value=True
)
return boiler_efficiency, gas_price
@app.cell
def _(mo):
num_timesteps = mo.ui.slider(
start=3,
stop=24,
value=3,
label="Number of timesteps",
show_value=True
)
return (num_timesteps,)
@app.cell
def _(np, num_timesteps, pd):
"""
## Time Series and Load Profile Setup
"""
# Define timesteps
timesteps = pd.date_range('2020-01-01', periods=num_timesteps.value, freq='h')
# Define thermal load profile (extend or truncate based on timesteps)
base_profile = np.array([30, 0, 20, 25, 15, 35, 10, 40]) # Extended base profile
if len(timesteps) <= len(base_profile):
thermal_load_profile = base_profile[:len(timesteps)]
else:
# Repeat pattern if we need more timesteps
thermal_load_profile = np.tile(base_profile, (len(timesteps) // len(base_profile)) + 1)[:len(timesteps)]
return thermal_load_profile, timesteps
@app.cell
def _(mo, results):
"""
## District Heating Balance Analysis
"""
if results is None:
dh_analysis = mo.callout(
mo.md("No calculation available for district heating analysis"),
kind="warn"
)
dh_results = None
else:
try:
# Get district heating results
dh_results = results['District Heating'].node_balance().to_dataframe()
dh_analysis = mo.vstack([
mo.md("### π₯ District Heating Balance"),
mo.carousel([
mo.ui.table(
data=dh_results.round(3),
selection=None
),
results['District Heating'].plot_node_balance(show=False)
])
])
except Exception as e:
dh_analysis = mo.callout(
mo.md(f"Error retrieving district heating results: {str(e)}"),
kind="danger"
)
dh_results = None
return (dh_analysis,)
@app.cell
def _(calculation, mo):
total_costs = mo.callout(
mo.md(f"**Total System Cost: {calculation.results.solution['costs|total'].item():.2f} β¬**"),
kind="info",
) if calculation is not None else None
return (total_costs,)
if __name__ == "__main__":
app.run()
|