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
12345678910111213---title: marimo app templateemoji: 🍃colorFrom: indigocolorTo: purplesdk: dockerpinned: truelicense: mitshort_description: Template for deploying a marimo application to HF---Check out marimo at <https://github.com/marimo-team/marimo>Check out the configuration reference at <https://huggingface.co/docs/hub/spaces-config-reference>1234567891011121314151617181920---title: "FlixOpt Tutorial 1: Basics"emoji: 🔧colorFrom: bluecolorTo: greensdk: dockerpinned: truelicense: mitshort_description: Interactive FlixOpt tutorial---# FlixOpt Tutorial 1: Getting StartedAn interactive Marimo tutorial covering FlixOpt basics.## Running Locally```bashpip install marimo flixoptmarimo run tutorials/tutorial-01-basics/app.py```
11 unmodified lines12131415161713 unmodified lines3132333435362 unmodified lines3940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412521 unmodified lines14714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528611 unmodified linesThis notebook demonstrates how to use the flixopt framework to model a minimalistic energy systemwith a boiler, heat demand, and natural gas supply.""")return13 unmodified linesreturn@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],])return@app.celldef _(calculation, mo):"""## District Heating Balance Analysis"""if calculation is not None:try:# Get district heating resultsdh_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)])except Exception as e:dh_analysis = mo.callout(mo.md(f"Error retrieving district heating results: {str(e)}"),kind="danger")dh_results = Noneelse:dh_analysis = mo.callout(mo.md("No calculation available for district heating analysis"),kind="warn")dh_results = Nonedh_analysisreturn (dh_results,)@app.celldef _(mo):num_timesteps = mo.ui.slider(start=3,stop=24,value=3,label="Number of timesteps",show_value=True)return (num_timesteps,)@app.celldef _(np, num_timesteps, pd):"""## Time Series and Load Profile Setup"""# Define timestepstimesteps = 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 profileif len(timesteps) <= len(base_profile):thermal_load_profile = base_profile[:len(timesteps)]else:# Repeat pattern if we need more timestepsthermal_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.cell21 unmodified lines@app.celldef _(boiler_efficiency, gas_price, mo, num_timesteps):# Display current parameter values in a calloutmo.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 busesdistrict_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 componentboiler = 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 costgas_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")return (flow_system,)@app.celldef _(flow_system, fx, mo):"""## Optimization and Solving"""try:# Create and solve the calculationcalculation = 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 = Nonestatusreturn (calculation,)@app.celldef _(dh_results, mo):"""Display district heating balance table"""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"),kind="warn")return@app.cell(column=1)def _():# Import required librariesimport marimo as moimport matplotlib.pyplot as pltimport numpy as npimport pandas as pdfrom rich.pretty import pprintimport flixopt as fxreturn fx, mo, np, pd@app.celldef _():returnif __name__ == "__main__":11 unmodified lines1213141516171813 unmodified lines32333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341352 unmodified lines13813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122221 unmodified lines24424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332411 unmodified linesThis notebook demonstrates how to use the flixopt framework to model a minimalistic energy systemwith a boiler, heat demand, and natural gas supply.THis has been updated again""")return13 unmodified linesreturn@app.celldef _(solve_button):solve_buttonreturn@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.2with 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 _(mo, solve_status, total_costs):# Display current parameter values in a calloutmo.hstack([solve_status,total_costs],align='center',widths='equal',justify='center')return@app.celldef _(results_overview):results_overviewreturn@app.celldef _(dh_analysis):dh_analysisreturn@app.cell(column=1)def _():# Import required librariesimport marimo as moimport matplotlib.pyplot as pltimport numpy as npimport pandas as pdfrom rich.pretty import pprintimport timeimport flixopt as fxcalculations = []return calculations, fx, mo, np, pd, time@app.celldef _():return@app.celldef _(calculations, solve_button):"""Refresh to latest"""solve_buttonif len(calculations) == 0:calculation = Noneresults = Noneelse:calculation = calculations[-1]results = calculation.resultsreturn calculation, results@app.celldef _(mo):solve_button = mo.ui.button(label="🚀 Run Optimization",on_click=lambda value: value + 1,value = 0,kind="success",)return (solve_button,)@app.celldef _(calculation, mo, results):resultsif 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 = Nonereturn (results_overview,)@app.cell21 unmodified lines@app.celldef _(mo):num_timesteps = mo.ui.slider(start=3,stop=24,value=3,label="Number of timesteps",show_value=True)return (num_timesteps,)@app.celldef _(np, num_timesteps, pd):"""## Time Series and Load Profile Setup"""# Define timestepstimesteps = 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 profileif len(timesteps) <= len(base_profile):thermal_load_profile = base_profile[:len(timesteps)]else:# Repeat pattern if we need more timestepsthermal_load_profile = np.tile(base_profile, (len(timesteps) // len(base_profile)) + 1)[:len(timesteps)]return thermal_load_profile, timesteps@app.celldef _(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 = Noneelse:try:# Get district heating resultsdh_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 = Nonereturn (dh_analysis,)@app.celldef _(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 Nonereturn (total_costs,)if __name__ == "__main__":
1 unmodified line23456781 unmodified line## Testing your Dockerfile locally```bashdocker build -t marimo-app .docker run -it --rm -p 7860:7860 marimo-app```1 unmodified line234567891011121314151 unmodified line## Testing your Dockerfile locallyNavigate 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.
123456marimo# Or a specific version# marimo>=0.9.0# Add other dependencies as neededflixopt==2.1.612marimoflixopt
README.md+14-7
app.py+213-175
development.md+7
requirements.txt+1-5