Skip to main content

Core simulation library for Biosimulant

Project description

biosim

PyPI - Version PyPI - Python Version

Composable simulation runtime + UI layer for orchestrating runnable biomodules.


Executive Summary & System Goals

Vision

Provide a small, stable composition layer for simulations: wire reusable components ("biomodules") into a BioWorld, run them with a single orchestration contract, and visualize/debug runs via a lightweight web UI (SimUI). Biomodules are self-contained Python packages that can wrap external simulators internally (SBML/NeuroML/CellML/etc.) without a separate adapter layer.

Core Mission

  • Compose simulations from reusable, interoperable biomodules.
  • Make "run + visualize + share a config" the default workflow (local-first; hosted later).
  • Keep the runtime small and predictable while letting biomodules embed their own simulator/tooling.

Primary Users

  • Developers and researchers who need composable simulation workflows and fast iteration.
  • Near-term beachhead: neuroscience demos (single neuron + small E/I microcircuits) with strong visuals and reproducible configs.

Installation

Preferred (pinned GitHub ref):

pip install "biosim @ git+https://github.com/<org>/biosim.git@<ref>"

Alternative (package index):

pip install biosim

Publishing to PyPI

See the release guide: docs/releasing.md.

Examples

  • See examples/ for quick-start scripts. Try:
pip install -e .
python examples/basic_usage.py

For advanced curated demos (neuro/ecology), wiring configs, and model-pack templates, see the companion repo:

Quick Start: BioWorld

Minimal usage:

import biosim
from biosim import BioSignal, SignalMetadata

class Counter(biosim.BioModule):
    min_dt = 0.1

    def __init__(self):
        self.value = 0

    def reset(self) -> None:
        self.value = 0

    def advance_to(self, t: float) -> None:
        self.value += 1

    def get_outputs(self):
        source = getattr(self, "_world_name", "counter")
        return {
            "count": BioSignal(
                source=source,
                name="count",
                value=self.value,
                time=0.0,
                metadata=SignalMetadata(units="1", description="tick counter"),
            )
        }

world = biosim.BioWorld()
world.add_biomodule("counter", Counter())
world.run(duration=1.0, tick_dt=0.1)

Visuals from Modules

Modules may optionally expose web-native visuals via visualize(), returning a dict or list of dicts with keys render and data. The world can collect them without any transport layer:

class MyModule(biosim.BioModule):
    min_dt = 0.1

    def advance_to(self, t: float) -> None:
        return

    def get_outputs(self):
        return {}

    def visualize(self):
        return {
            "render": "timeseries",
            "data": {"series": [{"name": "s", "points": [[0.0, 1.0]]}]},
        }

world = biosim.BioWorld()
world.add_biomodule("module", MyModule())
world.run(duration=0.1, tick_dt=0.1)
print(world.collect_visuals())  # [{"module": "module", "visuals": [...]}]

See examples/visuals_demo.py for a minimal end-to-end example.

SimUI (Python-Declared UI)

SimUI lets you build and launch a small web UI entirely from Python (similar to Gradio's ergonomics), backed by FastAPI and a prebuilt React SPA that renders visuals from JSON. The frontend uses Server-Sent Events (SSE) for real-time updates.

  • User usage (no Node/npm required):
    • Install UI extras: pip install -e '.[ui]'

    • Try the demo: python examples/ui_demo.py then open http://127.0.0.1:7860/ui/.

    • From your own code:

      from biosim.simui import Interface, Number, Button, EventLog, VisualsPanel
      world = biosim.BioWorld()
      ui = Interface(
          world,
          controls=[Number("duration", 10), Number("tick_dt", 0.1), Button("Run")],
          outputs=[EventLog(), VisualsPanel()],
      )
      ui.launch()
      
    • The UI provides endpoints under /ui/api/...:

      • GET /api/spec – UI layout (controls, outputs, modules)
      • POST /api/run – Start a simulation run
      • GET /api/status – Runner status (running/paused/error)
      • GET /api/state – Full state (status + last step + modules)
      • GET /api/events – Buffered world events (?since_id=&limit=)
      • GET /api/visuals – Collected module visuals
      • GET /api/snapshot – Full snapshot (status + visuals + events)
      • GET /api/stream – SSE endpoint for real-time event streaming
      • POST /api/pause – Pause running simulation
      • POST /api/resume – Resume paused simulation
      • POST /api/reset – Stop, reset, and clear buffers
      • Editor sub-API (/api/editor/...): visual config editor for loading, saving, validating, and applying YAML wiring configs as node graphs. Endpoints include modules, current, config, apply, validate, layout, to-yaml, from-yaml, and files.

Per-run resets for clean visuals

  • On each Run, the backend clears its event buffer and calls reset() on modules if they implement it.

  • The frontend clears visuals/events before posting /api/run.

  • To avoid overlapping charts across runs, add reset() to modules that accumulate history (e.g., time series points).

  • Maintainer flow (building the frontend SPA):

    • Edit the React/Vite app under src/biosim/simui/_frontend/.
    • Build via Python: python -m biosim.simui.build (requires Node/npm). This writes src/biosim/simui/static/app.js.
    • Alternatively: bash scripts/build_simui_frontend.sh.
    • Packaging includes src/biosim/simui/static/**, so end users never need npm.
  • CI packaging (recommended): run the frontend build before python -m build so wheels/sdists ship the bundled assets.

Troubleshooting:

  • If you see SimUI static bundle missing at .../static/app.js, build the frontend with python -m biosim.simui.build (requires Node/npm) before launching. End users installing a release wheel won't see this.

SimUI Design Notes

  • Transport: SSE (Server-Sent Events). The SPA connects to /api/stream for real-time updates. Polling endpoints (/api/status, /api/visuals, /api/events) remain available for fallback/debugging.
  • Events API: /api/events?since_id=<int>&limit=<int> returns { events, next_since_id } where events are appended world events and next_since_id is the cursor for subsequent calls.
  • VisualSpec types supported now:
    • timeseries: data = { "series": [{ "name": str, "points": [[x, y], ...] }, ...] }
    • bar: data = { "items": [{ "label": str, "value": number }, ...] }
    • table: data = { "columns": [..], "rows": [[..], ...] } or data = { "items": [{...}, ...] }
    • image: data = { "src": str, "alt"?: str, "width"?: number, "height"?: number }
    • scatter: scatter plot data
    • heatmap: matrix/heatmap data
    • graph: placeholder renderer shows counts + JSON; richer graph lib can be added later
    • custom:<type>: custom renderer namespace for user-defined types
    • unknown types: rendered as JSON fallback
  • VisualSpec may also include an optional description (string) for hover text or captions.

Terminology

Understanding the core concepts is essential for working with biosim effectively.

Term Description
BioWorld Runtime container that orchestrates multi-rate biomodules, routes signals, and publishes lifecycle events.
BioModule Pluggable unit of behavior with local state. Implements the runnable contract (setup/reset/advance_to/...).
BioSignal Typed, versioned data payload exchanged between modules via named ports.
WorldEvent Runtime events emitted by the BioWorld (STARTED, TICK, FINISHED, etc.).
Wiring Module connection graph. Defined programmatically, via WiringBuilder, or loaded from YAML/TOML configs.
VisualSpec JSON structure returned by module.visualize() with render type and data payload.

Event Lifecycle

Every simulation follows this sequence:

STARTED -> TICK (xN) -> FINISHED

PAUSED, RESUMED, STOPPED, and ERROR may also be emitted depending on runtime control flow.

License

MIT. See LICENSE.txt.

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

biosim-0.0.2.tar.gz (260.5 kB view details)

Uploaded Source

Built Distribution

If you're not sure about the file name format, learn more about wheel file names.

biosim-0.0.2-py3-none-any.whl (247.7 kB view details)

Uploaded Python 3

File details

Details for the file biosim-0.0.2.tar.gz.

File metadata

  • Download URL: biosim-0.0.2.tar.gz
  • Upload date:
  • Size: 260.5 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? Yes
  • Uploaded via: twine/6.1.0 CPython/3.13.7

File hashes

Hashes for biosim-0.0.2.tar.gz
Algorithm Hash digest
SHA256 420203df25ccf9a2080678cf36f6dcde64860406e5016d3e726cc4148ca5e0f0
MD5 011e4983bffba48f32d6dd830f68e3bb
BLAKE2b-256 50fb0ef7d583f9122c6945385e97bd6026acedb222836bed34e822a30a380a54

See more details on using hashes here.

Provenance

The following attestation bundles were made for biosim-0.0.2.tar.gz:

Publisher: publish-pypi.yml on Biosimulant/biosim

Attestations: Values shown here reflect the state when the release was signed and may no longer be current.

File details

Details for the file biosim-0.0.2-py3-none-any.whl.

File metadata

  • Download URL: biosim-0.0.2-py3-none-any.whl
  • Upload date:
  • Size: 247.7 kB
  • Tags: Python 3
  • Uploaded using Trusted Publishing? Yes
  • Uploaded via: twine/6.1.0 CPython/3.13.7

File hashes

Hashes for biosim-0.0.2-py3-none-any.whl
Algorithm Hash digest
SHA256 0f0fdf17eeb65078e6ec6fa72ada77a805dbe8801bfecb5cba4159bb3b255e9e
MD5 d954ae3c47b5f6a6f527bc38ca45dd83
BLAKE2b-256 94c47b63e306887fd50f09cdb0f3db653308b843de0261c4c2b88c3f41b1e803

See more details on using hashes here.

Provenance

The following attestation bundles were made for biosim-0.0.2-py3-none-any.whl:

Publisher: publish-pypi.yml on Biosimulant/biosim

Attestations: Values shown here reflect the state when the release was signed and may no longer be current.

Supported by

AWS Cloud computing and Security Sponsor Datadog Monitoring Depot Continuous Integration Fastly CDN Google Download Analytics Pingdom Monitoring Sentry Error logging StatusPage Status page