Spaces:
Sleeping
Sleeping
GitHub Action commited on
Commit ·
cc0102a
1
Parent(s): 13a4578
Update tutorial from GitHub Actions
Browse filesFiles changed (4)
- README.md+14-7
- app.py+213-175
- development.md+7
- requirements.txt+1-5
1234523456789910111213121314151617181920---title: marimo app templateemoji: 🍃colorFrom: indigocolorTo: purpletitle: "FlixOpt Tutorial 1: Basics"emoji: 🔧colorFrom: bluecolorTo: greensdk: dockerpinned: truelicense: mitshort_description: Template for deploying a marimo application to HFshort_description: Interactive FlixOpt tutorial---
Check out marimo at <https://github.com/marimo-team/marimo>Check out the configuration reference at <https://huggingface.co/docs/hub/spaces-config-reference># FlixOpt Tutorial 1: Getting Started
An interactive Marimo tutorial covering FlixOpt basics.
## Running Locally```bashpip install marimo flixoptmarimo run tutorials/tutorial-01-basics/app.py```11 unmodified lines1213141516171813 unmodified lines32333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341352 unmodified lines138139140424344454647484950515214114214314414514614714814915015115257585960153154155156626364651576768697071158159160161162737475767778798081828384163868716416516616716816917017117217317417517617717817918091929394959697989918118218318418510310410510618618718818919019119219319419519619710911019819920020120220320420520620711211311411511611711820812012112220921021121221321421521621721821922022122221 unmodified lines24424524615015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421524724824925025125225325421725525625725822125926022326126226322622722822923026423223323423523623723823924024124226526626724424526826927027127227327427527627727824927928025128128228325425525625725825926026126228428528628728826526628929029129229329426826927027127227327427529529629729829930030130230330430527727830630730830931031131231331431528228331631731831932032132232332411 unmodified lines
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 """ ) return13 unmodified lines return
@app.celldef _(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.celldef _(boiler_efficiency, gas_price, mo, num_timesteps):
2 unmodified lines
@app.celldef _(calculation, mo): mo.hstack([ mo.vstack([ mo.md("### 💰 Cost Analysis"), mo.callout( mo.md(f"**Total System Cost: {calculation.results.solution['costs|total'].item():.2f} €**"), kind="info" ), ]), calculation.results.solution['costs(operation)|total_per_timestep'].round(3).to_pandas()[:-1], ])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.celldef _(calculation, mo): """ ## District Heating Balance Analysis """def _(results_overview): results_overview return
if calculation is not None: try: # Get district heating results dh_results = calculation.results['District Heating'].node_balance().to_dataframe()
dh_analysis = mo.vstack([ mo.md("### ���� District Heating Balance"), dh_results, calculation.results['District Heating'].plot_node_balance(show=False) ])@app.celldef _(dh_analysis): dh_analysis return
except Exception as e: dh_analysis = mo.callout( mo.md(f"Error retrieving district heating results: {str(e)}"), kind="danger" ) dh_results = None else: dh_analysis = mo.callout( mo.md("No calculation available for district heating analysis"), kind="warn" ) dh_results = None
dh_analysis return (dh_results,)@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.celldef _(mo): num_timesteps = mo.ui.slider( start=3, stop=24, value=3, label="Number of timesteps", show_value=True ) return (num_timesteps,)def _(): return
@app.celldef _(np, num_timesteps, pd): """ ## Time Series and Load Profile Setup """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
# Define timesteps timesteps = pd.date_range('2020-01-01', periods=num_timesteps.value, freq='h')@app.celldef _(mo): solve_button = mo.ui.button( label="🚀 Run Optimization", on_click=lambda value: value + 1, value = 0, kind="success", ) return (solve_button,)
# 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)]
print(f"Modeling {len(timesteps)} timesteps") print(f"Thermal load profile: {thermal_load_profile}") return thermal_load_profile, timesteps@app.celldef _(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.cell21 unmodified lines
@app.celldef _(boiler_efficiency, gas_price, mo, num_timesteps): # Display current parameter values in a callout mo.callout( mo.md(f""" **Current Configuration:** - Timesteps: {num_timesteps.value} - Boiler efficiency: {boiler_efficiency.value:.1%} - Gas price: {gas_price.value:.3f} €/kWh """), kind="info" ) return
@app.celldef _(boiler_efficiency, fx, gas_price, mo, thermal_load_profile, timesteps): """ ## Component Creation """ flow_system = fx.FlowSystem(timesteps)
# Define energy buses district_heating_bus = fx.Bus('District Heating') natural_gas_bus = fx.Bus('Natural Gas')
# Define cost effect (optimization objective) cost_effect = fx.Effect('costs', '€', 'Cost', is_standard=True, is_objective=True)
# Create boiler component boiler = 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'), )
# Create heat demand (sink) heat_load = fx.Sink( 'Heat Demand', sink=fx.Flow( label='Thermal Load', bus='District Heating', size=1, fixed_relative_profile=thermal_load_profile ), )
# Create gas source with cost gas_source = fx.Source( 'Natural Gas Tariff', source=fx.Flow( label='Gas Flow', bus='Natural Gas', size=1000, effects_per_flow_hour=gas_price.value ), )
flow_system.add_elements(district_heating_bus, natural_gas_bus, cost_effect, boiler, heat_load, gas_source)
mo.callout( mo.md(f""" ✓ Flow system built successfully - Total elements: {len(flow_system.all_elements)} """), kind="success"def _(mo): num_timesteps = mo.ui.slider( start=3, stop=24, value=3, label="Number of timesteps", show_value=True ) return (flow_system,) return (num_timesteps,)
@app.celldef _(flow_system, fx, mo):def _(np, num_timesteps, pd): """ ## Optimization and Solving ## Time Series and Load Profile Setup """
try: # Create and solve the calculation calculation = fx.FullCalculation('Simulation1', flow_system) calculation.do_modeling() calculation.solve(fx.solvers.HighsSolver(0.01, 60))
status = mo.callout( mo.md("✅ **Optimization completed successfully!**"), kind="success" )
except Exception as e: status = mo.callout( mo.md(f"❌ **Optimization failed:** {str(e)}"), kind="danger" ) calculation = None # Define timesteps timesteps = pd.date_range('2020-01-01', periods=num_timesteps.value, freq='h')
status return (calculation,) # 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.celldef _(dh_results, mo):def _(mo, results): """ Display district heating balance table ## District Heating Balance Analysis """
if dh_results is not None: mo.ui.table( data=dh_results.round(3), pagination=False, selection=None ) else: mo.callout( mo.md("District heating results not available"), if results is None: dh_analysis = mo.callout( mo.md("No calculation available for district heating analysis"), kind="warn" ) return
dh_results = None else: try: # Get district heating results dh_results = results['District Heating'].node_balance().to_dataframe()
@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 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) ]) ])
import flixopt as fx return fx, mo, np, pd 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.celldef _(): returndef _(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__":1 unmodified line234567891011121314151 unmodified line
## Testing your Dockerfile locally
Navigate to the directory containing this file and the `.dockerfile`. Likely:```bashcd tutorials/tutorial-01-basics/```
Then build and run the docker image:```bashdocker build -t marimo-app .docker run -it --rm -p 7860:7860 marimo-app```YOu need to install and configure docker on your machine. See [here](https://docs.docker.com/get-docker/) for more information.1234562marimo# Or a specific version# marimo>=0.9.0
# Add other dependencies as neededflixopt==2.1.6flixoptREADME.md+14-7
app.py+213-175
development.md+7
requirements.txt+1-5