Spaces:
Sleeping
Sleeping
Insert Initial Code
Browse files12343456789101112131415161718192021227892425262728293031103334111236373839404142434445464748495051525354131415161718195960616263646566676869707172737475767720212223247980812526278384858687888990919293949596979899100101102103104105106107108109110111112113114282930313233341191201211221231241251261271281291301311321331341351361371381391403536142143144145146147148149150373839401541551561571581591601611621631641654142434445464748495051525354551691701711721731741751761775657585960616263646566676869707172737475767717918018118218318418518618718818919019119219378798081828384851951961971981998687888990203204205919293949596979899100101102209210211103104105106107108214215216217109110111112113114115116117118119220221222223120121122123124125227228229230231232233234235236237238239240241242243244245246247248249250126127128129130131132133134135136252253137255256257258259138139140141142143144145146147261262148264265266267149150151152153154155156157158159160161162163272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321164165166167168169170171172173174175176177178179180181182183184185323324325186187188189190191192193194195327196197198199200201202203204205206207330331332333334208209336337210211212213214215216339217218219220343344345221222223224225226227228229230231232233234235236237238239240241242243348349350351244245246247354355356357358359360361362363248249250251252253254255256257258259260261262263264265266267367368369370371372268269270271272273274275276374375376277278279378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466280281282283284285286import marimo
__generated_with = "0.9.2"app = marimo.App()__generated_with = "0.15.2"app = marimo.App(width="columns")
@app.celldef __(): import marimo as mo
mo.md("# Welcome to marimo! 🌊🍃") return (mo,)
@app.celldef __(mo): slider = mo.ui.slider(1, 22) return (slider,)
@app.celldef __(mo, slider):@app.cell(column=0)def _(mo): mo.md( f""" marimo is a **reactive** Python notebook.
This means that unlike traditional notebooks, marimo notebooks **run automatically** when you modify them or interact with UI elements, like this slider: {slider}.
{"##" + "🍃" * slider.value} """ ) return # Energy System Modeling with Flixopt
@app.cell(hide_code=True)def __(mo): mo.accordion( { "Tip: disabling automatic execution": mo.md( rf""" marimo lets you disable automatic execution: just go into the notebook settings and set
"Runtime > On Cell Change" to "lazy".
When the runtime is lazy, after running a cell, marimo marks its descendants as stale instead of automatically running them. The lazy runtime puts you in control over when cells are run, while still giving guarantees about the notebook state. """ ) } This notebook demonstrates how to use the flixopt framework to model a minimalistic energy system with a boiler, heat demand, and natural gas supply. """ ) return
@app.cell(hide_code=True)def __(mo): mo.md( """ Tip: This is a tutorial notebook. You can create your own notebooks by entering `marimo edit` at the command line. """ ).callout() return
@app.cell(hide_code=True)def __(mo): mo.md( """ ## 1. Reactive execution
A marimo notebook is made up of small blocks of Python code called cells.@app.celldef _(mo): """ ## System Configuration
marimo reads your cells and models the dependencies among them: whenever a cell that defines a global variable is run, marimo **automatically runs** all cells that reference that variable. Define the basic parameters for our energy system simulation. """
Reactivity keeps your program state and outputs in sync with your code, making for a dynamic programming environment that prevents bugs before they happen. """ ) return
@app.cell(hide_code=True)def __(changed, mo): ( mo.md( f""" **✨ Nice!** The value of `changed` is now {changed}.
When you updated the value of the variable `changed`, marimo **reacted** by running this cell automatically, because this cell references the global variable `changed`.
Reactivity ensures that your notebook state is always consistent, which is crucial for doing good science; it's also what enables marimo notebooks to double as tools and apps. """ ) if changed else mo.md( """ **🌊 See it in action.** In the next cell, change the value of the variable `changed` to `True`, then click the run button. """ ) ) mo.md(""" **Configure your energy system parameters:** """) return
@app.celldef __(): changed = False return (changed,)
@app.cell(hide_code=True)def __(mo): mo.accordion( { "Tip: execution order": ( """ The order of cells on the page has no bearing on the order in which cells are executed: marimo knows that a cell reading a variable must run after the cell that defines it. This frees you to organize your code in the way that makes the most sense for you. """ ) } ) return
def _(boiler_efficiency, gas_price, mo, num_timesteps):
@app.cell(hide_code=True)def __(mo): mo.md( """ **Global names must be unique.** To enable reactivity, marimo imposes a constraint on how names appear in cells: no two cells may define the same variable. """ ) mo.hstack([num_timesteps, boiler_efficiency, gas_price], justify="space-around") return
@app.cell(hide_code=True)def __(mo): mo.accordion( { "Tip: encapsulation": ( """ By encapsulating logic in functions, classes, or Python modules, you can minimize the number of global variables in your notebook. """ ) } )@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.cell(hide_code=True)def __(mo): mo.accordion( { "Tip: private variables": ( """ Variables prefixed with an underscore are "private" to a cell, so they can be defined by multiple cells. """@app.celldef _(calculation, mo): """ ## District Heating Balance Analysis """
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) ])
except Exception as e: dh_analysis = mo.callout( mo.md(f"Error retrieving district heating results: {str(e)}"), kind="danger" ) } ) return
@app.cell(hide_code=True)def __(mo): mo.md( """ ## 2. UI elements
Cells can output interactive UI elements. Interacting with a UI element **automatically triggers notebook execution**: when you interact with a UI element, its value is sent back to Python, and every cell that references that element is re-run. dh_results = None else: dh_analysis = mo.callout( mo.md("No calculation available for district heating analysis"), kind="warn" ) dh_results = None
marimo provides a library of UI elements to choose from under `marimo.ui`. """ ) return dh_analysis return (dh_results,)
@app.celldef __(mo): mo.md("""**🌊 Some UI elements.** Try interacting with the below elements.""") returndef _(mo): num_timesteps = mo.ui.slider( start=3, stop=24, value=3, label="Number of timesteps", show_value=True ) return (num_timesteps,)
@app.celldef __(mo): icon = mo.ui.dropdown(["🍃", "🌊", "✨"], value="🍃") return (icon,)def _(np, num_timesteps, pd): """ ## Time Series and Load Profile Setup """
@app.celldef __(icon, mo): repetitions = mo.ui.slider(1, 16, label=f"number of {icon.value}: ") return (repetitions,) # 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)]
@app.celldef __(icon, repetitions): icon, repetitions return print(f"Modeling {len(timesteps)} timesteps") print(f"Thermal load profile: {thermal_load_profile}") return thermal_load_profile, timesteps
@app.celldef __(icon, mo, repetitions): mo.md("# " + icon.value * repetitions.value) return
@app.cell(hide_code=True)def __(mo): mo.md( """ ## 3. marimo is just Python
marimo cells parse Python (and only Python), and marimo notebooks are stored as pure Python files — outputs are _not_ included. There's no magical syntax.
The Python files generated by marimo are:
- easily versioned with git, yielding minimal diffs - legible for both humans and machines - formattable using your tool of choice, - usable as Python scripts, with UI elements taking their default values, and - importable by other modules (more on that in the future). """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 ) return
@app.cell(hide_code=True)def __(mo): mo.md( """ ## 4. Running notebooks as apps 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
marimo notebooks can double as apps. Click the app window icon in the bottom-right to see this notebook in "app view."
Serve a notebook as an app with `marimo run` at the command-line. Of course, you can use marimo just to level-up your notebooking, without ever making apps. """@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.cell(hide_code=True)def __(mo): mo.md( """ ## 5. The `marimo` command-line tool
**Creating and editing notebooks.** Use
``` marimo edit ```
in a terminal to start the marimo notebook server. From here you can create a new notebook or edit existing ones.
**Running as apps.** Use
``` marimo run notebook.py ```
to start a webserver that serves your notebook as an app in read-only mode, with code cells hidden.
**Convert a Jupyter notebook.** Convert a Jupyter notebook to a marimo notebook using `marimo convert`:
``` marimo convert your_notebook.ipynb > your_app.py ```
**Tutorials.** marimo comes packaged with tutorials:
- `dataflow`: more on marimo's automatic execution - `ui`: how to use UI elements - `markdown`: how to write markdown, with interpolated values and LaTeX - `plots`: how plotting works in marimo - `sql`: how to use SQL - `layout`: layout elements in marimo - `fileformat`: how marimo's file format works - `markdown-format`: for using `.md` files in marimo - `for-jupyter-users`: if you are coming from Jupyter
Start a tutorial with `marimo tutorial`; for example,
``` marimo tutorial dataflow ```@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'), )
In addition to tutorials, we have examples in our [our GitHub repo](https://www.github.com/marimo-team/marimo/tree/main/examples). """ # 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 ), ) return
# 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 ), )
@app.cell(hide_code=True)def __(mo): mo.md( """ ## 6. The marimo editor flow_system.add_elements(district_heating_bus, natural_gas_bus, cost_effect, boiler, heat_load, gas_source)
Here are some tips to help you get started with the marimo editor. """ mo.callout( mo.md(f""" ✓ Flow system built successfully - Total elements: {len(flow_system.all_elements)} """), kind="success" ) return return (flow_system,)
@app.celldef __(mo, tips): mo.accordion(tips) returndef _(flow_system, fx, mo): """ ## Optimization and Solving """
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
@app.cell(hide_code=True)def __(mo): mo.md("""## Finally, a fun fact""") return status return (calculation,)
@app.cell(hide_code=True)def __(mo): mo.md( """ The name "marimo" is a reference to a type of algae that, under the right conditions, clumps together to form a small sphere called a "marimo moss ball". Made of just strands of algae, these beloved assemblages are greater than the sum of their parts. """ )@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(hide_code=True)def __(): tips = { "Saving": ( """ **Saving**@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
- _Name_ your app using the box at the top of the screen, or with `Ctrl/Cmd+s`. You can also create a named app at the command line, e.g., `marimo edit app_name.py`. import flixopt as fx return fx, mo, np, pd
- _Save_ by clicking the save icon on the bottom right, or by inputting `Ctrl/Cmd+s`. By default marimo is configured to autosave. """ ), "Running": ( """ 1. _Run a cell_ by clicking the play ( ▷ ) button on the top right of a cell, or by inputting `Ctrl/Cmd+Enter`.
2. _Run a stale cell_ by clicking the yellow run button on the right of the cell, or by inputting `Ctrl/Cmd+Enter`. A cell is stale when its code has been modified but not run.
3. _Run all stale cells_ by clicking the play ( ▷ ) button on the bottom right of the screen, or input `Ctrl/Cmd+Shift+r`. """ ), "Console Output": ( """ Console output (e.g., `print()` statements) is shown below a cell. """ ), "Creating, Moving, and Deleting Cells": ( """ 1. _Create_ a new cell above or below a given one by clicking the plus button to the left of the cell, which appears on mouse hover.
2. _Move_ a cell up or down by dragging on the handle to the right of the cell, which appears on mouse hover.
3. _Delete_ a cell by clicking the trash bin icon. Bring it back by clicking the undo button on the bottom right of the screen, or with `Ctrl/Cmd+Shift+z`. """ ), "Disabling Automatic Execution": ( """ Via the notebook settings (gear icon) or footer panel, you can disable automatic execution. This is helpful when working with expensive notebooks or notebooks that have side-effects like database transactions. """ ), "Disabling Cells": ( """ You can disable a cell via the cell context menu. marimo will never run a disabled cell or any cells that depend on it. This can help prevent accidental execution of expensive computations when editing a notebook. """ ), "Code Folding": ( """ You can collapse or fold the code in a cell by clicking the arrow icons in the line number column to the left, or by using keyboard shortcuts.
Use the command palette (`Ctrl/Cmd+k`) or a keyboard shortcut to quickly fold or unfold all cells. """ ), "Code Formatting": ( """ If you have [ruff](https://github.com/astral-sh/ruff) installed, you can format a cell with the keyboard shortcut `Ctrl/Cmd+b`. """ ), "Command Palette": ( """ Use `Ctrl/Cmd+k` to open the command palette. """ ), "Keyboard Shortcuts": ( """ Open the notebook menu (top-right) or input `Ctrl/Cmd+Shift+h` to view a list of all keyboard shortcuts. """ ), "Configuration": ( """ Configure the editor by clicking the gears icon near the top-right of the screen. """ ), } return (tips,)
@app.celldef _(): return
if __name__ == "__main__":app.py+218-401