# desflow > Realistic event streams from a SimPy simulation you can steer while it runs, written to Kafka, Redis, PostgreSQL, Parquet, JSONL and Iceberg. # Home # desflow **Realistic event streams from a simulation you can steer while it runs.** Most test data generators write random rows. desflow writes the events of a working process: orders queue for packers, waits grow at busy times, and a backlog builds when orders arrive faster than the packers can pack them. The data comes from a [SimPy](https://simpy.readthedocs.io/) discrete-event simulation, so each change in it has a cause in the model, as in a real system. [Why desflow](https://jaehyeon.me/desflow/latest/about/why-desflow/index.md) explains why it was built and what it is for. The three ways to write a model build one real-time run. Ingress connectors change its live parameters while it runs, and egress connectors write its events and telemetry: The control dashboard of the [Kafka Digital Twin](https://jaehyeon.me/desflow/latest/gallery/simulation-models/kafka/index.md) example changes simulation parameters during a run, and the telemetry shows the effect without a restart. The example's Quick Start runs the dashboard beside the simulation: ______________________________________________________________________ ## Key Features | Group | What it covers | | --------------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | [Ways to write a model](https://jaehyeon.me/desflow/latest/user-guide/writing-a-model/index.md) | a YAML blueprint with no Python, a Python script with the builder API, or SimPy code with the low-level API. All three build the same model and publish the same records. | | [Model parts](https://jaehyeon.me/desflow/latest/user-guide/model-parts/index.md) | arrivals drawn from a distribution, changed on a schedule or replayed from a file; tasks that run in a flow, with routing, rework and priorities; resources with queues, preemption, breakdowns and queue limits; stores and containers; signals, waits, patience and failures | | [Time](https://jaehyeon.me/desflow/latest/user-guide/time-and-pacing/index.md) | a run in real time or at full speed, history written at full speed and then carried on live, and a run that ends at a time, on an event or once the last work has left | | [Live changes](https://jaehyeon.me/desflow/latest/user-guide/live-runs-and-connectors/live-parameters/index.md) | arrival rates, service times and capacities changed during a run by name, such as `Shop.arrival.orders.rate`, from a timed scenario, a local schedule, a file you edit, Kafka, Redis or PostgreSQL | | [Records](https://jaehyeon.me/desflow/latest/reference/records-and-telemetry/index.md) | an event for each step of each entity, telemetry with the statistics, and label records that hold the ground truth of each planned change. Records are JSON, Avro, JSON Schema or Protobuf through the Confluent or AWS Glue Schema Registry, or Pydantic models. | | [Connectors](https://jaehyeon.me/desflow/latest/user-guide/live-runs-and-connectors/egress/index.md) | several sinks in one run, each with its own filter: Kafka, including SASL, mTLS, OAuth and AWS IAM clusters, Redis, PostgreSQL, Parquet or JSONL files on local disk, S3-compatible storage, Google Cloud Storage or Azure Blob Storage, and Iceberg tables. A connector of your own is one class. | | [Studies](https://jaehyeon.me/desflow/latest/user-guide/results/statistics/index.md) | built-in statistics with a warm-up, replications with a 95% interval for each statistic, experiments that compare designs with the same random numbers and write a report, a check against the queueing formulas before a long run, and distributions fitted to measured times | | [Tools](https://jaehyeon.me/desflow/latest/cli/index.md) | the `desflow` command, and a JSON Schema that gives an editor completion for blueprints | | [Integrations](https://jaehyeon.me/desflow/latest/integrations/index.md) | a study run as a task of Airflow, Dagster, Prefect or Kestra, and a later task that reads the figures from the file the run writes | | [AI Assistants](https://jaehyeon.me/desflow/latest/ai/index.md) | a plugin for Claude Code, Codex or Antigravity that installs the desflow skill, with which an assistant writes, checks and runs models, and the `desflow mcp` server, which gives it the desflow commands as tools | ## Commands The package comes with the `desflow` command. It runs a blueprint, and checks, compares and fits models, with no Python to write. [Command Line](https://jaehyeon.me/desflow/latest/cli/index.md) uses every command on the shop of the `experiment` example. | Command | What you use it for | How to use it | Reference | | -------------------- | --------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `desflow examples` | list the examples with `list`, and download one with `get` | [Get an Example](https://jaehyeon.me/desflow/latest/cli/#get-an-example) | [`desflow examples`](https://jaehyeon.me/desflow/latest/cli/examples/index.md), [`desflow examples list`](https://jaehyeon.me/desflow/latest/cli/examples-list/index.md), [`desflow examples get`](https://jaehyeon.me/desflow/latest/cli/examples-get/index.md) | | `desflow explain` | check a model for bottlenecks before a long run | [Check It Before a Long Run](https://jaehyeon.me/desflow/latest/cli/#check-it-before-a-long-run) | [`desflow explain`](https://jaehyeon.me/desflow/latest/cli/explain/index.md) | | `desflow check` | check that blueprints and builder files build, without running them | [Check It Before a Long Run](https://jaehyeon.me/desflow/latest/cli/#check-it-before-a-long-run) | [`desflow check`](https://jaehyeon.me/desflow/latest/cli/check/index.md) | | `desflow run` | run a blueprint, or its replications with a 95% interval for each statistic | [Run It](https://jaehyeon.me/desflow/latest/cli/#run-it) | [`desflow run`](https://jaehyeon.me/desflow/latest/cli/run/index.md) | | `desflow test` | run the `tests` of a blueprint and report the statistics that differ | [Run It](https://jaehyeon.me/desflow/latest/cli/#run-it) | [`desflow test`](https://jaehyeon.me/desflow/latest/cli/test/index.md) | | `desflow experiment` | compare designs of a model and check them against bounds | [Compare Designs](https://jaehyeon.me/desflow/latest/cli/#compare-designs) | [`desflow experiment`](https://jaehyeon.me/desflow/latest/cli/experiment/index.md) | | `desflow report` | build an experiment's report again from its files | [Compare Designs](https://jaehyeon.me/desflow/latest/cli/#compare-designs) | [`desflow report`](https://jaehyeon.me/desflow/latest/cli/report/index.md) | | `desflow fit` | fit every distribution family to measured times | [Fit Measured Times](https://jaehyeon.me/desflow/latest/cli/#fit-measured-times) | [`desflow fit`](https://jaehyeon.me/desflow/latest/cli/fit/index.md) | | `desflow dist` | turn a mean and a standard deviation into a family's parameters, and back | [Convert Parameters](https://jaehyeon.me/desflow/latest/cli/#convert-parameters) | [`desflow dist`](https://jaehyeon.me/desflow/latest/cli/dist/index.md) | | `desflow schema` | print the blueprint JSON Schema, for an editor | [Set Up an Editor](https://jaehyeon.me/desflow/latest/cli/#set-up-an-editor) | [`desflow schema`](https://jaehyeon.me/desflow/latest/cli/schema/index.md) | | `desflow mcp` | serve the commands as tools to an AI assistant on your machine | [Serve the Commands to an Assistant](https://jaehyeon.me/desflow/latest/cli/#serve-the-commands-to-an-assistant) | [`desflow mcp`](https://jaehyeon.me/desflow/latest/cli/mcp/index.md) | ## Where to Start A new reader follows one path: [Installation](https://jaehyeon.me/desflow/latest/installation/index.md), then [What Is DES?](https://jaehyeon.me/desflow/latest/learn/what-is-des/index.md), then the tutorial in [Learn](https://jaehyeon.me/desflow/latest/learn/index.md), which starts with [First Simulation](https://jaehyeon.me/desflow/latest/learn/first-model/first-simulation/index.md) and builds one shop model page by page. The table sends a reader with a task of their own to the page that does it. | To | Start with | | ---------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------- | | Learn why desflow exists and what it is for | [Why desflow](https://jaehyeon.me/desflow/latest/about/why-desflow/index.md) | | Find how many packers keep orders from waiting long | [Queues and Capacity](https://jaehyeon.me/desflow/latest/learn/first-model/queues-and-capacity/index.md) | | Stream events to Kafka | [Kafka Digital Twin](https://jaehyeon.me/desflow/latest/gallery/simulation-models/kafka/index.md) | | Write history to Parquet or Iceberg at full speed, then keep streaming | [Parquet History, Kafka Live](https://jaehyeon.me/desflow/latest/gallery/simulation-models/backfill-live/index.md) | | Change parameters during a run | [Live Parameters](https://jaehyeon.me/desflow/latest/user-guide/live-runs-and-connectors/live-parameters/index.md) | | Compare two designs and say which is better | [Comparing Designs](https://jaehyeon.me/desflow/latest/learn/studies/comparing-designs/index.md) | | Fit service times to measured data | [Fitting the Inputs](https://jaehyeon.me/desflow/latest/learn/inputs/fit-the-inputs/index.md) | | Move a SimPy model to desflow | [Coming from SimPy](https://jaehyeon.me/desflow/latest/simpy/coming-from-simpy/index.md) | | Run a study from Airflow, Dagster, Prefect or Kestra | [Integrations](https://jaehyeon.me/desflow/latest/integrations/index.md) | | Give an AI assistant the skill and the desflow commands | [AI Assistants](https://jaehyeon.me/desflow/latest/ai/index.md) | | Find every option of a part of desflow | [User Guide](https://jaehyeon.me/desflow/latest/user-guide/index.md) | | Do one task, step by step | [How-To](https://jaehyeon.me/desflow/latest/how-to/index.md) | | Look up a YAML key or a class | [YAML Keys](https://jaehyeon.me/desflow/latest/reference/yaml-keys/index.md) and [API Reference](https://jaehyeon.me/desflow/latest/reference/api/index.md) | | See public projects that generate their data with desflow | [Projects Using desflow](https://jaehyeon.me/desflow/latest/gallery/projects/index.md) | # Installation # Installation This page installs desflow and runs a first simulation that needs no containers. ## Install the Package Install the core library with uv or pip: ```bash # desflow command uv tool install desflow # Or the library, in a uv project uv add desflow ``` ```bash pip install desflow ``` desflow was called dynamic-des before 0.20.0. The package, the Python module and the command are now all named `desflow`. Version 1.0 removed the `dynamic_des` module and the `ddes` command. Code that imports `dynamic_des` and scripts that run `ddes` must change to `desflow`, and [Upgrading to 1.0](https://jaehyeon.me/desflow/latest/about/upgrading-to-1.0/#removed-names) says what to change. Connectors and input fitting are optional extras. For example, `uv add "desflow[kafka,parquet]"` or `pip install "desflow[kafka,parquet]"`, and `uv tool install "desflow[kafka,parquet]"` for the `desflow` command: | Extra | Adds | | ----------- | ------------------------------------------------------------------------------------------------------------------------------------------------------ | | `kafka` | Kafka ingress and egress | | `confluent` | Avro, JSON Schema and Protobuf with the Confluent Schema Registry (includes `kafka`) | | `glue` | Avro, JSON Schema and Protobuf with the AWS Glue Schema Registry (includes `kafka`) | | `redis` | Redis ingress and egress | | `postgres` | PostgreSQL ingress and egress | | `parquet` | Parquet and JSONL files on local disk, S3-compatible storage, Google Cloud Storage or Azure Blob Storage, and records kept in memory as pyarrow tables | | `iceberg` | Apache Iceberg tables through a REST catalog, a SQL catalog on SQLite or PostgreSQL, or the Glue catalog | | `fit` | scipy and matplotlib, for [input fitting](https://jaehyeon.me/desflow/latest/user-guide/model-parts/input-fitting/index.md) with `desflow fit` | | `fake` | Faker, for the `fake` generator of realistic names, addresses and dates | | `watch` | watchfiles, for `desflow run --watch`, which runs the file again each time it changes | | `mcp` | the MCP Python SDK, for `desflow mcp`, which serves the desflow commands as tools to an AI assistant | | `all` | Every extra above | Two cautions apply to the `fake` extra. A seeded `fake` field gives the same values again only with the same version of Faker, because 1.0 does not record the version. A Faker method that reads the date, such as `date_between`, reads the wall clock and not the simulation clock, so it gives other values on another day. On Python 3.15, the `kafka`, `confluent` and `glue` extras build aiokafka, and the `iceberg` extra builds pyiceberg and zstandard, from source, because those packages publish no wheel for 3.15 yet. A build from source needs a C compiler. Run `desflow` on its own to list its commands. [Command Line](https://jaehyeon.me/desflow/latest/cli/index.md) uses each command on one shop, the model of the `experiment` example, and links the full help of each. ______________________________________________________________________ ## Run an Example The local example models a shop that receives and packs customer orders. The simulation prints events and telemetry to the terminal. The example is written three ways: as a YAML blueprint, with the builder and with the low-level API. Each version runs in real time and ends on its own after 30 seconds. Pick the way you write models, then follow uv or pip: **Quick Start** `desflow examples get` downloads the example at the release you install, into a folder of its own. Pick uv or pip: ```bash # 1. Install uv tool install desflow # 2. Download the example desflow examples get local --api yaml cd local/yaml # 3. Run it desflow run local.yaml ``` ```bash # 1. Install pip install desflow # 2. Download the example desflow examples get local --api yaml cd local/yaml # 3. Run it desflow run local.yaml ``` **Quick Start** `desflow examples get` downloads the example at the release you install, into a folder of its own. Pick uv or pip: ```bash # 1. Install uv tool install desflow # 2. Download the example desflow examples get local --api builder cd local/builder # 3. Run it uv run --no-project --with desflow local_example.py ``` ```bash # 1. Install pip install desflow # 2. Download the example desflow examples get local --api builder cd local/builder # 3. Run it python local_example.py ``` **Quick Start** `desflow examples get` downloads the example at the release you install, into a folder of its own. Pick uv or pip: ```bash # 1. Install uv tool install desflow # 2. Download the example desflow examples get local --api low-level cd local/low-level # 3. Run it uv run --no-project --with desflow local_example.py ``` ```bash # 1. Install pip install desflow # 2. Download the example desflow examples get local --api low-level cd local/low-level # 3. Run it python local_example.py ``` `desflow examples` lists every example. Examples that need Kafka, a database or an object store start it with [odctl](https://github.com/jaehyeon-kim/odctl), and each example page shows how. ______________________________________________________________________ ## Next Steps - **[Learn](https://jaehyeon.me/desflow/latest/learn/index.md):** teaches discrete-event simulation and desflow from the start, through a tutorial that builds one shop model. Follow the tutorial in order. Read the Simulation Concepts pages for the theory after the tutorial, or when a tutorial page links to one. - **[User Guide](https://jaehyeon.me/desflow/latest/user-guide/index.md):** describes each part of desflow, what it does and all its options. Read a page when you need that part. - **[How-To](https://jaehyeon.me/desflow/latest/how-to/index.md):** does one task per page, step by step, from modelling to connectors and analysis. It also holds complete examples to download and run. # Learn # Learn Each page here teaches discrete-event simulation (DES), and how desflow does it, to a reader new to both. What Is DES? explains the idea with no maths. The tutorial then builds one model of a packing shop through a whole study, so read its pages in order. The Simulation Concepts pages explain the theory behind the tutorial's steps. Read them after the tutorial, or when a tutorial page links to one, because they use results from its later pages. If you already know SimPy, start with [Coming from SimPy](https://jaehyeon.me/desflow/latest/simpy/coming-from-simpy/index.md). To look up one part of desflow, see the [User Guide](https://jaehyeon.me/desflow/latest/user-guide/index.md). To do one task step by step, see [How-To](https://jaehyeon.me/desflow/latest/how-to/index.md). ## Tutorial | Group | What it covers | | --------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------- | | [What Is DES?](https://jaehyeon.me/desflow/latest/learn/what-is-des/index.md) | what a discrete-event simulation is, and how it plays out a system one event at a time, with no maths | | [Tutorial: A First Model](https://jaehyeon.me/desflow/latest/learn/first-model/first-simulation/index.md) | a first model of the shop: how many packers it needs, random times and seeds, what a run measures and how a run ends | | [Tutorial: Inputs](https://jaehyeon.me/desflow/latest/learn/inputs/choosing-inputs/index.md) | packing times chosen and fitted from measured data, demand that changes through the day, and a recorded morning replayed | | [Tutorial: Shop Logic](https://jaehyeon.me/desflow/latest/learn/shop-logic/stock/index.md) | stock, priorities, a flow of tasks, waits for signals, patience, interruptions, competing resources and filtered inventory | | [Tutorial: Studies](https://jaehyeon.me/desflow/latest/learn/studies/trusting-results/index.md) | how many runs to trust, comparing designs, parameter sweeps, checking a model, and a complete study from data to recommendation | | [Tutorial: Running Live](https://jaehyeon.me/desflow/latest/learn/running-live/live-changes/index.md) | parameters changed while the model runs, and records streamed out to files | ## Simulation Concepts | Group | What it covers | | ------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------- | | [Queueing Basics](https://jaehyeon.me/desflow/latest/learn/concepts/queueing-basics/index.md) | the results of queueing theory that a study uses: utilisation, Little's law, the effect of variation and the bottleneck | | [A Simulation Study](https://jaehyeon.me/desflow/latest/learn/concepts/a-simulation-study/index.md) | every step of a study, from the question to the report | | [Checking and Validating](https://jaehyeon.me/desflow/latest/learn/concepts/checking-and-validating/index.md) | verification, whether the program does what the model on paper says, and validation, whether the model is close enough to the real system | | [Output Analysis](https://jaehyeon.me/desflow/latest/learn/concepts/output-analysis/index.md) | how runs become an answer with a stated precision: replications, warm-up, intervals and comparing designs | | [Readiness and Reporting](https://jaehyeon.me/desflow/latest/learn/concepts/readiness-and-reporting/index.md) | what a model needs before someone else can trust and repeat it, with the published checklists | | [Common Mistakes](https://jaehyeon.me/desflow/latest/learn/concepts/common-mistakes/index.md) | eight mistakes that give wrong results, in the order they happen in a study | # What Is Discrete-Event Simulation? If you have never used simulation, start here. No maths is needed. A simulation plays out "what would happen if" on a computer, one step at a time, instead of guessing from averages. Think of a packing shop. Orders arrive about every 2 seconds, and a packer takes 1.5 seconds to pack one. Will orders queue in the busy hour? What if a second packer starts at 9:30, or a delivery brings twenty orders at once? You could answer by watching the shop with a notebook. You would not write something down every second, because most seconds nothing changes. You would write only the moments when something happens: an order arrives, a packer starts on it, the order is packed. Each of those moments is an **event**, and the notebook is enough to tell you who waited and for how long. A **discrete-event simulation** (DES) is that notebook, written by a computer. You describe the shop: how often orders come, how long packing takes, how many packers there are. The computer then plays out the events one after another, with random variation as in real life, and writes down what happens. Because it skips the moments when nothing changes, it plays out a day, or a year, in seconds. Change the description, add a packer or double the orders, and run it again to see the difference. desflow does this for any system with arrivals, work and limited capacity: a factory, a warehouse, a shop, a support desk, a network. It also sends every event out as a record, to Kafka, a database or files, so the simulation becomes a source of realistic data. The [tutorial](https://jaehyeon.me/desflow/latest/learn/first-model/first-simulation/index.md) builds the packing shop step by step, and this page explains the ideas it rests on. ______________________________________________________________________ ## Events and the Event List ### In the Tutorial The shop of [First Simulation](https://jaehyeon.me/desflow/latest/learn/first-model/first-simulation/index.md) has one packer, orders about every 2 seconds and 1.5 seconds of packing. Its records show the events: - An order arrives and finds the packer free, so it starts at once. - The next order arrives while the packer is busy, so it joins the queue. - 1.5 seconds after the first order started, it is packed, and the waiting order starts in the same instant. The waiting order's wait is the time from its arrival to that instant. Nothing in the model sets it: the wait comes from when the events fell. The two figures on this page use round times (0.0, 1.5, 2.6 and 4.1 seconds) to show the idea, and First Simulation shows the records of a run. ### Why It Matters A discrete-event simulation models a system as a series of events. Each event happens at an instant, and between two events nothing changes. The simulation therefore visits only the instants when events happen. It keeps a list of the events to come, in time order. It takes the earliest, moves its clock straight to that instant, and carries the event out. Carrying out an event usually schedules more: when a packer starts on an order, the simulation schedules the end of packing 1.5 seconds later. Because the clock jumps, a simulated week with a few thousand events takes only the time needed to compute those events, not a week. Two events can fall at the same instant, as order 1 finishing and order 2 starting do. They run by priority and then in the order they were scheduled, as [Run Length](https://jaehyeon.me/desflow/latest/user-guide/time-and-pacing/run-length/index.md) shows. ### How to Use It You do not write the event list. desflow runs on [SimPy](https://simpy.readthedocs.io/), which keeps the event list and the clock. You describe the arrivals, the work and the resources. desflow adds the parts of a simulation study that you would otherwise write yourself: statistics, repeated runs, comparisons of designs, checks against queueing theory and fits of measured times. The [User Guide](https://jaehyeon.me/desflow/latest/user-guide/index.md) covers each one, and the tutorial introduces them when a question needs them. To see these events yourself, follow [First Simulation](https://jaehyeon.me/desflow/latest/learn/first-model/first-simulation/index.md). It gives the shop's file in three forms, a YAML blueprint, a builder script and a low-level script, and how to install desflow and run each one. All three forms print the same records. ### What the Result Means In the records of First Simulation, read `sim_ts`, the simulation time of each record. It jumps from one event to the next, because nothing happens in between. A run unpaced, with `factor: 0`, gives the same records in a fraction of a second. A run paced to the wall clock gives them in real time, which is how desflow feeds live data to a system that reads it. ______________________________________________________________________ ## Entities, Resources and Queues ### In the Tutorial The orders are the **entities**: the things that flow through the model. Each order arrives, needs a packer, holds the packer while it is packed, and leaves. The packers are a **resource**: something limited that an entity holds while it is served. When every packer is busy, the next order waits in the resource's **queue**. An entity can carry **attributes**: facts about it that stay with it as it moves. [A Flow of Tasks](https://jaehyeon.me/desflow/latest/learn/shop-logic/flow-of-tasks/index.md) marks each order as express or not when it arrives, and marks it as backordered when it was picked from an empty shelf. A rule reads an attribute as `attr.express`. ### Why It Matters The time an entity spends in a model is of two kinds. An **activity** is a period of set length, such as the 1.5 seconds of packing. A **delay** is time spent waiting for something, such as a free packer, and the model does not set its length: it comes from the state of the shop. You describe the activities, and the simulation produces the delays. The wait in the queue is a delay, which is why it is a result and not an input. Two models with the same average times can have very different waits, because a run of quick arrivals or one slow order holds everyone up. A simulation shows that directly, where an average cannot. ### How to Use It A desflow model is built from these parts. An arrival starts entities, a service gives the length of an activity, a resource limits how many are served at once, and a task says what an entity does. [Model Parts](https://jaehyeon.me/desflow/latest/user-guide/model-parts/index.md) covers each one, [Arrivals and Services](https://jaehyeon.me/desflow/latest/user-guide/model-parts/arrivals-and-services/index.md) shows how to set an activity's length, and [Task Flow](https://jaehyeon.me/desflow/latest/user-guide/model-parts/task-flow/#attributes) shows how to set and read attributes. ### What the Result Means The waits and queue lengths a run reports are delays, so they change when anything about the shop changes: the arrival rate, the packing times, their spread or the number of packers. [Queueing Basics](https://jaehyeon.me/desflow/latest/learn/concepts/queueing-basics/index.md) explains how, and which results of queueing theory a model can be checked against. ______________________________________________________________________ ## From Model to Records ### In the Tutorial Each order in First Simulation publishes a `queued` event when it joins the queue, a `started` event when a packer takes it, and an `order_packed` event when it is packed. [Measuring a Run](https://jaehyeon.me/desflow/latest/learn/first-model/measuring-a-run/index.md) adds telemetry: the queue length, the utilisation and the waits, published every 10 seconds. ### Why It Matters A model on its own only moves its clock. What makes it useful here is what it publishes. A sink writes each record to a destination, such as a Kafka topic, a database table or an Iceberg table, so the simulation becomes a source of realistic data for whatever reads it. Whether that data looks real depends on the model being **stable**. If work arrives faster than the resources can finish it, the queue grows without limit and every later event is delayed more. The records then show waits that grow all day, which no real shop would allow. ### How to Use It Add a sink for each destination. [Streaming Out](https://jaehyeon.me/desflow/latest/learn/running-live/streaming-out/index.md) writes the shop's events to files, and [Egress](https://jaehyeon.me/desflow/latest/user-guide/live-runs-and-connectors/egress/index.md) lists every sink. Before a long run, check that every resource's utilisation is below 1, as [Queues and Capacity](https://jaehyeon.me/desflow/latest/learn/first-model/queues-and-capacity/index.md) shows. ### What the Result Means Each record carries the simulation time, the entity's key and what happened. A reader can rebuild every order's path from them, as [Checking and Validating](https://jaehyeon.me/desflow/latest/learn/concepts/checking-and-validating/#read-the-trace) does to check a model. ______________________________________________________________________ ## Terminating or Steady-State ### In the Tutorial The shop opens empty in the morning and closes at the end of the day. A question about one day, such as how many orders are still waiting at closing time, has a natural end: the day. A question about the busy hour, such as the mean wait in the busy hour, when orders arrive faster than the 2 seconds of the quiet shop, is about the shop after its empty start has stopped mattering. ### Why It Matters [Banks et al.'s lecture notes on output analysis](https://courses.grainger.illinois.edu/ece541/fa2016/OutputAnalysis.pdf) separate two kinds of study: - A **[terminating](https://jaehyeon.me/desflow/latest/learn/concepts/output-analysis/#terminating-or-steady-state)** run has a natural end, and its results over that period are the answer. - A **steady-state** study asks how the shop behaves in the long run. The start of each run is left out as a [warm-up](https://jaehyeon.me/desflow/latest/learn/concepts/output-analysis/#one-run-starts-empty), because an empty shop has shorter waits than a busy one. The kind of study decides how long to run, whether to leave out the start, and how many runs to make. ### How to Use It The same model can be run either way. A terminating run ends at the end of the day, and [End Conditions](https://jaehyeon.me/desflow/latest/learn/first-model/end-conditions/index.md) shows how to close the doors and let the last orders finish. A steady-state study sets a warm-up, as [Trusting Results](https://jaehyeon.me/desflow/latest/learn/studies/trusting-results/index.md) does with its 2 minutes. [Run Length](https://jaehyeon.me/desflow/latest/user-guide/time-and-pacing/run-length/index.md) shows how to set the end of a run. ### What the Result Means A terminating result describes that period, with its empty start included. A steady-state result describes the shop once it is busy, and does not say what happens in the first minutes. [Output Analysis](https://jaehyeon.me/desflow/latest/learn/concepts/output-analysis/index.md) explains how to get an interval for either. ______________________________________________________________________ ## Sources - Banks et al., *Discrete-Event System Simulation*, chapter 3, General Principles, read through [lecture notes on that chapter](https://eg.bucknell.edu/~xmeng/Course/CS6337/Note/master/node15.html). - Ingalls, "Introduction to Simulation" (Winter Simulation Conference, 2001), read through [its published text](https://www.informs-sim.org/wsc01papers/002.PDF). - [Banks et al.'s lecture notes on output analysis](https://courses.grainger.illinois.edu/ece541/fa2016/OutputAnalysis.pdf). - The explanations are our own. # First Simulation This tutorial models a shop that receives and packs customer orders: one packer, an order every 2 seconds on average, and 1.5 seconds of packing per order. It answers one question: **how long does an order wait with one packer?** - **Decision:** how many packers the shop needs, which later pages decide. - **Measures:** the wait of each order, from the moment it joins the queue to the moment packing starts. - **Runs:** one run of the first 20 seconds, with the seed 42. - **Assumptions:** orders arrive at random, and every order takes exactly the same time to pack. ## What You Will Learn This page shows how to: - describe a model as an arrival, a resource and a service time, in YAML, the builder or the low-level API; - run it and read the event records it prints; - read an order's wait from its `queued` and `started` events. ## What You Add This page builds the first model of the shop: a simulation called `Shop` with an `orders` arrival, a `packers` resource with one unit, a `packing` service and a `pack_order` task, and a sink that prints each record. The following pages extend the same model, one idea per page. Each step shows the code three ways, in tabs: a **YAML** blueprint, the **Builder** (`SimulationContext`) and the **Low-level** API (`DynamicRealtimeEnvironment` and SimPy processes). Choose the tab for your preferred API; all code tabs on the site switch to that API. The three build the same simulation and print the same records. [Writing a Model](https://jaehyeon.me/desflow/latest/user-guide/writing-a-model/index.md) explains how they relate. Look at the order of the parts: orders arrive, wait in the packer queue and take the packer for 1.5 seconds. The simulation prints a record of each step to the console. The arrival loop and the task read their values from the registry. The steps below explain each of these parts. ______________________________________________________________________ ## Install Install the core package, which includes the `desflow` command, as [Installation](https://jaehyeon.me/desflow/latest/installation/#install-the-package) shows. A blueprint needs only the `desflow` command. Install it with one of these forms, then run the file: ```bash # With uv, the command alone uv tool install desflow # Or with pip pip install desflow # Run the blueprint desflow run first_shop.yaml ``` A builder model is a Python file, so the Python that runs it must be able to import desflow. `uv tool install desflow` installs the command only. Run the file with one of these forms: ```bash # With uv, outside a project uv run --with desflow python first_shop.py # In a uv project, after `uv add desflow` uv run python first_shop.py # After `pip install desflow` python first_shop.py ``` The pages that follow show the plain `python .py` form. Run it with whichever form above you use. A low-level model is a Python file, so the Python that runs it must be able to import desflow. `uv tool install desflow` installs the command only. Run the file with one of these forms: ```bash # With uv, outside a project uv run --with desflow python first_shop_low_level.py # In a uv project, after `uv add desflow` uv run python first_shop_low_level.py # After `pip install desflow` python first_shop_low_level.py ``` The pages that follow show the plain `python .py` form. Run it with whichever form above you use. ______________________________________________________________________ ## Describe the Shop In discrete-event simulation (DES), an **entity** is a thing that moves through the model, here an order. A **resource** is what an entity needs and may have to wait for, here the packer. A **service** time is how long an entity holds the resource, and an **arrival** process sets when entities appear. In desflow, these are parameters of one simulation. Its name, the `sim_id`, is `Shop` here. The shop has a resource called `packers` with one unit, a service called `packing`, and an arrival stream called `orders`. ```yaml simulation: sim_id: Shop factor: 1.0 # 1 simulated second takes 1 real second random_seed: 42 # the same arrival times on every run resources: packers: {current_cap: 1, max_cap: 1} services: # Every order takes exactly 1.5 seconds to pack packing: {dist: constant, value: 1.5} arrivals: # One order every 2 seconds on average; each arrival spawns pack_order orders: {dist: exponential, rate: 0.5, spawn: pack_order} ``` ```python app = ( # 1 simulated second = 1 real second; a seed gives the same arrivals every run SimulationContext(sim_id="Shop", factor=1.0, random_seed=42) .add_resource("packers", current_cap=1, max_cap=1) # Every order takes exactly 1.5 seconds to pack .add_service("packing", dist="constant", value=1.5) # One order every 2 seconds on average .add_arrival("orders", dist="exponential", rate=0.5) ) ``` ```python PARAMS = SimParameter( sim_id="Shop", arrival={"orders": DistributionConfig(dist="exponential", rate=0.5)}, service={"packing": DistributionConfig(dist="constant", value=1.5)}, resources={"packers": CapacityConfig(current_cap=1, max_cap=1)}, ) SEED = 42 # the same arrival times on every run ``` Packing is `constant`, so every order takes 1.5 seconds and only the arrivals are random. The gaps between orders are drawn from an `exponential` distribution with a mean of 2 seconds (30 orders a minute on average), `rate: 0.5`. The seed makes those draws the same on every run, so your trace matches the one below; [Randomness and Seeds](https://jaehyeon.me/desflow/latest/learn/first-model/randomness-and-seeds/index.md) explains it. The registry holds the model's live values: the settings that can change while the simulation runs. Each value has a path, such as `Shop.arrival.orders.rate` or `Shop.resources.packers.current_cap`. A scenario, or a message from outside the simulation, changes a value through its path, and the run goes on with the new value. [Live Changes](https://jaehyeon.me/desflow/latest/learn/running-live/live-changes/index.md) does it on the shop, and [Live Parameters](https://jaehyeon.me/desflow/latest/user-guide/live-runs-and-connectors/live-parameters/index.md) explains how. ______________________________________________________________________ ## Say What an Order Does In DES terms an order **queues** for the packer, **seizes** it when it is free, is **delayed** for the service time, and **releases** the packer. desflow calls this a **task**. A task publishes three events: `queued` when the order joins the queue for the packer, `started` when the packer starts on it, and a finished event when packing ends. The value of the finished event is the task's payload. ```yaml tasks: pack_order: service: packing resource: packers # The value of the finished event payload: {event_type: order_packed} ``` `spawn: pack_order` on the arrival, in the step above, starts the task for every order. ```python @app.task(service_id="packing", resource_id="packers") def pack_order(task_id: int): # Requests a packer, waits the packing time, releases the packer. # The returned dictionary is the value of the finished event. return {"event_type": "order_packed"} @app.arrival_loop("orders") def order_generator(context: SimulationContext): task_id = 0 while True: # Waits for the next arrival and returns the new order, keyed orders-1, ... order = yield context.wait_for_arrival("orders") context.spawn(pack_order(task_id, entity=order)) task_id += 1 ``` `@app.task` publishes the three events and handles the packer for you. The arrival loop waits for each arrival and starts one `pack_order` for the order it returns. ```python def pack_order(env, sampler, packers, key, task_id): """One order: wait for a packer, pack it, release the packer.""" path_id = "Shop.service.packing" def publish(value): env.publish_event(key, value, task="pack_order", instance=task_id) publish( {"path_id": path_id, "sim_id": "Shop", "service": "packing", "status": "queued"} ) with packers.request() as request: yield request publish( { "path_id": path_id, "sim_id": "Shop", "service": "packing", "status": "started", } ) service = env.registry.get_config(path_id) yield env.timeout(sampler.sample(service)) publish({"event_type": "order_packed"}) def order_generator(env, sampler, packers): """Starts one pack_order for every arrival, keyed orders-1, orders-2, ...""" arrival = env.registry.get_config("Shop.arrival.orders") task_id = 0 while True: yield env.timeout(sampler.sample(arrival)) key = f"orders-{task_id + 1}" env.process(pack_order(env, sampler, packers, key, task_id)) task_id += 1 ``` These are SimPy constructs. `pack_order` is a **process**: a generator function that the environment runs, pausing at each `yield` until the event it yielded happens. `env.timeout(...)` is an event that happens after a delay. `packers.request()` is an event that happens when a packer is free, and leaving the `with` block releases the packer. `env.process(...)` starts a process. [SimPy and desflow](https://jaehyeon.me/desflow/latest/simpy/index.md) describes what desflow adds to them. ______________________________________________________________________ ## Print the Records A sink, called an egress, receives every record the simulation publishes. `ConsoleEgress` prints them; [Egress](https://jaehyeon.me/desflow/latest/user-guide/live-runs-and-connectors/egress/index.md) lists the others. ```yaml egress: - {type: Console} ``` ```python app.add_egress(ConsoleEgress()) ``` ```python SINKS = [ConsoleEgress()] # passed to env.setup_egress in run below ``` Every event record carries the order's key, `orders-1` for the first order, so all the events of one order can be found together. `task` names the task, and `instance` counts the task's runs from 0. [Records and Telemetry](https://jaehyeon.me/desflow/latest/reference/records-and-telemetry/index.md) describes every field. ______________________________________________________________________ ## Run It ```yaml run: {until: 20} ``` ```python if __name__ == "__main__": app.run(until=20) ``` ```python def run(until=20, factor=1.0): env = DynamicRealtimeEnvironment(factor=factor, strict=False) env.registry.register_sim_parameter(PARAMS) env.setup_egress(SINKS) packers = DynamicResource(env, "Shop", "packers") sampler = Sampler(seed=SEED) env.process(order_generator(env, sampler, packers)) try: env.run(until=until) finally: env.teardown() return env if __name__ == "__main__": run() ``` Save the files from [Full Files](#full-files) in one folder and run the commands there. `desflow examples` downloads separate examples, not the files of these tutorial pages. Start it from a terminal: ```bash desflow run first_shop.yaml ``` ```bash python first_shop.py ``` ```bash python first_shop_low_level.py ``` At `factor: 1.0` one simulated second takes one real second. The run stops at simulation time 20 (`until: 20`), so it takes 20 real seconds. Each record is one line: `[EVT]` lines are events, and `[TEL]` lines are telemetry. The only telemetry here is `system.simulation.lag_seconds`, published once per simulation second, which says how far the run is behind the wall clock. These are the events of the first 6 seconds: ```text [EVT] {'sim_ts': 0.6283113312939436, 'timestamp': '...', 'key': 'orders-1', 'task': 'pack_order', 'instance': 0, 'value': {'path_id': 'Shop.service.packing', 'sim_id': 'Shop', 'service': 'packing', 'status': 'queued'}} [EVT] {'sim_ts': 0.6283113312939436, 'timestamp': '...', 'key': 'orders-1', 'task': 'pack_order', 'instance': 0, 'value': {'path_id': 'Shop.service.packing', 'sim_id': 'Shop', 'service': 'packing', 'status': 'started'}} [EVT] {'sim_ts': 2.1283113312939435, 'timestamp': '...', 'key': 'orders-1', 'task': 'pack_order', 'instance': 0, 'value': {'event_type': 'order_packed'}} [EVT] {'sim_ts': 4.934338901219139, 'timestamp': '...', 'key': 'orders-2', 'task': 'pack_order', 'instance': 1, 'value': {'path_id': 'Shop.service.packing', 'sim_id': 'Shop', 'service': 'packing', 'status': 'queued'}} [EVT] {'sim_ts': 4.934338901219139, 'timestamp': '...', 'key': 'orders-2', 'task': 'pack_order', 'instance': 1, 'value': {'path_id': 'Shop.service.packing', 'sim_id': 'Shop', 'service': 'packing', 'status': 'started'}} [EVT] {'sim_ts': 5.0244486188135875, 'timestamp': '...', 'key': 'orders-3', 'task': 'pack_order', 'instance': 2, 'value': {'path_id': 'Shop.service.packing', 'sim_id': 'Shop', 'service': 'packing', 'status': 'queued'}} ``` Read `sim_ts`, the simulation time of each record. It does not count up in small steps: it jumps from 0.628 to 2.128, then to 4.934 and 5.024. The simulation clock moves straight to the time of the next event, because nothing changes between two events. At `factor: 0` the same run takes a fraction of a second, with the same records. `timestamp` is the date and time of the record: it counts from the moment the simulation is created, so it differs on every run, and this page shows it as `...`. [Logical Start Time](https://jaehyeon.me/desflow/latest/user-guide/time-and-pacing/clocks-and-pacing/#logical-start-time) sets a fixed date instead. `--sample 5` shows the first records without waiting and without changing the file. It runs the blueprint unpaced, as fast as it can, prints its first 5 events to stdout as JSON lines (one record per line), and stops: ```bash desflow run first_shop.yaml --sample 5 ``` ```text {"stream_type":"event","sim_ts":0.6283113312939436,"timestamp":"...","key":"orders-1","task":"pack_order","instance":0,"value":{"path_id":"Shop.service.packing","sim_id":"Shop","service":"packing","status":"queued"}} {"stream_type":"event","sim_ts":0.6283113312939436,"timestamp":"...","key":"orders-1","task":"pack_order","instance":0,"value":{"path_id":"Shop.service.packing","sim_id":"Shop","service":"packing","status":"started"}} {"stream_type":"event","sim_ts":2.1283113312939435,"timestamp":"...","key":"orders-1","task":"pack_order","instance":0,"value":{"event_type":"order_packed"}} {"stream_type":"event","sim_ts":4.934338901219139,"timestamp":"...","key":"orders-2","task":"pack_order","instance":1,"value":{"path_id":"Shop.service.packing","sim_id":"Shop","service":"packing","status":"queued"}} {"stream_type":"event","sim_ts":4.934338901219139,"timestamp":"...","key":"orders-2","task":"pack_order","instance":1,"value":{"path_id":"Shop.service.packing","sim_id":"Shop","service":"packing","status":"started"}} ``` They are the first five events above, each printed as the whole record, with its `stream_type`. The run's log stays on stderr, so a pipe such as `| jq .key` reads only the records. [YAML Blueprints](https://jaehyeon.me/desflow/latest/user-guide/writing-a-model/blueprints/#preview-the-records) lists the other ways to run a blueprint. While you edit the file, `desflow run first_shop.yaml --sample 5 --watch` runs it again each time the file changes. `--watch` needs the `watch` extra: `pip install "desflow[watch]"`, or `uv tool install "desflow[watch]"` for the command. `desflow check first_shop.yaml` loads the file and reports its mistakes without running it, which is cheaper than finding them after a long run. It prints `ok` and the `sim_id` for a valid file. `desflow` on its own lists every command, grouped by what it does, with examples. `desflow run --help` lists the options of `run`, also with examples. [Command Line](https://jaehyeon.me/desflow/latest/cli/index.md) uses every command on one shop. ______________________________________________________________________ ## Test the Model A blueprint can hold the answers you expect from it. A `tests` entry names a seed and an end time (both default to the file's own) and the statistics the run must give. `desflow test` runs each entry once, unpaced and with no sink, so it contacts no service, and reports each statistic that differs: ```yaml tests: # Run with: desflow test first_shop.yaml - name: seven_orders_in_20_seconds expect: {tasks.pack_order.finished: 7} ``` A builder file reads its tests from a `tests.yaml` in the same folder, with the same entries. A low-level script has no `desflow test`. [Test a Model](https://jaehyeon.me/desflow/latest/how-to/analysis/test-a-model/index.md) tests it with pytest. ```bash desflow test first_shop.yaml ``` ```text ok first_shop.yaml: seven_orders_in_20_seconds ``` Seven orders are packed in the first 20 seconds with the seed 42. A number is compared exactly. `{value: 7, within: 1}` allows a difference. The seed and the desflow version are part of the answer: after an upgrade, `desflow test --fix` writes the new numbers, and you read them before you keep them. [Test a Model](https://jaehyeon.me/desflow/latest/how-to/analysis/test-a-model/index.md) shows more. ______________________________________________________________________ ## What You Get and Why How long does an order wait with one packer? It depends on how many orders are ahead of it, as the same records on a timeline show: each order waits (yellow) until the packer is free, then holds it for 1.5 seconds of packing (blue). These records come from one run of the first 20 seconds, with the seed 42. `orders-1` and `orders-2` find the packer free, so their `queued` and `started` events have the same time. `orders-3` is the first order that has to wait: it is `queued` at 5.024 and `started` at 6.434, when `orders-2` finishes. **It waits 1.410 seconds.** `orders-4` arrives while `orders-3` is waiting and waits longer, 1.684 seconds, because two orders are ahead of it. So with one packer, an order that arrives while the packer is busy waits until every order ahead of it has been packed. The wait depends on when orders happen to arrive, which is why the next pages measure it over many orders. A discrete-event simulation keeps a list of future events, ordered by time. It takes the earliest one, moves the clock to its time, and runs what it triggers, which may add new events to the list: an arrival schedules the next arrival, and a start of packing schedules its end 1.5 seconds later. The trace above is that list, read in order. [What Is DES?](https://jaehyeon.me/desflow/latest/learn/what-is-des/index.md) explains the event list in more detail. ## Key Takeaways - A model has entities that arrive, resources they wait for, and service times that hold them. desflow calls the work an entity does a task. - A task publishes `queued`, `started` and a finished event, and an order's wait is its `started` time minus its `queued` time. - The simulation clock jumps from one event to the next, so a run gives the same records at any pace. ______________________________________________________________________ ## Full Files Full files The complete first shop, which the documentation tests run: ```yaml # First Simulation tutorial: the shop as a blueprint. # Run it with: desflow run first_shop.yaml simulation: sim_id: Shop factor: 1.0 # 1 simulated second takes 1 real second random_seed: 42 # the same arrival times on every run resources: packers: {current_cap: 1, max_cap: 1} services: # Every order takes exactly 1.5 seconds to pack packing: {dist: constant, value: 1.5} arrivals: # One order every 2 seconds on average; each arrival spawns pack_order orders: {dist: exponential, rate: 0.5, spawn: pack_order} tasks: pack_order: service: packing resource: packers # The value of the finished event payload: {event_type: order_packed} egress: - {type: Console} run: {until: 20} tests: # Run with: desflow test first_shop.yaml - name: seven_orders_in_20_seconds expect: {tasks.pack_order.finished: 7} ``` ```python """The First Simulation tutorial: the shop, with the SimulationContext builder. One packer, orders arriving about every 2 seconds, and 1.5 seconds of packing per order. Every record is printed to the terminal. """ import logging from desflow import ConsoleEgress, SimulationContext logging.basicConfig( level=logging.INFO, format="%(levelname)s [%(asctime)s] %(message)s" ) app = ( # 1 simulated second = 1 real second; a seed gives the same arrivals every run SimulationContext(sim_id="Shop", factor=1.0, random_seed=42) .add_resource("packers", current_cap=1, max_cap=1) # Every order takes exactly 1.5 seconds to pack .add_service("packing", dist="constant", value=1.5) # One order every 2 seconds on average .add_arrival("orders", dist="exponential", rate=0.5) ) @app.task(service_id="packing", resource_id="packers") def pack_order(task_id: int): # Requests a packer, waits the packing time, releases the packer. # The returned dictionary is the value of the finished event. return {"event_type": "order_packed"} @app.arrival_loop("orders") def order_generator(context: SimulationContext): task_id = 0 while True: # Waits for the next arrival and returns the new order, keyed orders-1, ... order = yield context.wait_for_arrival("orders") context.spawn(pack_order(task_id, entity=order)) task_id += 1 app.add_egress(ConsoleEgress()) if __name__ == "__main__": app.run(until=20) ``` ```python """The First Simulation tutorial: the shop, on the low-level API. One packer, orders arriving about every 2 seconds, and 1.5 seconds of packing per order. Every record is printed to the terminal. """ import logging from desflow import ( CapacityConfig, ConsoleEgress, DistributionConfig, DynamicRealtimeEnvironment, DynamicResource, Sampler, SimParameter, ) logging.basicConfig( level=logging.INFO, format="%(levelname)s [%(asctime)s] %(message)s" ) PARAMS = SimParameter( sim_id="Shop", arrival={"orders": DistributionConfig(dist="exponential", rate=0.5)}, service={"packing": DistributionConfig(dist="constant", value=1.5)}, resources={"packers": CapacityConfig(current_cap=1, max_cap=1)}, ) SEED = 42 # the same arrival times on every run def pack_order(env, sampler, packers, key, task_id): """One order: wait for a packer, pack it, release the packer.""" path_id = "Shop.service.packing" def publish(value): env.publish_event(key, value, task="pack_order", instance=task_id) publish( {"path_id": path_id, "sim_id": "Shop", "service": "packing", "status": "queued"} ) with packers.request() as request: yield request publish( { "path_id": path_id, "sim_id": "Shop", "service": "packing", "status": "started", } ) service = env.registry.get_config(path_id) yield env.timeout(sampler.sample(service)) publish({"event_type": "order_packed"}) def order_generator(env, sampler, packers): """Starts one pack_order for every arrival, keyed orders-1, orders-2, ...""" arrival = env.registry.get_config("Shop.arrival.orders") task_id = 0 while True: yield env.timeout(sampler.sample(arrival)) key = f"orders-{task_id + 1}" env.process(pack_order(env, sampler, packers, key, task_id)) task_id += 1 SINKS = [ConsoleEgress()] # passed to env.setup_egress in run below def run(until=20, factor=1.0): env = DynamicRealtimeEnvironment(factor=factor, strict=False) env.registry.register_sim_parameter(PARAMS) env.setup_egress(SINKS) packers = DynamicResource(env, "Shop", "packers") sampler = Sampler(seed=SEED) env.process(order_generator(env, sampler, packers)) try: env.run(until=until) finally: env.teardown() return env if __name__ == "__main__": run() ``` # Queues and Capacity In its busy hour the shop gets 1.8 orders a second, and packing still takes 1.5 seconds. One packer cannot keep up. This page asks: **how many packers keep the mean wait under 10 seconds?** - **Decision:** the number of packers for the busy hour. - **Measures:** the packers' [utilisation](https://jaehyeon.me/desflow/latest/learn/concepts/queueing-basics/#utilisation) and the mean wait. - **Runs:** four runs of the hour, one for each number of packers, each with the seed 42. - **Assumptions:** orders arrive at random at a steady rate, and every order takes the same time to pack. ## What You Will Learn This page shows how to: - work out a resource's utilisation before running the model; - read the load, the stability and the bottleneck with `desflow explain`; - choose the fewest packers that keep the mean wait short. ## What You Add This page adds more orders, then more packers, and `desflow explain`, which works out the load from the model before it runs. The shop is the one from [First Simulation](https://jaehyeon.me/desflow/latest/learn/first-model/first-simulation/index.md), with the arrival rate of the busy hour and the number of packers as a setting you change between runs. ______________________________________________________________________ ## Work Out the Load Before running anything, work out how busy the packers would be. **[Utilisation](https://jaehyeon.me/desflow/latest/learn/concepts/queueing-basics/#utilisation)** is the share of time a resource is busy: > utilisation = arrival rate × mean service time ÷ number of units The **load** is the part above the division: arrival rate × mean service time. Here it is 1.8 orders a second × 1.5 seconds = 2.7, so each second brings 2.7 seconds of packing, enough work for 2.7 packers. One packer would be busy 270% of the time, which is impossible: it falls further behind with every order. - With utilisation below 1 a model is **stable**: the queue rises and falls, but stays bounded. - At 1 or above it is not: the queue grows for as long as the run lasts, and every order waits longer than the one before. The shop needs at least 3 packers, the fewest that bring utilisation below 1: 2.7 ÷ 3 = 0.9. [Queueing Basics](https://jaehyeon.me/desflow/latest/learn/concepts/queueing-basics/index.md) explains utilisation, and why the queue grows without limit at 1 or above. Each resource in a model has its own utilisation. The one with the highest utilisation is the **[bottleneck](https://jaehyeon.me/desflow/latest/learn/concepts/queueing-basics/#flow-balance-and-the-bottleneck)**: it decides how long everything waits. Here is the busy hour. The arrival rate is 1.8 orders a second, and `until` is one hour of simulation time: ```yaml simulation: sim_id: Shop factor: 0 # unpaced: the hour runs in about a second random_seed: 42 services: packing: {dist: constant, value: 1.5 s} arrivals: # The busy hour: 1.8 orders a second, more than one packer can pack orders: {dist: exponential, rate: 1.8, spawn: pack_order} tasks: pack_order: service: packing resource: packers payload: {event_type: order_packed} egress: - {type: Console} run: {until: 1 h} ``` ```python app = SimulationContext(sim_id="Shop", factor=0, random_seed=42) # unpaced app.add_service("packing", dist="constant", value=1.5) # The busy hour: 1.8 orders a second, more than one packer can pack. Each # order starts the task pack_order. app.add_arrival("orders", dist="exponential", rate=1.8, spawn="pack_order") ``` `spawn="pack_order"` starts the task for each arrival, as `spawn:` does in YAML, so this page needs no `@app.arrival_loop`. ```python service={"packing": DistributionConfig(dist="constant", value=1.5)}, # The busy hour: 1.8 orders a second, more than one packer can pack arrival={"orders": DistributionConfig(dist="exponential", rate=1.8)}, ``` A blueprint accepts a duration with a unit wherever it takes a time, such as `until: 1 h` and `value: 1.5 s`, and reads a plain number as seconds. A text that is a plain number, such as `"5"` or `"1e-3"`, is read as seconds too. `factor: 0` runs the hour unpaced: as fast as the computer can, in about a second. Nobody needs to watch this run in real time. ______________________________________________________________________ ## Explain the Load `desflow explain` does this arithmetic from a YAML or builder model, without running it. It reads three numbers for each resource and works out the fourth: - **λ** (lambda), the arrival rate: `rate: 1.8` of `arrivals.orders`; - **μ** (mu), the service rate, one over the mean service time: `value: 1.5 s` of `services.packing` gives 1 ÷ 1.5 = 0.667 orders a second for each packer, one order every 1.5 seconds (40 a minute); - **c**, the number of units: `current_cap` of `resources.packers`; - **ρ** (rho), the utilisation: λ ÷ (c × μ). Save the files from [Full Files](#full-files) in one folder and run the commands there. ```bash desflow explain queues_and_capacity.yaml ``` The file is `queues_and_capacity.yaml` from [Full Files](#full-files). Its number of packers comes from the variable `PACKERS`, which [Run It With More Packers](#run-it-with-more-packers) sets. With `PACKERS` not set, the shop has one packer. ```python def explain(packers: int) -> str: """The busy hour with `packers` packers, as `desflow explain` prints it.""" return render_terminal(shop(packers).analyze()) ``` `context.analyze()` returns the same analysis as an `Explanation`, and `render_terminal` prints it as the command does. `desflow explain` also loads a builder Python file that defines a `SimulationContext` at module level. `desflow explain` does not support low-level models. It reads which arrival starts which task and which resource each task uses, and a low-level model does not declare those links: its SimPy code makes them as it runs. For a YAML or builder model, it prints the graph from each arrival, the resources, the utilisation at each number of units the resource allows, and hints: ```text Shop `-- orders (arrival, rate 1.8/s) `-- spawn -> pack_order (task, rate 1.8/s) +-- uses packers (resource) `-- next (share 1) -> exit Resources +-------------------------------------------------------+ | resource | λ | μ | c | ρ | Wq | L | status | |----------+-----+--------+---+-----+----+---+----------| | packers | 1.8 | 0.6667 | 1 | 2.7 | - | - | UNSTABLE | +-------------------------------------------------------+ packers by units +-------------------------+ | c | ρ | status | |----+--------+-----------| | 1 | 2.7 | UNSTABLE | | 2 | 1.35 | UNSTABLE | | 3 | 0.9 | CONGESTED | | 4 | 0.675 | OK | | 5 | 0.54 | OK | | 6 | 0.45 | OK | | 7 | 0.3857 | OK | | 8 | 0.3375 | OK | | 9 | 0.3 | OK | | 10 | 0.27 | OK | +-------------------------+ Bottleneck: packers Not estimated: wait at packers: unstable: the queue grows for as long as the run lasts Hints for utilisation 0.85: packers with 4 units: utilisation 0.675, at most 0.85 packers with 1 unit: utilisation 0.85 at a request every 1.76 seconds (34 a minute, 0.5667 a second) ``` The output has four parts: - The tree shows each order starting `pack_order`, which uses `packers`, and the flow ending after it. - The resources table gives λ (the arrival rate) 1.8 orders a second, μ (the rate one packer serves) 0.667 orders a second, c (the number of packers) 1 and utilisation ρ 2.7. The status is `CONGESTED` from utilisation 0.85 and `UNSTABLE` from 1, so it is `UNSTABLE`. The wait (`Wq`) and the number in the shop (`L`) are left blank, and the reason is printed below the tables: the queue grows for as long as the run lasts. - The table by units covers 1 to 10 packers, up to `max_cap`. Three packers are stable but congested at utilisation 0.9. - The first hint names 4 as the fewest packers at or below 0.85. The second hint keeps the current number of units. It gives the rate of requests into the resource at which utilisation reaches the target. With one packer, an arrival rate of 0.5667 orders a second, an order every 1.76 seconds (34 a minute), gives utilisation 0.85. In a network, that rate includes the requests that come back for rework, not only new arrivals. ______________________________________________________________________ ## Run It With More Packers The number of packers is the resource's `current_cap`. Each run sets it once: ```yaml resources: # The number of packers comes from the PACKERS variable, 1 when it is not set packers: current_cap: ${PACKERS:-1} max_cap: 10 ``` `${PACKERS:-1}` reads the environment variable `PACKERS`, and uses 1 when it is not set. ```python app.add_resource("packers", current_cap=packers, max_cap=10) ``` ```python resources={"packers": CapacityConfig(current_cap=packers, max_cap=10)}, ``` A `DynamicResource` with a `current_cap` of 3 behaves like a SimPy resource with three units: a request is granted as soon as any unit is free, so up to three orders are packed at once. [Resources](https://jaehyeon.me/desflow/latest/user-guide/resources/index.md) describes how it is built and why. `env.run(until=...)` runs [SimPy's event loop](https://jaehyeon.me/desflow/latest/simpy/#environment-and-the-event-list) until that time. `DynamicRealtimeEnvironment` is desflow's form of [SimPy's `RealtimeEnvironment`](https://jaehyeon.me/desflow/latest/simpy/#real-time-environment). A resource's capacity is its [number of units](https://jaehyeon.me/desflow/latest/simpy/#resources). To read the mean wait, switch on the built-in statistics at the `typical` level, which keeps the mean wait of every task; [Measuring a Run](https://jaehyeon.me/desflow/latest/learn/first-model/measuring-a-run/index.md) explains the levels. ```yaml # The mean wait of pack_order, published once an hour and at the end stats: {level: typical, interval: 1 h} ``` ```python # The mean wait of pack_order, kept by the run and read at the end app.with_stats("typical", interval=3600) ``` ```python # The mean wait of pack_order, kept by the environment and read at the end env.setup_stats("Shop", "typical", interval=3600) ``` A low-level process has no task for desflow to watch, so on this page it reports to `env.stats` itself instead of publishing events: it calls `task_queued`, `task_started` and `task_finished` with the task's name and instance id. [Measuring a Run](https://jaehyeon.me/desflow/latest/learn/first-model/measuring-a-run/index.md) explains these calls. Now run the hour with 1, 2, 3 and 4 packers: At the end, the run publishes the mean wait as `Shop.stats.tasks.pack_order.wait_mean`, among all its other records. `--stdout` prints the records as JSON lines, `grep` keeps the mean wait, and `tail -1` keeps its last reading: ```bash # The mean wait with one to four packers for n in 1 2 3 4; do PACKERS=$n desflow run queues_and_capacity.yaml --stdout | grep -E 'pack_order\.wait_mean"' | tail -1 done ``` ```python def mean_wait(packers: int) -> float: """Runs the busy hour with `packers` packers and returns the mean wait.""" app = shop(packers) app.run(until=UNTIL) return app.env.stats.readings()["Shop.stats.tasks.pack_order.wait_mean"] if __name__ == "__main__": for packers in range(1, 5): print(f"packers {packers}: mean wait {mean_wait(packers):8.2f} s") ``` ```python def mean_wait(packers: int) -> float: """Runs the busy hour with `packers` packers and returns the mean wait.""" env = run(packers) return env.stats.readings()["Shop.stats.tasks.pack_order.wait_mean"] if __name__ == "__main__": for packers in range(1, 5): print(f"packers {packers}: mean wait {mean_wait(packers):8.2f} s") ``` Each tab prints the mean wait with 1, 2, 3 and 4 packers: ```text {"stream_type":"telemetry","sim_ts":3600.0,"timestamp":"...","path_id":"Shop.stats.tasks.pack_order.wait_mean","value":1139.8758548010155} {"stream_type":"telemetry","sim_ts":3600.0,"timestamp":"...","path_id":"Shop.stats.tasks.pack_order.wait_mean","value":484.65045270890204} {"stream_type":"telemetry","sim_ts":3600.0,"timestamp":"...","path_id":"Shop.stats.tasks.pack_order.wait_mean","value":1.8791946460820799} {"stream_type":"telemetry","sim_ts":3600.0,"timestamp":"...","path_id":"Shop.stats.tasks.pack_order.wait_mean","value":0.24164977417889455} ``` ```bash python queues_and_capacity.py 2>/dev/null ``` ```text packers 1: mean wait 1139.88 s packers 2: mean wait 484.65 s packers 3: mean wait 1.88 s packers 4: mean wait 0.24 s ``` ```bash python queues_and_capacity_low_level.py 2>/dev/null ``` ```text packers 1: mean wait 1139.88 s packers 2: mean wait 484.65 s packers 3: mean wait 1.88 s packers 4: mean wait 0.24 s ``` ______________________________________________________________________ ## Waits Near Full Use With 2 packers, utilisation is 1.35. The queue grows all hour, so the mean wait depends mainly on how long the run was: run two hours and it roughly doubles. With 3 packers, utilisation is 0.9 and the wait settles. With 4 it is 0.675, and almost nobody waits. A stable model can still wait a long time, because the wait grows much faster than utilisation near 1, and variable times make it longer still. [Queueing Basics](https://jaehyeon.me/desflow/latest/learn/concepts/queueing-basics/#waits-near-full-use) gives the formulas for one packer, the effect of variation and Little's law, and checks them against runs of this shop. `desflow explain` uses them, and [Choosing Inputs](https://jaehyeon.me/desflow/latest/learn/inputs/choosing-inputs/index.md) measures the wait with constant, triangular, empirical and exponential packing times. ______________________________________________________________________ ## Find the Bottleneck The **bottleneck** is the resource with the highest utilisation. Relieving it makes the next busiest resource the new bottleneck. In a shop with one resource that is the packer. In a shop with several tasks, `desflow explain` finds it from each task's rate, as [A Flow of Tasks](https://jaehyeon.me/desflow/latest/learn/shop-logic/flow-of-tasks/#networks-and-bottlenecks) shows for a shop with a checker and rework. The hints that `desflow explain` prints for tuning a resource, and its `--target` option, are in [Check It Before a Long Run](https://jaehyeon.me/desflow/latest/cli/#check-it-before-a-long-run). ______________________________________________________________________ ## What You Get and Why How many packers keep the mean wait under 10 seconds? **3 packers**, as the mean wait for 1 to 4 packers shows: With 3 packers the mean wait is 1.88 seconds, from [one run of the hour](https://jaehyeon.me/desflow/latest/learn/concepts/output-analysis/#busy-hour-figures) with constant packing and the seed 42. With 2 packers it is over 400 seconds and still growing when the hour ends. The answer is the fewest packers that bring utilisation below 1. At utilisation 0.9 the wait stays under 10 seconds, because the shop's packing time is constant and 0.9 is not yet close enough to 1. [Queueing Basics](https://jaehyeon.me/desflow/latest/learn/concepts/queueing-basics/index.md) explains why the wait grows without limit as utilisation reaches 1, as the table shows for 1 and 2 packers. It also gives the formula for several packers sharing one queue. Each term of the utilisation is a live parameter, so a running model can be relieved, or overloaded on purpose, as [Live Parameters](https://jaehyeon.me/desflow/latest/user-guide/live-runs-and-connectors/live-parameters/index.md) shows. [Statistics](https://jaehyeon.me/desflow/latest/user-guide/results/statistics/index.md) describes how the mean wait is measured. The formulas describe a queue that has settled. A run starts with no orders in the shop, so its early waits are shorter than the settled waits. A live change, such as a rush, makes the waits rise, and they take time to settle again. [Trusting Results](https://jaehyeon.me/desflow/latest/learn/studies/trusting-results/index.md) shows how to leave out a [warm-up](https://jaehyeon.me/desflow/latest/learn/concepts/output-analysis/#one-run-starts-empty) and how long to run. ## Key Takeaways - Utilisation is the arrival rate times the mean service time, divided by the number of units. Below 1 the queue settles; at 1 or above it grows for as long as the run lasts. - Near utilisation 1 the wait grows much faster than the utilisation, and variable times make it longer still. - The resource with the highest utilisation is the bottleneck. Relieving it makes the next busiest resource the bottleneck. ______________________________________________________________________ ## Full Files Full files ```yaml # The Queues and Capacity tutorial: the shop in its busy hour, as a blueprint. # Run it once per number of packers, and read the mean wait from the last lines: # PACKERS=3 desflow run queues_and_capacity.yaml 2>&1 | grep wait_mean simulation: sim_id: Shop factor: 0 # unpaced: the hour runs in about a second random_seed: 42 services: packing: {dist: constant, value: 1.5 s} arrivals: # The busy hour: 1.8 orders a second, more than one packer can pack orders: {dist: exponential, rate: 1.8, spawn: pack_order} tasks: pack_order: service: packing resource: packers payload: {event_type: order_packed} egress: - {type: Console} run: {until: 1 h} resources: # The number of packers comes from the PACKERS variable, 1 when it is not set packers: current_cap: ${PACKERS:-1} max_cap: 10 # The mean wait of pack_order, published once an hour and at the end stats: {level: typical, interval: 1 h} ``` ```yaml # Queues and Capacity: the busy shop as a network. Packed orders are checked, and # one in ten goes back to be packed again. # Explain it with: desflow explain queues_network.yaml simulation: {sim_id: Shop, factor: 0, random_seed: 42} arrivals: orders: {dist: exponential, rate: 1.6, spawn: pack_order} services: packing: {dist: constant, value: 1.5 s} checking: {dist: exponential, rate: 2.5} # 0.4 s on average resources: packers: {current_cap: 4, max_cap: 10} checkers: {current_cap: 1, max_cap: 4} tasks: pack_order: service: packing resource: packers payload: {event_type: order_packed} next: check_order check_order: service: checking resource: checkers payload: {event_type: order_checked} # Nine in ten pass; the tenth is packed again next: weights: {ship_order: 9, pack_order: 1} ship_order: payload: {event_type: order_shipped} egress: - {type: Console} run: {until: 1 h} ``` ```python """The Queues and Capacity tutorial: the shop's busy hour, with the builder. Orders arrive at 1.8 a second and each takes 1.5 seconds to pack. `explain` prints what `desflow explain` prints for the shop. The script runs the hour once for each number of packers, unpaced, and prints the mean wait of each run. `network` is the shop with a checker and rework. """ from desflow import SimulationContext from desflow.explain import render_terminal UNTIL = "1 h" # the busy hour def shop(packers: int) -> SimulationContext: """The shop in its busy hour, with `packers` packers.""" app = SimulationContext(sim_id="Shop", factor=0, random_seed=42) # unpaced app.add_service("packing", dist="constant", value=1.5) # The busy hour: 1.8 orders a second, more than one packer can pack. Each # order starts the task pack_order. app.add_arrival("orders", dist="exponential", rate=1.8, spawn="pack_order") app.add_resource("packers", current_cap=packers, max_cap=10) # The mean wait of pack_order, kept by the run and read at the end app.with_stats("typical", interval=3600) @app.task(service_id="packing", resource_id="packers") def pack_order(task_id): return {"event_type": "order_packed"} return app def explain(packers: int) -> str: """The busy hour with `packers` packers, as `desflow explain` prints it.""" return render_terminal(shop(packers).analyze()) def network() -> SimulationContext: """The busy shop as a network: packed orders are checked, one in ten packed again.""" app = SimulationContext(sim_id="Shop", factor=0, random_seed=42) app.add_arrival("orders", dist="exponential", rate=1.6, spawn="pack_order") app.add_service("packing", dist="constant", value=1.5) app.add_service("checking", dist="exponential", rate=2.5) # 0.4 s on average app.add_resource("packers", current_cap=4, max_cap=10) app.add_resource("checkers", current_cap=1, max_cap=4) @app.task(service_id="packing", resource_id="packers", next="check_order") def pack_order(task_id): return {"event_type": "order_packed"} # Nine in ten pass; the tenth is packed again @app.task( service_id="checking", resource_id="checkers", next={"weights": {"ship_order": 9, "pack_order": 1}}, ) def check_order(task_id): return {"event_type": "order_checked"} @app.task() def ship_order(task_id): return {"event_type": "order_shipped"} # print(render_terminal(app.analyze())) prints what desflow explain prints return app def mean_wait(packers: int) -> float: """Runs the busy hour with `packers` packers and returns the mean wait.""" app = shop(packers) app.run(until=UNTIL) return app.env.stats.readings()["Shop.stats.tasks.pack_order.wait_mean"] if __name__ == "__main__": for packers in range(1, 5): print(f"packers {packers}: mean wait {mean_wait(packers):8.2f} s") ``` ```python """The Queues and Capacity tutorial: the shop's busy hour, on the low-level API. Orders arrive at 1.8 a second and each takes 1.5 seconds to pack. The script runs the hour once for each number of packers, unpaced, and prints the mean wait of each run. `run_network` is the shop with a checker and rework. """ import itertools from desflow import ( CapacityConfig, DistributionConfig, DynamicRealtimeEnvironment, DynamicResource, Router, Sampler, SimParameter, Upstream, ) UNTIL = 3600 # the busy hour, in seconds def params(packers: int) -> SimParameter: """The shop in its busy hour, with `packers` packers.""" return SimParameter( sim_id="Shop", service={"packing": DistributionConfig(dist="constant", value=1.5)}, # The busy hour: 1.8 orders a second, more than one packer can pack arrival={"orders": DistributionConfig(dist="exponential", rate=1.8)}, resources={"packers": CapacityConfig(current_cap=packers, max_cap=10)}, ) def pack_order(env, sampler, packers, task_id): """One order, which reports each step to the statistics.""" path_id = "Shop.service.packing" env.stats.task_queued("pack_order", task_id) with packers.request() as request: yield request env.stats.task_started("pack_order", task_id) yield env.timeout(sampler.sample(env.registry.get_config(path_id))) env.stats.task_finished("pack_order", task_id) def order_generator(env, sampler, packers): arrival = env.registry.get_config("Shop.arrival.orders") task_id = 0 while True: yield env.timeout(sampler.sample(arrival)) env.process(pack_order(env, sampler, packers, task_id)) task_id += 1 def run(packers: int, until=UNTIL, factor=0.0): """Runs the busy hour with `packers` packers, unpaced, and returns the environment.""" env = DynamicRealtimeEnvironment(factor=factor) env.registry.register_sim_parameter(params(packers)) # The mean wait of pack_order, kept by the environment and read at the end env.setup_stats("Shop", "typical", interval=3600) packers_resource = DynamicResource(env, "Shop", "packers") sampler = Sampler(seed=42) env.process(order_generator(env, sampler, packers_resource)) try: env.run(until=until) finally: env.teardown() return env NETWORK = SimParameter( sim_id="Shop", arrival={"orders": DistributionConfig(dist="exponential", rate=1.6)}, service={ "packing": DistributionConfig(dist="constant", value=1.5), # One check takes 0.4 s on average "checking": DistributionConfig(dist="exponential", rate=2.5), }, resources={ "packers": CapacityConfig(current_cap=4, max_cap=10), "checkers": CapacityConfig(current_cap=1, max_cap=4), }, ) # Each task's service and resource, and the task after it STEPS = { "pack_order": ("packing", "packers", Router("check_order")), # Nine in ten pass; the tenth is packed again "check_order": ( "checking", "checkers", Router({"weights": {"ship_order": 9, "pack_order": 1}}), ), "ship_order": (None, None, Router(None)), } def step(env, sampler, shop, name, entity, counters): """One task of an order, then the task its router chooses.""" service, resource, router = STEPS[name] task_id = next(counters[name]) if resource is None: env.stats.task_finished(name, task_id) else: env.stats.task_queued(name, task_id) with shop[resource].request() as request: yield request env.stats.task_started(name, task_id) config = env.registry.get_config(f"Shop.service.{service}") yield env.timeout(sampler.sample(config)) env.stats.task_finished(name, task_id) following = router.choose(Upstream(task_id, entity, {}, {}), env) if following is None: env.stats.flow_finished("orders") else: yield from step(env, sampler, shop, following, entity, counters) def network_orders(env, sampler, shop, counters): arrival = env.registry.get_config("Shop.arrival.orders") for number in itertools.count(1): yield env.timeout(sampler.sample(arrival)) env.stats.flow_started("orders") env.process( step(env, sampler, shop, "pack_order", f"orders-{number}", counters) ) def run_network(until=UNTIL): """Runs the network for the hour, unpaced, and returns the environment.""" env = DynamicRealtimeEnvironment(factor=0.0) env.registry.register_sim_parameter(NETWORK) env.setup_stats("Shop", "typical", interval=3600) shop = { name: DynamicResource(env, "Shop", name) for name in ("packers", "checkers") } sampler = Sampler(seed=42) # Weights draw from the routing task's own sequence, as the builder's do STEPS["check_order"][2].rng = sampler.generator("route.check_order") counters = {name: itertools.count() for name in STEPS} env.process(network_orders(env, sampler, shop, counters)) try: env.run(until=until) finally: env.teardown() return env def mean_wait(packers: int) -> float: """Runs the busy hour with `packers` packers and returns the mean wait.""" env = run(packers) return env.stats.readings()["Shop.stats.tasks.pack_order.wait_mean"] if __name__ == "__main__": for packers in range(1, 5): print(f"packers {packers}: mean wait {mean_wait(packers):8.2f} s") ``` # Randomness and Seeds Run the busy shop twice, and the orders arrive at different times and take different times to pack. A stochastic model, one that draws random times, behaves this way, but its results are then hard to check or to compare. This page asks: **why do runs differ, and how can you reproduce one?** - **Decision:** how to set up runs so that a result can be checked and two versions of the model compared. - **Measures:** the times of one order's events, on repeated runs and after a second arrival is added. - **Runs:** runs of one minute: two with no seed, then repeated runs with the seed 42, with and without a second arrival. - **Assumptions:** orders arrive at random at 1.8 a second, and each packing time is drawn on its own, whatever the others were. ## What You Will Learn This page shows how to: - see why two runs of a stochastic model differ; - repeat a run exactly with a seed; - add a part to a model without changing the random times of the others. ## What You Add This page adds a seed, then a second arrival: returned parcels. The model simulates the busy hour from [Queues and Capacity](https://jaehyeon.me/desflow/latest/learn/first-model/queues-and-capacity/index.md), using its answer of 3 packers. Packing times now vary: 1.5 seconds on average with a standard deviation of 0.5 seconds, drawn from a `normal` distribution. This page uses the normal only to get times that vary. [Choosing Inputs](https://jaehyeon.me/desflow/latest/learn/inputs/choosing-inputs/index.md) chooses packing times from data. [Common Mistakes](https://jaehyeon.me/desflow/latest/learn/concepts/common-mistakes/#choosing-a-normal-or-uniform-by-habit) explains why a normal is a poor model of a time. This one draws a value below 0 about once in 740 draws, and desflow raises such a draw to 0, so the step takes no time, as [Distributions](https://jaehyeon.me/desflow/latest/reference/distributions/index.md) says. ______________________________________________________________________ ## Run Twice A simulation draws its random times from a **random number stream**: a long sequence of numbers that looks random but is computed from a starting value, the **seed**. The same seed gives the same sequence, and so the same run. A simulation given no seed starts from a new seed each time, so two runs give two different sets of records. Save the files from [Full Files](#full-files) in one folder and run the commands there. desflow never runs without a seed. When you give none, it draws one, uses it, and logs it, so any run can be repeated afterwards: Leave `random_seed` out of the `simulation` section and run the blueprint twice. Each run logs its seed with the command that repeats it. Each run draws its own seed, so your number differs from this one: ```text No random_seed was given, so this run uses 3166812249. Repeat it with: desflow run randomness_and_seeds.yaml --seed 3166812249 ``` Leave `random_seed` out of `SimulationContext` and run the script twice. Each run logs its seed with the argument that repeats it. Each run draws its own seed, so your number differs from this one: ```text No random_seed was given, so this run uses 3166812249. Pass random_seed=3166812249 to repeat it. ``` The low-level API never draws a seed for you: you pass one to `Sampler`. A `Sampler()` with no seed draws nothing at random, as [Arrivals and Services](https://jaehyeon.me/desflow/latest/user-guide/model-parts/arrivals-and-services/#how-it-works) explains. To start from a new seed each run, draw one yourself, for example with `secrets.randbelow(2**32)`, and print it. ______________________________________________________________________ ## Fix the Seed Set the seed once, and every run draws the same numbers: ```yaml # The same random numbers on every run; leave it out to draw a new seed random_seed: 42 ``` `desflow run randomness_and_seeds.yaml --seed 7` runs with another seed without editing the file; `--seed` overrides `random_seed`. ```python # The same random numbers on every run; leave it out to draw a new seed SimulationContext(sim_id="Shop", factor=0, random_seed=42) ``` ```python # The same random numbers on every run, passed to Sampler(seed=SEED) in run below SEED = 42 ``` Repeating a run exactly is called **reproducibility**. It is what lets you check a result, show it to someone else, and see what a change to the model does on its own. Pick one order and follow it: the twelfth order, `orders-12`, has these events on every run with the seed 42: ```text [EVT] {'sim_ts': 7.549626752406978, 'timestamp': '...', 'key': 'orders-12', 'task': 'pack_order', 'instance': 11, 'value': {'path_id': 'Shop.service.packing', 'sim_id': 'Shop', 'service': 'packing', 'status': 'queued'}} [EVT] {'sim_ts': 7.549626752406978, 'timestamp': '...', 'key': 'orders-12', 'task': 'pack_order', 'instance': 11, 'value': {'path_id': 'Shop.service.packing', 'sim_id': 'Shop', 'service': 'packing', 'status': 'started'}} [EVT] {'sim_ts': 8.080484400652141, 'timestamp': '...', 'key': 'orders-12', 'task': 'pack_order', 'instance': 11, 'value': {'event_type': 'order_packed'}} ``` It is `queued` at 7.550, gets a packer at the same moment and is packed at 8.080: a wait of 0 seconds. ______________________________________________________________________ ## Add Returns Now add returned parcels: one every 5 seconds on average (12 a minute), each recorded as it arrives. They do not use the packers. ```yaml arrivals: orders: {dist: exponential, rate: 1.8, spawn: pack_order} # Returned parcels: one every 5 seconds on average returns: {dist: exponential, rate: 0.2, spawn: receive_return} tasks: # A return is recorded as it arrives; it does not use a packer receive_return: payload: {event_type: return_received} ``` ```python # Returned parcels: one every 5 seconds on average app.add_arrival("returns", dist="exponential", rate=0.2) @app.task() def receive_return(task_id: int): # A return is recorded as it arrives; it does not use a packer return {"event_type": "return_received"} @app.arrival_loop("returns") def return_generator(context: SimulationContext): task_id = 0 while True: parcel = yield context.wait_for_arrival("returns") context.spawn(receive_return(task_id, entity=parcel)) task_id += 1 ``` ```python # Returned parcels: one every 5 seconds on average PARAMS.arrival["returns"] = DistributionConfig(dist="exponential", rate=0.2) def return_generator(env, sampler): """Records each return as it arrives; it does not use a packer.""" # Once registered, the config draws from sampler.generator("arrival.returns") arrival = env.registry.get_config("Shop.arrival.returns") task_id = 0 while True: yield env.timeout(sampler.sample(arrival)) key = f"returns-{task_id + 1}" value = {"event_type": "return_received"} env.publish_event(key, value, task="receive_return", instance=task_id) task_id += 1 ``` `Sampler(seed=SEED)` makes one generator per name, `sampler.generator("arrival.returns")`, from the seed and the name. The registry names each distribution it registers by its path without the sim id, such as `arrival.returns`. `sampler.sample(config)` draws from the generator of that name. Your own code can take a sequence of its own the same way. A task with no service and no resource, such as `receive_return`, takes no time: it publishes its payload as soon as the arrival starts it. Run it with the seed 42. `orders-12` has the same three events as before, at the same times. Adding an arrival changed nothing for the orders, because each distribution draws from a random number stream of its own, named by its registry path without the sim id. The orders draw from `arrival.orders`, packing from `service.packing`, and the new returns from `arrival.returns`. Look at the two runs side by side: With one shared stream, the returns would take some of the numbers the orders and packing used to get, and every later time would shift. The name is part of the stream. Renaming a service, an arrival or a task that routes by weights therefore gives it a new stream, and a run with the same seed then gives other results. [Busy Hour Figures](https://jaehyeon.me/desflow/latest/learn/concepts/output-analysis/#busy-hour-figures) lists two such runs: the same measured packing times give 1.81 or 2.01 seconds of mean wait, depending on the service's name. ______________________________________________________________________ ## What You Get and Why Why do runs differ, and how can you reproduce one? Runs differ because they start their random number streams from different seeds. Repeat a run by supplying the same seed: `random_seed: 42` in the blueprint, `random_seed=42` on `SimulationContext`, `Sampler(seed=42)` in the low-level API, or `desflow run --seed 42`. With it, **the twelfth order waits 0 seconds** on every run, and still 0 seconds after the returns are added. One stream per input means that two versions of a model run with the same seed see the same arrivals and the same service times wherever they share them. A difference between their results then comes from the change, not from different random numbers. Each node of a generated value, such as a `uniform` or a `fake` field, also has a stream of its own, so adding a generated field never moves an arrival or a service draw. This is called **common random numbers** ([Output Analysis](https://jaehyeon.me/desflow/latest/learn/concepts/output-analysis/#comparing-designs) explains it), and it is how two designs are compared fairly. [Arrivals and Services](https://jaehyeon.me/desflow/latest/user-guide/model-parts/arrivals-and-services/index.md) describes how each stream is made, and [Distributions](https://jaehyeon.me/desflow/latest/reference/distributions/index.md) lists every family with its parameters. ## Key Takeaways - A seed fixes the random numbers, so the same seed gives the same run. A YAML or builder run that was given no seed draws one and logs it, so it can be repeated. - Each distribution draws from its own random number stream, named after its registry path, so adding an arrival leaves the other draws as they were. - Renaming a service, an arrival or a weighted route gives it a new stream, and the results change with the same seed. ______________________________________________________________________ ## Full Files Full files ```yaml # The Randomness and Seeds tutorial: the busy shop, seeded, with returns. # Run it with: desflow run randomness_and_seeds.yaml simulation: sim_id: Shop factor: 0 # The same random numbers on every run; leave it out to draw a new seed random_seed: 42 resources: packers: {current_cap: 3, max_cap: 10} services: # Packing varies: 1.5 seconds on average, with a standard deviation of 0.5 packing: {dist: normal, mean: 1.5 s, std: 0.5 s} arrivals: orders: {dist: exponential, rate: 1.8, spawn: pack_order} # Returned parcels: one every 5 seconds on average returns: {dist: exponential, rate: 0.2, spawn: receive_return} tasks: # A return is recorded as it arrives; it does not use a packer receive_return: payload: {event_type: return_received} pack_order: service: packing resource: packers payload: {event_type: order_packed} egress: - {type: Console} run: {until: 1 min} ``` ```python """The Randomness and Seeds tutorial: the busy shop, seeded, with returns, builder. Orders arrive at 1.8 a second, and three packers pack each in 1.5 seconds on average, with a standard deviation of 0.5 seconds. Returned parcels arrive every 5 seconds on average and are recorded as they arrive. Every record is printed to the terminal. """ import logging from desflow import ConsoleEgress, SimulationContext logging.basicConfig( level=logging.INFO, format="%(levelname)s [%(asctime)s] %(message)s" ) app = ( # The same random numbers on every run; leave it out to draw a new seed SimulationContext(sim_id="Shop", factor=0, random_seed=42) .add_resource("packers", current_cap=3, max_cap=10) # Packing varies: 1.5 seconds on average, with a standard deviation of 0.5 .add_service("packing", dist="normal", mean=1.5, std=0.5) .add_arrival("orders", dist="exponential", rate=1.8) .add_egress(ConsoleEgress()) ) @app.task(service_id="packing", resource_id="packers") def pack_order(task_id: int): return {"event_type": "order_packed"} @app.arrival_loop("orders") def order_generator(context: SimulationContext): task_id = 0 while True: order = yield context.wait_for_arrival("orders") context.spawn(pack_order(task_id, entity=order)) task_id += 1 # Returned parcels: one every 5 seconds on average app.add_arrival("returns", dist="exponential", rate=0.2) @app.task() def receive_return(task_id: int): # A return is recorded as it arrives; it does not use a packer return {"event_type": "return_received"} @app.arrival_loop("returns") def return_generator(context: SimulationContext): task_id = 0 while True: parcel = yield context.wait_for_arrival("returns") context.spawn(receive_return(task_id, entity=parcel)) task_id += 1 if __name__ == "__main__": app.run(until="1 min") ``` ```python """The Randomness and Seeds tutorial: the busy shop, seeded, with returns, low-level. Orders arrive at 1.8 a second, and three packers pack each in 1.5 seconds on average, with a standard deviation of 0.5 seconds. Returned parcels arrive every 5 seconds on average and are recorded as they arrive. Every record is printed to the terminal. """ import logging from desflow import ( CapacityConfig, ConsoleEgress, DistributionConfig, DynamicRealtimeEnvironment, DynamicResource, Sampler, SimParameter, ) logging.basicConfig( level=logging.INFO, format="%(levelname)s [%(asctime)s] %(message)s" ) PARAMS = SimParameter( sim_id="Shop", arrival={"orders": DistributionConfig(dist="exponential", rate=1.8)}, # Packing varies: 1.5 seconds on average, with a standard deviation of 0.5 service={"packing": DistributionConfig(dist="normal", mean=1.5, std=0.5)}, resources={"packers": CapacityConfig(current_cap=3, max_cap=10)}, ) # The same random numbers on every run, passed to Sampler(seed=SEED) in run below SEED = 42 def pack_order(env, sampler, packers, key, task_id): path_id = "Shop.service.packing" def publish(value): env.publish_event(key, value, task="pack_order", instance=task_id) publish( {"path_id": path_id, "sim_id": "Shop", "service": "packing", "status": "queued"} ) with packers.request() as request: yield request publish( { "path_id": path_id, "sim_id": "Shop", "service": "packing", "status": "started", } ) yield env.timeout(sampler.sample(env.registry.get_config(path_id))) publish({"event_type": "order_packed"}) def order_generator(env, sampler, packers): arrival = env.registry.get_config("Shop.arrival.orders") task_id = 0 while True: yield env.timeout(sampler.sample(arrival)) env.process(pack_order(env, sampler, packers, f"orders-{task_id + 1}", task_id)) task_id += 1 # Returned parcels: one every 5 seconds on average PARAMS.arrival["returns"] = DistributionConfig(dist="exponential", rate=0.2) def return_generator(env, sampler): """Records each return as it arrives; it does not use a packer.""" # Once registered, the config draws from sampler.generator("arrival.returns") arrival = env.registry.get_config("Shop.arrival.returns") task_id = 0 while True: yield env.timeout(sampler.sample(arrival)) key = f"returns-{task_id + 1}" value = {"event_type": "return_received"} env.publish_event(key, value, task="receive_return", instance=task_id) task_id += 1 def run(until=60, factor=0.0): env = DynamicRealtimeEnvironment(factor=factor) env.registry.register_sim_parameter(PARAMS) env.setup_egress([ConsoleEgress()]) packers = DynamicResource(env, "Shop", "packers") sampler = Sampler(seed=SEED) env.process(order_generator(env, sampler, packers)) env.process(return_generator(env, sampler)) try: env.run(until=until) finally: env.teardown() return env if __name__ == "__main__": run() ``` # Measuring a Run Most of the pages so far read one number, the mean wait. A run knows much more. This page asks: **what does a run tell me?** - **Decision:** which numbers to read from a run before acting on it. - **Measures:** five of the numbers the run publishes: the packers' [utilisation](https://jaehyeon.me/desflow/latest/learn/concepts/queueing-basics/#utilisation), the mean queue, the mean and longest wait, and the orders packed. - **Runs:** one run of the busy hour, with the seed 42, starting with an empty shop. - **Assumptions:** orders arrive at random at 1.8 a second, and the times measured at the bench stand for every packer. ## What You Will Learn This page shows how to: - switch on the built-in statistics at a level; - read utilisation, queue length, waits and counts at the end of a run; - check the statistics against each other with Little's Law. ## What You Add This page adds `stats: typical`, the built-in statistics at the level that includes waits. The model simulates the busy hour with 3 packers from [Queues and Capacity](https://jaehyeon.me/desflow/latest/learn/first-model/queues-and-capacity/index.md), and draws each packing time from 40 times measured at the bench, each equally likely. The model calls this an `empirical` distribution. Real packing times vary, so these times describe the shop better than the constant 1.5 seconds of the earlier pages; [Choosing Inputs](https://jaehyeon.me/desflow/latest/learn/inputs/choosing-inputs/#measured-times) explains the distribution and compares it with others. ______________________________________________________________________ ## Switch On Statistics desflow keeps statistics about a run as it goes. It publishes them as telemetry every 10 simulation seconds and once more at the end, so the last value of each statistic is the state at the end of the run. Statistics are off by default, because most runs only generate data. A level switches them on: `none` (the default), `minimal`, `basic`, `typical` or `all`, each publishing what the one before it does and more. `typical` adds each task's mean and maximum wait and service time. [Statistics](https://jaehyeon.me/desflow/latest/user-guide/results/statistics/#choose-a-level) lists what each level adds. Switch on `typical`: ```yaml # Counts, time averages, and the mean and maximum wait and service, every 10 s stats: typical ``` ```python # Counts, time averages, and the mean and maximum wait and service, every 10 s .with_stats("typical") ``` ```python # Counts, time averages, and the mean and maximum wait and service, every 10 s env.setup_stats("Shop", "typical", interval=10) ``` The environment keeps the statistics in `env.stats`. Resources report their own changes. A low-level process has no task for desflow to watch, so the process reports each step itself. It calls `env.stats.task_queued`, `task_started` and `task_finished` with the task's name and instance id, and `flow_started` and `flow_finished` when the order enters and leaves the shop. The full file below shows them. The statistics are telemetry, so they reach every sink, and they can also be read in Python at the end of the run: ```yaml # The statistics are telemetry, so every sink receives them egress: - {type: Console} ``` ```python if __name__ == "__main__": app.run(until="1 h") # The statistics are telemetry, so the console printed them; read them here too for name, value in app.env.stats.readings().items(): print(f"{name} = {value}") ``` ```python if __name__ == "__main__": env = run() # The statistics are telemetry, so the console printed them; read them here too for name, value in env.stats.readings().items(): print(f"{name} = {value}") ``` Every name has the same form, `.stats...`, such as `Shop.stats.tasks.pack_order.wait_mean`. Save the files from [Full Files](#full-files) in one folder and run the commands there: `desflow run measuring_a_run.yaml`, `python measuring_a_run.py` or `python measuring_a_run_low_level.py`. The run prints about 24,000 lines, because the console also prints every event. These 15 are the statistics published at the end of the hour. The command keeps only the telemetry records stamped 3600.0: ```bash desflow run measuring_a_run.yaml 2>&1 | grep "\[TEL\] {'sim_ts': 3600.0" ``` ```text [TEL] {'sim_ts': 3600.0, 'timestamp': '...', 'path_id': 'Shop.stats.resources.packers.capacity', 'value': 3} [TEL] {'sim_ts': 3600.0, 'timestamp': '...', 'path_id': 'Shop.stats.resources.packers.in_use', 'value': 3} [TEL] {'sim_ts': 3600.0, 'timestamp': '...', 'path_id': 'Shop.stats.resources.packers.queue_length', 'value': 0} [TEL] {'sim_ts': 3600.0, 'timestamp': '...', 'path_id': 'Shop.stats.resources.packers.utilization', 'value': 100.0} [TEL] {'sim_ts': 3600.0, 'timestamp': '...', 'path_id': 'Shop.stats.resources.packers.utilization_avg', 'value': 89.98409865705875} [TEL] {'sim_ts': 3600.0, 'timestamp': '...', 'path_id': 'Shop.stats.resources.packers.queue_length_avg', 'value': 3.617867825881605} [TEL] {'sim_ts': 3600.0, 'timestamp': '...', 'path_id': 'Shop.stats.tasks.pack_order.in_progress', 'value': 3} [TEL] {'sim_ts': 3600.0, 'timestamp': '...', 'path_id': 'Shop.stats.tasks.pack_order.finished', 'value': 6488} [TEL] {'sim_ts': 3600.0, 'timestamp': '...', 'path_id': 'Shop.stats.tasks.pack_order.wait_mean', 'value': 2.0065204395584315} [TEL] {'sim_ts': 3600.0, 'timestamp': '...', 'path_id': 'Shop.stats.tasks.pack_order.wait_max', 'value': 11.938984807219526} [TEL] {'sim_ts': 3600.0, 'timestamp': '...', 'path_id': 'Shop.stats.tasks.pack_order.service_mean', 'value': 1.4977034525277377} [TEL] {'sim_ts': 3600.0, 'timestamp': '...', 'path_id': 'Shop.stats.tasks.pack_order.service_max', 'value': 2.7000000000000455} [TEL] {'sim_ts': 3600.0, 'timestamp': '...', 'path_id': 'Shop.stats.flows.orders.finished', 'value': 6488} [TEL] {'sim_ts': 3600.0, 'timestamp': '...', 'path_id': 'Shop.stats.flows.orders.started', 'value': 6491} [TEL] {'sim_ts': 3600.0, 'timestamp': '...', 'path_id': 'Shop.stats.flows.orders.in_system', 'value': 3} ``` The statistics mean: - `utilization_avg` 89.98: the packers were busy 89.98% of the time. The utilisation statistics are percentages, while `desflow explain` and `--verify` give utilisation as a fraction, 0.9 for 90%. - `utilization` 100.0: all three packers were busy at the end. - `tasks.pack_order.finished`: the orders the task finished. - `flows.orders.finished`: the orders that left the shop. The flow is named after the arrival that started them, `orders`. With one task the two counts are equal. - `flows.orders.started`: the orders that entered the shop, 6,491. - `flows.orders.in_system`: the 3 orders still in the shop when the hour ended. `tasks.pack_order.in_progress` gives the same 3. The names use the spelling `utilization`, and the text uses "utilisation" for the same thing. The mean wait is 2.01 seconds, over the orders that started packing in [this one run with the seed 42](https://jaehyeon.me/desflow/latest/learn/concepts/output-analysis/#busy-hour-figures). [End Conditions](https://jaehyeon.me/desflow/latest/learn/first-model/end-conditions/index.md) shows what a run leaves out when it ends. ______________________________________________________________________ ## Counts and Averages Over Time The statistics are of two kinds. A **count**, such as `finished`, adds one for each order. An **average over time**, also called a time-weighted average, such as `utilization_avg` or `queue_length_avg`, weighs each value by how long it lasted. Look at the area under the number of busy packers: desflow adds the area every time the value changes, so the average is exact at any moment. A reading taken now and then, such as every 10 seconds, sees only the value at that instant. The queue in the first five minutes of the hour shows the difference: The queue rises and falls many times between two readings, and a handful of readings can land on high points by chance. Here the readings average 2.33 orders and the average over time for the same five minutes is 2.30 orders. They are close in this run, but the readings only estimate the average, while the average over time is exact. ______________________________________________________________________ ## Wait and Service The time each order spends in the shop has two parts, both measured from the task's own events: - **wait** runs from `queued` to `started`: the time spent waiting for a packer; - **service** runs from `started` to the finished event: the time spent being packed. `service_mean` is 1.50 seconds and `service_max` is 2.7 seconds. The 40 measured times have the same mean and the same longest time, so the model draws what it was given. `wait_max` is 11.94 seconds: one order waited almost six times as long as the average one. ______________________________________________________________________ ## What You Get and Why What does a run tell me? One run of the busy hour, with the seed 42, the measured packing times and no warm-up, tells you that: - the packers were busy **90.0%** of the time on average; - the queue held **3.62** orders on average; - an order waited **2.01 seconds** on average and **11.94 seconds** at most; - **6,488** orders were packed. The numbers check each other. [Little's Law](https://jaehyeon.me/desflow/latest/learn/concepts/queueing-basics/#littles-law) says that the average number waiting equals the rate at which orders arrive times the average time each waits. 6,488 orders in 3,600 seconds is 1.80 a second, and 1.80 × 2.01 = 3.62, which matches `queue_length_avg`, 3.62. The [utilisation](https://jaehyeon.me/desflow/latest/learn/concepts/queueing-basics/#utilisation) checks the same way: 1.80 orders a second × 1.50 seconds ÷ 3 packers = 0.90. A set of statistics that fails a check like this one points to a mistake in the model or in how it is read, as [Checking and Validating](https://jaehyeon.me/desflow/latest/learn/concepts/checking-and-validating/#check-the-statistics-against-each-other) explains. [Statistics](https://jaehyeon.me/desflow/latest/user-guide/results/statistics/index.md) describes how each one is computed, and the [Statistics reference](https://jaehyeon.me/desflow/latest/reference/statistics/index.md) lists every name each level publishes. ## Key Takeaways - Statistics are off by default. A level, such as `typical`, switches them on, and the run publishes them as telemetry. - An average over time weighs each value by how long it lasted, so it is exact, unlike readings taken now and then. - Statistics that fail a check such as Little's Law point to a mistake in the model or in how it is read. ______________________________________________________________________ ## Full Files Full files ```yaml # The Measuring a Run tutorial: the busy hour, with built-in statistics. # Run it with: desflow run measuring_a_run.yaml simulation: {sim_id: Shop, factor: 0, random_seed: 42} resources: packers: {current_cap: 3, max_cap: 10} arrivals: orders: {dist: exponential, rate: 1.8, spawn: pack_order} services: # The 40 packing times measured at the bench, in seconds packing: dist: empirical values: [1.5, 2.5, 2.4, 1.2, 1.3, 1.2, 1.8, 1.4, 2.0, 0.7, 2.7, 1.4, 1.9, 1.4, 1.3, 1.8, 2.0, 1.4, 1.4, 1.9, 1.1, 0.8, 1.7, 1.1, 0.7, 1.1, 1.2, 0.9, 0.8, 1.5, 2.1, 1.3, 1.1, 1.7, 1.9, 1.3, 1.8, 2.2, 1.4, 1.1] tasks: pack_order: service: packing resource: packers payload: {event_type: order_packed} # Counts, time averages, and the mean and maximum wait and service, every 10 s stats: typical # The statistics are telemetry, so every sink receives them egress: - {type: Console} run: {until: 1 h} ``` ```python """The Measuring a Run tutorial: the busy hour, with built-in statistics, builder. Three packers, orders at 1.8 a second and the measured packing times. Every record, the statistics included, is printed to the terminal, and the script prints the final statistics again at the end. """ import logging from desflow import ConsoleEgress, SimulationContext logging.basicConfig( level=logging.INFO, format="%(levelname)s [%(asctime)s] %(message)s" ) # The 40 packing times measured at the bench, in seconds MEASURED = [ 1.5, 2.5, 2.4, 1.2, 1.3, 1.2, 1.8, 1.4, 2.0, 0.7, 2.7, 1.4, 1.9, 1.4, 1.3, 1.8, 2.0, 1.4, 1.4, 1.9, 1.1, 0.8, 1.7, 1.1, 0.7, 1.1, 1.2, 0.9, 0.8, 1.5, 2.1, 1.3, 1.1, 1.7, 1.9, 1.3, 1.8, 2.2, 1.4, 1.1, ] # fmt: skip app = ( SimulationContext(sim_id="Shop", factor=0, random_seed=42) .add_resource("packers", current_cap=3, max_cap=10) .add_arrival("orders", dist="exponential", rate=1.8) .add_service("packing", dist="empirical", values=MEASURED) # Counts, time averages, and the mean and maximum wait and service, every 10 s .with_stats("typical") .add_egress(ConsoleEgress()) ) @app.task(service_id="packing", resource_id="packers") def pack_order(task_id: int): return {"event_type": "order_packed"} @app.arrival_loop("orders") def order_generator(context: SimulationContext): task_id = 0 while True: order = yield context.wait_for_arrival("orders") context.spawn(pack_order(task_id, entity=order)) task_id += 1 if __name__ == "__main__": app.run(until="1 h") # The statistics are telemetry, so the console printed them; read them here too for name, value in app.env.stats.readings().items(): print(f"{name} = {value}") ``` ```python """The Measuring a Run tutorial: the busy hour, with built-in statistics, low-level. Three packers, orders at 1.8 a second and the measured packing times. The order process reports each step to the environment's statistics, which publish them as telemetry; the script prints the final statistics again at the end. """ import logging from desflow import ( CapacityConfig, ConsoleEgress, DistributionConfig, DynamicRealtimeEnvironment, DynamicResource, Sampler, SimParameter, ) logging.basicConfig( level=logging.INFO, format="%(levelname)s [%(asctime)s] %(message)s" ) # The 40 packing times measured at the bench, in seconds MEASURED = [ 1.5, 2.5, 2.4, 1.2, 1.3, 1.2, 1.8, 1.4, 2.0, 0.7, 2.7, 1.4, 1.9, 1.4, 1.3, 1.8, 2.0, 1.4, 1.4, 1.9, 1.1, 0.8, 1.7, 1.1, 0.7, 1.1, 1.2, 0.9, 0.8, 1.5, 2.1, 1.3, 1.1, 1.7, 1.9, 1.3, 1.8, 2.2, 1.4, 1.1, ] # fmt: skip PARAMS = SimParameter( sim_id="Shop", arrival={"orders": DistributionConfig(dist="exponential", rate=1.8)}, service={"packing": DistributionConfig(dist="empirical", values=MEASURED)}, resources={"packers": CapacityConfig(current_cap=3, max_cap=10)}, ) def pack_order(env, sampler, packers, key, task_id): """One order, which reports each step to the statistics.""" path_id = "Shop.service.packing" def publish(value): env.publish_event(key, value, task="pack_order", instance=task_id) publish( {"path_id": path_id, "sim_id": "Shop", "service": "packing", "status": "queued"} ) env.stats.task_queued("pack_order", task_id) with packers.request() as request: yield request publish( { "path_id": path_id, "sim_id": "Shop", "service": "packing", "status": "started", } ) env.stats.task_started("pack_order", task_id) yield env.timeout(sampler.sample(env.registry.get_config(path_id))) publish({"event_type": "order_packed"}) env.stats.task_finished("pack_order", task_id) env.stats.flow_finished("orders") # the order leaves the shop def order_generator(env, sampler, packers): arrival = env.registry.get_config("Shop.arrival.orders") task_id = 0 while True: yield env.timeout(sampler.sample(arrival)) env.stats.flow_started("orders") # the order enters the shop env.process(pack_order(env, sampler, packers, f"orders-{task_id + 1}", task_id)) task_id += 1 def run(until=3600, factor=0.0): env = DynamicRealtimeEnvironment(factor=factor) env.registry.register_sim_parameter(PARAMS) env.setup_egress([ConsoleEgress()]) # Counts, time averages, and the mean and maximum wait and service, every 10 s env.setup_stats("Shop", "typical", interval=10) packers = DynamicResource(env, "Shop", "packers") env.process(order_generator(env, Sampler(seed=42), packers)) try: env.run(until=until) finally: env.teardown() return env if __name__ == "__main__": env = run() # The statistics are telemetry, so the console printed them; read them here too for name, value in env.stats.readings().items(): print(f"{name} = {value}") ``` # End Conditions For an hour the shop now gets an order every 1.43 seconds on average (42 a minute, `rate: 0.7`). Its one packer takes 1.5 seconds per order, so it packs at most 40 a minute, a little fewer than the 42 that arrive. Orders are still waiting when the hour ends. A report that counts only the orders packed in the hour leaves them out. This page asks: **does a fixed horizon answer the same question as closing the doors and packing every order already in the shop?** - **Decision:** which way of ending the run the shop's report uses. - **Measures:** the orders started, finished and still in the shop, the mean wait, and the time the run ends. - **Runs:** two runs, each with the seed 42: one stops at the end of the hour, and one stops taking orders then and runs until the last order is packed. - **Assumptions:** orders arrive at random, and every order takes the same time to pack. ## What You Will Learn This page shows how to: - end a run at a fixed time, or close the doors and drain the orders already in the shop; - count the orders started, finished and still in the shop; - see which orders a mean wait leaves out. ## What You Add This page adds a **drain** at the end of the run, which packs every order still in the shop, and the counts that show which orders each way of ending leaves out. The shop is the one from [First Simulation](https://jaehyeon.me/desflow/latest/learn/first-model/first-simulation/index.md), busier: one packer and 1.5 seconds of packing. ______________________________________________________________________ ## Count Who Is Still There An end condition decides which entities a run's results describe. These statistics count the orders: - `flows.orders.started`, from the `basic` level, counts the orders that entered the shop. An order enters when its first task begins, before any queue. - `flows.orders.finished`, from `basic`, counts the orders that left. - `flows.orders.in_system`, from `basic`, counts the orders still in the shop. - `tasks.pack_order.in_progress`, from `minimal`, counts the orders waiting to be packed or being packed. The model switches on `typical`, which also keeps the mean wait: ```yaml # Orders started, finished and still in the shop, and the mean wait, at the end stats: {level: typical, interval: 2 h} ``` ```python # Orders started, finished and still in the shop, and the mean wait, at the end .with_stats("typical", interval=7200) ``` ```python # Orders started, finished and still in the shop, and the mean wait, at the end env.setup_stats("Shop", "typical", interval=7200) ``` A low-level process reports its entities with `env.stats.flow_started(arrival)` and `env.stats.flow_finished(arrival)`, as the full file below does. Every order that started is either finished or still in the shop, so `started` is `finished` plus `in_system`. These counts say how many orders a mean wait leaves out. ______________________________________________________________________ ## Close the Doors, Then Finish Save the files from [Full Files](#full-files) in one folder and run the commands there. A **fixed horizon** stops the clock at `until`, whatever is still going on. A **drain** stops only the arrivals at `until` and keeps running until every entity in the model has left. In SimPy that is two steps: interrupt the source process, then run until every admitted process has ended. desflow writes both with `drain`: ```yaml run: # No new orders after one hour until: 1 h # true: pack every order already in the shop before the run ends drain: ${DRAIN:-false} ``` `${DRAIN:-false}` reads the environment variable `DRAIN`, so `DRAIN=true desflow run end_conditions.yaml` runs the drain, as `desflow run end_conditions.yaml --drain` does. ```python # No new orders after one hour; with drain, pack every order already in the shop app.run(until="1 h", drain=drain or None) ``` ```python env.run(until=3600) # no new orders after one hour if drain: # Stop the source, then run until every admitted order has ended source.interrupt() env.run(until=env.all_of([o for o in orders if o.is_alive])) ``` `env.all_of(...)` is SimPy's `AllOf`: it happens when every order process has ended. [SimPy and desflow](https://jaehyeon.me/desflow/latest/simpy/#waiting-for-one-or-all) explains waiting for all events. `source.interrupt()` raises an `Interrupt` inside the source process, which ends its loop. [SimPy and desflow](https://jaehyeon.me/desflow/latest/simpy/#interrupts) explains interrupts. [`o.is_alive`](https://simpy.readthedocs.io/en/4.1.2/api_reference/simpy.events.html#simpy.events.Process.is_alive) is true while a process has not ended. `env.now` is the clock, which the script reads to report the end time. [SimPy and desflow](https://jaehyeon.me/desflow/latest/simpy/#environment-and-the-event-list) explains the clock. The stop at `until` is an event that SimPy schedules with the `URGENT` priority, so it comes before the other events at that time. A script that stops its own run at an event can do the same with `env.schedule(event, URGENT, delay)`. In a blueprint, the `fire` action's `urgent` and `after` keys do it, as [Signals and Waiting](https://jaehyeon.me/desflow/latest/user-guide/tasks-and-processes/signals-and-waiting/#actions-when-an-event-happens) shows. A drain can also take a limit, `drain: {limit: 10 min}`, so a model that never empties still ends. A limit of 0, below 0 or NaN is refused, and an infinite limit means no limit. A `stop` ends the run as soon as an event or a condition happens. [Run Length](https://jaehyeon.me/desflow/latest/user-guide/time-and-pacing/run-length/#stop-early) describes both. ______________________________________________________________________ ## What You Get and Why Does a fixed horizon answer the same question as a drain? Not for every order. Each figure here comes from a run with the seed 42: one that stops at the hour, and one that drains after it. The fixed horizon ends at **3,600** seconds with **2,561** orders started, **2,386** finished and **175** still in the shop, one being packed and 174 waiting. The drain ends **261.8** seconds later, at **3,861.8**, with all **2,561** finished: `desflow explain` shows why so many orders are left, without a run: ```bash desflow explain end_conditions.yaml ``` ```text Resources +--------------------------------------------------------+ | resource | λ | μ | c | ρ | Wq | L | status | |----------+-----+--------+---+------+----+---+----------| | packers | 0.7 | 0.6667 | 1 | 1.05 | - | - | UNSTABLE | +--------------------------------------------------------+ Not estimated: wait at packers: unstable: the queue grows for as long as the run lasts ``` The packer gets 1.05 seconds of work every second, more than it can do, so the queue grows for as long as orders arrive. The longer the horizon, the more orders it leaves in the shop. A drain packs them all. In Python, `context.analyze()` gives the same analysis for a builder model. A low-level model has no `explain`, because its SimPy code makes the links between arrivals, tasks and resources as it runs, so there are none to read. The mean wait moves less than the count of finished orders: **122.81** seconds with the fixed horizon against **131.27** with the drain. An order's wait is measured when its packing starts, so only the 174 of the 2,561 orders that start packing after the hour change the mean, and they raise it because they waited longer than the orders before them. Each tab prints both runs: the orders started, finished and still in the shop, and the mean wait. A record's `sim_ts` is the time the run ended. ```bash # Stop at the end time: orders started, finished and still in the shop, and the mean wait desflow run end_conditions.yaml --stdout | grep -E 'orders\.(started|finished|in_system)"|pack_order\.wait_mean"' | tail -4 # Finish the orders in the shop first DRAIN=true desflow run end_conditions.yaml --stdout | grep -E 'orders\.(started|finished|in_system)"|pack_order\.wait_mean"' | tail -4 ``` ```text {"stream_type":"telemetry","sim_ts":3600.0,"timestamp":"...","path_id":"Shop.stats.tasks.pack_order.wait_mean","value":122.8142837353294} {"stream_type":"telemetry","sim_ts":3600.0,"timestamp":"...","path_id":"Shop.stats.flows.orders.finished","value":2386} {"stream_type":"telemetry","sim_ts":3600.0,"timestamp":"...","path_id":"Shop.stats.flows.orders.started","value":2561} {"stream_type":"telemetry","sim_ts":3600.0,"timestamp":"...","path_id":"Shop.stats.flows.orders.in_system","value":175} {"stream_type":"telemetry","sim_ts":3861.806114353957,"timestamp":"...","path_id":"Shop.stats.tasks.pack_order.wait_mean","value":131.26839079806425} {"stream_type":"telemetry","sim_ts":3861.806114353957,"timestamp":"...","path_id":"Shop.stats.flows.orders.finished","value":2561} {"stream_type":"telemetry","sim_ts":3861.806114353957,"timestamp":"...","path_id":"Shop.stats.flows.orders.started","value":2561} {"stream_type":"telemetry","sim_ts":3861.806114353957,"timestamp":"...","path_id":"Shop.stats.flows.orders.in_system","value":0} ``` ```bash python end_conditions.py 2>/dev/null ``` ```text horizon: ends at 3600.0 s, 2561 started, 2386 finished, 175 left, mean wait 122.81 s drain : ends at 3861.8 s, 2561 started, 2561 finished, 0 left, mean wait 131.27 s ``` ```bash python end_conditions_low_level.py 2>/dev/null ``` ```text horizon: ends at 3600.0 s, 2561 started, 2386 finished, 175 left, mean wait 122.81 s drain : ends at 3861.8 s, 2561 started, 2561 finished, 0 left, mean wait 131.27 s ``` A fixed horizon answers a question about a period, such as how many orders the shop packs in an hour. The orders still in the shop at the end are unfinished work, and `in_system` says how many there are. A drain answers a question about a batch of orders, such as how long the day's orders take to clear. It serves every admitted order, but the run goes on past the hour. Report the counts beside any mean, so a reader knows which orders it covers. [Output Analysis](https://jaehyeon.me/desflow/latest/learn/concepts/output-analysis/#terminating-or-steady-state) explains the two kinds of run, and [Statistics](https://jaehyeon.me/desflow/latest/user-guide/results/statistics/index.md) describes each count. ## Key Takeaways - A fixed horizon answers a question about a period. A drain answers a question about a batch of orders. - `started` equals `finished` plus `in_system`, so these counts show the orders a result leaves out. - Report the counts beside any mean, so a reader knows which orders it covers. ______________________________________________________________________ ## Full Files Full files ```yaml # The End Conditions tutorial: a fixed horizon against a drain. # Run it with: desflow run end_conditions.yaml # With a drain after the hour: DRAIN=true desflow run end_conditions.yaml simulation: {sim_id: Shop, factor: 0, random_seed: 42} resources: packers: {current_cap: 1, max_cap: 4} services: packing: {dist: constant, value: 1.5 s} arrivals: orders: {dist: exponential, rate: 0.7, spawn: pack_order} tasks: pack_order: service: packing resource: packers payload: {event_type: order_packed} # Orders started, finished and still in the shop, and the mean wait, at the end stats: {level: typical, interval: 2 h} egress: - {type: Console} run: # No new orders after one hour until: 1 h # true: pack every order already in the shop before the run ends drain: ${DRAIN:-false} ``` ```python """The End Conditions tutorial: a fixed horizon against a drain. One packer, an order every 1.43 seconds on average (rate 0.7) and 1.5 seconds of packing, for an hour. Every record is printed to the terminal, and the script prints the counts and the mean wait with a fixed horizon and with a drain at the end. To see only those lines, run: python end_conditions.py 2>/dev/null """ import logging from desflow import ConsoleEgress, SimulationContext logging.basicConfig( level=logging.INFO, format="%(levelname)s [%(asctime)s] %(message)s" ) def shop() -> SimulationContext: """The shop of First Simulation, busier: more orders than one packer can pack.""" app = ( SimulationContext(sim_id="Shop", factor=0, random_seed=42) .add_resource("packers", current_cap=1, max_cap=4) .add_service("packing", dist="constant", value=1.5) .add_arrival("orders", dist="exponential", rate=0.7) # Orders started, finished and still in the shop, and the mean wait, at the end .with_stats("typical", interval=7200) .add_egress(ConsoleEgress()) ) @app.task(service_id="packing", resource_id="packers") def pack_order(task_id: int): return {"event_type": "order_packed"} @app.arrival_loop("orders") def order_generator(context: SimulationContext): task_id = 0 while True: order = yield context.wait_for_arrival("orders") context.spawn(pack_order(task_id, entity=order)) task_id += 1 return app def outcomes(drain: bool) -> dict: """Runs the hour, with or without a drain, and returns the counts and the wait.""" app = shop() # No new orders after one hour; with drain, pack every order already in the shop app.run(until="1 h", drain=drain or None) r = app.env.stats.readings() name = "Shop.stats.{}".format return { "started": r[name("flows.orders.started")], "finished": r[name("flows.orders.finished")], "in_system": r[name("flows.orders.in_system")], "wait_mean": r[name("tasks.pack_order.wait_mean")], "end": app.env.now, } if __name__ == "__main__": for drain in (False, True): r = outcomes(drain) label = "drain " if drain else "horizon" print( f"{label}: ends at {r['end']:7.1f} s, {r['started']} started, " f"{r['finished']} finished, {r['in_system']} left, " f"mean wait {r['wait_mean']:5.2f} s" ) ``` ```python """The End Conditions tutorial: a fixed horizon against a drain. One packer, an order every 1.43 seconds on average (rate 0.7) and 1.5 seconds of packing, for an hour. Every record is printed to the terminal, and the script prints the counts and the mean wait with a fixed horizon and with a drain at the end. To see only those lines, run: python end_conditions_low_level.py 2>/dev/null """ import itertools import logging import simpy from desflow import ( CapacityConfig, ConsoleEgress, DistributionConfig, DynamicRealtimeEnvironment, DynamicResource, Sampler, SimParameter, ) logging.basicConfig( level=logging.INFO, format="%(levelname)s [%(asctime)s] %(message)s" ) PARAMS = SimParameter( sim_id="Shop", arrival={"orders": DistributionConfig(dist="exponential", rate=0.7)}, service={"packing": DistributionConfig(dist="constant", value=1.5)}, resources={"packers": CapacityConfig(current_cap=1, max_cap=4)}, ) def pack_order(env, sampler, packers, key, task_id): path_id = "Shop.service.packing" def publish(value): env.publish_event(key, value, task="pack_order", instance=task_id) env.stats.flow_started("orders") # the order enters the shop publish( {"path_id": path_id, "sim_id": "Shop", "service": "packing", "status": "queued"} ) env.stats.task_queued("pack_order", task_id) with packers.request() as request: yield request publish( { "path_id": path_id, "sim_id": "Shop", "service": "packing", "status": "started", } ) env.stats.task_started("pack_order", task_id) yield env.timeout(sampler.sample(env.registry.get_config(path_id))) publish({"event_type": "order_packed"}) env.stats.task_finished("pack_order", task_id) env.stats.flow_finished("orders") def order_generator(env, sampler, packers, orders): arrival = env.registry.get_config("Shop.arrival.orders") try: for task_id in itertools.count(): yield env.timeout(sampler.sample(arrival)) key = f"orders-{task_id + 1}" orders.append(env.process(pack_order(env, sampler, packers, key, task_id))) except simpy.Interrupt: pass # no new orders after the hour def run(drain=False, factor=0.0): env = DynamicRealtimeEnvironment(factor=factor) env.registry.register_sim_parameter(PARAMS) env.setup_egress([ConsoleEgress()]) # Orders started, finished and still in the shop, and the mean wait, at the end env.setup_stats("Shop", "typical", interval=7200) packers = DynamicResource(env, "Shop", "packers") orders = [] source = env.process(order_generator(env, Sampler(seed=42), packers, orders)) try: env.run(until=3600) # no new orders after one hour if drain: # Stop the source, then run until every admitted order has ended source.interrupt() env.run(until=env.all_of([o for o in orders if o.is_alive])) finally: env.teardown() return env def outcomes(drain: bool) -> dict: """Runs the hour, with or without a drain, and returns the counts and the wait.""" env = run(drain) r = env.stats.readings() name = "Shop.stats.{}".format return { "started": r[name("flows.orders.started")], "finished": r[name("flows.orders.finished")], "in_system": r[name("flows.orders.in_system")], "wait_mean": r[name("tasks.pack_order.wait_mean")], "end": env.now, } if __name__ == "__main__": for drain in (False, True): r = outcomes(drain) label = "drain " if drain else "horizon" print( f"{label}: ends at {r['end']:7.1f} s, {r['started']} started, " f"{r['finished']} finished, {r['in_system']} left, " f"mean wait {r['wait_mean']:5.2f} s" ) ``` # Choosing Inputs Packing takes 1.5 seconds on average. So far the model has used exactly that: a `constant` 1.5 seconds. Real packing times vary, and a model's results are only as accurate as the times it draws. This page asks: **which distribution fits packing times?** - **Decision:** which candidate distribution the model uses for packing. - **Measures:** the shape of each candidate beside the measured times, and the busy hour's mean wait with each. - **Runs:** four runs of the busy hour, one for each candidate, each with the seed 42. - **Assumptions:** orders arrive at random at 1.8 a second, and the times measured at the bench stand for every packer. ## What You Will Learn This page shows how to: - write a packing time as a constant, an exponential, a triangular or an empirical distribution; - turn a mean and a standard deviation into a family's parameters with `desflow dist`; - see how the spread of an input changes the waits. ## What You Add This page adds a packing time chosen from evidence. The model simulates the busy hour with 3 packers from [Queues and Capacity](https://jaehyeon.me/desflow/latest/learn/first-model/queues-and-capacity/index.md). It gets four candidates for packing, all with a mean of 1.5 seconds, and runs the hour with each: - `constant`: the mean alone, as the shop had it; - `exponential`: the usual choice when nothing is known; - `triangular`: an expert's estimate; - `empirical`: times measured at the packing bench. ______________________________________________________________________ ## An Expert's Range Choosing a distribution for an input is called **input modelling**. Often there is no data yet, but someone who knows the work can say how long it takes at least, usually and at most. A **triangular** distribution takes exactly those three numbers, `low`, `mode` and `high`, and all three are required: ```yaml # An expert's estimate: at least 1 s, usually 1.25 s, at most 2.25 s triangular: {dist: triangular, low: 1 s, mode: 1.25 s, high: 2.25 s} ``` ```python # An expert's estimate: at least 1 s, usually 1.25 s, at most 2.25 s app.add_service("triangular", dist="triangular", low=1, mode=1.25, high=2.25) ``` ```python # An expert's estimate: at least 1 s, usually 1.25 s, at most 2.25 s TRIANGULAR = DistributionConfig(dist="triangular", low=1, mode=1.25, high=2.25) ``` Its mean is (low + mode + high) ÷ 3 = (1 + 1.25 + 2.25) ÷ 3 = 1.5 seconds. ______________________________________________________________________ ## Measured Times When times can be measured, use them. An **empirical** distribution draws from a list of measured `values`. Each value is equally likely, unless a `weights` list gives one weight per value. The 40 packing times below are illustrative: they stand for times taken at the bench, and their mean is 1.5 seconds: ```yaml # 40 packing times measured at the bench, in seconds empirical: dist: empirical values: [1.5, 2.5, 2.4, 1.2, 1.3, 1.2, 1.8, 1.4, 2.0, 0.7, 2.7, 1.4, 1.9, 1.4, 1.3, 1.8, 2.0, 1.4, 1.4, 1.9, 1.1, 0.8, 1.7, 1.1, 0.7, 1.1, 1.2, 0.9, 0.8, 1.5, 2.1, 1.3, 1.1, 1.7, 1.9, 1.3, 1.8, 2.2, 1.4, 1.1] ``` ```python # 40 packing times measured at the bench, in seconds measured = [ 1.5, 2.5, 2.4, 1.2, 1.3, 1.2, 1.8, 1.4, 2.0, 0.7, 2.7, 1.4, 1.9, 1.4, 1.3, 1.8, 2.0, 1.4, 1.4, 1.9, 1.1, 0.8, 1.7, 1.1, 0.7, 1.1, 1.2, 0.9, 0.8, 1.5, 2.1, 1.3, 1.1, 1.7, 1.9, 1.3, 1.8, 2.2, 1.4, 1.1, ] # fmt: skip app.add_service("empirical", dist="empirical", values=measured) ``` ```python # 40 packing times measured at the bench, in seconds MEASURED = [ 1.5, 2.5, 2.4, 1.2, 1.3, 1.2, 1.8, 1.4, 2.0, 0.7, 2.7, 1.4, 1.9, 1.4, 1.3, 1.8, 2.0, 1.4, 1.4, 1.9, 1.1, 0.8, 1.7, 1.1, 0.7, 1.1, 1.2, 0.9, 0.8, 1.5, 2.1, 1.3, 1.1, 1.7, 1.9, 1.3, 1.8, 2.2, 1.4, 1.1, ] # fmt: skip EMPIRICAL = DistributionConfig(dist="empirical", values=MEASURED) ``` The values are taken when the model is loaded. A registry path holds one number, and a list is not one number. So an `empirical` distribution has no registry path, and its values do not change while the run goes on. The other distributions have one path per parameter, such as `Shop.service.triangular.mode`. The measured times have a mean of 1.5 seconds and a standard deviation of 0.4832 seconds. A family fitted to them, such as a `gamma`, takes other parameters: a `shape` and a `scale`. `desflow dist` turns a mean and a standard deviation into them. Save the files from [Full Files](#full-files) in one folder and run the commands there: ```bash desflow dist gamma --mean 1.5 --std 0.4832 ``` ```text parameters: shape 9.63671, scale 0.155655 mean 1.5, std 0.4832 variability: low (std / mean 0.322) with no random generator, every draw is 1.5 YAML: {dist: gamma, shape: 9.63671, scale: 0.155655} Python: dist="gamma", shape=9.63671, scale=0.155655 ``` The lines after the mean read as follows: - The variability label is desflow's own scale for the standard deviation divided by the mean: `none` at 0, `low` below 0.75, `moderate` from 0.75 to 1.33, and `high` above 1.33. It is `low` here, because the standard deviation is about a third of the mean (0.322). - The fourth line is the value a `Sampler` with no seed gives for every draw. A run always has a seed, so it draws at random and never uses that value. A test can use the value to get the same times on every run, as [Arrivals and Services](https://jaehyeon.me/desflow/latest/user-guide/model-parts/arrivals-and-services/#how-it-works) explains. - The last two lines are the service in a blueprint and in the builder. An `exponential` has a standard deviation equal to its mean, a ratio of 1, so it is `moderate`. The arrivals of the busy hour show it. `--rate` gives the family's own parameter, here 1.8 orders a second: ```bash desflow dist exponential --rate 1.8 ``` ```text parameters: rate 1.8 mean 0.555556, std 0.555556 variability: moderate (std / mean 1) ``` The gap between two orders is 0.56 seconds on average, and its standard deviation is the same 0.56 seconds. ______________________________________________________________________ ## Same Mean, Different Waits All four candidates have the same mean, so the packers are equally busy with each: [utilisation](https://jaehyeon.me/desflow/latest/learn/concepts/queueing-basics/#utilisation) 0.9. Run the hour with each, and read the mean wait from the statistics at the `typical` level, which [Measuring a Run](https://jaehyeon.me/desflow/latest/learn/first-model/measuring-a-run/index.md) explains: ```yaml tasks: pack_order: # The candidate comes from the PACKING variable, empirical when it is not set service: ${PACKING:-empirical} resource: packers payload: {event_type: order_packed} # The mean wait of pack_order, published at the end stats: {level: typical, interval: 1 h} ``` ```bash # The mean wait with each packing-time distribution for packing in constant triangular empirical exponential; do PACKING=$packing desflow run choosing_inputs.yaml --stdout | grep -E 'pack_order\.wait_mean"' | tail -1 done ``` ```python # The task packs with the candidate; the mean wait is read at the end @app.task(service_id=packing, resource_id="packers") def pack_order(task_id): return {"event_type": "order_packed"} app.with_stats("typical", interval=3600) ``` ```python def pack_order(env, sampler, packers, packing, task_id): """One order, packed with the candidate called `packing`.""" env.stats.task_queued("pack_order", task_id) with packers.request() as request: yield request env.stats.task_started("pack_order", task_id) service = env.registry.get_config(f"Shop.service.{packing}") yield env.timeout(sampler.sample(service)) env.stats.task_finished("pack_order", task_id) ``` Each tab prints the mean wait of each candidate, in the order constant, triangular, empirical and exponential: ```text {"stream_type":"telemetry","sim_ts":3600.0,"timestamp":"...","path_id":"Shop.stats.tasks.pack_order.wait_mean","value":1.8791946460820799} {"stream_type":"telemetry","sim_ts":3600.0,"timestamp":"...","path_id":"Shop.stats.tasks.pack_order.wait_mean","value":1.9465363475526438} {"stream_type":"telemetry","sim_ts":3600.0,"timestamp":"...","path_id":"Shop.stats.tasks.pack_order.wait_mean","value":1.8059063505648683} {"stream_type":"telemetry","sim_ts":3600.0,"timestamp":"...","path_id":"Shop.stats.tasks.pack_order.wait_mean","value":3.461835405008601} ``` ```bash python choosing_inputs.py 2>/dev/null ``` ```text constant mean wait 1.88 s triangular mean wait 1.95 s empirical mean wait 1.81 s exponential mean wait 3.46 s ``` ```bash python choosing_inputs_low_level.py 2>/dev/null ``` ```text constant mean wait 1.88 s triangular mean wait 1.95 s empirical mean wait 1.81 s exponential mean wait 3.46 s ``` A mean alone hides queues. With constant packing nobody holds a packer for long. With exponential packing a few orders take 4, 5 or 6 seconds, and everyone behind them waits: the mean wait almost doubles at the same utilisation. ______________________________________________________________________ ## What You Get and Why Which distribution fits packing times? **The empirical distribution**, because it is the measured times themselves. The chart shows the shapes of the four candidates on the left, and the mean wait each gives in the busy hour on the right: With the empirical distribution the mean wait is **1.81 seconds**, from [one run of the hour with the seed 42 and no warm-up](https://jaehyeon.me/desflow/latest/learn/concepts/output-analysis/#busy-hour-figures), like each figure here. The constant mean gives 1.88 seconds, 4% longer than with the measured times. The exponential guess gives 3.46 seconds, 92% longer. The expert's triangle gives 1.95 seconds. These three are close, and one run does not put them in the order of their spreads: the measured times are a little below the constant, which has no spread. The exponential guess is the only one clearly apart. In the busy hour the mean wait grows with the spread of the gaps between orders and with the spread of the packing times. [Kingman's formula](https://jaehyeon.me/desflow/latest/learn/concepts/queueing-basics/#variation-lengthens-waits) puts it in numbers: the wait is roughly proportional to the square of one spread plus the square of the other, each spread measured relative to its mean. The gaps are the same in all four runs, so only the packing spread differs: none for `constant`, a little for `triangular`, more for the measured times, and as much as the mean itself for `exponential`. Replacing a distribution by its mean, as `constant` does, is one of the [Common Mistakes](https://jaehyeon.me/desflow/latest/learn/concepts/common-mistakes/#replacing-a-distribution-by-its-mean). [Arrivals and Services](https://jaehyeon.me/desflow/latest/user-guide/model-parts/arrivals-and-services/index.md) lists each distribution with its parameters and rules. [Fitting the Inputs](https://jaehyeon.me/desflow/latest/learn/inputs/fit-the-inputs/index.md) fits every family to the 40 times with `desflow fit`. [Input Fitting](https://jaehyeon.me/desflow/latest/user-guide/model-parts/input-fitting/index.md) describes its options and outcomes, and [Fit a Distribution](https://jaehyeon.me/desflow/latest/how-to/analysis/fit-a-distribution/index.md) fits a column of your own. [Distributions](https://jaehyeon.me/desflow/latest/reference/distributions/index.md) gives the mean and variance of each family. ## Key Takeaways - Use measured times when they exist: an empirical distribution draws from them. - Candidates with the same mean keep the packers equally busy, but give different waits, because waits grow with the spread of the times. - Replacing a distribution by its mean shortens the waits a model reports. ______________________________________________________________________ ## Full Files Full files ```yaml # The Choosing Inputs tutorial: the busy hour with four candidate packing times. # Run it once per candidate, and read the mean wait from the last lines: # PACKING=empirical desflow run choosing_inputs.yaml 2>&1 | grep wait_mean simulation: {sim_id: Shop, factor: 0, random_seed: 42} resources: packers: {current_cap: 3, max_cap: 10} arrivals: orders: {dist: exponential, rate: 1.8, spawn: pack_order} services: # Four candidates for packing, each with a mean of 1.5 seconds constant: {dist: constant, value: 1.5 s} exponential: {dist: exponential, rate: 0.6667} # 1 / 1.5 s # An expert's estimate: at least 1 s, usually 1.25 s, at most 2.25 s triangular: {dist: triangular, low: 1 s, mode: 1.25 s, high: 2.25 s} # 40 packing times measured at the bench, in seconds empirical: dist: empirical values: [1.5, 2.5, 2.4, 1.2, 1.3, 1.2, 1.8, 1.4, 2.0, 0.7, 2.7, 1.4, 1.9, 1.4, 1.3, 1.8, 2.0, 1.4, 1.4, 1.9, 1.1, 0.8, 1.7, 1.1, 0.7, 1.1, 1.2, 0.9, 0.8, 1.5, 2.1, 1.3, 1.1, 1.7, 1.9, 1.3, 1.8, 2.2, 1.4, 1.1] tasks: pack_order: # The candidate comes from the PACKING variable, empirical when it is not set service: ${PACKING:-empirical} resource: packers payload: {event_type: order_packed} # The mean wait of pack_order, published at the end stats: {level: typical, interval: 1 h} egress: - {type: Console} run: {until: 1 h} ``` ```python """The Choosing Inputs tutorial: the busy hour with four candidate packing times. Each candidate has a mean of 1.5 seconds. The script runs the busy hour once per candidate, unpaced, and prints the mean wait of each run. """ from desflow import SimulationContext CANDIDATES = ["constant", "triangular", "empirical", "exponential"] def shop(packing: str) -> SimulationContext: """The busy hour with 3 packers, packing with the service called `packing`.""" app = ( SimulationContext(sim_id="Shop", factor=0, random_seed=42) .add_resource("packers", current_cap=3, max_cap=10) # Each order starts the task pack_order .add_arrival("orders", dist="exponential", rate=1.8, spawn="pack_order") # Four candidates for packing, each with a mean of 1.5 seconds .add_service("constant", dist="constant", value=1.5) .add_service("exponential", dist="exponential", rate=0.6667) # 1 / 1.5 s ) # An expert's estimate: at least 1 s, usually 1.25 s, at most 2.25 s app.add_service("triangular", dist="triangular", low=1, mode=1.25, high=2.25) # 40 packing times measured at the bench, in seconds measured = [ 1.5, 2.5, 2.4, 1.2, 1.3, 1.2, 1.8, 1.4, 2.0, 0.7, 2.7, 1.4, 1.9, 1.4, 1.3, 1.8, 2.0, 1.4, 1.4, 1.9, 1.1, 0.8, 1.7, 1.1, 0.7, 1.1, 1.2, 0.9, 0.8, 1.5, 2.1, 1.3, 1.1, 1.7, 1.9, 1.3, 1.8, 2.2, 1.4, 1.1, ] # fmt: skip app.add_service("empirical", dist="empirical", values=measured) # The task packs with the candidate; the mean wait is read at the end @app.task(service_id=packing, resource_id="packers") def pack_order(task_id): return {"event_type": "order_packed"} app.with_stats("typical", interval=3600) return app def mean_wait(packing: str) -> float: """Runs the busy hour with one candidate and returns the mean wait.""" app = shop(packing) app.run(until="1 h") return app.env.stats.readings()["Shop.stats.tasks.pack_order.wait_mean"] if __name__ == "__main__": for packing in CANDIDATES: print(f"{packing:<12} mean wait {mean_wait(packing):5.2f} s") ``` ```python """The Choosing Inputs tutorial: the busy hour with four candidate packing times. Each candidate has a mean of 1.5 seconds. The script runs the busy hour once per candidate, unpaced, and prints the mean wait of each run. """ from desflow import ( CapacityConfig, DistributionConfig, DynamicRealtimeEnvironment, DynamicResource, Sampler, SimParameter, ) CANDIDATES = ["constant", "triangular", "empirical", "exponential"] # An expert's estimate: at least 1 s, usually 1.25 s, at most 2.25 s TRIANGULAR = DistributionConfig(dist="triangular", low=1, mode=1.25, high=2.25) # 40 packing times measured at the bench, in seconds MEASURED = [ 1.5, 2.5, 2.4, 1.2, 1.3, 1.2, 1.8, 1.4, 2.0, 0.7, 2.7, 1.4, 1.9, 1.4, 1.3, 1.8, 2.0, 1.4, 1.4, 1.9, 1.1, 0.8, 1.7, 1.1, 0.7, 1.1, 1.2, 0.9, 0.8, 1.5, 2.1, 1.3, 1.1, 1.7, 1.9, 1.3, 1.8, 2.2, 1.4, 1.1, ] # fmt: skip EMPIRICAL = DistributionConfig(dist="empirical", values=MEASURED) def params() -> SimParameter: """The busy hour with 3 packers and the four candidates.""" return SimParameter( sim_id="Shop", arrival={"orders": DistributionConfig(dist="exponential", rate=1.8)}, # Four candidates for packing, each with a mean of 1.5 seconds service={ "constant": DistributionConfig(dist="constant", value=1.5), "exponential": DistributionConfig(dist="exponential", rate=0.6667), "triangular": TRIANGULAR, "empirical": EMPIRICAL, }, resources={"packers": CapacityConfig(current_cap=3, max_cap=10)}, ) def pack_order(env, sampler, packers, packing, task_id): """One order, packed with the candidate called `packing`.""" env.stats.task_queued("pack_order", task_id) with packers.request() as request: yield request env.stats.task_started("pack_order", task_id) service = env.registry.get_config(f"Shop.service.{packing}") yield env.timeout(sampler.sample(service)) env.stats.task_finished("pack_order", task_id) def order_generator(env, sampler, packers, packing): arrival = env.registry.get_config("Shop.arrival.orders") task_id = 0 while True: yield env.timeout(sampler.sample(arrival)) env.process(pack_order(env, sampler, packers, packing, task_id)) task_id += 1 def mean_wait(packing: str) -> float: """Runs the busy hour with one candidate and returns the mean wait.""" env = DynamicRealtimeEnvironment(factor=0) env.registry.register_sim_parameter(params()) env.setup_stats("Shop", "typical", interval=3600) packers = DynamicResource(env, "Shop", "packers") env.process(order_generator(env, Sampler(seed=42), packers, packing)) try: env.run(until=3600) finally: env.teardown() return env.stats.readings()["Shop.stats.tasks.pack_order.wait_mean"] if __name__ == "__main__": for packing in CANDIDATES: print(f"{packing:<12} mean wait {mean_wait(packing):5.2f} s") ``` # Fitting the Inputs [Choosing Inputs](https://jaehyeon.me/desflow/latest/learn/inputs/choosing-inputs/index.md) compared four candidates for the packing time by hand and chose the 40 times measured at the bench. desflow can fit every distribution family to those times and say which fits best. A fit is worth making for two reasons. The 40 times can only repeat themselves, while a fitted distribution also draws longer times than any of the 40, in the tail where long waits come from. A fitted distribution's parameters are also registry paths, so a running model can change them, which a list of 40 times cannot do. This page asks: **which supported distribution fits the 40 packing times, and does the choice change the busy hour's answer?** - **Decision:** which fitted distribution the busy hour uses for packing. - **Measures:** how well each distribution fits the times, and the busy hour's mean wait with the two best fits and with the 40 times. - **Runs:** 40 replications of the busy hour with 3 packers for each distribution, with seeds spawned from 42, each after a 2-minute warm-up. - **Assumptions:** orders arrive at random at 1.8 a second, and the 40 times stand for every packer. ## What You Will Learn This page shows how to: - fit every distribution family to measured times with `desflow fit`; - read the AIC and the KS test of each fit, and look at the fit in a plot; - check whether the choice of fit changes the answer. ## What You Add This page runs `desflow fit`, or `fit_column` in Python, on the 40 packing times. It then uses the fitted settings in the busy hour of [Choosing Inputs](https://jaehyeon.me/desflow/latest/learn/inputs/choosing-inputs/index.md), in place of the times themselves. Fitting needs the `fit` extra, which adds scipy and matplotlib: ```bash # desflow command, with uv uv tool install "desflow[fit]" # A Python file, with uv outside a project uv run --with "desflow[fit]" python fit_the_inputs.py # In a uv project uv add "desflow[fit]" # With pip pip install "desflow[fit]" ``` ______________________________________________________________________ ## Fit the Packing Times Save the files from [Full Files](#full-files) in one folder, with `packing.yaml`, `packing_gamma.yaml` and `packing_times.yaml` in a `fitted` folder inside it, and run the commands there. The two fit commands on this page write `packing.yaml` and `packing_gamma.yaml` again. Fit the times, which are in seconds and cannot be below 0: ```bash # Fit the packing times, write the best fit and plot every candidate desflow fit packing_times.csv --column packing_seconds --lower 0 --out fitted/packing.yaml --plot fit.png ``` `packing_times.csv`, in [Full Files](#full-files), has a column `packing_seconds` with the 40 times. `--out` writes the best candidate's settings, and `--plot` draws the data against it. ```python # The 40 packing times, in seconds; none can be below 0 result = fit_column(MEASURED, unit="s", lower=0) print(result.text()) # every candidate, its status and diagnostics ``` ```python # The 40 packing times, in seconds; none can be below 0 result = fit_column(MEASURED, unit="s", lower=0) print(result.text()) # every candidate, its status and diagnostics ``` desflow fits each family by maximum likelihood: it chooses the parameters under which the measured values are most probable. It then checks each fit and prints one row per family: ```text 40 rows: 40 used, 0 missing, 0 invalid family status AIC KS stat KS p (approx.) parameters or reason exponential rejected its std is 1.5, the data's is 0.4832: more than 25% apart normal fitted 59.33 0.157 0.2504 mean=1.5, std=0.483218 (can draw below the lower bound 0) lognormal fitted 57.33 0.09406 0.8385 mean=1.50251, std=0.511854 truncated_normal fitted 59.25 0.1558 0.2579 mean=1.49836, std=0.48579, low=0 constant skipped the values are not all equal uniform fitted 59.45 0.225 0.02923 low=0.7, high=2.7 triangular * fitted 56.68 0.1258 0.511 low=0.546332, mode=1.2, high=2.83766 gamma fitted 56.79 0.1157 0.6165 shape=9.55777, scale=0.15694 weibull fitted 58.99 0.1502 0.2972 shape=3.33522, scale=1.67203 empirical fitted values: 40 numbers * best: triangular ``` Lower AIC is better, and a small KS p-value is a reason to reject a family. [A Simulation Study](https://jaehyeon.me/desflow/latest/learn/concepts/a-simulation-study/#aic-and-the-ks-test) explains both scores. The `KS stat` column is the KS statistic, and the next column is its p-value. desflow reports the p-value but does not reject a family on it. Each family's outcome is: - `triangular` has the lowest AIC, 56.68, and is marked best. `gamma` is 0.11 behind it. - `uniform` stays `fitted` with a p-value of 0.029. That is below 0.05, which is a reason not to use it. - `normal` fitted, but it can draw values below 0. desflow does not choose it while another family that stays within the bounds fits. - `exponential` was rejected: its standard deviation equals its mean, 1.5 seconds, more than three times the data's 0.4832. - `constant` was skipped, because the times are not all equal. - `empirical`, the 40 times themselves, is always offered. ______________________________________________________________________ ## Look at the Fit `--plot`, or `result.plot("fit.png")`, draws the data against 10,000 values drawn from the best fit through desflow's `Sampler`, as a run draws them: On the left, the data and the generated values cover the same range. On the right, each sorted packing time is plotted against the generated value at the same quantile. Points on the diagonal mean the two agree. Forty values cannot show much more than that. ______________________________________________________________________ ## Load the Settings The fitted settings go where the 40 times were: ```yaml services: # The best fit of the 40 packing times, as desflow fit wrote it, or the fit # file the PACKING_FIT variable names packing: !include ${PACKING_FIT:-fitted/packing.yaml} ``` `!include` reads a mapping from another file, relative to the blueprint. The file `desflow fit` wrote: ```yaml # Fitted by desflow fit from packing_times.csv, column packing_seconds: triangular, from # 40 values in s, written in seconds. dist: triangular low: 0.546332 mode: 1.2 high: 2.83766 ``` ```python # The best fit's settings: dist="triangular", low, mode and high .add_service("packing", **packing) ``` ```python params = SimParameter( sim_id="Shop", arrival={"orders": DistributionConfig(dist="exponential", rate=1.8)}, # The best fit's settings: dist="triangular", low, mode and high service={"packing": DistributionConfig(**packing)}, resources={"packers": CapacityConfig(current_cap=3, max_cap=10)}, ) ``` `result.settings()` returns the best candidate's settings, the same numbers as the file, so a script and a blueprint that use the same fit draw the same values. `result.settings("gamma")` returns the gamma's. ______________________________________________________________________ ## Does the Choice Matter? Run the busy hour 40 times with each distribution, each time with a different seed. These runs are **[replications](https://jaehyeon.me/desflow/latest/learn/concepts/output-analysis/#replications)**. The mean wait differs from one replication to the next. The 95% [half-width](https://jaehyeon.me/desflow/latest/learn/concepts/output-analysis/#interval-and-half-width) below says how far the mean of the 40 replications can be from the true mean wait. Each replication also leaves out its first 2 minutes, a **[warm-up](https://jaehyeon.me/desflow/latest/learn/concepts/output-analysis/#one-run-starts-empty)**, because the shop starts empty and its first orders wait less than later ones. [Trusting Results](https://jaehyeon.me/desflow/latest/learn/studies/trusting-results/index.md) shows how to choose both numbers. Each tab prints the mean wait and half-width of the three rows below, in the order of the table. In YAML, the three files in `fitted/` come from Full Files, and `fitted/packing_times.yaml` holds the 40 times as they are: ```bash # The triangular, the best fit, from fitted/packing.yaml desflow run fit_the_inputs.yaml --replications 40 --measure tasks.pack_order.wait_mean | grep '^tasks' # The gamma PACKING_FIT=fitted/packing_gamma.yaml desflow run fit_the_inputs.yaml --replications 40 --measure tasks.pack_order.wait_mean | grep '^tasks' # The 40 times PACKING_FIT=fitted/packing_times.yaml desflow run fit_the_inputs.yaml --replications 40 --measure tasks.pack_order.wait_mean | grep '^tasks' ``` ```text tasks.pack_order.wait_mean 40 2.583 0.1278 tasks.pack_order.wait_mean 40 2.11 0.1004 tasks.pack_order.wait_mean 40 2.1 0.1004 ``` ```yaml # The 40 packing times of packing_times.csv, column packing_seconds, as they are, in # seconds. dist: empirical values: [1.5, 2.5, 2.4, 1.2, 1.3, 1.2, 1.8, 1.4, 2.0, 0.7, 2.7, 1.4, 1.9, 1.4, 1.3, 1.8, 2.0, 1.4, 1.4, 1.9, 1.1, 0.8, 1.7, 1.1, 0.7, 1.1, 1.2, 0.9, 0.8, 1.5, 2.1, 1.3, 1.1, 1.7, 1.9, 1.3, 1.8, 2.2, 1.4, 1.1] ``` ```bash python fit_the_inputs.py 2>/dev/null | tail -3 ``` ```text triangular: mean wait 2.58 ± 0.13 s gamma: mean wait 2.11 ± 0.10 s empirical: mean wait 2.10 ± 0.10 s ``` ```bash python fit_the_inputs_low_level.py 2>/dev/null | tail -3 ``` ```text triangular: mean wait 2.58 ± 0.13 s gamma: mean wait 2.11 ± 0.10 s empirical: mean wait 2.10 ± 0.10 s ``` The table gives each distribution's mean packing time, and the [mean wait over the 40 replications](https://jaehyeon.me/desflow/latest/learn/concepts/output-analysis/#busy-hour-figures) with its half-width: | Packing time | Mean packing time (s) | Mean wait over 40 replications (s) | | -------------------------- | --------------------- | ---------------------------------- | | triangular, the lowest AIC | 1.53 | 2.58 ± 0.13 | | gamma | 1.50 | 2.11 ± 0.10 | | the 40 times | 1.50 | 2.10 ± 0.10 | ______________________________________________________________________ ## What You Get and Why Which supported distribution fits the 40 packing times? The `triangular` has the lowest AIC, but the `gamma` fits almost as well, 0.11 behind. By the guideline in [AIC and the KS Test](https://jaehyeon.me/desflow/latest/learn/concepts/a-simulation-study/#aic-and-the-ks-test), a difference this small does not tell two fits apart. The choice does change the answer. Over 40 replications after a 2-minute warm-up, with seeds spawned from 42, the triangular gives a mean wait of **2.58 ± 0.13 seconds**, and the gamma **2.11 ± 0.10**, which agrees with the 2.10 ± 0.10 of the 40 times. The gamma fits almost as well and gives the same answer as the measured times, so it is the better choice for this question. The first file the page loads holds the triangular only because `desflow fit` writes the candidate with the lowest AIC. An AIC difference this small does not make it the better fit. `--candidates gamma` fits only the gamma (spaces around a name are ignored, and an unknown name is refused with the name quoted), and `PACKING_FIT` makes the blueprint include its file: ```bash # Fit only the gamma desflow fit packing_times.csv --column packing_seconds --lower 0 --candidates gamma --out fitted/packing_gamma.yaml # 40 runs with the gamma packing times PACKING_FIT=fitted/packing_gamma.yaml desflow run fit_the_inputs.yaml --replications 40 --measure tasks.pack_order.wait_mean ``` The file it writes: ```yaml # Fitted by desflow fit from packing_times.csv, column packing_seconds: gamma, from 40 # values in s, written in seconds. dist: gamma shape: 9.55777 scale: 0.15694 ``` In Python, `result.settings("gamma")` gives the same settings, as the Builder and Low-level scripts in [Full Files](#full-files) show. The triangular's mean is (0.546 + 1.2 + 2.838) ÷ 3 = 1.53 seconds, 2% above the data's 1.50. The gamma keeps the data's mean exactly: shape × scale = 9.558 × 0.157 = 1.50. With the packers busy 90% of the time, 2% more packing raises utilisation to about 0.92, and the packers' spare time falls from 10% to about 8%, a fifth less. The wait depends on the spare time, as [Waits Near Full Use](https://jaehyeon.me/desflow/latest/learn/concepts/queueing-basics/#waits-near-full-use) shows, so it grows far more than 2%: 2.58 seconds against 2.11. [Common Mistakes](https://jaehyeon.me/desflow/latest/learn/concepts/common-mistakes/#choosing-a-normal-or-uniform-by-habit) lists the choice of a family by habit, and [Input Fitting](https://jaehyeon.me/desflow/latest/user-guide/model-parts/input-fitting/index.md) describes every option and outcome. ## Key Takeaways - The family with the lowest AIC is not always the best choice: a small difference in AIC does not tell two fits apart. - A fit that changes the mean, even by 2%, can change the waits much more when the resource is busy. - Run the question with each close fit, and choose the one whose answer agrees with the data. ______________________________________________________________________ ## Full Files Full files ```yaml # The Fitting the Inputs tutorial: the busy hour, with a packing time fitted to the # data. Fit, then run it: # desflow fit packing_times.csv --column packing_seconds --lower 0 \ # --out fitted/packing.yaml # desflow run fit_the_inputs.yaml # 40 replications: desflow run fit_the_inputs.yaml --replications 40 --measure \ # tasks.pack_order.wait_mean # The gamma fit instead: write fitted/packing_gamma.yaml with --candidates gamma, then # PACKING_FIT=fitted/packing_gamma.yaml desflow run fit_the_inputs.yaml simulation: {sim_id: Shop, factor: 0, random_seed: 42, warmup: 2 min} resources: packers: {current_cap: 3, max_cap: 10} arrivals: orders: {dist: exponential, rate: 1.8, spawn: pack_order} services: # The best fit of the 40 packing times, as desflow fit wrote it, or the fit # file the PACKING_FIT variable names packing: !include ${PACKING_FIT:-fitted/packing.yaml} tasks: pack_order: service: packing resource: packers payload: {event_type: order_packed} stats: typical run: {until: 1 h} ``` ```yaml # Fitted by desflow fit from packing_times.csv, column packing_seconds: triangular, from # 40 values in s, written in seconds. dist: triangular low: 0.546332 mode: 1.2 high: 2.83766 ``` ```yaml # Fitted by desflow fit from packing_times.csv, column packing_seconds: gamma, from 40 # values in s, written in seconds. dist: gamma shape: 9.55777 scale: 0.15694 ``` ```yaml # The 40 packing times of packing_times.csv, column packing_seconds, as they are, in # seconds. dist: empirical values: [1.5, 2.5, 2.4, 1.2, 1.3, 1.2, 1.8, 1.4, 2.0, 0.7, 2.7, 1.4, 1.9, 1.4, 1.3, 1.8, 2.0, 1.4, 1.4, 1.9, 1.1, 0.8, 1.7, 1.1, 0.7, 1.1, 1.2, 0.9, 0.8, 1.5, 2.1, 1.3, 1.1, 1.7, 1.9, 1.3, 1.8, 2.2, 1.4, 1.1] ``` ```text bench_order,packing_seconds 1,1.5 2,2.5 3,2.4 4,1.2 5,1.3 6,1.2 7,1.8 8,1.4 9,2.0 10,0.7 11,2.7 12,1.4 13,1.9 14,1.4 15,1.3 16,1.8 17,2.0 18,1.4 19,1.4 20,1.9 21,1.1 22,0.8 23,1.7 24,1.1 25,0.7 26,1.1 27,1.2 28,0.9 29,0.8 30,1.5 31,2.1 32,1.3 33,1.1 34,1.7 35,1.9 36,1.3 37,1.8 38,2.2 39,1.4 40,1.1 ``` The three fitted files go in a folder `fitted` beside the blueprint. `desflow fit` can write `packing.yaml` and `packing_gamma.yaml` as the page shows. `packing_times.yaml` is the 40 times as they are, so save it from here. ```python """The Fitting the Inputs tutorial: which distribution fits the 40 packing times? builder. Fits every family to the 40 packing times measured at the bench and prints the table of candidates. Then it runs the busy hour 40 times with each of three packing distributions: the best fit, the gamma fit and the 40 times themselves. Each run leaves out a 2-minute warm-up. The script prints the mean wait for each distribution. """ import logging from desflow import SimulationContext, fit_column, replicate from measuring_a_run import MEASURED # The imported model logs at INFO; replications log only their warnings logging.getLogger("desflow").setLevel(logging.WARNING) def fitted(): """Every family fitted to the measured times.""" # The 40 packing times, in seconds; none can be below 0 result = fit_column(MEASURED, unit="s", lower=0) print(result.text()) # every candidate, its status and diagnostics return result def shop(packing=None) -> SimulationContext: """The busy hour; `packing` is a fit's settings, or None for the 40 times.""" if packing is None: packing = {"dist": "empirical", "values": MEASURED} app = ( SimulationContext(sim_id="Shop", factor=0, random_seed=42, warmup="2 min") .add_resource("packers", current_cap=3, max_cap=10) .add_arrival("orders", dist="exponential", rate=1.8) # The best fit's settings: dist="triangular", low, mode and high .add_service("packing", **packing) .with_stats("typical") ) @app.task(service_id="packing", resource_id="packers") def pack_order(task_id: int): return {"event_type": "order_packed"} @app.arrival_loop("orders") def order_generator(context: SimulationContext): task_id = 0 while True: order = yield context.wait_for_arrival("orders") context.spawn(pack_order(task_id, entity=order)) task_id += 1 return app def mean_waits(result) -> dict: """The mean wait over 40 replications, with each packing distribution.""" choices = { "triangular": result.settings(), "gamma": result.settings("gamma"), "empirical": None, } return { name: replicate( lambda: shop(packing), 40, seed=42, until="1 h", measures=["tasks.pack_order.wait_mean"], ).summary[0] for name, packing in choices.items() } if __name__ == "__main__": for name, row in mean_waits(fitted()).items(): print(f"{name}: mean wait {row['mean']:.2f} ± {row['half_width']:.2f} s") ``` ```python """The Measuring a Run tutorial: the busy hour, with built-in statistics, builder. Three packers, orders at 1.8 a second and the measured packing times. Every record, the statistics included, is printed to the terminal, and the script prints the final statistics again at the end. """ import logging from desflow import ConsoleEgress, SimulationContext logging.basicConfig( level=logging.INFO, format="%(levelname)s [%(asctime)s] %(message)s" ) # The 40 packing times measured at the bench, in seconds MEASURED = [ 1.5, 2.5, 2.4, 1.2, 1.3, 1.2, 1.8, 1.4, 2.0, 0.7, 2.7, 1.4, 1.9, 1.4, 1.3, 1.8, 2.0, 1.4, 1.4, 1.9, 1.1, 0.8, 1.7, 1.1, 0.7, 1.1, 1.2, 0.9, 0.8, 1.5, 2.1, 1.3, 1.1, 1.7, 1.9, 1.3, 1.8, 2.2, 1.4, 1.1, ] # fmt: skip app = ( SimulationContext(sim_id="Shop", factor=0, random_seed=42) .add_resource("packers", current_cap=3, max_cap=10) .add_arrival("orders", dist="exponential", rate=1.8) .add_service("packing", dist="empirical", values=MEASURED) # Counts, time averages, and the mean and maximum wait and service, every 10 s .with_stats("typical") .add_egress(ConsoleEgress()) ) @app.task(service_id="packing", resource_id="packers") def pack_order(task_id: int): return {"event_type": "order_packed"} @app.arrival_loop("orders") def order_generator(context: SimulationContext): task_id = 0 while True: order = yield context.wait_for_arrival("orders") context.spawn(pack_order(task_id, entity=order)) task_id += 1 if __name__ == "__main__": app.run(until="1 h") # The statistics are telemetry, so the console printed them; read them here too for name, value in app.env.stats.readings().items(): print(f"{name} = {value}") ``` ```python """The Fitting the Inputs tutorial: which distribution fits the 40 packing times? low-level. Fits every family to the 40 packing times measured at the bench and prints the table of candidates. Then it runs the busy hour 40 times with each of three packing distributions: the best fit, the gamma fit and the 40 times themselves. Each run leaves out a 2-minute warm-up. The script prints the mean wait for each distribution. """ import logging from desflow import ( CapacityConfig, DistributionConfig, DynamicResource, LowLevelModel, SimParameter, fit_column, replicate, ) from measuring_a_run_low_level import MEASURED, order_generator # The imported model logs at INFO; replications log only their warnings logging.getLogger("desflow").setLevel(logging.WARNING) # Records and statistics start after the first 2 minutes of each run WARMUP = 120.0 # seconds def fitted(): """Every family fitted to the measured times.""" # The 40 packing times, in seconds; none can be below 0 result = fit_column(MEASURED, unit="s", lower=0) print(result.text()) # every candidate, its status and diagnostics return result def busy_hour(packing): """The busy hour's model, with a packing distribution's settings.""" params = SimParameter( sim_id="Shop", arrival={"orders": DistributionConfig(dist="exponential", rate=1.8)}, # The best fit's settings: dist="triangular", low, mode and high service={"packing": DistributionConfig(**packing)}, resources={"packers": CapacityConfig(current_cap=3, max_cap=10)}, ) def model(env, sampler): env.registry.register_sim_parameter(params) packers = DynamicResource(env, "Shop", "packers") env.process(order_generator(env, sampler, packers)) return LowLevelModel(model, sim_id="Shop") def mean_waits(result) -> dict: """The mean wait over 40 replications, with each packing distribution.""" choices = { "triangular": result.settings(), "gamma": result.settings("gamma"), "empirical": {"dist": "empirical", "values": MEASURED}, } return { name: replicate( busy_hour(packing), 40, seed=42, until=3600, warmup=WARMUP, measures=["tasks.pack_order.wait_mean"], ).summary[0] for name, packing in choices.items() } if __name__ == "__main__": for name, row in mean_waits(fitted()).items(): print(f"{name}: mean wait {row['mean']:.2f} ± {row['half_width']:.2f} s") ``` ```python """The Measuring a Run tutorial: the busy hour, with built-in statistics, low-level. Three packers, orders at 1.8 a second and the measured packing times. The order process reports each step to the environment's statistics, which publish them as telemetry; the script prints the final statistics again at the end. """ import logging from desflow import ( CapacityConfig, ConsoleEgress, DistributionConfig, DynamicRealtimeEnvironment, DynamicResource, Sampler, SimParameter, ) logging.basicConfig( level=logging.INFO, format="%(levelname)s [%(asctime)s] %(message)s" ) # The 40 packing times measured at the bench, in seconds MEASURED = [ 1.5, 2.5, 2.4, 1.2, 1.3, 1.2, 1.8, 1.4, 2.0, 0.7, 2.7, 1.4, 1.9, 1.4, 1.3, 1.8, 2.0, 1.4, 1.4, 1.9, 1.1, 0.8, 1.7, 1.1, 0.7, 1.1, 1.2, 0.9, 0.8, 1.5, 2.1, 1.3, 1.1, 1.7, 1.9, 1.3, 1.8, 2.2, 1.4, 1.1, ] # fmt: skip PARAMS = SimParameter( sim_id="Shop", arrival={"orders": DistributionConfig(dist="exponential", rate=1.8)}, service={"packing": DistributionConfig(dist="empirical", values=MEASURED)}, resources={"packers": CapacityConfig(current_cap=3, max_cap=10)}, ) def pack_order(env, sampler, packers, key, task_id): """One order, which reports each step to the statistics.""" path_id = "Shop.service.packing" def publish(value): env.publish_event(key, value, task="pack_order", instance=task_id) publish( {"path_id": path_id, "sim_id": "Shop", "service": "packing", "status": "queued"} ) env.stats.task_queued("pack_order", task_id) with packers.request() as request: yield request publish( { "path_id": path_id, "sim_id": "Shop", "service": "packing", "status": "started", } ) env.stats.task_started("pack_order", task_id) yield env.timeout(sampler.sample(env.registry.get_config(path_id))) publish({"event_type": "order_packed"}) env.stats.task_finished("pack_order", task_id) env.stats.flow_finished("orders") # the order leaves the shop def order_generator(env, sampler, packers): arrival = env.registry.get_config("Shop.arrival.orders") task_id = 0 while True: yield env.timeout(sampler.sample(arrival)) env.stats.flow_started("orders") # the order enters the shop env.process(pack_order(env, sampler, packers, f"orders-{task_id + 1}", task_id)) task_id += 1 def run(until=3600, factor=0.0): env = DynamicRealtimeEnvironment(factor=factor) env.registry.register_sim_parameter(PARAMS) env.setup_egress([ConsoleEgress()]) # Counts, time averages, and the mean and maximum wait and service, every 10 s env.setup_stats("Shop", "typical", interval=10) packers = DynamicResource(env, "Shop", "packers") env.process(order_generator(env, Sampler(seed=42), packers)) try: env.run(until=until) finally: env.teardown() return env if __name__ == "__main__": env = run() # The statistics are telemetry, so the console printed them; read them here too for name, value in env.stats.readings().items(): print(f"{name} = {value}") ``` # Changing Demand The shop's one packer packs an order in 1.5 seconds, so it can pack 40 orders a minute. Orders usually arrive every 2.5 seconds on average (24 a minute, `rate: 0.4`). From 20 to 40 minutes a promotion brings an order every 1.11 seconds on average (54 a minute, `rate: 0.9`), more than one packer can pack. This page asks: **what does a 20-minute rush do to waits, and does a second packer for the rush keep them short?** - **Decision:** one packer or two during the rush. - **Measures:** the mean and the longest wait over the hour, and the number of orders packed. - **Runs:** two runs of the hour, one with one packer in the rush and one with two, each with the seed 42. - **Assumptions:** orders arrive at random at each rate, every order takes the same time to pack, and the rush starts and ends exactly on time. ## What You Will Learn This page shows how to: - change the arrival rate and the number of packers at set times with a schedule; - measure what a rush that ends does to the waits; - choose what to report for an hour that is not steady. ## What You Add This page adds a **schedule**: changes to the arrival rate and the number of packers at set times. The shop is the one from [First Simulation](https://jaehyeon.me/desflow/latest/learn/first-model/first-simulation/index.md), with packing at a constant 1.5 seconds. ______________________________________________________________________ ## Write the Schedule A schedule is a list of steps. Each step names a registry path, a value and the simulation time at which the value applies. The rush is four steps: the rate and the packers change at 20 minutes and change back at 40. Save the files from [Full Files](#full-files) in one folder and run the commands there: ```yaml # The rush from 20 to 40 minutes: an order every 1.11 s on average (rate 0.9), # and RUSH_PACKERS packers scenario: - {at: 20 min, path: Shop.arrival.orders.rate, value: 0.9} - {at: 20 min, path: Shop.resources.packers.current_cap, value: "${RUSH_PACKERS:-1}"} - {at: 40 min, path: Shop.arrival.orders.rate, value: 0.4} - {at: 40 min, path: Shop.resources.packers.current_cap, value: 1} ``` `${RUSH_PACKERS:-1}` reads the environment variable `RUSH_PACKERS`, so `RUSH_PACKERS=2 desflow run changing_demand.yaml` runs the second plan. ```python # The rush from 20 to 40 minutes: an order every 1.11 s on average (rate 0.9), # and rush_packers packers .add_scenario( [ {"at": "20 min", "path": "Shop.arrival.orders.rate", "value": 0.9}, { "at": "20 min", "path": "Shop.resources.packers.current_cap", "value": rush_packers, }, {"at": "40 min", "path": "Shop.arrival.orders.rate", "value": 0.4}, { "at": "40 min", "path": "Shop.resources.packers.current_cap", "value": 1, }, ] ) ``` ```python def schedule(rush_packers): """The rush from 20 to 40 minutes, with rush_packers packers. During the rush an order arrives every 1.11 s on average (rate 0.9). """ return [ {"at": 1200, "path": "Shop.arrival.orders.rate", "value": 0.9}, { "at": 1200, "path": "Shop.resources.packers.current_cap", "value": rush_packers, }, {"at": 2400, "path": "Shop.arrival.orders.rate", "value": 0.4}, {"at": 2400, "path": "Shop.resources.packers.current_cap", "value": 1}, ] ``` `run_scenario` is the SimPy process that applies the steps: ```python # Each step applies before every other event at its time env.process(run_scenario(env, schedule(rush_packers), until=3600)) ``` The steps follow the simulation clock, so the schedule repeats exactly on every run and at any `factor`. A step applies before every other event at its time: the order that arrives at 20 minutes draws its next gap from the rush rate. [Vary Arrivals by Time](https://jaehyeon.me/desflow/latest/how-to/modelling/time-varying-arrivals/#boundaries) sets out these boundaries. ______________________________________________________________________ ## What You Get and Why What does a 20-minute rush do to waits? With one packer, it builds a queue for the whole rush. In one run of the hour with the seed 42, the mean wait over the hour is **177.81 seconds** and the longest **453.38 seconds**, more than 7 minutes. A second packer for the rush keeps the mean at **0.93 seconds** and the longest at **11.48**. Both pack the same **2,054** orders: Each tab prints both plans: the orders packed, the mean wait and the longest wait. ```bash # One packer in the rush: orders packed, mean wait and longest wait desflow run changing_demand.yaml --stdout | grep -E 'pack_order\.(finished|wait_mean|wait_max)"' | tail -3 # Two packers in the rush RUSH_PACKERS=2 desflow run changing_demand.yaml --stdout | grep -E 'pack_order\.(finished|wait_mean|wait_max)"' | tail -3 ``` ```text {"stream_type":"telemetry","sim_ts":3600.0,"timestamp":"...","path_id":"Shop.stats.tasks.pack_order.finished","value":2054} {"stream_type":"telemetry","sim_ts":3600.0,"timestamp":"...","path_id":"Shop.stats.tasks.pack_order.wait_mean","value":177.806243989145} {"stream_type":"telemetry","sim_ts":3600.0,"timestamp":"...","path_id":"Shop.stats.tasks.pack_order.wait_max","value":453.38095500451755} {"stream_type":"telemetry","sim_ts":3600.0,"timestamp":"...","path_id":"Shop.stats.tasks.pack_order.finished","value":2054} {"stream_type":"telemetry","sim_ts":3600.0,"timestamp":"...","path_id":"Shop.stats.tasks.pack_order.wait_mean","value":0.9256089466996981} {"stream_type":"telemetry","sim_ts":3600.0,"timestamp":"...","path_id":"Shop.stats.tasks.pack_order.wait_max","value":11.477742012224326} ``` ```bash python changing_demand.py 2>/dev/null ``` ```text 1 in the rush: 2054 packed, mean wait 177.81 s, longest 453.38 s 2 in the rush: 2054 packed, mean wait 0.93 s, longest 11.48 s ``` ```bash python changing_demand_low_level.py 2>/dev/null ``` ```text 1 in the rush: 2054 packed, mean wait 177.81 s, longest 453.38 s 2 in the rush: 2054 packed, mean wait 0.93 s, longest 11.48 s ``` During the rush one packer would need 0.9 × 1.5 = 1.35 seconds of packing every second, more than it has. Orders arrive at 54 a minute and the packer finishes at most 40, so the queue grows by about 14 orders a minute for as long as the rush lasts. An overload that ends is a **finite overload**. When the rush ends the load falls to 0.4 × 1.5 = 0.6, and the packer works off the queue, here by about 59 minutes. A load that stays at 1 or above is different: its queue grows for as long as the run lasts, and no run length gives a stable mean wait, as [Queueing Basics](https://jaehyeon.me/desflow/latest/learn/concepts/queueing-basics/#utilisation) explains. A finite overload has an answer, but the answer depends on the schedule. A mean over the hour mixes the quiet minutes with the rush, so report the longest wait, or the waits during the rush, beside it. With two packers the rush load is 1.35 ÷ 2 = 0.68 for each packer, below 1, so waits stay short. ## Key Takeaways - A schedule follows the simulation clock, so it repeats exactly on every run and at any pace. - An overload that ends builds a queue that clears only after the rush, so the waits stay high for a while. - A mean over the hour mixes the rush with quiet minutes, so report the longest wait, or the waits during the rush, beside it. ______________________________________________________________________ ## Full Files Full files ```yaml # The Changing Demand tutorial: a 20-minute rush, with one packer or two. # Run it with: desflow run changing_demand.yaml # With a second packer for the rush: RUSH_PACKERS=2 desflow run changing_demand.yaml simulation: {sim_id: Shop, factor: 0, random_seed: 42} resources: packers: {current_cap: 1, max_cap: 2} services: packing: {dist: constant, value: 1.5 s} arrivals: orders: {dist: exponential, rate: 0.4, spawn: pack_order} tasks: pack_order: service: packing resource: packers payload: {event_type: order_packed} # The rush from 20 to 40 minutes: an order every 1.11 s on average (rate 0.9), # and RUSH_PACKERS packers scenario: - {at: 20 min, path: Shop.arrival.orders.rate, value: 0.9} - {at: 20 min, path: Shop.resources.packers.current_cap, value: "${RUSH_PACKERS:-1}"} - {at: 40 min, path: Shop.arrival.orders.rate, value: 0.4} - {at: 40 min, path: Shop.resources.packers.current_cap, value: 1} # Orders packed, and the mean and longest wait, at the end stats: {level: typical, interval: 2 h} egress: - {type: Console} run: {until: 1 h} ``` ```python """The Changing Demand tutorial: a 20-minute rush, with one packer or two. One packer and 1.5 seconds of packing. An order arrives every 2.5 seconds on average (rate 0.4), and every 1.11 seconds (rate 0.9) from 20 to 40 minutes. Every record is printed to the terminal, and the script prints the waits with one packer through the rush and with a second packer for it. To see only those lines, run: python changing_demand.py 2>/dev/null """ import logging from desflow import ConsoleEgress, SimulationContext logging.basicConfig( level=logging.INFO, format="%(levelname)s [%(asctime)s] %(message)s" ) def shop(rush_packers: int) -> SimulationContext: """The shop of First Simulation, with a rush from 20 to 40 minutes.""" app = ( SimulationContext(sim_id="Shop", factor=0, random_seed=42) .add_resource("packers", current_cap=1, max_cap=2) .add_service("packing", dist="constant", value=1.5) .add_arrival("orders", dist="exponential", rate=0.4) # The rush from 20 to 40 minutes: an order every 1.11 s on average (rate 0.9), # and rush_packers packers .add_scenario( [ {"at": "20 min", "path": "Shop.arrival.orders.rate", "value": 0.9}, { "at": "20 min", "path": "Shop.resources.packers.current_cap", "value": rush_packers, }, {"at": "40 min", "path": "Shop.arrival.orders.rate", "value": 0.4}, { "at": "40 min", "path": "Shop.resources.packers.current_cap", "value": 1, }, ] ) # Orders packed, and the mean and longest wait, at the end .with_stats("typical", interval=7200) .add_egress(ConsoleEgress()) ) @app.task(service_id="packing", resource_id="packers") def pack_order(task_id: int): return {"event_type": "order_packed"} @app.arrival_loop("orders") def order_generator(context: SimulationContext): task_id = 0 while True: # The gap is drawn from the rate in force now order = yield context.wait_for_arrival("orders") context.spawn(pack_order(task_id, entity=order)) task_id += 1 return app def outcomes(rush_packers: int) -> dict: """Runs the hour and returns the orders packed and their waits.""" app = shop(rush_packers) app.run(until="1 h") r = app.env.stats.readings() name = "Shop.stats.tasks.pack_order.{}".format return { "finished": r[name("finished")], "wait_mean": r[name("wait_mean")], "wait_max": r[name("wait_max")], } if __name__ == "__main__": for packers in (1, 2): r = outcomes(packers) print( f"{packers} in the rush: {r['finished']} packed, " f"mean wait {r['wait_mean']:5.2f} s, longest {r['wait_max']:6.2f} s" ) ``` ```python """The Changing Demand tutorial: a 20-minute rush, with one packer or two. One packer and 1.5 seconds of packing. An order arrives every 2.5 seconds on average (rate 0.4), and every 1.11 seconds (rate 0.9) from 20 to 40 minutes. Every record is printed to the terminal, and the script prints the waits with one packer through the rush and with a second packer for it. To see only those lines, run: python changing_demand_low_level.py 2>/dev/null """ import itertools import logging from desflow import ( CapacityConfig, ConsoleEgress, DistributionConfig, DynamicRealtimeEnvironment, DynamicResource, Sampler, SimParameter, run_scenario, ) logging.basicConfig( level=logging.INFO, format="%(levelname)s [%(asctime)s] %(message)s" ) PARAMS = SimParameter( sim_id="Shop", arrival={"orders": DistributionConfig(dist="exponential", rate=0.4)}, service={"packing": DistributionConfig(dist="constant", value=1.5)}, resources={"packers": CapacityConfig(current_cap=1, max_cap=2)}, ) def schedule(rush_packers): """The rush from 20 to 40 minutes, with rush_packers packers. During the rush an order arrives every 1.11 s on average (rate 0.9). """ return [ {"at": 1200, "path": "Shop.arrival.orders.rate", "value": 0.9}, { "at": 1200, "path": "Shop.resources.packers.current_cap", "value": rush_packers, }, {"at": 2400, "path": "Shop.arrival.orders.rate", "value": 0.4}, {"at": 2400, "path": "Shop.resources.packers.current_cap", "value": 1}, ] def pack_order(env, sampler, packers, key, task_id): path_id = "Shop.service.packing" def publish(value): env.publish_event(key, value, task="pack_order", instance=task_id) publish( {"path_id": path_id, "sim_id": "Shop", "service": "packing", "status": "queued"} ) env.stats.task_queued("pack_order", task_id) with packers.request() as request: yield request publish( { "path_id": path_id, "sim_id": "Shop", "service": "packing", "status": "started", } ) env.stats.task_started("pack_order", task_id) yield env.timeout(sampler.sample(env.registry.get_config(path_id))) publish({"event_type": "order_packed"}) env.stats.task_finished("pack_order", task_id) def order_generator(env, sampler, packers): arrival = env.registry.get_config("Shop.arrival.orders") for task_id in itertools.count(): # The gap is drawn from the rate in force now yield env.timeout(sampler.sample(arrival)) key = f"orders-{task_id + 1}" env.process(pack_order(env, sampler, packers, key, task_id)) def run(rush_packers=1, factor=0.0): env = DynamicRealtimeEnvironment(factor=factor) env.registry.register_sim_parameter(PARAMS) env.setup_egress([ConsoleEgress()]) # Orders packed, and the mean and longest wait, at the end env.setup_stats("Shop", "typical", interval=7200) packers = DynamicResource(env, "Shop", "packers") # Each step applies before every other event at its time env.process(run_scenario(env, schedule(rush_packers), until=3600)) env.process(order_generator(env, Sampler(seed=42), packers)) try: env.run(until=3600) finally: env.teardown() return env def outcomes(rush_packers: int) -> dict: """Runs the hour and returns the orders packed and their waits.""" r = run(rush_packers).stats.readings() name = "Shop.stats.tasks.pack_order.{}".format return { "finished": r[name("finished")], "wait_mean": r[name("wait_mean")], "wait_max": r[name("wait_max")], } if __name__ == "__main__": for packers in (1, 2): r = outcomes(packers) print( f"{packers} in the rush: {r['finished']} packed, " f"mean wait {r['wait_mean']:5.2f} s, longest {r['wait_max']:6.2f} s" ) ``` # Local Replay The shop recorded every order of one morning, 09:00 to 10:00 on 1 October 2026: 1,963 orders, one every 1.83 seconds on average (33 a minute). A model with exponential gaps at that rate says one packer keeps waits short. This page asks: **what does the shop do with the same orders, at the times they were really placed?** - **Decision:** whether one packer is enough for that morning. - **Measures:** the mean and the longest wait. - **Runs:** one replay of the recorded hour, and one run of the model with exponential gaps at the same mean rate and the seed 42, each from an order's arrival to the end of its packing. - **Assumptions:** every order takes the same time to pack. ## What You Will Learn This page shows how to: - replay the arrivals recorded in a file at their recorded times; - compare the replay with a model that has the same mean rate; - see what a mean rate leaves out. ## What You Add This page adds a **replayed arrival**: arrivals taken from the rows of a file instead of a distribution. The shop is the one from [First Simulation](https://jaehyeon.me/desflow/latest/learn/first-model/first-simulation/index.md), with packing at a constant 1.5 seconds. The recorded orders are [`local_replay_orders.csv`](https://raw.githubusercontent.com/jaehyeon-kim/desflow/v1.3.0/docs/snippets/tutorials/local_replay_orders.csv), one row per order. Save the files from [Full Files](#full-files) in one folder and run the commands there. Download the recorded orders into the same folder: ```bash # The recorded order times curl -O https://raw.githubusercontent.com/jaehyeon-kim/desflow/v1.3.0/docs/snippets/tutorials/local_replay_orders.csv ``` The file starts with these rows: ```text ordered_at,order_id,items 2026-10-01T09:00:00.3,A10001,2 2026-10-01T09:00:02.0,A10002,2 ``` ______________________________________________________________________ ## Replay the Rows Each row becomes one arrival at its time, and the fields named in `fields` become the order's attributes. `unit` says what the time column holds. It is `ms`, `s`, `min` or `h` from the start of the run, or `timestamp`, a date and time. A field is read as a number only when it is a CSV number, so `1_0`, `nan` and `0x1` stay text, and a time written like that is refused. A timestamp is placed on the run's clock from its `logical_start_time`, here 09:00 on the recorded day: ```yaml arrivals: orders: # Each row is one order, at its recorded time, carrying its order_id and items replay: path: local_replay_orders.csv time: ordered_at unit: timestamp fields: [order_id, items] # A row without a valid time is left out, with a warning naming it on_invalid: skip spawn: pack_order ``` The `path` is relative to the blueprint. ```python # Each row is one order, at its recorded time, carrying its order_id and items app.add_arrival_replay( "orders", TRACE, time="ordered_at", unit="timestamp", fields=["order_id", "items"], # A row without a valid time is left out, with a warning naming it on_invalid="skip", ) ``` The source can also be a list of dicts. The arrival loop is written as for any other arrival: ```python @app.arrival_loop("orders") def order_generator(context: SimulationContext): task_id = 0 while True: # The wait for the next row, as for any other arrival order = yield context.wait_for_arrival("orders") context.spawn(pack_order(task_id, entity=order)) task_id += 1 ``` ```python def replayed_orders(env, sampler, packers): """Starts one order at each row's time, carrying its order_id and items.""" rows = read_trace( TRACE, time="ordered_at", unit="timestamp", fields=["order_id", "items"], # A row without a valid time is left out, with a warning naming it on_invalid="skip", start=START, ) for task_id, row in enumerate(rows): # A row at or after the end of the run never arrives yield env.timeout(row.time - env.now) key = f"orders-{task_id + 1}" env.process(pack_order(env, sampler, packers, key, task_id, row.fields)) ``` `read_trace` reads and checks the rows. Each `row` has its simulation `time`, its row `number` and its `fields`. The rows are read and checked when the run starts, by the rules that [Replay](https://jaehyeon.me/desflow/latest/user-guide/model-parts/arrivals-and-services/#replay) lists. In the morning's file, times are given to a tenth of a second, so 74 rows have the same time as the row above them. Rows with the same time arrive in the order of the file. The 19 orders after 10:00 are at or after `until`, so they never arrive. Row 501 has no time, and `on_invalid: skip` leaves it out with a warning: ```text Skipped row 501, which has no valid ordered_at: '' ``` A Parquet file works the same way and needs the `parquet` extra. ______________________________________________________________________ ## What You Get and Why What does the shop do with the orders of the real morning? The replay shows something the model does not. Replayed, the orders wait **91.31 seconds** on average and up to **295.40 seconds**. In one run of the model, with exponential gaps at the same mean rate and the seed 42, orders wait **3.79 seconds** on average and at most **19.24**. The recorded morning holds two bursts of three minutes each, at 09:15 and 09:40. The packer clears the queue of the first burst only at about 09:32, and the queue of the second at about 09:54: The replay packs 1,962 of the 1,963 recorded orders: the last is still being packed when the hour ends, and `flows.orders.in_system` is 1. Each tab prints both runs: the orders packed, the mean wait and the longest wait. The second run is the model. Copy `local_replay.yaml` to `local_replay_modelled.yaml`, and replace its `replay:` block with `dist: exponential` and `rate: 0.545`, an order every 1.83 seconds on average. ```bash # The recorded orders: orders packed, mean wait and longest wait desflow run local_replay.yaml --stdout | grep -E 'pack_order\.(finished|wait_mean|wait_max)"' | tail -3 # The modelled orders desflow run local_replay_modelled.yaml --stdout | grep -E 'pack_order\.(finished|wait_mean|wait_max)"' | tail -3 ``` ```text {"stream_type":"telemetry","sim_ts":3600.0,"timestamp":"...","path_id":"Shop.stats.tasks.pack_order.finished","value":1962} {"stream_type":"telemetry","sim_ts":3600.0,"timestamp":"...","path_id":"Shop.stats.tasks.pack_order.wait_mean","value":91.3063678043811} {"stream_type":"telemetry","sim_ts":3600.0,"timestamp":"...","path_id":"Shop.stats.tasks.pack_order.wait_max","value":295.39999999999986} {"stream_type":"telemetry","sim_ts":3600.0,"timestamp":"...","path_id":"Shop.stats.tasks.pack_order.finished","value":1984} {"stream_type":"telemetry","sim_ts":3600.0,"timestamp":"...","path_id":"Shop.stats.tasks.pack_order.wait_mean","value":3.7877552416477402} {"stream_type":"telemetry","sim_ts":3600.0,"timestamp":"...","path_id":"Shop.stats.tasks.pack_order.wait_max","value":19.23704444923061} ``` ```bash python local_replay.py 2>/dev/null ``` ```text recorded: 1962 packed, mean wait 91.31 s, longest 295.40 s modelled: 1984 packed, mean wait 3.79 s, longest 19.24 s ``` ```bash python local_replay_low_level.py 2>/dev/null ``` ```text recorded: 1962 packed, mean wait 91.31 s, longest 295.40 s modelled: 1984 packed, mean wait 3.79 s, longest 19.24 s ``` A mean rate says how many orders come in an hour, not when they come. Exponential gaps spread the orders evenly over the hour, with small random clusters. The recorded morning has bursts that push the load above what one packer can pack for minutes at a time: a finite overload, like the rush of [Changing Demand](https://jaehyeon.me/desflow/latest/learn/inputs/changing-demand/index.md). Replaying the recorded rows keeps the bursts, so it shows waits the fitted model cannot. Use a replay to check a model against the data it was fitted to, as [Checking and Validating](https://jaehyeon.me/desflow/latest/learn/concepts/checking-and-validating/#compare-with-the-real-shop) describes. When the two disagree, the arrivals are not exponential at one rate, and the model needs a schedule, as on [Vary Arrivals by Time](https://jaehyeon.me/desflow/latest/how-to/modelling/time-varying-arrivals/index.md), or the replay itself. ## Key Takeaways - A replay keeps when the orders came, not only how many came. - Bursts in real data can overload a resource for minutes, which a model with exponential gaps at the mean rate does not show. - When a replay and a model disagree, the arrivals need a schedule, or the replay itself. ______________________________________________________________________ ## Full Files Full files ```yaml # The Local Replay tutorial: a recorded morning of orders, at their recorded times. # Run it with: desflow run local_replay.yaml simulation: sim_id: Shop factor: 0 random_seed: 42 # Simulation time 0 is 09:00 on the recorded day logical_start_time: 2026-10-01T09:00:00 resources: packers: {current_cap: 1, max_cap: 2} services: packing: {dist: constant, value: 1.5 s} arrivals: orders: # Each row is one order, at its recorded time, carrying its order_id and items replay: path: local_replay_orders.csv time: ordered_at unit: timestamp fields: [order_id, items] # A row without a valid time is left out, with a warning naming it on_invalid: skip spawn: pack_order tasks: pack_order: service: packing resource: packers payload: {event_type: order_packed} # Orders packed, and the mean and longest wait, at the end stats: {level: typical, interval: 2 h} egress: - {type: Console} run: {until: 1 h} ``` ```python """The Local Replay tutorial: a recorded morning of orders, against a model of it. One packer and 1.5 seconds of packing. The orders of 09:00 to 10:00 on 1 October 2026 arrive at their recorded times from local_replay_orders.csv. A second run draws exponential gaps at the same mean rate: an order every 1.83 seconds on average (rate 0.545). Every record is printed to the terminal, and the script prints the waits of both runs. To see only those lines, run: python local_replay.py 2>/dev/null """ import logging from datetime import datetime from pathlib import Path from desflow import ConsoleEgress, SimulationContext logging.basicConfig( level=logging.INFO, format="%(levelname)s [%(asctime)s] %(message)s" ) TRACE = Path(__file__).resolve().parent / "local_replay_orders.csv" def shop(replay: bool) -> SimulationContext: """One packer, with the recorded orders or with a model of them.""" app = ( SimulationContext( sim_id="Shop", factor=0, random_seed=42, # Simulation time 0 is 09:00 on the recorded day logical_start_time=datetime(2026, 10, 1, 9, 0), ) .add_resource("packers", current_cap=1, max_cap=2) .add_service("packing", dist="constant", value=1.5) # Orders packed, and the mean and longest wait, at the end .with_stats("typical", interval=7200) .add_egress(ConsoleEgress()) ) if replay: # Each row is one order, at its recorded time, carrying its order_id and items app.add_arrival_replay( "orders", TRACE, time="ordered_at", unit="timestamp", fields=["order_id", "items"], # A row without a valid time is left out, with a warning naming it on_invalid="skip", ) else: # The same mean rate: 1,963 orders in the hour app.add_arrival("orders", dist="exponential", rate=0.545) @app.task(service_id="packing", resource_id="packers") def pack_order(task_id: int): return {"event_type": "order_packed"} @app.arrival_loop("orders") def order_generator(context: SimulationContext): task_id = 0 while True: # The wait for the next row, as for any other arrival order = yield context.wait_for_arrival("orders") context.spawn(pack_order(task_id, entity=order)) task_id += 1 return app def outcomes(replay: bool) -> dict: """Runs the hour and returns the orders packed and their waits.""" app = shop(replay) app.run(until="1 h") r = app.env.stats.readings() name = "Shop.stats.tasks.pack_order.{}".format return { "finished": r[name("finished")], "wait_mean": r[name("wait_mean")], "wait_max": r[name("wait_max")], } if __name__ == "__main__": for replay in (True, False): r = outcomes(replay) label = "recorded" if replay else "modelled" print( f"{label}: {r['finished']} packed, " f"mean wait {r['wait_mean']:5.2f} s, longest {r['wait_max']:6.2f} s" ) ``` ```python """The Local Replay tutorial: a recorded morning of orders, against a model of it. One packer and 1.5 seconds of packing. The orders of 09:00 to 10:00 on 1 October 2026 arrive at their recorded times from local_replay_orders.csv. A second run draws exponential gaps at the same mean rate: an order every 1.83 seconds on average (rate 0.545). Every record is printed to the terminal, and the script prints the waits of both runs. To see only those lines, run: python local_replay_low_level.py 2>/dev/null """ import itertools import logging from datetime import datetime from pathlib import Path from desflow import ( CapacityConfig, ConsoleEgress, DistributionConfig, DynamicRealtimeEnvironment, DynamicResource, Sampler, SimParameter, read_trace, ) logging.basicConfig( level=logging.INFO, format="%(levelname)s [%(asctime)s] %(message)s" ) TRACE = Path(__file__).resolve().parent / "local_replay_orders.csv" START = datetime(2026, 10, 1, 9, 0) # simulation time 0 is 09:00 on the recorded day PARAMS = SimParameter( sim_id="Shop", # The same mean rate: 1,963 orders in the hour arrival={"orders": DistributionConfig(dist="exponential", rate=0.545)}, service={"packing": DistributionConfig(dist="constant", value=1.5)}, resources={"packers": CapacityConfig(current_cap=1, max_cap=2)}, ) def pack_order(env, sampler, packers, key, task_id, fields): path_id = "Shop.service.packing" def publish(value): env.publish_event(key, value, task="pack_order", instance=task_id) publish( {"path_id": path_id, "sim_id": "Shop", "service": "packing", "status": "queued"} ) env.stats.task_queued("pack_order", task_id) with packers.request() as request: yield request publish( { "path_id": path_id, "sim_id": "Shop", "service": "packing", "status": "started", } ) env.stats.task_started("pack_order", task_id) yield env.timeout(sampler.sample(env.registry.get_config(path_id))) publish({"event_type": "order_packed"}) env.stats.task_finished("pack_order", task_id) def replayed_orders(env, sampler, packers): """Starts one order at each row's time, carrying its order_id and items.""" rows = read_trace( TRACE, time="ordered_at", unit="timestamp", fields=["order_id", "items"], # A row without a valid time is left out, with a warning naming it on_invalid="skip", start=START, ) for task_id, row in enumerate(rows): # A row at or after the end of the run never arrives yield env.timeout(row.time - env.now) key = f"orders-{task_id + 1}" env.process(pack_order(env, sampler, packers, key, task_id, row.fields)) def modelled_orders(env, sampler, packers): arrival = env.registry.get_config("Shop.arrival.orders") for task_id in itertools.count(): yield env.timeout(sampler.sample(arrival)) key = f"orders-{task_id + 1}" env.process(pack_order(env, sampler, packers, key, task_id, {})) def run(replay=True, factor=0.0): env = DynamicRealtimeEnvironment(factor=factor, logical_start_time=START) env.registry.register_sim_parameter(PARAMS) env.setup_egress([ConsoleEgress()]) # Orders packed, and the mean and longest wait, at the end env.setup_stats("Shop", "typical", interval=7200) packers = DynamicResource(env, "Shop", "packers") orders = replayed_orders if replay else modelled_orders env.process(orders(env, Sampler(seed=42), packers)) try: env.run(until=3600) finally: env.teardown() return env def outcomes(replay: bool) -> dict: """Runs the hour and returns the orders packed and their waits.""" r = run(replay).stats.readings() name = "Shop.stats.tasks.pack_order.{}".format return { "finished": r[name("finished")], "wait_mean": r[name("wait_mean")], "wait_max": r[name("wait_max")], } if __name__ == "__main__": for replay in (True, False): r = outcomes(replay) label = "recorded" if replay else "modelled" print( f"{label}: {r['finished']} packed, " f"mean wait {r['wait_mean']:5.2f} s, longest {r['wait_max']:6.2f} s" ) ``` # Stock Every order needs a box, and boxes come from a shelf that a delivery fills every 100 seconds. In that time about 50 orders arrive on average, and each takes one box. This page asks: **what happens when stock runs out?** - **Decision:** the size of each delivery: 60 boxes or 40. - **Measures:** the mean wait for packing and how often the shelf is empty. - **Runs:** two runs of the hour, one for each delivery size, each with the seed 42 and starting with 50 boxes on the shelf. - **Assumptions:** orders arrive at random, every delivery comes on time, and every order takes the same time to pack. ## What You Will Learn This page shows how to: - hold boxes in a container that packing takes from and deliveries fill; - watch the stock's level over a run; - see what happens when deliveries cannot keep up with orders. ## What You Add This page adds a `stock` container, from which packing takes one box per order, and a `deliveries` arrival, whose task adds boxes to the shelf. The shop is the one from [First Simulation](https://jaehyeon.me/desflow/latest/learn/first-model/first-simulation/index.md): one packer, an order every 2 seconds on average, and 1.5 seconds of packing. ______________________________________________________________________ ## Hold Stock So far each order needed only a packer, a **resource** that it holds and gives back. Stock is different: it is a **quantity**, which some tasks take away and others add, and which is not given back. In SimPy it is a `Container`: a level between 0 and a capacity, with `get(amount)` to take and `put(amount)` to add. A `get` waits while the level is too low, and a `put` waits while there is no room. A desflow container behaves like a SimPy `Container` in all three APIs. The tests compare its waiting gets and puts with a plain SimPy `Container` ([SimPy Compatibility](https://jaehyeon.me/desflow/latest/simpy/compatibility/index.md)). In desflow it is a container in the `containers` section. Its `current_cap` is the capacity, the most it can hold, and `level` is what it holds when the run starts: ```yaml containers: # Boxes on the shelf: room for 200, and 50 when the run starts stock: {current_cap: 200, max_cap: 200, level: 50} ``` ```python # Boxes on the shelf: room for 200, and 50 when the run starts app.add_container("stock", current_cap=200, max_cap=200, level=50) ``` ```python # Boxes on the shelf: room for 200, and 50 when the run starts containers={"stock": ContainerConfig(current_cap=200, max_cap=200, level=50)}, ``` A `ContainerConfig` holds the level a container starts at. The `DynamicContainer` built in `run` reads it, as the full file below shows. The run builds the container, as it builds the packers. Look at what can wait on it: ______________________________________________________________________ ## Take and Restock Packing an order takes one box. The task gets its packer first and then its box, so an order that finds the shelf empty waits for stock while it holds the packer: ```yaml pack_order: service: packing resource: packers # One box per order, taken once the order has a packer; waits while stock is 0 get: {container: stock, amount: 1} payload: {event_type: order_packed} ``` ```python # One box per order, taken once the order has a packer; waits while stock is 0 @app.task( service_id="packing", resource_id="packers", get={"container": "stock", "amount": 1}, ) def pack_order(task_id: int): return {"event_type": "order_packed"} ``` ```python with shop["packers"].request() as request: yield request # One box per order, taken once the order has a packer; waits while stock is 0 yield shop["stock"].get(1) ``` The stock is a SimPy container: `get(1)` is an event that happens when the level covers the amount, and the process waits at the `yield` until then. [SimPy and desflow](https://jaehyeon.me/desflow/latest/simpy/#containers-and-stores) describes containers and stores. Save the files from [Full Files](#full-files) in one folder and run the commands there. A delivery arrives every 100 seconds, and its task puts the boxes on the shelf. The task waits while there is no room for all of them. It has no service and no resource, so it takes no time and publishes its payload once the boxes are on the shelf: ```yaml # A delivery every 100 seconds deliveries: {dist: constant, value: 100 s, spawn: restock} ``` ```yaml restock: # Adds the delivery to the shelf; waits while there is no room for it all put: container: stock amount: ${DELIVERY:-60} payload: {event_type: stock_delivered} ``` `${DELIVERY:-60}` reads the environment variable `DELIVERY`, 60 when it is not set, so `DELIVERY=40 desflow run stock.yaml` runs the smaller deliveries. ```python # A delivery every 100 seconds app.add_arrival("deliveries", dist="constant", value=100) # Adds the delivery to the shelf; waits while there is no room for it all @app.task(put={"container": "stock", "amount": delivery}) def restock(task_id: int): return {"event_type": "stock_delivered"} @app.arrival_loop("deliveries") def delivery_generator(context: SimulationContext): task_id = 0 while True: arrival = yield context.wait_for_arrival("deliveries") context.spawn(restock(task_id, entity=arrival)) task_id += 1 ``` ```python def restock(env, shop, delivery, key, task_id): """Adds the delivery to the shelf; waits while there is no room for it all.""" yield shop["stock"].put(delivery) value = {"event_type": "stock_delivered"} env.publish_event(key, value, task="restock", instance=task_id) def delivery_generator(env, sampler, shop, delivery): arrival = env.registry.get_config("Shop.arrival.deliveries") task_id = 0 while True: yield env.timeout(sampler.sample(arrival)) key = f"deliveries-{task_id + 1}" env.process(restock(env, shop, delivery, key, task_id)) task_id += 1 ``` ______________________________________________________________________ ## Watch the Level At the `minimal` level and above, the built-in statistics publish each container's `capacity`, `level`, `getters_waiting` and `putters_waiting`. `typical` adds the mean wait. [Statistics](https://jaehyeon.me/desflow/latest/user-guide/results/statistics/index.md) describes the statistics: ```yaml # The stock's level and waiting tasks every 10 seconds, and the mean wait at the end stats: typical ``` ```python # The stock's level and waiting tasks every 10 seconds, and the mean wait .with_stats("typical") ``` ```python # The stock's level and waiting tasks every 10 seconds, and the mean wait env.setup_stats("Shop", "typical", interval=10) ``` With deliveries of 40, the shelf runs out before the third delivery. Each reading publishes every statistic of the level. The block keeps three of them, around the stock-out: the packer queue, the level and the orders waiting for a box: ```text [TEL] {'sim_ts': 270.0, 'timestamp': '...', 'path_id': 'Shop.stats.resources.packers.queue_length', 'value': 2} [TEL] {'sim_ts': 270.0, 'timestamp': '...', 'path_id': 'Shop.stats.containers.stock.level', 'value': 7} [TEL] {'sim_ts': 270.0, 'timestamp': '...', 'path_id': 'Shop.stats.containers.stock.getters_waiting', 'value': 0} [TEL] {'sim_ts': 280.0, 'timestamp': '...', 'path_id': 'Shop.stats.resources.packers.queue_length', 'value': 1} [TEL] {'sim_ts': 280.0, 'timestamp': '...', 'path_id': 'Shop.stats.containers.stock.level', 'value': 3} [TEL] {'sim_ts': 280.0, 'timestamp': '...', 'path_id': 'Shop.stats.containers.stock.getters_waiting', 'value': 0} [TEL] {'sim_ts': 290.0, 'timestamp': '...', 'path_id': 'Shop.stats.resources.packers.queue_length', 'value': 3} [TEL] {'sim_ts': 290.0, 'timestamp': '...', 'path_id': 'Shop.stats.containers.stock.level', 'value': 0} [TEL] {'sim_ts': 290.0, 'timestamp': '...', 'path_id': 'Shop.stats.containers.stock.getters_waiting', 'value': 1} [TEL] {'sim_ts': 300.0, 'timestamp': '...', 'path_id': 'Shop.stats.resources.packers.queue_length', 'value': 6} [TEL] {'sim_ts': 300.0, 'timestamp': '...', 'path_id': 'Shop.stats.containers.stock.level', 'value': 40} [TEL] {'sim_ts': 300.0, 'timestamp': '...', 'path_id': 'Shop.stats.containers.stock.getters_waiting', 'value': 1} ``` At 290 seconds the shelf is empty, one order waits for a box, and three more wait behind it for the packer. The delivery at 300 seconds puts 40 boxes on the shelf. The waiting order takes its box at that same moment, just after the reading. The level is also a registry path, `Shop.containers.stock.level`, so a scenario step or a message from outside can set it during a run, as a stock count would. [Stores and Containers](https://jaehyeon.me/desflow/latest/user-guide/model-parts/stores-and-containers/index.md) describes what such an update does. ______________________________________________________________________ ## What You Get and Why What happens when stock runs out? Orders wait for boxes, and when deliveries cannot keep up, the wait grows all hour. The level over the first 30 minutes, for both delivery sizes: These figures come from one run of the hour for each delivery size, with the seed 42. With deliveries of 60, the mean wait for packing is **2.54 seconds**, and stock never runs out. With deliveries of 40, the mean wait is **330.02 seconds**, and the shelf is empty for about 40 of every 100 seconds. Deliveries of 40 boxes every 100 seconds allow at most 40 orders to be packed in 100 seconds, while 50 arrive on average. So the packer queue grows all hour, as with too few packers on [Queues and Capacity](https://jaehyeon.me/desflow/latest/learn/first-model/queues-and-capacity/index.md). Each tab prints the mean wait for deliveries of 60, then of 40: ```bash desflow run stock.yaml --stdout | grep -E 'pack_order\.wait_mean"' | tail -1 DELIVERY=40 desflow run stock.yaml --stdout | grep -E 'pack_order\.wait_mean"' | tail -1 ``` ```text {"stream_type":"telemetry","sim_ts":3600.0,"timestamp":"...","path_id":"Shop.stats.tasks.pack_order.wait_mean","value":2.5353067783084926} {"stream_type":"telemetry","sim_ts":3600.0,"timestamp":"...","path_id":"Shop.stats.tasks.pack_order.wait_mean","value":330.02115687302364} ``` ```bash python stock.py 2>/dev/null ``` ```text deliveries of 60: mean wait 2.54 s deliveries of 40: mean wait 330.02 s ``` ```bash python stock_low_level.py 2>/dev/null ``` ```text deliveries of 60: mean wait 2.54 s deliveries of 40: mean wait 330.02 s ``` Stock adds a second queue: orders wait at the shelf as well as at the packer. Packing takes its packer before its box. So the shelf's queue is never longer than the number of packers, and the other orders wait in the packer queue behind it. An empty shelf therefore also stops the packer. A task whose resource is scarce can take the box first instead: the `get` goes in a task of its own, with no resource, and that task names the packing task in `next`. The long queue then forms at the shelf, and the packer stays free: ```yaml take_box: # One box per order, taken before the packer; waits while stock is 0 get: {container: stock, amount: 1} payload: {event_type: box_taken} next: pack_order pack_order: service: packing resource: packers payload: {event_type: order_packed} ``` The Builder writes `take_box` with `get={"container": "stock", "amount": 1}` and `next="pack_order"`, and `pack_order` with `resource_id="packers"`. The YAML tab shows the keys. The low-level form takes the box first with `yield stock.get(1)` and then requests a packer. The YAML tab shows the two tasks. The arrival spawns `take_box` in place of `pack_order`. Either way, supply below demand means a queue that grows for as long as the run lasts, as [Queueing Basics](https://jaehyeon.me/desflow/latest/learn/concepts/queueing-basics/#utilisation) explains for a packer. [Stores and Containers](https://jaehyeon.me/desflow/latest/user-guide/model-parts/stores-and-containers/index.md) describes both kinds of holding. ## Key Takeaways - Stock adds a second queue, at the shelf, beside the queue at the packer. - Packing takes its packer before its box, so an empty shelf also stops the packer. - Supply below demand gives a queue that grows for as long as the run lasts, as too few packers do. ______________________________________________________________________ ## Full Files Full files ```yaml # The Stock tutorial: packing takes a box from stock, and deliveries restock it. # Run it with: desflow run stock.yaml # With smaller deliveries: DELIVERY=40 desflow run stock.yaml simulation: {sim_id: Shop, factor: 0, random_seed: 42} resources: packers: {current_cap: 1, max_cap: 4} services: packing: {dist: constant, value: 1.5 s} containers: # Boxes on the shelf: room for 200, and 50 when the run starts stock: {current_cap: 200, max_cap: 200, level: 50} arrivals: # One order every 2 seconds on average: 50 boxes every 100 seconds orders: {dist: exponential, rate: 0.5, spawn: pack_order} # A delivery every 100 seconds deliveries: {dist: constant, value: 100 s, spawn: restock} tasks: pack_order: service: packing resource: packers # One box per order, taken once the order has a packer; waits while stock is 0 get: {container: stock, amount: 1} payload: {event_type: order_packed} restock: # Adds the delivery to the shelf; waits while there is no room for it all put: container: stock amount: ${DELIVERY:-60} payload: {event_type: stock_delivered} # The stock's level and waiting tasks every 10 seconds, and the mean wait at the end stats: typical egress: - {type: Console} run: {until: 1 h} ``` ```python """The Stock tutorial: packing takes a box from stock, and deliveries restock it. One packer, an order every 2 seconds on average, and a delivery of boxes every 100 seconds. Every record is printed to the terminal, and the script prints the mean wait for 60-box and 40-box deliveries at the end. To see only those lines, run: python stock.py 2>/dev/null """ import logging from desflow import ConsoleEgress, SimulationContext logging.basicConfig( level=logging.INFO, format="%(levelname)s [%(asctime)s] %(message)s" ) def shop(delivery: float = 60) -> SimulationContext: """The shop with deliveries of `delivery` boxes every 100 seconds.""" app = ( SimulationContext(sim_id="Shop", factor=0, random_seed=42) .add_resource("packers", current_cap=1, max_cap=4) .add_service("packing", dist="constant", value=1.5) # One order every 2 seconds on average: 50 boxes every 100 seconds .add_arrival("orders", dist="exponential", rate=0.5) # The stock's level and waiting tasks every 10 seconds, and the mean wait .with_stats("typical") .add_egress(ConsoleEgress()) ) # Boxes on the shelf: room for 200, and 50 when the run starts app.add_container("stock", current_cap=200, max_cap=200, level=50) # One box per order, taken once the order has a packer; waits while stock is 0 @app.task( service_id="packing", resource_id="packers", get={"container": "stock", "amount": 1}, ) def pack_order(task_id: int): return {"event_type": "order_packed"} @app.arrival_loop("orders") def order_generator(context: SimulationContext): task_id = 0 while True: order = yield context.wait_for_arrival("orders") context.spawn(pack_order(task_id, entity=order)) task_id += 1 # A delivery every 100 seconds app.add_arrival("deliveries", dist="constant", value=100) # Adds the delivery to the shelf; waits while there is no room for it all @app.task(put={"container": "stock", "amount": delivery}) def restock(task_id: int): return {"event_type": "stock_delivered"} @app.arrival_loop("deliveries") def delivery_generator(context: SimulationContext): task_id = 0 while True: arrival = yield context.wait_for_arrival("deliveries") context.spawn(restock(task_id, entity=arrival)) task_id += 1 return app def mean_wait(delivery: float) -> float: """Runs one hour and returns the mean wait for packing.""" app = shop(delivery) app.run(until="1 h") return app.env.stats.readings()["Shop.stats.tasks.pack_order.wait_mean"] if __name__ == "__main__": for delivery in (60, 40): print(f"deliveries of {delivery}: mean wait {mean_wait(delivery):6.2f} s") ``` ```python """The Stock tutorial: packing takes a box from stock, and deliveries restock it. One packer, an order every 2 seconds on average, and a delivery of boxes every 100 seconds. Every record is printed to the terminal, and the script prints the mean wait for 60-box and 40-box deliveries at the end. To see only those lines, run: python stock_low_level.py 2>/dev/null """ import logging from desflow import ( CapacityConfig, ConsoleEgress, ContainerConfig, DistributionConfig, DynamicContainer, DynamicRealtimeEnvironment, DynamicResource, Sampler, SimParameter, ) logging.basicConfig( level=logging.INFO, format="%(levelname)s [%(asctime)s] %(message)s" ) PARAMS = SimParameter( sim_id="Shop", arrival={ # One order every 2 seconds on average: 50 boxes every 100 seconds "orders": DistributionConfig(dist="exponential", rate=0.5), # A delivery every 100 seconds "deliveries": DistributionConfig(dist="constant", value=100), }, service={"packing": DistributionConfig(dist="constant", value=1.5)}, resources={"packers": CapacityConfig(current_cap=1, max_cap=4)}, # Boxes on the shelf: room for 200, and 50 when the run starts containers={"stock": ContainerConfig(current_cap=200, max_cap=200, level=50)}, ) def pack_order(env, sampler, shop, key, task_id): path_id = "Shop.service.packing" def publish(value): env.publish_event(key, value, task="pack_order", instance=task_id) publish( {"path_id": path_id, "sim_id": "Shop", "service": "packing", "status": "queued"} ) env.stats.task_queued("pack_order", task_id) with shop["packers"].request() as request: yield request # One box per order, taken once the order has a packer; waits while stock is 0 yield shop["stock"].get(1) publish( { "path_id": path_id, "sim_id": "Shop", "service": "packing", "status": "started", } ) env.stats.task_started("pack_order", task_id) yield env.timeout(sampler.sample(env.registry.get_config(path_id))) publish({"event_type": "order_packed"}) env.stats.task_finished("pack_order", task_id) def order_generator(env, sampler, shop): arrival = env.registry.get_config("Shop.arrival.orders") task_id = 0 while True: yield env.timeout(sampler.sample(arrival)) env.process(pack_order(env, sampler, shop, f"orders-{task_id + 1}", task_id)) task_id += 1 def restock(env, shop, delivery, key, task_id): """Adds the delivery to the shelf; waits while there is no room for it all.""" yield shop["stock"].put(delivery) value = {"event_type": "stock_delivered"} env.publish_event(key, value, task="restock", instance=task_id) def delivery_generator(env, sampler, shop, delivery): arrival = env.registry.get_config("Shop.arrival.deliveries") task_id = 0 while True: yield env.timeout(sampler.sample(arrival)) key = f"deliveries-{task_id + 1}" env.process(restock(env, shop, delivery, key, task_id)) task_id += 1 def run(delivery=60, until=3600, factor=0.0): env = DynamicRealtimeEnvironment(factor=factor) env.registry.register_sim_parameter(PARAMS) env.setup_egress([ConsoleEgress()]) # The stock's level and waiting tasks every 10 seconds, and the mean wait env.setup_stats("Shop", "typical", interval=10) shop = { "packers": DynamicResource(env, "Shop", "packers"), # Starts at the level its ContainerConfig gives, 50 "stock": DynamicContainer(env, "Shop", "stock"), } sampler = Sampler(seed=42) env.process(order_generator(env, sampler, shop)) env.process(delivery_generator(env, sampler, shop, delivery)) try: env.run(until=until) finally: env.teardown() return env def mean_wait(delivery: float) -> float: """Runs one hour and returns the mean wait for packing.""" return run(delivery).stats.readings()["Shop.stats.tasks.pack_order.wait_mean"] if __name__ == "__main__": for delivery in (60, 40): print(f"deliveries of {delivery}: mean wait {mean_wait(delivery):6.2f} s") ``` # Priorities A quarter of the shop's orders are now express: the customer paid for speed. With one packer and an order every 1.67 seconds on average (36 a minute), an order waits about 5 seconds on average. This page asks: **can express orders jump the queue?** And what does that cost the others? - **Decision:** whether the packer serves express orders first or every order in order of arrival. - **Measures:** the mean wait of express orders and of regular orders. - **Runs:** two runs of the hour, one for each queue order, each with the seed 42, then runs at two lower arrival rates. - **Assumptions:** both kinds of order arrive at random at steady rates, and every order takes the same time to pack. ## What You Will Learn This page shows how to: - serve a resource's queue by priority instead of in order of arrival; - give express orders priority over regular ones; - measure what priority costs the orders that wait longer. ## What You Add This page adds an `express` arrival, whose task has `priority: 0`, while regular orders keep `priority: 1`. It also makes the packer serve its queue by priority. The shop is the one from [First Simulation](https://jaehyeon.me/desflow/latest/learn/first-model/first-simulation/index.md), with one packer and 1.5 seconds of packing. A regular order arrives every 2.22 seconds on average (27 a minute, `rate: 0.45`), and an express order every 6.67 seconds (9 a minute, `rate: 0.15`). ______________________________________________________________________ ## Order the Queue Which waiting entity a resource serves next is its **queue discipline**. The usual one is first in, first out (FIFO). Others are last in, first out (LIFO), and service by priority. Look at four requests that join a queue while the packer is busy, and the order each discipline serves them in: SimPy has a `PriorityResource` for the priority discipline, and a `PriorityStore` for items. In desflow every resource has a `queue`: `fifo` (the default), `lifo` or `priority`. Under `priority` the lowest number goes first, and requests with the same priority are served first in, first out. Save the files from [Full Files](#full-files) in one folder and run the commands there: ```yaml resources: # The packer serves the lowest priority first, the oldest first among equals packers: {current_cap: 1, max_cap: 4, queue: priority} ``` ```python # The packer serves the lowest priority first, the oldest first among equals app.add_resource("packers", current_cap=1, max_cap=4, queue=queue) ``` ```python # The packer serves the lowest priority first, the oldest first among equals packers = DynamicResource(env, "Shop", "packers", queue=queue) ``` ______________________________________________________________________ ## Give Express Orders Priority Each task gives its requests a priority. Express orders get 0, so they are served before any regular order that is waiting. Regular orders get 1: ```yaml tasks: pack_order: service: packing resource: packers priority: 1 payload: {event_type: order_packed} pack_express: service: packing resource: packers priority: 0 # served before any regular order that is waiting payload: {event_type: express_packed} ``` Here each task has a fixed number. A priority can also be an expression that reads the entity's attributes, such as `priority: attr.priority`, so each order gets its own. [Task Flow](https://jaehyeon.me/desflow/latest/user-guide/model-parts/task-flow/#attributes) describes attributes. A `priority` on a task whose resource does not have `queue: priority` is refused when the file loads. So to run the shop under `fifo`, remove `queue: priority` and both `priority` lines. A resource can also rank its line by a rule of its own: `queue: {rank: attr.priority, ties: fifo}` serves the lowest rank first, and `ties` orders equal ranks as `fifo` or `lifo`. A `priority` on a task is refused on a resource that has a `rank`. A rank or priority that is NaN or text is refused with the resource and the task named. A priority is not an expression of the order's payload, because the payload exists only when the task finishes. ```python @app.task(service_id="packing", resource_id="packers", priority=rank(1)) def pack_order(task_id: int): return {"event_type": "order_packed"} # Served before any regular order that is waiting @app.task(service_id="packing", resource_id="packers", priority=rank(0)) def pack_express(task_id: int): return {"event_type": "express_packed"} ``` `rank` gives each task its priority under `priority`, and no priority under `fifo`, because a priority on a resource with another queue order is refused when the run starts. A task's priority can also be an expression, such as `priority="attr.tier"`, or a function of the task id and the entity's attributes, such as `priority=lambda task_id, attributes: attributes["tier"]`, so each order gets its own. The priority can come from the attributes because they exist before the order joins the queue. The payload does not exist yet. ```python # Express orders are served before any regular order that is waiting TASKS = {"orders": ("pack_order", 1), "express": ("pack_express", 0)} ``` ```python # Under fifo and lifo the priority is ignored with packers.request(priority=priority) as request: ``` In the low-level API each request carries its priority. A resource whose queue is `fifo` or `lifo` ignores it, so the same code runs under every queue order. Both kinds of order use the same packer, so they share one queue. The built-in statistics keep a separate mean wait for each task: `Shop.stats.tasks.pack_express.wait_mean` and `Shop.stats.tasks.pack_order.wait_mean`. [Statistics](https://jaehyeon.me/desflow/latest/user-guide/results/statistics/index.md) describes them. ______________________________________________________________________ ## Starvation Priority has a price. A regular order is served only when no express order is waiting, so every express order that arrives while it waits pushes it back. The price grows quickly as the shop gets busier. Run the hour once with the seed 42 at each of three total arrival rates, with a quarter of the orders express each time. When no rate is given, a regular order arrives every 2.22 seconds (27 a minute, `0.45`) and an express order every 6.67 seconds (9 a minute, `0.15`), 36 orders a minute in all (0.6 a second). The commands below run 30 orders a minute (0.5 a second) with the rates `0.375` and `0.125`, and print the mean wait of a regular order under `priority`: The variables `ORDERS_RATE` and `EXPRESS_RATE` set the two rates. ```bash ORDERS_RATE=0.375 EXPRESS_RATE=0.125 desflow run priorities.yaml --stdout | grep -E 'pack_order\.wait_mean"' | tail -1 ``` ```text {"stream_type":"telemetry","sim_ts":3600.0,"timestamp":"...","path_id":"Shop.stats.tasks.pack_order.wait_mean","value":2.6988794009208137} ``` The two rates are the arguments of the script. ```bash python priorities.py 0.375 0.125 2>/dev/null | grep -E '^priority +pack_order' ``` ```text priority pack_order mean wait 2.70 s ``` ```bash python priorities_low_level.py 0.375 0.125 2>/dev/null | grep -E '^priority +pack_order' ``` ```text priority pack_order mean wait 2.70 s ``` Use the rates `0.4125` and `0.1375`, as variables in YAML and as arguments in the scripts, for 33 a minute (0.55). For 36 a minute (0.6), leave the rates out, because those are the file's own rates. The mean wait of a regular order is 2.70 seconds at 30 orders a minute, 4.12 seconds at 33 a minute and 7.17 seconds at 36 a minute. Express orders wait less than a second on average at all three rates. If express orders alone kept the packer busy, regular orders would never be served at all: they would **starve**. `desflow explain` shows how busy the packer is at the default 36 orders a minute, without a run. Its output includes these lines: ```bash desflow explain priorities.yaml ``` ```text Resources +--------------------------------------------------------+ | resource | λ | μ | c | ρ | Wq | L | status | |----------+-----+--------+---+-----+----+---+-----------| | packers | 0.6 | 0.6667 | 1 | 0.9 | - | - | CONGESTED | +--------------------------------------------------------+ Not estimated: wait at packers: a priority queue serves its tasks in a different order from first come, first served; run --verify to measure it ``` At utilisation 0.9 the packer is `CONGESTED`: orders often wait in a long queue, so the order in which it is served matters. `explain` gives no wait here, because its formulas assume first come, first served. The runs above measure the waits instead. In Python, `context.analyze()` gives the same analysis for a builder model. A low-level model has no `explain`, because its SimPy code makes the links between arrivals, tasks and resources as it runs, so there are none to read. ______________________________________________________________________ ## What You Get and Why Can express orders jump the queue? **Yes**, and the regular orders pay for it. Each tab prints the mean wait of each kind of order, under `fifo`, then under `priority`: The `fifo` run needs its own file, because a priority on a `fifo` resource is refused when the file loads. `priorities_fifo.yaml` is `priorities.yaml` without `queue: priority` and without the two `priority:` lines: ```yaml resources: # The packer serves the oldest request first packers: {current_cap: 1, max_cap: 4} ``` ```yaml tasks: pack_order: service: packing resource: packers payload: {event_type: order_packed} pack_express: service: packing resource: packers payload: {event_type: express_packed} ``` ```bash # First come, first served: the mean wait of each kind of order desflow run priorities_fifo.yaml --stdout | grep -E 'pack_(order|express)\.wait_mean"' | tail -2 # Express orders first desflow run priorities.yaml --stdout | grep -E 'pack_(order|express)\.wait_mean"' | tail -2 ``` ```text {"stream_type":"telemetry","sim_ts":3600.0,"timestamp":"...","path_id":"Shop.stats.tasks.pack_order.wait_mean","value":5.718486776602804} {"stream_type":"telemetry","sim_ts":3600.0,"timestamp":"...","path_id":"Shop.stats.tasks.pack_express.wait_mean","value":5.444253373607553} {"stream_type":"telemetry","sim_ts":3600.0,"timestamp":"...","path_id":"Shop.stats.tasks.pack_order.wait_mean","value":7.174611091045217} {"stream_type":"telemetry","sim_ts":3600.0,"timestamp":"...","path_id":"Shop.stats.tasks.pack_express.wait_mean","value":0.8578810127630234} ``` ```bash python priorities.py 2>/dev/null ``` ```text fifo pack_express mean wait 5.44 s fifo pack_order mean wait 5.72 s priority pack_express mean wait 0.86 s priority pack_order mean wait 7.17 s ``` ```bash python priorities_low_level.py 2>/dev/null ``` ```text fifo pack_express mean wait 5.44 s fifo pack_order mean wait 5.72 s priority pack_express mean wait 0.86 s priority pack_order mean wait 7.17 s ``` In one run of the hour with the seed 42, under `priority`, express orders wait **0.86 seconds** on average instead of **5.44**. Regular orders pay for it: **7.17 seconds** instead of **5.72**. Priority does not make the packer faster, so it cannot remove waiting. It only decides who waits. Weighted by how many orders of each kind arrive, the mean wait is 0.75 × 5.72 + 0.25 × 5.44 = 5.65 seconds under `fifo` and 0.75 × 7.17 + 0.25 × 0.86 = 5.59 seconds under `priority`: almost the same total, shared out differently. Both queue orders keep the packer busy the same share of the time, 0.6 × 1.5 = 0.9 ([utilisation](https://jaehyeon.me/desflow/latest/learn/concepts/queueing-basics/#utilisation)). Every order takes the same time, so the queue holds the same number of orders on average under both, and [Little's Law](https://jaehyeon.me/desflow/latest/learn/concepts/queueing-basics/#littles-law) turns that number into the same mean wait over all orders. [Resources](https://jaehyeon.me/desflow/latest/user-guide/resources/index.md) describes how the queue orders requests. Plain SimPy's `PriorityResource`, which [SimPy and desflow](https://jaehyeon.me/desflow/latest/simpy/#resources) shows, serves these requests in the same order, ties included. The tests check the order in all three APIs ([SimPy Compatibility](https://jaehyeon.me/desflow/latest/simpy/compatibility/index.md)). Items can be ranked too: a priority store returns the parcel with the lowest priority first, as [Stores and Containers](https://jaehyeon.me/desflow/latest/user-guide/model-parts/stores-and-containers/#start-with-items-and-serve-by-priority) describes. A resource's priority decides which request is served, and a store's priority decides which item is taken. ## Key Takeaways - Every resource has a queue order: `fifo` (the default), `lifo` or `priority`. Under `priority` the lowest number goes first. - Priority does not make the packer faster. It only decides who waits, so the mean wait over all orders hardly changes. - The orders that lose priority pay for it, and their price grows quickly as the shop gets busier. ______________________________________________________________________ ## Full Files Full files ```yaml # The Priorities tutorial: express orders go before regular ones. # Run it with: desflow run priorities.yaml simulation: {sim_id: Shop, factor: 0, random_seed: 42} resources: # The packer serves the lowest priority first, the oldest first among equals packers: {current_cap: 1, max_cap: 4, queue: priority} services: packing: {dist: constant, value: 1.5 s} arrivals: # An order every 1.67 s on average in all (0.6 a second), one in four express; # ORDERS_RATE and EXPRESS_RATE set other rates orders: {dist: exponential, rate: "${ORDERS_RATE:-0.45}", spawn: pack_order} express: {dist: exponential, rate: "${EXPRESS_RATE:-0.15}", spawn: pack_express} tasks: pack_order: service: packing resource: packers priority: 1 payload: {event_type: order_packed} pack_express: service: packing resource: packers priority: 0 # served before any regular order that is waiting payload: {event_type: express_packed} # The mean wait of each task at the end stats: {level: typical, interval: 1 h} egress: - {type: Console} run: {until: 1 h} ``` ```python """The Priorities tutorial: express orders go before regular ones, builder. One packer and 1.5 seconds of packing. A regular order arrives every 2.22 seconds on average (rate 0.45), and an express order every 6.67 seconds (rate 0.15). Every record is printed to the terminal, and the script prints the mean wait of each kind of order under each queue order at the end. To see only those lines, run: python priorities.py 2>/dev/null To use other rates, give the two as arguments: python priorities.py 0.375 0.125 """ import logging import sys from desflow import ConsoleEgress, SimulationContext logging.basicConfig( level=logging.INFO, format="%(levelname)s [%(asctime)s] %(message)s" ) def shop( queue: str = "priority", orders_rate: float = 0.45, express_rate: float = 0.15 ) -> SimulationContext: """The shop with the packer's queue in `queue` order and the two arrival rates.""" def rank(value): # A priority counts only under the priority order, and the other orders # refuse one, so under fifo the tasks have none return value if queue == "priority" else None app = ( SimulationContext(sim_id="Shop", factor=0, random_seed=42) .add_service("packing", dist="constant", value=1.5) # An order every 1.67 s on average in all (0.6 a second), one in four express .add_arrival("orders", dist="exponential", rate=orders_rate) .add_arrival("express", dist="exponential", rate=express_rate) .with_stats("typical", interval=3600) # the mean wait of each task .add_egress(ConsoleEgress()) ) # The packer serves the lowest priority first, the oldest first among equals app.add_resource("packers", current_cap=1, max_cap=4, queue=queue) @app.task(service_id="packing", resource_id="packers", priority=rank(1)) def pack_order(task_id: int): return {"event_type": "order_packed"} # Served before any regular order that is waiting @app.task(service_id="packing", resource_id="packers", priority=rank(0)) def pack_express(task_id: int): return {"event_type": "express_packed"} def loop(arrival, task): def generator(context: SimulationContext): task_id = 0 while True: order = yield context.wait_for_arrival(arrival) context.spawn(task(task_id, entity=order)) task_id += 1 return generator app.arrival_loop("orders")(loop("orders", pack_order)) app.arrival_loop("express")(loop("express", pack_express)) return app def mean_waits( queue: str, orders_rate: float = 0.45, express_rate: float = 0.15 ) -> dict: """Runs one hour and returns the mean wait of each task.""" app = shop(queue, orders_rate, express_rate) app.run(until="1 h") readings = app.env.stats.readings() return { task: readings[f"Shop.stats.tasks.{task}.wait_mean"] for task in ("pack_express", "pack_order") } if __name__ == "__main__": rates = [float(rate) for rate in sys.argv[1:3]] for queue in ("fifo", "priority"): for task, wait in mean_waits(queue, *rates).items(): print(f"{queue:<8} {task:<12} mean wait {wait:5.2f} s") ``` ```python """The Priorities tutorial: express orders go before regular ones, low-level. One packer and 1.5 seconds of packing. A regular order arrives every 2.22 seconds on average (rate 0.45), and an express order every 6.67 seconds (rate 0.15). Every record is printed to the terminal, and the script prints the mean wait of each kind of order under each queue order at the end. To see only those lines, run: python priorities_low_level.py 2>/dev/null To use other rates, give the two as arguments: python priorities_low_level.py 0.375 0.125 """ import copy import logging import sys from desflow import ( CapacityConfig, ConsoleEgress, DistributionConfig, DynamicRealtimeEnvironment, DynamicResource, Sampler, SimParameter, ) logging.basicConfig( level=logging.INFO, format="%(levelname)s [%(asctime)s] %(message)s" ) PARAMS = SimParameter( sim_id="Shop", arrival={ # An order every 1.67 s on average in all (0.6 a second), one in four express "orders": DistributionConfig(dist="exponential", rate=0.45), "express": DistributionConfig(dist="exponential", rate=0.15), }, service={"packing": DistributionConfig(dist="constant", value=1.5)}, resources={"packers": CapacityConfig(current_cap=1, max_cap=4)}, ) # Express orders are served before any regular order that is waiting TASKS = {"orders": ("pack_order", 1), "express": ("pack_express", 0)} def pack(env, sampler, packers, arrival, key, task_id): task, priority = TASKS[arrival] path_id = "Shop.service.packing" def publish(value): env.publish_event(key, value, task=task, instance=task_id) publish( {"path_id": path_id, "sim_id": "Shop", "service": "packing", "status": "queued"} ) env.stats.task_queued(task, task_id) # Under fifo and lifo the priority is ignored with packers.request(priority=priority) as request: yield request publish( { "path_id": path_id, "sim_id": "Shop", "service": "packing", "status": "started", } ) env.stats.task_started(task, task_id) yield env.timeout(sampler.sample(env.registry.get_config(path_id))) event = "express_packed" if arrival == "express" else "order_packed" publish({"event_type": event}) env.stats.task_finished(task, task_id) def order_generator(env, sampler, packers, arrival): config = env.registry.get_config(f"Shop.arrival.{arrival}") task_id = 0 while True: yield env.timeout(sampler.sample(config)) key = f"{arrival}-{task_id + 1}" env.process(pack(env, sampler, packers, arrival, key, task_id)) task_id += 1 def run(queue="priority", until=3600, factor=0.0, orders_rate=0.45, express_rate=0.15): params = copy.deepcopy(PARAMS) params.arrival["orders"] = DistributionConfig(dist="exponential", rate=orders_rate) params.arrival["express"] = DistributionConfig( dist="exponential", rate=express_rate ) env = DynamicRealtimeEnvironment(factor=factor) env.registry.register_sim_parameter(params) env.setup_egress([ConsoleEgress()]) env.setup_stats("Shop", "typical", interval=3600) # the mean wait of each task # The packer serves the lowest priority first, the oldest first among equals packers = DynamicResource(env, "Shop", "packers", queue=queue) sampler = Sampler(seed=42) env.process(order_generator(env, sampler, packers, "orders")) env.process(order_generator(env, sampler, packers, "express")) try: env.run(until=until) finally: env.teardown() return env def mean_waits( queue: str, orders_rate: float = 0.45, express_rate: float = 0.15 ) -> dict: """Runs one hour and returns the mean wait of each task.""" readings = run( queue, orders_rate=orders_rate, express_rate=express_rate ).stats.readings() return { task: readings[f"Shop.stats.tasks.{task}.wait_mean"] for task in ("pack_express", "pack_order") } if __name__ == "__main__": rates = [float(rate) for rate in sys.argv[1:3]] for queue in ("fifo", "priority"): for task, wait in mean_waits(queue, *rates).items(): print(f"{queue:<8} {task:<12} mean wait {wait:5.2f} s") ``` # A Flow of Tasks Until now an order was one task: it was packed and left. A real order is picked from the shelves, packed and shipped. Sometimes an item is out of stock, and sometimes a parcel fails its check and is packed again. This page asks: **how do orders move through pick, pack and ship?** - **Decision:** how much work to plan for beyond one pick and one pack per order. - **Measures:** two shares: how many orders go to backorder, and how many parcels are packed again. - **Runs:** one run of an hour with the seed 42, from an order's arrival to its shipment, with the supplier modelled only as a delay. - **Assumptions:** orders arrive at random, each picking time is equally likely to be anywhere from 1 to 3 seconds, and packing always takes 1.5 seconds. ## What You Will Learn This page shows how to: - chain tasks so an order is picked, packed and shipped; - route a share of the orders to backorder or back to packing; - carry an attribute, such as `express`, through the flow. ## What You Add This page adds three tasks in a row: `pick_order`, `pack_order` and `ship_order`. It also adds a `backorder` delay for an order picked while the shelf of boxes from [Stock](https://jaehyeon.me/desflow/latest/learn/shop-logic/stock/index.md) is empty, and an `express` attribute that each order carries. The shop is set up as follows: - It has two pickers and two packers. - A regular order arrives every 2.5 seconds on average (24 a minute, `rate: 0.4`), and an express order every 10 seconds (6 a minute, `rate: 0.1`). - A delivery of 53 boxes comes every 100 seconds, a little more than the orders take. - Picking time is `uniform` from 1 to 3 seconds only to keep the example short. [Common Mistakes](https://jaehyeon.me/desflow/latest/learn/concepts/common-mistakes/#choosing-a-normal-or-uniform-by-habit) explains why a real study fits a distribution to measured times instead, as [Choosing Inputs](https://jaehyeon.me/desflow/latest/learn/inputs/choosing-inputs/index.md) does. Look at the flow first: ______________________________________________________________________ ## Chain the Tasks Choosing where an entity goes next is called **routing**. In desflow a task names what follows it with `next`. [Tasks and Processes](https://jaehyeon.me/desflow/latest/user-guide/tasks-and-processes/index.md) describes tasks. `next` takes one of three forms: - a task name, which always leads there; - a list of `when` rules, each a condition and a task: the first rule that holds wins, and `default` catches the rest; - `weights`, which [Rework](#rework) shows. A task with no `next` ends the order's flow. Save the files from [Full Files](#full-files) in one folder and run the commands there. ```yaml pick_order: service: picking resource: pickers payload: {event_type: order_picked} # The first rule that holds wins; default catches the rest next: when: - {condition: "level.stock == 0", task: backorder} default: pack_order ``` Here the arrival loop passes the context to each task after its id. A task started by `next` receives the same arguments as the task before it. So every task function in the flow declares `context`. ```python # The first rule that holds wins; default catches the rest @app.task( service_id="picking", resource_id="pickers", next={ "when": [{"condition": "level.stock == 0", "task": "backorder"}], "default": "pack_order", }, ) def pick_order(task_id: int, context: SimulationContext): return {"event_type": "order_picked"} ``` ```python # The first rule that holds wins; default catches the rest "pick_order": Router( { "when": [{"condition": "level.stock == 0", "task": "backorder"}], "default": "pack_order", } ), ``` A `Router` takes the same rules as `next` and returns the name of the task to start. When a task finishes, its process asks the router and runs the next task with `yield from`, in the same process and the same step, with the same entity: ```python entity.attributes.update(SETS.get(name, {})) upstream = Upstream(task_id, entity.key, entity.attributes, finished) following = ROUTES[name].choose(upstream, env, levels={"stock": shop["stock"]}) if following is None: env.stats.flow_finished(entity.arrival) # the order leaves the shop return instance = next(counters[following]) yield from task(env, sampler, shop, following, entity, instance, counters) ``` In SimPy terms, `yield from` runs a generator inside the current process, so the next task is the next statement of one process. A process that started the next task with `env.process(...)` would begin it in a later step, and at a tie it would ask for a unit after the processes already started. [SimPy and desflow](https://jaehyeon.me/desflow/latest/simpy/#processes-and-waiting-for-a-process) describes processes. The rule reads `level.stock`, the level of the container `stock`, at the moment picking finishes. [Stores and Containers](https://jaehyeon.me/desflow/latest/user-guide/model-parts/stores-and-containers/index.md) describes containers. Each name in a condition says where its value comes from: `level.` for a store or container, `attr.` for the entity's attributes, `payload.` for the finished task's payload, and `registry["..."]` for a live parameter. [Task Flow](https://jaehyeon.me/desflow/latest/user-guide/model-parts/task-flow/index.md) lists everything a condition can use. Every event of every task carries the order's key, `orders-1`, so one order can be followed through its whole flow. `task` names the task, and `instance` numbers its runs. Each task has one counter, shared by its arrivals and by `next`, so a re-pick after a backorder gets a new id. In the full builder file the arrival loops take the id from `context.next_instance("pick_order")`, and the low-level file keeps one `counters` entry per task. ______________________________________________________________________ ## Out of Stock An order picked while the shelf is empty waits for the supplier for a minute, then is picked again. The wait uses no picker or packer, so `backorder` has a `service` and no `resource`: a **timed step**. It publishes `started` at once, with no `queued` event, waits the sampled time, and publishes its finished event: ```yaml backorder: # A timed step: a service and no resource, so it starts at once service: supplying payload: {event_type: order_backordered} # Applied to the order's attributes when the step finishes set: {backordered: 1} next: pick_order ``` ```python # A timed step: a service and no resource, so it starts at once. `set` is applied # to the order's attributes when the step finishes. @app.task(service_id="supplying", set={"backordered": 1}, next="pick_order") def backorder(task_id: int, context: SimulationContext): return {"event_type": "order_backordered"} ``` ```python "backorder": Router("pick_order"), ``` ```python # Applied to the order's attributes when the step finishes SETS = {"backorder": {"backordered": 1}} ``` `next: pick_order` sends the order back to an earlier task. A route back is allowed anywhere in a flow. ______________________________________________________________________ ## Rework One parcel in 20 fails its check and is packed again. Sending work back to a task it has passed is called **rework**. `weights` chooses the next task at random, in proportion to the weights. A weight of infinity or `true` is refused when the blueprint loads. It draws from the routing task's own random number stream, `route.pack_order`. So a seeded run repeats, and the choice does not change any other draw: ```yaml pack_order: service: packing resource: packers get: {container: stock, amount: 1} payload: {event_type: order_packed} # One parcel in 20 fails its check and is packed again next: weights: {ship_order: 95, pack_order: 5} ``` ```python # One parcel in 20 fails its check and is packed again @app.task( service_id="packing", resource_id="packers", get={"container": "stock", "amount": 1}, next={"weights": {"ship_order": 95, "pack_order": 5}}, ) def pack_order(task_id: int, context: SimulationContext): return {"event_type": "order_packed"} ``` ```python # One parcel in 20 fails its check and is packed again; the generator is set # in run below "pack_order": Router({"weights": {"ship_order": 95, "pack_order": 5}}), ``` The low-level router needs a generator to draw from: `ROUTES["pack_order"].rng = sampler.generator("route.pack_order")` in `run`, the stream the builder uses. ______________________________________________________________________ ## Carry Attributes An order is an **entity** with **attributes**: values it carries from task to task, such as whether it is express. The arrival gives each new entity its starting attributes, and `set` on a task changes them when the task finishes, as `backorder` does with `backordered: 1`: ```yaml arrivals: # Each order starts with the attributes given here, read as attr. orders: dist: exponential rate: 0.4 spawn: pick_order attributes: {express: 0} express: dist: exponential rate: 0.1 spawn: pick_order attributes: {express: 1} ``` ```python # Each order starts with the attributes given here, read as attr. app.add_arrival("orders", dist="exponential", rate=0.4, attributes={"express": 0}) app.add_arrival("express", dist="exponential", rate=0.1, attributes={"express": 1}) ``` ```python # Each order starts with the attributes given here, read as attr. ATTRIBUTES = {"orders": {"express": 0}, "express": {"express": 1}} ``` `Entity(key, arrival, attributes)` is the order, created by the arrival process; the full file below shows it. Attributes are not published. A condition reads them as `attr.express`, and a payload includes them only when it names them. `ship_order` names `express` and `backordered`, so its finished event carries both. This is `orders-851`, which was picked while the shelf was empty, backordered, picked again and packed twice. Every tab prints its records to the terminal, so `grep` finds the order's lines: ```bash desflow run flow_of_tasks.yaml 2>&1 | grep orders-851 ``` ```bash python flow_of_tasks.py 2>&1 | grep orders-851 ``` ```bash python flow_of_tasks_low_level.py 2>&1 | grep orders-851 ``` ```text [EVT] {'sim_ts': 2092.1809997632477, 'timestamp': '...', 'key': 'orders-851', 'task': 'pick_order', 'instance': 1057, 'value': {'path_id': 'Shop.service.picking', 'sim_id': 'Shop', 'service': 'picking', 'status': 'queued'}} [EVT] {'sim_ts': 2092.1809997632477, 'timestamp': '...', 'key': 'orders-851', 'task': 'pick_order', 'instance': 1057, 'value': {'path_id': 'Shop.service.picking', 'sim_id': 'Shop', 'service': 'picking', 'status': 'started'}} [EVT] {'sim_ts': 2094.2512057061713, 'timestamp': '...', 'key': 'orders-851', 'task': 'pick_order', 'instance': 1057, 'value': {'event_type': 'order_picked'}} [EVT] {'sim_ts': 2094.2512057061713, 'timestamp': '...', 'key': 'orders-851', 'task': 'backorder', 'instance': 0, 'value': {'path_id': 'Shop.service.supplying', 'sim_id': 'Shop', 'service': 'supplying', 'status': 'started'}} [EVT] {'sim_ts': 2154.2512057061713, 'timestamp': '...', 'key': 'orders-851', 'task': 'backorder', 'instance': 0, 'value': {'event_type': 'order_backordered'}} [EVT] {'sim_ts': 2154.2512057061713, 'timestamp': '...', 'key': 'orders-851', 'task': 'pick_order', 'instance': 1092, 'value': {'path_id': 'Shop.service.picking', 'sim_id': 'Shop', 'service': 'picking', 'status': 'queued'}} [EVT] {'sim_ts': 2154.2512057061713, 'timestamp': '...', 'key': 'orders-851', 'task': 'pick_order', 'instance': 1092, 'value': {'path_id': 'Shop.service.picking', 'sim_id': 'Shop', 'service': 'picking', 'status': 'started'}} [EVT] {'sim_ts': 2156.282710424913, 'timestamp': '...', 'key': 'orders-851', 'task': 'pick_order', 'instance': 1092, 'value': {'event_type': 'order_picked'}} [EVT] {'sim_ts': 2156.282710424913, 'timestamp': '...', 'key': 'orders-851', 'task': 'pack_order', 'instance': 1139, 'value': {'path_id': 'Shop.service.packing', 'sim_id': 'Shop', 'service': 'packing', 'status': 'queued'}} [EVT] {'sim_ts': 2156.282710424913, 'timestamp': '...', 'key': 'orders-851', 'task': 'pack_order', 'instance': 1139, 'value': {'path_id': 'Shop.service.packing', 'sim_id': 'Shop', 'service': 'packing', 'status': 'started'}} [EVT] {'sim_ts': 2157.782710424913, 'timestamp': '...', 'key': 'orders-851', 'task': 'pack_order', 'instance': 1139, 'value': {'event_type': 'order_packed'}} [EVT] {'sim_ts': 2157.782710424913, 'timestamp': '...', 'key': 'orders-851', 'task': 'pack_order', 'instance': 1142, 'value': {'path_id': 'Shop.service.packing', 'sim_id': 'Shop', 'service': 'packing', 'status': 'queued'}} [EVT] {'sim_ts': 2158.3141197359328, 'timestamp': '...', 'key': 'orders-851', 'task': 'pack_order', 'instance': 1142, 'value': {'path_id': 'Shop.service.packing', 'sim_id': 'Shop', 'service': 'packing', 'status': 'started'}} [EVT] {'sim_ts': 2159.8141197359328, 'timestamp': '...', 'key': 'orders-851', 'task': 'pack_order', 'instance': 1142, 'value': {'event_type': 'order_packed'}} [EVT] {'sim_ts': 2159.8141197359328, 'timestamp': '...', 'key': 'orders-851', 'task': 'ship_order', 'instance': 1088, 'value': {'event_type': 'order_shipped', 'express': 0, 'backordered': 1}} ``` ______________________________________________________________________ ## Networks and Bottlenecks A shop with several tasks is a network: each task's rate comes from the tasks before it. This version of the shop checks every packed order with one checker, and sends one order in ten back to be packed again. A weight in `next.weights` is a number or an expression read when the task finishes, such as `attr.w`, `registry[...]`, `level.` or `t`, with no bare name. The draw is one number from `route.`. A result below 0, or text that is not a number, fails the run with the weight's name, and weights that add up to 0 fail the run. `desflow explain` makes the cumulative shares once, for numbers only, and gives no shares for expression weights: ```yaml arrivals: orders: {dist: exponential, rate: 1.6, spawn: pack_order} services: packing: {dist: constant, value: 1.5 s} checking: {dist: exponential, rate: 2.5} # 0.4 s on average resources: packers: {current_cap: 4, max_cap: 10} checkers: {current_cap: 1, max_cap: 4} tasks: pack_order: service: packing resource: packers payload: {event_type: order_packed} next: check_order check_order: service: checking resource: checkers payload: {event_type: order_checked} # Nine in ten pass; the tenth is packed again next: weights: {ship_order: 9, pack_order: 1} ship_order: payload: {event_type: order_shipped} ``` ```python app = SimulationContext(sim_id="Shop", factor=0, random_seed=42) app.add_arrival("orders", dist="exponential", rate=1.6, spawn="pack_order") app.add_service("packing", dist="constant", value=1.5) app.add_service("checking", dist="exponential", rate=2.5) # 0.4 s on average app.add_resource("packers", current_cap=4, max_cap=10) app.add_resource("checkers", current_cap=1, max_cap=4) @app.task(service_id="packing", resource_id="packers", next="check_order") def pack_order(task_id): return {"event_type": "order_packed"} # Nine in ten pass; the tenth is packed again @app.task( service_id="checking", resource_id="checkers", next={"weights": {"ship_order": 9, "pack_order": 1}}, ) def check_order(task_id): return {"event_type": "order_checked"} @app.task() def ship_order(task_id): return {"event_type": "order_shipped"} # print(render_terminal(app.analyze())) prints what desflow explain prints ``` ```python NETWORK = SimParameter( sim_id="Shop", arrival={"orders": DistributionConfig(dist="exponential", rate=1.6)}, service={ "packing": DistributionConfig(dist="constant", value=1.5), # One check takes 0.4 s on average "checking": DistributionConfig(dist="exponential", rate=2.5), }, resources={ "packers": CapacityConfig(current_cap=4, max_cap=10), "checkers": CapacityConfig(current_cap=1, max_cap=4), }, ) # Each task's service and resource, and the task after it STEPS = { "pack_order": ("packing", "packers", Router("check_order")), # Nine in ten pass; the tenth is packed again "check_order": ( "checking", "checkers", Router({"weights": {"ship_order": 9, "pack_order": 1}}), ), "ship_order": (None, None, Router(None)), } def step(env, sampler, shop, name, entity, counters): """One task of an order, then the task its router chooses.""" service, resource, router = STEPS[name] task_id = next(counters[name]) if resource is None: env.stats.task_finished(name, task_id) else: env.stats.task_queued(name, task_id) with shop[resource].request() as request: yield request env.stats.task_started(name, task_id) config = env.registry.get_config(f"Shop.service.{service}") yield env.timeout(sampler.sample(config)) env.stats.task_finished(name, task_id) following = router.choose(Upstream(task_id, entity, {}, {}), env) if following is None: env.stats.flow_finished("orders") else: yield from step(env, sampler, shop, following, entity, counters) ``` `Router` is the object that chooses the task after a finished one, from the same `next` rule a blueprint uses: a name, `when` rules or `weights`. `Upstream` is what the finished task hands it: the instance id, the entity key, the entity's attributes and the payload. Here no condition reads them, so the router gets an empty `Upstream` with the entity. `counters` gives each task's instance numbers, counting from 0. `flow_finished` tells the statistics that the order has left the shop. `desflow explain` does not support low-level models. It reads which arrival starts which task and which resource each task uses, and a low-level model does not declare those links: its SimPy code makes them as it runs. Every packed order is checked. Packing receives the new orders, 1.6 a second, and also the tenth of the checked orders that come back. Call the rate into packing x: then x = 1.6 + 0.1 × x, which gives x = 1.6 ÷ 0.9 = 1.778 orders a second. `desflow explain queues_network.yaml` solves this [flow balance](https://jaehyeon.me/desflow/latest/learn/concepts/queueing-basics/#flow-balance-and-the-bottleneck) for every task. This is its output without the hints at the end: ```text Shop `-- orders (arrival, rate 1.6/s) `-- spawn -> pack_order (task, rate 1.778/s) +-- uses packers (resource) `-- next (share 1) -> check_order (task, rate 1.778/s) +-- uses checkers (resource) +-- next (share 0.9) -> ship_order (task, rate 1.6/s) | `-- next (share 1) -> exit `-- next (share 0.1) -> pack_order (again) Resources +----------------------------------------------------------+ | resource | λ | μ | c | ρ | Wq | L | status | |----------+-------+--------+---+--------+----+---+--------| | packers | 1.778 | 0.6667 | 4 | 0.6667 | - | - | OK | | checkers | 1.778 | 2.5 | 1 | 0.7111 | - | - | OK | +----------------------------------------------------------+ packers by units +-------------------------+ | c | ρ | status | |----+--------+-----------| | 1 | 2.667 | UNSTABLE | | 2 | 1.333 | UNSTABLE | | 3 | 0.8889 | CONGESTED | | 4 | 0.6667 | OK | | 5 | 0.5333 | OK | | 6 | 0.4444 | OK | | 7 | 0.381 | OK | | 8 | 0.3333 | OK | | 9 | 0.2963 | OK | | 10 | 0.2667 | OK | +-------------------------+ checkers by units +---------------------+ | c | ρ | status | |---+--------+--------| | 1 | 0.7111 | OK | | 2 | 0.3556 | OK | | 3 | 0.237 | OK | | 4 | 0.1778 | OK | +---------------------+ Bottleneck: checkers Not estimated: wait at packers: no closed formula for c > 1 with non-exponential times; run --verify to measure it wait at checkers: its input is not one arrival or a Poisson flow, which Kingman's formula needs; run --verify to measure it ``` The four packers are at utilisation 0.667 and the checker at 0.711, the higher of the two, so the checker is the bottleneck. In the table by units, 3 packers would be at utilisation 0.889, above the checker. So with 3 packers the packers are the bottleneck, and a fourth packer moves the bottleneck to the checker. Relieving a bottleneck makes the next busiest resource the new one. `desflow explain` estimates neither wait here, and says why: four packers with constant packing have no closed formula, and the checker's input is the packers' output, which is neither one arrival nor a [Poisson](https://jaehyeon.me/desflow/latest/learn/concepts/queueing-basics/#kendalls-notation) flow. `--verify`, in [Check Against Theory](https://jaehyeon.me/desflow/latest/how-to/analysis/check-against-theory/index.md), measures both. ______________________________________________________________________ ## What You Get and Why How do orders move through pick, pack and ship? Most go straight through, and a few go to backorder or are packed again. The run publishes the finished count of every task at the end, with `stats: basic` in the YAML file, `with_stats("basic", interval=3600)` in the Builder file and `env.setup_stats("Shop", "basic", interval=3600)` in the Low-level file. Each tab prints the four counts: ```bash desflow run flow_of_tasks.yaml --stdout | grep -E 'tasks\.(pick_order|backorder|pack_order|ship_order)\.finished"' ``` ```text {"stream_type":"telemetry","sim_ts":3600.0,"timestamp":"...","path_id":"Shop.stats.tasks.pick_order.finished","value":2011} {"stream_type":"telemetry","sim_ts":3600.0,"timestamp":"...","path_id":"Shop.stats.tasks.pack_order.finished","value":1904} {"stream_type":"telemetry","sim_ts":3600.0,"timestamp":"...","path_id":"Shop.stats.tasks.ship_order.finished","value":1812} {"stream_type":"telemetry","sim_ts":3600.0,"timestamp":"...","path_id":"Shop.stats.tasks.backorder.finished","value":198} ``` ```bash python flow_of_tasks.py 2>/dev/null ``` ```text pick_order: 2011 finished backorder : 198 finished pack_order: 1904 finished ship_order: 1812 finished ``` ```bash python flow_of_tasks_low_level.py 2>/dev/null ``` ```text pick_order: 2011 finished backorder : 198 finished pack_order: 1904 finished ship_order: 1812 finished ``` The counts are: | Task | Finished in the hour | | ------------ | -------------------- | | `pick_order` | 2,011 | | `backorder` | 198 | | `pack_order` | 1,904 | | `ship_order` | 1,812 | **9.8% of picks led to backorder** (198 of 2,011), and **4.8% of parcels were packed again** (92 of 1,904 packs did not lead to a shipment). The weights set 5% for packing again, and this one run of the hour, with the seed 42, drew slightly fewer. **[Flow balance](https://jaehyeon.me/desflow/latest/learn/concepts/queueing-basics/#flow-balance-and-the-bottleneck)** is the rule that, in a flow, each task's arrival rate follows from the rates into it and the routing weights. Every pack leads to a shipment with probability 0.95, so each order is packed 1 ÷ 0.95 = 1.05 times on average, and the packers see 5% more work than there are orders. A rework loop therefore raises [utilisation](https://jaehyeon.me/desflow/latest/learn/concepts/queueing-basics/#utilisation), so it belongs in the load you work out before running. [Queueing Basics](https://jaehyeon.me/desflow/latest/learn/concepts/queueing-basics/#waits-near-full-use) shows why waits grow quickly near full use. [Task Flow](https://jaehyeon.me/desflow/latest/user-guide/model-parts/task-flow/index.md) describes routing in full. ## Key Takeaways - A task names the task that follows it, by a condition or by weights. - In a flow, each task's rate follows from the rates into it and the routing weights. - A rework loop adds work to the resources it returns to, so include it in the load you work out before running. ______________________________________________________________________ ## Full Files Full files ```yaml # The A Flow of Tasks tutorial: orders are picked, packed and shipped. # Run it with: desflow run flow_of_tasks.yaml simulation: {sim_id: Shop, factor: 0, random_seed: 42} resources: pickers: {current_cap: 2, max_cap: 4} packers: {current_cap: 2, max_cap: 4} containers: # Boxes on the shelf, restocked with 53 every 100 seconds stock: {current_cap: 200, max_cap: 200, level: 50} services: picking: {dist: uniform, low: 1 s, high: 3 s} packing: {dist: constant, value: 1.5 s} # The supplier takes a minute to send an item that is out of stock supplying: {dist: constant, value: 1 min} arrivals: # Each order starts with the attributes given here, read as attr. orders: dist: exponential rate: 0.4 spawn: pick_order attributes: {express: 0} express: dist: exponential rate: 0.1 spawn: pick_order attributes: {express: 1} deliveries: {dist: constant, value: 100 s, spawn: restock} tasks: pick_order: service: picking resource: pickers payload: {event_type: order_picked} # The first rule that holds wins; default catches the rest next: when: - {condition: "level.stock == 0", task: backorder} default: pack_order backorder: # A timed step: a service and no resource, so it starts at once service: supplying payload: {event_type: order_backordered} # Applied to the order's attributes when the step finishes set: {backordered: 1} next: pick_order pack_order: service: packing resource: packers get: {container: stock, amount: 1} payload: {event_type: order_packed} # One parcel in 20 fails its check and is packed again next: weights: {ship_order: 95, pack_order: 5} ship_order: payload: {event_type: order_shipped} # A payload includes attributes only when it names them attributes: [express, backordered] restock: put: {container: stock, amount: 53} payload: {event_type: stock_delivered} # Finished counts of every task and flow, at the end stats: {level: basic, interval: 1 h} egress: - {type: Console} run: {until: 1 h} ``` ```python """The A Flow of Tasks tutorial: orders are picked, packed and shipped, builder. Two pickers, two packers and a shelf of boxes restocked every 100 seconds. An order picked while the shelf is empty goes to backorder for a minute and is picked again, and one parcel in 20 is packed again. Every record is printed to the terminal, and the finished count of each task is printed at the end. """ import logging from desflow import ConsoleEgress, SimulationContext logging.basicConfig( level=logging.INFO, format="%(levelname)s [%(asctime)s] %(message)s" ) app = ( SimulationContext(sim_id="Shop", factor=0, random_seed=42) .add_resource("pickers", current_cap=2, max_cap=4) .add_resource("packers", current_cap=2, max_cap=4) # Boxes on the shelf, restocked with 53 every 100 seconds .add_container("stock", current_cap=200, max_cap=200, level=50) .add_service("picking", dist="uniform", low=1, high=3) .add_service("packing", dist="constant", value=1.5) # The supplier takes a minute to send an item that is out of stock .add_service("supplying", dist="constant", value=60) .add_arrival("deliveries", dist="constant", value=100) # Finished counts of every task and flow, at the end .with_stats("basic", interval=3600) .add_egress(ConsoleEgress()) ) # Each order starts with the attributes given here, read as attr. app.add_arrival("orders", dist="exponential", rate=0.4, attributes={"express": 0}) app.add_arrival("express", dist="exponential", rate=0.1, attributes={"express": 1}) # The first rule that holds wins; default catches the rest @app.task( service_id="picking", resource_id="pickers", next={ "when": [{"condition": "level.stock == 0", "task": "backorder"}], "default": "pack_order", }, ) def pick_order(task_id: int, context: SimulationContext): return {"event_type": "order_picked"} # A timed step: a service and no resource, so it starts at once. `set` is applied # to the order's attributes when the step finishes. @app.task(service_id="supplying", set={"backordered": 1}, next="pick_order") def backorder(task_id: int, context: SimulationContext): return {"event_type": "order_backordered"} # One parcel in 20 fails its check and is packed again @app.task( service_id="packing", resource_id="packers", get={"container": "stock", "amount": 1}, next={"weights": {"ship_order": 95, "pack_order": 5}}, ) def pack_order(task_id: int, context: SimulationContext): return {"event_type": "order_packed"} @app.task() def ship_order(task_id: int, context: SimulationContext, entity): # A payload includes attributes only when it asks for them return { "event_type": "order_shipped", "express": entity.attributes.get("express"), "backordered": entity.attributes.get("backordered"), } @app.task(put={"container": "stock", "amount": 53}) def restock(task_id: int, context: SimulationContext): return {"event_type": "stock_delivered"} def spawn(arrival, task, name): def loop(context: SimulationContext): while True: entity = yield context.wait_for_arrival(arrival) # One counter per task, shared by both order arrivals and by next context.spawn(task(context.next_instance(name), context, entity=entity)) return loop app.arrival_loop("orders")(spawn("orders", pick_order, "pick_order")) app.arrival_loop("express")(spawn("express", pick_order, "pick_order")) app.arrival_loop("deliveries")(spawn("deliveries", restock, "restock")) if __name__ == "__main__": app.run(until="1 h") readings = app.env.stats.readings() for name in ("pick_order", "backorder", "pack_order", "ship_order"): print(f"{name:<10}: {readings[f'Shop.stats.tasks.{name}.finished']} finished") ``` ```python """The A Flow of Tasks tutorial: orders are picked, packed and shipped, low-level. Two pickers, two packers and a shelf of boxes restocked every 100 seconds. An order picked while the shelf is empty goes to backorder for a minute and is picked again, and one parcel in 20 is packed again. Every record is printed to the terminal, and the finished count of each task is printed at the end. """ import contextlib import itertools import logging from desflow import ( CapacityConfig, ConsoleEgress, ContainerConfig, DistributionConfig, DynamicContainer, DynamicRealtimeEnvironment, DynamicResource, Entity, Router, Sampler, SimParameter, Upstream, ) logging.basicConfig( level=logging.INFO, format="%(levelname)s [%(asctime)s] %(message)s" ) PARAMS = SimParameter( sim_id="Shop", arrival={ "orders": DistributionConfig(dist="exponential", rate=0.4), "express": DistributionConfig(dist="exponential", rate=0.1), "deliveries": DistributionConfig(dist="constant", value=100), }, service={ "picking": DistributionConfig(dist="uniform", low=1, high=3), "packing": DistributionConfig(dist="constant", value=1.5), # The supplier takes a minute to send an item that is out of stock "supplying": DistributionConfig(dist="constant", value=60), }, resources={ "pickers": CapacityConfig(current_cap=2, max_cap=4), "packers": CapacityConfig(current_cap=2, max_cap=4), }, # Boxes on the shelf, restocked with 53 every 100 seconds containers={"stock": ContainerConfig(current_cap=200, max_cap=200, level=50)}, ) # Each order starts with the attributes given here, read as attr. ATTRIBUTES = {"orders": {"express": 0}, "express": {"express": 1}} # Each task's service and resource; None for a timed step or a task that takes no time TASKS = { "pick_order": ("picking", "pickers"), "backorder": ("supplying", None), "pack_order": ("packing", "packers"), "ship_order": (None, None), } EVENTS = { "pick_order": "order_picked", "backorder": "order_backordered", "pack_order": "order_packed", } ROUTES = { # The first rule that holds wins; default catches the rest "pick_order": Router( { "when": [{"condition": "level.stock == 0", "task": "backorder"}], "default": "pack_order", } ), "backorder": Router("pick_order"), # One parcel in 20 fails its check and is packed again; the generator is set # in run below "pack_order": Router({"weights": {"ship_order": 95, "pack_order": 5}}), "ship_order": Router(None), } # Applied to the order's attributes when the step finishes SETS = {"backorder": {"backordered": 1}} def payload(name, entity): if name == "ship_order": # A payload includes attributes only when it names them return { "event_type": "order_shipped", "express": entity.attributes.get("express"), "backordered": entity.attributes.get("backordered"), } return {"event_type": EVENTS[name]} def task(env, sampler, shop, name, entity, task_id, counters): """Runs one task for an order, then the task its router chooses, in the same process.""" service, resource = TASKS[name] path_id = f"Shop.service.{service}" def publish(value): env.publish_event(entity.key, value, task=name, instance=task_id) if resource is not None: publish( { "path_id": path_id, "sim_id": "Shop", "service": service, "status": "queued", } ) env.stats.task_queued(name, task_id) unit = shop[resource].request() if resource else contextlib.nullcontext() with unit as request: if request is not None: yield request if name == "pack_order": yield shop["stock"].get(1) if service is not None: publish( { "path_id": path_id, "sim_id": "Shop", "service": service, "status": "started", } ) env.stats.task_started(name, task_id) finished = payload(name, entity) if service is not None: yield env.timeout(sampler.sample(env.registry.get_config(path_id))) publish(finished) env.stats.task_finished(name, task_id) entity.attributes.update(SETS.get(name, {})) upstream = Upstream(task_id, entity.key, entity.attributes, finished) following = ROUTES[name].choose(upstream, env, levels={"stock": shop["stock"]}) if following is None: env.stats.flow_finished(entity.arrival) # the order leaves the shop return instance = next(counters[following]) yield from task(env, sampler, shop, following, entity, instance, counters) def order_generator(env, sampler, shop, arrival, counters): """Starts an order for every arrival, keyed orders-1, express-1 and so on.""" gap = env.registry.get_config(f"Shop.arrival.{arrival}") for number in itertools.count(1): yield env.timeout(sampler.sample(gap)) entity = Entity(f"{arrival}-{number}", arrival, dict(ATTRIBUTES[arrival])) instance = next(counters["pick_order"]) env.process(task(env, sampler, shop, "pick_order", entity, instance, counters)) def delivery_generator(env, sampler, shop): gap = env.registry.get_config("Shop.arrival.deliveries") for number in itertools.count(1): yield env.timeout(sampler.sample(gap)) yield shop["stock"].put(53) value = {"event_type": "stock_delivered"} env.publish_event( f"deliveries-{number}", value, task="restock", instance=number - 1 ) env.stats.task_finished("restock", number - 1) env.stats.flow_finished("deliveries") def run(until=3600, factor=0.0): env = DynamicRealtimeEnvironment(factor=factor) env.registry.register_sim_parameter(PARAMS) env.setup_egress([ConsoleEgress()]) # Finished counts of every task and flow, at the end env.setup_stats("Shop", "basic", interval=3600) shop = { "pickers": DynamicResource(env, "Shop", "pickers"), "packers": DynamicResource(env, "Shop", "packers"), "stock": DynamicContainer(env, "Shop", "stock"), } sampler = Sampler(seed=42) # Weights draw from the routing task's own sequence, as the builder's do ROUTES["pack_order"].rng = sampler.generator("route.pack_order") # One counter per task, shared by the arrivals and the rules counters = {name: itertools.count() for name in TASKS} for arrival in ("orders", "express"): env.process(order_generator(env, sampler, shop, arrival, counters)) env.process(delivery_generator(env, sampler, shop)) try: env.run(until=until) finally: env.teardown() return env if __name__ == "__main__": readings = run().stats.readings() for name in ("pick_order", "backorder", "pack_order", "ship_order"): print(f"{name:<10}: {readings[f'Shop.stats.tasks.{name}.finished']} finished") ``` # Process Interaction Packed orders now wait for a courier, who comes every 10 minutes and takes every order that is waiting. An order that waits too long goes by post instead, which costs more and takes longer. This page asks: **when does a waiting order resume, and how long must it be allowed to wait so that most orders go by courier?** - **Decision:** how long a packed order may wait for the courier: 5 minutes or 8. - **Measures:** the orders sent by courier and by post, and the mean wait for dispatch. - **Runs:** two runs of an 8-hour day, one for each limit, each with the seed 42, up to the moment each order leaves the shop: the courier's trip and the post are left out. - **Assumptions:** orders arrive at random, every order takes the same time to pack, and the courier is always on time. ## What You Will Learn This page shows how to: - fire a signal from one process and wait for it in another; - wait for the first of a signal and a time limit; - measure how a limit splits the orders between two outcomes. ## What You Add This page adds a signal, `courier_left`, that the courier fires as it leaves, and a `dispatch` task that waits for either the signal or its limit, whichever comes first. The shop is the one from [First Simulation](https://jaehyeon.me/desflow/latest/learn/first-model/first-simulation/index.md): one packer, an order every 2 seconds on average and 1.5 seconds of packing. ______________________________________________________________________ ## A Signal So far a process has waited for time, a resource or an item. Processes can also wait for each other. In SimPy one process yields an event, and another process succeeds it, which marks the event as happened. Every process waiting for the event then resumes. desflow gives such an event a name and calls it a **signal**. A signal is declared once, and a task fires it when the task finishes. A signal is one-shot by default: it fires once, and a second firing is an error. The courier comes every 10 minutes, so this signal says `once: false`, and each firing wakes every process that is waiting for it at that moment: ```yaml signals: # Fired by the courier as it leaves with every order that waits for it, # and again at each later courier, so it is not one-shot courier_left: {once: false} ``` ```python # Fired by the courier as it leaves with every order that waits for it, # and again at each later courier, so it is not one-shot app.add_signal("courier_left", once=False) ``` ```python # Fired by the courier as it leaves with every order that waits for it, # and again at each later courier, so it is not one-shot "courier_left": Signal(env, "courier_left", once=False), ``` `Signal` holds one pending SimPy `Event`. `wait()` returns it. `fire(value)` succeeds it and puts a fresh one in its place. So a process that starts waiting after a firing waits for the next firing. [SimPy and desflow](https://jaehyeon.me/desflow/latest/simpy/#events-and-callbacks) describes events. The courier arrives every 10 minutes, and its task fires the signal with its payload. Save the files from [Full Files](#full-files) in one folder and run the commands there: ```yaml # A courier every 10 minutes couriers: {dist: constant, value: 10 min, spawn: collect} ``` ```yaml collect: payload: {event_type: courier_left} # Fires courier_left with this payload, so every waiting order resumes signal: courier_left ``` ```python # A courier every 10 minutes .add_arrival("couriers", dist="constant", value=600) ``` ```python # Fires courier_left with this payload, so every waiting order resumes @app.task(signal="courier_left") def collect(task_id: int): return {"event_type": "courier_left"} ``` ```python # A courier every 10 minutes "couriers": DistributionConfig(dist="constant", value=600), ``` ```python def collect(env, shop, key, ids): """Fires courier_left with the payload, so every waiting order resumes.""" task_id = next(ids["collect"]) payload = {"event_type": "courier_left"} publish(env, key, "collect", task_id, payload) env.stats.task_finished("collect", task_id) shop["courier_left"].fire(payload) env.stats.flow_finished("couriers") yield env.timeout(0) ``` ______________________________________________________________________ ## Wait for the First of Two A packed order waits for the courier or for its limit. SimPy waits for the first of several events with `a | b`, an `AnyOf`. desflow's `wait` does the same with `any`, whose branches each have a name, here `courier` and `limit`. After the wait, `wait..done` says whether that branch happened, so `next` can route on it: ```yaml dispatch: # The courier's departure, or the limit, whichever comes first wait: any: courier: {signal: courier_left} limit: {timeout: "${LIMIT:-5 min}"} payload: {event_type: dispatched} # wait.courier.done is true when the courier came before the limit next: when: - {condition: wait.courier.done, task: by_courier} default: by_post ``` `"${LIMIT:-5 min}"` reads the environment variable `LIMIT`, 5 minutes when it is not set, so `LIMIT="8 min" desflow run process_interaction.yaml` runs the longer limit. ```python @app.task( # The courier's departure, or the limit, whichever comes first wait={ "any": {"courier": {"signal": "courier_left"}, "limit": {"timeout": limit}} }, # wait.courier.done is true when the courier came before the limit next={ "when": [{"condition": "wait.courier.done", "task": "by_courier"}], "default": "by_post", }, ) def dispatch(task_id: int): return {"event_type": "dispatched"} ``` ```python def dispatch(env, shop, key, ids): task_id = next(ids["dispatch"]) publish(env, key, "dispatch", task_id, {"status": "queued"}) env.stats.task_queued("dispatch", task_id) # The courier's departure, or the limit, whichever comes first courier = shop["courier_left"].wait() done = yield env.any_of([courier, env.timeout(shop["limit"])]) publish(env, key, "dispatch", task_id, {"status": "started"}) env.stats.task_started("dispatch", task_id) publish(env, key, "dispatch", task_id, {"event_type": "dispatched"}) env.stats.task_finished("dispatch", task_id) # The courier came before the limit when its event is in the AnyOf's value task = "by_courier" if courier in done else "by_post" yield from send(env, key, task, ids) ``` `env.any_of([...])` is the `AnyOf`. Its value holds the events that happened, so `courier in done` is the YAML's `wait.courier.done`. The task publishes `queued` when it starts waiting and `started` when the wait ends, so its wait statistics measure the time waiting for the courier: ```yaml # How many orders went each way, and the mean wait for dispatch, at the end stats: {level: typical, interval: 8 h} ``` ```python # How many orders went each way, and the mean wait for dispatch, at the end .with_stats("typical", interval=8 * 3600) ``` ```python # How many orders went each way, and the mean wait for dispatch, at the end env.setup_stats("Shop", "typical", interval=8 * 3600) ``` ______________________________________________________________________ ## What You Get and Why When does a waiting order resume? It resumes when the courier leaves, if the courier leaves within the order's limit, and at the limit otherwise. Each figure here comes from one run of the 8-hour day with the seed 42. With a limit of 5 minutes, **7,131** orders go by courier and **7,247** by post. With a limit of 8 minutes, **11,376** go by courier and **2,903** by post, and the mean wait for dispatch rises from **225.0** to **287.6** seconds. How long must an order be allowed to wait? Of the two limits, **8 minutes** is the one at which most orders go by courier, 80% of them. At 5 minutes, fewer than half do: Each tab prints both runs: the orders sent by courier and by post, and the mean wait for dispatch. ```bash # Orders sent by courier and by post, and the mean wait for dispatch desflow run process_interaction.yaml --stdout | grep -E '(by_courier|by_post)\.finished"|dispatch\.wait_mean"' | tail -3 # A limit of 8 minutes LIMIT="8 min" desflow run process_interaction.yaml --stdout | grep -E '(by_courier|by_post)\.finished"|dispatch\.wait_mean"' | tail -3 ``` ```text {"stream_type":"telemetry","sim_ts":28800.0,"timestamp":"...","path_id":"Shop.stats.tasks.dispatch.wait_mean","value":225.0344900431784} {"stream_type":"telemetry","sim_ts":28800.0,"timestamp":"...","path_id":"Shop.stats.tasks.by_post.finished","value":7247} {"stream_type":"telemetry","sim_ts":28800.0,"timestamp":"...","path_id":"Shop.stats.tasks.by_courier.finished","value":7131} {"stream_type":"telemetry","sim_ts":28800.0,"timestamp":"...","path_id":"Shop.stats.tasks.dispatch.wait_mean","value":287.5709842609553} {"stream_type":"telemetry","sim_ts":28800.0,"timestamp":"...","path_id":"Shop.stats.tasks.by_post.finished","value":2903} {"stream_type":"telemetry","sim_ts":28800.0,"timestamp":"...","path_id":"Shop.stats.tasks.by_courier.finished","value":11376} ``` ```bash python process_interaction.py 2>/dev/null ``` ```text limit 5 min: 7131 by courier, 7247 by post, mean wait 225.0 s limit 8 min: 11376 by courier, 2903 by post, mean wait 287.6 s ``` ```bash python process_interaction_low_level.py 2>/dev/null ``` ```text limit 5 min: 7131 by courier, 7247 by post, mean wait 225.0 s limit 8 min: 11376 by courier, 2903 by post, mean wait 287.6 s ``` Orders are packed at random moments, so the time from packing to the next courier is spread evenly over the 10 minutes between couriers. A limit of 5 minutes catches the courier for half the orders, and a limit of 8 minutes for 8 in 10. The runs show these shares: 49.6% and 79.7% of the orders go by courier. Every waiting order resumes at the same firing, so the courier takes them all at once. The mean wait for dispatch rises with the limit for the same reason: an order waits for the smaller of the time to the courier, spread evenly from 0 to 10 minutes, and the limit. Its mean is the limit less the limit squared divided by 20 minutes: 3.75 minutes (225 seconds) for a limit of 5 minutes and 4.8 minutes (288 seconds) for 8 minutes. These shares come from one run, and [Replications](https://jaehyeon.me/desflow/latest/learn/concepts/output-analysis/#replications) explains how runs with other seeds would give each share an interval. [SimPy and desflow](https://jaehyeon.me/desflow/latest/simpy/#waiting-for-one-or-all) shows the plain SimPy forms. [Signals and Waiting](https://jaehyeon.me/desflow/latest/user-guide/tasks-and-processes/signals-and-waiting/#wait-signals-and-child-flows) describes every kind of wait, and [Wait for One or All](https://jaehyeon.me/desflow/latest/how-to/modelling/wait-for-one-or-all/index.md) shows ties and failures. ## Key Takeaways - A signal wakes every task waiting for it at once. - A wait for the first of two events resumes at whichever comes first: here the courier or the limit. - The share of orders that catch the courier follows from the limit and the time between couriers. ______________________________________________________________________ ## Full Files Full files ```yaml # The Process Interaction tutorial: packed orders wait for the courier, with a limit. # Run it with: desflow run process_interaction.yaml # With a limit of 8 minutes: LIMIT="8 min" desflow run process_interaction.yaml simulation: {sim_id: Shop, factor: 0, random_seed: 42} resources: packers: {current_cap: 1, max_cap: 4} services: packing: {dist: constant, value: 1.5 s} signals: # Fired by the courier as it leaves with every order that waits for it, # and again at each later courier, so it is not one-shot courier_left: {once: false} arrivals: orders: {dist: exponential, rate: 0.5, spawn: pack_order} # A courier every 10 minutes couriers: {dist: constant, value: 10 min, spawn: collect} tasks: pack_order: service: packing resource: packers payload: {event_type: order_packed} next: dispatch dispatch: # The courier's departure, or the limit, whichever comes first wait: any: courier: {signal: courier_left} limit: {timeout: "${LIMIT:-5 min}"} payload: {event_type: dispatched} # wait.courier.done is true when the courier came before the limit next: when: - {condition: wait.courier.done, task: by_courier} default: by_post by_courier: payload: {event_type: sent_by_courier} by_post: payload: {event_type: sent_by_post} collect: payload: {event_type: courier_left} # Fires courier_left with this payload, so every waiting order resumes signal: courier_left # How many orders went each way, and the mean wait for dispatch, at the end stats: {level: typical, interval: 8 h} egress: - {type: Console} run: {until: 8 h} ``` ```python """The Process Interaction tutorial: packed orders wait for the courier, with a limit. One packer, an order every 2 seconds on average, and a courier every 10 minutes. Every record is printed to the terminal, and the script prints how many orders went by courier and by post, with limits of 5 and 8 minutes, at the end. To see only those lines, run: python process_interaction.py 2>/dev/null """ import logging from desflow import ConsoleEgress, SimulationContext logging.basicConfig( level=logging.INFO, format="%(levelname)s [%(asctime)s] %(message)s" ) def shop(limit: float = 300) -> SimulationContext: """The shop, where a packed order waits at most `limit` seconds for the courier.""" app = ( SimulationContext(sim_id="Shop", factor=0, random_seed=42) .add_resource("packers", current_cap=1, max_cap=4) .add_service("packing", dist="constant", value=1.5) .add_arrival("orders", dist="exponential", rate=0.5) # A courier every 10 minutes .add_arrival("couriers", dist="constant", value=600) # How many orders went each way, and the mean wait for dispatch, at the end .with_stats("typical", interval=8 * 3600) .add_egress(ConsoleEgress()) ) # Fired by the courier as it leaves with every order that waits for it, # and again at each later courier, so it is not one-shot app.add_signal("courier_left", once=False) @app.task(service_id="packing", resource_id="packers", next="dispatch") def pack_order(task_id: int): return {"event_type": "order_packed"} @app.task( # The courier's departure, or the limit, whichever comes first wait={ "any": {"courier": {"signal": "courier_left"}, "limit": {"timeout": limit}} }, # wait.courier.done is true when the courier came before the limit next={ "when": [{"condition": "wait.courier.done", "task": "by_courier"}], "default": "by_post", }, ) def dispatch(task_id: int): return {"event_type": "dispatched"} @app.task() def by_courier(task_id: int): return {"event_type": "sent_by_courier"} @app.task() def by_post(task_id: int): return {"event_type": "sent_by_post"} # Fires courier_left with this payload, so every waiting order resumes @app.task(signal="courier_left") def collect(task_id: int): return {"event_type": "courier_left"} for arrival, task, name in ( ("orders", pack_order, "pack_order"), ("couriers", collect, "collect"), ): def loop(context: SimulationContext, arrival=arrival, task=task, name=name): while True: entity = yield context.wait_for_arrival(arrival) context.spawn(task(context.next_instance(name), entity=entity)) app.arrival_loop(arrival)(loop) return app def outcomes(limit: float) -> dict: """Runs eight hours and returns how orders went, and the mean wait for dispatch.""" app = shop(limit) app.run(until="8 h") readings = app.env.stats.readings() name = "Shop.stats.tasks.{}".format return { "by_courier": readings[name("by_courier.finished")], "by_post": readings[name("by_post.finished")], "wait_mean": readings[name("dispatch.wait_mean")], } if __name__ == "__main__": for limit in (300, 480): result = outcomes(limit) print( f"limit {limit / 60:.0f} min: {result['by_courier']} by courier, " f"{result['by_post']} by post, mean wait {result['wait_mean']:6.1f} s" ) ``` ```python """The Process Interaction tutorial: packed orders wait for the courier, with a limit. One packer, an order every 2 seconds on average, and a courier every 10 minutes. Every record is printed to the terminal, and the script prints how many orders went by courier and by post, with limits of 5 and 8 minutes, at the end. To see only those lines, run: python process_interaction_low_level.py 2>/dev/null """ import itertools import logging from desflow import ( CapacityConfig, ConsoleEgress, DistributionConfig, DynamicRealtimeEnvironment, DynamicResource, Sampler, Signal, SimParameter, ) logging.basicConfig( level=logging.INFO, format="%(levelname)s [%(asctime)s] %(message)s" ) PARAMS = SimParameter( sim_id="Shop", arrival={ "orders": DistributionConfig(dist="exponential", rate=0.5), # A courier every 10 minutes "couriers": DistributionConfig(dist="constant", value=600), }, service={"packing": DistributionConfig(dist="constant", value=1.5)}, resources={"packers": CapacityConfig(current_cap=1, max_cap=4)}, ) def publish(env, key, task, task_id, value): env.publish_event(key, value, task=task, instance=task_id) def pack_order(env, sampler, shop, key, ids): task_id, path_id = next(ids["pack_order"]), "Shop.service.packing" publish( env, key, "pack_order", task_id, { "path_id": path_id, "sim_id": "Shop", "service": "packing", "status": "queued", }, ) env.stats.task_queued("pack_order", task_id) with shop["packers"].request() as request: yield request started = { "path_id": path_id, "sim_id": "Shop", "service": "packing", "status": "started", } publish(env, key, "pack_order", task_id, started) env.stats.task_started("pack_order", task_id) yield env.timeout(sampler.sample(env.registry.get_config(path_id))) publish(env, key, "pack_order", task_id, {"event_type": "order_packed"}) env.stats.task_finished("pack_order", task_id) yield from dispatch(env, shop, key, ids) def dispatch(env, shop, key, ids): task_id = next(ids["dispatch"]) publish(env, key, "dispatch", task_id, {"status": "queued"}) env.stats.task_queued("dispatch", task_id) # The courier's departure, or the limit, whichever comes first courier = shop["courier_left"].wait() done = yield env.any_of([courier, env.timeout(shop["limit"])]) publish(env, key, "dispatch", task_id, {"status": "started"}) env.stats.task_started("dispatch", task_id) publish(env, key, "dispatch", task_id, {"event_type": "dispatched"}) env.stats.task_finished("dispatch", task_id) # The courier came before the limit when its event is in the AnyOf's value task = "by_courier" if courier in done else "by_post" yield from send(env, key, task, ids) def send(env, key, task, ids): task_id = next(ids[task]) publish(env, key, task, task_id, {"event_type": f"sent_{task}"}) env.stats.task_finished(task, task_id) env.stats.flow_finished("orders") yield env.timeout(0) def collect(env, shop, key, ids): """Fires courier_left with the payload, so every waiting order resumes.""" task_id = next(ids["collect"]) payload = {"event_type": "courier_left"} publish(env, key, "collect", task_id, payload) env.stats.task_finished("collect", task_id) shop["courier_left"].fire(payload) env.stats.flow_finished("couriers") yield env.timeout(0) def generator(env, sampler, shop, arrival, ids): gap = env.registry.get_config(f"Shop.arrival.{arrival}") for number in itertools.count(1): yield env.timeout(sampler.sample(gap)) key = f"{arrival}-{number}" if arrival == "orders": env.process(pack_order(env, sampler, shop, key, ids)) else: env.process(collect(env, shop, key, ids)) def run(limit=300, until=8 * 3600, factor=0.0): env = DynamicRealtimeEnvironment(factor=factor) env.registry.register_sim_parameter(PARAMS) env.setup_egress([ConsoleEgress()]) # How many orders went each way, and the mean wait for dispatch, at the end env.setup_stats("Shop", "typical", interval=8 * 3600) shop = { "packers": DynamicResource(env, "Shop", "packers"), # Fired by the courier as it leaves with every order that waits for it, # and again at each later courier, so it is not one-shot "courier_left": Signal(env, "courier_left", once=False), "limit": limit, } names = ("pack_order", "dispatch", "by_courier", "by_post", "collect") ids = {name: itertools.count() for name in names} sampler = Sampler(seed=42) env.process(generator(env, sampler, shop, "orders", ids)) env.process(generator(env, sampler, shop, "couriers", ids)) try: env.run(until=until) finally: env.teardown() return env def outcomes(limit: float) -> dict: """Runs eight hours and returns how orders went, and the mean wait for dispatch.""" readings = run(limit).stats.readings() name = "Shop.stats.tasks.{}".format return { "by_courier": readings[name("by_courier.finished")], "by_post": readings[name("by_post.finished")], "wait_mean": readings[name("dispatch.wait_mean")], } if __name__ == "__main__": for limit in (300, 480): result = outcomes(limit) print( f"limit {limit / 60:.0f} min: {result['by_courier']} by courier, " f"{result['by_post']} by post, mean wait {result['wait_mean']:6.1f} s" ) ``` # Patience The shop now gets an order every 1.43 seconds on average (42 a minute, `rate: 0.7`). Its one packer packs one every 1.5 seconds (40 a minute), so orders arrive faster than they can be packed. A real customer does not wait for ever: one whose order has not started within 30 seconds cancels it. The courier also leaves at the hour, so the shop takes no new orders in the last five minutes. This page asks: **which orders leave or refuse to join, and what does that do to the wait of the others?** - **Decision:** which figures the shop reports for an hour in which customers may leave. - **Measures:** the orders that leave the queue or refuse to join, and the mean and longest wait of the packed orders. - **Runs:** two runs of the hour, one with a patience of 30 seconds and one without, each with the seed 42. - **Assumptions:** orders arrive at random, every order takes the same time to pack, and every customer has the same patience. ## What You Will Learn This page shows how to: - let an order leave the queue after waiting too long; - stop orders joining near closing time; - count the orders that left or never joined. ## What You Add This page adds a `patience` and a `balk` condition to the packing task. The shop is the one from [First Simulation](https://jaehyeon.me/desflow/latest/learn/first-model/first-simulation/index.md), with one packer and 1.5 seconds of packing, but with an order every 1.43 seconds on average. ______________________________________________________________________ ## Leave After a Wait An entity that leaves a queue after waiting too long **reneges**. In SimPy it waits for whichever comes first, the unit or a timeout, with the `|` of two events (an `AnyOf`), then checks which one happened. In desflow it is the task's `patience`: how long the task may wait before it leaves the queue and publishes `reneged`. The patience covers the task's `wait`, then its resource, then its `get` from a store or container. It counts waiting time only, and pauses while the task is served. Save the files from [Full Files](#full-files) in one folder and run the commands there: ```yaml # A customer cancels an order not started within 30 seconds patience: ${PATIENCE:-30 s} ``` `${PATIENCE:-30 s}` reads the environment variable `PATIENCE`, 30 seconds when it is not set, so `PATIENCE="1 h" desflow run patience.yaml` runs the hour with no limit that matters. `patience` takes seconds, a duration, or an expression such as `attr.patience`, so each order can bring its own. ```python # A customer cancels an order not started within 30 seconds patience=patience, ``` `patience` is 30 here, in seconds. It also takes a duration, as in YAML: `patience="30 s"`. `add_service` and `add_arrival` take a duration too, such as `value="4 min"`, as YAML does. Only the low-level `DistributionConfig` takes seconds. ```python # A customer cancels an order not started within 30 seconds result = yield request | env.timeout(patience) if request not in result: # Leaving the with block takes the request out of the queue publish("reneged") env.stats.task_reneged("pack_order", task_id) return ``` `request | env.timeout(patience)` is SimPy's `AnyOf`: it happens when either event does, and the yield gives back a mapping of the events that had happened by then. `request not in result` is true when the patience ran out first. Reading the result, and not `request.triggered`, matters when the unit is granted at the instant the patience ends: the order then reneges, as it does in a blueprint, where `request.triggered` would be true and serve it. Leaving the `with` block takes a waiting request out of the queue at once, so the packer is never granted to an order that has gone. [SimPy and desflow](https://jaehyeon.me/desflow/latest/simpy/#waiting-for-one-or-all) describes events and conditions. A reneged order publishes `reneged` in place of `started` and its finished event, and adds nothing to the wait statistics, because it was never served. Its flow ends there, unless the task names another to go on to: `on_renege` for an order that gave up and `on_balk` for one that was refused (it needs `balk`, `resource`, `seize` or `open`). The task they name reads `upstream.status`, which is `reneged` or `balked`. [Go On After Leaving](https://jaehyeon.me/desflow/latest/how-to/modelling/reneging-and-balking/#go-on-after-leaving) shows it in the three forms. `--stdout` prints the run's records as JSON lines, one record per line, instead of sending them to the blueprint's sinks. So `grep` can pick out one kind of record. These are the first two orders that leave: ```bash desflow run patience.yaml --stdout | grep '"reneged"' | head -2 ``` ```text {"stream_type":"event","sim_ts":370.51998198108714,"timestamp":"...","key":"orders-235","task":"pack_order","instance":234,"value":{"path_id":"Shop.service.packing","sim_id":"Shop","service":"packing","status":"reneged"}} {"stream_type":"event","sim_ts":601.3635869519446,"timestamp":"...","key":"orders-390","task":"pack_order","instance":389,"value":{"path_id":"Shop.service.packing","sim_id":"Shop","service":"packing","status":"reneged"}} ``` Both orders were queued 30 seconds earlier, at 340.5 and 571.4 seconds, and left when their patience ran out. In the builder and the low-level API, `ConsoleEgress(format="json")` as the sink prints the same lines. A grant and a patience can fall at the same instant: the packer finishes the previous order at exactly the moment the next order's 30 seconds run out. desflow then does what plain SimPy does: the outcome depends on which of the two events was scheduled first. The [Add Reneging and Balking](https://jaehyeon.me/desflow/latest/how-to/modelling/reneging-and-balking/index.md) guide shows both cases. ______________________________________________________________________ ## Refuse to Join An entity that does not join a queue at all **balks**. In SimPy it is an `if` before the request. In desflow it is the task's `balk`, a condition checked before the task joins the queue. When the condition holds, the task publishes `balked` and never requests the resource. Here `t`, the simulation time, stops new orders in the last five minutes: ```yaml # The courier leaves at the hour, so the last 5 minutes take no new orders balk: t >= 3300 ``` ```python # The courier leaves at the hour, so the last 5 minutes take no new orders balk="t >= 3300", ``` ```python # The courier leaves at the hour, so the last 5 minutes take no new orders if env.now >= 3300: publish("balked") env.stats.task_balked("pack_order", task_id) return ``` The condition reads the names every expression reads, such as `attr.` for the order's own attributes and `level.` for a store or container. [Task Flow](https://jaehyeon.me/desflow/latest/user-guide/model-parts/task-flow/#how-it-works) lists them. A resource can refuse an order too. With a `queue_limit`, the resource refuses a request made while that many requests already wait, and the task balks, as [Queue Limit](https://jaehyeon.me/desflow/latest/user-guide/resources/units-and-queues/#queue-limit) describes. The limit is also a registry path, `Shop.resources.packers.queue_limit`, so a scenario step can change it during a run. A smaller limit removes nobody who waits, and `null` is no limit. ______________________________________________________________________ ## Count Who Left With statistics at `basic` and above, each task publishes how many instances reneged and balked, as `Shop.stats.tasks.pack_order.reneged` and `.balked`, once the first one happens. `typical` adds the mean and longest wait of the orders that were served: ```yaml # Counts of finished, reneged and balked orders, and the mean wait, at the end stats: {level: typical, interval: 1 h} ``` ```python # Counts of finished, reneged and balked orders, and the mean wait, at the end .with_stats("typical", interval=3600) ``` ```python # Counts of finished, reneged and balked orders, and the mean wait, at the end env.setup_stats("Shop", "typical", interval=3600) ``` A low-level process counts its own outcomes with `env.stats.task_reneged(task, instance)` and `env.stats.task_balked(task, instance)`, as the full file below does. ______________________________________________________________________ ## What You Get and Why Which orders leave or refuse to join, and what does that do to the others? Each figure here comes from one run of the hour with the seed 42. With a patience of 30 seconds, **144 orders** leave the queue during the hour, and the mean wait of the packed orders falls from **120.75 seconds** to **19.56 seconds**. No packed order waits more than 30 seconds. In both runs the **217 orders** that arrive in the last five minutes refuse to join. The wait of each packed order over the hour shows why: Each tab prints both runs: the orders packed, reneged and balked, and the mean wait. A patience of an hour is longer than any wait, so no order reneges, and the run publishes no `reneged` count. ```bash # Orders packed, given up and turned away, and the mean wait desflow run patience.yaml --stdout | grep -E 'pack_order\.(finished|reneged|balked|wait_mean)"' | tail -4 # A patience of an hour PATIENCE="1 h" desflow run patience.yaml --stdout | grep -E 'pack_order\.(finished|reneged|balked|wait_mean)"' | tail -4 ``` ```text {"stream_type":"telemetry","sim_ts":3600.0,"timestamp":"...","path_id":"Shop.stats.tasks.pack_order.finished","value":2200} {"stream_type":"telemetry","sim_ts":3600.0,"timestamp":"...","path_id":"Shop.stats.tasks.pack_order.balked","value":217} {"stream_type":"telemetry","sim_ts":3600.0,"timestamp":"...","path_id":"Shop.stats.tasks.pack_order.reneged","value":144} {"stream_type":"telemetry","sim_ts":3600.0,"timestamp":"...","path_id":"Shop.stats.tasks.pack_order.wait_mean","value":19.561415419101984} {"stream_type":"telemetry","sim_ts":3600.0,"timestamp":"...","path_id":"Shop.stats.tasks.pack_order.finished","value":2344} {"stream_type":"telemetry","sim_ts":3600.0,"timestamp":"...","path_id":"Shop.stats.tasks.pack_order.balked","value":217} {"stream_type":"telemetry","sim_ts":3600.0,"timestamp":"...","path_id":"Shop.stats.tasks.pack_order.wait_mean","value":120.75119985855385} ``` ```bash python patience.py 2>/dev/null ``` ```text patience 30 s: 2200 packed, 144 reneged, 217 balked, mean wait 19.56 s patience none: 2344 packed, 0 reneged, 217 balked, mean wait 120.75 s ``` ```bash python patience_low_level.py 2>/dev/null ``` ```text patience 30 s: 2200 packed, 144 reneged, 217 balked, mean wait 19.56 s patience none: 2344 packed, 0 reneged, 217 balked, mean wait 120.75 s ``` Orders arrive at 42 a minute and bring 0.7 × 1.5 = 1.05 seconds of packing each second, more than one packer can do. So without patience the queue grows, and every order waits longer than the one before. Patience removes the orders that have waited longest, so the queue stays short for the rest. The shop packs 144 fewer orders, and every order it packs waits less. The mean wait of packed orders leaves out the orders that left. So report the reneged and balked counts beside it. [Queueing Basics](https://jaehyeon.me/desflow/latest/learn/concepts/queueing-basics/#utilisation) explains why a queue grows without limit above utilisation 1. [Statistics](https://jaehyeon.me/desflow/latest/user-guide/results/statistics/index.md) describes what each count measures. ## Key Takeaways - Patience removes the orders that have waited longest, so the others wait less. - The mean wait of packed orders leaves out the orders that left. - Report the reneged and balked counts beside the mean wait. ______________________________________________________________________ ## Full Files Full files ```yaml # The Patience tutorial: orders leave after waiting too long, and none join near # closing. Run it with: desflow run patience.yaml # With no time limit: PATIENCE="1 h" desflow run patience.yaml simulation: {sim_id: Shop, factor: 0, random_seed: 42} resources: packers: {current_cap: 1, max_cap: 4} services: packing: {dist: constant, value: 1.5 s} arrivals: # An order every 1.43 s on average (0.7 a second): more than one packer packs orders: {dist: exponential, rate: 0.7, spawn: pack_order} tasks: pack_order: service: packing resource: packers # A customer cancels an order not started within 30 seconds patience: ${PATIENCE:-30 s} # The courier leaves at the hour, so the last 5 minutes take no new orders balk: t >= 3300 payload: {event_type: order_packed} # Counts of finished, reneged and balked orders, and the mean wait, at the end stats: {level: typical, interval: 1 h} egress: - {type: Console} run: {until: 1 h} ``` ```python """The Patience tutorial: orders leave after waiting too long, and none join near closing. One packer, an order every 1.43 seconds on average (rate 0.7) and 1.5 seconds of packing. Every record is printed to the terminal, and the script prints what happened to the orders with a patience of 30 seconds and with none at the end. To see only those lines, run: python patience.py 2>/dev/null """ import logging from desflow import ConsoleEgress, SimulationContext logging.basicConfig( level=logging.INFO, format="%(levelname)s [%(asctime)s] %(message)s" ) def shop(patience: float = 30) -> SimulationContext: """The shop, where a customer waits at most `patience` seconds.""" app = ( SimulationContext(sim_id="Shop", factor=0, random_seed=42) .add_resource("packers", current_cap=1, max_cap=4) .add_service("packing", dist="constant", value=1.5) # An order every 1.43 s on average (0.7 a second): more than one packer packs .add_arrival("orders", dist="exponential", rate=0.7) # Counts of finished, reneged and balked orders, and the mean wait, at the end .with_stats("typical", interval=3600) .add_egress(ConsoleEgress()) ) @app.task( service_id="packing", resource_id="packers", # A customer cancels an order not started within 30 seconds patience=patience, # The courier leaves at the hour, so the last 5 minutes take no new orders balk="t >= 3300", ) def pack_order(task_id: int): return {"event_type": "order_packed"} @app.arrival_loop("orders") def order_generator(context: SimulationContext): task_id = 0 while True: order = yield context.wait_for_arrival("orders") context.spawn(pack_order(task_id, entity=order)) task_id += 1 return app def outcomes(patience: float) -> dict: """Runs one hour and returns what happened to the orders, and the mean wait.""" app = shop(patience) app.run(until="1 h") readings = app.env.stats.readings() name = "Shop.stats.tasks.pack_order.{}".format return { outcome: readings.get(name(outcome), 0) for outcome in ("finished", "reneged", "balked", "wait_mean") } if __name__ == "__main__": for patience, label in ((30, "30 s"), (3600, "none")): result = outcomes(patience) print( f"patience {label:>4}: {result['finished']} packed, " f"{result['reneged']} reneged, {result['balked']} balked, " f"mean wait {result['wait_mean']:5.2f} s" ) ``` ```python """The Patience tutorial: orders leave after waiting too long, and none join near closing. One packer, an order every 1.43 seconds on average (rate 0.7) and 1.5 seconds of packing. Every record is printed to the terminal, and the script prints what happened to the orders with a patience of 30 seconds and with none at the end. To see only those lines, run: python patience_low_level.py 2>/dev/null """ import logging from desflow import ( CapacityConfig, ConsoleEgress, DistributionConfig, DynamicRealtimeEnvironment, DynamicResource, Sampler, SimParameter, ) logging.basicConfig( level=logging.INFO, format="%(levelname)s [%(asctime)s] %(message)s" ) PARAMS = SimParameter( sim_id="Shop", # An order every 1.43 s on average (0.7 a second): more than one packer packs arrival={"orders": DistributionConfig(dist="exponential", rate=0.7)}, service={"packing": DistributionConfig(dist="constant", value=1.5)}, resources={"packers": CapacityConfig(current_cap=1, max_cap=4)}, ) def pack_order(env, sampler, packers, key, task_id, patience): path_id = "Shop.service.packing" def publish(status): value = { "path_id": path_id, "sim_id": "Shop", "service": "packing", "status": status, } env.publish_event(key, value, task="pack_order", instance=task_id) # The courier leaves at the hour, so the last 5 minutes take no new orders if env.now >= 3300: publish("balked") env.stats.task_balked("pack_order", task_id) return publish("queued") env.stats.task_queued("pack_order", task_id) with packers.request() as request: # A customer cancels an order not started within 30 seconds result = yield request | env.timeout(patience) if request not in result: # Leaving the with block takes the request out of the queue publish("reneged") env.stats.task_reneged("pack_order", task_id) return publish("started") env.stats.task_started("pack_order", task_id) yield env.timeout(sampler.sample(env.registry.get_config(path_id))) value = {"event_type": "order_packed"} env.publish_event(key, value, task="pack_order", instance=task_id) env.stats.task_finished("pack_order", task_id) def order_generator(env, sampler, packers, patience): arrival = env.registry.get_config("Shop.arrival.orders") task_id = 0 while True: yield env.timeout(sampler.sample(arrival)) key = f"orders-{task_id + 1}" env.process(pack_order(env, sampler, packers, key, task_id, patience)) task_id += 1 def run(patience=30, until=3600, factor=0.0): env = DynamicRealtimeEnvironment(factor=factor) env.registry.register_sim_parameter(PARAMS) env.setup_egress([ConsoleEgress()]) # Counts of finished, reneged and balked orders, and the mean wait, at the end env.setup_stats("Shop", "typical", interval=3600) packers = DynamicResource(env, "Shop", "packers") sampler = Sampler(seed=42) env.process(order_generator(env, sampler, packers, patience)) try: env.run(until=until) finally: env.teardown() return env def outcomes(patience: float) -> dict: """Runs one hour and returns what happened to the orders, and the mean wait.""" readings = run(patience).stats.readings() name = "Shop.stats.tasks.pack_order.{}".format return { outcome: readings.get(name(outcome), 0) for outcome in ("finished", "reneged", "balked", "wait_mean") } if __name__ == "__main__": for patience, label in ((30, "30 s"), (3600, "none")): result = outcomes(patience) print( f"patience {label:>4}: {result['finished']} packed, " f"{result['reneged']} reneged, {result['balked']} balked, " f"mean wait {result['wait_mean']:5.2f} s" ) ``` [Add Reneging and Balking](https://jaehyeon.me/desflow/latest/how-to/modelling/reneging-and-balking/index.md) shows the same two decisions in a shop example, with ties and how to check that every order is accounted for. # Interruptions A quarter of the shop's orders are express, as in [Priorities](https://jaehyeon.me/desflow/latest/learn/shop-logic/priorities/index.md), but now an express order does not wait for the regular order being packed: it takes the packer at once. This page asks: **what remains of a regular order's packing when an express order takes its packer, and which way of carrying on keeps regular orders waiting least?** - **Decision:** which of three policies a regular order follows when it loses the packer. - **Measures:** the number of preemptions, the mean wait of regular orders, and the orders packed and lost. - **Runs:** three runs of the hour, one for each policy, each with the seed 42. - **Assumptions:** both kinds of order arrive at random, and every order takes the same time to pack. ## What You Will Learn This page shows how to: - let express orders take the packer from regular ones; - choose what a preempted order does: resume, restart or abandon; - interrupt the orders in the shop from outside. ## What You Add This page adds a packer that can be **preempted**, as [Preemption](#preemption) explains, and an `on_interrupt` policy on regular orders: `resume`, `restart` or `abandon`. It also recalls the regular orders once: every regular order in the shop receives an interrupt and follows its policy, and the packer stays available. Under `resume` and `restart` a recalled order queues for the packer again with the same priority, so it waits behind the express orders and behind the regular orders that queued again before it. Under `abandon` it is lost. [Model Breakdowns](https://jaehyeon.me/desflow/latest/how-to/modelling/breakdowns/index.md) shows a packer that is out of use for a time. The shop is the one from Priorities: one packer and 1.5 seconds of packing. A regular order arrives every 2.22 seconds on average (`rate: 0.45`), and an express order every 6.67 seconds (`rate: 0.15`). ______________________________________________________________________ ## Preemption Priority so far decided only who goes next. **Preemption** also stops the work in progress. In SimPy, a request may find every unit of a `PreemptiveResource` busy. A lower priority value is more urgent. When the request is more urgent than a process holding a unit, the resource takes the unit from the least urgent holder, the one with the highest priority value, and that process receives an `Interrupt`. In desflow it is `preempt: true` on a resource whose queue is `priority`. Save the files from [Full Files](#full-files) in one folder and run the commands there: ```yaml resources: # An express order takes the packer from a regular one being packed packers: {current_cap: 1, max_cap: 4, queue: priority, preempt: true} ``` ```python # An express order takes the packer from a regular one being packed .add_resource( "packers", current_cap=1, max_cap=4, queue="priority", preempt=True ) ``` ```python # An express order takes the packer from a regular one being packed "packers": DynamicResource( env, "Shop", "packers", queue="priority", preempt=True ), ``` [`preempt=True`](https://jaehyeon.me/desflow/latest/simpy/#resources) gives the resource SimPy's preemption, and the process that holds a unit [receives an interrupt](https://jaehyeon.me/desflow/latest/simpy/#interrupts) when it is preempted. The code below uses three more SimPy names: - [`release(request)`](https://simpy.readthedocs.io/en/4.1.2/api_reference/simpy.resources.html#simpy.resources.resource.Resource.release) gives back the unit a request holds; - [`env.active_process`](https://simpy.readthedocs.io/en/4.1.2/api_reference/simpy.core.html#simpy.core.Environment.active_process) is the process that is running now; - [`request.cancel()`](https://simpy.readthedocs.io/en/4.1.2/api_reference/simpy.resources.html#simpy.resources.base.Put.cancel) takes a request that has not been granted out of the queue. Equal priorities do not preempt, so one express order does not take the packer from another. ______________________________________________________________________ ## Resume, Restart or Abandon A preempted or interrupted task stops waiting for anything. A preemption takes its packer, so it gives that up. A plain `interrupt` leaves a packer it already holds with it, as a SimPy process that keeps its request does. A packer it was still waiting for depends on how the task asks for it. With `resource:`, the request goes back to the end of the line. With `seize` or a `request` in a wait, the request keeps its place under `resume`, and asks again at the back of the line under `restart`. A packer granted at the instant of the interrupt stays held. A breakdown takes the unit too. Its `on_interrupt` then says what it does: - `resume`, the default: it goes on at once with a packer it still holds, or queues again and, once it has the packer back, packs for the time it had left; - `restart`: it does the same but packs for a new time, drawn from the same seeded stream, as if the work were spoiled; - `abandon`: it gives back every unit and ends, and its flow with it, unless `on_interrupt_next` names a task to go to. A task that names a task which asks for the packer again queues behind the orders already waiting. A task can also do work of its own when the interrupt arrives, without giving up its place in the flow. `on_interrupt_run` names a task that runs as a child flow of the same entity after each interrupt or preemption under `resume` or `restart`. The task then goes on with the time it had left, or with a new time under `restart`. An interrupt that arrives while the child runs reaches the child, and a child that fails fails the task. `on_interrupt_run` is refused with `abandon`, with `resource` and with a `request` in a wait, because it is for work that holds no unit of its own. An order that is abandoned when it loses its packer, and goes to be packed by hand: ```yaml # An order that loses its packer to a rush order is packed by hand instead on_interrupt: abandon on_interrupt_next: pack_by_hand ``` ```python @app.task( service_id="packing", resource_id="packers", priority=1, # An order that loses its packer to a rush order is packed by hand instead on_interrupt="abandon", on_interrupt_next="pack_by_hand", ) def pack(task_id: int): return {"event_type": "packed"} ``` ```python def pack(env, sampler, packers, counts): request = packers.request(priority=1) try: yield request yield env.timeout( sampler.sample(env.registry.get_config("Shop.service.packing")) ) counts["packed"] += 1 except simpy.Interrupt: # An order that loses its packer to a rush order is packed by hand instead yield from pack_by_hand(env, sampler, counts) finally: packers.release(request) ``` In the low-level API the process catches the `Interrupt` and packs by hand with `yield from`, in the same process. The task publishes `preempted` (or `interrupted`) when it loses the packer, and `resumed` when it is served again, also when it never gave the packer up. A preempted request is marked as preempted, so the packer is never given back to it by mistake. If the order that lost the packer has already ended, the preemption fails the flow that asked, with SimPy's `RuntimeError`. A `seize` unit is asked for again under `resume` and `restart`. A `preempted` record names the express order that took the packer (`preempted_by`, its entity key) and the time the regular order had held it (`usage_since`). In a blueprint, a task that `on_interrupt_next` names reads the same facts as `cause.by`, `cause.usage_since` and `cause.left` (the service time that was left). An expression reads who holds a unit and who waits as `held(packers)` and `waiting(packers)`, lists with each entity and its `rank` and `time`: ```yaml pack_order: service: packing resource: packers priority: 1 # What a regular order does when it loses the packer on_interrupt: ${POLICY:-resume} payload: {event_type: order_packed} ``` `${POLICY:-resume}` reads the environment variable `POLICY`, so `POLICY=restart desflow run interruptions.yaml` runs the second policy. ```python @app.task( service_id="packing", resource_id="packers", priority=1, # What a regular order does when it loses the packer on_interrupt=policy, ) def pack_order(task_id: int): return {"event_type": "order_packed"} ``` ```python def pack(env, sampler, shop, arrival, key, task_id, policy): """Packs one order; when it loses the packer, it follows `policy`.""" task, priority = TASKS[arrival] path_id = "Shop.service.packing" def publish(value): env.publish_event(key, value, task=task, instance=task_id) publish( {"path_id": path_id, "sim_id": "Shop", "service": "packing", "status": "queued"} ) env.stats.task_queued(task, task_id) shop["running"].setdefault(task, []).append(env.active_process) shop["keys"][env.active_process] = key remaining, started = None, False request = None while True: if request is None: request = shop["packers"].request(priority=priority) since = None try: if not request.processed: yield request status = "resumed" if started else "started" publish( { "path_id": path_id, "sim_id": "Shop", "service": "packing", "status": status, } ) if started: env.stats.task_resumed(task, task_id) else: env.stats.task_started(task, task_id) started = True if remaining is None: remaining = sampler.sample(env.registry.get_config(path_id)) since = env.now yield env.timeout(remaining) publish({"event_type": "order_packed" if priority else "express_packed"}) env.stats.task_finished(task, task_id) shop["packers"].release(request) break except simpy.Interrupt as interrupt: if policy == "abandon" or request not in shop["packers"].users: # Ask again if queued or preempted; abandon gives a held unit back request.cancel() shop["packers"].release(request) request = None if since is not None: # resume serves what is left; restart draws a new packing time remaining = ( remaining - (env.now - since) if policy == "resume" else None ) preempted = isinstance(interrupt.cause, Preempted) if preempted: value = { "status": "preempted", "resource": "packers", "preempted_by": shop["keys"].get(interrupt.cause.by), "usage_since": interrupt.cause.usage_since, } else: value = {"status": "interrupted", "cause": interrupt.cause} publish( {"path_id": path_id, "sim_id": "Shop", "service": "packing", **value} ) env.stats.task_interrupted(task, task_id, preempted=preempted) if policy == "abandon": env.stats.task_dropped(task, task_id) shop["running"][task].remove(env.active_process) del shop["keys"][env.active_process] return shop["running"][task].remove(env.active_process) del shop["keys"][env.active_process] env.stats.flow_finished(arrival) ``` The process catches `simpy.Interrupt`. For a preemption, its cause is SimPy's `Preempted`. A preempted process, or one whose request still waits, cancels its request and requests the packer again. An interrupted process that holds the packer keeps its request. `on_interrupt` writes that loop for you. SimPy delivers an interrupt as an `URGENT` event, which [End Conditions](https://jaehyeon.me/desflow/latest/learn/first-model/end-conditions/#close-the-doors-then-finish) explains. The statistics count each `preempted`, `interrupted` and `resumed`. A resumed order's wait is the sum of its waits, and its packing time is the total time it was packed: ```yaml # Counts of preemptions and resumptions, and the mean wait and service, at the end stats: {level: typical, interval: 1 h} ``` ```python # Counts of preemptions and resumptions, and the mean wait and service, at the end .with_stats("typical", interval=3600) ``` ```python # Counts of preemptions and resumptions, and the mean wait and service, at the end env.setup_stats("Shop", "typical", interval=3600) ``` ______________________________________________________________________ ## Interrupt a Task Preemption is one source of interrupts, and a model can send others. An `interrupt` names a task. Every instance of that task that is running, waiting or being served receives an interrupt with the given `cause`, and follows its `on_interrupt`. A `where` condition, such as `attr.order == 3`, is read in the scope of each instance, and limits the interrupt to the instances for which it holds. It reads what the instance's own expressions read. `wait..done` is false until the instance's wait has ended. Here a recall at 31 minutes interrupts every regular order: ```yaml scenario: # A recall at 31 minutes: every regular order in the shop, # waiting or being packed, is interrupted - at: 31 min interrupt: {task: pack_order, cause: recalled} ``` A task can carry the same `interrupt`, applied when it finishes. ```python def recall_orders(context: SimulationContext): """A recall at 31 minutes: every regular order in the shop, waiting or being packed, is interrupted.""" yield context.env.timeout(1860) context.interrupt("pack_order", cause="recalled") app.add_process(recall_orders) ``` `context.interrupt(task, where=None, cause=None)` returns how many instances it reached. It never reaches the instance that calls it. ```python def recall_orders(env, shop): """A recall at 31 minutes: every regular order in the shop, waiting or being packed, is interrupted.""" yield env.timeout(1860) for process in list(shop["running"].get("pack_order", [])): process.interrupt("recalled") ``` `process.interrupt(cause)` is SimPy's. The model keeps its own list of the processes it may interrupt. ______________________________________________________________________ ## What You Get and Why What remains of a regular order's packing when an express order takes its packer? Each figure here comes from one run of the hour with the seed 42. - With `resume`, the time it had left remains. After **349** preemptions, regular orders wait **8.17 seconds** on average. - With `restart`, nothing remains: each preempted order packs again from the start. Preemptions rise to **389**, and the mean wait rises more than fivefold to **44.11 seconds**. - With `abandon`, the order is lost. **313** orders are lost, 311 to preemption and 2 to the recall at 31 minutes. The **1,328** packed orders wait only **3.64 seconds** on average, because every interrupted order leaves the queue. The recall at 31 minutes reaches every regular order in the shop at that moment: 3 under `resume`, 24 under `restart`, whose longer queue holds more orders, and 2 under `abandon`: Each tab prints all three policies: the orders packed, preempted and recalled (`interrupted`), the mean wait and the mean packing time. ```bash # The resume policy: orders preempted, recalled and packed, mean wait and packing time desflow run interruptions.yaml --stdout | grep -E 'pack_order\.(preempted|interrupted|finished|wait_mean|service_mean)"' | tail -5 # The restart policy POLICY=restart desflow run interruptions.yaml --stdout | grep -E 'pack_order\.(preempted|interrupted|finished|wait_mean|service_mean)"' | tail -5 # The abandon policy POLICY=abandon desflow run interruptions.yaml --stdout | grep -E 'pack_order\.(preempted|interrupted|finished|wait_mean|service_mean)"' | tail -5 ``` ```text {"stream_type":"telemetry","sim_ts":3600.0,"timestamp":"...","path_id":"Shop.stats.tasks.pack_order.finished","value":1640} {"stream_type":"telemetry","sim_ts":3600.0,"timestamp":"...","path_id":"Shop.stats.tasks.pack_order.interrupted","value":3} {"stream_type":"telemetry","sim_ts":3600.0,"timestamp":"...","path_id":"Shop.stats.tasks.pack_order.preempted","value":349} {"stream_type":"telemetry","sim_ts":3600.0,"timestamp":"...","path_id":"Shop.stats.tasks.pack_order.wait_mean","value":8.167685860665559} {"stream_type":"telemetry","sim_ts":3600.0,"timestamp":"...","path_id":"Shop.stats.tasks.pack_order.service_mean","value":1.5} {"stream_type":"telemetry","sim_ts":3600.0,"timestamp":"...","path_id":"Shop.stats.tasks.pack_order.finished","value":1640} {"stream_type":"telemetry","sim_ts":3600.0,"timestamp":"...","path_id":"Shop.stats.tasks.pack_order.interrupted","value":24} {"stream_type":"telemetry","sim_ts":3600.0,"timestamp":"...","path_id":"Shop.stats.tasks.pack_order.preempted","value":389} {"stream_type":"telemetry","sim_ts":3600.0,"timestamp":"...","path_id":"Shop.stats.tasks.pack_order.wait_mean","value":44.11194399851226} {"stream_type":"telemetry","sim_ts":3600.0,"timestamp":"...","path_id":"Shop.stats.tasks.pack_order.service_mean","value":1.6706232870060977} {"stream_type":"telemetry","sim_ts":3600.0,"timestamp":"...","path_id":"Shop.stats.tasks.pack_order.finished","value":1328} {"stream_type":"telemetry","sim_ts":3600.0,"timestamp":"...","path_id":"Shop.stats.tasks.pack_order.interrupted","value":2} {"stream_type":"telemetry","sim_ts":3600.0,"timestamp":"...","path_id":"Shop.stats.tasks.pack_order.preempted","value":311} {"stream_type":"telemetry","sim_ts":3600.0,"timestamp":"...","path_id":"Shop.stats.tasks.pack_order.wait_mean","value":3.643851284875778} {"stream_type":"telemetry","sim_ts":3600.0,"timestamp":"...","path_id":"Shop.stats.tasks.pack_order.service_mean","value":1.5000000000000002} ``` ```bash python interruptions.py 2>/dev/null ``` ```text resume : 349 preempted, 3 recalled, 1640 packed, mean wait 8.17 s, mean packing 1.50 s restart: 389 preempted, 24 recalled, 1640 packed, mean wait 44.11 s, mean packing 1.67 s abandon: 311 preempted, 2 recalled, 1328 packed, mean wait 3.64 s, mean packing 1.50 s ``` ```bash python interruptions_low_level.py 2>/dev/null ``` ```text resume : 349 preempted, 3 recalled, 1640 packed, mean wait 8.17 s, mean packing 1.50 s restart: 389 preempted, 24 recalled, 1640 packed, mean wait 44.11 s, mean packing 1.67 s abandon: 311 preempted, 2 recalled, 1328 packed, mean wait 3.64 s, mean packing 1.50 s ``` Under `restart` the packer spends part of its time on packing that is thrown away, so it does more work for the same orders. The mean time packed rises from 1.50 to 1.67 seconds, and the load nears what one packer can do. Waits then grow fast, as [Queueing Basics](https://jaehyeon.me/desflow/latest/learn/concepts/queueing-basics/#waits-near-full-use) explains. `resume` loses no work, so its waits are close to those of plain priority. `abandon` looks best only because the mean leaves out the orders it lost. So report the count of lost orders beside its mean wait. The decision is `resume`: it loses no order and its mean wait, 8.17 seconds, is the lowest of the two policies that keep every order. [Priority and Preemption](https://jaehyeon.me/desflow/latest/user-guide/resources/priority-and-preemption/#preemption) describes preemption, and [Tasks and Processes](https://jaehyeon.me/desflow/latest/user-guide/tasks-and-processes/index.md) the task's steps. ## Key Takeaways - Preemption gives an urgent task the resource at once, and the task it takes it from must wait. - `resume` loses no work. `restart` throws work away and adds load, so waits grow fast near full use. - `abandon` looks best only because the mean leaves out the lost orders, so report their count beside it. ______________________________________________________________________ ## Full Files Full files ```yaml # The Interruptions tutorial: express orders take the packer from regular ones. # Run it with: desflow run interruptions.yaml # With restart instead of resume: POLICY=restart desflow run interruptions.yaml simulation: {sim_id: Shop, factor: 0, random_seed: 42} resources: # An express order takes the packer from a regular one being packed packers: {current_cap: 1, max_cap: 4, queue: priority, preempt: true} services: packing: {dist: constant, value: 1.5 s} arrivals: # An order every 1.67 s on average in all (0.6 a second), one in four express orders: {dist: exponential, rate: 0.45, spawn: pack_order} express: {dist: exponential, rate: 0.15, spawn: pack_express} tasks: pack_order: service: packing resource: packers priority: 1 # What a regular order does when it loses the packer on_interrupt: ${POLICY:-resume} payload: {event_type: order_packed} pack_express: service: packing resource: packers priority: 0 payload: {event_type: express_packed} scenario: # A recall at 31 minutes: every regular order in the shop, # waiting or being packed, is interrupted - at: 31 min interrupt: {task: pack_order, cause: recalled} # Counts of preemptions and resumptions, and the mean wait and service, at the end stats: {level: typical, interval: 1 h} egress: - {type: Console} run: {until: 1 h} ``` ```python """The Interruptions tutorial: express orders take the packer from regular ones. One packer and 1.5 seconds of packing. A regular order arrives every 2.22 seconds on average (rate 0.45), and an express order every 6.67 seconds (rate 0.15). Every record is printed to the terminal, and the script prints what preemption did to regular orders under each policy at the end. To see only those lines, run: python interruptions.py 2>/dev/null """ import logging from desflow import ConsoleEgress, SimulationContext logging.basicConfig( level=logging.INFO, format="%(levelname)s [%(asctime)s] %(message)s" ) def shop(policy: str = "resume") -> SimulationContext: """The shop, where a regular order follows `policy` when it loses the packer.""" app = ( SimulationContext(sim_id="Shop", factor=0, random_seed=42) # An express order takes the packer from a regular one being packed .add_resource( "packers", current_cap=1, max_cap=4, queue="priority", preempt=True ) .add_service("packing", dist="constant", value=1.5) # An order every 1.67 s on average in all (0.6 a second), one in four express .add_arrival("orders", dist="exponential", rate=0.45) .add_arrival("express", dist="exponential", rate=0.15) # Counts of preemptions and resumptions, and the mean wait and service, at the end .with_stats("typical", interval=3600) .add_egress(ConsoleEgress()) ) @app.task( service_id="packing", resource_id="packers", priority=1, # What a regular order does when it loses the packer on_interrupt=policy, ) def pack_order(task_id: int): return {"event_type": "order_packed"} @app.task(service_id="packing", resource_id="packers", priority=0) def pack_express(task_id: int): return {"event_type": "express_packed"} for arrival, task, name in ( ("orders", pack_order, "pack_order"), ("express", pack_express, "pack_express"), ): def loop(context: SimulationContext, arrival=arrival, task=task, name=name): while True: entity = yield context.wait_for_arrival(arrival) context.spawn(task(context.next_instance(name), entity=entity)) app.arrival_loop(arrival)(loop) def recall_orders(context: SimulationContext): """A recall at 31 minutes: every regular order in the shop, waiting or being packed, is interrupted.""" yield context.env.timeout(1860) context.interrupt("pack_order", cause="recalled") app.add_process(recall_orders) return app def outcomes(policy: str) -> dict: """Runs one hour and returns what preemption did to regular orders.""" app = shop(policy) app.run(until="1 h") readings = app.env.stats.readings() name = "Shop.stats.tasks.pack_order.{}".format return { "preempted": readings[name("preempted")], "interrupted": readings.get(name("interrupted"), 0), "finished": readings[name("finished")], "wait_mean": readings[name("wait_mean")], "service_mean": readings[name("service_mean")], } if __name__ == "__main__": for policy in ("resume", "restart", "abandon"): r = outcomes(policy) print( f"{policy:<7}: {r['preempted']} preempted, {r['interrupted']} recalled, " f"{r['finished']} packed, " f"mean wait {r['wait_mean']:5.2f} s, mean packing {r['service_mean']:4.2f} s" ) ``` ```python """The Interruptions tutorial: express orders take the packer from regular ones. One packer and 1.5 seconds of packing. A regular order arrives every 2.22 seconds on average (rate 0.45), and an express order every 6.67 seconds (rate 0.15). Every record is printed to the terminal, and the script prints what preemption did to regular orders under each policy at the end. To see only those lines, run: python interruptions_low_level.py 2>/dev/null """ import itertools import logging import simpy from simpy.resources.resource import Preempted from desflow import ( CapacityConfig, ConsoleEgress, DistributionConfig, DynamicRealtimeEnvironment, DynamicResource, Sampler, SimParameter, ) logging.basicConfig( level=logging.INFO, format="%(levelname)s [%(asctime)s] %(message)s" ) PARAMS = SimParameter( sim_id="Shop", arrival={ # An order every 1.67 s on average in all (0.6 a second), one in four express "orders": DistributionConfig(dist="exponential", rate=0.45), "express": DistributionConfig(dist="exponential", rate=0.15), }, service={"packing": DistributionConfig(dist="constant", value=1.5)}, resources={"packers": CapacityConfig(current_cap=1, max_cap=4)}, ) TASKS = {"orders": ("pack_order", 1), "express": ("pack_express", 0)} def pack(env, sampler, shop, arrival, key, task_id, policy): """Packs one order; when it loses the packer, it follows `policy`.""" task, priority = TASKS[arrival] path_id = "Shop.service.packing" def publish(value): env.publish_event(key, value, task=task, instance=task_id) publish( {"path_id": path_id, "sim_id": "Shop", "service": "packing", "status": "queued"} ) env.stats.task_queued(task, task_id) shop["running"].setdefault(task, []).append(env.active_process) shop["keys"][env.active_process] = key remaining, started = None, False request = None while True: if request is None: request = shop["packers"].request(priority=priority) since = None try: if not request.processed: yield request status = "resumed" if started else "started" publish( { "path_id": path_id, "sim_id": "Shop", "service": "packing", "status": status, } ) if started: env.stats.task_resumed(task, task_id) else: env.stats.task_started(task, task_id) started = True if remaining is None: remaining = sampler.sample(env.registry.get_config(path_id)) since = env.now yield env.timeout(remaining) publish({"event_type": "order_packed" if priority else "express_packed"}) env.stats.task_finished(task, task_id) shop["packers"].release(request) break except simpy.Interrupt as interrupt: if policy == "abandon" or request not in shop["packers"].users: # Ask again if queued or preempted; abandon gives a held unit back request.cancel() shop["packers"].release(request) request = None if since is not None: # resume serves what is left; restart draws a new packing time remaining = ( remaining - (env.now - since) if policy == "resume" else None ) preempted = isinstance(interrupt.cause, Preempted) if preempted: value = { "status": "preempted", "resource": "packers", "preempted_by": shop["keys"].get(interrupt.cause.by), "usage_since": interrupt.cause.usage_since, } else: value = {"status": "interrupted", "cause": interrupt.cause} publish( {"path_id": path_id, "sim_id": "Shop", "service": "packing", **value} ) env.stats.task_interrupted(task, task_id, preempted=preempted) if policy == "abandon": env.stats.task_dropped(task, task_id) shop["running"][task].remove(env.active_process) del shop["keys"][env.active_process] return shop["running"][task].remove(env.active_process) del shop["keys"][env.active_process] env.stats.flow_finished(arrival) def order_generator(env, sampler, shop, arrival, policy): config = env.registry.get_config(f"Shop.arrival.{arrival}") for task_id in itertools.count(): yield env.timeout(sampler.sample(config)) key = f"{arrival}-{task_id + 1}" env.process(pack(env, sampler, shop, arrival, key, task_id, policy)) def recall_orders(env, shop): """A recall at 31 minutes: every regular order in the shop, waiting or being packed, is interrupted.""" yield env.timeout(1860) for process in list(shop["running"].get("pack_order", [])): process.interrupt("recalled") def run(policy="resume", until=3600, factor=0.0): env = DynamicRealtimeEnvironment(factor=factor) env.registry.register_sim_parameter(PARAMS) env.setup_egress([ConsoleEgress()]) # Counts of preemptions and resumptions, and the mean wait and service, at the end env.setup_stats("Shop", "typical", interval=3600) shop = { # An express order takes the packer from a regular one being packed "packers": DynamicResource( env, "Shop", "packers", queue="priority", preempt=True ), "running": {}, # The key of the order each process packs, for the `preempted_by` of a record "keys": {}, } sampler = Sampler(seed=42) env.process(order_generator(env, sampler, shop, "orders", policy)) env.process(order_generator(env, sampler, shop, "express", policy)) env.process(recall_orders(env, shop)) try: env.run(until=until) finally: env.teardown() return env def outcomes(policy: str) -> dict: """Runs one hour and returns what preemption did to regular orders.""" readings = run(policy).stats.readings() name = "Shop.stats.tasks.pack_order.{}".format return { "preempted": readings[name("preempted")], "interrupted": readings.get(name("interrupted"), 0), "finished": readings[name("finished")], "wait_mean": readings[name("wait_mean")], "service_mean": readings[name("service_mean")], } if __name__ == "__main__": for policy in ("resume", "restart", "abandon"): r = outcomes(policy) print( f"{policy:<7}: {r['preempted']} preempted, {r['interrupted']} recalled, " f"{r['finished']} packed, " f"mean wait {r['wait_mean']:5.2f} s, mean packing {r['service_mean']:4.2f} s" ) ``` # Competing Resources The shop now picks each order from the shelves before packing it. One picker fetches the order in a second and carries it to the one packing bench, where packing takes 2 seconds on average. The picker could put the order down by the bench and go back for the next one, or stay with it until the bench is free, so the order is never left unattended. This page asks: **what does holding one resource while waiting for another cost?** - **Decision:** whether the picker stays with each order until the bench is free. - **Measures:** the mean wait for the picker and for the bench, and the share of time the picker is busy. - **Runs:** two runs of the hour, one for each way of working, each with the seed 42. - **Assumptions:** orders arrive at random, one every 2.5 seconds on average (24 a minute), picking always takes exactly one second, and packing times follow an exponential distribution. ## What You Will Learn This page shows how to: - give a task two resources, a picker and a packing bench; - keep the first resource for the next task with a handoff; - measure what holding one resource while waiting for another costs. ## What You Add This page adds a second resource, the `bench`, and a handoff. The picking task keeps the picker for the packing task, which gives the picker back once the order is on the bench. ______________________________________________________________________ ## Hold One While Waiting for Another In SimPy a process holds a resource from the moment its request is granted until it releases the resource. It can request a second resource while it holds the first, with nested `with` blocks. A desflow task does the same in two ways. It can list several resources, `resource: [picker, bench]`, and hold them all while it works. Or it can hand a unit to the next task of its flow with `keep`, as [Several Resources](https://jaehyeon.me/desflow/latest/user-guide/resources/several-resources/#how-to-use-it) describes. Save the files from [Full Files](#full-files) in one folder and run the commands there: ```yaml pick_order: service: picking resource: picker # The picker carries the order and stays with it until it is on the bench keep: [picker] payload: {event_type: order_picked} next: pack_order pack_order: service: packing resource: bench payload: {event_type: order_packed} ``` Remove `keep: [picker]` to run it without the handoff: `pick_order` then gives the picker back when it finishes, as every task does. ```python @app.task( service_id="picking", resource_id="picker", # The picker carries the order and stays with it until it is on the bench keep=["picker"] if keep else None, next="pack_order", ) def pick_order(task_id: int): return {"event_type": "order_picked"} @app.task(service_id="packing", resource_id="bench") def pack_order(task_id: int): return {"event_type": "order_packed"} ``` Without `keep`, `pick_order` gives the picker back when it finishes, as every task does. ```python def pick_order(env, sampler, shop, key, task_id, keep): status, finished, duration = step( env, sampler, key, "pick_order", task_id, "picking" ) status("queued") env.stats.task_queued("pick_order", task_id) picker = shop["picker"].request() yield picker status("started") env.stats.task_started("pick_order", task_id) yield env.timeout(duration()) finished({"event_type": "order_picked"}) env.stats.task_finished("pick_order", task_id) if not keep: shop["picker"].release(picker) picker = None # With keep, the picker carries the order and stays with it until it is on the bench yield from pack_order(env, sampler, shop, key, task_id, picker) def pack_order(env, sampler, shop, key, task_id, picker): status, finished, duration = step( env, sampler, key, "pack_order", task_id, "packing" ) status("queued") env.stats.task_queued("pack_order", task_id) with shop["bench"].request() as bench: yield bench status("started") env.stats.task_started("pack_order", task_id) if picker is not None: shop["picker"].release(picker) # the order is on the bench yield env.timeout(duration()) finished({"event_type": "order_packed"}) env.stats.task_finished("pack_order", task_id) env.stats.flow_finished("orders") ``` The picker's request is not in a `with` block, because the next process releases it. While the order waits for the bench it holds the picker: a **partial holding**. Nothing grants the picker and the bench together. Each is acquired in turn, and the units already held stay held while the task waits for the next. The picker's busy share includes that waiting time: ```yaml # The mean wait of each task and the picker's busy share, at the end stats: {level: typical, interval: 1 h} ``` ```python # The mean wait of each task and the picker's busy share, at the end .with_stats("typical", interval=3600) ``` ```python # The mean wait of each task and the picker's busy share, at the end env.setup_stats("Shop", "typical", interval=3600) ``` ______________________________________________________________________ ## One Order of Acquisition Two orders that each hold one resource and wait for the other wait for ever: a **deadlock**. If a picking task held the picker and waited for the bench while a wrapping task held the bench and waited for the picker, both could stop. SimPy runs such a model, and its run ends with no error when the tasks wait. desflow checks the order when the model loads. A model whose tasks acquire two resources in opposite orders still loads, and the run logs one WARNING that names both places. A `seize` counts as holding a resource until its `release`. A `keep` for a task that requests the same resource in a `wait` is refused, because that wait would queue behind the unit it keeps. Here every order goes picker first, then bench, so there is nothing to warn about. ______________________________________________________________________ ## What You Get and Why What does holding the picker while waiting for the bench cost? Each figure here is a mean from one run of the hour with the seed 42. - When the picker puts the order down and goes back, orders wait **0.35 seconds** for the picker and **8.43 seconds** for the bench, **8.78 seconds** in all. - When the picker stays with the order, the wait moves to the picker. Orders wait **14.23 seconds** for it and only **1.11 seconds** for the bench, **15.34 seconds** in all. The picker is then busy **85.2%** of the time instead of **40.4%**, most of it standing by the bench: Each tab prints both: the picker's busy share and the mean waits, first with the picker freed, then with it kept. The first run is the shop without the handoff. `competing_resources_free.yaml` is `competing_resources.yaml` without its `keep: [picker]` line: ```yaml tasks: pick_order: service: picking resource: picker payload: {event_type: order_picked} next: pack_order pack_order: service: packing resource: bench payload: {event_type: order_packed} ``` ```bash # Without the handoff: the mean waits and the pickers' utilisation desflow run competing_resources_free.yaml --stdout | grep -E '(pick_order|pack_order)\.wait_mean"|picker\.utilization_avg"' | tail -3 # With the handoff desflow run competing_resources.yaml --stdout | grep -E '(pick_order|pack_order)\.wait_mean"|picker\.utilization_avg"' | tail -3 ``` ```text {"stream_type":"telemetry","sim_ts":3600.0,"timestamp":"...","path_id":"Shop.stats.resources.picker.utilization_avg","value":40.38888888888891} {"stream_type":"telemetry","sim_ts":3600.0,"timestamp":"...","path_id":"Shop.stats.tasks.pick_order.wait_mean","value":0.34588107621855696} {"stream_type":"telemetry","sim_ts":3600.0,"timestamp":"...","path_id":"Shop.stats.tasks.pack_order.wait_mean","value":8.430633032800593} {"stream_type":"telemetry","sim_ts":3600.0,"timestamp":"...","path_id":"Shop.stats.resources.picker.utilization_avg","value":85.23420399919257} {"stream_type":"telemetry","sim_ts":3600.0,"timestamp":"...","path_id":"Shop.stats.tasks.pick_order.wait_mean","value":14.229028340474315} {"stream_type":"telemetry","sim_ts":3600.0,"timestamp":"...","path_id":"Shop.stats.tasks.pack_order.wait_mean","value":1.1103379257021557} ``` ```bash python competing_resources.py 2>/dev/null ``` ```text frees the picker: wait to pick 0.35 s, to pack 8.43 s, picker busy 40.4% keeps the picker: wait to pick 14.23 s, to pack 1.11 s, picker busy 85.2% ``` ```bash python competing_resources_low_level.py 2>/dev/null ``` ```text frees the picker: wait to pick 0.35 s, to pack 8.43 s, picker busy 40.4% keeps the picker: wait to pick 14.23 s, to pack 1.11 s, picker busy 85.2% ``` Each order brings 2 seconds of packing on average and arrives every 2.5 seconds on average, so the bench is busy 2 ÷ 2.5 = 80% of the time and the picker 1 ÷ 2.5 = 40%. The bench is the busier of the two, the [bottleneck](https://jaehyeon.me/desflow/latest/learn/concepts/queueing-basics/#flow-balance-and-the-bottleneck). When the picker waits at the bench, it spends its own time in the bench's queue. So the picker is busy longer than its work needs, and the next order waits for it. Releasing a resource as soon as it is no longer needed keeps the waits where the work is. [Queueing Basics](https://jaehyeon.me/desflow/latest/learn/concepts/queueing-basics/#utilisation) explains utilisation. [Several Resources](https://jaehyeon.me/desflow/latest/user-guide/resources/several-resources/#several-resources) describes several resources, handoffs and the order rule. ## Key Takeaways - A task that holds a resource while it waits for another keeps that resource busy without work. - The wait then moves to the resource that is held, and the next order waits for it. - Release a resource as soon as it is no longer needed, unless the work requires it to stay. ______________________________________________________________________ ## Full Files Full files ```yaml # The Competing Resources tutorial: an order keeps the picker until it is on the bench. # Run it with: desflow run competing_resources.yaml simulation: {sim_id: Shop, factor: 0, random_seed: 42} resources: picker: {current_cap: 1, max_cap: 2} bench: {current_cap: 1, max_cap: 2} services: picking: {dist: constant, value: 1 s} packing: {dist: exponential, rate: 0.5} arrivals: orders: {dist: exponential, rate: 0.4, spawn: pick_order} tasks: pick_order: service: picking resource: picker # The picker carries the order and stays with it until it is on the bench keep: [picker] payload: {event_type: order_picked} next: pack_order pack_order: service: packing resource: bench payload: {event_type: order_packed} # The mean wait of each task and the picker's busy share, at the end stats: {level: typical, interval: 1 h} egress: - {type: Console} run: {until: 1 h} ``` ```python """The Competing Resources tutorial: an order keeps the picker until it is on the bench. One picker, one packing bench, and an order every 2.5 seconds on average. Every record is printed to the terminal, and the script prints the waits and the picker's busy share with and without the handoff at the end. To see only those lines, run: python competing_resources.py 2>/dev/null """ import logging from desflow import ConsoleEgress, SimulationContext logging.basicConfig( level=logging.INFO, format="%(levelname)s [%(asctime)s] %(message)s" ) def shop(keep: bool = True) -> SimulationContext: """The shop; with `keep`, an order keeps the picker until it is on the bench.""" app = ( SimulationContext(sim_id="Shop", factor=0, random_seed=42) .add_resource("picker", current_cap=1, max_cap=2) .add_resource("bench", current_cap=1, max_cap=2) .add_service("picking", dist="constant", value=1) .add_service("packing", dist="exponential", rate=0.5) .add_arrival("orders", dist="exponential", rate=0.4) # The mean wait of each task and the picker's busy share, at the end .with_stats("typical", interval=3600) .add_egress(ConsoleEgress()) ) @app.task( service_id="picking", resource_id="picker", # The picker carries the order and stays with it until it is on the bench keep=["picker"] if keep else None, next="pack_order", ) def pick_order(task_id: int): return {"event_type": "order_picked"} @app.task(service_id="packing", resource_id="bench") def pack_order(task_id: int): return {"event_type": "order_packed"} @app.arrival_loop("orders") def order_generator(context: SimulationContext): task_id = 0 while True: order = yield context.wait_for_arrival("orders") context.spawn(pick_order(task_id, entity=order)) task_id += 1 return app def outcomes(keep: bool) -> dict: """Runs one hour and returns each task's mean wait and the picker's busy share.""" app = shop(keep) app.run(until="1 h") r = app.env.stats.readings() return { "pick_wait": r["Shop.stats.tasks.pick_order.wait_mean"], "pack_wait": r["Shop.stats.tasks.pack_order.wait_mean"], "picker_busy": r["Shop.stats.resources.picker.utilization_avg"], } if __name__ == "__main__": for keep in (False, True): r = outcomes(keep) label = "keeps the picker" if keep else "frees the picker" print( f"{label}: wait to pick {r['pick_wait']:6.2f} s, to pack " f"{r['pack_wait']:5.2f} s, picker busy {r['picker_busy']:4.1f}%" ) ``` ```python """The Competing Resources tutorial: an order keeps the picker until it is on the bench. One picker, one packing bench, and an order every 2.5 seconds on average. Every record is printed to the terminal, and the script prints the waits and the picker's busy share with and without the handoff at the end. To see only those lines, run: python competing_resources_low_level.py 2>/dev/null """ import itertools import logging from desflow import ( CapacityConfig, ConsoleEgress, DistributionConfig, DynamicRealtimeEnvironment, DynamicResource, Sampler, SimParameter, ) logging.basicConfig( level=logging.INFO, format="%(levelname)s [%(asctime)s] %(message)s" ) PARAMS = SimParameter( sim_id="Shop", arrival={"orders": DistributionConfig(dist="exponential", rate=0.4)}, service={ "picking": DistributionConfig(dist="constant", value=1), "packing": DistributionConfig(dist="exponential", rate=0.5), }, resources={ "picker": CapacityConfig(current_cap=1, max_cap=2), "bench": CapacityConfig(current_cap=1, max_cap=2), }, ) def step(env, sampler, key, task, task_id, service): """The publish and service-time helpers of one task instance.""" path_id = f"Shop.service.{service}" def status(state): value = { "path_id": path_id, "sim_id": "Shop", "service": service, "status": state, } env.publish_event(key, value, task=task, instance=task_id) def finished(value): env.publish_event(key, value, task=task, instance=task_id) return status, finished, lambda: sampler.sample(env.registry.get_config(path_id)) def pick_order(env, sampler, shop, key, task_id, keep): status, finished, duration = step( env, sampler, key, "pick_order", task_id, "picking" ) status("queued") env.stats.task_queued("pick_order", task_id) picker = shop["picker"].request() yield picker status("started") env.stats.task_started("pick_order", task_id) yield env.timeout(duration()) finished({"event_type": "order_picked"}) env.stats.task_finished("pick_order", task_id) if not keep: shop["picker"].release(picker) picker = None # With keep, the picker carries the order and stays with it until it is on the bench yield from pack_order(env, sampler, shop, key, task_id, picker) def pack_order(env, sampler, shop, key, task_id, picker): status, finished, duration = step( env, sampler, key, "pack_order", task_id, "packing" ) status("queued") env.stats.task_queued("pack_order", task_id) with shop["bench"].request() as bench: yield bench status("started") env.stats.task_started("pack_order", task_id) if picker is not None: shop["picker"].release(picker) # the order is on the bench yield env.timeout(duration()) finished({"event_type": "order_packed"}) env.stats.task_finished("pack_order", task_id) env.stats.flow_finished("orders") def order_generator(env, sampler, shop, keep): arrival = env.registry.get_config("Shop.arrival.orders") for task_id in itertools.count(): yield env.timeout(sampler.sample(arrival)) key = f"orders-{task_id + 1}" env.process(pick_order(env, sampler, shop, key, task_id, keep)) def run(keep=True, until=3600, factor=0.0): env = DynamicRealtimeEnvironment(factor=factor) env.registry.register_sim_parameter(PARAMS) env.setup_egress([ConsoleEgress()]) # The mean wait of each task and the picker's busy share, at the end env.setup_stats("Shop", "typical", interval=3600) shop = { "picker": DynamicResource(env, "Shop", "picker"), "bench": DynamicResource(env, "Shop", "bench"), } env.process(order_generator(env, Sampler(seed=42), shop, keep)) try: env.run(until=until) finally: env.teardown() return env def outcomes(keep: bool) -> dict: """Runs one hour and returns each task's mean wait and the picker's busy share.""" r = run(keep).stats.readings() return { "pick_wait": r["Shop.stats.tasks.pick_order.wait_mean"], "pack_wait": r["Shop.stats.tasks.pack_order.wait_mean"], "picker_busy": r["Shop.stats.resources.picker.utilization_avg"], } if __name__ == "__main__": for keep in (False, True): r = outcomes(keep) label = "keeps the picker" if keep else "frees the picker" print( f"{label}: wait to pick {r['pick_wait']:6.2f} s, to pack " f"{r['pack_wait']:5.2f} s, picker busy {r['picker_busy']:4.1f}%" ) ``` # Filtered Inventory The shop now sells shirts in three sizes: small, medium and large. Shirts of every size go on one shelf. A new shirt arrives every 10 seconds on average, and a new order also arrives every 10 seconds on average. Each order is for one shirt of a given size. A customer cancels an order not filled within 10 minutes. Half the orders are for medium shirts, but only 4 shirts in 10 are medium. This page asks: **which waiting order can use the shirt that arrives, and which orders go unfilled?** - **Decision:** whether the shop's mix of shirt sizes is right for its orders. - **Measures:** the orders filled and cancelled for each size, and the shirts left on the shelf. - **Runs:** one run of a working day of 8 hours, with the seed 42, covering only taking shirts from the shelf: packing is left out. - **Assumptions:** shirts and orders of each size arrive at random, each at a steady rate. ## What You Will Learn This page shows how to: - hold items of several kinds on one shelf, in a store; - take only an item that matches the order, with a filter; - see which orders go unfilled when one kind is short. ## What You Add This page adds a `shelf` store, and a `filter` on the order's `get` that picks a shirt of the order's size. The order task has no resource: it waits only for its shirt, with the [Patience](https://jaehyeon.me/desflow/latest/learn/shop-logic/patience/index.md) of 10 minutes covering that wait. ______________________________________________________________________ ## One Shelf of Items A store holds items, and each item is a value of its own. Here each shirt is a mapping such as `{size: M}`, and a restock task puts it on the shelf. [Stores and Containers](https://jaehyeon.me/desflow/latest/user-guide/model-parts/stores-and-containers/index.md) describes stores. Save the files from [Full Files](#full-files) in one folder and run the commands there: ```yaml stores: # Shirts of every size on one shelf, each item a mapping such as {size: M} shelf: {current_cap: 1000, max_cap: 1000} ``` ```python # Shirts of every size on one shelf, each item a mapping such as {"size": "M"} app.add_store("shelf", current_cap=1000, max_cap=1000) ``` ```python # Shirts of every size on one shelf, each item a mapping such as {"size": "M"} stores={"shelf": CapacityConfig(current_cap=1000, max_cap=1000)}, ``` The shirts and the orders arrive from six arrivals, one per size, each with a `size` attribute: ```yaml # A shirt every 10 seconds on average: 3 in 10 small, 4 medium, 3 large shirts_s: dist: exponential rate: 0.03 spawn: restock attributes: {size: S} shirts_m: dist: exponential rate: 0.04 spawn: restock attributes: {size: M} shirts_l: dist: exponential rate: 0.03 spawn: restock attributes: {size: L} # An order every 10 seconds on average: a quarter small, half medium, a quarter large orders_s: dist: exponential rate: 0.025 spawn: take_shirt attributes: {size: S} orders_m: dist: exponential rate: 0.05 spawn: take_shirt attributes: {size: M} orders_l: dist: exponential rate: 0.025 spawn: take_shirt attributes: {size: L} ``` ```python for size, rate in SHIRTS.items(): name = f"shirts_{size.lower()}" app.add_arrival(name, dist="exponential", rate=rate, attributes={"size": size}) for size, rate in ORDERS.items(): name = f"orders_{size.lower()}" app.add_arrival(name, dist="exponential", rate=rate, attributes={"size": size}) ``` `SHIRTS` and `ORDERS` map each size to its rate, as the full file shows. ```python arrival={ **{ f"shirts_{s.lower()}": DistributionConfig(dist="exponential", rate=r) for s, r in SHIRTS.items() }, **{ f"orders_{s.lower()}": DistributionConfig(dist="exponential", rate=r) for s, r in ORDERS.items() }, }, ``` `SHIRTS` and `ORDERS` map each size to its rate. Each arrival process passes its size to the task, as the full file shows. A shirt becomes an item of the shelf when its restock task puts it there. Each API builds the item from the shirt's size in its own way: ```yaml restock: # The shirt goes on the shelf, as a mapping with its size put: {store: shelf} payload: {} attributes: [size] ``` A `put` adds the task's finished payload as the item. The payload is empty, and `attributes: [size]` adds the arrival's `size` to it, so the item is `{size: M}`. ```python # The shirt goes on the shelf, as a mapping with its size @app.task(put={"store": "shelf"}) def restock(task_id: int, entity): return {"size": entity.attributes["size"]} ``` The item put on the shelf is the dict the function returns. ```python def restock(env, shelf, key, size, task_id): """The shirt goes on the shelf, as a mapping with its size.""" yield shelf.put({"size": size}) env.publish_event(key, {"size": size}, task="restock", instance=task_id) ``` The item is the argument of `shelf.put`. ______________________________________________________________________ ## Take the Right Item A plain `get` takes the oldest item, whatever it is. A `get` with a `filter` takes the oldest item the filter accepts and waits while none does. In SimPy this is a `FilterStore`, whose `get` takes a function of the item. In desflow the filter is a condition. In it, `item.` reads a field of the shirt on offer. The condition can also read every name that other conditions read, such as `attr.size` for the size the order is for: ```yaml take_shirt: # Takes the oldest shirt of the order's own size; waits while there is none get: {store: shelf, filter: item.size == attr.size} # A customer cancels an order not filled within 10 minutes patience: 10 min # Adds the shirt the get took to the finished event item_field: shirt payload: {event_type: order_filled} ``` `item_field: shirt` adds the shirt the get took to the finished event's payload under the key `shirt`, as `id_field` adds the task id under the key it names ([YAML Keys](https://jaehyeon.me/desflow/latest/reference/yaml-keys/#tasks) lists both). ```python @app.task( # Takes the oldest shirt of the order's own size; waits while there is none get={"store": "shelf", "filter": "item.size == attr.size"}, # A customer cancels an order not filled within 10 minutes patience="10 min", ) def take_shirt(task_id: int, item): # `item` is the shirt the get took return {"event_type": "order_filled", "shirt": item} ``` The builder also takes a function of the item, such as `"filter": lambda shirt: shirt["size"] == "M"`. ```python def take_shirt(env, shelf, key, size, task_id): arrival = key.rsplit("-", 1)[0] def publish(value): env.publish_event(key, value, task="take_shirt", instance=task_id) publish({"status": "queued"}) env.stats.flow_started(arrival) env.stats.task_queued("take_shirt", task_id) # Takes the oldest shirt of the order's own size; waits while there is none get = shelf.get(filter=lambda shirt: shirt["size"] == size) # A customer cancels an order not filled within 10 minutes result = yield get | env.timeout(PATIENCE) if get not in result: get.cancel() # out of the queue, so it never takes a shirt later publish({"status": "reneged"}) env.stats.task_reneged("take_shirt", task_id) env.stats.flow_ended(arrival) return publish({"status": "started"}) env.stats.task_started("take_shirt", task_id) publish({"event_type": "order_filled", "shirt": get.value}) env.stats.task_finished("take_shirt", task_id) env.stats.flow_finished(arrival) ``` `shelf.get(filter=...)` is SimPy's `FilterStore.get`. Cancelling a get that has not succeeded takes it out of the queue, so it never takes a shirt later. When a shirt arrives, it is offered to the waiting orders one at a time, oldest first, and the first order whose filter accepts it takes it. A medium order waiting at the front does not stop a small order behind it from taking a small shirt, as it would if all orders waited in one line for the next shirt. `patience` covers the wait for the get, as it covers a wait for a resource. A get that gives up takes nothing later: the shirt that would have filled it stays on the shelf for the next order. ______________________________________________________________________ ## What You Get and Why Which waiting order can use the shirt that arrives? The oldest order of the shirt's size, and no other. In one run of 8 hours with the seed 42, **199** orders are cancelled: **167** medium, 24 large and 8 small. Medium orders are half of all orders, but medium shirts are only 4 in 10: Each tab prints the counts: The blueprint publishes its statistics once, at the end of the 8 hours: ```yaml # The counts of each arrival's orders, published once, at the end of the 8 hours stats: {level: basic, interval: 8 h} ``` ```bash # Orders finished for each size, and the orders that gave up waiting desflow run filtered_inventory.yaml --stdout | grep -E 'orders_[sml]\.finished"|take_shirt\.reneged"' | tail -4 ``` ```text {"stream_type":"telemetry","sim_ts":28800.0,"timestamp":"...","path_id":"Shop.stats.tasks.take_shirt.reneged","value":199} {"stream_type":"telemetry","sim_ts":28800.0,"timestamp":"...","path_id":"Shop.stats.flows.orders_s.finished","value":711} {"stream_type":"telemetry","sim_ts":28800.0,"timestamp":"...","path_id":"Shop.stats.flows.orders_m.finished","value":1181} {"stream_type":"telemetry","sim_ts":28800.0,"timestamp":"...","path_id":"Shop.stats.flows.orders_l.finished","value":779} ``` Each `flows.orders_.finished` is the number of filled orders of that size. `tasks.take_shirt.reneged` counts the cancelled orders of every size together. A cancelled order leaves its flow without finishing it, so a size's cancelled orders are its flow's `started` minus `finished` minus `in_system`, the orders still waiting at the end. For medium orders that is 1,383 − 1,181 − 35 = 167, most of the 199 cancelled orders. The started and waiting counts of the medium orders, and the shirts left on the shelf, come from the same run: ```bash desflow run filtered_inventory.yaml --stdout | grep -E 'orders_m\.(started|in_system)"|shelf\.level"' ``` ```text {"stream_type":"telemetry","sim_ts":28800.0,"timestamp":"...","path_id":"Shop.stats.stores.shelf.level","value":197} {"stream_type":"telemetry","sim_ts":28800.0,"timestamp":"...","path_id":"Shop.stats.flows.orders_m.started","value":1383} {"stream_type":"telemetry","sim_ts":28800.0,"timestamp":"...","path_id":"Shop.stats.flows.orders_m.in_system","value":35} ``` ```python # The counts of each arrival's orders, published once, at the end of the 8 hours app.with_stats("basic", interval=8 * 3600) ``` The script reads the same statistics with `app.env.stats.readings()`. A cancelled order is the flow's `started` minus `finished` minus `in_system`: ```bash python filtered_inventory.py 2>/dev/null ``` ```text size S: 719 started, 711 filled, 0 waiting, 8 cancelled size M: 1383 started, 1181 filled, 35 waiting, 167 cancelled size L: 803 started, 779 filled, 0 waiting, 24 cancelled shirts left on the shelf: 197 ``` ```python # The counts of each arrival's orders, published once, at the end of the 8 hours env.setup_stats("Shop", "basic", interval=8 * 3600) ``` A low-level model reports its own events to the statistics, as `take_shirt` does with `env.stats.flow_started`, `task_reneged`, `flow_ended` and `flow_finished`. The script then reads `run().stats.readings()`: ```bash python filtered_inventory_low_level.py 2>/dev/null ``` ```text size S: 719 started, 711 filled, 0 waiting, 8 cancelled size M: 1383 started, 1181 filled, 35 waiting, 167 cancelled size L: 803 started, 779 filled, 0 waiting, 24 cancelled shirts left on the shelf: 197 ``` A filtered store works like one shelf with a separate queue for each kind of item. Orders and shirts of each size arrive at their own rates, on average: | Size | An order arrives | A shirt arrives | | ------ | ---------------------------------------------- | --------------------------------------------- | | Small | every 40 seconds (1.5 a minute, `rate: 0.025`) | every 33 seconds (1.8 a minute, `rate: 0.03`) | | Medium | every 20 seconds (3 a minute, `rate: 0.05`) | every 25 seconds (2.4 a minute, `rate: 0.04`) | | Large | every 40 seconds (1.5 a minute, `rate: 0.025`) | every 33 seconds (1.8 a minute, `rate: 0.03`) | Medium orders outnumber medium shirts all day: they ask for 0.05 shirts a second and get 0.04, a [utilisation](https://jaehyeon.me/desflow/latest/learn/concepts/queueing-basics/#utilisation) of 1.25. So their queue would grow without end if customers did not cancel after 10 minutes. There are more small and large shirts than orders of those sizes, so nearly every small and large order is filled before its customer cancels. The few that cancel (8 small and 24 large in this run) are orders that waited for a shirt of their size for more than 10 minutes, because shirts arrive at random times. The shirts left over, 197 at the end of the run, wait on the shelf, which has room for 1,000. The mix of sizes is therefore not right for the orders: the shop should stock more medium shirts, and fewer small and large ones, until medium shirts are as large a share of the deliveries as medium orders are of the orders. [SimPy and desflow](https://jaehyeon.me/desflow/latest/simpy/#containers-and-stores) compares stores and containers with SimPy's. [Stores and Containers](https://jaehyeon.me/desflow/latest/user-guide/model-parts/stores-and-containers/#take-and-add) describes filters and cancelled gets. ## Key Takeaways - A filtered store works like one shelf with a separate queue for each kind of item. - A kind whose orders outnumber its items has a queue that grows, even when the shelf holds other items. - Patience on the wait ends that growth, at the cost of cancelled orders. ______________________________________________________________________ ## Full Files Full files ```yaml # The Filtered Inventory tutorial: each order waits for a shirt of its own size. # Run it with: desflow run filtered_inventory.yaml simulation: {sim_id: Shop, factor: 0, random_seed: 42} stores: # Shirts of every size on one shelf, each item a mapping such as {size: M} shelf: {current_cap: 1000, max_cap: 1000} arrivals: # A shirt every 10 seconds on average: 3 in 10 small, 4 medium, 3 large shirts_s: dist: exponential rate: 0.03 spawn: restock attributes: {size: S} shirts_m: dist: exponential rate: 0.04 spawn: restock attributes: {size: M} shirts_l: dist: exponential rate: 0.03 spawn: restock attributes: {size: L} # An order every 10 seconds on average: a quarter small, half medium, a quarter large orders_s: dist: exponential rate: 0.025 spawn: take_shirt attributes: {size: S} orders_m: dist: exponential rate: 0.05 spawn: take_shirt attributes: {size: M} orders_l: dist: exponential rate: 0.025 spawn: take_shirt attributes: {size: L} tasks: restock: # The shirt goes on the shelf, as a mapping with its size put: {store: shelf} payload: {} attributes: [size] take_shirt: # Takes the oldest shirt of the order's own size; waits while there is none get: {store: shelf, filter: item.size == attr.size} # A customer cancels an order not filled within 10 minutes patience: 10 min # Adds the shirt the get took to the finished event item_field: shirt payload: {event_type: order_filled} # The counts of each arrival's orders, published once, at the end of the 8 hours stats: {level: basic, interval: 8 h} egress: - {type: Console} run: {until: 8 h} ``` ```python """The Filtered Inventory tutorial: each order waits for a shirt of its own size. Shirts of three sizes arrive on one shelf, and orders of three sizes take them. Every record is printed to the terminal. The script then prints, for each size, how many orders started, were filled, were still waiting and were cancelled, and the shirts left on the shelf. To see only those lines, run: python filtered_inventory.py 2>/dev/null """ import logging from desflow import ConsoleEgress, SimulationContext logging.basicConfig( level=logging.INFO, format="%(levelname)s [%(asctime)s] %(message)s" ) # A shirt every 10 seconds on average: 3 in 10 small, 4 medium, 3 large SHIRTS = {"S": 0.03, "M": 0.04, "L": 0.03} # An order every 10 seconds on average: a quarter small, half medium, a quarter large ORDERS = {"S": 0.025, "M": 0.05, "L": 0.025} def shop() -> SimulationContext: """The shop with one shelf of shirts and orders of three sizes.""" app = SimulationContext(sim_id="Shop", factor=0, random_seed=42).add_egress( ConsoleEgress() ) # The counts of each arrival's orders, published once, at the end of the 8 hours app.with_stats("basic", interval=8 * 3600) # Shirts of every size on one shelf, each item a mapping such as {"size": "M"} app.add_store("shelf", current_cap=1000, max_cap=1000) for size, rate in SHIRTS.items(): name = f"shirts_{size.lower()}" app.add_arrival(name, dist="exponential", rate=rate, attributes={"size": size}) for size, rate in ORDERS.items(): name = f"orders_{size.lower()}" app.add_arrival(name, dist="exponential", rate=rate, attributes={"size": size}) # The shirt goes on the shelf, as a mapping with its size @app.task(put={"store": "shelf"}) def restock(task_id: int, entity): return {"size": entity.attributes["size"]} @app.task( # Takes the oldest shirt of the order's own size; waits while there is none get={"store": "shelf", "filter": "item.size == attr.size"}, # A customer cancels an order not filled within 10 minutes patience="10 min", ) def take_shirt(task_id: int, item): # `item` is the shirt the get took return {"event_type": "order_filled", "shirt": item} def spawn(arrival: str, task, name: str): def loop(context: SimulationContext): while True: entity = yield context.wait_for_arrival(arrival) context.spawn(task(context.next_instance(name), entity=entity)) app.arrival_loop(arrival)(loop) for size in SHIRTS: spawn(f"shirts_{size.lower()}", restock, "restock") for size in ORDERS: spawn(f"orders_{size.lower()}", take_shirt, "take_shirt") return app def outcomes() -> dict: """Runs eight hours; returns each size's order counts and the shirts left.""" app = shop() app.run(until="8 h") readings = app.env.stats.readings() result: dict = {} for size in ORDERS: flow = f"Shop.stats.flows.orders_{size.lower()}" started = readings[f"{flow}.started"] filled = readings[f"{flow}.finished"] waiting = readings[f"{flow}.in_system"] # A cancelled order leaves its flow without finishing it result[size] = (started, filled, waiting, started - filled - waiting) result["left"] = readings["Shop.stats.stores.shelf.level"] return result if __name__ == "__main__": result = outcomes() for size in ORDERS: started, filled, waiting, cancelled = result[size] print( f"size {size}: {started:4} started, {filled:4} filled, " f"{waiting:2} waiting, {cancelled:3} cancelled" ) print(f"shirts left on the shelf: {result['left']}") ``` ```python """The Filtered Inventory tutorial: each order waits for a shirt of its own size. Shirts of three sizes arrive on one shelf, and orders of three sizes take them. Every record is printed to the terminal. The script then prints, for each size, how many orders started, were filled, were still waiting and were cancelled, and the shirts left on the shelf. To see only those lines, run: python filtered_inventory_low_level.py 2>/dev/null """ import itertools import logging from desflow import ( CapacityConfig, ConsoleEgress, DistributionConfig, DynamicRealtimeEnvironment, DynamicStore, Sampler, SimParameter, ) logging.basicConfig( level=logging.INFO, format="%(levelname)s [%(asctime)s] %(message)s" ) # A shirt every 10 seconds on average: 3 in 10 small, 4 medium, 3 large SHIRTS = {"S": 0.03, "M": 0.04, "L": 0.03} # An order every 10 seconds on average: a quarter small, half medium, a quarter large ORDERS = {"S": 0.025, "M": 0.05, "L": 0.025} PATIENCE = 600 # a customer cancels an order not filled within 10 minutes PARAMS = SimParameter( sim_id="Shop", arrival={ **{ f"shirts_{s.lower()}": DistributionConfig(dist="exponential", rate=r) for s, r in SHIRTS.items() }, **{ f"orders_{s.lower()}": DistributionConfig(dist="exponential", rate=r) for s, r in ORDERS.items() }, }, # Shirts of every size on one shelf, each item a mapping such as {"size": "M"} stores={"shelf": CapacityConfig(current_cap=1000, max_cap=1000)}, ) def restock(env, shelf, key, size, task_id): """The shirt goes on the shelf, as a mapping with its size.""" yield shelf.put({"size": size}) env.publish_event(key, {"size": size}, task="restock", instance=task_id) def take_shirt(env, shelf, key, size, task_id): arrival = key.rsplit("-", 1)[0] def publish(value): env.publish_event(key, value, task="take_shirt", instance=task_id) publish({"status": "queued"}) env.stats.flow_started(arrival) env.stats.task_queued("take_shirt", task_id) # Takes the oldest shirt of the order's own size; waits while there is none get = shelf.get(filter=lambda shirt: shirt["size"] == size) # A customer cancels an order not filled within 10 minutes result = yield get | env.timeout(PATIENCE) if get not in result: get.cancel() # out of the queue, so it never takes a shirt later publish({"status": "reneged"}) env.stats.task_reneged("take_shirt", task_id) env.stats.flow_ended(arrival) return publish({"status": "started"}) env.stats.task_started("take_shirt", task_id) publish({"event_type": "order_filled", "shirt": get.value}) env.stats.task_finished("take_shirt", task_id) env.stats.flow_finished(arrival) def generator(env, sampler, shelf, arrival, size, task, ids): gap = env.registry.get_config(f"Shop.arrival.{arrival}") for number in itertools.count(1): yield env.timeout(sampler.sample(gap)) env.process(task(env, shelf, f"{arrival}-{number}", size, next(ids))) def run(until=8 * 3600, factor=0.0): env = DynamicRealtimeEnvironment(factor=factor) env.registry.register_sim_parameter(PARAMS) env.setup_egress([ConsoleEgress()]) # The counts of each arrival's orders, published once, at the end of the 8 hours env.setup_stats("Shop", "basic", interval=8 * 3600) shelf = DynamicStore(env, "Shop", "shelf") sampler = Sampler(seed=42) restocks, takes = itertools.count(), itertools.count() for size in SHIRTS: arrival = f"shirts_{size.lower()}" env.process(generator(env, sampler, shelf, arrival, size, restock, restocks)) for size in ORDERS: arrival = f"orders_{size.lower()}" env.process(generator(env, sampler, shelf, arrival, size, take_shirt, takes)) try: env.run(until=until) finally: env.teardown() return env def outcomes() -> dict: """Runs eight hours; returns each size's order counts and the shirts left.""" readings = run().stats.readings() result: dict = {} for size in ORDERS: flow = f"Shop.stats.flows.orders_{size.lower()}" started = readings[f"{flow}.started"] filled = readings[f"{flow}.finished"] waiting = readings[f"{flow}.in_system"] # A cancelled order leaves its flow without finishing it result[size] = (started, filled, waiting, started - filled - waiting) result["left"] = readings["Shop.stats.stores.shelf.level"] return result if __name__ == "__main__": result = outcomes() for size in ORDERS: started, filled, waiting, cancelled = result[size] print( f"size {size}: {started:4} started, {filled:4} filled, " f"{waiting:2} waiting, {cancelled:3} cancelled" ) print(f"shirts left on the shelf: {result['left']}") ``` # Trusting Results [Measuring a Run](https://jaehyeon.me/desflow/latest/learn/first-model/measuring-a-run/index.md) read five numbers from one run of the busy hour. The run started with an empty shop: no orders waiting and every packer free. A real shop at that hour is never empty. The first orders of the run find free packers, so they wait less than orders in the real shop would. This page asks: **is one run enough?** - **Decision:** how much of the start to leave out, and how many runs give an answer precise enough to act on. - **Measures:** the mean wait and the packers' [utilisation](https://jaehyeon.me/desflow/latest/learn/concepts/queueing-basics/#utilisation), and how much each varies from run to run. - **Runs:** the busy hour with 3 packers, run once with the seed 42, then 40 times with seeds spawned from 42, then 5 times after each of three warm-ups. - **Assumptions:** those of Measuring a Run: orders at random at 1.8 a second, and the 40 packing times measured at the bench. ## What You Will Learn This page shows how to: - leave a warm-up out of a run's statistics; - run replications with spawned seeds and read the mean with its interval; - choose a warm-up and a number of replications. ## What You Add This page adds a `warmup` to the run, then [replications](https://jaehyeon.me/desflow/latest/learn/concepts/output-analysis/#replications): the same run repeated with other seeds. The model simulates the same busy hour as Measuring a Run. ______________________________________________________________________ ## Plot the Start Some runs have a natural start and end, such as a shop that opens empty at 9:00 and closes at 17:00. These are **[terminating](https://jaehyeon.me/desflow/latest/learn/concepts/output-analysis/#terminating-or-steady-state)** runs, and the empty start is part of what they measure. Other runs stand for a system that keeps going, such as the shop in the middle of its busy hour. These are **steady-state** runs, and their empty start is a distortion called **[initialisation bias](https://jaehyeon.me/desflow/latest/learn/concepts/output-analysis/#one-run-starts-empty)**. The busy hour is a steady-state run. To see how long the distortion lasts, plot an output over time and look for where it stops trending. Save the files from [Full Files](#full-files) in one folder and run the commands there. Publish the statistics every 10 seconds: `wait_mean` is then the mean wait of every order so far, and `queue_length` is the queue at that moment. ```yaml # Every 10 seconds, wait_mean is the mean wait so far: plot it against sim_ts stats: {level: typical, interval: 10} egress: - {type: Console} ``` `WARMUP=0` keeps the first minutes, and `--until` stops the run at 15 minutes. `head -4` keeps the first four lines, the queue and the mean wait at 10 and 20 seconds: ```bash WARMUP=0 desflow run trusting_results.yaml --until "15 min" --stdout | grep -E 'packers\.queue_length"|pack_order\.wait_mean"' | head -4 ``` ```text {"stream_type":"telemetry","sim_ts":10.0,"timestamp":"...","path_id":"Shop.stats.resources.packers.queue_length","value":0} {"stream_type":"telemetry","sim_ts":10.0,"timestamp":"...","path_id":"Shop.stats.tasks.pack_order.wait_mean","value":0.058519544055964254} {"stream_type":"telemetry","sim_ts":20.0,"timestamp":"...","path_id":"Shop.stats.resources.packers.queue_length","value":0} {"stream_type":"telemetry","sim_ts":20.0,"timestamp":"...","path_id":"Shop.stats.tasks.pack_order.wait_mean","value":0.03277094467133998} ``` ```python # Every 10 seconds, wait_mean is the mean wait so far: plot it against sim_ts .with_stats("typical", interval=10) .add_egress(ConsoleEgress()) ``` The script runs the first 15 minutes without a warm-up when it is given the argument `start`. `head -4` keeps the first four lines, the queue and the mean wait at 10 and 20 seconds: ```bash python trusting_results.py start 2>&1 | grep -E "packers\.queue_length'|pack_order\.wait_mean'" | head -4 ``` ```text [TEL] {'sim_ts': 10.0, 'timestamp': '...', 'path_id': 'Shop.stats.resources.packers.queue_length', 'value': 0} [TEL] {'sim_ts': 10.0, 'timestamp': '...', 'path_id': 'Shop.stats.tasks.pack_order.wait_mean', 'value': 0.058519544055964254} [TEL] {'sim_ts': 20.0, 'timestamp': '...', 'path_id': 'Shop.stats.resources.packers.queue_length', 'value': 0} [TEL] {'sim_ts': 20.0, 'timestamp': '...', 'path_id': 'Shop.stats.tasks.pack_order.wait_mean', 'value': 0.03277094467133998} ``` ```python # Every 10 seconds, wait_mean is the mean wait so far: plot it against sim_ts env.setup_stats("Shop", "typical", interval=10) # The warm-up is set with the sinks: no sink receives a record stamped before it # ends, and the statistics start again from zero when it ends env.setup_egress([ConsoleEgress()], warmup=warmup) ``` The script runs the first 15 minutes without a warm-up when it is given the argument `start`. `head -4` keeps the first four lines, the queue and the mean wait at 10 and 20 seconds: ```bash python trusting_results_low_level.py start 2>&1 | grep -E "packers\.queue_length'|pack_order\.wait_mean'" | head -4 ``` ```text [TEL] {'sim_ts': 10.0, 'timestamp': '...', 'path_id': 'Shop.stats.resources.packers.queue_length', 'value': 0} [TEL] {'sim_ts': 10.0, 'timestamp': '...', 'path_id': 'Shop.stats.tasks.pack_order.wait_mean', 'value': 0.058519544055964254} [TEL] {'sim_ts': 20.0, 'timestamp': '...', 'path_id': 'Shop.stats.resources.packers.queue_length', 'value': 0} [TEL] {'sim_ts': 20.0, 'timestamp': '...', 'path_id': 'Shop.stats.tasks.pack_order.wait_mean', 'value': 0.03277094467133998} ``` Without `head -4`, each tab prints the two values every 10 seconds of the first 15 minutes, 90 lines for each path. Plot the `value` of the two paths against `sim_ts`. Some of the values: | `sim_ts` (s) | Queue | Mean wait so far (s) | | ------------ | ----- | -------------------- | | 10 | 0 | 0.06 | | 30 | 0 | 0.21 | | 60 | 2 | 0.65 | | 90 | 1 | 0.60 | | 120 | 0 | 0.59 | | 300 | 0 | 1.31 | | 600 | 10 | 2.60 | | 900 | 0 | 2.35 | The plot of all 90 readings: The queue is empty for the first 40 seconds and then moves between 0 and 17 orders. The mean wait so far climbs for about a minute, because the first orders found free packers, and stays near 0.6 seconds until two minutes. After that it climbs in steps, each after a burst of orders, to about 2.5 seconds at eight minutes, and then moves up and down with no trend. The plot shows one seed only, and another seed could climb for longer. So the plot alone cannot settle the [warm-up](https://jaehyeon.me/desflow/latest/learn/concepts/output-analysis/#one-run-starts-empty). It suggests three candidates: - 1 minute, when the first orders have queued and the first climb of the mean wait has ended; - 2 minutes, twice that, to cover the first climb with a margin; - 4 minutes, twice that again, to see whether a longer warm-up still moves the mean. The next section sets 2 minutes. [Compare Warm-ups](#compare-warm-ups), after the replications, checks the three candidates with five seeds. ______________________________________________________________________ ## Leave Out the Start A `warmup` time leaves the start out of everything the run reports: ```yaml # Records and statistics start after the first 2 minutes; 0 keeps everything warmup: ${WARMUP:-2 min} ``` ```python # Records and statistics start after the first 2 minutes; None keeps everything SimulationContext(sim_id="Shop", factor=0, random_seed=42, warmup=warmup) ``` ```python # Records and statistics start after the first 2 minutes; None keeps everything WARMUP = 120.0 # seconds, passed to setup_egress in run below ``` In the low-level API the warm-up is an argument of `env.setup_egress`, as the `plot` step above shows, because the sinks are what leave the records out. A run has one warm-up, in simulation time. Every sink leaves out the records and telemetry stamped before the warm-up ends. The built-in statistics start again from zero when it ends, so they describe only the rest of the run. An order that queued before the warm-up ended and started after it counts with its whole wait. The warm-up differs from `go_live_at`, a setting of `simulation` that names the time when records stop counting as history and count as live, so that one sink can take the earlier records and another the later ones. `go_live_at` drops nothing. [Time and Pacing](https://jaehyeon.me/desflow/latest/user-guide/time-and-pacing/index.md) compares the two. Run the hour without and with the warm-up. Each tab prints the mean wait without it, then with it: `WARMUP=0` runs the blueprint without the warm-up. ```bash # The mean wait without the warm-up, then with it WARMUP=0 desflow run trusting_results.yaml --stdout | grep -E 'pack_order\.wait_mean"' | tail -1 desflow run trusting_results.yaml --stdout | grep -E 'pack_order\.wait_mean"' | tail -1 ``` ```text {"stream_type":"telemetry","sim_ts":3600.0,"timestamp":"...","path_id":"Shop.stats.tasks.pack_order.wait_mean","value":2.0065204395584315} {"stream_type":"telemetry","sim_ts":3600.0,"timestamp":"...","path_id":"Shop.stats.tasks.pack_order.wait_mean","value":2.050372976906103} ``` ```bash python trusting_results.py 2>/dev/null | grep -E '^(without|with a)' ``` ```text without a warm-up: mean wait 2.007 s with a 2 min warm-up: mean wait 2.050 s ``` ```bash python trusting_results_low_level.py 2>/dev/null | grep -E '^(without|with a)' ``` ```text without a warm-up: mean wait 2.007 s with a 2 min warm-up: mean wait 2.050 s ``` ______________________________________________________________________ ## Run It With Other Seeds The run in [Leave Out the Start](#leave-out-the-start) used one seed, 42. Another seed draws other arrival gaps and packing times, and gives another mean wait. One run cannot show how far apart those answers are. Within one run, an order's wait depends on the orders queued ahead of it, so the waits are not independent samples. **Replications** show it: the same run repeated with other seeds, each giving one independent value of every statistic. Run the busy hour 40 times. The 40 seeds are spawned from the seed 42, so every run of the command uses the same 40 seeds. Each replication leaves out the same 2-minute warm-up: ```bash # 5, 10, 20 and 40 runs: the mean wait and the packers' utilisation, each with its interval for n in 5 10 20 40; do desflow run trusting_results.yaml --replications $n --measure tasks.pack_order.wait_mean --measure resources.packers.utilization_avg 2>/dev/null | grep -E '^(tasks|resources)' done ``` ```text tasks.pack_order.wait_mean 5 2.006 0.4289 resources.packers.utilization_avg 5 89.6 1.779 tasks.pack_order.wait_mean 10 2.147 0.3011 resources.packers.utilization_avg 10 90 1.084 tasks.pack_order.wait_mean 20 2.151 0.1518 resources.packers.utilization_avg 20 89.99 0.6034 tasks.pack_order.wait_mean 40 2.1 0.1004 resources.packers.utilization_avg 40 89.82 0.3858 ``` ```python MEASURES = ["tasks.pack_order.wait_mean", "resources.packers.utilization_avg"] def replications(n=40): """Runs the busy hour n times, each after the warm-up, with seeds spawned from 42.""" return replicate(shop, n, seed=42, until="1 h", measures=MEASURES) ``` ```bash python trusting_results.py 2>/dev/null | grep ' runs: ' ``` ```text tasks.pack_order.wait_mean, 5 runs: 2.01 ± 0.43 (21.4%) tasks.pack_order.wait_mean, 10 runs: 2.15 ± 0.30 (14.0%) tasks.pack_order.wait_mean, 20 runs: 2.15 ± 0.15 (7.1%) tasks.pack_order.wait_mean, 40 runs: 2.10 ± 0.10 (4.8%) resources.packers.utilization_avg, 5 runs: 89.60 ± 1.78 (2.0%) resources.packers.utilization_avg, 10 runs: 90.00 ± 1.08 (1.2%) resources.packers.utilization_avg, 20 runs: 89.99 ± 0.60 (0.7%) resources.packers.utilization_avg, 40 runs: 89.82 ± 0.39 (0.4%) ``` ```python MEASURES = ["tasks.pack_order.wait_mean", "resources.packers.utilization_avg"] def model(env, sampler): """The busy hour in a given environment: replicate sets the statistics.""" env.registry.register_sim_parameter(PARAMS) packers = DynamicResource(env, "Shop", "packers") env.process(order_generator(env, sampler, packers)) def replications(n=40): """Runs the busy hour n times, each after the warm-up, with seeds spawned from 42.""" shop = LowLevelModel(model, sim_id="Shop") return replicate(shop, n, seed=42, until=3600, warmup=WARMUP, measures=MEASURES) ``` ```bash python trusting_results_low_level.py 2>/dev/null | grep ' runs: ' ``` It prints the same eight lines as the Builder script. `LowLevelModel` names the function that builds the model in an environment it is given, and the warm-up is an argument of `replicate`, because a replication has no sinks. Each replication runs unpaced with no sinks and reads the built-in statistics at its end. [Replications](https://jaehyeon.me/desflow/latest/user-guide/results/replications/index.md) describes every option. The mean of the 40 values is the estimate. Its **[95% interval](https://jaehyeon.me/desflow/latest/learn/concepts/output-analysis/#interval-and-half-width)** says how far off it may be: with 95% confidence, the true mean lies within the estimate plus or minus the **half-width**. The seeds are spawned in order, so the first 10 of the 40 replications are the 10 a run with `--replications 10` makes. Each tab prints the estimate after the first 5, 10 and 20 replications and after all 40, which the table gives with the half-width as a share of the mean: | Replications | Mean wait (s) | Half-width (s) | Wait half-width share | Utilisation (%) | Half-width (%) | Utilisation half-width share | | ------------ | ------------- | -------------- | --------------------- | --------------- | -------------- | ---------------------------- | | 5 | 2.01 | 0.43 | 21.4% | 89.60 | 1.78 | 2.0% | | 10 | 2.15 | 0.30 | 14.0% | 90.00 | 1.08 | 1.2% | | 20 | 2.15 | 0.15 | 7.1% | 89.99 | 0.60 | 0.7% | | 40 | 2.10 | 0.10 | 4.8% | 89.82 | 0.39 | 0.4% | The mean waits of the 40 replications range from 1.52 to 3.05 seconds. The [single run with the seed 42](https://jaehyeon.me/desflow/latest/learn/concepts/output-analysis/#busy-hour-figures) measured 2.01 seconds, inside that range and close to the mean of the 40. ______________________________________________________________________ ## Choose the Precision How many replications are enough depends on the decision, not on a fixed number such as 30. Choose the precision each output needs. Here it is a half-width within 10% of the mean. [Utilisation](https://jaehyeon.me/desflow/latest/learn/concepts/queueing-basics/#utilisation) meets it with 5 replications. Of the replication counts in the table of [Run It With Other Seeds](#run-it-with-other-seeds), the mean wait first meets it at 20, because waits vary far more from run to run than how busy the packers are. Each output therefore needs its own number of replications, and the study needs enough replications for the least precise output the decision uses. The half-width shrinks in proportion to 1 ÷ √n, so a half-width k times smaller needs about k² times as many replications. 10 replications gave 14.0%, so 10% needs about 10 × (14.0 ÷ 10)² ≈ 20. That figure is a guide, not a promise: the half-width is itself an estimate, and 20 replications gave 7.1%. Add replications, then read the half-width again. The precision also depends on the confidence level, which is 95% unless you choose another. `--level 0.9` gives 90% intervals from the same 40 runs (`level=0.9` in `replicate`, for a builder or a low-level model): ```bash # 40 runs with a 90% interval desflow run trusting_results.yaml --replications 40 --measure tasks.pack_order.wait_mean --level 0.9 ``` ```text measure n mean half-width (90%) tasks.pack_order.wait_mean 40 2.1 0.08363 ``` The run also prints its seeds and how to repeat one replication. The half-width falls from 0.10 to 0.084 seconds, 4.0% of the mean, with no extra run. A 90% interval misses the true mean more often, 1 study in 10 instead of 1 in 20, so choose the level with the precision, before the runs. ______________________________________________________________________ ## Compare Warm-ups One seed gives one path through the hour. Run five replications after each candidate warm-up, with the same five seeds spawned from 42, and compare the mean waits. Five replications are few, and the mean wait needs 20 for 10% precision. The comparison does not need a precise mean: it asks only whether a longer warm-up moves the mean by a visible amount. Each candidate runs the same five seeds, so a difference between candidates comes from the warm-up and not from the seeds: ```bash # 5 runs with each candidate warm-up for w in "1 min" "2 min" "4 min"; do WARMUP="$w" desflow run trusting_results.yaml --replications 5 --measure tasks.pack_order.wait_mean 2>/dev/null | grep '^tasks' done ``` ```text tasks.pack_order.wait_mean 5 2.01 0.4146 tasks.pack_order.wait_mean 5 2.006 0.4289 tasks.pack_order.wait_mean 5 2.005 0.4918 ``` ```python def warmups(n=5) -> dict: """The mean wait of n runs after each candidate warm-up, with seeds spawned from 42.""" wait = ["tasks.pack_order.wait_mean"] return { warmup: replicate(shop, n, seed=42, until="1 h", warmup=warmup, measures=wait) for warmup in ("1 min", "2 min", "4 min") } ``` ```bash python trusting_results.py 2>/dev/null | grep '^warm-up' ``` ```text warm-up 1 min: mean wait 2.010 ± 0.41 s warm-up 2 min: mean wait 2.006 ± 0.43 s warm-up 4 min: mean wait 2.005 ± 0.49 s ``` ```python def warmups(n=5) -> dict: """The mean wait of n runs after each candidate warm-up, with seeds spawned from 42.""" shop = LowLevelModel(model, sim_id="Shop") wait = ["tasks.pack_order.wait_mean"] return { warmup: replicate(shop, n, seed=42, until=3600, warmup=warmup, measures=wait) for warmup in (60, WARMUP, 240) } ``` ```bash python trusting_results_low_level.py 2>/dev/null | grep '^warm-up' ``` ```text warm-up 60 s: mean wait 2.010 ± 0.41 s warm-up 120 s: mean wait 2.006 ± 0.43 s warm-up 240 s: mean wait 2.005 ± 0.49 s ``` `model` is the function from [Run It With Other Seeds](#run-it-with-other-seeds) above. The mean wait over the five replications, in seconds, with its 95% half-width: | Warm-up | Mean wait (s) | | --------- | ------------- | | 1 minute | 2.010 ± 0.41 | | 2 minutes | 2.006 ± 0.43 | | 4 minutes | 2.005 ± 0.49 | [Output Analysis](https://jaehyeon.me/desflow/latest/learn/concepts/output-analysis/#one-run-starts-empty) keeps the shortest candidate that passes this comparison and covers the first climb in the plot with a margin. After 1 minute, the longer warm-ups move the mean by 0.004 and 0.005 seconds, under 0.3% of the mean wait, so no candidate shows a visible change in the mean. The first climb in the plot ends at about a minute, which 1 minute only just covers, so the warm-up is **2 minutes**, which covers the climb with a minute to spare. The plotted wait goes on rising in steps after 2 minutes, to about 2.5 seconds at 8 minutes. A 4-minute warm-up, which leaves out half of that rise, moves the mean by only 0.001 seconds from the 2-minute one, so the rise changes the estimate little. This comparison does not show whether the rise is part of the start-up or ordinary variation, because both warm-ups keep the part after 4 minutes. ______________________________________________________________________ ## What You Get and Why Is one run enough? No, because one run's answer depends on its seed. The 40 replications range from 1.52 to 3.05 seconds, so a run with another seed could have given a very different answer, even though the run with the seed 42 measured 2.01 seconds, close to their mean. Over 40 replications the mean wait is **2.10 ± 0.10 seconds** with 95% confidence, within the chosen 10% precision, and the packers are busy **89.82 ± 0.39%** of the time. The empty start is not the problem. The warm-up is **2 minutes**: 1 minute passes the comparison over five seeds but only just covers the climb in the plot, and 2 minutes covers it with a margin. In the run with the seed 42, a 2-minute warm-up changes the mean wait only from 2.007 to 2.050 seconds. The shop fills within a minute or two, and those minutes are a small part of one hour. A shorter run, or a start further from the usual state, such as a shop that opens with a backlog of orders, needs the warm-up much more. Initialisation bias ([Output Analysis](https://jaehyeon.me/desflow/latest/learn/concepts/output-analysis/#one-run-starts-empty) explains it) fades once the state of the shop no longer depends on how the run started. Here the queue, empty for the first orders, reaches its usual range within about two minutes. The warmed-up numbers still pass the [Little's law](https://jaehyeon.me/desflow/latest/learn/concepts/queueing-basics/#littles-law) check from Measuring a Run. In the 3,480 seconds after the warm-up, 6,294 orders were packed, 1.81 a second. 1.81 orders a second × 2.050 seconds of mean wait = 3.71 orders waiting on average, which matches the `queue_length_avg` of 3.71 that the same statistics report. Each tab prints the two counts: ```bash desflow run trusting_results.yaml --stdout | grep -E 'pack_order\.finished"|queue_length_avg"' | tail -2 ``` ```text {"stream_type":"telemetry","sim_ts":3600.0,"timestamp":"...","path_id":"Shop.stats.resources.packers.queue_length_avg","value":3.7095253628163287} {"stream_type":"telemetry","sim_ts":3600.0,"timestamp":"...","path_id":"Shop.stats.tasks.pack_order.finished","value":6294} ``` ```bash python trusting_results.py 2>/dev/null | grep '^after' ``` ```text after the warm-up: 6294 orders packed, queue_length_avg 3.71 ``` ```bash python trusting_results_low_level.py 2>/dev/null | grep '^after' ``` ```text after the warm-up: 6294 orders packed, queue_length_avg 3.71 ``` [Statistics](https://jaehyeon.me/desflow/latest/user-guide/results/statistics/index.md) describes how the reset works. Replications ([Output Analysis](https://jaehyeon.me/desflow/latest/learn/concepts/output-analysis/#replications) explains them) are independent of each other, because each has its own seed. So the spread of their values measures how much the answer depends on chance. With few replications the spread itself is uncertain. The [Student t quantile](https://jaehyeon.me/desflow/latest/learn/concepts/output-analysis/#interval-and-half-width) allows for it: the half-width is the standard error times 2.776 for 5 replications, and times 2.023 for 40. ## Key Takeaways - One run's answer depends on its seed. Replications measure how much. - Report the mean of the replications with its 95% interval, not the value of one run. - A warm-up removes the start of a run, which begins empty. Choose the shortest warm-up that gives the same answer as longer ones. ______________________________________________________________________ ## Full Files Full files ```yaml # The Trusting Results tutorial: the busy hour, measured after a warm-up. # Run it with: desflow run trusting_results.yaml # Without the warm-up: WARMUP=0 desflow run trusting_results.yaml simulation: sim_id: Shop factor: 0 random_seed: 42 # Records and statistics start after the first 2 minutes; 0 keeps everything warmup: ${WARMUP:-2 min} resources: packers: {current_cap: 3, max_cap: 10} arrivals: orders: {dist: exponential, rate: 1.8, spawn: pack_order} services: # The 40 packing times measured at the bench, in seconds packing: dist: empirical values: [1.5, 2.5, 2.4, 1.2, 1.3, 1.2, 1.8, 1.4, 2.0, 0.7, 2.7, 1.4, 1.9, 1.4, 1.3, 1.8, 2.0, 1.4, 1.4, 1.9, 1.1, 0.8, 1.7, 1.1, 0.7, 1.1, 1.2, 0.9, 0.8, 1.5, 2.1, 1.3, 1.1, 1.7, 1.9, 1.3, 1.8, 2.2, 1.4, 1.1] tasks: pack_order: service: packing resource: packers payload: {event_type: order_packed} # Every 10 seconds, wait_mean is the mean wait so far: plot it against sim_ts stats: {level: typical, interval: 10} egress: - {type: Console} run: {until: 1 h} ``` ```python """The Trusting Results tutorial: the busy hour, measured after a warm-up, builder. Three packers pack orders that arrive at 1.8 a second on average, with the packing times measured at the bench. Every record is printed to the terminal. At the end the script prints the mean wait without and with the warm-up, the mean wait of 5 runs after each of three candidate warm-ups, then the mean and half-width of two outputs over 5, 10, 20 and 40 replications. To see only those lines, run: python trusting_results.py 2>/dev/null With the argument start, it runs the first 15 minutes without a warm-up, to plot: python trusting_results.py start 2>&1 """ import logging import sys from desflow import ConsoleEgress, SimulationContext, replicate from desflow.analysis import interval logging.basicConfig( level=logging.INFO, format="%(levelname)s [%(asctime)s] %(message)s" ) # The 40 packing times measured at the bench, in seconds MEASURED = [ 1.5, 2.5, 2.4, 1.2, 1.3, 1.2, 1.8, 1.4, 2.0, 0.7, 2.7, 1.4, 1.9, 1.4, 1.3, 1.8, 2.0, 1.4, 1.4, 1.9, 1.1, 0.8, 1.7, 1.1, 0.7, 1.1, 1.2, 0.9, 0.8, 1.5, 2.1, 1.3, 1.1, 1.7, 1.9, 1.3, 1.8, 2.2, 1.4, 1.1, ] # fmt: skip def shop(warmup="2 min") -> SimulationContext: """The busy hour; records and statistics start after `warmup`.""" app = ( # Records and statistics start after the first 2 minutes; None keeps everything SimulationContext(sim_id="Shop", factor=0, random_seed=42, warmup=warmup) .add_resource("packers", current_cap=3, max_cap=10) .add_arrival("orders", dist="exponential", rate=1.8) .add_service("packing", dist="empirical", values=MEASURED) # Every 10 seconds, wait_mean is the mean wait so far: plot it against sim_ts .with_stats("typical", interval=10) .add_egress(ConsoleEgress()) ) @app.task(service_id="packing", resource_id="packers") def pack_order(task_id: int): return {"event_type": "order_packed"} @app.arrival_loop("orders") def order_generator(context: SimulationContext): task_id = 0 while True: order = yield context.wait_for_arrival("orders") context.spawn(pack_order(task_id, entity=order)) task_id += 1 return app def busy_hour(warmup) -> dict: """Runs the busy hour and returns the statistics it measured.""" app = shop(warmup) app.run(until="1 h") return app.env.stats.readings() def mean_wait(warmup) -> float: """Runs the busy hour and returns the mean wait it measured.""" return busy_hour(warmup)["Shop.stats.tasks.pack_order.wait_mean"] MEASURES = ["tasks.pack_order.wait_mean", "resources.packers.utilization_avg"] def replications(n=40): """Runs the busy hour n times, each after the warm-up, with seeds spawned from 42.""" return replicate(shop, n, seed=42, until="1 h", measures=MEASURES) def warmups(n=5) -> dict: """The mean wait of n runs after each candidate warm-up, with seeds spawned from 42.""" wait = ["tasks.pack_order.wait_mean"] return { warmup: replicate(shop, n, seed=42, until="1 h", warmup=warmup, measures=wait) for warmup in ("1 min", "2 min", "4 min") } def precision(result) -> dict: """Each output's mean and half-width over the first 5, 10, 20 and 40 replications.""" return { (measure, n): interval(result.values[measure][:n]) for measure in MEASURES for n in (5, 10, 20, 40) } WAIT = "Shop.stats.tasks.pack_order.wait_mean" PACKED = "Shop.stats.tasks.pack_order.finished" QUEUE = "Shop.stats.resources.packers.queue_length_avg" def report() -> None: """Prints the mean waits, the Little's law figures and the precision.""" print(f"without a warm-up: mean wait {mean_wait(None):.3f} s") warmed = busy_hour("2 min") print(f"with a 2 min warm-up: mean wait {warmed[WAIT]:.3f} s") print( f"after the warm-up: {warmed[PACKED]} orders packed, " f"queue_length_avg {warmed[QUEUE]:.2f}" ) for warmup, result in warmups().items(): row = result.summary[0] print( f"warm-up {warmup}: mean wait {row['mean']:.3f} ± {row['half_width']:.2f} s" ) for (measure, n), result in precision(replications()).items(): share = result.half_width / result.mean print( f"{measure}, {n} runs: {result.mean:.2f} ± {result.half_width:.2f} ({share:.1%})" ) if __name__ == "__main__": if sys.argv[1:] == ["start"]: # The statistics every 10 seconds of the first 15 minutes, without a warm-up shop(None).run(until="15 min") else: report() ``` ```python """The Trusting Results tutorial: the busy hour, measured after a warm-up, low-level. Three packers pack orders that arrive at 1.8 a second on average, with the packing times measured at the bench. Every record is printed to the terminal. At the end the script prints the mean wait without and with the warm-up, the mean wait of 5 runs after each of three candidate warm-ups, then the mean and half-width of two outputs over 5, 10, 20 and 40 replications. To see only those lines, run: python trusting_results_low_level.py 2>/dev/null With the argument start, it runs the first 15 minutes without a warm-up, to plot: python trusting_results_low_level.py start 2>&1 """ import logging import sys from desflow import ( CapacityConfig, ConsoleEgress, DistributionConfig, DynamicRealtimeEnvironment, DynamicResource, LowLevelModel, Sampler, SimParameter, replicate, ) from desflow.analysis import interval logging.basicConfig( level=logging.INFO, format="%(levelname)s [%(asctime)s] %(message)s" ) # The 40 packing times measured at the bench, in seconds MEASURED = [ 1.5, 2.5, 2.4, 1.2, 1.3, 1.2, 1.8, 1.4, 2.0, 0.7, 2.7, 1.4, 1.9, 1.4, 1.3, 1.8, 2.0, 1.4, 1.4, 1.9, 1.1, 0.8, 1.7, 1.1, 0.7, 1.1, 1.2, 0.9, 0.8, 1.5, 2.1, 1.3, 1.1, 1.7, 1.9, 1.3, 1.8, 2.2, 1.4, 1.1, ] # fmt: skip PARAMS = SimParameter( sim_id="Shop", arrival={"orders": DistributionConfig(dist="exponential", rate=1.8)}, service={"packing": DistributionConfig(dist="empirical", values=MEASURED)}, resources={"packers": CapacityConfig(current_cap=3, max_cap=10)}, ) def pack_order(env, sampler, packers, key, task_id): """One order, which reports each step to the statistics.""" path_id = "Shop.service.packing" def publish(value): env.publish_event(key, value, task="pack_order", instance=task_id) publish( {"path_id": path_id, "sim_id": "Shop", "service": "packing", "status": "queued"} ) env.stats.flow_started("orders") # the order enters the shop env.stats.task_queued("pack_order", task_id) with packers.request() as request: yield request publish( { "path_id": path_id, "sim_id": "Shop", "service": "packing", "status": "started", } ) env.stats.task_started("pack_order", task_id) yield env.timeout(sampler.sample(env.registry.get_config(path_id))) publish({"event_type": "order_packed"}) env.stats.task_finished("pack_order", task_id) env.stats.flow_finished("orders") # the order leaves the shop def order_generator(env, sampler, packers): arrival = env.registry.get_config("Shop.arrival.orders") task_id = 0 while True: yield env.timeout(sampler.sample(arrival)) env.process(pack_order(env, sampler, packers, f"orders-{task_id + 1}", task_id)) task_id += 1 # Records and statistics start after the first 2 minutes; None keeps everything WARMUP = 120.0 # seconds, passed to setup_egress in run below def run(warmup=WARMUP, until=3600, factor=0.0): env = DynamicRealtimeEnvironment(factor=factor) env.registry.register_sim_parameter(PARAMS) # Every 10 seconds, wait_mean is the mean wait so far: plot it against sim_ts env.setup_stats("Shop", "typical", interval=10) # The warm-up is set with the sinks: no sink receives a record stamped before it # ends, and the statistics start again from zero when it ends env.setup_egress([ConsoleEgress()], warmup=warmup) packers = DynamicResource(env, "Shop", "packers") env.process(order_generator(env, Sampler(seed=42), packers)) try: env.run(until=until) finally: env.teardown() return env def mean_wait(warmup) -> float: """Runs the busy hour and returns the mean wait it measured.""" return run(warmup).stats.readings()["Shop.stats.tasks.pack_order.wait_mean"] MEASURES = ["tasks.pack_order.wait_mean", "resources.packers.utilization_avg"] def model(env, sampler): """The busy hour in a given environment: replicate sets the statistics.""" env.registry.register_sim_parameter(PARAMS) packers = DynamicResource(env, "Shop", "packers") env.process(order_generator(env, sampler, packers)) def replications(n=40): """Runs the busy hour n times, each after the warm-up, with seeds spawned from 42.""" shop = LowLevelModel(model, sim_id="Shop") return replicate(shop, n, seed=42, until=3600, warmup=WARMUP, measures=MEASURES) def warmups(n=5) -> dict: """The mean wait of n runs after each candidate warm-up, with seeds spawned from 42.""" shop = LowLevelModel(model, sim_id="Shop") wait = ["tasks.pack_order.wait_mean"] return { warmup: replicate(shop, n, seed=42, until=3600, warmup=warmup, measures=wait) for warmup in (60, WARMUP, 240) } def precision(result) -> dict: """Each output's mean and half-width over the first 5, 10, 20 and 40 replications.""" return { (measure, n): interval(result.values[measure][:n]) for measure in MEASURES for n in (5, 10, 20, 40) } WAIT = "Shop.stats.tasks.pack_order.wait_mean" PACKED = "Shop.stats.tasks.pack_order.finished" QUEUE = "Shop.stats.resources.packers.queue_length_avg" def report() -> None: """Prints the mean waits, the Little's law figures and the precision.""" print(f"without a warm-up: mean wait {mean_wait(None):.3f} s") warmed = run(WARMUP).stats.readings() print(f"with a 2 min warm-up: mean wait {warmed[WAIT]:.3f} s") print( f"after the warm-up: {warmed[PACKED]} orders packed, " f"queue_length_avg {warmed[QUEUE]:.2f}" ) for warmup, result in warmups().items(): row = result.summary[0] print( f"warm-up {warmup:g} s: mean wait {row['mean']:.3f} ± {row['half_width']:.2f} s" ) for (measure, n), result in precision(replications()).items(): share = result.half_width / result.mean print( f"{measure}, {n} runs: {result.mean:.2f} ± {result.half_width:.2f} ({share:.1%})" ) if __name__ == "__main__": if sys.argv[1:] == ["start"]: # The statistics every 10 seconds of the first 15 minutes, without a warm-up run(None, until=900) else: report() ``` # Comparing Designs [Trusting Results](https://jaehyeon.me/desflow/latest/learn/studies/trusting-results/index.md) measured the busy hour with three packers: over 40 [replications](https://jaehyeon.me/desflow/latest/learn/concepts/output-analysis/#replications) the mean wait was 2.10 ± 0.10 seconds. The shop could hire a fourth packer. This page asks: **does a fourth packer cut the mean wait, and by how much?** - **Decision:** three packers or four. - **Measures:** the mean wait and the packers' [utilisation](https://jaehyeon.me/desflow/latest/learn/concepts/queueing-basics/#utilisation). - **Runs:** the busy hour after its 2-minute [warm-up](https://jaehyeon.me/desflow/latest/learn/concepts/output-analysis/#one-run-starts-empty), 20 replications of each design with the same seeds, spawned from 42. Twenty are enough, because the decision rests on the difference between the two designs under the same seeds, which is far from 0, and not on the precision of each design's own mean. The rest of the day is not modelled. - **Assumptions:** those of Trusting Results: orders at random at 1.8 a second, and the 40 packing times measured at the bench. ## What You Will Learn This page shows how to: - write an experiment that names the model, the designs, a comparison and a check; - compare two designs with the same seeds; - read the difference with its interval, and the report. ## What You Add This page adds an experiment: a file in YAML, or a mapping in Python, that names the model, the two designs, the comparison and a check. The model is the busy hour of Trusting Results, unchanged. ______________________________________________________________________ ## Name the Model An experiment runs a model written in any of the three ways, for a number of replications from one seed: ```yaml # The busy hour of Trusting Results, with its 2-minute warm-up model: trusting_results.yaml until: 1 h replications: 20 seed: 42 ``` The path is read from the experiment file's folder. ```python # A function returning a new busy hour, with its 2-minute warm-up "model": shop, "until": "1 h", "replications": 20, "seed": 42, ``` `shop` is the function of Trusting Results that returns a new busy hour. The experiment calls it once per run. ```python # The function that builds the busy hour, and its 2-minute warm-up "model": LowLevelModel(model, sim_id="Shop"), "warmup": WARMUP, "until": 3600, "replications": 20, "seed": 42, ``` The low-level model has no [warm-up](https://jaehyeon.me/desflow/latest/learn/concepts/output-analysis/#one-run-starts-empty) of its own, so the experiment gives it one. ______________________________________________________________________ ## Compare Two Designs Each variant names the registry values it changes before the clock starts. `three` changes nothing, so it is the busy hour as written. `four` sets the packers' capacity to 4. `pairing: common` gives both designs the same 20 seeds, and `compare` asks for their difference seed by seed: ```yaml # Every design runs with the same 20 seeds, so they are compared seed by seed pairing: common measures: [tasks.pack_order.wait_mean, resources.packers.utilization_avg] variants: three: {} four: {Shop.resources.packers.current_cap: 4} compare: - {baseline: three, variant: four} ``` ```python # Every design runs with the same 20 seeds, so they are compared seed by seed "pairing": "common", "measures": ["tasks.pack_order.wait_mean", "resources.packers.utilization_avg"], "variants": {"three": {}, "four": {"Shop.resources.packers.current_cap": 4}}, "compare": [{"baseline": "three", "variant": "four"}], ``` The same keys, in the same mapping as the model. Save the files from [Full Files](#full-files) in one folder and run the commands there: ```bash desflow experiment comparing_designs_experiment.yaml ``` ```bash python comparing_designs.py ``` ```bash python comparing_designs_low_level.py ``` The experiment runs 40 replications, 20 of each design, and writes what it found to `results/four-packers`. The YAML command prints only where it wrote and the result of the check. The two scripts print the difference of each measure and the result of the check. Open `results/four-packers/report.md`: its Results and Comparisons sections hold the two tables below. Each design's results, with the 95% [half-width](https://jaehyeon.me/desflow/latest/learn/concepts/output-analysis/#interval-and-half-width): | Design | Mean wait (s) | Utilisation (%) | | ------ | ------------- | --------------- | | three | 2.15 ± 0.15 | 89.99 ± 0.60 | | four | 0.27 ± 0.01 | 67.51 ± 0.46 | The three-packer design ran with the first 20 of the seeds that Trusting Results used. Its row therefore equals that page's figure for 20 replications, not its mean of 2.10 seconds over 40. [Busy Hour Figures](https://jaehyeon.me/desflow/latest/learn/concepts/output-analysis/#busy-hour-figures) lists both. The comparison gives the four-packer value minus the three-packer value, seed by seed: | Measure | Difference | Half-width | Random streams | | ----------------------------------- | ------------------------ | ---------------------- | -------------- | | `tasks.pack_order.wait_mean` | -1.89 s | 0.14 s | 2 shared | | `resources.packers.utilization_avg` | -22.49 percentage points | 0.15 percentage points | 2 shared | The difference in [utilisation](https://jaehyeon.me/desflow/latest/learn/concepts/queueing-basics/#utilisation) has a half-width of 0.15 percentage points, although each design's own utilisation has a half-width of 0.60 or 0.46. The same seed gives both designs the same arrivals and packing times, so a busy run of one design is a busy run of the other. Their difference therefore leaves out most of the variation that comes from chance. Running every design with the same seeds is called **[common random numbers](https://jaehyeon.me/desflow/latest/learn/concepts/output-analysis/#comparing-designs)**. The difference in waits has a half-width of 0.14 seconds, about the same as the half-width of the three-packer wait, 0.15 seconds. With four packers the wait hardly varies, so the difference varies about as much as the three-packer wait does. "2 shared" says both designs drew from the same two random streams, `arrival.orders` and `service.packing`. desflow records which streams each run drew from. It lists any stream that only one design used, such as the stream of a gift-wrap step that only one design has, because draws from such a stream are not paired. With `pairing: independent` each design gets seeds of its own instead. A comparison is then refused, because no seed pairs one run of each design. ______________________________________________________________________ ## Check the Answer A check states what the answer must be. This one asks for a mean wait under half a second with four packers: ```yaml checks: # The upper end of the interval must be under half a second - {measure: tasks.pack_order.wait_mean, variant: four, max: 0.5} ``` ```python # The upper end of the interval must be under half a second "checks": [ {"measure": "tasks.pack_order.wait_mean", "variant": "four", "max": 0.5} ], ``` The same key, in the same mapping. A check compares its bound with the end of the interval that is nearer to failing it, here the upper end. A mean that is below the bound only by chance has an upper end above the bound, so it does not pass. The upper end is 0.276 seconds, so the check passes. When a check fails, `desflow experiment` still writes every file, then exits with status 1, and `run_experiment` raises `CheckFailed`. Either way, a script or a CI job stops at the failed check. ______________________________________________________________________ ## Read the Report The experiment writes `report.md` beside its results. It states the question, the model and its versions, the assumptions, each input distribution with where it came from, the run settings, the counts, the results, the comparison and the checks, and what the experiment does not state. The experiment file names its assumptions, the source of its inputs and its limits: ```yaml assumptions: - Orders arrive at random, at a steady 1.8 a second, through the busy hour. - The 40 packing times measured at the bench stand for every packer. inputs: Shop.service.packing: 40 packing times measured at the bench, in seconds limits: [One busy hour only; the rest of the day is not modelled.] output: results/four-packers ``` The experiment states where the packing times came from but not the arrival rate, so the report's Missing Inputs section says: "The provenance of `Shop.arrival.orders` is not stated." It names the gap rather than filling it in. [Experiments](https://jaehyeon.me/desflow/latest/user-guide/results/experiments/index.md) lists every file and section. `output` in the experiment file names the results folder. `--output` names another folder for one run, so a second run keeps the results of the first. `desflow report` builds `report.md` again from the other files in a results folder, with no new run, such as after editing `experiment.json` by hand. `output=` in `run_experiment` names the folder in Python: ```bash desflow experiment comparing_designs_experiment.yaml --output results/four-packers-again desflow report results/four-packers-again ``` ______________________________________________________________________ ## What You Get and Why The mean wait of each design over its 20 replications, with its 95% interval: Does a fourth packer cut the mean wait, and by how much? Yes. Over 20 replications of each design after the 2-minute warm-up, with the same seeds, a fourth packer cuts the busy hour's mean wait by **1.89 ± 0.14 seconds**, from 2.15 to 0.27 seconds. The packers are busy **22.49 ± 0.15 percentage points** less of the time. The whole interval of the difference is below zero, and the four-packer wait stays under the half-second bound. Two designs run with different seeds differ by the design and by chance, and the chance part can hide a small effect. With the same seeds, each pair of runs has the same arrivals and the same packing times, so the chance part partly cancels in their difference, as [Output Analysis](https://jaehyeon.me/desflow/latest/learn/concepts/output-analysis/#comparing-designs) explains. Each difference comes from a seed of its own, so the 20 differences are independent of each other, and the interval is a [Student t interval](https://jaehyeon.me/desflow/latest/learn/concepts/output-analysis/#interval-and-half-width) on them. ## Key Takeaways - Running both designs with the same seeds makes the chance part of their difference partly cancel. - The difference between two designs has its own interval. An interval that lies wholly below or wholly above zero shows a difference that chance alone does not explain, at 95% confidence. - A check in the experiment turns the decision rule into a test that passes or fails. ______________________________________________________________________ ## Full Files Full files ```yaml # The Comparing Designs tutorial: does a fourth packer cut the busy hour's mean wait? # Run it with: desflow experiment comparing_designs_experiment.yaml # Each design separately: change pairing to independent and remove compare. experiment: four-packers question: Does a fourth packer cut the mean wait of the busy hour, and by how much? # The busy hour of Trusting Results, with its 2-minute warm-up model: trusting_results.yaml until: 1 h replications: 20 seed: 42 # Every design runs with the same 20 seeds, so they are compared seed by seed pairing: common measures: [tasks.pack_order.wait_mean, resources.packers.utilization_avg] variants: three: {} four: {Shop.resources.packers.current_cap: 4} compare: - {baseline: three, variant: four} checks: # The upper end of the interval must be under half a second - {measure: tasks.pack_order.wait_mean, variant: four, max: 0.5} assumptions: - Orders arrive at random, at a steady 1.8 a second, through the busy hour. - The 40 packing times measured at the bench stand for every packer. inputs: Shop.service.packing: 40 packing times measured at the bench, in seconds limits: [One busy hour only; the rest of the day is not modelled.] output: results/four-packers ``` ```yaml # The Trusting Results tutorial: the busy hour, measured after a warm-up. # Run it with: desflow run trusting_results.yaml # Without the warm-up: WARMUP=0 desflow run trusting_results.yaml simulation: sim_id: Shop factor: 0 random_seed: 42 # Records and statistics start after the first 2 minutes; 0 keeps everything warmup: ${WARMUP:-2 min} resources: packers: {current_cap: 3, max_cap: 10} arrivals: orders: {dist: exponential, rate: 1.8, spawn: pack_order} services: # The 40 packing times measured at the bench, in seconds packing: dist: empirical values: [1.5, 2.5, 2.4, 1.2, 1.3, 1.2, 1.8, 1.4, 2.0, 0.7, 2.7, 1.4, 1.9, 1.4, 1.3, 1.8, 2.0, 1.4, 1.4, 1.9, 1.1, 0.8, 1.7, 1.1, 0.7, 1.1, 1.2, 0.9, 0.8, 1.5, 2.1, 1.3, 1.1, 1.7, 1.9, 1.3, 1.8, 2.2, 1.4, 1.1] tasks: pack_order: service: packing resource: packers payload: {event_type: order_packed} # Every 10 seconds, wait_mean is the mean wait so far: plot it against sim_ts stats: {level: typical, interval: 10} egress: - {type: Console} run: {until: 1 h} ``` ```python """The Comparing Designs tutorial: a fourth packer, builder. Runs the busy hour of Trusting Results 20 times with three packers and 20 times with four, with the same seeds, and compares the two designs seed by seed. The experiment writes its artifacts and report to results/four-packers, and the script prints the comparison and the check. """ import logging from desflow import run_experiment from trusting_results import shop # The imported model logs at INFO; an experiment logs only its warnings logging.getLogger("desflow").setLevel(logging.WARNING) EXPERIMENT = { "experiment": "four-packers", "question": "Does a fourth packer cut the mean wait of the busy hour, and by how much?", # A function returning a new busy hour, with its 2-minute warm-up "model": shop, "until": "1 h", "replications": 20, "seed": 42, # Every design runs with the same 20 seeds, so they are compared seed by seed "pairing": "common", "measures": ["tasks.pack_order.wait_mean", "resources.packers.utilization_avg"], "variants": {"three": {}, "four": {"Shop.resources.packers.current_cap": 4}}, "compare": [{"baseline": "three", "variant": "four"}], # The upper end of the interval must be under half a second "checks": [ {"measure": "tasks.pack_order.wait_mean", "variant": "four", "max": 0.5} ], "assumptions": [ "Orders arrive at random, at a steady 1.8 a second, through the busy hour.", "The 40 packing times measured at the bench stand for every packer.", ], "inputs": { "Shop.service.packing": "40 packing times measured at the bench, in seconds" }, "limits": ["One busy hour only; the rest of the day is not modelled."], "output": "results/four-packers", } def experiment(pairing="common", output=None): """Runs the experiment; independent pairing gives each design seeds of its own.""" settings = dict(EXPERIMENT, pairing=pairing) if pairing == "independent": settings["compare"] = [] # a comparison needs the same seeds return run_experiment(settings, output=output) if __name__ == "__main__": result = experiment() for row in result.comparisons: print(f"{row['measure']}: {row['difference']:.2f} ± {row['half_width']:.2f}") for row in result.checks: print(f"check {row['design']}: {row['value']:.3f} passed={row['passed']}") ``` ```python """The Trusting Results tutorial: the busy hour, measured after a warm-up, builder. Three packers pack orders that arrive at 1.8 a second on average, with the packing times measured at the bench. Every record is printed to the terminal. At the end the script prints the mean wait without and with the warm-up, the mean wait of 5 runs after each of three candidate warm-ups, then the mean and half-width of two outputs over 5, 10, 20 and 40 replications. To see only those lines, run: python trusting_results.py 2>/dev/null With the argument start, it runs the first 15 minutes without a warm-up, to plot: python trusting_results.py start 2>&1 """ import logging import sys from desflow import ConsoleEgress, SimulationContext, replicate from desflow.analysis import interval logging.basicConfig( level=logging.INFO, format="%(levelname)s [%(asctime)s] %(message)s" ) # The 40 packing times measured at the bench, in seconds MEASURED = [ 1.5, 2.5, 2.4, 1.2, 1.3, 1.2, 1.8, 1.4, 2.0, 0.7, 2.7, 1.4, 1.9, 1.4, 1.3, 1.8, 2.0, 1.4, 1.4, 1.9, 1.1, 0.8, 1.7, 1.1, 0.7, 1.1, 1.2, 0.9, 0.8, 1.5, 2.1, 1.3, 1.1, 1.7, 1.9, 1.3, 1.8, 2.2, 1.4, 1.1, ] # fmt: skip def shop(warmup="2 min") -> SimulationContext: """The busy hour; records and statistics start after `warmup`.""" app = ( # Records and statistics start after the first 2 minutes; None keeps everything SimulationContext(sim_id="Shop", factor=0, random_seed=42, warmup=warmup) .add_resource("packers", current_cap=3, max_cap=10) .add_arrival("orders", dist="exponential", rate=1.8) .add_service("packing", dist="empirical", values=MEASURED) # Every 10 seconds, wait_mean is the mean wait so far: plot it against sim_ts .with_stats("typical", interval=10) .add_egress(ConsoleEgress()) ) @app.task(service_id="packing", resource_id="packers") def pack_order(task_id: int): return {"event_type": "order_packed"} @app.arrival_loop("orders") def order_generator(context: SimulationContext): task_id = 0 while True: order = yield context.wait_for_arrival("orders") context.spawn(pack_order(task_id, entity=order)) task_id += 1 return app def busy_hour(warmup) -> dict: """Runs the busy hour and returns the statistics it measured.""" app = shop(warmup) app.run(until="1 h") return app.env.stats.readings() def mean_wait(warmup) -> float: """Runs the busy hour and returns the mean wait it measured.""" return busy_hour(warmup)["Shop.stats.tasks.pack_order.wait_mean"] MEASURES = ["tasks.pack_order.wait_mean", "resources.packers.utilization_avg"] def replications(n=40): """Runs the busy hour n times, each after the warm-up, with seeds spawned from 42.""" return replicate(shop, n, seed=42, until="1 h", measures=MEASURES) def warmups(n=5) -> dict: """The mean wait of n runs after each candidate warm-up, with seeds spawned from 42.""" wait = ["tasks.pack_order.wait_mean"] return { warmup: replicate(shop, n, seed=42, until="1 h", warmup=warmup, measures=wait) for warmup in ("1 min", "2 min", "4 min") } def precision(result) -> dict: """Each output's mean and half-width over the first 5, 10, 20 and 40 replications.""" return { (measure, n): interval(result.values[measure][:n]) for measure in MEASURES for n in (5, 10, 20, 40) } WAIT = "Shop.stats.tasks.pack_order.wait_mean" PACKED = "Shop.stats.tasks.pack_order.finished" QUEUE = "Shop.stats.resources.packers.queue_length_avg" def report() -> None: """Prints the mean waits, the Little's law figures and the precision.""" print(f"without a warm-up: mean wait {mean_wait(None):.3f} s") warmed = busy_hour("2 min") print(f"with a 2 min warm-up: mean wait {warmed[WAIT]:.3f} s") print( f"after the warm-up: {warmed[PACKED]} orders packed, " f"queue_length_avg {warmed[QUEUE]:.2f}" ) for warmup, result in warmups().items(): row = result.summary[0] print( f"warm-up {warmup}: mean wait {row['mean']:.3f} ± {row['half_width']:.2f} s" ) for (measure, n), result in precision(replications()).items(): share = result.half_width / result.mean print( f"{measure}, {n} runs: {result.mean:.2f} ± {result.half_width:.2f} ({share:.1%})" ) if __name__ == "__main__": if sys.argv[1:] == ["start"]: # The statistics every 10 seconds of the first 15 minutes, without a warm-up shop(None).run(until="15 min") else: report() ``` ```python """The Comparing Designs tutorial: a fourth packer, low-level. Runs the busy hour of Trusting Results 20 times with three packers and 20 times with four, with the same seeds, and compares the two designs seed by seed. The experiment writes its artifacts and report to results/four-packers, and the script prints the comparison and the check. """ import logging from desflow import LowLevelModel, run_experiment from trusting_results_low_level import WARMUP, model # The imported model logs at INFO; an experiment logs only its warnings logging.getLogger("desflow").setLevel(logging.WARNING) EXPERIMENT = { "experiment": "four-packers", "question": "Does a fourth packer cut the mean wait of the busy hour, and by how much?", # The function that builds the busy hour, and its 2-minute warm-up "model": LowLevelModel(model, sim_id="Shop"), "warmup": WARMUP, "until": 3600, "replications": 20, "seed": 42, "pairing": "common", "measures": ["tasks.pack_order.wait_mean", "resources.packers.utilization_avg"], "variants": {"three": {}, "four": {"Shop.resources.packers.current_cap": 4}}, "compare": [{"baseline": "three", "variant": "four"}], "checks": [ {"measure": "tasks.pack_order.wait_mean", "variant": "four", "max": 0.5} ], "assumptions": [ "Orders arrive at random, at a steady 1.8 a second, through the busy hour.", "The 40 packing times measured at the bench stand for every packer.", ], "inputs": { "Shop.service.packing": "40 packing times measured at the bench, in seconds" }, "limits": ["One busy hour only; the rest of the day is not modelled."], "output": "results/four-packers", } def experiment(pairing="common", output=None): """Runs the experiment; independent pairing gives each design seeds of its own.""" settings = dict(EXPERIMENT, pairing=pairing) if pairing == "independent": settings["compare"] = [] # a comparison needs the same seeds return run_experiment(settings, output=output) if __name__ == "__main__": result = experiment() for row in result.comparisons: print(f"{row['measure']}: {row['difference']:.2f} ± {row['half_width']:.2f}") for row in result.checks: print(f"check {row['design']}: {row['value']:.3f} passed={row['passed']}") ``` ```python """The Trusting Results tutorial: the busy hour, measured after a warm-up, low-level. Three packers pack orders that arrive at 1.8 a second on average, with the packing times measured at the bench. Every record is printed to the terminal. At the end the script prints the mean wait without and with the warm-up, the mean wait of 5 runs after each of three candidate warm-ups, then the mean and half-width of two outputs over 5, 10, 20 and 40 replications. To see only those lines, run: python trusting_results_low_level.py 2>/dev/null With the argument start, it runs the first 15 minutes without a warm-up, to plot: python trusting_results_low_level.py start 2>&1 """ import logging import sys from desflow import ( CapacityConfig, ConsoleEgress, DistributionConfig, DynamicRealtimeEnvironment, DynamicResource, LowLevelModel, Sampler, SimParameter, replicate, ) from desflow.analysis import interval logging.basicConfig( level=logging.INFO, format="%(levelname)s [%(asctime)s] %(message)s" ) # The 40 packing times measured at the bench, in seconds MEASURED = [ 1.5, 2.5, 2.4, 1.2, 1.3, 1.2, 1.8, 1.4, 2.0, 0.7, 2.7, 1.4, 1.9, 1.4, 1.3, 1.8, 2.0, 1.4, 1.4, 1.9, 1.1, 0.8, 1.7, 1.1, 0.7, 1.1, 1.2, 0.9, 0.8, 1.5, 2.1, 1.3, 1.1, 1.7, 1.9, 1.3, 1.8, 2.2, 1.4, 1.1, ] # fmt: skip PARAMS = SimParameter( sim_id="Shop", arrival={"orders": DistributionConfig(dist="exponential", rate=1.8)}, service={"packing": DistributionConfig(dist="empirical", values=MEASURED)}, resources={"packers": CapacityConfig(current_cap=3, max_cap=10)}, ) def pack_order(env, sampler, packers, key, task_id): """One order, which reports each step to the statistics.""" path_id = "Shop.service.packing" def publish(value): env.publish_event(key, value, task="pack_order", instance=task_id) publish( {"path_id": path_id, "sim_id": "Shop", "service": "packing", "status": "queued"} ) env.stats.flow_started("orders") # the order enters the shop env.stats.task_queued("pack_order", task_id) with packers.request() as request: yield request publish( { "path_id": path_id, "sim_id": "Shop", "service": "packing", "status": "started", } ) env.stats.task_started("pack_order", task_id) yield env.timeout(sampler.sample(env.registry.get_config(path_id))) publish({"event_type": "order_packed"}) env.stats.task_finished("pack_order", task_id) env.stats.flow_finished("orders") # the order leaves the shop def order_generator(env, sampler, packers): arrival = env.registry.get_config("Shop.arrival.orders") task_id = 0 while True: yield env.timeout(sampler.sample(arrival)) env.process(pack_order(env, sampler, packers, f"orders-{task_id + 1}", task_id)) task_id += 1 # Records and statistics start after the first 2 minutes; None keeps everything WARMUP = 120.0 # seconds, passed to setup_egress in run below def run(warmup=WARMUP, until=3600, factor=0.0): env = DynamicRealtimeEnvironment(factor=factor) env.registry.register_sim_parameter(PARAMS) # Every 10 seconds, wait_mean is the mean wait so far: plot it against sim_ts env.setup_stats("Shop", "typical", interval=10) # The warm-up is set with the sinks: no sink receives a record stamped before it # ends, and the statistics start again from zero when it ends env.setup_egress([ConsoleEgress()], warmup=warmup) packers = DynamicResource(env, "Shop", "packers") env.process(order_generator(env, Sampler(seed=42), packers)) try: env.run(until=until) finally: env.teardown() return env def mean_wait(warmup) -> float: """Runs the busy hour and returns the mean wait it measured.""" return run(warmup).stats.readings()["Shop.stats.tasks.pack_order.wait_mean"] MEASURES = ["tasks.pack_order.wait_mean", "resources.packers.utilization_avg"] def model(env, sampler): """The busy hour in a given environment: replicate sets the statistics.""" env.registry.register_sim_parameter(PARAMS) packers = DynamicResource(env, "Shop", "packers") env.process(order_generator(env, sampler, packers)) def replications(n=40): """Runs the busy hour n times, each after the warm-up, with seeds spawned from 42.""" shop = LowLevelModel(model, sim_id="Shop") return replicate(shop, n, seed=42, until=3600, warmup=WARMUP, measures=MEASURES) def warmups(n=5) -> dict: """The mean wait of n runs after each candidate warm-up, with seeds spawned from 42.""" shop = LowLevelModel(model, sim_id="Shop") wait = ["tasks.pack_order.wait_mean"] return { warmup: replicate(shop, n, seed=42, until=3600, warmup=warmup, measures=wait) for warmup in (60, WARMUP, 240) } def precision(result) -> dict: """Each output's mean and half-width over the first 5, 10, 20 and 40 replications.""" return { (measure, n): interval(result.values[measure][:n]) for measure in MEASURES for n in (5, 10, 20, 40) } WAIT = "Shop.stats.tasks.pack_order.wait_mean" PACKED = "Shop.stats.tasks.pack_order.finished" QUEUE = "Shop.stats.resources.packers.queue_length_avg" def report() -> None: """Prints the mean waits, the Little's law figures and the precision.""" print(f"without a warm-up: mean wait {mean_wait(None):.3f} s") warmed = run(WARMUP).stats.readings() print(f"with a 2 min warm-up: mean wait {warmed[WAIT]:.3f} s") print( f"after the warm-up: {warmed[PACKED]} orders packed, " f"queue_length_avg {warmed[QUEUE]:.2f}" ) for warmup, result in warmups().items(): row = result.summary[0] print( f"warm-up {warmup:g} s: mean wait {row['mean']:.3f} ± {row['half_width']:.2f} s" ) for (measure, n), result in precision(replications()).items(): share = result.half_width / result.mean print( f"{measure}, {n} runs: {result.mean:.2f} ± {result.half_width:.2f} ({share:.1%})" ) if __name__ == "__main__": if sys.argv[1:] == ["start"]: # The statistics every 10 seconds of the first 15 minutes, without a warm-up run(None, until=900) else: report() ``` # Parameter Sweeps [Comparing Designs](https://jaehyeon.me/desflow/latest/learn/studies/comparing-designs/index.md) found that a fourth packer cuts the busy hour's mean wait from 2.15 to 0.27 seconds over 20 [replications](https://jaehyeon.me/desflow/latest/learn/concepts/output-analysis/#replications) of each, at 1.8 orders a second. That rate is an estimate, and demand moves from day to day. This page asks: **how much does the answer depend on the arrival rate?** - **Decision:** whether the choice of a fourth packer holds if demand differs from the estimate. - **Measures:** the mean wait of each design at each rate. - **Runs:** the busy hour after its 2-minute [warm-up](https://jaehyeon.me/desflow/latest/learn/concepts/output-analysis/#one-run-starts-empty), at four arrival rates around the estimate, 20 replications of each design with the same seeds, spawned from 42. - **Assumptions:** those of Trusting Results: orders at random at a steady rate, and the 40 packing times measured at the bench. ## What You Will Learn This page shows how to: - sweep a registry path over several values in an experiment; - read each design's result at each value; - check whether a decision holds if an input differs from its estimate. ## What You Add This page adds a `sweep` to the experiment: a registry path and the values it takes. The model and the two designs are those of Comparing Designs. ______________________________________________________________________ ## Sweep One Input A sweep runs every variant at every value of its paths. Here that is two variants, three and four packers, at four arrival rates from 1.6 to 1.9 orders a second. That makes 8 designs, each run 20 times with the same 20 seeds: ```yaml variants: three: {} four: {Shop.resources.packers.current_cap: 4} # Each variant at each rate: 8 designs, all run with the same 20 seeds sweep: {Shop.arrival.orders.rate: [1.6, 1.7, 1.8, 1.9]} ``` ```python "variants": {"three": {}, "four": {"Shop.resources.packers.current_cap": 4}}, # Each variant at each rate: 8 designs, all run with the same 20 seeds "sweep": {"Shop.arrival.orders.rate": [1.6, 1.7, 1.8, 1.9]}, ``` ```python "variants": {"three": {}, "four": {"Shop.resources.packers.current_cap": 4}}, # Each variant at each rate: 8 designs, all run with the same 20 seeds "sweep": {"Shop.arrival.orders.rate": [1.6, 1.7, 1.8, 1.9]}, ``` Changing one input while every other input stays the same is called **one-factor sensitivity** analysis. It shows how much the answer depends on that input. A sweep with two paths runs every combination of their values, so its size is the product of the list lengths. Save the files from [Full Files](#full-files) in one folder and run the commands there: `desflow experiment parameter_sweeps_experiment.yaml`, or `python parameter_sweeps.py` and `python parameter_sweeps_low_level.py`. Each design's name is its variant followed by its swept value, such as `three Shop.arrival.orders.rate=1.9`. `results.csv` and `summary.csv` have a column for the swept path. The table gives the mean wait of each design over its 20 replications, with the 95% [half-width](https://jaehyeon.me/desflow/latest/learn/concepts/output-analysis/#interval-and-half-width). The row for 1.8 orders a second is the experiment of Comparing Designs, as [Busy Hour Figures](https://jaehyeon.me/desflow/latest/learn/concepts/output-analysis/#busy-hour-figures) lists: | Orders a second | Three packers (s) | Four packers (s) | | --------------- | ----------------- | ---------------- | | 1.6 | 0.90 ± 0.05 | 0.16 ± 0.01 | | 1.7 | 1.32 ± 0.07 | 0.21 ± 0.01 | | 1.8 | 2.15 ± 0.15 | 0.27 ± 0.01 | | 1.9 | 4.52 ± 0.64 | 0.34 ± 0.02 | ______________________________________________________________________ ## What You Get and Why The mean wait of each design against the arrival rate, with its 95% interval: Each point is the mean of 20 replications after the 2-minute warm-up, with seeds spawned from 42, the same for every rate and design. How much does the answer depend on the arrival rate? With three packers, a great deal. A rate of 1.9 orders a second, about 6% above the estimate, more than doubles the mean wait, to **4.52 seconds**. A rate of 1.6 orders a second cuts it to 0.90 seconds. With four packers the mean wait stays at most **0.34 seconds** at every rate. The decision to add a packer therefore holds at every rate in this range. The three-packer wait, on the other hand, cannot be predicted well without a better estimate of the rate. Three packers that take 1.5 seconds an order on average pack 2 orders a second at most. At 1.9 orders a second they are busy 95% of the time. Close to that limit, a small rise in demand makes the queue much longer, so the wait grows faster than the rate, as [Queueing Basics](https://jaehyeon.me/desflow/latest/learn/concepts/queueing-basics/#waits-near-full-use) explains. Four packers stay below 72% busy at every rate in the sweep, far from their limit. Every design ran with the same seeds, so the differences between rows come from the rate, not from different random draws. The intervals widen with the rate, because a busier shop varies more from run to run. ## Key Takeaways - A sweep shows how much an answer depends on an input that is only estimated. - Near full use a small rise in demand makes the wait grow much faster than the demand. - A decision that holds over the whole range of the sweep does not depend on the exact estimate. ______________________________________________________________________ ## Full Files Full files ```yaml # The Parameter Sweeps tutorial: how much does the mean wait depend on the demand? # Run it with: desflow experiment parameter_sweeps_experiment.yaml experiment: demand question: How sensitive is the busy hour's mean wait to the arrival rate? # The busy hour of Trusting Results, with its 2-minute warm-up model: trusting_results.yaml until: 1 h replications: 20 seed: 42 measures: [tasks.pack_order.wait_mean] variants: three: {} four: {Shop.resources.packers.current_cap: 4} # Each variant at each rate: 8 designs, all run with the same 20 seeds sweep: {Shop.arrival.orders.rate: [1.6, 1.7, 1.8, 1.9]} output: results/demand ``` ```yaml # The Trusting Results tutorial: the busy hour, measured after a warm-up. # Run it with: desflow run trusting_results.yaml # Without the warm-up: WARMUP=0 desflow run trusting_results.yaml simulation: sim_id: Shop factor: 0 random_seed: 42 # Records and statistics start after the first 2 minutes; 0 keeps everything warmup: ${WARMUP:-2 min} resources: packers: {current_cap: 3, max_cap: 10} arrivals: orders: {dist: exponential, rate: 1.8, spawn: pack_order} services: # The 40 packing times measured at the bench, in seconds packing: dist: empirical values: [1.5, 2.5, 2.4, 1.2, 1.3, 1.2, 1.8, 1.4, 2.0, 0.7, 2.7, 1.4, 1.9, 1.4, 1.3, 1.8, 2.0, 1.4, 1.4, 1.9, 1.1, 0.8, 1.7, 1.1, 0.7, 1.1, 1.2, 0.9, 0.8, 1.5, 2.1, 1.3, 1.1, 1.7, 1.9, 1.3, 1.8, 2.2, 1.4, 1.1] tasks: pack_order: service: packing resource: packers payload: {event_type: order_packed} # Every 10 seconds, wait_mean is the mean wait so far: plot it against sim_ts stats: {level: typical, interval: 10} egress: - {type: Console} run: {until: 1 h} ``` ```python """The Parameter Sweeps tutorial: the wait at four arrival rates, builder. Runs the busy hour of Trusting Results with three packers and with four, each at four arrival rates, 20 times with the same seeds. The experiment writes its artifacts and report to results/demand, and the script prints each design's mean wait. """ import logging from desflow import run_experiment from trusting_results import shop # The imported model logs at INFO; an experiment logs only its warnings logging.getLogger("desflow").setLevel(logging.WARNING) EXPERIMENT = { "experiment": "demand", "question": "How sensitive is the busy hour's mean wait to the arrival rate?", "model": shop, "until": "1 h", "replications": 20, "seed": 42, "measures": ["tasks.pack_order.wait_mean"], "variants": {"three": {}, "four": {"Shop.resources.packers.current_cap": 4}}, # Each variant at each rate: 8 designs, all run with the same 20 seeds "sweep": {"Shop.arrival.orders.rate": [1.6, 1.7, 1.8, 1.9]}, "output": "results/demand", } def experiment(output=None): """Runs every design of the sweep.""" return run_experiment(EXPERIMENT, output=output) if __name__ == "__main__": for row in experiment().summary: if row["statistic"] == "tasks.pack_order.wait_mean": print(f"{row['design']}: {row['mean']:.2f} ± {row['half_width']:.2f} s") ``` ```python """The Trusting Results tutorial: the busy hour, measured after a warm-up, builder. Three packers pack orders that arrive at 1.8 a second on average, with the packing times measured at the bench. Every record is printed to the terminal. At the end the script prints the mean wait without and with the warm-up, the mean wait of 5 runs after each of three candidate warm-ups, then the mean and half-width of two outputs over 5, 10, 20 and 40 replications. To see only those lines, run: python trusting_results.py 2>/dev/null With the argument start, it runs the first 15 minutes without a warm-up, to plot: python trusting_results.py start 2>&1 """ import logging import sys from desflow import ConsoleEgress, SimulationContext, replicate from desflow.analysis import interval logging.basicConfig( level=logging.INFO, format="%(levelname)s [%(asctime)s] %(message)s" ) # The 40 packing times measured at the bench, in seconds MEASURED = [ 1.5, 2.5, 2.4, 1.2, 1.3, 1.2, 1.8, 1.4, 2.0, 0.7, 2.7, 1.4, 1.9, 1.4, 1.3, 1.8, 2.0, 1.4, 1.4, 1.9, 1.1, 0.8, 1.7, 1.1, 0.7, 1.1, 1.2, 0.9, 0.8, 1.5, 2.1, 1.3, 1.1, 1.7, 1.9, 1.3, 1.8, 2.2, 1.4, 1.1, ] # fmt: skip def shop(warmup="2 min") -> SimulationContext: """The busy hour; records and statistics start after `warmup`.""" app = ( # Records and statistics start after the first 2 minutes; None keeps everything SimulationContext(sim_id="Shop", factor=0, random_seed=42, warmup=warmup) .add_resource("packers", current_cap=3, max_cap=10) .add_arrival("orders", dist="exponential", rate=1.8) .add_service("packing", dist="empirical", values=MEASURED) # Every 10 seconds, wait_mean is the mean wait so far: plot it against sim_ts .with_stats("typical", interval=10) .add_egress(ConsoleEgress()) ) @app.task(service_id="packing", resource_id="packers") def pack_order(task_id: int): return {"event_type": "order_packed"} @app.arrival_loop("orders") def order_generator(context: SimulationContext): task_id = 0 while True: order = yield context.wait_for_arrival("orders") context.spawn(pack_order(task_id, entity=order)) task_id += 1 return app def busy_hour(warmup) -> dict: """Runs the busy hour and returns the statistics it measured.""" app = shop(warmup) app.run(until="1 h") return app.env.stats.readings() def mean_wait(warmup) -> float: """Runs the busy hour and returns the mean wait it measured.""" return busy_hour(warmup)["Shop.stats.tasks.pack_order.wait_mean"] MEASURES = ["tasks.pack_order.wait_mean", "resources.packers.utilization_avg"] def replications(n=40): """Runs the busy hour n times, each after the warm-up, with seeds spawned from 42.""" return replicate(shop, n, seed=42, until="1 h", measures=MEASURES) def warmups(n=5) -> dict: """The mean wait of n runs after each candidate warm-up, with seeds spawned from 42.""" wait = ["tasks.pack_order.wait_mean"] return { warmup: replicate(shop, n, seed=42, until="1 h", warmup=warmup, measures=wait) for warmup in ("1 min", "2 min", "4 min") } def precision(result) -> dict: """Each output's mean and half-width over the first 5, 10, 20 and 40 replications.""" return { (measure, n): interval(result.values[measure][:n]) for measure in MEASURES for n in (5, 10, 20, 40) } WAIT = "Shop.stats.tasks.pack_order.wait_mean" PACKED = "Shop.stats.tasks.pack_order.finished" QUEUE = "Shop.stats.resources.packers.queue_length_avg" def report() -> None: """Prints the mean waits, the Little's law figures and the precision.""" print(f"without a warm-up: mean wait {mean_wait(None):.3f} s") warmed = busy_hour("2 min") print(f"with a 2 min warm-up: mean wait {warmed[WAIT]:.3f} s") print( f"after the warm-up: {warmed[PACKED]} orders packed, " f"queue_length_avg {warmed[QUEUE]:.2f}" ) for warmup, result in warmups().items(): row = result.summary[0] print( f"warm-up {warmup}: mean wait {row['mean']:.3f} ± {row['half_width']:.2f} s" ) for (measure, n), result in precision(replications()).items(): share = result.half_width / result.mean print( f"{measure}, {n} runs: {result.mean:.2f} ± {result.half_width:.2f} ({share:.1%})" ) if __name__ == "__main__": if sys.argv[1:] == ["start"]: # The statistics every 10 seconds of the first 15 minutes, without a warm-up shop(None).run(until="15 min") else: report() ``` ```python """The Parameter Sweeps tutorial: the wait at four arrival rates, low-level. Runs the busy hour of Trusting Results with three packers and with four, each at four arrival rates, 20 times with the same seeds. The experiment writes its artifacts and report to results/demand, and the script prints each design's mean wait. """ import logging from desflow import LowLevelModel, run_experiment from trusting_results_low_level import WARMUP, model # The imported model logs at INFO; an experiment logs only its warnings logging.getLogger("desflow").setLevel(logging.WARNING) EXPERIMENT = { "experiment": "demand", "question": "How sensitive is the busy hour's mean wait to the arrival rate?", "model": LowLevelModel(model, sim_id="Shop"), "warmup": WARMUP, "until": 3600, "replications": 20, "seed": 42, "measures": ["tasks.pack_order.wait_mean"], "variants": {"three": {}, "four": {"Shop.resources.packers.current_cap": 4}}, # Each variant at each rate: 8 designs, all run with the same 20 seeds "sweep": {"Shop.arrival.orders.rate": [1.6, 1.7, 1.8, 1.9]}, "output": "results/demand", } def experiment(output=None): """Runs every design of the sweep.""" return run_experiment(EXPERIMENT, output=output) if __name__ == "__main__": for row in experiment().summary: if row["statistic"] == "tasks.pack_order.wait_mean": print(f"{row['design']}: {row['mean']:.2f} ± {row['half_width']:.2f} s") ``` ```python """The Trusting Results tutorial: the busy hour, measured after a warm-up, low-level. Three packers pack orders that arrive at 1.8 a second on average, with the packing times measured at the bench. Every record is printed to the terminal. At the end the script prints the mean wait without and with the warm-up, the mean wait of 5 runs after each of three candidate warm-ups, then the mean and half-width of two outputs over 5, 10, 20 and 40 replications. To see only those lines, run: python trusting_results_low_level.py 2>/dev/null With the argument start, it runs the first 15 minutes without a warm-up, to plot: python trusting_results_low_level.py start 2>&1 """ import logging import sys from desflow import ( CapacityConfig, ConsoleEgress, DistributionConfig, DynamicRealtimeEnvironment, DynamicResource, LowLevelModel, Sampler, SimParameter, replicate, ) from desflow.analysis import interval logging.basicConfig( level=logging.INFO, format="%(levelname)s [%(asctime)s] %(message)s" ) # The 40 packing times measured at the bench, in seconds MEASURED = [ 1.5, 2.5, 2.4, 1.2, 1.3, 1.2, 1.8, 1.4, 2.0, 0.7, 2.7, 1.4, 1.9, 1.4, 1.3, 1.8, 2.0, 1.4, 1.4, 1.9, 1.1, 0.8, 1.7, 1.1, 0.7, 1.1, 1.2, 0.9, 0.8, 1.5, 2.1, 1.3, 1.1, 1.7, 1.9, 1.3, 1.8, 2.2, 1.4, 1.1, ] # fmt: skip PARAMS = SimParameter( sim_id="Shop", arrival={"orders": DistributionConfig(dist="exponential", rate=1.8)}, service={"packing": DistributionConfig(dist="empirical", values=MEASURED)}, resources={"packers": CapacityConfig(current_cap=3, max_cap=10)}, ) def pack_order(env, sampler, packers, key, task_id): """One order, which reports each step to the statistics.""" path_id = "Shop.service.packing" def publish(value): env.publish_event(key, value, task="pack_order", instance=task_id) publish( {"path_id": path_id, "sim_id": "Shop", "service": "packing", "status": "queued"} ) env.stats.flow_started("orders") # the order enters the shop env.stats.task_queued("pack_order", task_id) with packers.request() as request: yield request publish( { "path_id": path_id, "sim_id": "Shop", "service": "packing", "status": "started", } ) env.stats.task_started("pack_order", task_id) yield env.timeout(sampler.sample(env.registry.get_config(path_id))) publish({"event_type": "order_packed"}) env.stats.task_finished("pack_order", task_id) env.stats.flow_finished("orders") # the order leaves the shop def order_generator(env, sampler, packers): arrival = env.registry.get_config("Shop.arrival.orders") task_id = 0 while True: yield env.timeout(sampler.sample(arrival)) env.process(pack_order(env, sampler, packers, f"orders-{task_id + 1}", task_id)) task_id += 1 # Records and statistics start after the first 2 minutes; None keeps everything WARMUP = 120.0 # seconds, passed to setup_egress in run below def run(warmup=WARMUP, until=3600, factor=0.0): env = DynamicRealtimeEnvironment(factor=factor) env.registry.register_sim_parameter(PARAMS) # Every 10 seconds, wait_mean is the mean wait so far: plot it against sim_ts env.setup_stats("Shop", "typical", interval=10) # The warm-up is set with the sinks: no sink receives a record stamped before it # ends, and the statistics start again from zero when it ends env.setup_egress([ConsoleEgress()], warmup=warmup) packers = DynamicResource(env, "Shop", "packers") env.process(order_generator(env, Sampler(seed=42), packers)) try: env.run(until=until) finally: env.teardown() return env def mean_wait(warmup) -> float: """Runs the busy hour and returns the mean wait it measured.""" return run(warmup).stats.readings()["Shop.stats.tasks.pack_order.wait_mean"] MEASURES = ["tasks.pack_order.wait_mean", "resources.packers.utilization_avg"] def model(env, sampler): """The busy hour in a given environment: replicate sets the statistics.""" env.registry.register_sim_parameter(PARAMS) packers = DynamicResource(env, "Shop", "packers") env.process(order_generator(env, sampler, packers)) def replications(n=40): """Runs the busy hour n times, each after the warm-up, with seeds spawned from 42.""" shop = LowLevelModel(model, sim_id="Shop") return replicate(shop, n, seed=42, until=3600, warmup=WARMUP, measures=MEASURES) def warmups(n=5) -> dict: """The mean wait of n runs after each candidate warm-up, with seeds spawned from 42.""" shop = LowLevelModel(model, sim_id="Shop") wait = ["tasks.pack_order.wait_mean"] return { warmup: replicate(shop, n, seed=42, until=3600, warmup=warmup, measures=wait) for warmup in (60, WARMUP, 240) } def precision(result) -> dict: """Each output's mean and half-width over the first 5, 10, 20 and 40 replications.""" return { (measure, n): interval(result.values[measure][:n]) for measure in MEASURES for n in (5, 10, 20, 40) } WAIT = "Shop.stats.tasks.pack_order.wait_mean" PACKED = "Shop.stats.tasks.pack_order.finished" QUEUE = "Shop.stats.resources.packers.queue_length_avg" def report() -> None: """Prints the mean waits, the Little's law figures and the precision.""" print(f"without a warm-up: mean wait {mean_wait(None):.3f} s") warmed = run(WARMUP).stats.readings() print(f"with a 2 min warm-up: mean wait {warmed[WAIT]:.3f} s") print( f"after the warm-up: {warmed[PACKED]} orders packed, " f"queue_length_avg {warmed[QUEUE]:.2f}" ) for warmup, result in warmups().items(): row = result.summary[0] print( f"warm-up {warmup:g} s: mean wait {row['mean']:.3f} ± {row['half_width']:.2f} s" ) for (measure, n), result in precision(replications()).items(): share = result.half_width / result.mean print( f"{measure}, {n} runs: {result.mean:.2f} ± {result.half_width:.2f} ({share:.1%})" ) if __name__ == "__main__": if sys.argv[1:] == ["start"]: # The statistics every 10 seconds of the first 15 minutes, without a warm-up run(None, until=900) else: report() ``` [Experiments](https://jaehyeon.me/desflow/latest/user-guide/results/experiments/index.md) describes every setting of an experiment, its files and its report. # Checking a Model [Comparing Designs](https://jaehyeon.me/desflow/latest/learn/studies/comparing-designs/index.md) chose a fourth packer from the busy hour model of [Trusting Results](https://jaehyeon.me/desflow/latest/learn/studies/trusting-results/index.md), and [Parameter Sweeps](https://jaehyeon.me/desflow/latest/learn/studies/parameter-sweeps/index.md) found the choice holds for rates from 1.6 to 1.9 orders a second. Both answers are only as good as the model. This page asks: **does the program do what the model on paper says, and is that model good enough to decide the number of packers?** - **Decision:** three packers or four. - **Measures:** the mean wait and the packers' [utilisation](https://jaehyeon.me/desflow/latest/learn/concepts/queueing-basics/#utilisation). - **Runs:** one run of 10 seconds with fixed inputs, then the busy hour after its 2-minute [warm-up](https://jaehyeon.me/desflow/latest/learn/concepts/output-analysis/#one-run-starts-empty), 20 replications of each design with seeds spawned from 42, and 10 replications for `desflow explain --verify`. - **Assumptions:** those of Trusting Results: orders at random at 1.8 a second, and the 40 packing times measured at the bench. ## What You Will Learn This page shows how to: - check a model against a trace worked by hand and against estimates at the extremes; - check it against Little's Law and the queueing formulas with `desflow explain --verify`; - compare it with values observed in the real shop, as tests that run again after every change. ## What You Add This page adds checks on the model, written as tests that fail when a check fails: - a run with fixed inputs, against a trace worked by hand; - runs at the extremes, against estimates made by hand; - [Little's law](https://jaehyeon.me/desflow/latest/learn/concepts/queueing-basics/#littles-law) and the queueing formulas of `desflow explain --verify`; - a comparison with values observed in the real shop; - a check that the decision still holds at a higher rate. [Checking and Validating](https://jaehyeon.me/desflow/latest/learn/concepts/checking-and-validating/index.md) explains each kind of check, and this page applies them to the shop. ______________________________________________________________________ ## Trace Fixed Inputs Replace every random input with a constant, and the run has one answer that can be worked out by hand. Here the shop has three packers, an order arrives every second, each order takes 4 seconds to pack, and the run lasts 10 seconds. Save the files from [Full Files](#full-files) in one folder and run the commands there: ```yaml # Three packers; an order arrives every second and takes 4 seconds to pack resources: packers: {current_cap: 3, max_cap: 10} arrivals: orders: {dist: constant, value: 1, spawn: pack_order} services: packing: {dist: constant, value: 4} ``` `desflow run checking_a_model.yaml` prints the 20 records of the run, which are its trace, then the statistics at 10 seconds. ```python def fixed_shop() -> SimulationContext: """Three packers, an order every second and 4 seconds to pack each, for 10 s.""" app = ( SimulationContext(sim_id="Shop", factor=0, random_seed=42) .add_resource("packers", current_cap=3, max_cap=10) .add_arrival("orders", dist="constant", value=1) .add_service("packing", dist="constant", value=4) .with_stats("typical", interval=3600) ) ``` ```python # Three packers; an order arrives every second and takes 4 seconds to pack FIXED = SimParameter( sim_id="Shop", arrival={"orders": DistributionConfig(dist="constant", value=1)}, service={"packing": DistributionConfig(dist="constant", value=4)}, resources={"packers": CapacityConfig(current_cap=3, max_cap=10)}, ) ``` The full file reuses `order_generator` and `pack_order` from Trusting Results. In them, SimPy's `env.timeout(...)` makes each gap, and `packers.request()` waits for a free packer, as [SimPy and desflow](https://jaehyeon.me/desflow/latest/simpy/#resources) describes. Worked by hand, orders arrive at 1, 2, ... 9 seconds. The first three start at once. Each later order starts when a packer becomes free, 4 seconds after that packer started its last order. The run stops at 10 seconds, before the events at that time: | Order | Arrives | Starts | Waits | Finishes | | ------- | ------- | --------- | ----- | -------- | | 1, 2, 3 | 1, 2, 3 | 1, 2, 3 | 0 | 5, 6, 7 | | 4 | 4 | 5 | 1 | 9 | | 5, 6 | 5, 6 | 6, 7 | 1 | after 10 | | 7 | 7 | 9 | 2 | after 10 | | 8, 9 | 8, 9 | not by 10 | | | By the table, **4** orders finish and **5** are still in the shop. Seven orders started packing, and all 9 that arrived count in `flows.orders.started`. The waits of the seven add up to 5 seconds, so the mean wait is 5 / 7 = **0.714** seconds, and the longest is **2** seconds. The three packers can work 3 × 10 = 30 seconds in all, and they are busy for 24 of them, **80%**. Orders 8 and 9 are still waiting at 10 seconds, after 2 seconds and 1 second, which adds 3 seconds. So the time orders spend in the queue adds up to 5 + 3 = 8 seconds. Over 10 seconds that gives an average queue of 8 ÷ 10 = **0.8** orders. The run reports the same six numbers. A difference here means a mistake in the program or in the trace worked by hand, and the mistake must be found before any experiment. ______________________________________________________________________ ## Push to the Extremes A fixed trace checks the logic, not the busy hour itself. Run the busy hour with settings whose results can be estimated without the model. The checks run as an [experiment](https://jaehyeon.me/desflow/latest/user-guide/results/experiments/index.md) on the busy hour, 20 [replications](https://jaehyeon.me/desflow/latest/learn/concepts/output-analysis/#replications) of each design: ```yaml # The busy hour of Trusting Results, with its 2-minute warm-up model: trusting_results.yaml until: 1 h replications: 20 seed: 42 measures: [tasks.pack_order.wait_mean, resources.packers.utilization_avg, resources.packers.queue_length_avg] ``` ```python # The busy hour of Trusting Results, with its 2-minute warm-up "model": shop, "until": "1 h", "replications": 20, "seed": 42, "measures": [ "tasks.pack_order.wait_mean", "resources.packers.utilization_avg", "resources.packers.queue_length_avg", ], ``` ```python # The function that builds the busy hour, and its 2-minute warm-up "model": LowLevelModel(model, sim_id="Shop"), "warmup": WARMUP, "until": 3600, "replications": 20, "seed": 42, "measures": [ "tasks.pack_order.wait_mean", "resources.packers.utilization_avg", "resources.packers.queue_length_avg", ], ``` The summary also has the task's counts, such as `tasks.pack_order.finished`, although `measures` does not name them. The designs are variants of the number of packers: ```yaml # One packer cannot keep up, and ten are mostly idle three: {} one: {Shop.resources.packers.current_cap: 1} ten: {Shop.resources.packers.current_cap: 10} ``` ```python # One packer cannot keep up, and ten are mostly idle "variants": { "three": {}, "one": {"Shop.resources.packers.current_cap": 1}, "ten": {"Shop.resources.packers.current_cap": 10}, ``` The same keys, in the same mapping as the model. Run the experiment and print the means of the two extremes: ```bash desflow experiment checking_a_model_experiment.yaml >/dev/null awk -F, '($1=="one"||$1=="ten") && $3 ~ /pack_order\.finished|utilization_avg|pack_order\.wait_mean/ {printf "%s %s %.2f\n", $1, $3, $7}' results/checking-a-model/summary.csv ``` ```text one tasks.pack_order.wait_mean 1169.71 one resources.packers.utilization_avg 100.00 one tasks.pack_order.finished 2318.10 ten tasks.pack_order.wait_mean 0.00 ten resources.packers.utilization_avg 27.00 ten tasks.pack_order.finished 6269.90 ``` ```bash python checking_a_model.py 2>/dev/null ``` The script prints the fixed run first. Then it prints one line for each extreme, and the lines of the later sections: ```text one: 2318 finished, utilisation 100.00%, mean wait 1169.71 s ten: 6270 finished, utilisation 27.00%, mean wait 0.00 s ``` ```bash python checking_a_model_low_level.py 2>/dev/null ``` It prints the same lines as the Builder script. One packer takes 1.5 seconds an order on average, so it can finish at most 3,480 ÷ 1.5 = 2,320 orders in the 3,480 seconds after the warm-up. Over the experiment's 20 replications, the one-packer design finishes **2,318** orders on average, with the packer busy **100%** of the time and a mean wait of about **1,170** seconds. Ten packers would be busy 1.8 orders a second × 1.5 seconds ÷ 10 packers = 27% of the time. The experiment measures **27.00%** on average, and the mean wait rounds to **0.00** seconds. Turn each extreme into a check, so a later change that breaks it fails. A check tests the far end of the interval, so it passes only when the whole interval is within the bound: ```yaml checks: # One packer is busy all the time: the lower end of the interval is 99.9% or more - {measure: resources.packers.utilization_avg, variant: one, min: 99.9} # With ten packers almost no order waits - {measure: tasks.pack_order.wait_mean, variant: ten, max: 0.01} ``` ```python "checks": [ # One packer is busy all the time: the lower end of the interval is 99.9% or more { "measure": "resources.packers.utilization_avg", "variant": "one", "min": 99.9, }, # With ten packers almost no order waits {"measure": "tasks.pack_order.wait_mean", "variant": "ten", "max": 0.01}, ``` The same keys, in the same mapping as the model. ______________________________________________________________________ ## Check It Against Theory Two checks compare the run with queueing theory: Little's law, which holds for any model that settles, and the formulas `desflow explain` applies where their assumptions hold. ### Little's Law [Little's law](https://jaehyeon.me/desflow/latest/learn/concepts/queueing-basics/#littles-law) says the average queue equals the arrival rate times the mean wait. The experiment measures the three separately, so they test each other. The arrival rate is the number of orders that arrived after the warm-up, `flows.orders.started`, divided by the 3,480 seconds that follow the warm-up: Print the means of `flows.orders.started`, `resources.packers.queue_length_avg` and `tasks.pack_order.wait_mean` from `summary.csv`, and multiply by hand. The arrival rate is 6269.5 ÷ 3480 = 1.8016 orders a second: ```bash awk -F, '($1=="three"||$1=="one") && $3 ~ /flows\.orders\.started|queue_length_avg|pack_order\.wait_mean/ {printf "%s %s %.3f\n", $1, $3, $7}' results/checking-a-model/summary.csv ``` ```text three tasks.pack_order.wait_mean 2.151 three resources.packers.queue_length_avg 3.882 three flows.orders.started 6269.500 one tasks.pack_order.wait_mean 1169.707 one resources.packers.queue_length_avg 2101.667 one flows.orders.started 6269.500 ``` ```python HORIZON = 3600 - 120 # the measured part of the hour, after the warm-up, in seconds def littles_law(result, design): """The mean queue, and the arrival rate and mean wait whose product it should be.""" means = {r["statistic"]: r["mean"] for r in result.summary if r["design"] == design} rate = means["flows.orders.started"] / HORIZON return ( means["resources.packers.queue_length_avg"], rate, means["tasks.pack_order.wait_mean"], ) ``` The same function, with `HORIZON = 3600 - WARMUP`. The Builder and Low-level scripts print this check as the `three:` and `one:` lines `queue 3.882, 1.8016 x 2.151 = 3.875` and `queue 2101.667, 1.8016 x 1169.707 = 2107.321`, after the lines of the extremes. Over the 20 replications with three packers, the queue averages **3.882** orders, and 1.8016 orders a second × 2.151 seconds = **3.875** orders. The two agree. With one packer they also roughly agree: a queue of **2,101.7** orders against 1.8016 × 1,169.7 = **2,107.3**. One packer's queue grows through the whole run and never settles, so its mean depends on how long the run lasts. The agreement there therefore proves less than it does for three packers. Agreement with the law shows the statistics are consistent with each other. It does not show the model is right for the shop: a model with the wrong packing times would agree just as well. ### Queueing Formulas With explain `desflow explain --verify` puts the queueing formulas beside runs of the model. It works out what the formulas give for each resource, runs the model unpaced, and marks each pair as agreeing or differing. Here it runs the busy hour of Trusting Results ten times: ```bash desflow explain trusting_results.yaml --verify --replications 10 ``` ```bash desflow explain trusting_results.yaml --verify --replications 10 ``` `context.analyze(verify=True, replications=10)` returns the same comparison for a context loaded from a blueprint, or from a builder file with `load_context`. `desflow explain` on `trusting_results.py` does not work, because that file defines no module-level `app`. Giving it one does not help: the builder file starts its orders in an `arrival_loop` function, which is code, so the formulas cannot see which task an order starts and every measure reads `not compared`. The command above uses the YAML file of Trusting Results, which is the same model with its arrivals declared. `desflow explain` does not support low-level models. It reads which arrival starts which task and which resource each task uses, and a low-level model does not declare those links: its SimPy code makes them as it runs. The end of its output: ```text Not estimated: wait at packers: no closed formula for c > 1 with non-exponential times Hints for utilisation 0.85: packers with 4 units: utilisation 0.675, at most 0.85 packers with 3 units: utilisation 0.85 at 1.7 requests a second Verify: 10 runs to 3600 s, seed 42 +--------------------------------------------------------------------------+ | node | measure | analysis | measured | ± | result | |------------+--------------+----------+----------+---------+--------------| | packers | utilization | 0.9 | 0.9 | 0.01084 | agrees | | packers | queue_length | - | 3.879 | 0.5873 | not compared | | pack_order | wait | - | 2.147 | 0.3011 | not compared | | orders | throughput | 1.8 | 1.803 | 0.02181 | agrees | +--------------------------------------------------------------------------+ Not compared: packers queue_length: no closed formula for c > 1 with non-exponential times pack_order wait: no closed formula for c > 1 with non-exponential times --verify checks the implementation against the queueing analysis where it applies; it does not show that the model is close enough to the real system ``` The utilisation of 0.9 and the throughput of 1.8 orders a second agree with the replications. `explain` and `--verify` give the utilisation as a fraction, so 0.9034 is 90.34%, while the experiment's statistics give a percentage. The measured wait, 2.147 ± 0.3011 seconds, is the mean of the 10 replications after the blueprint's 2-minute warm-up. The replications use the seeds of Trusting Results, so the figure equals that page's figure for 10 replications, as [Busy Hour Figures](https://jaehyeon.me/desflow/latest/learn/concepts/output-analysis/#busy-hour-figures) lists. The wait and the queue length have no analytical value, and the `Not estimated` line says why: three packers with measured packing times have no closed formula. For them the interval of the experiment is the check, as the next section shows. Agreement shows that the program computes what the model on paper says. It says nothing about whether the model is close enough to the real shop. [Check Against Theory](https://jaehyeon.me/desflow/latest/how-to/analysis/check-against-theory/index.md) runs the same check on a shop the formulas describe in full. ______________________________________________________________________ ## Compare With the Real Shop Only data from the real shop can show that the model is adequate. The observed values below are illustrative, and a real check uses the shop's own records. Suppose the shop recorded a mean wait of 2.6 seconds and a utilisation of 91% over 58 minutes of a busy hour with three packers. `checking_a_model_observed.csv`, in [Full Files](#full-files), holds them, with the unit, population and horizon of each, as [Experiment Results](https://jaehyeon.me/desflow/latest/user-guide/results/experiment-results/#compare-with-observed-values) describes. The experiment places each value beside the three-packer interval: ```yaml # Illustrative values for the real shop, which has three packers; # a real check reads the shop's own records observed: {file: checking_a_model_observed.csv, variant: three} ``` ```python # Illustrative values for the real shop, which has three packers; # a real check reads the shop's own records "observed": { "file": str(HERE / "checking_a_model_observed.csv"), "variant": "three", }, ``` The same key, in the same mapping as the model. The busy-hour wait with three packers and measured packing times has no closed formula in [Queueing Basics](https://jaehyeon.me/desflow/latest/learn/concepts/queueing-basics/index.md), so the model's runs are the check. Each interval below is the 95% interval of the model's mean over the 20 replications with three packers. An interval for a mean is narrow, and one observed period is not a mean: it varies about as much as one run does, so only 4 and 5 of the 20 single runs fall inside these two intervals. Compare each observed value with the standard deviation of one run instead. A value more than about two of these from the model's mean is a [disagreement](https://jaehyeon.me/desflow/latest/learn/concepts/checking-and-validating/#compare-with-the-real-shop) that the study must explain before it trusts the model for the decision: | Measure | Observed in the shop | Interval for the model's mean | Standard deviation of one run | Distance from the model's mean | Result | | ----------- | -------------------- | ----------------------------- | ----------------------------- | ------------------------------ | ------ | | Mean wait | 2.6 seconds | **2.00 to 2.30** seconds | 0.32 seconds | 1.38 standard deviations | agrees | | Utilisation | 91% | **89.39 to 90.60%** | 1.29 points | 0.78 standard deviations | agrees | Each tab prints the mean, the standard deviation of one run, the distance and the number of the 20 runs inside the interval, for the two measures: The command reads the observed values, the intervals in `summary.csv` and the 20 runs in `results.csv`: ```bash awk -F, ' FILENAME ~ /observed\.csv$/ && FNR > 1 {obs[$1] = $2; order[++k] = $1} FILENAME ~ /summary\.csv$/ && $1 == "three" {low[$3] = $9; high[$3] = $10} FILENAME ~ /results\.csv$/ && $1 == "three" && $5 in obs { n[$5]++; sum[$5] += $9; sq[$5] += $9 * $9 if ($9 >= low[$5] && $9 <= high[$5]) inside[$5]++ } END { for (i = 1; i <= k; i++) { m = order[i]; mean = sum[m] / n[m] sd = sqrt((sq[m] - n[m] * mean * mean) / (n[m] - 1)) d = obs[m] - mean; if (d < 0) d = -d printf "%s: mean %.2f, sd %.2f, distance %.2f sd, %d of %d runs inside\n", m, mean, sd, d / sd, inside[m], n[m] } }' checking_a_model_observed.csv results/checking-a-model/summary.csv results/checking-a-model/results.csv ``` ```text tasks.pack_order.wait_mean: mean 2.15, sd 0.32, distance 1.38 sd, 4 of 20 runs inside resources.packers.utilization_avg: mean 89.99, sd 1.29, distance 0.78 sd, 5 of 20 runs inside ``` ```python def agreement(result, design="three"): """For each observed value: the model's mean, the standard deviation of one run, the distance in standard deviations, and how many of the runs lie inside the interval for the mean.""" rows = [] for row in result.observed: runs = [ r["value"] for r in result.results if r["design"] == design and r["statistic"] == row["measure"] ] mean, sd = statistics.mean(runs), statistics.stdev(runs) inside = sum(row["low"] <= value <= row["high"] for value in runs) rows.append( (row["measure"], mean, sd, abs(row["value"] - mean) / sd, inside, len(runs)) ) return rows ``` The script prints one line for each measure, after the lines of the earlier sections: ```text tasks.pack_order.wait_mean: mean 2.15, sd 0.32, distance 1.38 sd, 4 of 20 runs inside resources.packers.utilization_avg: mean 89.99, sd 1.29, distance 0.78 sd, 5 of 20 runs inside ``` The same function and the same two lines, from `checking_a_model_low_level.py`. Both observed values lie outside the interval for the mean and still agree, because one observed hour is not a mean. An observed utilisation of 95% would be (95 - 89.99) ÷ 1.29 = 3.9 standard deviations away. The study would then check how the shop measured its utilisation, or whether the packing times are right. ______________________________________________________________________ ## Test the Sensitivity [Parameter Sweeps](https://jaehyeon.me/desflow/latest/learn/studies/parameter-sweeps/index.md) found that the four-packer wait stays low at every rate. Keep that as a check, so a change to the model that breaks it fails. Add a design with four packers, the chosen number, at 1.9 orders a second, about 6% above the estimate of 1.8: ```yaml # The design chosen in Comparing Designs, at a rate 6% above the estimate four-busier: {Shop.resources.packers.current_cap: 4, Shop.arrival.orders.rate: 1.9} ``` ```python # The design chosen in Comparing Designs, at a rate 6% above the estimate "four-busier": { "Shop.resources.packers.current_cap": 4, "Shop.arrival.orders.rate": 1.9, }, ``` The same keys, in the same mapping as the model. Then bound it: ```yaml # Four packers keep the mean wait under half a second at the higher rate - {measure: tasks.pack_order.wait_mean, variant: four-busier, max: 0.5} ``` ```python # Four packers keep the mean wait under half a second at the higher rate { "measure": "tasks.pack_order.wait_mean", "variant": "four-busier", "max": 0.5, }, ``` The same keys, in the same mapping as the model. At 1.9 orders a second, the mean wait with four packers is **0.34 ± 0.02** seconds over 20 replications. The upper end of its interval, 0.36 seconds, is under the bound of 0.5 seconds, so the check passes. ______________________________________________________________________ ## Run the Checks Run the checks after every change to the model, in the same way as the tests of any program. The Builder and Low-level tabs run [pytest](https://docs.pytest.org/), which desflow does not install. Run it with `uv run --with desflow --with pytest pytest checking_a_model.py`, or install it with `uv add --dev pytest` in a uv project or `pip install pytest`: ```bash desflow experiment checking_a_model_experiment.yaml ``` The command writes the results and the report, then exits with status 1 when a check fails, so a CI job that runs it fails too. After a change to the model's logic, also run `desflow run checking_a_model.yaml` and compare its statistics with the hand-worked figures in [Trace Fixed Inputs](#trace-fixed-inputs). ```python def test_fixed_inputs_match_the_hand_trace(): readings = fixed_run() assert readings["tasks.pack_order.finished"] == 4 assert readings["tasks.pack_order.in_progress"] == 5 assert readings["tasks.pack_order.wait_mean"] == 5 / 7 assert readings["tasks.pack_order.wait_max"] == 2 def test_extremes_sensitivity_and_littles_law(tmp_path): result = experiment(output=tmp_path) # a failed check raises CheckFailed queue, rate, wait = littles_law(result, "three") assert abs(queue - rate * wait) < 0.05 * queue ``` ```bash pytest checking_a_model.py ``` pytest collects the `test_` functions of a file named on its command line. `run_experiment` raises `CheckFailed` when a check fails, and the exception fails the second test. The same two tests, in the full file: ```bash pytest checking_a_model_low_level.py ``` ______________________________________________________________________ ## What You Get and Why Each value observed in the real shop beside the three-packer interval of the experiment: Does the program do what the model on paper says, and is the model good enough to decide the number of packers? The program does what the model on paper says: - The fixed run, 10 seconds with fixed inputs, matches the trace by hand: **4** orders finished, **5** still in the shop and a mean wait of **0.714** seconds. - Over the experiment's 20 replications after the 2-minute warm-up, one packer finishes **2,318** orders on average against 2,320 by hand, and ten packers are busy **27.00%** of the time against 27%. - Over the same replications, Little's law holds for three packers, with a mean queue of **3.882** orders against 3.875, and the measured utilisation agrees with the formula's 0.9. - With four packers at a rate 6% higher, the mean wait over 20 replications is **0.34 ± 0.02** seconds, and all three checks pass. The observed values are illustrative, and a real check uses the shop's own records. Against them, the mean wait of 2.6 seconds is **1.38** standard deviations of one run from the model's mean, and the utilisation of 91% is **0.78**, so both agree. Both lie outside the intervals for the mean, **2.00 to 2.30** and **89.39 to 90.60**, because those intervals are for a mean of 20 runs and not for one observed hour. The trace, the extremes, Little's law and the queueing formulas test the program against the model on paper. [Checking and Validating](https://jaehyeon.me/desflow/latest/learn/concepts/checking-and-validating/#verification-and-validation) calls these checks verification. The observed values and the sensitivity check test the model against the shop and the decision, and that page calls them validation. Written as tests, the checks run again after every change, so a model that was checked once stays checked. ## Key Takeaways - Verification checks that the program does what the model on paper says. Validation checks that the model is close enough to the real shop for the decision. - Compare one observed period with the spread of single runs, not with the interval of a mean. A value far outside that spread must be explained before the model is trusted. - Checks written as tests keep a checked model checked after every change. ______________________________________________________________________ ## Full Files Full files ```yaml # The Checking a Model tutorial: the shop with fixed inputs, to compare with a trace # worked by hand. Run it with: desflow run checking_a_model.yaml simulation: {sim_id: Shop, factor: 0, random_seed: 42} # Three packers; an order arrives every second and takes 4 seconds to pack resources: packers: {current_cap: 3, max_cap: 10} arrivals: orders: {dist: constant, value: 1, spawn: pack_order} services: packing: {dist: constant, value: 4} tasks: pack_order: service: packing resource: packers payload: {event_type: order_packed} # Every record is the trace; the statistics are published once, at the end stats: {level: typical, interval: 1 h} egress: - {type: Console} run: {until: 10} ``` ```yaml # The Checking a Model tutorial: extremes, sensitivity and the real shop, as checks. # Run it with: desflow experiment checking_a_model_experiment.yaml # It exits 1 when a check fails, after writing every file. experiment: checking-a-model question: Is the busy hour model adequate for choosing the number of packers? # The busy hour of Trusting Results, with its 2-minute warm-up model: trusting_results.yaml until: 1 h replications: 20 seed: 42 measures: [tasks.pack_order.wait_mean, resources.packers.utilization_avg, resources.packers.queue_length_avg] variants: # One packer cannot keep up, and ten are mostly idle three: {} one: {Shop.resources.packers.current_cap: 1} ten: {Shop.resources.packers.current_cap: 10} # The design chosen in Comparing Designs, at a rate 6% above the estimate four-busier: {Shop.resources.packers.current_cap: 4, Shop.arrival.orders.rate: 1.9} checks: # One packer is busy all the time: the lower end of the interval is 99.9% or more - {measure: resources.packers.utilization_avg, variant: one, min: 99.9} # With ten packers almost no order waits - {measure: tasks.pack_order.wait_mean, variant: ten, max: 0.01} # Four packers keep the mean wait under half a second at the higher rate - {measure: tasks.pack_order.wait_mean, variant: four-busier, max: 0.5} # Illustrative values for the real shop, which has three packers; # a real check reads the shop's own records observed: {file: checking_a_model_observed.csv, variant: three} output: results/checking-a-model ``` ```yaml # The Trusting Results tutorial: the busy hour, measured after a warm-up. # Run it with: desflow run trusting_results.yaml # Without the warm-up: WARMUP=0 desflow run trusting_results.yaml simulation: sim_id: Shop factor: 0 random_seed: 42 # Records and statistics start after the first 2 minutes; 0 keeps everything warmup: ${WARMUP:-2 min} resources: packers: {current_cap: 3, max_cap: 10} arrivals: orders: {dist: exponential, rate: 1.8, spawn: pack_order} services: # The 40 packing times measured at the bench, in seconds packing: dist: empirical values: [1.5, 2.5, 2.4, 1.2, 1.3, 1.2, 1.8, 1.4, 2.0, 0.7, 2.7, 1.4, 1.9, 1.4, 1.3, 1.8, 2.0, 1.4, 1.4, 1.9, 1.1, 0.8, 1.7, 1.1, 0.7, 1.1, 1.2, 0.9, 0.8, 1.5, 2.1, 1.3, 1.1, 1.7, 1.9, 1.3, 1.8, 2.2, 1.4, 1.1] tasks: pack_order: service: packing resource: packers payload: {event_type: order_packed} # Every 10 seconds, wait_mean is the mean wait so far: plot it against sim_ts stats: {level: typical, interval: 10} egress: - {type: Console} run: {until: 1 h} ``` ```text measure,value,unit,population,horizon tasks.pack_order.wait_mean,2.6,s,started instances,58 min resources.packers.utilization_avg,91.0,percent,time average,58 min ``` ```python """The Checking a Model tutorial: checks of the busy hour, written as tests, builder. A run of the shop with fixed inputs is compared with a trace worked by hand. An experiment then runs the busy hour of Trusting Results with one, three and ten packers and with four packers at a higher rate, checks each against a bound, and places the three-packer design beside the values observed in the real shop. Run the checks with: pytest checking_a_model.py """ import logging import statistics from pathlib import Path from desflow import SimulationContext, run_experiment from trusting_results import shop # The imported model logs at INFO; the checks log only their warnings logging.getLogger("desflow").setLevel(logging.WARNING) HERE = Path(__file__).resolve().parent def fixed_shop() -> SimulationContext: """Three packers, an order every second and 4 seconds to pack each, for 10 s.""" app = ( SimulationContext(sim_id="Shop", factor=0, random_seed=42) .add_resource("packers", current_cap=3, max_cap=10) .add_arrival("orders", dist="constant", value=1) .add_service("packing", dist="constant", value=4) .with_stats("typical", interval=3600) ) @app.task(service_id="packing", resource_id="packers") def pack_order(task_id: int): return {"event_type": "order_packed"} @app.arrival_loop("orders") def order_generator(context: SimulationContext): task_id = 0 while True: order = yield context.wait_for_arrival("orders") context.spawn(pack_order(task_id, entity=order)) task_id += 1 return app def fixed_run() -> dict: """The statistics of the fixed shop after 10 seconds, without the Shop.stats. prefix.""" app = fixed_shop() app.run(until=10) readings = app.env.stats.readings() return {key.removeprefix("Shop.stats."): value for key, value in readings.items()} EXPERIMENT = { "experiment": "checking-a-model", "question": "Is the busy hour model adequate for choosing the number of packers?", # The busy hour of Trusting Results, with its 2-minute warm-up "model": shop, "until": "1 h", "replications": 20, "seed": 42, "measures": [ "tasks.pack_order.wait_mean", "resources.packers.utilization_avg", "resources.packers.queue_length_avg", ], # One packer cannot keep up, and ten are mostly idle "variants": { "three": {}, "one": {"Shop.resources.packers.current_cap": 1}, "ten": {"Shop.resources.packers.current_cap": 10}, # The design chosen in Comparing Designs, at a rate 6% above the estimate "four-busier": { "Shop.resources.packers.current_cap": 4, "Shop.arrival.orders.rate": 1.9, }, }, "checks": [ # One packer is busy all the time: the lower end of the interval is 99.9% or more { "measure": "resources.packers.utilization_avg", "variant": "one", "min": 99.9, }, # With ten packers almost no order waits {"measure": "tasks.pack_order.wait_mean", "variant": "ten", "max": 0.01}, # Four packers keep the mean wait under half a second at the higher rate { "measure": "tasks.pack_order.wait_mean", "variant": "four-busier", "max": 0.5, }, ], # Illustrative values for the real shop, which has three packers; # a real check reads the shop's own records "observed": { "file": str(HERE / "checking_a_model_observed.csv"), "variant": "three", }, "output": "results/checking-a-model", } def experiment(output=None): """Runs the checks; raises CheckFailed when one fails, after writing every file.""" return run_experiment(EXPERIMENT, output=output) HORIZON = 3600 - 120 # the measured part of the hour, after the warm-up, in seconds def littles_law(result, design): """The mean queue, and the arrival rate and mean wait whose product it should be.""" means = {r["statistic"]: r["mean"] for r in result.summary if r["design"] == design} rate = means["flows.orders.started"] / HORIZON return ( means["resources.packers.queue_length_avg"], rate, means["tasks.pack_order.wait_mean"], ) def agreement(result, design="three"): """For each observed value: the model's mean, the standard deviation of one run, the distance in standard deviations, and how many of the runs lie inside the interval for the mean.""" rows = [] for row in result.observed: runs = [ r["value"] for r in result.results if r["design"] == design and r["statistic"] == row["measure"] ] mean, sd = statistics.mean(runs), statistics.stdev(runs) inside = sum(row["low"] <= value <= row["high"] for value in runs) rows.append( (row["measure"], mean, sd, abs(row["value"] - mean) / sd, inside, len(runs)) ) return rows def test_fixed_inputs_match_the_hand_trace(): readings = fixed_run() assert readings["tasks.pack_order.finished"] == 4 assert readings["tasks.pack_order.in_progress"] == 5 assert readings["tasks.pack_order.wait_mean"] == 5 / 7 assert readings["tasks.pack_order.wait_max"] == 2 def test_extremes_sensitivity_and_littles_law(tmp_path): result = experiment(output=tmp_path) # a failed check raises CheckFailed queue, rate, wait = littles_law(result, "three") assert abs(queue - rate * wait) < 0.05 * queue if __name__ == "__main__": print(fixed_run()) result = experiment() means = {(r["design"], r["statistic"]): r["mean"] for r in result.summary} for design in ("one", "ten"): print( f"{design}: {means[design, 'tasks.pack_order.finished']:.0f} finished, " f"utilisation {means[design, 'resources.packers.utilization_avg']:.2f}%, " f"mean wait {means[design, 'tasks.pack_order.wait_mean']:.2f} s" ) for design in ("three", "one"): queue, rate, wait = littles_law(result, design) print( f"{design}: queue {queue:.3f}, {rate:.4f} x {wait:.3f} = {rate * wait:.3f}" ) for row in result.observed: print(f"observed {row['measure']}: {row['value']} inside={row['inside']}") for measure, mean, sd, distance, inside, runs in agreement(result): print( f"{measure}: mean {mean:.2f}, sd {sd:.2f}, distance {distance:.2f} sd, " f"{inside} of {runs} runs inside" ) ``` ```python """The Trusting Results tutorial: the busy hour, measured after a warm-up, builder. Three packers pack orders that arrive at 1.8 a second on average, with the packing times measured at the bench. Every record is printed to the terminal. At the end the script prints the mean wait without and with the warm-up, the mean wait of 5 runs after each of three candidate warm-ups, then the mean and half-width of two outputs over 5, 10, 20 and 40 replications. To see only those lines, run: python trusting_results.py 2>/dev/null With the argument start, it runs the first 15 minutes without a warm-up, to plot: python trusting_results.py start 2>&1 """ import logging import sys from desflow import ConsoleEgress, SimulationContext, replicate from desflow.analysis import interval logging.basicConfig( level=logging.INFO, format="%(levelname)s [%(asctime)s] %(message)s" ) # The 40 packing times measured at the bench, in seconds MEASURED = [ 1.5, 2.5, 2.4, 1.2, 1.3, 1.2, 1.8, 1.4, 2.0, 0.7, 2.7, 1.4, 1.9, 1.4, 1.3, 1.8, 2.0, 1.4, 1.4, 1.9, 1.1, 0.8, 1.7, 1.1, 0.7, 1.1, 1.2, 0.9, 0.8, 1.5, 2.1, 1.3, 1.1, 1.7, 1.9, 1.3, 1.8, 2.2, 1.4, 1.1, ] # fmt: skip def shop(warmup="2 min") -> SimulationContext: """The busy hour; records and statistics start after `warmup`.""" app = ( # Records and statistics start after the first 2 minutes; None keeps everything SimulationContext(sim_id="Shop", factor=0, random_seed=42, warmup=warmup) .add_resource("packers", current_cap=3, max_cap=10) .add_arrival("orders", dist="exponential", rate=1.8) .add_service("packing", dist="empirical", values=MEASURED) # Every 10 seconds, wait_mean is the mean wait so far: plot it against sim_ts .with_stats("typical", interval=10) .add_egress(ConsoleEgress()) ) @app.task(service_id="packing", resource_id="packers") def pack_order(task_id: int): return {"event_type": "order_packed"} @app.arrival_loop("orders") def order_generator(context: SimulationContext): task_id = 0 while True: order = yield context.wait_for_arrival("orders") context.spawn(pack_order(task_id, entity=order)) task_id += 1 return app def busy_hour(warmup) -> dict: """Runs the busy hour and returns the statistics it measured.""" app = shop(warmup) app.run(until="1 h") return app.env.stats.readings() def mean_wait(warmup) -> float: """Runs the busy hour and returns the mean wait it measured.""" return busy_hour(warmup)["Shop.stats.tasks.pack_order.wait_mean"] MEASURES = ["tasks.pack_order.wait_mean", "resources.packers.utilization_avg"] def replications(n=40): """Runs the busy hour n times, each after the warm-up, with seeds spawned from 42.""" return replicate(shop, n, seed=42, until="1 h", measures=MEASURES) def warmups(n=5) -> dict: """The mean wait of n runs after each candidate warm-up, with seeds spawned from 42.""" wait = ["tasks.pack_order.wait_mean"] return { warmup: replicate(shop, n, seed=42, until="1 h", warmup=warmup, measures=wait) for warmup in ("1 min", "2 min", "4 min") } def precision(result) -> dict: """Each output's mean and half-width over the first 5, 10, 20 and 40 replications.""" return { (measure, n): interval(result.values[measure][:n]) for measure in MEASURES for n in (5, 10, 20, 40) } WAIT = "Shop.stats.tasks.pack_order.wait_mean" PACKED = "Shop.stats.tasks.pack_order.finished" QUEUE = "Shop.stats.resources.packers.queue_length_avg" def report() -> None: """Prints the mean waits, the Little's law figures and the precision.""" print(f"without a warm-up: mean wait {mean_wait(None):.3f} s") warmed = busy_hour("2 min") print(f"with a 2 min warm-up: mean wait {warmed[WAIT]:.3f} s") print( f"after the warm-up: {warmed[PACKED]} orders packed, " f"queue_length_avg {warmed[QUEUE]:.2f}" ) for warmup, result in warmups().items(): row = result.summary[0] print( f"warm-up {warmup}: mean wait {row['mean']:.3f} ± {row['half_width']:.2f} s" ) for (measure, n), result in precision(replications()).items(): share = result.half_width / result.mean print( f"{measure}, {n} runs: {result.mean:.2f} ± {result.half_width:.2f} ({share:.1%})" ) if __name__ == "__main__": if sys.argv[1:] == ["start"]: # The statistics every 10 seconds of the first 15 minutes, without a warm-up shop(None).run(until="15 min") else: report() ``` ```text measure,value,unit,population,horizon tasks.pack_order.wait_mean,2.6,s,started instances,58 min resources.packers.utilization_avg,91.0,percent,time average,58 min ``` ```python """The Checking a Model tutorial: checks of the busy hour, written as tests, low-level. A run of the shop with fixed inputs is compared with a trace worked by hand. An experiment then runs the busy hour of Trusting Results with one, three and ten packers and with four packers at a higher rate, checks each against a bound, and places the three-packer design beside the values observed in the real shop. Run the checks with: pytest checking_a_model_low_level.py """ import logging import statistics from pathlib import Path from desflow import ( CapacityConfig, DistributionConfig, DynamicRealtimeEnvironment, DynamicResource, LowLevelModel, Sampler, SimParameter, run_experiment, ) from trusting_results_low_level import WARMUP, model, order_generator # The imported model logs at INFO; the checks log only their warnings logging.getLogger("desflow").setLevel(logging.WARNING) HERE = Path(__file__).resolve().parent # Three packers; an order arrives every second and takes 4 seconds to pack FIXED = SimParameter( sim_id="Shop", arrival={"orders": DistributionConfig(dist="constant", value=1)}, service={"packing": DistributionConfig(dist="constant", value=4)}, resources={"packers": CapacityConfig(current_cap=3, max_cap=10)}, ) def fixed_run() -> dict: """The statistics of the fixed shop after 10 seconds, without the Shop.stats. prefix.""" env = DynamicRealtimeEnvironment(factor=0.0) env.registry.register_sim_parameter(FIXED) env.setup_stats("Shop", "typical", interval=3600) packers = DynamicResource(env, "Shop", "packers") env.process(order_generator(env, Sampler(seed=42), packers)) try: env.run(until=10) finally: env.teardown() readings = env.stats.readings() return {key.removeprefix("Shop.stats."): value for key, value in readings.items()} EXPERIMENT = { "experiment": "checking-a-model", "question": "Is the busy hour model adequate for choosing the number of packers?", # The function that builds the busy hour, and its 2-minute warm-up "model": LowLevelModel(model, sim_id="Shop"), "warmup": WARMUP, "until": 3600, "replications": 20, "seed": 42, "measures": [ "tasks.pack_order.wait_mean", "resources.packers.utilization_avg", "resources.packers.queue_length_avg", ], "variants": { "three": {}, "one": {"Shop.resources.packers.current_cap": 1}, "ten": {"Shop.resources.packers.current_cap": 10}, "four-busier": { "Shop.resources.packers.current_cap": 4, "Shop.arrival.orders.rate": 1.9, }, }, "checks": [ { "measure": "resources.packers.utilization_avg", "variant": "one", "min": 99.9, }, {"measure": "tasks.pack_order.wait_mean", "variant": "ten", "max": 0.01}, { "measure": "tasks.pack_order.wait_mean", "variant": "four-busier", "max": 0.5, }, ], # Illustrative values for the real shop, which has three packers; # a real check reads the shop's own records "observed": { "file": str(HERE / "checking_a_model_observed.csv"), "variant": "three", }, "output": "results/checking-a-model", } def experiment(output=None): """Runs the checks; raises CheckFailed when one fails, after writing every file.""" return run_experiment(EXPERIMENT, output=output) HORIZON = 3600 - WARMUP # the measured part of the hour, in seconds def littles_law(result, design): """The mean queue, and the arrival rate and mean wait whose product it should be.""" means = {r["statistic"]: r["mean"] for r in result.summary if r["design"] == design} rate = means["flows.orders.started"] / HORIZON return ( means["resources.packers.queue_length_avg"], rate, means["tasks.pack_order.wait_mean"], ) def agreement(result, design="three"): """For each observed value: the model's mean, the standard deviation of one run, the distance in standard deviations, and how many of the runs lie inside the interval for the mean.""" rows = [] for row in result.observed: runs = [ r["value"] for r in result.results if r["design"] == design and r["statistic"] == row["measure"] ] mean, sd = statistics.mean(runs), statistics.stdev(runs) inside = sum(row["low"] <= value <= row["high"] for value in runs) rows.append( (row["measure"], mean, sd, abs(row["value"] - mean) / sd, inside, len(runs)) ) return rows def test_fixed_inputs_match_the_hand_trace(): readings = fixed_run() assert readings["tasks.pack_order.finished"] == 4 assert readings["tasks.pack_order.in_progress"] == 5 assert readings["tasks.pack_order.wait_mean"] == 5 / 7 assert readings["tasks.pack_order.wait_max"] == 2 def test_extremes_sensitivity_and_littles_law(tmp_path): result = experiment(output=tmp_path) # a failed check raises CheckFailed queue, rate, wait = littles_law(result, "three") assert abs(queue - rate * wait) < 0.05 * queue if __name__ == "__main__": print(fixed_run()) result = experiment() means = {(r["design"], r["statistic"]): r["mean"] for r in result.summary} for design in ("one", "ten"): print( f"{design}: {means[design, 'tasks.pack_order.finished']:.0f} finished, " f"utilisation {means[design, 'resources.packers.utilization_avg']:.2f}%, " f"mean wait {means[design, 'tasks.pack_order.wait_mean']:.2f} s" ) for design in ("three", "one"): queue, rate, wait = littles_law(result, design) print( f"{design}: queue {queue:.3f}, {rate:.4f} x {wait:.3f} = {rate * wait:.3f}" ) for row in result.observed: print(f"observed {row['measure']}: {row['value']} inside={row['inside']}") for measure, mean, sd, distance, inside, runs in agreement(result): print( f"{measure}: mean {mean:.2f}, sd {sd:.2f}, distance {distance:.2f} sd, " f"{inside} of {runs} runs inside" ) ``` ```python """The Trusting Results tutorial: the busy hour, measured after a warm-up, low-level. Three packers pack orders that arrive at 1.8 a second on average, with the packing times measured at the bench. Every record is printed to the terminal. At the end the script prints the mean wait without and with the warm-up, the mean wait of 5 runs after each of three candidate warm-ups, then the mean and half-width of two outputs over 5, 10, 20 and 40 replications. To see only those lines, run: python trusting_results_low_level.py 2>/dev/null With the argument start, it runs the first 15 minutes without a warm-up, to plot: python trusting_results_low_level.py start 2>&1 """ import logging import sys from desflow import ( CapacityConfig, ConsoleEgress, DistributionConfig, DynamicRealtimeEnvironment, DynamicResource, LowLevelModel, Sampler, SimParameter, replicate, ) from desflow.analysis import interval logging.basicConfig( level=logging.INFO, format="%(levelname)s [%(asctime)s] %(message)s" ) # The 40 packing times measured at the bench, in seconds MEASURED = [ 1.5, 2.5, 2.4, 1.2, 1.3, 1.2, 1.8, 1.4, 2.0, 0.7, 2.7, 1.4, 1.9, 1.4, 1.3, 1.8, 2.0, 1.4, 1.4, 1.9, 1.1, 0.8, 1.7, 1.1, 0.7, 1.1, 1.2, 0.9, 0.8, 1.5, 2.1, 1.3, 1.1, 1.7, 1.9, 1.3, 1.8, 2.2, 1.4, 1.1, ] # fmt: skip PARAMS = SimParameter( sim_id="Shop", arrival={"orders": DistributionConfig(dist="exponential", rate=1.8)}, service={"packing": DistributionConfig(dist="empirical", values=MEASURED)}, resources={"packers": CapacityConfig(current_cap=3, max_cap=10)}, ) def pack_order(env, sampler, packers, key, task_id): """One order, which reports each step to the statistics.""" path_id = "Shop.service.packing" def publish(value): env.publish_event(key, value, task="pack_order", instance=task_id) publish( {"path_id": path_id, "sim_id": "Shop", "service": "packing", "status": "queued"} ) env.stats.flow_started("orders") # the order enters the shop env.stats.task_queued("pack_order", task_id) with packers.request() as request: yield request publish( { "path_id": path_id, "sim_id": "Shop", "service": "packing", "status": "started", } ) env.stats.task_started("pack_order", task_id) yield env.timeout(sampler.sample(env.registry.get_config(path_id))) publish({"event_type": "order_packed"}) env.stats.task_finished("pack_order", task_id) env.stats.flow_finished("orders") # the order leaves the shop def order_generator(env, sampler, packers): arrival = env.registry.get_config("Shop.arrival.orders") task_id = 0 while True: yield env.timeout(sampler.sample(arrival)) env.process(pack_order(env, sampler, packers, f"orders-{task_id + 1}", task_id)) task_id += 1 # Records and statistics start after the first 2 minutes; None keeps everything WARMUP = 120.0 # seconds, passed to setup_egress in run below def run(warmup=WARMUP, until=3600, factor=0.0): env = DynamicRealtimeEnvironment(factor=factor) env.registry.register_sim_parameter(PARAMS) # Every 10 seconds, wait_mean is the mean wait so far: plot it against sim_ts env.setup_stats("Shop", "typical", interval=10) # The warm-up is set with the sinks: no sink receives a record stamped before it # ends, and the statistics start again from zero when it ends env.setup_egress([ConsoleEgress()], warmup=warmup) packers = DynamicResource(env, "Shop", "packers") env.process(order_generator(env, Sampler(seed=42), packers)) try: env.run(until=until) finally: env.teardown() return env def mean_wait(warmup) -> float: """Runs the busy hour and returns the mean wait it measured.""" return run(warmup).stats.readings()["Shop.stats.tasks.pack_order.wait_mean"] MEASURES = ["tasks.pack_order.wait_mean", "resources.packers.utilization_avg"] def model(env, sampler): """The busy hour in a given environment: replicate sets the statistics.""" env.registry.register_sim_parameter(PARAMS) packers = DynamicResource(env, "Shop", "packers") env.process(order_generator(env, sampler, packers)) def replications(n=40): """Runs the busy hour n times, each after the warm-up, with seeds spawned from 42.""" shop = LowLevelModel(model, sim_id="Shop") return replicate(shop, n, seed=42, until=3600, warmup=WARMUP, measures=MEASURES) def warmups(n=5) -> dict: """The mean wait of n runs after each candidate warm-up, with seeds spawned from 42.""" shop = LowLevelModel(model, sim_id="Shop") wait = ["tasks.pack_order.wait_mean"] return { warmup: replicate(shop, n, seed=42, until=3600, warmup=warmup, measures=wait) for warmup in (60, WARMUP, 240) } def precision(result) -> dict: """Each output's mean and half-width over the first 5, 10, 20 and 40 replications.""" return { (measure, n): interval(result.values[measure][:n]) for measure in MEASURES for n in (5, 10, 20, 40) } WAIT = "Shop.stats.tasks.pack_order.wait_mean" PACKED = "Shop.stats.tasks.pack_order.finished" QUEUE = "Shop.stats.resources.packers.queue_length_avg" def report() -> None: """Prints the mean waits, the Little's law figures and the precision.""" print(f"without a warm-up: mean wait {mean_wait(None):.3f} s") warmed = run(WARMUP).stats.readings() print(f"with a 2 min warm-up: mean wait {warmed[WAIT]:.3f} s") print( f"after the warm-up: {warmed[PACKED]} orders packed, " f"queue_length_avg {warmed[QUEUE]:.2f}" ) for warmup, result in warmups().items(): row = result.summary[0] print( f"warm-up {warmup:g} s: mean wait {row['mean']:.3f} ± {row['half_width']:.2f} s" ) for (measure, n), result in precision(replications()).items(): share = result.half_width / result.mean print( f"{measure}, {n} runs: {result.mean:.2f} ± {result.half_width:.2f} ({share:.1%})" ) if __name__ == "__main__": if sys.argv[1:] == ["start"]: # The statistics every 10 seconds of the first 15 minutes, without a warm-up run(None, until=900) else: report() ``` ```text measure,value,unit,population,horizon tasks.pack_order.wait_mean,2.6,s,started instances,58 min resources.packers.utilization_avg,91.0,percent,time average,58 min ``` # Complete Model Each earlier page added one idea to the shop and answered one question. This page carries out a whole study, from the shop's own records to a recommendation, in the steps of [A Simulation Study](https://jaehyeon.me/desflow/latest/learn/concepts/a-simulation-study/index.md). In the busy hour the shop has one picker and three packers, and it can hire one more person, as a second picker or a fourth packer. This page asks: **which shop design should be recommended?** - **Decision:** today's shop, a second picker or a fourth packer. The rule: recommend the design in which the upper end of the [95% interval](https://jaehyeon.me/desflow/latest/learn/concepts/output-analysis/#interval-and-half-width) of both mean waits is under 1 second. - **Measures:** the mean wait for picking and the mean wait for packing, over the orders that start each step after a [warm-up](https://jaehyeon.me/desflow/latest/learn/concepts/output-analysis/#one-run-starts-empty), which [Choose Warm-up and Precision](#choose-warm-up-and-precision) sets at 2 minutes. - **Runs:** one busy hour, from an order's arrival to its shipment, with the shelf of shipping boxes and its deliveries. Each design runs 40 replications with the same seeds, spawned from 42. Before that, `desflow explain --verify` runs 10 replications, and [Choose Warm-up and Precision](#choose-warm-up-and-precision) runs today's design 40 times after each of three warm-ups. - **Assumptions:** orders arrive at random at a steady rate, the picker and the packers work the whole hour, and each order is one parcel in one box. ## What You Will Learn This page shows how to: - carry out a whole study, from the shop's records to a recommendation; - use `desflow fit`, `desflow explain --verify`, an experiment and `desflow report` in the order of a study; - state a decision rule and recommend the design that meets it. ## What You Add This page adds no new feature. The study uses the built-in commands of the earlier pages, in the order of a study: 1. `desflow fit`, from [Fitting the Inputs](https://jaehyeon.me/desflow/latest/learn/inputs/fit-the-inputs/index.md), fits the inputs to the records. 1. `desflow explain --verify`, from [Checking a Model](https://jaehyeon.me/desflow/latest/learn/studies/checking-a-model/index.md), checks the program against the queueing formulas. 1. An experiment, as in [Comparing Designs](https://jaehyeon.me/desflow/latest/learn/studies/comparing-designs/index.md), compares the model with values observed in the shop, measures each design with the same seeds and checks the decision rule. 1. `desflow report` writes the report. The model puts picking before packing, as in [A Flow of Tasks](https://jaehyeon.me/desflow/latest/learn/shop-logic/flow-of-tasks/index.md), and adds a shelf of boxes, from which each order takes one, as in [Stock](https://jaehyeon.me/desflow/latest/learn/shop-logic/stock/index.md). Fitting needs the `fit` extra, which adds scipy and matplotlib: ```bash # desflow command, with uv uv tool install "desflow[fit]" # A Python file, with uv outside a project uv run --with "desflow[fit]" python complete_model.py # In a uv project uv add "desflow[fit]" # With pip pip install "desflow[fit]" ``` ______________________________________________________________________ ## Fit the Inputs For each of 300 orders in a busy hour, the shop recorded the gap since the order before, the time to pick the order and the time to pack it, in seconds. [`complete_model_observed.csv`](https://raw.githubusercontent.com/jaehyeon-kim/desflow/v1.3.0/docs/snippets/tutorials/complete_model_observed.csv) holds them. The values are illustrative, and a real study uses the shop's own records. Save the files from [Full Files](#full-files) in one folder, download the records into it, and run the commands there: ```bash # The observed gaps, picking times and packing times curl -O https://raw.githubusercontent.com/jaehyeon-kim/desflow/v1.3.0/docs/snippets/tutorials/complete_model_observed.csv ``` Fit each column, with no time below 0: ```bash # Fit each column and write its best fit to a file desflow fit complete_model_observed.csv --column gap_seconds --lower 0 --out fitted/complete_orders.yaml desflow fit complete_model_observed.csv --column picking_seconds --lower 0 --out fitted/complete_picking.yaml desflow fit complete_model_observed.csv --column packing_seconds --lower 0 --out fitted/complete_packing.yaml ``` ```python with OBSERVED.open(newline="", encoding="utf-8") as handle: rows = list(csv.DictReader(handle)) columns = { "orders": "gap_seconds", "picking": "picking_seconds", "packing": "packing_seconds", } # Every column is in seconds, and no time can be below 0 return { name: fit_column([float(row[column]) for row in rows], unit="s", lower=0) for name, column in columns.items() } ``` ```python with OBSERVED.open(newline="", encoding="utf-8") as handle: rows = list(csv.DictReader(handle)) columns = { "orders": "gap_seconds", "picking": "picking_seconds", "packing": "packing_seconds", } # Every column is in seconds, and no time can be below 0 return { name: fit_column([float(row[column]) for row in rows], unit="s", lower=0) for name, column in columns.items() } ``` The best fit of each column, as `desflow fit` wrote it: ```yaml # Fitted by desflow fit from complete_model_observed.csv, column gap_seconds: # exponential, from 300 values in s, written in seconds. dist: exponential rate: 1.50719 ``` ```yaml # Fitted by desflow fit from complete_model_observed.csv, column picking_seconds: gamma, # from 300 values in s, written in seconds. dist: gamma shape: 4.01421 scale: 0.110615 ``` ```yaml # Fitted by desflow fit from complete_model_observed.csv, column packing_seconds: gamma, # from 300 values in s, written in seconds. dist: gamma shape: 8.56765 scale: 0.204467 ``` Each fit also comes with its diagnostics. The table `desflow fit` prints for the packing times: ```text 300 rows: 300 used, 0 missing, 0 invalid family status AIC KS stat KS p (approx.) parameters or reason exponential rejected its std is 1.752, the data's is 0.5887: more than 25% apart normal fitted 537.5 0.05413 0.3311 mean=1.7518, std=0.588695 (can draw below the lower bound 0) lognormal fitted 534.3 0.0501 0.4248 mean=1.75783, std=0.643777 truncated_normal fitted 536.5 0.05303 0.3552 mean=1.74874, std=0.593237, low=0 constant skipped the values are not all equal uniform rejected its std is 0.9093, the data's is 0.5887: more than 25% apart triangular fitted 546.3 0.1169 0.0004971 low=0.465992, mode=1.41, high=3.71725 gamma * fitted 523.3 0.02959 0.9484 shape=8.56765, scale=0.204467 weibull fitted 534.9 0.05002 0.427 shape=3.1729, scale=1.95579 empirical fitted values: 300 numbers * best: gamma ``` The gamma has the lowest [AIC](https://jaehyeon.me/desflow/latest/learn/concepts/a-simulation-study/#aic-and-the-ks-test), and its KS p-value of 0.9484 gives no reason to reject it. [AIC and the KS Test](https://jaehyeon.me/desflow/latest/learn/concepts/a-simulation-study/#aic-and-the-ks-test) explains both scores. The same tables give a KS p-value of 0.995 for the exponential of the gaps and 0.634 for the gamma of the picking times. The gaps fit an exponential distribution at about 1.5 orders a second, which is the distribution of the gaps between orders placed independently of each other. The picking and packing times each fit a gamma distribution, with means of about 0.44 and 1.75 seconds, close to the means of the data. These are inputs: the fit says which distribution draws times like the recorded ones. Whether the model then behaves like the shop is a separate question, answered by its outputs below. The model reads the fits in place of the times: ```yaml arrivals: # The fitted gaps between orders; each order starts with picking orders: !include {file: fitted/complete_orders.yaml, spawn: pick_order} # A delivery of 1,000 boxes every 10 minutes deliveries: {dist: constant, value: 10 min, spawn: restock} services: # The fitted picking and packing times picking: !include fitted/complete_picking.yaml packing: !include fitted/complete_packing.yaml ``` The fitted file of the gaps holds only a distribution, and an arrival also needs its `spawn`. `!include {file: ..., spawn: pick_order}` reads the file and adds the other keys to it. [Input Fitting](https://jaehyeon.me/desflow/latest/user-guide/model-parts/input-fitting/index.md) describes both forms of `!include`. ```python # The fitted gaps between orders; each order starts with picking .add_arrival("orders", **FITS["orders"], spawn="pick_order") # A delivery of 1,000 boxes every 10 minutes .add_arrival("deliveries", dist="constant", value=600, spawn="restock") # The fitted picking and packing times .add_service("picking", **FITS["picking"]) .add_service("packing", **FITS["packing"]) ``` `FITS` holds `result.settings()` of each fit. It holds the same numbers as the fitted files that the blueprint reads, so the builder draws the same values as the blueprint. ```python PARAMS = SimParameter( sim_id="Shop", arrival={ # The fitted gaps between orders "orders": DistributionConfig(**FITS["orders"]), # A delivery of 1,000 boxes every 10 minutes "deliveries": DistributionConfig(dist="constant", value=600), }, # The fitted picking and packing times service={ "picking": DistributionConfig(**FITS["picking"]), "packing": DistributionConfig(**FITS["packing"]), }, # One picker and three packers, as the shop has today resources={ "pickers": CapacityConfig(current_cap=1, max_cap=4), "packers": CapacityConfig(current_cap=3, max_cap=10), }, # Shipping boxes: 1,000 on the shelf at the start, and room for 2,000 containers={"stock": ContainerConfig(current_cap=2000, max_cap=2000, level=1000)}, ) ``` ______________________________________________________________________ ## Build the Model The shop has one picker, three packers and a shelf of shipping boxes: ```yaml resources: # One picker and three packers, as the shop has today pickers: {current_cap: 1, max_cap: 4} packers: {current_cap: 3, max_cap: 10} containers: # Shipping boxes: 1,000 on the shelf at the start, and room for 2,000 stock: {current_cap: 2000, max_cap: 2000, level: 1000} ``` ```python # One picker and three packers, as the shop has today .add_resource("pickers", current_cap=1, max_cap=4) .add_resource("packers", current_cap=3, max_cap=10) # Shipping boxes: 1,000 on the shelf at the start, and room for 2,000 .add_container("stock", current_cap=2000, max_cap=2000, level=1000) ``` The resources and the shelf are in `PARAMS` above. Each order is picked, then packed, then shipped in a box from the shelf. A delivery puts 1,000 boxes on the shelf every 10 minutes: ```yaml tasks: pick_order: service: picking resource: pickers payload: {event_type: order_picked} next: pack_order pack_order: service: packing resource: packers payload: {event_type: order_packed} next: ship_order ship_order: # Each parcel leaves in a box from the shelf; waits while the shelf is empty get: {container: stock, amount: 1} payload: {event_type: order_shipped} restock: put: {container: stock, amount: 1000} payload: {event_type: stock_delivered} ``` ```python @app.task(service_id="picking", resource_id="pickers", next="pack_order") def pick_order(task_id: int): return {"event_type": "order_picked"} @app.task(service_id="packing", resource_id="packers", next="ship_order") def pack_order(task_id: int): return {"event_type": "order_packed"} # Each parcel leaves in a box from the shelf; waits while the shelf is empty @app.task(get={"container": "stock", "amount": 1}) def ship_order(task_id: int): return {"event_type": "order_shipped"} @app.task(put={"container": "stock", "amount": 1000}) def restock(task_id: int): return {"event_type": "stock_delivered"} ``` ```python # Each task's service, resource and the task after it; None where it has none TASKS = { "pick_order": ("picking", "pickers", "pack_order"), "pack_order": ("packing", "packers", "ship_order"), "ship_order": (None, None, None), } EVENTS = { "pick_order": "order_picked", "pack_order": "order_packed", "ship_order": "order_shipped", } def task(env, sampler, shop, name, key, task_id, counters): """Runs one task of an order, then the task after it, in the same process.""" service, resource, following = TASKS[name] status = ( {"path_id": f"Shop.service.{service}", "sim_id": "Shop", "service": service} if service else {} ) def publish(value): env.publish_event(key, value, task=name, instance=task_id) if name == "pick_order": env.stats.flow_started("orders") # the order enters the shop publish({**status, "status": "queued"}) env.stats.task_queued(name, task_id) if resource is not None: with shop[resource].request() as request: yield request publish({**status, "status": "started"}) env.stats.task_started(name, task_id) yield env.timeout( sampler.sample(env.registry.get_config(status["path_id"])) ) publish({"event_type": EVENTS[name]}) env.stats.task_finished(name, task_id) else: # Each parcel leaves in a box from the shelf; waits while the shelf is empty yield shop["stock"].get(1) publish({"status": "started"}) env.stats.task_started(name, task_id) publish({"event_type": EVENTS[name]}) env.stats.task_finished(name, task_id) if following is None: env.stats.flow_finished("orders") # the order leaves the shop return instance = next(counters[following]) yield from task(env, sampler, shop, following, key, instance, counters) def restock(env, shop, key, task_id): """One delivery: 1,000 boxes onto the shelf, waiting while there is no room.""" env.stats.flow_started("deliveries") yield shop["stock"].put(1000) env.publish_event( key, {"event_type": "stock_delivered"}, task="restock", instance=task_id ) env.stats.task_finished("restock", task_id) env.stats.flow_finished("deliveries") ``` `shop["stock"].get(1)` and `put(1000)` are SimPy's container operations, which [Stock](https://jaehyeon.me/desflow/latest/learn/shop-logic/stock/index.md) introduced. `get` waits until the shelf holds a box, and `put` waits until the shelf has room for the boxes. The three tabs publish the same records. The model keeps the `typical` statistics, so each task has a mean wait and each resource a [utilisation](https://jaehyeon.me/desflow/latest/learn/concepts/queueing-basics/#utilisation). ______________________________________________________________________ ## Check the Model A model is checked twice before it answers anything: against the model on paper, which is verification, and against the shop, which is validation ([Checking and Validating](https://jaehyeon.me/desflow/latest/learn/concepts/checking-and-validating/#verification-and-validation)). ### Against Theory `desflow explain --verify` puts the queueing formulas beside 10 replications of the model: ```bash desflow explain complete_model.yaml --verify --replications 10 ``` ```bash desflow explain complete_model.py --verify --until "1 h" --replications 10 ``` `explain` reads the one `SimulationContext` the file defines at module level, `app`. A builder file has no `run.until`, so `--until` gives the length of each run. `desflow explain` does not support low-level models. It reads which arrival starts which task and which resource each task uses, and a low-level model does not declare those links: its SimPy code makes them as it runs. The resources, what is not estimated, and the comparison: ```text Resources +---------------------------------------------------------------------+ | resource | λ | μ | c | ρ | Wq | L | status | |----------+-------+--------+---+--------+--------+-------+-----------| | pickers | 1.507 | 2.252 | 1 | 0.6692 | 0.5611 | 1.515 | OK | | packers | 1.507 | 0.5708 | 3 | 0.8801 | - | - | CONGESTED | +---------------------------------------------------------------------+ Bottleneck: packers Not estimated: task ship_order: it has get, which the formulas leave out task restock: it has put, which the formulas leave out wait at packers: no closed formula for c > 1 with non-exponential times container stock: no queueing analysis for a container Verify: 10 runs to 3600 s, seed 42 +---------------------------------------------------------------------------+ | node | measure | analysis | measured | ± | result | |------------+--------------+----------+----------+----------+--------------| | pickers | utilization | 0.6692 | 0.6745 | 0.009403 | agrees | | pickers | queue_length | 0.8457 | 0.8899 | 0.06531 | agrees | | packers | utilization | 0.8801 | 0.8827 | 0.01191 | agrees | | packers | queue_length | - | 2.789 | 0.3652 | not compared | | pick_order | wait | 0.5611 | 0.5886 | 0.03728 | agrees | | pack_order | wait | - | 1.842 | 0.2238 | not compared | | orders | throughput | - | 1.51 | 0.01979 | not compared | | deliveries | throughput | - | 0.001437 | 0 | not compared | +---------------------------------------------------------------------------+ Not compared: packers queue_length: no closed formula for c > 1 with non-exponential times pack_order wait: no closed formula for c > 1 with non-exponential times orders throughput: task ship_order: it has get, which the formulas leave out deliveries throughput: task restock: it has put, which the formulas leave out --verify checks the implementation against the queueing analysis where it applies; it does not show that the model is close enough to the real system ``` The comparison covers only the parts the formulas describe: - The picker is one server, and the orders reach it directly, with exponential gaps. For such a server [Kingman's formula](https://jaehyeon.me/desflow/latest/learn/concepts/queueing-basics/#variation-lengthens-waits) gives the wait exactly, and the utilisation, the queue and the wait all agree with the runs. - The packers' utilisation agrees too, and at a utilisation of 0.88 they are the [bottleneck](https://jaehyeon.me/desflow/latest/learn/concepts/queueing-basics/#flow-balance-and-the-bottleneck). - Three packers with gamma times are outside the formulas' assumptions, so their wait has no closed formula, and only the runs measure it. - The shipping step takes a box from the shelf, which the formulas leave out, so the orders' throughput is not compared either. Agreement shows that the program computes what the model on paper says. It says nothing about whether the model is close enough to the shop. ### Against the Shop Suppose the shop also measured, over the busy hour after its first 2 minutes, a mean wait of 0.57 seconds for picking, 1.9 seconds for packing, and the packers busy 88% of the time. `complete_model_outputs.csv`, in [Full Files](#full-files), holds these values, with the unit, population and horizon of each. They were chosen by hand to be close to the model's means for today's design. The page shows the method, not evidence about a real shop. The experiment run in [Compare the Designs](#compare-the-designs) places each beside the interval of today's design, `current`: ```yaml # Values made from the model's own runs to show the method, not shop records; # the real shop runs the current design observed: {file: complete_model_outputs.csv, variant: current} ``` ```python # Values made from the model's own runs to show the method, not shop records; # the real shop runs the current design "observed": { "file": str(HERE / "complete_model_outputs.csv"), "variant": "current", }, ``` The same key, in the same mapping as the model below. Only one of the three values lies inside the model's interval for its mean: 88 inside **87.37 to 88.15**. The picking wait of 0.57 seconds is just above **0.538 to 0.569**, and the packing wait of 1.9 seconds is above **1.63 to 1.84**. An interval for a mean is narrow, and one observed hour is not a mean. One observed hour varies as much as one run does. Across the 40 replications of `current`, the standard deviation of one run is: - 0.049 seconds for the picking wait; - 0.325 seconds for the packing wait; - 1.214 percentage points for the packers' utilisation. Only 12, 8 and 7 of the 40 single runs fall inside the three intervals. A real observed hour can therefore fall outside an interval while the model is right. For this reason a study compares the observed value with the spread of single runs instead. Here each observed value lies within one such standard deviation of the model's mean: 0.57 is 0.34 standard deviations from it, 1.9 is 0.51 and 88 is 0.2. ______________________________________________________________________ ## Choose Warm-up and Precision Each run starts with the shop empty. The real busy hour does not start empty, because orders are already in the shop when it starts. The study therefore treats the hour as [steady state](https://jaehyeon.me/desflow/latest/learn/concepts/output-analysis/#terminating-or-steady-state) and leaves out the empty start. Run today's design 40 times after three candidate warm-ups and compare the mean waits: ```bash # 40 runs with no warm-up: the mean picking and packing waits WARMUP=0 desflow run complete_model.yaml --replications 40 --measure tasks.pick_order.wait_mean --measure tasks.pack_order.wait_mean ``` `WARMUP="10 min"` runs the third candidate, and the file's own setting of 2 minutes is the second. ```python return { warmup: replicate(shop, 40, seed=42, until="1 h", warmup=warmup, measures=WAITS) for warmup in (0, "2 min", "10 min") } ``` ```python return { warmup: replicate(SHOP, 40, seed=42, until=3600, warmup=warmup, measures=WAITS) for warmup in (0, WARMUP, 600) } ``` The mean waits over the 40 replications, in seconds, with the 95% half-width: | Warm-up | Picking | Packing | | ---------- | ------------- | ------------- | | none | 0.553 ± 0.015 | 1.718 ± 0.103 | | 2 minutes | 0.553 ± 0.016 | 1.733 ± 0.104 | | 10 minutes | 0.550 ± 0.016 | 1.699 ± 0.104 | Without a warm-up, the mean packing wait is 0.015 seconds lower than with 2 minutes, well inside the half-width. A warm-up of 10 minutes gives means within 0.04 seconds of those with 2 minutes, also well inside the half-width. Every candidate therefore passes the comparison. The rule of [Output Analysis](https://jaehyeon.me/desflow/latest/learn/concepts/output-analysis/#one-run-starts-empty) also needs the warm-up to cover the climb in a plot of the start. This shop has no plot of its own. Its packers are about as busy as those of [Trusting Results](https://jaehyeon.me/desflow/latest/learn/studies/trusting-results/#plot-the-start), 88% of the time against 90%, and that page's plot first climbs for about a minute. The study therefore keeps 2 minutes. The comparison holds for this shop and this hour only, and a busier shop or another horizon needs it run again. The precision the decision needs is set by the rule: each interval must lie wholly on one side of 1 second. With 40 replications of each design, the experiment below gives half-widths of at most 0.11 seconds for the picking and packing waits. The interval nearest the bound, that of the fourth packer's picking wait, ends at **0.57** seconds. Every interval is far from 1 second, so 40 replications are enough. A design whose interval crossed 1 second would need more replications before it could be decided ([How Many Replications](https://jaehyeon.me/desflow/latest/learn/concepts/output-analysis/#how-many-replications)). ______________________________________________________________________ ## Compare the Designs The experiment runs each design 40 times, with the measures of the decision and of the checks: ```yaml # The busy hour, with its 2-minute warm-up; 40 runs of each design model: complete_model.yaml until: 1 h replications: 40 seed: 42 measures: [tasks.pick_order.wait_mean, tasks.pack_order.wait_mean, resources.packers.utilization_avg, tasks.ship_order.wait_mean] ``` ```python # The busy hour, with its 2-minute warm-up; 40 replications of each design "model": shop, "until": "1 h", "replications": 40, "seed": 42, "measures": [ "tasks.pick_order.wait_mean", "tasks.pack_order.wait_mean", "resources.packers.utilization_avg", "tasks.ship_order.wait_mean", ], ``` ```python # The busy hour as a LowLevelModel, and its 2-minute warm-up "model": SHOP, "warmup": WARMUP, "until": 3600, "replications": 40, "seed": 42, "measures": [ "tasks.pick_order.wait_mean", "tasks.pack_order.wait_mean", "resources.packers.utilization_avg", "tasks.ship_order.wait_mean", ], ``` Each design changes one capacity, and every design runs with the same seeds, so each is compared with today's shop seed by seed: ```yaml # Every design runs with the same seeds, so they are compared seed by seed pairing: common compare: - {baseline: current, variant: second-picker} - {baseline: current, variant: fourth-packer} variants: current: {} second-picker: {Shop.resources.pickers.current_cap: 2} fourth-packer: {Shop.resources.packers.current_cap: 4} ``` ```python # Every design runs with the same seeds, so they are compared seed by seed "pairing": "common", "compare": [ {"baseline": "current", "variant": "second-picker"}, {"baseline": "current", "variant": "fourth-packer"}, ], "variants": { "current": {}, "second-picker": {"Shop.resources.pickers.current_cap": 2}, "fourth-packer": {"Shop.resources.packers.current_cap": 4}, ``` The same keys, in the same mapping as the model. The checks state the decision rule for the recommended design, and that no order waits for a box in any of the three designs: ```yaml checks: # The recommended design: the upper end of each wait's interval is under 1 second - {measure: tasks.pick_order.wait_mean, variant: fourth-packer, max: 1} - {measure: tasks.pack_order.wait_mean, variant: fourth-packer, max: 1} # In each of the three designs, no order waits for a shipping box - {measure: tasks.ship_order.wait_mean, variant: current, max: 0} - {measure: tasks.ship_order.wait_mean, variant: second-picker, max: 0} - {measure: tasks.ship_order.wait_mean, variant: fourth-packer, max: 0} ``` ```python "checks": [ # The recommended design: the upper end of each wait's interval is under 1 s {"measure": "tasks.pick_order.wait_mean", "variant": "fourth-packer", "max": 1}, {"measure": "tasks.pack_order.wait_mean", "variant": "fourth-packer", "max": 1}, # In each of the three designs, no order waits for a shipping box {"measure": "tasks.ship_order.wait_mean", "variant": "current", "max": 0}, {"measure": "tasks.ship_order.wait_mean", "variant": "second-picker", "max": 0}, {"measure": "tasks.ship_order.wait_mean", "variant": "fourth-packer", "max": 0}, ``` The same key, in the same mapping as the model. Run it: ```bash desflow experiment complete_model_experiment.yaml ``` ```bash python complete_model.py ``` ```bash python complete_model_low_level.py ``` The table gives each design's mean waits over its 40 replications, in seconds, and the packers' utilisation in percent, with the 95% half-width: | Design | Picking wait | Packing wait | Packers busy | | ------------- | ------------ | ------------ | ------------ | | current | 0.55 ± 0.02 | 1.73 ± 0.10 | 87.76 ± 0.39 | | second-picker | 0.04 ± 0.00 | 1.98 ± 0.11 | 87.76 ± 0.39 | | fourth-packer | 0.55 ± 0.02 | 0.15 ± 0.01 | 65.83 ± 0.29 | Only the fourth packer keeps both waits under 1 second. Seed by seed, it cuts the packing wait by **1.58 ± 0.10** seconds and leaves the picking wait as it was. A second picker cuts the picking wait by 0.52 ± 0.01 seconds but lengthens the packing wait by 0.25 ± 0.01 seconds. One picker passes orders on one at a time, with at least one picking time between them. Two pickers pass orders on closer together, nearer the times they arrive, so more orders find all three packers busy. `explain` named the packers as the bottleneck, and the experiment measures how much each design changes the wait there. Every design draws from the same three random streams, `arrival.orders`, `service.packing` and `service.picking`, and the constant deliveries draw from none. Every difference is therefore [paired](https://jaehyeon.me/desflow/latest/learn/concepts/output-analysis/#comparing-designs). In none of the three designs did an order wait for a box, so the shelf does not limit the answer. ### Test the Sensitivity The recommendation rests on the fitted arrival rate of 1.50719 orders a second. The rate is fitted from 300 gaps. Its standard error is the standard deviation of the fitted rate over repeated samples. For an exponential fit, the standard error is about the rate ÷ √n for n gaps, so here it is about 1/√300 of the rate, about 6%. A 95% interval for the rate reaches about 1.96 standard errors either side, about 11%, so the data cannot rule out a rate 10% higher. The experiment therefore also runs the fourth packer with orders 10% faster, at 1.65791 orders a second. The new variant is a test of the recommendation, not a design to recommend: ```yaml # The recommended design, with orders 10% faster than the fitted rate of 1.50719 fourth-packer-busier: Shop.resources.packers.current_cap: 4 Shop.arrival.orders.rate: 1.65791 ``` ```python # The recommended design, with orders 10% faster than the fitted rate of 1.50719 "fourth-packer-busier": { "Shop.resources.packers.current_cap": 4, "Shop.arrival.orders.rate": 1.65791, }, ``` The same keys, in the same mapping as the model. A sixth and a seventh check state that both waits stay under 1 second: ```yaml # With orders 10% faster, the fourth packer keeps both waits under 1 second - {measure: tasks.pick_order.wait_mean, variant: fourth-packer-busier, max: 1} - {measure: tasks.pack_order.wait_mean, variant: fourth-packer-busier, max: 1} ``` ```python # With orders 10% faster, the fourth packer keeps both waits under 1 s { "measure": "tasks.pick_order.wait_mean", "variant": "fourth-packer-busier", "max": 1, }, { "measure": "tasks.pack_order.wait_mean", "variant": "fourth-packer-busier", "max": 1, }, ``` The same key, in the same mapping as the model. With orders 10% faster, the mean picking wait over the 40 replications is **0.76 ± 0.02** seconds, the mean packing wait **0.23 ± 0.01** seconds, and the packers are busy 72.44 ± 0.31% of the time. Both upper ends stay under 1 second, at 0.78 and 0.24 seconds, so the sixth and seventh checks pass. The variant shows something the three designs did not: orders now wait for shipping boxes, 0.14 ± 0.17 seconds on average. In 22 of the 40 replications some orders waited for a box, and the highest mean wait of one run was 3.41 seconds. A delivery of 1,000 boxes every 10 minutes is 1.67 boxes a second, only just above 1.66 orders a second. Orders arrive at random, so in some periods they take boxes faster than the deliveries replace them, and the shelf is empty before the next delivery. A busier hour would need larger or more frequent deliveries as well as the fourth packer. ______________________________________________________________________ ## Build the Report The experiment states its assumptions, where each input came from, and its limits, and writes them into `report.md`: ```yaml assumptions: - Orders arrive at random, at a steady rate, through the busy hour. - One picker and three packers work the whole hour; nobody takes a break. - Every order is one parcel in one shipping box. inputs: Shop.arrival.orders: gaps between 300 orders observed in the shop, fitted by desflow fit Shop.service.picking: picking times of the same 300 orders, fitted by desflow fit Shop.service.packing: packing times of the same 300 orders, fitted by desflow fit Shop.arrival.deliveries: the supplier's schedule, a delivery every 10 minutes limits: - One busy hour only; the rest of the day is not modelled. - The observed values were made from the model's own runs, so comparing with them shows the method only. output: results/complete-model ``` ```python "assumptions": [ "Orders arrive at random, at a steady rate, through the busy hour.", "One picker and three packers work the whole hour; nobody takes a break.", "Every order is one parcel in one shipping box.", ], "inputs": { "Shop.arrival.orders": "gaps between 300 orders observed in the shop, " "fitted by fit_column", "Shop.service.picking": "picking times of the same 300 orders, " "fitted by fit_column", "Shop.service.packing": "packing times of the same 300 orders, " "fitted by fit_column", "Shop.arrival.deliveries": "the supplier's schedule, a delivery every 10 " "minutes", }, "limits": [ "One busy hour only; the rest of the day is not modelled.", "The observed values were made from the model's own runs, so comparing " "with them shows the method only.", ], "output": "results/complete-model", ``` The same keys, in the same mapping as the model. `report.md` gives the question, the model and its versions, the assumptions, each input with its fitted parameters and provenance, the run settings, the counts, the results, the comparisons, the checks and the observed comparison, then the limits and any input with no provenance. Every input has its provenance, so its Missing Inputs section says "None." [Readiness and Reporting](https://jaehyeon.me/desflow/latest/learn/concepts/readiness-and-reporting/#reporting-a-study) lists what else a report of a study needs. The part that answers the question: ```text ## Comparisons Each difference is the variant's value minus the baseline's, seed by seed, with the confidence interval of the mean difference. | Baseline | Variant | Measure | Difference | Half-width | Interval | Random streams | |---|---|---|---|---|---|---| | current | second-picker | `tasks.pick_order.wait_mean` | -0.5164 | 0.01466 | -0.531 to -0.5017 | 3 shared | | current | second-picker | `tasks.pack_order.wait_mean` | 0.2493 | 0.01344 | 0.2359 to 0.2628 | 3 shared | | current | second-picker | `resources.packers.utilization_avg` | 0.00107 | 0.004154 | -0.003084 to 0.005224 | 3 shared | | current | second-picker | `tasks.ship_order.wait_mean` | 0 | 0 | 0 to 0 | 3 shared | | current | fourth-packer | `tasks.pick_order.wait_mean` | 0 | 0 | 0 to 0 | 3 shared | | current | fourth-packer | `tasks.pack_order.wait_mean` | -1.584 | 0.09887 | -1.682 to -1.485 | 3 shared | | current | fourth-packer | `resources.packers.utilization_avg` | -21.94 | 0.1045 | -22.04 to -21.83 | 3 shared | | current | fourth-packer | `tasks.ship_order.wait_mean` | 0 | 0 | 0 to 0 | 3 shared | ## Checks Checks passed: 7 of 7. | Design | Measure | Checked | Bound | Value | Result | |---|---|---|---|---|---| | fourth-packer | `tasks.pick_order.wait_mean` | the upper end | max 1 | 0.5688 | passed | | fourth-packer | `tasks.pack_order.wait_mean` | the upper end | max 1 | 0.1558 | passed | | current | `tasks.ship_order.wait_mean` | the upper end | max 0 | 0 | passed | | second-picker | `tasks.ship_order.wait_mean` | the upper end | max 0 | 0 | passed | | fourth-packer | `tasks.ship_order.wait_mean` | the upper end | max 0 | 0 | passed | | fourth-packer-busier | `tasks.pick_order.wait_mean` | the upper end | max 1 | 0.7835 | passed | | fourth-packer-busier | `tasks.pack_order.wait_mean` | the upper end | max 1 | 0.2366 | passed | ## Observed Comparison | Design | Measure | Observed | Unit | Simulated interval | Inside | |---|---|---|---|---|---| | current | `tasks.pick_order.wait_mean` | 0.57 | s | 0.5377 to 0.5688 | no | | current | `tasks.pack_order.wait_mean` | 1.9 | s | 1.629 to 1.837 | no | | current | `resources.packers.utilization_avg` | 88 | percent | 87.37 to 88.15 | yes | ``` The report is built from the files the experiment wrote, so it can be built again without running anything: ```bash desflow report results/complete-model ``` [Experiment Results](https://jaehyeon.me/desflow/latest/user-guide/results/experiment-results/index.md) describes each file and section. ______________________________________________________________________ ## What You Get and Why Which shop design should be recommended? The fourth packer: - With it, the mean picking wait over 40 replications is **0.55 ± 0.02** seconds and the mean packing wait **0.15 ± 0.01** seconds. Both upper ends are under 1 second, and every check passes. - In today's shop the mean packing wait is **1.73 ± 0.10** seconds, and a second picker would lengthen it by 0.25 seconds. - The model agrees with the formulas where they apply, and each observed value lies within one standard deviation of a single run from the model's mean. - Any warm-up from none to 10 minutes changes the mean waits by less than their half-widths. - With orders 10% faster, the fourth packer still keeps both waits under 1 second, but orders then sometimes wait for shipping boxes. The data on this page are illustrative, and a real study reaches its recommendation from the shop's own records. Each step answers a different doubt about the result. The fits test the inputs, the formulas test the program, and the observed values test the model. The warm-up removes the empty start, the replications measure the effect of chance, and the paired seeds measure the size of each difference. [A Simulation Study](https://jaehyeon.me/desflow/latest/learn/concepts/a-simulation-study/index.md) sets out the steps, [Checking and Validating](https://jaehyeon.me/desflow/latest/learn/concepts/checking-and-validating/index.md) the checks, and [Output Analysis](https://jaehyeon.me/desflow/latest/learn/concepts/output-analysis/index.md) the warm-up, the replications and the paired comparison. The report records every step in one file, so another reader can repeat the study and see what it rests on. ## Key Takeaways - Each step of a study answers a different doubt: the fits test the inputs, the formulas test the program, and the observed values test the model. - A decision rule stated before the runs, such as an upper interval end under 1 second, makes the recommendation a check, not an opinion. - The report records every step in one file, so another reader can repeat the study. ______________________________________________________________________ ## Full Files Full files ```yaml # The Complete Model tutorial: the shop's busy hour, from order to shipment, with its # inputs fitted to the observed orders. # Fit the inputs, then run it: # desflow fit complete_model_observed.csv --column gap_seconds --lower 0 \ # --out fitted/complete_orders.yaml # desflow fit complete_model_observed.csv --column picking_seconds --lower 0 \ # --out fitted/complete_picking.yaml # desflow fit complete_model_observed.csv --column packing_seconds --lower 0 \ # --out fitted/complete_packing.yaml # desflow run complete_model.yaml simulation: sim_id: Shop factor: 0 random_seed: 42 # Records and statistics start after the first 2 minutes; 0 keeps everything warmup: ${WARMUP:-2 min} resources: # One picker and three packers, as the shop has today pickers: {current_cap: 1, max_cap: 4} packers: {current_cap: 3, max_cap: 10} containers: # Shipping boxes: 1,000 on the shelf at the start, and room for 2,000 stock: {current_cap: 2000, max_cap: 2000, level: 1000} arrivals: # The fitted gaps between orders; each order starts with picking orders: !include {file: fitted/complete_orders.yaml, spawn: pick_order} # A delivery of 1,000 boxes every 10 minutes deliveries: {dist: constant, value: 10 min, spawn: restock} services: # The fitted picking and packing times picking: !include fitted/complete_picking.yaml packing: !include fitted/complete_packing.yaml tasks: pick_order: service: picking resource: pickers payload: {event_type: order_picked} next: pack_order pack_order: service: packing resource: packers payload: {event_type: order_packed} next: ship_order ship_order: # Each parcel leaves in a box from the shelf; waits while the shelf is empty get: {container: stock, amount: 1} payload: {event_type: order_shipped} restock: put: {container: stock, amount: 1000} payload: {event_type: stock_delivered} # Waits, utilisation and the stock's level, published at the end stats: {level: typical, interval: 1 h} run: {until: 1 h} ``` ```yaml # The Complete Model tutorial: which shop design should be recommended? # Run it with: desflow experiment complete_model_experiment.yaml # Rebuild the report from its files with: desflow report results/complete-model experiment: complete-model question: Which design keeps both mean waits of the busy hour under 1 second? # The busy hour, with its 2-minute warm-up; 40 runs of each design model: complete_model.yaml until: 1 h replications: 40 seed: 42 measures: [tasks.pick_order.wait_mean, tasks.pack_order.wait_mean, resources.packers.utilization_avg, tasks.ship_order.wait_mean] # Values made from the model's own runs to show the method, not shop records; # the real shop runs the current design observed: {file: complete_model_outputs.csv, variant: current} # Every design runs with the same seeds, so they are compared seed by seed pairing: common compare: - {baseline: current, variant: second-picker} - {baseline: current, variant: fourth-packer} variants: current: {} second-picker: {Shop.resources.pickers.current_cap: 2} fourth-packer: {Shop.resources.packers.current_cap: 4} # The recommended design, with orders 10% faster than the fitted rate of 1.50719 fourth-packer-busier: Shop.resources.packers.current_cap: 4 Shop.arrival.orders.rate: 1.65791 checks: # The recommended design: the upper end of each wait's interval is under 1 second - {measure: tasks.pick_order.wait_mean, variant: fourth-packer, max: 1} - {measure: tasks.pack_order.wait_mean, variant: fourth-packer, max: 1} # In each of the three designs, no order waits for a shipping box - {measure: tasks.ship_order.wait_mean, variant: current, max: 0} - {measure: tasks.ship_order.wait_mean, variant: second-picker, max: 0} - {measure: tasks.ship_order.wait_mean, variant: fourth-packer, max: 0} # With orders 10% faster, the fourth packer keeps both waits under 1 second - {measure: tasks.pick_order.wait_mean, variant: fourth-packer-busier, max: 1} - {measure: tasks.pack_order.wait_mean, variant: fourth-packer-busier, max: 1} assumptions: - Orders arrive at random, at a steady rate, through the busy hour. - One picker and three packers work the whole hour; nobody takes a break. - Every order is one parcel in one shipping box. inputs: Shop.arrival.orders: gaps between 300 orders observed in the shop, fitted by desflow fit Shop.service.picking: picking times of the same 300 orders, fitted by desflow fit Shop.service.packing: packing times of the same 300 orders, fitted by desflow fit Shop.arrival.deliveries: the supplier's schedule, a delivery every 10 minutes limits: - One busy hour only; the rest of the day is not modelled. - The observed values were made from the model's own runs, so comparing with them shows the method only. output: results/complete-model ``` ```text measure,value,unit,population,horizon tasks.pick_order.wait_mean,0.57,s,started instances,58 min tasks.pack_order.wait_mean,1.9,s,started instances,58 min resources.packers.utilization_avg,88.0,percent,time average,58 min ``` ```python """The Complete Model tutorial, builder: which shop design should be recommended? Fits the gaps between orders and the picking and packing times of 300 observed orders, builds the shop's busy hour from the fits, compares three warm-ups, and runs the experiment that compares the designs, checks them and writes the report. Explain and verify the model with: desflow explain complete_model.py --verify --until "1 h" --replications 10 """ import csv import logging from pathlib import Path from desflow import SimulationContext, fit_column, replicate, run_experiment # Replications and the experiment log only their warnings logging.getLogger("desflow").setLevel(logging.WARNING) HERE = Path(__file__).resolve().parent OBSERVED = HERE / "complete_model_observed.csv" def fitted() -> dict: """Each input fitted to its column of the observed orders.""" with OBSERVED.open(newline="", encoding="utf-8") as handle: rows = list(csv.DictReader(handle)) columns = { "orders": "gap_seconds", "picking": "picking_seconds", "packing": "packing_seconds", } # Every column is in seconds, and no time can be below 0 return { name: fit_column([float(row[column]) for row in rows], unit="s", lower=0) for name, column in columns.items() } # The best fit of each input: dist and its parameters FITS = {name: result.settings() for name, result in fitted().items()} def shop() -> SimulationContext: """A new busy hour, built from the fits.""" app = ( SimulationContext(sim_id="Shop", factor=0, random_seed=42, warmup="2 min") # One picker and three packers, as the shop has today .add_resource("pickers", current_cap=1, max_cap=4) .add_resource("packers", current_cap=3, max_cap=10) # Shipping boxes: 1,000 on the shelf at the start, and room for 2,000 .add_container("stock", current_cap=2000, max_cap=2000, level=1000) # The fitted gaps between orders; each order starts with picking .add_arrival("orders", **FITS["orders"], spawn="pick_order") # A delivery of 1,000 boxes every 10 minutes .add_arrival("deliveries", dist="constant", value=600, spawn="restock") # The fitted picking and packing times .add_service("picking", **FITS["picking"]) .add_service("packing", **FITS["packing"]) # Waits, utilisation and the stock's level, published at the end .with_stats("typical", interval=3600) ) @app.task(service_id="picking", resource_id="pickers", next="pack_order") def pick_order(task_id: int): return {"event_type": "order_picked"} @app.task(service_id="packing", resource_id="packers", next="ship_order") def pack_order(task_id: int): return {"event_type": "order_packed"} # Each parcel leaves in a box from the shelf; waits while the shelf is empty @app.task(get={"container": "stock", "amount": 1}) def ship_order(task_id: int): return {"event_type": "order_shipped"} @app.task(put={"container": "stock", "amount": 1000}) def restock(task_id: int): return {"event_type": "stock_delivered"} return app # The one context desflow explain complete_model.py reads app = shop() WAITS = ["tasks.pick_order.wait_mean", "tasks.pack_order.wait_mean"] DESIGNS = ["current", "second-picker", "fourth-packer"] def warmups() -> dict: """The mean waits of 40 replications of today's shop, after three candidate warm-ups.""" return { warmup: replicate(shop, 40, seed=42, until="1 h", warmup=warmup, measures=WAITS) for warmup in (0, "2 min", "10 min") } EXPERIMENT = { "experiment": "complete-model", "question": "Which design keeps both mean waits of the busy hour under 1 second?", # The busy hour, with its 2-minute warm-up; 40 replications of each design "model": shop, "until": "1 h", "replications": 40, "seed": 42, "measures": [ "tasks.pick_order.wait_mean", "tasks.pack_order.wait_mean", "resources.packers.utilization_avg", "tasks.ship_order.wait_mean", ], # Values made from the model's own runs to show the method, not shop records; # the real shop runs the current design "observed": { "file": str(HERE / "complete_model_outputs.csv"), "variant": "current", }, # Every design runs with the same seeds, so they are compared seed by seed "pairing": "common", "compare": [ {"baseline": "current", "variant": "second-picker"}, {"baseline": "current", "variant": "fourth-packer"}, ], "variants": { "current": {}, "second-picker": {"Shop.resources.pickers.current_cap": 2}, "fourth-packer": {"Shop.resources.packers.current_cap": 4}, # The recommended design, with orders 10% faster than the fitted rate of 1.50719 "fourth-packer-busier": { "Shop.resources.packers.current_cap": 4, "Shop.arrival.orders.rate": 1.65791, }, }, "checks": [ # The recommended design: the upper end of each wait's interval is under 1 s {"measure": "tasks.pick_order.wait_mean", "variant": "fourth-packer", "max": 1}, {"measure": "tasks.pack_order.wait_mean", "variant": "fourth-packer", "max": 1}, # In each of the three designs, no order waits for a shipping box {"measure": "tasks.ship_order.wait_mean", "variant": "current", "max": 0}, {"measure": "tasks.ship_order.wait_mean", "variant": "second-picker", "max": 0}, {"measure": "tasks.ship_order.wait_mean", "variant": "fourth-packer", "max": 0}, # With orders 10% faster, the fourth packer keeps both waits under 1 s { "measure": "tasks.pick_order.wait_mean", "variant": "fourth-packer-busier", "max": 1, }, { "measure": "tasks.pack_order.wait_mean", "variant": "fourth-packer-busier", "max": 1, }, ], "assumptions": [ "Orders arrive at random, at a steady rate, through the busy hour.", "One picker and three packers work the whole hour; nobody takes a break.", "Every order is one parcel in one shipping box.", ], "inputs": { "Shop.arrival.orders": "gaps between 300 orders observed in the shop, " "fitted by fit_column", "Shop.service.picking": "picking times of the same 300 orders, " "fitted by fit_column", "Shop.service.packing": "packing times of the same 300 orders, " "fitted by fit_column", "Shop.arrival.deliveries": "the supplier's schedule, a delivery every 10 " "minutes", }, "limits": [ "One busy hour only; the rest of the day is not modelled.", "The observed values were made from the model's own runs, so comparing " "with them shows the method only.", ], "output": "results/complete-model", } def experiment(output=None): """Runs the designs; raises CheckFailed when a check fails, after writing every file.""" return run_experiment(EXPERIMENT, output=output) def recommended(result) -> list: """The designs whose two mean waits both have an upper end under 1 second; the sensitivity variant is not a design.""" upper: dict = {} for row in result.summary: if row["design"] in DESIGNS and row["statistic"] in WAITS: high = row["mean"] + row["half_width"] upper[row["design"]] = max(upper.get(row["design"], 0), high) return [design for design, high in upper.items() if high < 1] if __name__ == "__main__": for name, result in fitted().items(): print(f"{name}:\n{result.text()}\n") for warmup, result in warmups().items(): for row in result.summary: print( f"warm-up {warmup}: {row['measure']} {row['mean']:.3f} ± {row['half_width']:.3f}" ) print(f"recommended: {recommended(experiment())}") ``` ```text measure,value,unit,population,horizon tasks.pick_order.wait_mean,0.57,s,started instances,58 min tasks.pack_order.wait_mean,1.9,s,started instances,58 min resources.packers.utilization_avg,88.0,percent,time average,58 min ``` ```python """The Complete Model tutorial, low-level: which shop design should be recommended? Fits the gaps between orders and the picking and packing times of 300 observed orders, builds the shop's busy hour from the fits, checks it against the queueing formulas worked by hand, compares three warm-ups, and runs the experiment that compares the designs, checks them and writes the report. """ import csv import itertools import logging from pathlib import Path from desflow import ( CapacityConfig, ContainerConfig, DistributionConfig, DynamicContainer, DynamicRealtimeEnvironment, DynamicResource, LowLevelModel, Sampler, SimParameter, fit_column, replicate, run_experiment, ) # Replications and the experiment log only their warnings logging.getLogger("desflow").setLevel(logging.WARNING) HERE = Path(__file__).resolve().parent OBSERVED = HERE / "complete_model_observed.csv" def fitted() -> dict: """Each input fitted to its column of the observed orders.""" with OBSERVED.open(newline="", encoding="utf-8") as handle: rows = list(csv.DictReader(handle)) columns = { "orders": "gap_seconds", "picking": "picking_seconds", "packing": "packing_seconds", } # Every column is in seconds, and no time can be below 0 return { name: fit_column([float(row[column]) for row in rows], unit="s", lower=0) for name, column in columns.items() } # The best fit of each input: dist and its parameters FITS = {name: result.settings() for name, result in fitted().items()} PARAMS = SimParameter( sim_id="Shop", arrival={ # The fitted gaps between orders "orders": DistributionConfig(**FITS["orders"]), # A delivery of 1,000 boxes every 10 minutes "deliveries": DistributionConfig(dist="constant", value=600), }, # The fitted picking and packing times service={ "picking": DistributionConfig(**FITS["picking"]), "packing": DistributionConfig(**FITS["packing"]), }, # One picker and three packers, as the shop has today resources={ "pickers": CapacityConfig(current_cap=1, max_cap=4), "packers": CapacityConfig(current_cap=3, max_cap=10), }, # Shipping boxes: 1,000 on the shelf at the start, and room for 2,000 containers={"stock": ContainerConfig(current_cap=2000, max_cap=2000, level=1000)}, ) # Records and statistics start after the first 2 minutes WARMUP = 120.0 # Each task's service, resource and the task after it; None where it has none TASKS = { "pick_order": ("picking", "pickers", "pack_order"), "pack_order": ("packing", "packers", "ship_order"), "ship_order": (None, None, None), } EVENTS = { "pick_order": "order_picked", "pack_order": "order_packed", "ship_order": "order_shipped", } def task(env, sampler, shop, name, key, task_id, counters): """Runs one task of an order, then the task after it, in the same process.""" service, resource, following = TASKS[name] status = ( {"path_id": f"Shop.service.{service}", "sim_id": "Shop", "service": service} if service else {} ) def publish(value): env.publish_event(key, value, task=name, instance=task_id) if name == "pick_order": env.stats.flow_started("orders") # the order enters the shop publish({**status, "status": "queued"}) env.stats.task_queued(name, task_id) if resource is not None: with shop[resource].request() as request: yield request publish({**status, "status": "started"}) env.stats.task_started(name, task_id) yield env.timeout( sampler.sample(env.registry.get_config(status["path_id"])) ) publish({"event_type": EVENTS[name]}) env.stats.task_finished(name, task_id) else: # Each parcel leaves in a box from the shelf; waits while the shelf is empty yield shop["stock"].get(1) publish({"status": "started"}) env.stats.task_started(name, task_id) publish({"event_type": EVENTS[name]}) env.stats.task_finished(name, task_id) if following is None: env.stats.flow_finished("orders") # the order leaves the shop return instance = next(counters[following]) yield from task(env, sampler, shop, following, key, instance, counters) def restock(env, shop, key, task_id): """One delivery: 1,000 boxes onto the shelf, waiting while there is no room.""" env.stats.flow_started("deliveries") yield shop["stock"].put(1000) env.publish_event( key, {"event_type": "stock_delivered"}, task="restock", instance=task_id ) env.stats.task_finished("restock", task_id) env.stats.flow_finished("deliveries") def order_generator(env, sampler, shop, counters): """Starts picking for every order, keyed orders-1, orders-2 and so on.""" gap = env.registry.get_config("Shop.arrival.orders") for number in itertools.count(1): yield env.timeout(sampler.sample(gap)) instance = next(counters["pick_order"]) env.process( task( env, sampler, shop, "pick_order", f"orders-{number}", instance, counters ) ) def delivery_generator(env, sampler, shop): gap = env.registry.get_config("Shop.arrival.deliveries") for number in itertools.count(1): yield env.timeout(sampler.sample(gap)) env.process(restock(env, shop, f"deliveries-{number}", number - 1)) def model(env, sampler): """The busy hour in a given environment: the runner sets the statistics.""" env.registry.register_sim_parameter(PARAMS) shop = { "pickers": DynamicResource(env, "Shop", "pickers"), "packers": DynamicResource(env, "Shop", "packers"), "stock": DynamicContainer(env, "Shop", "stock"), } # One counter per task, shared by the arrivals and the next task counters = {name: itertools.count() for name in TASKS} env.process(order_generator(env, sampler, shop, counters)) env.process(delivery_generator(env, sampler, shop)) def run(egress=(), until=3600): """One busy hour from the seed 42, its records sent to `egress`.""" env = DynamicRealtimeEnvironment(factor=0.0) # Waits, utilisation and the stock's level, published at the end env.setup_stats("Shop", "typical", interval=3600) env.setup_egress(list(egress), warmup=WARMUP) model(env, Sampler(seed=42)) try: env.run(until=until) finally: env.teardown() return env SHOP = LowLevelModel(model, sim_id="Shop") WAITS = ["tasks.pick_order.wait_mean", "tasks.pack_order.wait_mean"] DESIGNS = ["current", "second-picker", "fourth-packer"] def warmups() -> dict: """The mean waits of 40 replications of today's shop, after three candidate warm-ups.""" return { warmup: replicate(SHOP, 40, seed=42, until=3600, warmup=warmup, measures=WAITS) for warmup in (0, WARMUP, 600) } EXPERIMENT = { "experiment": "complete-model", "question": "Which design keeps both mean waits of the busy hour under 1 second?", # The busy hour as a LowLevelModel, and its 2-minute warm-up "model": SHOP, "warmup": WARMUP, "until": 3600, "replications": 40, "seed": 42, "measures": [ "tasks.pick_order.wait_mean", "tasks.pack_order.wait_mean", "resources.packers.utilization_avg", "tasks.ship_order.wait_mean", ], # Values made from the model's own runs to show the method, not shop records; # the real shop runs the current design "observed": { "file": str(HERE / "complete_model_outputs.csv"), "variant": "current", }, "pairing": "common", "compare": [ {"baseline": "current", "variant": "second-picker"}, {"baseline": "current", "variant": "fourth-packer"}, ], "variants": { "current": {}, "second-picker": {"Shop.resources.pickers.current_cap": 2}, "fourth-packer": {"Shop.resources.packers.current_cap": 4}, "fourth-packer-busier": { "Shop.resources.packers.current_cap": 4, "Shop.arrival.orders.rate": 1.65791, }, }, "checks": [ {"measure": "tasks.pick_order.wait_mean", "variant": "fourth-packer", "max": 1}, {"measure": "tasks.pack_order.wait_mean", "variant": "fourth-packer", "max": 1}, {"measure": "tasks.ship_order.wait_mean", "variant": "current", "max": 0}, {"measure": "tasks.ship_order.wait_mean", "variant": "second-picker", "max": 0}, {"measure": "tasks.ship_order.wait_mean", "variant": "fourth-packer", "max": 0}, { "measure": "tasks.pick_order.wait_mean", "variant": "fourth-packer-busier", "max": 1, }, { "measure": "tasks.pack_order.wait_mean", "variant": "fourth-packer-busier", "max": 1, }, ], "assumptions": [ "Orders arrive at random, at a steady rate, through the busy hour.", "One picker and three packers work the whole hour; nobody takes a break.", "Every order is one parcel in one shipping box.", ], "inputs": { "Shop.arrival.orders": "gaps between 300 orders observed in the shop, " "fitted by fit_column", "Shop.service.picking": "picking times of the same 300 orders, " "fitted by fit_column", "Shop.service.packing": "packing times of the same 300 orders, " "fitted by fit_column", "Shop.arrival.deliveries": "the supplier's schedule, a delivery every 10 " "minutes", }, "limits": [ "One busy hour only; the rest of the day is not modelled.", "The observed values were made from the model's own runs, so comparing " "with them shows the method only.", ], "output": "results/complete-model", } def experiment(output=None): """Runs the designs; raises CheckFailed when a check fails, after writing every file.""" return run_experiment(EXPERIMENT, output=output) def recommended(result) -> list: """The designs whose two mean waits both have an upper end under 1 second; the sensitivity variant is not a design.""" upper: dict = {} for row in result.summary: if row["design"] in DESIGNS and row["statistic"] in WAITS: high = row["mean"] + row["half_width"] upper[row["design"]] = max(upper.get(row["design"], 0), high) return [design for design, high in upper.items() if high < 1] if __name__ == "__main__": for warmup, result in warmups().items(): for row in result.summary: print( f"warm-up {warmup} s: {row['measure']} {row['mean']:.3f} ± {row['half_width']:.3f}" ) print(f"recommended: {recommended(experiment())}") ``` ```text measure,value,unit,population,horizon tasks.pick_order.wait_mean,0.57,s,started instances,58 min tasks.pack_order.wait_mean,1.9,s,started instances,58 min resources.packers.utilization_avg,88.0,percent,time average,58 min ``` # Live Changes The shop of [Changing Demand](https://jaehyeon.me/desflow/latest/learn/inputs/changing-demand/index.md) has one packer, which takes 1.5 seconds to pack an order. An order arrives every 2.5 seconds on average (24 a minute, `rate: 0.4`). At 20 minutes the packer's label printer jams, and packing takes 3 seconds until the printer is fixed at 30 minutes. This page asks: **how long does the jam keep orders waiting after the fix, and how can someone who reads only the records tell what changed?** - **Decision:** how long to keep a delay notice up after a fault on the bench is fixed. - **Measures:** the mean wait of the orders queued in the 10 minutes of the jam and in the 10 minutes after it, and the records that name the change. - **Runs:** one run of the hour with the seed 42, a second run of the hour without the jam on the same seed, and a paced run of 5 minutes with the change sent live. - **Assumptions:** the jam doubles the packing time, and orders arrive at random at the same rate throughout. ## What You Will Learn This page shows how to: - change a parameter during a run with a scenario, and record each change as a label; - measure the effect of a change against a baseline run on the same seed; - send the same change live, from outside the run. ## What You Add This page adds a **planned intervention**: two scenario steps that change the packing time and publish a **label**, a ground-truth record of each change. The events go to one file sink and the labels to another. The file sinks need the `parquet` extra, so install `desflow[parquet]` (`pip install "desflow[parquet]"`). Without it, the run logs that pyarrow is required and writes no files. A second run without the jam gives the baseline. A last step sends the same change live from `LocalIngress`, with no broker. ______________________________________________________________________ ## Record the Jam A scenario step with a `record` mapping also publishes a label, as [Live Parameters](https://jaehyeon.me/desflow/latest/user-guide/live-runs-and-connectors/live-parameters/#record-what-a-change-was-for) describes. The jam is two steps, each with its own label: ```yaml # The jam: 3 seconds of packing from 20 to 30 minutes, each change recorded scenario: - at: 20 min path: Shop.service.packing.value value: 3.0 record: {intervention: printer_jam} - at: 30 min path: Shop.service.packing.value value: 1.5 record: {intervention: printer_fixed} ``` ```python # The jam: 3 seconds of packing from 20 to 30 minutes, each change recorded app.add_scenario( [ { "at": "20 min", "path": "Shop.service.packing.value", "value": 3.0, "record": {"intervention": "printer_jam"}, }, { "at": "30 min", "path": "Shop.service.packing.value", "value": 1.5, "record": {"intervention": "printer_fixed"}, }, ] ) ``` ```python # The jam: 3 seconds of packing from 20 to 30 minutes, each change recorded JAM = [ { "at": 1200, "path": "Shop.service.packing.value", "value": 3.0, "record": {"intervention": "printer_jam"}, }, { "at": 1800, "path": "Shop.service.packing.value", "value": 1.5, "record": {"intervention": "printer_fixed"}, }, ] ``` `run_scenario` is the SimPy process that applies the steps, started with `env.process`: ```python # Each step applies before every other event at its time env.process(run_scenario(env, JAM, until=until)) ``` It waits on SimPy's clock with timeout events, as [SimPy and desflow](https://jaehyeon.me/desflow/latest/simpy/#environment-and-the-event-list) describes. The steps follow the simulation clock, so the jam lands at exactly 20 and 30 minutes on every run, as in Changing Demand. The path `Shop.service.packing.value` is the `value` of a `constant` distribution. [Live Parameters](https://jaehyeon.me/desflow/latest/user-guide/live-runs-and-connectors/live-parameters/#find-the-path) shows how to list every path of a model. ______________________________________________________________________ ## Write Events and Labels Apart The labels go only to a sink with `when: labels`, for the reasons [Live Parameters](https://jaehyeon.me/desflow/latest/user-guide/live-runs-and-connectors/live-parameters/#record-what-a-change-was-for) gives: ```yaml egress: # The events, one flat row per event - type: Jsonl config: {default_path: events/orders.jsonl} # The ground-truth records only - type: Jsonl config: {default_path: labels/labels.jsonl} when: labels ``` ```python # The events, one flat row per event .add_egress(JsonlStorageEgress(default_path=f"{out}/events/orders.jsonl")) # The ground-truth records only .add_egress( JsonlStorageEgress(default_path=f"{out}/labels/labels.jsonl"), when="labels", ) ``` ```python env.setup_egress( [ # The events, one flat row per event JsonlStorageEgress(default_path=f"{out}/events/orders.jsonl"), # The ground-truth records only JsonlStorageEgress(default_path=f"{out}/labels/labels.jsonl"), ], labels=[False, True], flush_interval=flush_interval, ) ``` `labels` takes one entry per sink, in the order of the list. Save the files from [Full Files](#full-files) in one folder and run the commands there: `desflow run live_changes.yaml`, `python live_changes.py` or `python live_changes_low_level.py`. Each sink writes one file per batch, such as `labels/labels_1a2b3c4d.jsonl`. The YAML file writes `events/` and `labels/` in the folder where you run it, and the scripts write below `live_changes_output/`. A second run in the same folder adds new files beside the old ones, so start each run in an empty folder. The run writes these two labels. `--stdout` prints the run's records as JSON lines instead of writing the files, so `grep` shows the labels without a file to open. In the builder and the low-level API, `ConsoleEgress(format="json")` as the sink prints the same lines: ```bash desflow run live_changes.yaml --stdout | grep '"label"' ``` ```text {"stream_type":"label","sim_ts":1200.0,"timestamp":"...","path":"Shop.service.packing.value","old":1.5,"new":3.0,"label":{"intervention":"printer_jam"}} {"stream_type":"label","sim_ts":1800.0,"timestamp":"...","path":"Shop.service.packing.value","old":3.0,"new":1.5,"label":{"intervention":"printer_fixed"}} ``` `path`, `old` and `new` say what changed and by how much, and `label` says why. [Records and Telemetry](https://jaehyeon.me/desflow/latest/reference/records-and-telemetry/#record-shape) lists every field. ______________________________________________________________________ ## Measure Against a Baseline The labels say when the packing time went back to 1.5 seconds, but not when the orders stopped waiting longer because of it. To measure that, run the hour again without the jam, on the same seed, and compare the waits. Each order's wait is its `started` time minus its `queued` time, read from the event files: ```python def read_rows(folder: Path) -> list: """Every row of every JSONL file the sink wrote to folder.""" return [ json.loads(line) for path in sorted(folder.glob("*.jsonl")) for line in path.read_text().splitlines() ] def waits(out: Path) -> dict: """The wait of each order, by the time it was queued, in seconds.""" queued, started = {}, {} for row in read_rows(out / "events"): if row.get("status") == "queued": queued[row["instance"]] = row["sim_ts"] elif row.get("status") == "started": started[row["instance"]] = row["sim_ts"] return {queued[i]: started[i] - queued[i] for i in started} def mean_wait(by_time: dict, start: float, end: float) -> float: """The mean wait of the orders queued from start to end, in seconds.""" window = [wait for at, wait in by_time.items() if start <= at < end] return sum(window) / len(window) ``` The Builder and Low-level scripts run both hours and print the comparison. They write the files to `live_changes_output/jam/` and `live_changes_output/baseline/`. The YAML file runs one hour at a time, so the baseline is a copy without the `scenario` block, and the Builder script reads the two folders with the functions above: ```bash mkdir jam baseline sed '/^scenario:/,/^$/d' live_changes.yaml > live_changes_baseline.yaml (cd jam && desflow run ../live_changes.yaml) (cd baseline && desflow run ../live_changes_baseline.yaml) python live_changes.py compare jam baseline ``` ```bash python live_changes.py 2>/dev/null ``` ```bash python live_changes_low_level.py 2>/dev/null ``` Each command ends with the same five lines, which [What You Get and Why](#what-you-get-and-why) shows. The packing time is constant and draws no random numbers, so the jam does not change the arrival gaps the seed draws. Both runs therefore have the same orders at the same times, and each order's two waits can be compared one to one. ______________________________________________________________________ ## Send It Live A scenario is planned in advance. A change from outside arrives while the run goes on, from an ingress connector. `LocalIngress` is the ingress connector that needs no broker. It applies each change after a delay in wall-clock seconds, so the run must be paced. Here the run lasts 5 simulated minutes, paced at 200 simulated seconds for each wall-clock second (`factor: 0.005`, so each simulated second takes 0.005 wall-clock seconds), so it takes 1.5 wall-clock seconds. A paced run raises an error when a step starts more than `factor` wall-clock seconds late, because `strict` is on at a factor above 0, as [Clocks and Pacing](https://jaehyeon.me/desflow/latest/user-guide/time-and-pacing/clocks-and-pacing/#strict-pacing) describes. This run sets `strict` off, so a slow machine can fall behind without stopping it: ```yaml # Half a wall-clock second after the start, set packing to 3 seconds ingress: - type: Local config: {schedule: [[0.5, Shop.service.packing.value, 3.0]]} ``` ```python # Half a wall-clock second after the start, set packing to 3 seconds app.add_ingress(LocalIngress(schedule=[(0.5, "Shop.service.packing.value", 3.0)])) ``` ```python # Half a wall-clock second after the start, set packing to 3 seconds ingress = [LocalIngress(schedule=[(0.5, "Shop.service.packing.value", 3.0)])] ``` `env.setup_ingress(ingress)` starts it, and a SimPy process checks the ingress queue every 0.1 simulated seconds. Half a wall-clock second is 100 simulated seconds at this pace, and packing changes to 3 seconds about then. The exact time depends on how fast the machine runs, so it differs from run to run. The change publishes no label: an ingress update changes the registry and nothing else, so no `labels/` folder is created. To keep the ground truth of a live change, the sender must record it itself. `live_changes_live.yaml` writes to `live/`, and the scripts to `live_changes_output/live/`, so the files stay apart from those of the jam runs. Send it live with `desflow run live_changes_live.yaml`, `python live_changes.py live` or `python live_changes_low_level.py live`. The two scripts print `packing after the live change: 3.0 s`. [Ingress](https://jaehyeon.me/desflow/latest/user-guide/live-runs-and-connectors/ingress/index.md) describes the connectors that read Kafka, Redis and PostgreSQL in the same way. ______________________________________________________________________ ## What You Get and Why The wait of every order over the hour, by the time it was queued, with the jam and without it: How long does the jam keep orders waiting after the fix? In one run of the hour with the seed 42, the orders queued during the jam wait **45.79 seconds** on average, against **1.26** seconds in the run without the jam. The orders queued in the 10 minutes after the fix still wait **14.60 seconds** on average, against **1.30** seconds. The last order that waits longer than in the baseline is queued at **1,982.3 seconds**, about 3 minutes after the fix, so the delay notice should stay up for about 3 minutes more. The two labels, at **1,200** and **1,800 seconds**, tell a reader what changed and when. Each tab gives the labels and the mean waits: ```bash python live_changes.py compare jam baseline ``` ```text label at 1200.0 s: printer_jam, packing 1.5 s to 3.0 s label at 1800.0 s: printer_fixed, packing 3.0 s to 1.5 s with the jam: mean wait 45.79 s from 20 to 30 min, 14.60 s from 30 to 40 min without it: mean wait 1.26 s from 20 to 30 min, 1.30 s from 30 to 40 min the last order that waits longer is queued at 1982.3 s ``` ```bash python live_changes.py 2>/dev/null ``` ```text label at 1200.0 s: printer_jam, packing 1.5 s to 3.0 s label at 1800.0 s: printer_fixed, packing 3.0 s to 1.5 s with the jam: mean wait 45.79 s from 20 to 30 min, 14.60 s from 30 to 40 min without it: mean wait 1.26 s from 20 to 30 min, 1.30 s from 30 to 40 min the last order that waits longer is queued at 1982.3 s ``` ```bash python live_changes_low_level.py 2>/dev/null ``` ```text label at 1200.0 s: printer_jam, packing 1.5 s to 3.0 s label at 1800.0 s: printer_fixed, packing 3.0 s to 1.5 s with the jam: mean wait 45.79 s from 20 to 30 min, 14.60 s from 30 to 40 min without it: mean wait 1.26 s from 20 to 30 min, 1.30 s from 30 to 40 min the last order that waits longer is queued at 1982.3 s ``` During the jam the packer finishes one order every 3 seconds (20 a minute), while an order arrives every 2.5 seconds on average (24 a minute). The queue grows by about 4 orders a minute, so about 40 orders build up in 10 minutes. After the fix the packer finishes an order every 1.5 seconds (40 a minute), 16 a minute more than arrive, so the queue takes a few minutes to clear. The effect of a change therefore lasts beyond the change itself. A label names the cause, and only a comparison with a baseline on the same orders measures the effect, as [Output Analysis](https://jaehyeon.me/desflow/latest/learn/concepts/output-analysis/#comparing-designs) explains for any two designs. ## Key Takeaways - The effect of a change lasts beyond the change: a queue built during a fault takes time to clear. - A label names the cause of a change. Only a comparison with a baseline on the same orders measures its effect. - The same registry path takes a change from a scenario or from a message sent while the run goes on. ______________________________________________________________________ ## Full Files Full files ```yaml # The Live Changes tutorial: a label printer jam, written as a scenario. # Run it with: desflow run live_changes.yaml # The events are written to events/ and the ground-truth records to labels/. simulation: {sim_id: Shop, factor: 0, random_seed: 42} resources: packers: {current_cap: 1, max_cap: 1} services: packing: {dist: constant, value: 1.5 s} arrivals: orders: {dist: exponential, rate: 0.4, spawn: pack_order} tasks: pack_order: service: packing resource: packers payload: {event_type: order_packed} # The jam: 3 seconds of packing from 20 to 30 minutes, each change recorded scenario: - at: 20 min path: Shop.service.packing.value value: 3.0 record: {intervention: printer_jam} - at: 30 min path: Shop.service.packing.value value: 1.5 record: {intervention: printer_fixed} egress: # The events, one flat row per event - type: Jsonl config: {default_path: events/orders.jsonl} # The ground-truth records only - type: Jsonl config: {default_path: labels/labels.jsonl} when: labels run: {until: 1 h} ``` ```yaml # The Live Changes tutorial: the same jam sent live, from a LocalIngress schedule. # Run it with: desflow run live_changes_live.yaml # The run is paced at 200 simulated seconds a wall-clock second, so 5 minutes take 1.5 # s. # strict: false keeps a slow machine from stopping the run if it falls behind simulation: {sim_id: Shop, factor: 0.005, strict: false, random_seed: 42} resources: packers: {current_cap: 1, max_cap: 1} services: packing: {dist: constant, value: 1.5 s} arrivals: orders: {dist: exponential, rate: 0.4, spawn: pack_order} tasks: pack_order: service: packing resource: packers payload: {event_type: order_packed} # Half a wall-clock second after the start, set packing to 3 seconds ingress: - type: Local config: {schedule: [[0.5, Shop.service.packing.value, 3.0]]} egress: # Flush every 60 simulated seconds: at this pace the default of 1 s flushes on a timer # over and over, and desflow warns about it. The files go to live/, apart from the # files of live_changes.yaml - type: Jsonl config: {default_path: live/events/orders.jsonl} flush_interval: 60 - type: Jsonl config: {default_path: live/labels/labels.jsonl} when: labels run: {until: 5 min} ``` ```python """The Live Changes tutorial: a label printer jam, written as a scenario, builder. One packer takes 1.5 seconds to pack an order, and an order arrives every 2.5 seconds on average (rate 0.4). From 20 to 30 minutes a jammed label printer slows packing to 3 seconds. The events are written to events/ and the ground-truth records of the jam to labels/, and the script prints the mean waits with and without the jam. Run it with: python live_changes.py With the argument live, it sends the jam live: python live_changes.py live With compare and two folders, it reads two runs that are already written, such as the runs of live_changes.yaml with and without its scenario block: python live_changes.py compare jam baseline """ import json import logging import shutil import sys from pathlib import Path from desflow import JsonlStorageEgress, LocalIngress, SimulationContext logging.basicConfig(level=logging.WARNING) def shop(out: Path, jam: bool = True) -> SimulationContext: """The shop of Changing Demand, writing its events and labels under out.""" app = ( SimulationContext(sim_id="Shop", factor=0, random_seed=42) .add_resource("packers", current_cap=1, max_cap=1) .add_service("packing", dist="constant", value=1.5) .add_arrival("orders", dist="exponential", rate=0.4) # The events, one flat row per event .add_egress(JsonlStorageEgress(default_path=f"{out}/events/orders.jsonl")) # The ground-truth records only .add_egress( JsonlStorageEgress(default_path=f"{out}/labels/labels.jsonl"), when="labels", ) ) if jam: # The jam: 3 seconds of packing from 20 to 30 minutes, each change recorded app.add_scenario( [ { "at": "20 min", "path": "Shop.service.packing.value", "value": 3.0, "record": {"intervention": "printer_jam"}, }, { "at": "30 min", "path": "Shop.service.packing.value", "value": 1.5, "record": {"intervention": "printer_fixed"}, }, ] ) @app.task(service_id="packing", resource_id="packers") def pack_order(task_id: int): return {"event_type": "order_packed"} @app.arrival_loop("orders") def order_generator(context: SimulationContext): task_id = 0 while True: order = yield context.wait_for_arrival("orders") context.spawn(pack_order(task_id, entity=order)) task_id += 1 return app def read_rows(folder: Path) -> list: """Every row of every JSONL file the sink wrote to folder.""" return [ json.loads(line) for path in sorted(folder.glob("*.jsonl")) for line in path.read_text().splitlines() ] def waits(out: Path) -> dict: """The wait of each order, by the time it was queued, in seconds.""" queued, started = {}, {} for row in read_rows(out / "events"): if row.get("status") == "queued": queued[row["instance"]] = row["sim_ts"] elif row.get("status") == "started": started[row["instance"]] = row["sim_ts"] return {queued[i]: started[i] - queued[i] for i in started} def mean_wait(by_time: dict, start: float, end: float) -> float: """The mean wait of the orders queued from start to end, in seconds.""" window = [wait for at, wait in by_time.items() if start <= at < end] return sum(window) / len(window) def outcomes(out: Path) -> dict: """Runs the hour with and without the jam; returns the labels and mean waits.""" for jam in (True, False): folder = out / ("jam" if jam else "baseline") shutil.rmtree(folder, ignore_errors=True) # a run adds files; start empty shop(folder, jam).run(until="1 h") return compare(out / "jam", out / "baseline") def compare(jam_folder: Path, baseline_folder: Path) -> dict: """Reads the two runs' files; returns the labels and mean waits.""" result: dict = {} by_run = {True: waits(jam_folder), False: waits(baseline_folder)} for jam, by_time in by_run.items(): result[jam] = { "jam": round(mean_wait(by_time, 1200, 1800), 2), "after": round(mean_wait(by_time, 1800, 2400), 2), } # Both runs meet the same orders, so each order's two waits can be compared result["last_longer"] = max( at for at, wait in by_run[True].items() if wait > by_run[False][at] + 0.001 ) labels = read_rows(jam_folder / "labels") result["labels"] = [ (row["sim_ts"], row["label"]["intervention"], row["old"], row["new"]) for row in sorted(labels, key=lambda row: row["sim_ts"]) ] return result def report(result: dict) -> None: """Prints the labels and the mean waits.""" for at, name, old, new in result["labels"]: print(f"label at {at:6.1f} s: {name}, packing {old} s to {new} s") for jam, label in ((True, "with the jam"), (False, "without it")): print( f"{label:>12}: mean wait {result[jam]['jam']:6.2f} s from 20 to 30 min, " f"{result[jam]['after']:6.2f} s from 30 to 40 min" ) print( f"the last order that waits longer is queued at {result['last_longer']:.1f} s" ) def live(out: Path) -> SimulationContext: """The same jam sent live, half a second of wall-clock time after the start.""" app = shop(out, jam=False) app.factor = 0.005 # A paced run raises when it falls behind the wall clock, unless strict is off app.strict = False # Half a wall-clock second after the start, set packing to 3 seconds app.add_ingress(LocalIngress(schedule=[(0.5, "Shop.service.packing.value", 3.0)])) # Flush every 60 simulated seconds: at this pace the default of 1 s flushes on a # timer over and over, and desflow warns about it app.with_batching(batch_size=500, flush_interval=60) app.run(until="5 min") return app if __name__ == "__main__": here = Path("live_changes_output") if sys.argv[1:] == ["live"]: # python live_changes.py live: the jam sent live instead # A run adds files; start empty shutil.rmtree(here / "live", ignore_errors=True) env = live(here / "live").env packing = env.registry.get_config("Shop.service.packing").value print(f"packing after the live change: {packing} s") elif sys.argv[1:2] == ["compare"]: # python live_changes.py compare jam baseline: two runs that are already written report(compare(Path(sys.argv[2]), Path(sys.argv[3]))) else: report(outcomes(here)) ``` ```python """The Live Changes tutorial: a label printer jam, written as a scenario, low-level. One packer takes 1.5 seconds to pack an order, and an order arrives every 2.5 seconds on average (rate 0.4). From 20 to 30 minutes a jammed label printer slows packing to 3 seconds. The events are written to events/ and the ground-truth records of the jam to labels/, and the script prints the mean waits with and without the jam. Run it with: python live_changes_low_level.py With the argument live, it sends the jam live: python live_changes_low_level.py live """ import copy import itertools import json import logging import shutil import sys from pathlib import Path from desflow import ( CapacityConfig, DistributionConfig, DynamicRealtimeEnvironment, DynamicResource, JsonlStorageEgress, LocalIngress, Sampler, SimParameter, run_scenario, ) logging.basicConfig(level=logging.WARNING) PARAMS = SimParameter( sim_id="Shop", arrival={"orders": DistributionConfig(dist="exponential", rate=0.4)}, service={"packing": DistributionConfig(dist="constant", value=1.5)}, resources={"packers": CapacityConfig(current_cap=1, max_cap=1)}, ) # The jam: 3 seconds of packing from 20 to 30 minutes, each change recorded JAM = [ { "at": 1200, "path": "Shop.service.packing.value", "value": 3.0, "record": {"intervention": "printer_jam"}, }, { "at": 1800, "path": "Shop.service.packing.value", "value": 1.5, "record": {"intervention": "printer_fixed"}, }, ] def pack_order(env, sampler, packers, key, task_id): path_id = "Shop.service.packing" def publish(value): env.publish_event(key, value, task="pack_order", instance=task_id) publish( {"path_id": path_id, "sim_id": "Shop", "service": "packing", "status": "queued"} ) with packers.request() as request: yield request publish( { "path_id": path_id, "sim_id": "Shop", "service": "packing", "status": "started", } ) yield env.timeout(sampler.sample(env.registry.get_config(path_id))) publish({"event_type": "order_packed"}) def order_generator(env, sampler, packers): arrival = env.registry.get_config("Shop.arrival.orders") for task_id in itertools.count(): yield env.timeout(sampler.sample(arrival)) key = f"orders-{task_id + 1}" env.process(pack_order(env, sampler, packers, key, task_id)) def run( out: Path, jam: bool = True, factor: float = 0.0, until: float = 3600, ingress=None, flush_interval: float = 1.0, ): # strict=False lets a paced run fall behind the wall clock without stopping env = DynamicRealtimeEnvironment(factor=factor, strict=False) # A copy, because a change to the registry changes the parameters it holds env.registry.register_sim_parameter(copy.deepcopy(PARAMS)) env.setup_egress( [ # The events, one flat row per event JsonlStorageEgress(default_path=f"{out}/events/orders.jsonl"), # The ground-truth records only JsonlStorageEgress(default_path=f"{out}/labels/labels.jsonl"), ], labels=[False, True], flush_interval=flush_interval, ) if ingress: env.setup_ingress(ingress) packers = DynamicResource(env, "Shop", "packers") if jam: # Each step applies before every other event at its time env.process(run_scenario(env, JAM, until=until)) env.process(order_generator(env, Sampler(seed=42), packers)) try: env.run(until=until) finally: env.teardown() return env def read_rows(folder: Path) -> list: """Every row of every JSONL file the sink wrote to folder.""" return [ json.loads(line) for path in sorted(folder.glob("*.jsonl")) for line in path.read_text().splitlines() ] def waits(out: Path) -> dict: """The wait of each order, by the time it was queued, in seconds.""" queued, started = {}, {} for row in read_rows(out / "events"): if row.get("status") == "queued": queued[row["instance"]] = row["sim_ts"] elif row.get("status") == "started": started[row["instance"]] = row["sim_ts"] return {queued[i]: started[i] - queued[i] for i in started} def mean_wait(by_time: dict, start: float, end: float) -> float: """The mean wait of the orders queued from start to end, in seconds.""" window = [wait for at, wait in by_time.items() if start <= at < end] return sum(window) / len(window) def outcomes(out: Path) -> dict: """Runs the hour with and without the jam; returns the labels and mean waits.""" result: dict = {} by_run: dict = {} for jam in (True, False): folder = out / ("jam" if jam else "baseline") shutil.rmtree(folder, ignore_errors=True) # a run adds files; start empty run(folder, jam) by_time = by_run[jam] = waits(folder) result[jam] = { "jam": round(mean_wait(by_time, 1200, 1800), 2), "after": round(mean_wait(by_time, 1800, 2400), 2), } # Both runs meet the same orders, so each order's two waits can be compared result["last_longer"] = max( at for at, wait in by_run[True].items() if wait > by_run[False][at] + 0.001 ) labels = read_rows(out / "jam" / "labels") result["labels"] = [ (row["sim_ts"], row["label"]["intervention"], row["old"], row["new"]) for row in sorted(labels, key=lambda row: row["sim_ts"]) ] return result def live(out: Path): """The same jam sent live, half a second of wall-clock time after the start.""" # Half a wall-clock second after the start, set packing to 3 seconds ingress = [LocalIngress(schedule=[(0.5, "Shop.service.packing.value", 3.0)])] # Flush every 60 simulated seconds: at this pace the default of 1 s flushes on a # timer over and over, and desflow warns about it return run( out, jam=False, factor=0.005, until=300, ingress=ingress, flush_interval=60 ) if __name__ == "__main__": here = Path("live_changes_output") if sys.argv[1:] == ["live"]: # python live_changes_low_level.py live: the jam sent live instead # A run adds files; start empty shutil.rmtree(here / "live", ignore_errors=True) env = live(here / "live") packing = env.registry.get_config("Shop.service.packing").value print(f"packing after the live change: {packing} s") else: r = outcomes(here) for at, name, old, new in r["labels"]: print(f"label at {at:6.1f} s: {name}, packing {old} s to {new} s") for jam, label in ((True, "with the jam"), (False, "without it")): print( f"{label:>12}: mean wait {r[jam]['jam']:6.2f} s from 20 to 30 min, " f"{r[jam]['after']:6.2f} s from 30 to 40 min" ) print(f"the last order that waits longer is queued at {r['last_longer']:.1f} s") ``` # Streaming Out The shop of [Changing Demand](https://jaehyeon.me/desflow/latest/learn/inputs/changing-demand/index.md), without the rush, packs orders for an hour. It has one packer, which takes 1.5 seconds to pack an order, and an order arrives every 2.5 seconds on average (24 a minute, `rate: 0.4`). A team downstream wants a file of the finished orders. This page asks: **which records reach the team's files, how does the team find every record of one order, and when are the files complete?** - **Decision:** what the file sink receives, and when the team's job may read the folder. - **Measures:** the records each sink receives, the files the file sink writes and the rows in each. - **Runs:** one unpaced run (`factor: 0`) of the hour with the seed 42. - **Assumptions:** the default batch of 500 records. ## What You Will Learn This page shows how to: - send every record to the terminal and only some of them to a file; - find every record of one order by its key; - know when the files are complete. ## What You Add This page adds two **sinks**: `ConsoleEgress`, which prints every record to the terminal, and `JsonlStorageEgress`, which writes JSON Lines files. The file sink has a `when` predicate that passes only the finished orders. The file sink needs the `parquet` extra, so install `desflow[parquet]` (`pip install "desflow[parquet]"`). Without it, the run logs that pyarrow is required and writes no file. [Egress, Batching and Delivery](https://jaehyeon.me/desflow/latest/user-guide/live-runs-and-connectors/egress/index.md) describes every sink. ______________________________________________________________________ ## Choose What Each Sink Gets Every sink receives every event and every telemetry record, unless its `when` says otherwise. `when` is a test of one record that is true when the record goes to that sink. This one passes the events whose value says `order_packed`: A blueprint writes `when` as an expression over the record. It reads `record.stream_type` (`event` or `telemetry`), `record.key`, `record.task` and `record.value.`. A name the record lacks reads as nothing, so the test is false for a telemetry record and for an event without that field: ```yaml egress: # Every event and every telemetry record - {type: Console} # The finished orders only, one flat row each - type: Jsonl config: {default_path: packed/orders.jsonl} when: {expr: "record.value.event_type == 'order_packed'"} ``` `when: events` and `when: telemetry` pass every record of that stream. A function of your own is written as `when: !python module.function`, as [Call Python from YAML](https://jaehyeon.me/desflow/latest/how-to/tools/yaml-advanced/index.md) shows. ```python def packed_only(record: dict) -> bool: """Keeps the finished orders: events whose value says order_packed.""" return ( record["stream_type"] == "event" and record["value"].get("event_type") == "order_packed" ) ``` ```python # Every event and every telemetry record .add_egress(ConsoleEgress()) # The finished orders only, one flat row each .add_egress( JsonlStorageEgress(default_path=f"{out}/packed/orders.jsonl"), when=packed_only, ) ``` ```python env.setup_egress( [ # Every event and every telemetry record ConsoleEgress(), # The finished orders only, one flat row each JsonlStorageEgress(default_path=f"{out}/packed/orders.jsonl"), ], predicates=[None, packed_only], ) ``` `predicates` takes one entry per sink, in the order of the list, and `None` passes every record. `packed_only` is the same function as in the Builder tab. The test sees the record as published, so an event's payload is still under `value`. A telemetry record's `value` is a single number, so a function checks `stream_type` first. A record that no sink passes is written nowhere. ______________________________________________________________________ ## Find One Order's Records Save the files from [Full Files](#full-files) in one folder and run the commands there: `desflow run streaming_out.yaml`, `python streaming_out.py` or `python streaming_out_low_level.py`. Every event carries three names. `key` names the entity, here the order, and the arrival names the orders `orders-1`, `orders-2`, and so on. `task` names the task, and `instance` names this run of it. The terminal shows the three events of `orders-12`, each with the same three names: ```text [EVT] {'sim_ts': 33.9733203858314, 'timestamp': '...', 'key': 'orders-12', 'task': 'pack_order', 'instance': 11, 'value': {'path_id': 'Shop.service.packing', 'sim_id': 'Shop', 'service': 'packing', 'status': 'queued'}} [EVT] {'sim_ts': 34.3280675455825, 'timestamp': '...', 'key': 'orders-12', 'task': 'pack_order', 'instance': 11, 'value': {'path_id': 'Shop.service.packing', 'sim_id': 'Shop', 'service': 'packing', 'status': 'started'}} [EVT] {'sim_ts': 35.8280675455825, 'timestamp': '...', 'key': 'orders-12', 'task': 'pack_order', 'instance': 11, 'value': {'event_type': 'order_packed'}} ``` The file sink receives only the last of the three, the `order_packed` event. Without a router it writes one flat row per event, with the payload's fields beside the record's own: ```text {"stream_type":"event","sim_ts":35.8280675455825,"timestamp":"...","key":"orders-12","task":"pack_order","instance":11,"event_type":"order_packed"} ``` To find one order's records among the 4,392 of the hour, print the records as JSON lines with `--stdout` and keep the lines with its key. `--stdout` sends the records to the terminal in place of the sinks, so this run writes no files: ```bash desflow run streaming_out.yaml --stdout | grep '"key":"orders-12"' ``` It prints the three events of `orders-12` above, each as the whole record. In the builder and the low-level API, `ConsoleEgress(format="json")` as the sink prints the same lines. A reader that joins the files with another source uses `key`, and one that follows a task through its states uses `task` and `instance`. [Records and Telemetry](https://jaehyeon.me/desflow/latest/reference/records-and-telemetry/#record-shape) lists every field, and [What Each Sink Writes](https://jaehyeon.me/desflow/latest/reference/records-and-telemetry/#what-each-sink-writes) shows how each sink lays them out. ______________________________________________________________________ ## Read the Files The file sink writes one file per batch, named after `default_path` with 8 random hexadecimal digits, such as `packed/orders_1a2b3c4d.jsonl`. A file sink with neither a `default_path` nor a `path_router` writes only the records that carry a `__path__`, and each flush logs a warning that says how many records it skipped. A file, once written, is never changed: ```python def read_files(folder: Path) -> dict: """The rows of each file the sink wrote to folder, by file name.""" return { path.name: [json.loads(line) for line in path.read_text().splitlines()] for path in sorted(folder.glob("*.jsonl")) } ``` The names are random, so the order of the files is not the order of the records. Sort by `sim_ts` when the order matters. A second run in the same folder adds new files beside the old ones, so the scripts empty `packed/` before they run. ______________________________________________________________________ ## Know When the Files Are Complete The model and the sinks finish at different times. The model stops at `until`. A sink receives records in batches. At `factor: 0`, a batch is handed over only when it holds 500 records, and the records left over are handed over at **teardown**, after the model has stopped. Teardown hands over what each sink still holds, then waits until every sink has written it: `desflow run` tears the run down when it reaches `run.until`, and returns once the sinks have finished. `app.run(until="1 h")` tears the run down when it reaches the end, and returns once the sinks have finished. ```python try: env.run(until=3600) # the model stops at 1 hour finally: env.teardown() # the sinks receive the rest and finish writing ``` `env.run` runs SimPy's event loop and stops at `until`, as [SimPy and desflow](https://jaehyeon.me/desflow/latest/simpy/#environment-and-the-event-list) describes. `env.teardown()` is desflow's step that hands over the rest and waits for the sinks. A job that reads the folder while the run is going therefore sees only the full batches. The terminal can show the same effect. On a fast machine the model can finish before the console sink prints its first line, and then every line appears after the log says `Tearing down egress connectors`. Teardown waits for the sinks to finish writing, and gives up only when they have made no progress for `drain_stall_seconds`, as [Egress](https://jaehyeon.me/desflow/latest/user-guide/live-runs-and-connectors/egress/#how-it-works) describes. Records not written by then are lost, with a warning. ______________________________________________________________________ ## What You Get and Why The rows the file sink writes over the hour, counted by the time each order was packed: Which records reach the team's files? These figures come from one unpaced run of the hour with the seed 42. - The terminal receives every record: **4,362** events (**1,454** orders queued, **1,454** started and **1,454** packed) and **30** telemetry records, five statistics read every 10 minutes. - The file sink receives only the **1,454** packed orders, one row each, in **3** files of **500**, **500** and **454** rows. The two files of 500 were handed over while the model ran. The file of 454 was handed over at teardown, after the model stopped. The run returns only when teardown has finished, so the team's job should start only after the run has returned. One order's records share its `key`: `orders-12` was queued at **33.9733** seconds, started at **34.3281** and packed at **35.8281**, rounded to four places. Each tab gives the files' rows and the records of `orders-12`: Run the blueprint in an empty folder, then count the rows of each file it wrote, smallest first: ```bash desflow run streaming_out.yaml > /dev/null 2>&1 for f in packed/*.jsonl; do grep -c . "$f"; done | sort -n ``` ```text 454 500 500 ``` `desflow run streaming_out.yaml --stdout | grep '"key":"orders-12"'` prints the records of `orders-12`, as [Find One Order's Records](#find-one-orders-records) shows. ```bash python streaming_out.py 2>/dev/null ``` ```text 3 files, with [454, 500, 500] rows orders-12: {'stream_type': 'event', 'sim_ts': 35.8280675455825, 'key': 'orders-12', 'task': 'pack_order', 'instance': 11, 'event_type': 'order_packed'} ``` ```bash python streaming_out_low_level.py 2>/dev/null ``` ```text 3 files, with [454, 500, 500] rows orders-12: {'stream_type': 'event', 'sim_ts': 35.8280675455825, 'key': 'orders-12', 'task': 'pack_order', 'instance': 11, 'event_type': 'order_packed'} ``` A record goes from `publish_event` to each sink's `when` test, then into that sink's buffer, then to a queue that a separate thread writes from. The model only fills buffers, so it can finish while the threads are still writing. Teardown is the step that waits for them. Writing records on background threads is one of the things desflow adds to SimPy, as [What desflow Changes](https://jaehyeon.me/desflow/latest/simpy/coming-from-simpy/#what-desflow-changes) sets out. [Egress, Batching and Delivery](https://jaehyeon.me/desflow/latest/user-guide/live-runs-and-connectors/egress/#how-it-works) shows each stage of that path. Finding one order's records by its key is also how a run is checked by hand, as [Read the Trace](https://jaehyeon.me/desflow/latest/learn/concepts/checking-and-validating/#read-the-trace) shows. ## Key Takeaways - Each sink has its own `when` test, so one run can send different records to different places. - A file sink writes in batches, on a separate thread, and the last batch is written at teardown. - Read the files only after the run has returned, when teardown has finished. ______________________________________________________________________ ## Full Files Full files ```yaml # The Streaming Out tutorial: the shop's records, to the terminal and to a file. # Run it with: desflow run streaming_out.yaml # Every record is printed; the finished orders are written to packed/. simulation: {sim_id: Shop, factor: 0, random_seed: 42} resources: packers: {current_cap: 1, max_cap: 1} services: packing: {dist: constant, value: 1.5 s} arrivals: orders: {dist: exponential, rate: 0.4, spawn: pack_order} tasks: pack_order: service: packing resource: packers payload: {event_type: order_packed} # The packers' and the packing task's readings every 10 minutes, as telemetry stats: {level: minimal, interval: 10 min} egress: # Every event and every telemetry record - {type: Console} # The finished orders only, one flat row each - type: Jsonl config: {default_path: packed/orders.jsonl} when: {expr: "record.value.event_type == 'order_packed'"} run: {until: 1 h} ``` ```python """The Streaming Out tutorial: the shop's records, to the terminal and to a file, builder. One packer takes 1.5 seconds to pack an order, and an order arrives every 2.5 seconds on average (rate 0.4), for an hour. Every record is printed to the terminal, and the finished orders are written to packed/. The script then prints the files the sink wrote and one order's row. To see only those lines, run: python streaming_out.py 2>/dev/null """ import json import logging import shutil from pathlib import Path from desflow import ConsoleEgress, JsonlStorageEgress, SimulationContext logging.basicConfig( level=logging.INFO, format="%(levelname)s [%(asctime)s] %(message)s" ) def packed_only(record: dict) -> bool: """Keeps the finished orders: events whose value says order_packed.""" return ( record["stream_type"] == "event" and record["value"].get("event_type") == "order_packed" ) def shop(out: Path) -> SimulationContext: """The shop of Changing Demand, without the rush, writing under out.""" app = ( SimulationContext(sim_id="Shop", factor=0, random_seed=42) .add_resource("packers", current_cap=1, max_cap=1) .add_service("packing", dist="constant", value=1.5) .add_arrival("orders", dist="exponential", rate=0.4) # The packers' and the packing task's readings every 10 minutes, as telemetry .with_stats("minimal", interval=600) # Every event and every telemetry record .add_egress(ConsoleEgress()) # The finished orders only, one flat row each .add_egress( JsonlStorageEgress(default_path=f"{out}/packed/orders.jsonl"), when=packed_only, ) ) @app.task(service_id="packing", resource_id="packers") def pack_order(task_id: int): return {"event_type": "order_packed"} @app.arrival_loop("orders") def order_generator(context: SimulationContext): task_id = 0 while True: order = yield context.wait_for_arrival("orders") context.spawn(pack_order(task_id, entity=order)) task_id += 1 return app def read_files(folder: Path) -> dict: """The rows of each file the sink wrote to folder, by file name.""" return { path.name: [json.loads(line) for line in path.read_text().splitlines()] for path in sorted(folder.glob("*.jsonl")) } def outcomes(out: Path) -> dict: """Runs the hour; returns the rows in each file and the row of orders-12.""" shutil.rmtree(out / "packed", ignore_errors=True) # a run adds files; start empty shop(out).run(until="1 h") files = read_files(out / "packed") rows = [row for file_rows in files.values() for row in file_rows] return { "file_rows": sorted(len(file_rows) for file_rows in files.values()), "row": next(row for row in rows if row["key"] == "orders-12"), } if __name__ == "__main__": r = outcomes(Path("streaming_out_output")) print(f"{len(r['file_rows'])} files, with {r['file_rows']} rows") row = {k: v for k, v in r["row"].items() if k != "timestamp"} print(f"orders-12: {row}") ``` ```python """The Streaming Out tutorial: the shop's records, to the terminal and to a file, low-level. One packer takes 1.5 seconds to pack an order, and an order arrives every 2.5 seconds on average (rate 0.4), for an hour. Every record is printed to the terminal, and the finished orders are written to packed/. The script then prints the files the sink wrote and one order's row. To see only those lines, run: python streaming_out_low_level.py 2>/dev/null """ import itertools import json import logging import shutil from pathlib import Path from desflow import ( CapacityConfig, ConsoleEgress, DistributionConfig, DynamicRealtimeEnvironment, DynamicResource, JsonlStorageEgress, Sampler, SimParameter, ) logging.basicConfig( level=logging.INFO, format="%(levelname)s [%(asctime)s] %(message)s" ) PARAMS = SimParameter( sim_id="Shop", arrival={"orders": DistributionConfig(dist="exponential", rate=0.4)}, service={"packing": DistributionConfig(dist="constant", value=1.5)}, resources={"packers": CapacityConfig(current_cap=1, max_cap=1)}, ) def packed_only(record: dict) -> bool: """Keeps the finished orders: events whose value says order_packed.""" return ( record["stream_type"] == "event" and record["value"].get("event_type") == "order_packed" ) def pack_order(env, sampler, packers, key, task_id): path_id = "Shop.service.packing" def publish(value): # The key names the order; task and instance name this run of the task env.publish_event(key, value, task="pack_order", instance=task_id) publish( {"path_id": path_id, "sim_id": "Shop", "service": "packing", "status": "queued"} ) env.stats.task_queued("pack_order", task_id) with packers.request() as request: yield request publish( { "path_id": path_id, "sim_id": "Shop", "service": "packing", "status": "started", } ) env.stats.task_started("pack_order", task_id) yield env.timeout(sampler.sample(env.registry.get_config(path_id))) publish({"event_type": "order_packed"}) env.stats.task_finished("pack_order", task_id) def order_generator(env, sampler, packers): arrival = env.registry.get_config("Shop.arrival.orders") for task_id in itertools.count(): yield env.timeout(sampler.sample(arrival)) key = f"orders-{task_id + 1}" env.process(pack_order(env, sampler, packers, key, task_id)) def run(out: Path): env = DynamicRealtimeEnvironment(factor=0) env.registry.register_sim_parameter(PARAMS) env.setup_egress( [ # Every event and every telemetry record ConsoleEgress(), # The finished orders only, one flat row each JsonlStorageEgress(default_path=f"{out}/packed/orders.jsonl"), ], predicates=[None, packed_only], ) # The packers' and the packing task's readings every 10 minutes, as telemetry env.setup_stats("Shop", "minimal", interval=600) packers = DynamicResource(env, "Shop", "packers") env.process(order_generator(env, Sampler(seed=42), packers)) try: env.run(until=3600) # the model stops at 1 hour finally: env.teardown() # the sinks receive the rest and finish writing return env def read_files(folder: Path) -> dict: """The rows of each file the sink wrote to folder, by file name.""" return { path.name: [json.loads(line) for line in path.read_text().splitlines()] for path in sorted(folder.glob("*.jsonl")) } def outcomes(out: Path) -> dict: """Runs the hour; returns the rows in each file and the row of orders-12.""" shutil.rmtree(out / "packed", ignore_errors=True) # a run adds files; start empty run(out) files = read_files(out / "packed") rows = [row for file_rows in files.values() for row in file_rows] return { "file_rows": sorted(len(file_rows) for file_rows in files.values()), "row": next(row for row in rows if row["key"] == "orders-12"), } if __name__ == "__main__": r = outcomes(Path("streaming_out_output")) print(f"{len(r['file_rows'])} files, with {r['file_rows']} rows") row = {k: v for k, v in r["row"].items() if k != "timestamp"} print(f"orders-12: {row}") ``` [Experiments](https://jaehyeon.me/desflow/latest/user-guide/results/experiments/index.md) describes every setting of an experiment, its files and its report, and the rest of the [User Guide](https://jaehyeon.me/desflow/latest/user-guide/writing-a-model/index.md) describes each part of desflow in full. The [Kafka Digital Twin](https://jaehyeon.me/desflow/latest/gallery/simulation-models/kafka/index.md) example takes live changes from Kafka and sends its records to Kafka. # Queueing Basics A queue forms when orders arrive faster than the packers can pack them, even for a short time. How long an order waits depends on more than the averages. This page explains the few results of queueing theory that a simulation study uses. Each one is explained with the packing shop of the [tutorial](https://jaehyeon.me/desflow/latest/learn/first-model/first-simulation/index.md) and checked against a run of it. The numbers on this page come from [queueing_basics.py](https://github.com/jaehyeon-kim/desflow/blob/v1.3.0/docs/snippets/pages/queueing_basics.py), which asserts every one of them. ______________________________________________________________________ ## What You Will Learn - how to write the shop as a queueing model, such as M/D/3; - how to work out utilisation, and why the queue settles only below 1; - what Little's law says, why it holds, and how to check a run's statistics with it; - why waits grow fast near full use, and less with several packers; - how the spread of the gaps and the packing times lengthens waits; - how to find the bottleneck of a network of tasks; - how to check a formula against runs of the shop. ______________________________________________________________________ ## Kendall's Notation ### In the Tutorial A queueing model has three parts: the arrivals, the queue, and the servers that serve them. In the shop, the arrivals are the orders, the queue is the line in front of the packers, and the servers are the packers. In desflow a server is one unit of a resource, so the `packers` resource with `current_cap: 3` has three servers. The diagram shows the three things a model must say: how far apart orders arrive, how long a packer takes, and how many packers there are. **Kendall's notation** writes these three things as arrivals/service/servers. The letter `c` stands for the number of servers. The busy hour of [Queues and Capacity](https://jaehyeon.me/desflow/latest/learn/first-model/queues-and-capacity/index.md) is M/D/3: exponential gaps between orders, a constant packing time of 1.5 seconds, and three packers. Each letter names a distribution: - `M` is an exponential distribution. Gaps between orders placed independently of each other are exponential, and such arrivals are called a **Poisson** flow. - `D` is a constant time, the same for every order. - `G` is any distribution. [Measuring a Run](https://jaehyeon.me/desflow/latest/learn/first-model/measuring-a-run/index.md) packs with 40 measured times, so its shop is M/G/3. So M/M/1 has exponential gaps, exponential service times and one server. M/D/1 has constant service times instead, and D/M/1 has constant gaps and exponential service times. When a model leaves out the further terms, they have their defaults: the queue has room for any number of orders, the orders come from an unlimited population, and they are served in the order they arrive. ### Why It Matters Each formula on this page holds for some models and not others. The notation says which one applies. A wait worked out with the M/M/3 formula for an M/D/3 shop is about twice too long, as [Check a Formula Against the Shop](#check-a-formula-against-the-shop) measures. ### How to Use It Write the letters for the model before you use a formula: what the gaps are, what the packing times are, and how many units the resource has. `desflow explain` does the same for each resource. It names the formula it used, or says why none applies. For the busy hour of Queues and Capacity, an M/D/3 shop, its `Wq` column is `-` because there is no closed formula for c > 1 with non-exponential times, as the output under [Utilisation](#utilisation) shows. ### What the Result Means One server with general gaps and general service times (G/G/1), and several servers with service times that are not exponential, have no closed formula for the wait. The run of the shop is then the only measure of the wait, and a formula gives at best an approximation to check it against. One server with exponential gaps and any service times (M/G/1) does have one, the [Pollaczek-Khinchine formula](#pollaczek-khinchine-formula). ______________________________________________________________________ ## Utilisation ### In the Tutorial **Utilisation** is the share of time a server is busy. In the busy hour of Queues and Capacity, orders arrive at 1.8 a second and each takes 1.5 seconds to pack. That is 1.8 × 1.5 = 2.7 seconds of packing arriving every second. Three packers share it, so each is busy 2.7 ÷ 3 = 0.9 of the time, or 90%. In general, utilisation is the arrival rate times the mean service time, divided by the number of servers. Formulas and the `desflow explain` tables write it with these symbols: - λ (lambda) is the arrival rate, 1.8 orders a second. - μ (mu) is the service rate of one server, one over the mean service time: 1 ÷ 1.5 = 0.667 orders a second. - c is the number of servers, 3. - ρ (rho) is the utilisation: ρ = λ ÷ (c × μ) = 1.8 ÷ (3 × 0.667) = 0.9. ### Why It Matters Utilisation decides whether the queue settles at all. There are three cases: - Below 1, the packers have spare time on average. The queue grows and shrinks, and its average length settles. - At exactly 1, the packers have no spare time. The queue does not settle, and it drifts longer over time. The one exception is constant gaps with constant packing times, where each order arrives just as a packer becomes free. - Above 1, orders arrive faster than the packers can pack them. The queue grows without limit in every case. Queues and Capacity runs the busy hour with 1 to 4 packers. One packer (utilisation 2.7) and two (1.35) leave mean waits of 1139.88 and 484.65 seconds, and the waits keep growing with the length of the run. Three packers (0.9) give 1.88 seconds and four (0.675) give 0.24 seconds. ### How to Use It The commands on this page use the files of the tutorials they name. Save them from the Full Files of [Queues and Capacity](https://jaehyeon.me/desflow/latest/learn/first-model/queues-and-capacity/index.md), [Measuring a Run](https://jaehyeon.me/desflow/latest/learn/first-model/measuring-a-run/index.md) and [Choosing Inputs](https://jaehyeon.me/desflow/latest/learn/inputs/choosing-inputs/index.md). Work out utilisation for each resource before you run the model. `desflow explain` does it from the model, without running it. Its output includes these lines: ```bash PACKERS=3 desflow explain queues_and_capacity.yaml ``` ```text Resources +--------------------------------------------------------+ | resource | λ | μ | c | ρ | Wq | L | status | |----------+-----+--------+---+-----+----+---+-----------| | packers | 1.8 | 0.6667 | 3 | 0.9 | - | - | CONGESTED | +--------------------------------------------------------+ ``` ```python def utilisation_before_the_run(): """The packers of the Queues and Capacity shop, as `desflow explain` works them out.""" from queues_and_capacity import shop packers = shop(3).analyze().resources[0] # the busy hour with three packers return packers.rate, packers.service_mean, packers.servers, packers.utilization ``` ```text packers: rate 1.8, mean service 1.5 s, units 3, utilisation 0.9 ``` `desflow explain` and `analyze()` do not support low-level models, because a low-level model makes its links between arrivals, tasks and resources in SimPy code as it runs. Work out ρ by hand, or explain the [YAML or builder form](https://jaehyeon.me/desflow/latest/learn/first-model/queues-and-capacity/#explain-the-load) of the model. The status column is `OK` below 0.85, `CONGESTED` from 0.85 and `UNSTABLE` from 1. ### What the Result Means A utilisation of 1 or above means the design needs more capacity, and no run length gives a stable answer. A utilisation below 1 means the queue settles, but not that the wait is short: [Waits Near Full Use](#waits-near-full-use) shows how long it can be at 0.9. A run measures utilisation too, as `utilization_avg`, a percentage. Measuring a Run's busy hour measured 89.98%, close to the 0.9 of the formula. The formula with that run's own figures gives the same share: 6,488 orders finished in 3,600 seconds is 1.802 a second, and its packing times averaged 1.4977 seconds, so 1.802 × 1.4977 ÷ 3 = 0.900. That hour's random gaps were very close to the mean of 1 ÷ 1.8 seconds: ```text utilisation 0.900 measured, 0.900 from the run's rate and service ``` ______________________________________________________________________ ## Little's Law ### In the Tutorial **Little's law** says that, in a system that settles, the average number of orders in it equals the arrival rate times the average time an order spends in it: L = λ × W. It needs no assumption about the gaps, the packing times or the order of service. It holds for the queue alone, for the packers alone, and for the whole shop. In the busy hour of [Measuring a Run](https://jaehyeon.me/desflow/latest/learn/first-model/measuring-a-run/index.md), 6,488 orders finished in 3,600 seconds, so λ = 1.802 orders a second. The mean wait was 2.0065 seconds, so λ × W = 1.802 × 2.0065 = 3.616. The time-weighted average queue length was 3.618 orders. The two figures agree. ### Why It Matters The law holds because both sides count the same total. Add up, over the hour, the seconds each order spent in the queue. Counted second by second, the total is the number waiting at each moment, added over 3,600 seconds: L × 3,600. Counted order by order, it is the number of orders times their mean wait: λ × 3,600 × W. The two totals are equal, so L = λ × W. desflow measures the queue length, the arrival count and the wait separately. If they do not agree, one of them is wrong. That makes the law the first check on a model's statistics, before any result is trusted. ### How to Use It Read the five statistics at the end of a run, and compare L with λ × W for the queue and for the whole shop. The number in the whole shop is the queue plus the orders being packed, and the orders being packed are the three packers times their utilisation. This function does the arithmetic on the readings of any run of the shop: ```python def littles_law(readings: dict, seconds: float): """The arrival rate, then L and lambda x W for the queue and for the whole shop.""" rate = readings["Shop.stats.flows.orders.finished"] / seconds in_queue = readings["Shop.stats.resources.packers.queue_length_avg"] packers = readings["Shop.stats.resources.packers.capacity"] in_service = ( packers * readings["Shop.stats.resources.packers.utilization_avg"] / 100 ) wait = readings["Shop.stats.tasks.pack_order.wait_mean"] service = readings["Shop.stats.tasks.pack_order.service_mean"] return ( rate, (in_queue, rate * wait), (in_queue + in_service, rate * (wait + service)), ) ``` Each tab runs the Measuring a Run hour and reads its statistics: ```bash # Utilisation, queue length, mean wait and packing time, and orders finished desflow run measuring_a_run.yaml --stdout | grep -E 'utilization_avg"|queue_length_avg"|(wait|service)_mean"|orders\.finished"' | tail -5 ``` ```text {"stream_type":"telemetry","sim_ts":3600.0,"timestamp":"...","path_id":"Shop.stats.resources.packers.utilization_avg","value":89.98409865705875} {"stream_type":"telemetry","sim_ts":3600.0,"timestamp":"...","path_id":"Shop.stats.resources.packers.queue_length_avg","value":3.617867825881605} {"stream_type":"telemetry","sim_ts":3600.0,"timestamp":"...","path_id":"Shop.stats.tasks.pack_order.wait_mean","value":2.0065204395584315} {"stream_type":"telemetry","sim_ts":3600.0,"timestamp":"...","path_id":"Shop.stats.tasks.pack_order.service_mean","value":1.4977034525277377} {"stream_type":"telemetry","sim_ts":3600.0,"timestamp":"...","path_id":"Shop.stats.flows.orders.finished","value":6488} ``` Put these five values into the arithmetic of `littles_law`, with 3 packers and 3,600 seconds. ```python from measuring_a_run import app app.run(until="1 h") readings = app.env.stats.readings() ``` Then `littles_law(readings, 3600)`. ```python from measuring_a_run_low_level import run env = run() readings = env.stats.readings() ``` Then `littles_law(readings, 3600)`. All three give the same figures: ```text arrival rate 1.802 orders a second queue: L 3.618, lambda x W 3.616 shop: L 6.317, lambda x W 6.315 ``` ### What the Result Means The queue gives 3.618 against 3.616, and the whole shop 6.317 against 6.315. Both agree within 0.1%. The 3 orders still in the shop when the hour ended explain part of the difference for the whole shop: the time they have spent in the shop counts in L, but their full time in the shop is not yet in W. All 3 are being packed and none is in the queue, so their waits are already in W and they do not change the queue's figures. In a long run of a settled shop, a difference of more than a few percent means a statistic is wrong, for example a task that keeps its packer after it finishes. [Checking and Validating](https://jaehyeon.me/desflow/latest/learn/concepts/checking-and-validating/index.md) uses the law as one of its checks. ______________________________________________________________________ ## Waits Near Full Use ### In the Tutorial [Parameter Sweeps](https://jaehyeon.me/desflow/latest/learn/studies/parameter-sweeps/index.md) runs the busy hour with three packers and the measured packing times at four arrival rates, 20 replications each. At 1.6 orders a second (utilisation 0.8) the mean wait is 0.90 seconds. At 1.8 (utilisation 0.9) it is 2.15 seconds. At 1.9 (utilisation 0.95) it is 4.52 seconds. A rise of 6% in the rate more than doubles the wait. ### Why It Matters For one server with exponential gaps and service times (M/M/1), the mean wait in the queue has a closed form: utilisation ÷ (1 − utilisation) × the mean service time. With constant service times (M/D/1) it is exactly half. The first part, utilisation ÷ (1 − utilisation), grows faster and faster as utilisation nears 1: it is 1 at 0.5, 9 at 0.9 and 19 at 0.95. The bars show this for one packer with a mean packing time of 1.5 seconds: So a design that only keeps utilisation below 1 is not enough. A shop that is stable can still make orders wait a long time, and a small change in demand changes the wait a great deal. ### How to Use It The formulas are short enough to compute. These functions are the ones the rest of the page uses: ```python def mm1_wait(utilisation: float) -> float: """Mean wait in the queue of an M/M/1 queue: utilisation / (1 - utilisation) x service.""" return utilisation / (1 - utilisation) * SERVICE def erlang_c(units: int, load: float) -> float: """The share of arrivals that find all `units` busy, for a load in packers' worth of work.""" last = load**units / math.factorial(units) / (1 - load / units) return last / (sum(load**k / math.factorial(k) for k in range(units)) + last) def mmc_wait(units: int, arrival_rate: float) -> float: """Mean wait in the queue of an M/M/c queue: Erlang C divided by (c / service - lambda).""" return erlang_c(units, arrival_rate * SERVICE) / (units / SERVICE - arrival_rate) def kingman_wait(utilisation: float, arrival_cv: float, service_cv: float) -> float: """Kingman's formula for the mean wait in a one-server queue.""" variability = (arrival_cv**2 + service_cv**2) / 2 return utilisation / (1 - utilisation) * variability * SERVICE ``` ```text utilisation 0.5: mean wait M/M/1 1.50 s, M/D/1 0.75 s utilisation 0.75: mean wait M/M/1 4.50 s, M/D/1 2.25 s utilisation 0.9: mean wait M/M/1 13.50 s, M/D/1 6.75 s utilisation 0.95: mean wait M/M/1 28.50 s, M/D/1 14.25 s ``` `desflow explain` gives the same figure for a one-packer model: for the shop of First Simulation, M/D/1 at utilisation 0.75, its `Wq` column reads 2.25 seconds. ### What the Result Means Near full use, the wait depends strongly on the exact arrival rate. Before trusting a wait at a utilisation of 0.9 or more, check how good the estimate of the rate is, as Parameter Sweeps does. A run near full use also needs to be long before its mean wait settles, as [Output Analysis](https://jaehyeon.me/desflow/latest/learn/concepts/output-analysis/index.md) explains. ______________________________________________________________________ ## Several Packers ### In the Tutorial The busy hour has three packers with constant packing at utilisation 0.9. Ten long runs of it give a mean wait of 2.06 seconds, as [Check a Formula Against the Shop](#check-a-formula-against-the-shop) shows. One packer with constant packing at the same utilisation would make orders wait 6.75 seconds on average, by the M/D/1 formula above. Three packers sharing one queue wait far less at the same utilisation. ### Why It Matters With several packers sharing one queue, an order waits only when every packer is busy. For exponential gaps and service times (M/M/c), the share of orders that find every packer busy is the **Erlang C** formula. The mean wait in the queue is that share divided by (c ÷ the mean service time − the arrival rate). The `erlang_c` and `mmc_wait` functions above compute it. ### How to Use It Compare three packers with a queue each against three packers sharing one queue, with the formulas. With a mean packing time of 1.5 seconds and utilisation 0.8, each of the three packers with its own queue is one packer at utilisation 0.8, and gives a mean wait of 6 seconds. Three packers sharing one queue give about 1.6 seconds: ```text one packer at utilisation 0.8: mean wait 6.0 s three packers at utilisation 0.8: mean wait 1.62 s ``` ### What the Result Means Pooling packers into one queue shortens the wait at the same load. A design question such as "one fast packer or three slower ones" depends on the measure, so utilisation alone cannot answer it. With one packer three times as fast, with a mean of 0.5 seconds at utilisation 0.8, an order waits 2.0 seconds in the queue and spends 2.5 seconds in the system. With three slower packers sharing a queue, it waits about 1.6 seconds and spends about 3.1 seconds in the system. The formula covers exponential times only, so the shop's own runs answer the question for other times. ______________________________________________________________________ ## Variation Lengthens Waits ### In the Tutorial [Choosing Inputs](https://jaehyeon.me/desflow/latest/learn/inputs/choosing-inputs/index.md) runs the busy hour with four candidate packing times, all with a mean of 1.5 seconds. The mean waits are 1.88 seconds with constant times, 1.95 with triangular, 1.81 with the measured times and 3.46 with exponential. The same mean with the widest spread, the exponential, gives a much longer wait. The three narrower spreads give waits within 8% of each other in one run, and their order is not that of their spreads. ### Why It Matters **Kingman's formula** gives an approximate mean wait for one server with any distributions. It measures the spread of each input by its **coefficient of variation**, the standard deviation divided by the mean, called variation for short. The variation is 1 for an exponential distribution and 0 for a constant one. The mean wait is the product of three parts: - utilisation ÷ (1 − utilisation), which grows quickly as utilisation nears 1; - (arrival variation² + service variation²) ÷ 2, the effect of the spread; - the mean service time. With exponential gaps (variation 1) and constant service (variation 0), the middle part is 0.5. The formula then gives half the M/M/1 wait, which is the M/D/1 result above. Variation in the gaps counts as much as variation in the packing times. When both variations are 0, the formula gives no wait at all. #### Pollaczek-Khinchine Formula For one server with exponential gaps and any service times (M/G/1), the **Pollaczek-Khinchine formula** gives the mean wait exactly: utilisation ÷ (1 − utilisation) × (1 + service variation²) ÷ 2 × the mean service time. It is Kingman's formula with an arrival variation of 1. With constant service it gives the M/D/1 wait, and with exponential service it gives the M/M/1 wait. ### How to Use It The `kingman_wait` function above computes Kingman's formula, and with an arrival variation of 1 it gives the Pollaczek-Khinchine wait. Use it to judge how much the choice of an input distribution matters before you fit one. Choosing Inputs shows how to compare the candidates by running each. ### What the Result Means A model whose inputs are replaced by their averages has no variation, so it shows no queue while utilisation is below 1. Its waits are too short. [Common Mistakes](https://jaehyeon.me/desflow/latest/learn/concepts/common-mistakes/index.md) lists this among the errors that distort a result. ______________________________________________________________________ ## Flow Balance and the Bottleneck ### In the Tutorial [A Flow of Tasks](https://jaehyeon.me/desflow/latest/learn/shop-logic/flow-of-tasks/#networks-and-bottlenecks) adds a checker to the shop. Orders arrive at 1.6 a second, every packed order is checked, and a tenth of the checked orders go back to packing. Four packers take 1.5 seconds an order, and one checker takes 0.4 seconds on average. ### Why It Matters In a network of tasks, work reaches a task in two ways: as new work, and as work routed to it from other tasks. The rate into a task is the sum of the two. This is **flow balance**. For packing, the rate is 1.6 + 0.1 × the rate into packing. Solving for it gives 1.6 ÷ (1 − 0.1) = 1.6 ÷ 0.9 = 1.778 orders a second. Every packed order goes to the checker, so the checker receives the same 1.778. Each resource's utilisation follows from its rate. The four packers have 1.778 × 1.5 ÷ 4 = 0.667. The checker has 1.778 × 0.4 = 0.711. The resource with the highest utilisation is the **bottleneck**, here the checker. It is the first to reach full use when demand grows, and adding units anywhere else does not raise the most the shop can handle. ### How to Use It Work out the rate into each task, then each resource's utilisation: ```python # Orders arrive at 1.6 a second, and a tenth of the checked orders go back to packing, # so the rate into packing solves: rate = 1.6 + 0.1 x rate. flow_rate = 1.6 / (1 - 0.1) packers = flow_rate * 1.5 / 4 # four packers, 1.5 seconds an order checker = flow_rate * 0.4 # one checker, 0.4 seconds an order on average print(f"rate into packing and into checking: {flow_rate:.3f} orders a second") print(f"utilisation: packers {packers:.3f}, checker {checker:.3f}") ``` `desflow explain` does the same from the model and names the bottleneck, as [A Flow of Tasks](https://jaehyeon.me/desflow/latest/learn/shop-logic/flow-of-tasks/#networks-and-bottlenecks) shows. The last line below is what the Builder's `analyze()` reports for the same shop: ```text rate into packing and into checking: 1.778 orders a second utilisation: packers 0.667, checker 0.711 desflow explain names the bottleneck: checkers ``` ### What the Result Means Add capacity at the bottleneck first. Here a second checker lowers the checker's utilisation to 0.356, while a fifth packer lowers the packers' utilisation but leaves the checker at 0.711, so it does not raise the most the shop can handle. Rework raises the load on every task it passes through, so a model without it underestimates every utilisation. ______________________________________________________________________ ## Check a Formula Against the Shop ### In the Tutorial The busy hour with exponential packing times is M/M/3 at utilisation 0.9. The Erlang C formula gives a mean wait of 4.083 seconds. Ten one-hour runs of the shop measure 4.784 ± 1.301 seconds, so the formula lies within the interval of the runs. ### Why It Matters A formula and a run that agree check each other. The formula shows that the model is built as intended, and the runs show that the formula applies. A model that disagrees with a formula on a case the formula covers has a fault in its logic or its statistics. ### How to Use It `desflow explain --verify` runs the model and compares each measure with the analysis. [Check Against Theory](https://jaehyeon.me/desflow/latest/how-to/analysis/check-against-theory/index.md) runs it step by step on this shop with exponential packing times, where the Erlang C wait is 4.083 seconds and ten one-hour runs measure 4.784 ± 1.301 seconds. This shop takes the gaps and the packing times as exponential or constant by choice: ```python def shop(arrival: dict, service: dict, packers: int) -> SimulationContext: """The shop with the given arrival gaps and packing times, and `packers` packers.""" app = SimulationContext(sim_id="Shop", factor=0, random_seed=42) app.add_arrival("orders", **arrival) app.add_service("packing", **service) app.add_resource("packers", current_cap=packers, max_cap=10) app.with_stats("typical", interval=3600) @app.task(service_id="packing", resource_id="packers") def pack_order(task_id): return {"event_type": "order_packed"} @app.arrival_loop("orders") def order_generator(context): task_id = 0 while True: order = yield context.wait_for_arrival("orders") context.spawn(pack_order(task_id, entity=order)) task_id += 1 return app # Exponential gaps and times are the M of Kendall's notation, constant ones the D def exponential(mean: float) -> dict: return {"dist": "exponential", "rate": 1 / mean} def constant(mean: float) -> dict: return {"dist": "constant", "value": mean} ``` This function runs ten [replications](https://jaehyeon.me/desflow/latest/learn/concepts/output-analysis/#replications), each leaving out its first 2,000 seconds, and returns the mean wait with its 95% [half-width](https://jaehyeon.me/desflow/latest/learn/concepts/output-analysis/#interval-and-half-width): ```python def measured_wait(arrival: dict, service: dict, packers: int, until: int): """Mean wait over 10 runs, with its 95% half-width; each run leaves out its first 2,000 s.""" result = replicate( lambda: shop(arrival, service, packers), 10, seed=42, until=until, warmup=2000, measures=["tasks.pack_order.wait_mean"], ) row = result.summary[0] return row["mean"], row["half_width"] ``` `--verify` does not support low-level models. `replicate` runs a `LowLevelModel` the same way, as [Replications](https://jaehyeon.me/desflow/latest/user-guide/results/replications/index.md) shows, and its mean and half-width compare with a formula as in the Builder tab. The Builder tab's checks compare each formula with the runs, and pass when the formula lies within the interval: ```python for rho, figures in ((0.5, (1.50, 1.50, 0.06)), (0.75, (4.50, 4.39, 0.31))): arrival = exponential(SERVICE / rho) check( f"M/M/1 at utilisation {rho}", mm1_wait(rho), measured_wait(arrival, exponential(SERVICE), 1, 20_000), figures, ) check( "M/M/3 at utilisation 0.8", mmc_wait(3, 1.6), measured_wait(exponential(1 / 1.6), exponential(SERVICE), 3, 30_000), (1.62, 1.57, 0.09), ) arrival = exponential(SERVICE / 0.75) check( "M/D/1 at utilisation 0.75, Kingman", kingman_wait(0.75, 1, 0), measured_wait(arrival, constant(SERVICE), 1, 20_000), (2.25, 2.23, 0.13), ) ``` ```text M/M/1 at utilisation 0.5: formula 1.50 s, mean of 10 runs 1.50 ± 0.06 s M/M/1 at utilisation 0.75: formula 4.50 s, mean of 10 runs 4.39 ± 0.31 s M/M/3 at utilisation 0.8: formula 1.62 s, mean of 10 runs 1.57 ± 0.09 s M/D/1 at utilisation 0.75, Kingman: formula 2.25 s, mean of 10 runs 2.23 ± 0.13 s ``` The busy hour itself is M/D/3, which has no closed formula. For one packer, constant service halves the M/M/1 wait. This check compares the M/D/3 runs with half the M/M/3 wait, as an approximation: ```python # The busy hour is M/D/3: exponential gaps (M), constant service (D), three packers. # The runs are compared with half the M/M/3 wait at this load. check( "M/D/3 at utilisation 0.9, half the M/M/3 wait", mmc_wait(3, 1.8) / 2, measured_wait(exponential(1 / 1.8), constant(SERVICE), 3, 20_000), (2.04, 2.06, 0.17), ) ``` ```text M/D/3 at utilisation 0.9, half the M/M/3 wait: formula 2.04 s, mean of 10 runs 2.06 ± 0.17 s ``` These are [10 runs of 20,000 seconds](https://jaehyeon.me/desflow/latest/learn/concepts/output-analysis/#busy-hour-figures), each without its first 2,000 seconds, not one-hour runs. Kingman's formula is an approximation, and this check shows where it is not exact. Constant gaps of 2 seconds with exponential service (D/M/1) at utilisation 0.75: ```python mean, half_width = measured_wait( constant(SERVICE / 0.75), exponential(SERVICE), 1, 20_000 ) kingman = kingman_wait(0.75, 0, 1) print( f"D/M/1 at utilisation 0.75: Kingman {kingman:.2f} s, mean of 10 runs {mean:.2f} ± {half_width:.2f} s" ) ``` ```text D/M/1 at utilisation 0.75: Kingman 2.25 s, mean of 10 runs 1.76 ± 0.08 s ``` ### What the Result Means Where a formula is exact, as for M/M/1 and M/M/c, it lies within the interval of the runs. Half the M/M/3 wait is close for the M/D/3 busy hour. Kingman's formula lies outside the interval for D/M/1: it is exact with exponential gaps, accurate near full use, and a rough guide elsewhere. A check that fails on a case the formula covers points to a fault in the model. A check that fails outside the formula's cases says only that the formula does not apply. ______________________________________________________________________ ## Key Takeaways - Write the model in Kendall's notation first, to know which formulas apply. - Work out utilisation for every resource before a run. At 1 or above, the answer is more capacity. - Check a run's statistics with Little's law before trusting any result. - Expect long waits near full use, and longer ones when gaps or packing times vary. - Find the bottleneck with flow balance, and add capacity there first. - Check the model against a formula on the cases the formula covers. The simulation answers the cases it cannot: several resources, priorities, breakdowns and changing demand. ______________________________________________________________________ ## Sources - Wikipedia: [Kendall's notation](https://en.wikipedia.org/wiki/Kendall%27s_notation), [Little's law](https://en.wikipedia.org/wiki/Little%27s_law), [Kingman's formula](https://en.wikipedia.org/wiki/Kingman%27s_formula), the [Erlang C formula]() and the [Jackson network](https://en.wikipedia.org/wiki/Jackson_network). - The explanations and the checks are our own. # A Simulation Study Building a model is one step of a simulation study, and often not the largest. This page walks through the whole study, from the question to the report, with the packing shop as the example. Each step says what to produce and names the tutorial page that does it for the shop. [The Complete Model](https://jaehyeon.me/desflow/latest/learn/studies/complete-model/index.md) runs every step in order. The steps follow Law's seven-step approach. Two steps are checks: [Check the Assumptions](#check-the-assumptions) checks the conceptual model, and [Build and Check the Model](#build-and-check-the-model) checks the programmed model. When either check fails, the study goes back to [Ask One Question](#ask-one-question) and [Conceptual Model and Data](#conceptual-model-and-data), because the question or the conceptual model may need to change. Law notes that programming the model is only 25 to 50 percent of the work of a sound study, despite the common view of simulation as a programming exercise. ______________________________________________________________________ ## What You Will Learn - how to write a question that a study can answer; - what a conceptual model holds, and how to choose the inputs; - how AIC and the KS test score a fitted distribution; - how the assumptions and the model are checked; - how an experiment answers the question; - what a report of the study states. ______________________________________________________________________ ## Ask One Question ### In the Tutorial The shop's question is: **how many packers keep the mean wait under 10 seconds in the busy hour?** The measures are the mean wait of an order and how busy the packers are. The question also fixes the period (the busy hour), the system (the packing area, not the whole warehouse) and who decides (the shop manager). ### Why It Matters A study with no well-defined objective cannot say when it is finished, and Law lists this first among the pitfalls. Without a specific question the right level of model detail cannot be set either: every part of the warehouse could be modelled, and nothing says which parts matter. ### How to Use It Write the question and its measures down before building anything. Name the measure as a statistic the model publishes, such as `tasks.pack_order.wait_mean`, and the value that decides the answer, such as 10 seconds. An experiment file can state the question and check the decision rule, as [Comparing Designs](https://jaehyeon.me/desflow/latest/learn/studies/comparing-designs/index.md) does. ### What the Result Means [Queues and Capacity](https://jaehyeon.me/desflow/latest/learn/first-model/queues-and-capacity/index.md) answers the question: 3 packers. [Trusting Results](https://jaehyeon.me/desflow/latest/learn/studies/trusting-results/index.md) measures the mean wait of an order with 3 packers: 2.10 ± 0.10 seconds, the mean of 40 [replications](https://jaehyeon.me/desflow/latest/learn/concepts/output-analysis/#replications) with the half-width of its [95% interval](https://jaehyeon.me/desflow/latest/learn/concepts/output-analysis/#interval-and-half-width). Those runs use the measured packing times and a 2-minute [warm-up](https://jaehyeon.me/desflow/latest/learn/concepts/output-analysis/#one-run-starts-empty), and [other pages run the hour in other ways](https://jaehyeon.me/desflow/latest/learn/concepts/output-analysis/#busy-hour-figures). The whole interval is far below 10 seconds, so the answer holds at this precision. ______________________________________________________________________ ## Conceptual Model and Data ### In the Tutorial The shop's **conceptual model** says what the model includes, the assumptions it makes and the data it needs: - Orders arrive one at a time, at a rate that does not change during the hour. - A packer takes the next order from one queue, in order, and packs it. - Packing takes 1.5 seconds on average. The first model uses a constant 1.5 seconds, and [Choosing Inputs](https://jaehyeon.me/desflow/latest/learn/inputs/choosing-inputs/index.md) replaces it with the times measured at the bench. - Pickers, stock and delivery are outside the model. ### Why It Matters Law calls this the assumptions document. It is what the people who know the shop check, and what the model is checked against. It also decides how much detail goes in. Law warns against building one model element for each element of the real system: more detail costs run time, can miss the deadline and can hide the factors that matter. Each input is an estimate until it is measured. For the shop these are the arrival rate and the packing time. ### How to Use It Collect what is known about the system and write the document before writing code. Take the data from the real system where it exists, choose a distribution for each input, and test how much the choice matters. [Choosing Inputs](https://jaehyeon.me/desflow/latest/learn/inputs/choosing-inputs/index.md) compares the candidate distributions, and [Fitting the Inputs](https://jaehyeon.me/desflow/latest/learn/inputs/fit-the-inputs/index.md) fits them to measured times. Add detail only when it can change the decision. [Model Parts](https://jaehyeon.me/desflow/latest/user-guide/model-parts/index.md) lists the parts a model can have. ### What the Result Means A model with an input nobody has measured is still usable, as long as the study tests how far the answer depends on it. [Parameter Sweeps](https://jaehyeon.me/desflow/latest/learn/studies/parameter-sweeps/index.md) does this for the arrival rate: with three packers the wait depends strongly on the rate, and with four it does not. ______________________________________________________________________ ## AIC and the KS Test ### In the Tutorial Fitting a distribution to measured times gives a candidate from each family, such as a gamma or a lognormal, and two scores say how well each candidate matches the data. For the shop's 40 packing times, [Fitting the Inputs](https://jaehyeon.me/desflow/latest/learn/inputs/fit-the-inputs/#fit-the-packing-times) gives the triangular an AIC of 56.68 and the gamma 56.79. ### Why It Matters The two scores measure different things: - **AIC**, Akaike's information criterion, scores how likely the data is under the fitted family, with a penalty for each parameter the fit chose: 2k − 2 × the log-likelihood, where k is the number of parameters. Lower is better. - **KS**, the Kolmogorov-Smirnov statistic, is the largest gap between the share of the data below a value and the share the family puts below it. Its **p-value** is the chance of a gap at least that large if the data came from the family. ### How to Use It `desflow fit` fits each family to a column of measured values and prints both scores, as Fitting the Inputs shows. Compare the AIC of two families on the same data: only the difference means anything. Use the KS p-value to rule a family out: a small p-value, such as below 0.05, is a reason to reject it. ### What the Result Means By a common guideline, an AIC difference below 2 does not tell two fits apart, so the triangular and the gamma fit the shop's times equally well. When the family was fitted to the same data, the KS p-value is approximate and tends to be too high. A good score therefore does not settle the choice. Run the model with each close candidate and check whether the answer changes, as Fitting the Inputs does. ______________________________________________________________________ ## Check the Assumptions ### In the Tutorial Ask the shop manager whether arrivals really are steady in the busy hour, and whether a packer ever does anything else. If orders come in a rush at the start of the hour, the first assumption is wrong, and [Changing Demand](https://jaehyeon.me/desflow/latest/learn/inputs/changing-demand/index.md) shows the model that follows. ### Why It Matters Law calls this step a structured walk-through. It finds wrong assumptions before code depends on them. It also makes the results more credible to the people who will act on them, because they have checked what the model assumes. ### How to Use It Walk the people who know the system through the assumptions document, one line at a time. Record each assumption they confirm, and change the document where they correct it. An experiment file keeps the agreed assumptions, the source of each input and the limits of the model, as [The Complete Model](https://jaehyeon.me/desflow/latest/learn/studies/complete-model/#build-the-report) does. ### What the Result Means An assumption the owner of the system confirms can go into the model. One they correct sends the study back to the conceptual model, before any code is written. ______________________________________________________________________ ## Build and Check the Model ### In the Tutorial The shop's model is built in [First Simulation](https://jaehyeon.me/desflow/latest/learn/first-model/first-simulation/index.md) and extended in the tutorials that follow it. [Checking a Model](https://jaehyeon.me/desflow/latest/learn/studies/checking-a-model/index.md) checks it: it traces fixed inputs, pushes the inputs to extremes, compares the model with queueing theory and with the real shop, and tests its sensitivity. ### Why It Matters A model can run without errors and still be wrong. The checks are of two kinds, which [Checking and Validating](https://jaehyeon.me/desflow/latest/learn/concepts/checking-and-validating/index.md) describes. **Verification** checks that the program does what the conceptual model says. **Validation** checks that the model is a good enough picture of the shop for the question. ### How to Use It Verify by reading the trace, working a case by hand, and comparing the statistics with each other. `desflow explain --verify` compares the model with the queueing formulas where they apply. Validate by comparing the model's results with the real shop's where there is data, and by testing its sensitivity to the inputs. [Queueing Basics](https://jaehyeon.me/desflow/latest/learn/concepts/queueing-basics/index.md) gives the formulas that check the queue. ### What the Result Means A model that passes the checks is fit for the question it was checked against, not for every question. A failed check sends the study back to the conceptual model or to the code. ______________________________________________________________________ ## Run the Experiments ### In the Tutorial [Comparing Designs](https://jaehyeon.me/desflow/latest/learn/studies/comparing-designs/index.md) compares three packers with four. Over 20 replications of each design with the same seeds, a fourth packer cuts the busy hour's mean wait by 1.89 ± 0.14 seconds (the mean difference and the half-width of its 95% interval). ### Why It Matters An experiment is a set of runs designed to answer the question. One run of each design can show a difference that comes from the random numbers alone. Several replications, with the same seeds for each design, give an interval for the difference. ### How to Use It Decide the run length, the warm-up and the number of replications, then run each design and compute an interval for each measure. [Output Analysis](https://jaehyeon.me/desflow/latest/learn/concepts/output-analysis/index.md) explains these choices, and [Trusting Results](https://jaehyeon.me/desflow/latest/learn/studies/trusting-results/index.md) makes them for the shop. `desflow experiment` runs the designs and the checks from one file. ### What the Result Means The interval for the difference, 1.89 ± 0.14 seconds, lies wholly above 0, so the fourth packer shortens the wait at this precision. Whether 1.89 seconds is worth a packer is the shop manager's decision, not the model's. ______________________________________________________________________ ## Report the Result ### In the Tutorial [The Complete Model](https://jaehyeon.me/desflow/latest/learn/studies/complete-model/index.md) ends with `report.md`. It states the comparisons and the checks, the observed comparison, the assumptions, where each input came from, and the limits of the model. ### Why It Matters A reader who was not part of the study acts on the report alone. The report must let that reader judge how far to trust the answer, and repeat the study. ### How to Use It State the answer to the question first, then the evidence for it. Say what the model includes and leaves out, what the inputs were and where they came from, how the model was checked, and how precise each result is. `desflow report` writes the report from an experiment's results. [Readiness and Reporting](https://jaehyeon.me/desflow/latest/learn/concepts/readiness-and-reporting/index.md) lists what to include, and [Common Mistakes](https://jaehyeon.me/desflow/latest/learn/concepts/common-mistakes/index.md) lists the errors that make a study wrong. ### What the Result Means A study often repeats. A result that surprises is a reason to check the model again, and a changed question is a reason to change the model. The steps are an order of work, not a one-way path. ______________________________________________________________________ ## Key Takeaways - Write one question, its measures and the value that decides it, before building anything. - Write the assumptions down, and have the people who know the system check them. - Choose each input from data where it exists, and test how much the choice matters. - Verify the program and validate the model before trusting a result. - Answer the question with intervals from replications, and report the answer first, with its limits. ______________________________________________________________________ ## Sources - Law, "How to Conduct a Successful Simulation Study" (Winter Simulation Conference, 2003), which gives the seven-step approach. We read the paper in full. - Wikipedia: the [Akaike information criterion](https://en.wikipedia.org/wiki/Akaike_information_criterion) and the [Kolmogorov-Smirnov test](https://en.wikipedia.org/wiki/Kolmogorov%E2%80%93Smirnov_test). - The wording and the shop example are our own. # Checking and Validating A model that runs is not a model that is right. This page explains how to check a model in two ways that need different evidence: **verification** asks whether the program does what the model on paper says, and **validation** asks whether that model is a good enough picture of the real system for the question. Both are done on the way through a [simulation study](https://jaehyeon.me/desflow/latest/learn/concepts/a-simulation-study/index.md), and neither is finished by one test. [Checking a Model](https://jaehyeon.me/desflow/latest/learn/studies/checking-a-model/index.md) applies every check on this page to the shop. The page's own one-packer cases come from [checking_and_validating.py](https://github.com/jaehyeon-kim/desflow/blob/v1.3.0/docs/snippets/pages/checking_and_validating.py), which asserts each number. ______________________________________________________________________ ## What You Will Learn - the difference between verification and validation; - how to read a trace and work a case by hand; - which statistics must agree with each other, and which formulas a run must match; - how to compare a model with the real system, and what to do when they disagree; - how sensitivity analysis shows whether an estimate is good enough. ______________________________________________________________________ ## Verification and Validation ### In the Tutorial The model on paper says the shop's arrivals, packing times and number of packers. The program is the `SimulationContext`, the blueprint or the low-level code that runs them. The real shop is the packing area with its own records. Verification compares the program with the model on paper. Validation compares the program's results with the real shop. ### Why It Matters Banks et al., as the [lecture notes](https://courses.ie.bilkent.edu.tr/ie324/wp-content/uploads/sites/4/2016/09/Validation.pdf) give it, put the difference briefly: verification is building the model correctly, and validation is building the correct model. A model can pass one and fail the other. A program can follow the model on paper exactly, while the model leaves out the thing that makes the real shop slow. A model can also describe the shop well and have a fault in its code. ### How to Use It Name each check by what it compares. The trace, a case worked by hand, the statistics against each other and a formula are verification. A comparison with the real shop and sensitivity analysis are validation. Law adds **credibility**: a model is credible when the people who will use its results accept them, and walking them through the assumptions earns it. ### What the Result Means Checking a Model passes every verification check, and both of the shop's observed values lie within one standard deviation of a single run. Verification alone says nothing about the real shop, so the model is ready for the decision only after both kinds of check. ______________________________________________________________________ ## Read the Trace ### In the Tutorial The records of a desflow run are a trace: the record of each event in time order. In [First Simulation](https://jaehyeon.me/desflow/latest/learn/first-model/first-simulation/index.md), order 3 arrives at 5.024 seconds and joins the queue, and starts at 6.434 seconds, the instant order 2 is packed. ### Why It Matters The [lecture notes](https://courses.ie.bilkent.edu.tr/ie324/wp-content/uploads/sites/4/2016/09/Validation.pdf) on Banks et al. list three ways to find errors in a program: a trace, a look at whether the output is reasonable under a variety of input settings, and a check of the model by someone else. The trace is the cheapest of the three. ### How to Use It Run a few orders and follow one by hand. It should arrive, wait while every packer is busy, start when a packer is free, and finish after its packing time. [Streaming Out](https://jaehyeon.me/desflow/latest/learn/running-live/streaming-out/#find-one-orders-records) shows how to pick one order's records out of a long run. ### What the Result Means An order that starts while every packer is busy, or finishes before its packing time, is a fault in the program. A trace that follows the rules shows only that the cases in it are right, so the next checks test the rest. ______________________________________________________________________ ## Work a Case by Hand ### In the Tutorial [Checking a Model](https://jaehyeon.me/desflow/latest/learn/studies/checking-a-model/#trace-fixed-inputs) runs three packers for 10 seconds, with an order every second and 4 seconds to pack each. Worked by hand, 4 orders finish, 5 are still in the shop, the mean wait is 5 ÷ 7 = 0.714 seconds, the packers are busy 80% of the time and the queue averages 0.8 orders. The run reports the same numbers. ### Why It Matters Constant gaps and constant packing times make every number exact, so a difference is a fault, not chance. Cases at the extremes test the logic further: with demand above capacity, the queue must grow for as long as the run lasts, and a model that cannot show this has a fault. ### How to Use It Replace every random input with a constant, run for a short time, and compare each statistic with the answer worked on paper: ```yaml # Three packers; an order arrives every second and takes 4 seconds to pack resources: packers: {current_cap: 3, max_cap: 10} arrivals: orders: {dist: constant, value: 1, spawn: pack_order} services: packing: {dist: constant, value: 4} ``` `desflow run checking_a_model.yaml` prints the 20 records of the run, which are its trace, then the statistics at 10 seconds. ```python def fixed_shop() -> SimulationContext: """Three packers, an order every second and 4 seconds to pack each, for 10 s.""" app = ( SimulationContext(sim_id="Shop", factor=0, random_seed=42) .add_resource("packers", current_cap=3, max_cap=10) .add_arrival("orders", dist="constant", value=1) .add_service("packing", dist="constant", value=4) .with_stats("typical", interval=3600) ) ``` ```python # Three packers; an order arrives every second and takes 4 seconds to pack FIXED = SimParameter( sim_id="Shop", arrival={"orders": DistributionConfig(dist="constant", value=1)}, service={"packing": DistributionConfig(dist="constant", value=4)}, resources={"packers": CapacityConfig(current_cap=3, max_cap=10)}, ) ``` Then run the extremes, where the answer is known without the model. Four cases with one packer and 1.5 seconds of packing, over an hour: - One order every 3 seconds: orders arrive at 3, 6 and on to 3,597 seconds, so 1,199 arrive. Each is packed before the next arrives, so none waits, and the packer works 1,199 × 1.5 seconds of the 3,600, which is 49.96%. - One order every second: the packer needs 1.5 seconds for each, so it never keeps up. 3,599 orders arrive, 2,399 finish, and 1,200 are in the shop at the end. - One order every 10,000 seconds: no order arrives in the hour, so none starts and none finishes. - One order a second with 100 packers: a packer is always free, so no order waits. ### What the Result Means A run that matches every case worked by hand has the logic of the model on paper. Checking a Model also runs the busy hour at its extremes over 20 replications: one packer finishes 2,318 orders on average against the most possible, 2,320, and ten packers are busy 27.00% of the time against 27% by hand. A difference in any of these cases must be found before any experiment. ______________________________________________________________________ ## Check the Statistics Against Each Other ### In the Tutorial [Measuring a Run](https://jaehyeon.me/desflow/latest/learn/first-model/measuring-a-run/index.md) reports the queue length, the arrival count and the mean wait of the busy hour separately. By [Little's law](https://jaehyeon.me/desflow/latest/learn/concepts/queueing-basics/#littles-law) they must agree: 3.618 orders in the queue on average, against 1.802 orders a second × 2.0065 seconds = 3.616. ### Why It Matters Some relations hold for every model that settles, so they test the statistics without any hand calculation. A run measures each statistic separately, so if they disagree, one of them is wrong. ### How to Use It Compare the average queue with the arrival rate times the mean wait, as [Queueing Basics](https://jaehyeon.me/desflow/latest/learn/concepts/queueing-basics/#littles-law) shows in each form of the model. Check that the counts in [Statistics](https://jaehyeon.me/desflow/latest/user-guide/results/statistics/index.md) add up: when no order balks or reneges, the orders started over the whole run are those finished plus those still in the shop. In Measuring a Run, 6,491 started, 6,488 finished and 3 are still in the shop. ### What the Result Means Agreement shows the statistics are consistent with each other. It does not show the model is right for the shop: a model with the wrong packing times would agree just as well. Little's law is also weaker for a queue that never settles. Checking a Model finds it roughly holds with one packer, but that queue's mean depends on how long the run lasts. ______________________________________________________________________ ## Check Against a Formula ### In the Tutorial Checking a Model runs `desflow explain --verify` on the busy hour of Trusting Results, ten times. The utilisation of 0.9 and the throughput of 1.8 orders a second agree with the runs: 0.9034 and 1.807. The wait has no formula for three packers with measured packing times, so it is not compared. ### Why It Matters For a simple case there is a formula. One packer with exponential gaps and service times at [utilisation](https://jaehyeon.me/desflow/latest/learn/concepts/queueing-basics/#utilisation) 0.75 has a mean wait of 4.5 seconds when the service time averages 1.5 seconds. A run of the model, repeated with several seeds, must produce an interval that contains it. A formula tests the part of the model it covers. It cannot test priorities, breakdowns or changing demand, which is why those are the parts to check by hand and against the real shop. ### How to Use It `desflow explain` applies the formulas to a model without running it. It gives each resource's utilisation, and the mean wait where a formula applies. `desflow explain --verify` then runs the model and compares what the runs measure with those values. Where the formulas do not hold, it gives no value, makes no comparison and says why. [Queueing Basics](https://jaehyeon.me/desflow/latest/learn/concepts/queueing-basics/#check-a-formula-against-the-shop) shows the command in each form, and [Check Against Theory](https://jaehyeon.me/desflow/latest/how-to/analysis/check-against-theory/#when-the-formulas-do-not-apply) states the rule and how to read a difference. ### What the Result Means This is verification, not validation. It checks that the program agrees with the queueing formulas, and that the model's rates, units and service times are consistent with each other. It does not show that the model is close enough to the real shop. ______________________________________________________________________ ## Compare With the Real Shop ### In the Tutorial Checking a Model compares the model with values observed in the shop over 58 minutes of a busy hour: a mean wait of 2.6 seconds and a utilisation of 91%. The values are illustrative. Both lie outside the 95% intervals of the model's mean over 20 replications, 2.00 to 2.30 seconds and 89.39% to 90.60%, because those intervals are for a mean and one observed hour is not a mean. The wait is 1.38 standard deviations of a single run from the model's mean, and the utilisation 0.78, so both agree. ### Why It Matters Validation needs evidence from the real system. Law suggests comparing the model's results with the existing system's where there is one, along with a walk-through of the assumptions by the people who know the system, and sensitivity analysis. The [lecture notes](https://courses.ie.bilkent.edu.tr/ie324/wp-content/uploads/sites/4/2016/09/Validation.pdf) on Banks et al. describe calibration as a loop: compare the model with the real system, adjust it, compare again. They also give three steps: 1. Build a model with high face validity: one that looks right to the people who know the system. 1. Validate the model's assumptions. 1. Compare input-output behaviour with the real system's data. ### How to Use It Give the model the inputs of a real period and compare its measures with what happened. An experiment places each observed value beside the model's interval, as [Experiment Results](https://jaehyeon.me/desflow/latest/user-guide/results/experiment-results/#compare-with-observed-values) describes. Check the inputs as well as the outputs: [Choosing Inputs](https://jaehyeon.me/desflow/latest/learn/inputs/choosing-inputs/index.md) and [Fitting the Inputs](https://jaehyeon.me/desflow/latest/learn/inputs/fit-the-inputs/index.md) cover the inputs, and [Local Replay](https://jaehyeon.me/desflow/latest/learn/inputs/local-replay/index.md) runs a model on the arrivals of a real trace. ### What the Result Means The results need to agree closely enough for the decision, not exactly. The model's interval is for a mean of many runs, and one observed period varies about as much as one run does. So a value outside the interval can still agree, and the comparison uses the standard deviation of one run. A value more than about two of these from the model's mean is a disagreement that the study must explain before it trusts the model. Neither figure includes the error in the shop's own measurement. When the real system does not exist yet, as for a proposed design, there is nothing to compare with, and validity rests on the assumptions and on sensitivity analysis. ______________________________________________________________________ ## Test the Sensitivity ### In the Tutorial [Parameter Sweeps](https://jaehyeon.me/desflow/latest/learn/studies/parameter-sweeps/index.md) changes the shop's arrival rate around its estimate of 1.8 orders a second. With three packers, a rate 6% above the estimate more than doubles the mean wait, from 2.15 to 4.52 seconds, each the [mean of 20 replications after a 2-minute warm-up](https://jaehyeon.me/desflow/latest/learn/concepts/output-analysis/#busy-hour-figures). With four packers, the mean wait is at most 0.34 seconds at every rate in the sweep. ### Why It Matters A model has inputs that are estimates. **Sensitivity analysis** changes them and sees whether the answer changes. It shows which estimates the decision depends on, and so which ones need more data. ### How to Use It Sweep each uncertain input over the range it could take, and run every design at each value with the same seeds. `desflow experiment` runs a sweep from one file, as Parameter Sweeps shows. ### What the Result Means If a 6% change in the arrival rate changes the decision, the estimate needs more work. If the decision stays the same, the estimate is good enough. For the shop the choice of four packers holds for any demand in the range, while the three-packer wait cannot be predicted well without a better estimate of the rate. ______________________________________________________________________ ## Key Takeaways - Verification checks that the program does what the model on paper says. Validation checks that the model is close enough to the real system for the decision. - Check as you build: after each part is added, run a case with a known answer. - Before the experiments, check the statistics against each other and against a formula where one exists. - Before the results are used, compare with the real system, or say that no comparison was possible. - Write the checks as tests, as Checking a Model does, so they run again after every change. [Readiness and Reporting](https://jaehyeon.me/desflow/latest/learn/concepts/readiness-and-reporting/index.md) lists what a model needs before its results are trusted, and [Common Mistakes](https://jaehyeon.me/desflow/latest/learn/concepts/common-mistakes/index.md) lists the errors these checks find. ______________________________________________________________________ ## Sources - Banks et al., *Discrete-Event System Simulation*, chapter 10, read through [lecture notes on it](https://courses.ie.bilkent.edu.tr/ie324/wp-content/uploads/sites/4/2016/09/Validation.pdf): verification and validation, the trace, the reasonableness checks, review by someone else, calibration and the three-step approach. - Law, "How to Conduct a Successful Simulation Study" (Winter Simulation Conference, 2003), read through [the paper](https://www.informs-sim.org/wsc03papers/009.pdf): credibility and the comparison with the existing system. - The checks with Little's law, with a formula and with fixed gaps, the extreme-condition tests, the explanations and the shop examples are our own. # Output Analysis A simulation run gives numbers, and a number from one run is a sample, not the answer. Output analysis is the work of turning runs into an answer with a stated precision. This page explains the ideas with the busy hour of the shop. [Trusting Results](https://jaehyeon.me/desflow/latest/learn/studies/trusting-results/index.md) and [Comparing Designs](https://jaehyeon.me/desflow/latest/learn/studies/comparing-designs/index.md) apply them and show the commands. ______________________________________________________________________ ## What You Will Learn - whether a question is terminating or steady state, and what each needs; - why a run's empty start biases its mean, and how to choose a warm-up; - why one run is not enough, and what replications give; - how a 95% interval and its half-width are built; - how many replications a study needs; - which orders a reading covers; - why designs are compared with the same random numbers. ______________________________________________________________________ ## Terminating or Steady State ### In the Tutorial [End Conditions](https://jaehyeon.me/desflow/latest/learn/first-model/end-conditions/index.md) treats the shop as terminating: orders stop at 3,600 seconds, and the question is what happens to the work still in the shop. The busy hour of [Trusting Results](https://jaehyeon.me/desflow/latest/learn/studies/trusting-results/index.md) is treated as steady state, because the question is what the shop's waits usually are. ### Why It Matters A **terminating** run ends at a time or an event the system has by nature, and starts from conditions the system really has. A shop that opens empty and closes at the end of the day is terminating: the day's answer is the answer. A **steady-state** study asks how a system behaves in the long run, after the effect of its starting conditions has gone. The two need different handling of the start of the run and of its length. ### How to Use It Decide which question the study asks, before choosing a run length: - **Terminating:** the start is part of the answer. Run the real opening state, run to the real closing event, and use replications to measure the spread. - **Steady state:** the start is a distortion. Leave out a warm-up, and run long enough that the rest represents the long run. ### What the Result Means The same model can be either, because the choice depends on the question and on the system, not on the model. A terminating result describes the period with its start. A steady-state result describes the shop once it has settled, and says nothing about its first minutes. ______________________________________________________________________ ## One Run Starts Empty ### In the Tutorial The mean wait so far of the busy hour climbs in the first minute, because the first orders found free packers. That first climb is the start-up that a warm-up covers. The mean then rises in steps until about eight minutes, after which it moves up and down with no trend, and the warm-up chosen below of 2 minutes does not cover that rise. The comparison shows that leaving out the first four minutes, half of the rise, changes the mean little. [Trusting Results](https://jaehyeon.me/desflow/latest/learn/studies/trusting-results/#compare-warm-ups) has the plot and the numbers. ### Why It Matters The first orders of a run find every packer free, so their waits are shorter than the waits of the hour as a whole. The mean wait of a run is therefore biased low by its start. When the question is the long run, as for the busy hour, this distortion is called **initialisation bias**. A **warm-up** is a time at the start of a run whose observations are left out. ### How to Use It Choose the warm-up from evidence, not from habit, in two steps: 1. Plot a running statistic from the start of the run, such as the queue length or the mean wait so far, and note when it stops climbing. Law's paper shows a plot made with Welch's method for this, in which the warm-up is the time after which the average has levelled off, and advises choosing it conservatively. 1. Compare a few candidate warm-ups. Run the same replications after each, and check whether a longer warm-up moves the mean by more than its [half-width](#interval-and-half-width). A candidate passes when it does not. Then keep the shortest candidate that passes the comparison and covers the first climb in the plot with a margin, as Law advises. Set it on the run: ```yaml # Records and statistics start after the first 2 minutes; 0 keeps everything warmup: ${WARMUP:-2 min} ``` ```python # Records and statistics start after the first 2 minutes; None keeps everything SimulationContext(sim_id="Shop", factor=0, random_seed=42, warmup=warmup) ``` ```python # Records and statistics start after the first 2 minutes; None keeps everything WARMUP = 120.0 # seconds, passed to setup_egress in run below ``` In the low-level API the warm-up is an argument of `env.setup_egress`, because the sinks are what leave the records out, as [Trusting Results](https://jaehyeon.me/desflow/latest/learn/studies/trusting-results/#plot-the-start) shows. The warm-up resets every statistic once at that time, as [Run Length](https://jaehyeon.me/desflow/latest/user-guide/time-and-pacing/run-length/index.md) and [Statistics](https://jaehyeon.me/desflow/latest/user-guide/results/statistics/index.md) describe. ### What the Result Means [Trusting Results](https://jaehyeon.me/desflow/latest/learn/studies/trusting-results/#compare-warm-ups) compares warm-ups of 1, 2 and 4 minutes over five seeds, and none shows a visible change in the mean. The first climb ends at about a minute, and 2 minutes covers it with a minute to spare. The running mean goes on rising in steps after two minutes. Leaving out up to 4 minutes moves the mean by at most 0.005 seconds, so leaving out half of that rise changes the estimate little. The comparison does not test a warm-up that covers all of the rise, so it does not show whether the rise is part of the start-up. In the run with the seed 42, the warm-up changes the mean wait only from 2.007 to 2.050 seconds: an hour is long enough that its first minutes hardly count. A shorter run, or one that starts far from the usual state, needs the warm-up much more. A warm-up is not a fix for a model that never settles: if [utilisation](https://jaehyeon.me/desflow/latest/learn/concepts/queueing-basics/#utilisation) is 1 or more, there is no steady state for a warm-up to find. ______________________________________________________________________ ## Replications ### In the Tutorial In the busy hour, with the measured packing times and a 2-minute warm-up, 40 replications give a mean wait of 2.10 ± 0.10 seconds: the mean of the 40 values, with the half-width of its 95% interval. The mean waits of the 40 replications range from 1.52 to 3.05 seconds. The [one run with the seed 42](#busy-hour-figures) measured 2.01 seconds, inside that range and close to the mean of the 40. ### Why It Matters The waits of orders in one run follow each other: after a busy period, many orders in a row wait long. They are not independent samples, so the usual formula for the spread of an average, which assumes independent samples, gives an interval that is too narrow. Law lists this as a pitfall, along with treating one run as the truth. ### How to Use It A **replication** is a run of the same model with its own random stream. It gives one independent value of each statistic. Run several, and take the mean of their values as the estimate: ```bash # 40 runs: the mean wait and the packers' utilisation, each with its interval desflow run trusting_results.yaml --replications 40 --measure tasks.pack_order.wait_mean --measure resources.packers.utilization_avg ``` ```python MEASURES = ["tasks.pack_order.wait_mean", "resources.packers.utilization_avg"] def replications(n=40): """Runs the busy hour n times, each after the warm-up, with seeds spawned from 42.""" return replicate(shop, n, seed=42, until="1 h", measures=MEASURES) ``` ```python MEASURES = ["tasks.pack_order.wait_mean", "resources.packers.utilization_avg"] def model(env, sampler): """The busy hour in a given environment: replicate sets the statistics.""" env.registry.register_sim_parameter(PARAMS) packers = DynamicResource(env, "Shop", "packers") env.process(order_generator(env, sampler, packers)) def replications(n=40): """Runs the busy hour n times, each after the warm-up, with seeds spawned from 42.""" shop = LowLevelModel(model, sim_id="Shop") return replicate(shop, n, seed=42, until=3600, warmup=WARMUP, measures=MEASURES) ``` `LowLevelModel` names the function that builds the model in an environment it is given, and the warm-up is an argument of `replicate`, because a replication has no sinks. [Replications](https://jaehyeon.me/desflow/latest/user-guide/results/replications/index.md) describes every option. The seeds are spawned from one seed, so the set repeats exactly. [Randomness and Seeds](https://jaehyeon.me/desflow/latest/learn/first-model/randomness-and-seeds/index.md) explains the streams. ### What the Result Means One run gives a single value with no interval: 2.01 seconds here, close to the 2.10 ± 0.10 of 40 replications, although the 40 values range from 1.52 to 3.05 seconds, so another seed could have given an answer far from it. The [interval](#interval-and-half-width) says how precise the estimate is. ______________________________________________________________________ ## Interval and Half-width ### In the Tutorial Over 40 replications of the busy hour, the mean wait is 2.10 ± 0.10 seconds. The interval runs from 2.00 to 2.20 seconds, and 0.10 seconds is its **half-width**. ### Why It Matters A **95% interval**, in full a 95% confidence interval, is the mean of n replications plus or minus a half-width of t × s ÷ √n, where: - s is the standard deviation of the n values. - s ÷ √n is the **standard error**, an estimate of how far the mean itself varies from one set of replications to the next. - t is the **Student t quantile** for n − 1 degrees of freedom, one less than the number of replications. t is about 2.1 for 20 replications and 2.0 for 40, and larger for fewer, because s is then a rougher estimate. ### How to Use It Every replication command prints the mean and the half-width of each measure. `--level` changes the confidence level: `--level 0.9` on the command line, or `level=0.9` in `replicate`. Choose the level before the runs, with the precision the decision needs. ### What the Result Means Over many studies, about 95% of the intervals built this way contain the true mean. A 90% interval from the same 40 runs is narrower, ± 0.08 seconds, but misses the true mean more often: 1 study in 10 instead of 1 in 20. ______________________________________________________________________ ## How Many Replications ### In the Tutorial Trusting Results asks for a half-width within 10% of the mean. Utilisation meets it with 5 replications. The mean wait first meets it at 20: its half-width is 21.4% of the mean after 5 replications, 14.0% after 10, 7.1% after 20 and 4.8% after 40. ### Why It Matters There is no fixed number that is enough, such as 30. Waits vary far more from run to run than how busy the packers are, so each output needs its own number of replications, and the study needs enough for the least precise output the decision uses. ### How to Use It Decide the precision each output needs, then run until the least precise output has it. The half-width shrinks with √n, so a half-width k times smaller needs about k² times as many replications. A first set of a few replications suggests how many are needed: 10 replications gave 14.0%, so 10% needs about 10 × (14.0 ÷ 10)² ≈ 20. ### What the Result Means That estimate is a guide, not a promise: the half-width of the first set is itself an estimate, so the number needed can differ (here 20 replications gave 7.1%). Add replications, then read the half-width again. A longer run is the other way to gain precision. It reduces the effect of the start, but its mean is still one sample. ______________________________________________________________________ ## Which Orders a Reading Covers ### In the Tutorial In [End Conditions](https://jaehyeon.me/desflow/latest/learn/first-model/end-conditions/index.md), the fixed horizon ends at 3,600 seconds with 2,561 orders started, 2,386 finished and 175 in the shop. With a drain, the run ends at 3,861.8 seconds with all 2,561 finished. ### Why It Matters A mean is over some orders, and two runs of the same hour can cover different orders. At a fixed horizon, some orders have started and not finished, and the mean wait covers those that started. With a drain, every order admitted finishes, at the cost of running past the hour. ### How to Use It Report the counts beside the means. The warm-up adds a third group: orders that were in the shop when the warm-up ended. An order that started before the warm-up ended and finished after it counts as finished, and it does not count as started. An order still queued when the warm-up ended adds its whole wait to the wait times, and an order in service adds its whole service time and no wait. [Statistics](https://jaehyeon.me/desflow/latest/user-guide/results/statistics/index.md) has the table of which orders each count covers. ### What the Result Means Two means over different groups of orders are not comparable. A reader needs the counts to tell whether a difference between two results comes from the shop or from which orders each reading covers. ______________________________________________________________________ ## Comparing Designs ### In the Tutorial [Comparing Designs](https://jaehyeon.me/desflow/latest/learn/studies/comparing-designs/index.md) runs three packers and four with the same 20 seeds. A fourth packer cuts the busy hour's mean wait by 1.89 ± 0.14 seconds. ### Why It Matters Run each design with the same seeds, so that each pair of runs meets the same arrivals and the same service times, and take the difference seed by seed. This is a **paired comparison**, and the shared random numbers are called **common random numbers**. The random variation that the two runs of a pair share cancels in their difference. The interval of the differences is therefore narrower than the interval an unpaired comparison of the same runs gives. Law names comparing designs without a sound statistical approach as a pitfall. ### How to Use It An experiment pairs its designs by seed and reports the difference with its interval, as Comparing Designs shows. The check below shows the effect on 40 runs of the busy hour with 3 packers, 20 packing in 1.5 seconds and 20 packing in 1.45 seconds, with the same 20 seeds. It builds two intervals for the difference of the mean waits from the same runs: one paired by seed, and one that treats the designs as independent. ```bash desflow experiment comparing_designs_experiment.yaml ``` The experiment runs every design with the same seeds and reports each difference paired by seed. It does not build the unpaired interval, which the Builder tab computes for the comparison. ```python def waits(service: float, n: int = 20) -> list[float]: """The mean wait of each replication; the same seed gives the same seeds to every design.""" runs = replicate(lambda: shop(service), n, seed=42, until=3600, measures=[WAIT]) return runs.values[WAIT] def paired_and_unpaired(slow: list[float], fast: list[float]): """Half-widths of the difference of the means: paired by seed, and as if independent.""" n = len(slow) paired = interval([a - b for a, b in zip(slow, fast)]) # Welch's interval: the two designs' variances add, and the degrees of freedom shrink va, vb = statistics.variance(slow) / n, statistics.variance(fast) / n df = (va + vb) ** 2 / (va**2 / (n - 1) + vb**2 / (n - 1)) unpaired = t_quantile(0.975, df) * math.sqrt(va + vb) return paired, unpaired ``` `replicate` takes a `LowLevelModel` in place of the builder function, as the Replications section above shows. The two functions then work on its values unchanged. ### What the Result Means With the seeds spawned from 42, the mean wait of the 20 runs packing in 1.5 seconds is 0.56 seconds longer than that of the 20 runs packing in 1.45 seconds. The paired interval is ± 0.05 seconds and the unpaired one is ± 0.14 seconds, so pairing more than halves the interval here. [Common Mistakes](https://jaehyeon.me/desflow/latest/learn/concepts/common-mistakes/#comparing-designs-with-one-run-each) runs the same two designs with other seeds and without pairing, so its means differ from these. Pairing helps only when the designs use the random numbers in the same way. desflow gives each distribution a stream of its own, so adding a step to one design does not shift the numbers the shared steps draw. The comparison report lists any stream that only one design used, because draws from such a stream are not paired. Check that list before trusting a paired interval. ______________________________________________________________________ ## Busy Hour Figures The tutorial pages and the concept pages run the busy hour with 3 packers in different ways, so they give different figures for its mean wait. A figure changes with the number of runs, the packing times, the [warm-up](#one-run-starts-empty), the run length and the seeds. The table lists each figure, the pages that give it and how it was run. Every run is one hour at 1.8 orders a second unless the row says otherwise. Two terms in the table need a definition: - "Measured times" are the 40 packing times measured at the bench, drawn as an `empirical` distribution. - "Replications" have seeds spawned from 42. A run of 5, 10 or 20 replications uses the first 5, 10 or 20 of the 40 seeds. | Mean wait (s) | Pages | How it was run | | -------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------- | | 1.88 | [Queues and Capacity](https://jaehyeon.me/desflow/latest/learn/first-model/queues-and-capacity/index.md), [Choosing Inputs](https://jaehyeon.me/desflow/latest/learn/inputs/choosing-inputs/index.md), [Queueing Basics](https://jaehyeon.me/desflow/latest/learn/concepts/queueing-basics/index.md), [Common Mistakes](https://jaehyeon.me/desflow/latest/learn/concepts/common-mistakes/index.md) | one run, seed 42, constant packing, no warm-up | | 1.95 | [Choosing Inputs](https://jaehyeon.me/desflow/latest/learn/inputs/choosing-inputs/index.md), [Queueing Basics](https://jaehyeon.me/desflow/latest/learn/concepts/queueing-basics/index.md) | one run, seed 42, the expert's triangular packing (1 to 2.25 s, mode 1.25), no warm-up | | 1.81 | [Choosing Inputs](https://jaehyeon.me/desflow/latest/learn/inputs/choosing-inputs/index.md), [Queueing Basics](https://jaehyeon.me/desflow/latest/learn/concepts/queueing-basics/index.md), [Randomness and Seeds](https://jaehyeon.me/desflow/latest/learn/first-model/randomness-and-seeds/index.md) | one run, seed 42, measured times in a service named `empirical`, no warm-up | | 2.01 | [Measuring a Run](https://jaehyeon.me/desflow/latest/learn/first-model/measuring-a-run/index.md), [Trusting Results](https://jaehyeon.me/desflow/latest/learn/studies/trusting-results/index.md), [Output Analysis](https://jaehyeon.me/desflow/latest/learn/concepts/output-analysis/index.md), [Randomness and Seeds](https://jaehyeon.me/desflow/latest/learn/first-model/randomness-and-seeds/index.md) | one run, seed 42, measured times in a service named `packing`, without a warm-up (2.007) or with a 2-minute warm-up (2.050) | | 3.46 | [Choosing Inputs](https://jaehyeon.me/desflow/latest/learn/inputs/choosing-inputs/index.md), [Queueing Basics](https://jaehyeon.me/desflow/latest/learn/concepts/queueing-basics/index.md), [Common Mistakes](https://jaehyeon.me/desflow/latest/learn/concepts/common-mistakes/index.md) | one run, seed 42, exponential packing, no warm-up | | 1.93 | [Common Mistakes](https://jaehyeon.me/desflow/latest/learn/concepts/common-mistakes/#taking-one-run-as-the-answer) | 10 replications, constant packing, no warm-up | | 1.98 | [Common Mistakes](https://jaehyeon.me/desflow/latest/learn/concepts/common-mistakes/#comparing-designs-with-one-run-each) | 20 replications with seeds spawned from 1, constant packing, no warm-up | | 2.06 ± 0.17 | [Queueing Basics](https://jaehyeon.me/desflow/latest/learn/concepts/queueing-basics/#check-a-formula-against-the-shop) | 10 replications of 20,000 seconds, constant packing, the first 2,000 seconds left out | | 2.005 to 2.010 | [Trusting Results](https://jaehyeon.me/desflow/latest/learn/studies/trusting-results/#compare-warm-ups) | 5 replications, measured times, warm-ups of 1, 2 and 4 minutes | | 2.15 ± 0.30 | [Trusting Results](https://jaehyeon.me/desflow/latest/learn/studies/trusting-results/index.md), [Checking a Model](https://jaehyeon.me/desflow/latest/learn/studies/checking-a-model/index.md) | 10 replications, measured times, 2-minute warm-up | | 2.15 ± 0.15 | [Trusting Results](https://jaehyeon.me/desflow/latest/learn/studies/trusting-results/index.md), [Comparing Designs](https://jaehyeon.me/desflow/latest/learn/studies/comparing-designs/index.md), [Parameter Sweeps](https://jaehyeon.me/desflow/latest/learn/studies/parameter-sweeps/index.md), [Checking a Model](https://jaehyeon.me/desflow/latest/learn/studies/checking-a-model/index.md), [Checking and Validating](https://jaehyeon.me/desflow/latest/learn/concepts/checking-and-validating/index.md), [Queueing Basics](https://jaehyeon.me/desflow/latest/learn/concepts/queueing-basics/index.md) | 20 replications, measured times, 2-minute warm-up | | 2.10 ± 0.10 | [Trusting Results](https://jaehyeon.me/desflow/latest/learn/studies/trusting-results/index.md), [Fitting the Inputs](https://jaehyeon.me/desflow/latest/learn/inputs/fit-the-inputs/index.md), [Comparing Designs](https://jaehyeon.me/desflow/latest/learn/studies/comparing-designs/index.md), [Output Analysis](https://jaehyeon.me/desflow/latest/learn/concepts/output-analysis/index.md), [A Simulation Study](https://jaehyeon.me/desflow/latest/learn/concepts/a-simulation-study/index.md) | 40 replications, measured times, 2-minute warm-up | | 2.11 ± 0.10 | [Fitting the Inputs](https://jaehyeon.me/desflow/latest/learn/inputs/fit-the-inputs/index.md) | 40 replications, the gamma fitted to the measured times, 2-minute warm-up | | 2.58 ± 0.13 | [Fitting the Inputs](https://jaehyeon.me/desflow/latest/learn/inputs/fit-the-inputs/index.md) | 40 replications, the triangular fitted to the measured times, 2-minute warm-up | The 1.81 and 2.01 seconds come from the same measured times. The two services draw the times in a different order, because each distribution draws from a random number stream named after its registry path, `service.empirical` or `service.packing` ([Randomness and Seeds](https://jaehyeon.me/desflow/latest/learn/first-model/randomness-and-seeds/#add-returns) explains the streams). ______________________________________________________________________ ## Key Takeaways - Decide first whether the question is terminating or steady state. - For a steady-state question, choose the warm-up from a plot and a comparison of candidates, and report the evidence. - Answer with replications, not one run, and give each output as a mean with its half-width. - Choose the precision each output needs, and run until the least precise output has it. - Say which orders each count covers. - Compare designs with the same seeds, and check the list of unpaired streams. [Readiness and Reporting](https://jaehyeon.me/desflow/latest/learn/concepts/readiness-and-reporting/index.md) lists what a report must contain. ______________________________________________________________________ ## Sources - Banks et al., *Discrete-Event System Simulation*, chapter 11, on output analysis for a single model, read through [lecture notes on it](https://courses.grainger.illinois.edu/ece541/fa2016/OutputAnalysis.pdf). The notes give the interval across replications the same form as the one above. - Law, "Twenty-Three Critical Pitfalls in Simulation Modeling and How to Avoid Them" (Winter Simulation Conference, 2024), read through [its published text](https://informs-sim.org/wsc24papers/inv198.pdf): the output-analysis pitfalls and Welch's method. - The explanations are our own. # Readiness and Reporting A model is ready when someone who was not part of the study can see what it answers, how far to trust the answer, and how to repeat it. This page explains what that takes, with the shop's study in [The Complete Model](https://jaehyeon.me/desflow/latest/learn/studies/complete-model/index.md) as the example. It points to three published checklists written for simulation studies, and shows which parts desflow does for you and which parts only you can write. ______________________________________________________________________ ## What You Will Learn - why readiness is a statement about a decision, not about a model; - what the three levels of the Model Readiness Checklist ask for; - what a report needs, by the STRESS-DES checklist; - what to share so that others can run the model, by the STARS framework; - which items desflow records for you, and which only you can write. ______________________________________________________________________ ## Ready for What ### In the Tutorial The shop model is ready to say how many packers the busy hour needs: its inputs came from data, its checks passed, its results carry an interval, and a reader can repeat the runs. It is not ready to say anything about a holiday week, whatever its code looks like. ### Why It Matters A model is built and checked for one question. The checks of [Checking and Validating](https://jaehyeon.me/desflow/latest/learn/concepts/checking-and-validating/index.md) show it fits that question, with the inputs and the range of conditions it was checked under. Outside them, nothing has been checked. ### How to Use It Write down the question the model is ready for, as [A Simulation Study](https://jaehyeon.me/desflow/latest/learn/concepts/a-simulation-study/#ask-one-question) does, and state the limits of its use. An experiment file keeps them with the runs: The Complete Model lists "One busy hour only; the rest of the day is not modelled" among its limits, and `report.md` prints them. ### What the Result Means A reader who wants to use the model for another question can see at once that it was not built for it. That question needs its own checks before the model answers it. ______________________________________________________________________ ## Model Readiness Checklist ### In the Tutorial The shop's study meets most of the first level below. Its replications and warm-up come from [Trusting Results](https://jaehyeon.me/desflow/latest/learn/studies/trusting-results/index.md), its seeds are fixed, its core logic is checked in [Checking a Model](https://jaehyeon.me/desflow/latest/learn/studies/checking-a-model/index.md), and it is compared with values observed in the shop. The review of the process with the people who know it is the walk-through of [Check the Assumptions](https://jaehyeon.me/desflow/latest/learn/concepts/a-simulation-study/#check-the-assumptions), which no tool does. ### Why It Matters The open book [HSMA: the little book of DES](https://des.hsma.co.uk/) has a chapter, [Model Readiness Checklist](https://des.hsma.co.uk/model_checklist.html), that sorts what a model needs into three levels, by the size of the decision: - **Bronze** is the level for small to medium decisions within one organisation. It asks for views of the model running, checks of the core logic, enough [replications](https://jaehyeon.me/desflow/latest/learn/concepts/output-analysis/#replications) and a [warm-up](https://jaehyeon.me/desflow/latest/learn/concepts/output-analysis/#one-run-starts-empty), a fixed seed, a comparison with the real system, a review of the process with the people who know it, and documentation. - **Silver** is the level for larger or costlier decisions, or for models used across several areas. It adds a formal reporting checklist such as STRESS-DES, documented code, a code review, automated tests, an open licence, version control and a sensitivity analysis. - **Gold** is the level for models that will be reused, adapted or published. It adds: - a documentation site and a changelog; - identifiers for the authors and an archive of the code; - an online environment to run the model in, parallel runs, a web app and an animation; - formal methods for the warm-up and the number of replications; - tests against historical data. ### How to Use It Choose the level from the decision, then go through its items. Some items cost nothing in desflow, and some need you: | Item | In desflow | | ------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | A fixed seed and independent streams | `random_seed` fixes a run, and `replicate` makes one integer seed for each replication from one seed and records them, so the same call gives the same results and any replication can be repeated alone. See [Replications](https://jaehyeon.me/desflow/latest/user-guide/results/replications/index.md) | | Enough replications, with an interval | `replicate` gives the mean and the [half-width of the 95% interval](https://jaehyeon.me/desflow/latest/learn/concepts/output-analysis/#interval-and-half-width). [How many](https://jaehyeon.me/desflow/latest/learn/concepts/output-analysis/#how-many-replications) is your decision | | The designs and the inputs on record | An experiment records the compiled parameters of each design and writes its summary, its comparisons, its checks and a `report.md`. See [Experiments](https://jaehyeon.me/desflow/latest/user-guide/results/experiments/index.md) | | A comparison with the real system | An experiment can read an observed file and compare it with the model. See [Experiment Results](https://jaehyeon.me/desflow/latest/user-guide/results/experiment-results/index.md). Which data to use is your decision | | A view of the model running | Every event and reading is a record, which you can read or send to a sink. See [Egress, Batching and Delivery](https://jaehyeon.me/desflow/latest/user-guide/live-runs-and-connectors/egress/index.md) | | Core logic checked | Yours: [Checking and Validating](https://jaehyeon.me/desflow/latest/learn/concepts/checking-and-validating/index.md) shows the cases to work by hand | | Assumptions, data sources and limits | Yours: they go in the experiment file and the report, and no tool decides them | ### What the Result Means A level is met when every item of it is done, not most. An item left out goes into the report as a limit, so that the reader knows which check the model has not had. ______________________________________________________________________ ## Reporting a Study ### In the Tutorial The Complete Model's `report.md` gives the question, the model and its versions, the assumptions, each input with its fitted parameters and where it came from, the run settings, the counts, the results, the comparisons, the checks and the observed comparison, then the limits and any input with no source. Its Comparisons section answers the question with each difference and its interval: a fourth packer cuts the packing wait by 1.58 seconds, with a half-width of 0.10 seconds. ### Why It Matters A reader acts on the report alone. The reporting checklist STRESS-DES lists what that reader will ask. It has 20 items in six groups: objectives, logic, data, experimentation, implementation and code access. It is by Monks, Currie, Onggo, Robinson, Kunc and Taylor, and the book gives it in its chapter [STRESS-DES Reporting](https://des.hsma.co.uk/stress_des.html). ### How to Use It Answer each group in one short paragraph of the report, in this order, after the answer and its interval: - **Objectives:** the question and the measures, as in [Ask One Question](https://jaehyeon.me/desflow/latest/learn/concepts/a-simulation-study/#ask-one-question). - **Logic:** the conceptual model, with its assumptions and what it leaves out. - **Data:** where each input came from, and how it was fitted or chosen. - **Experimentation:** the run length, the warm-up, the number of replications and the designs compared. - **Implementation:** the software and its version, and the random number streams. - **Code access:** where the code, the data and the seeds are kept. ### What the Result Means `report.md` answers the objectives, the data and the experimentation from the experiment file, and gives the software versions. The logic beyond the listed assumptions, how the model was checked, and where the code is kept are yours to add. [Common Mistakes](https://jaehyeon.me/desflow/latest/learn/concepts/common-mistakes/index.md) lists what to look for before you send the report. ______________________________________________________________________ ## Sharing the Model ### In the Tutorial Each tutorial page ends with Full Files: every file its runs need, so a reader can repeat them. desflow itself is under the MIT licence and installs from PyPI with a stated version. ### Why It Matters The framework STARS, by Monks, Harper and Mustafee, says what to share so that others can run and reuse a model. The book gives it in [The STARS Framework](https://des.hsma.co.uk/stars.html). A model that only its author can run cannot be checked by anyone else. ### How to Use It STARS separates essential parts from optional ones: - **Essential:** an open licence; a list of the software the model needs, with its versions; free and open software; a minimum of documentation; an identifier for each author; a citation file; a code repository; and an archive that gives the code a permanent identifier. - **Optional:** fuller documentation, a hosted documentation site, an online environment to run the model in, an interface, and a hosted web app. Keep the blueprint or the Python files, the experiment file and the observed data in one repository, with the desflow version they ran on. ### What the Result Means A model shared with its essential parts can be run again by a reader, with the same seeds and the same results. That is the strongest evidence a report can give. ______________________________________________________________________ ## Key Takeaways - Ready is a statement about one decision: write down the question and the limits of the model's use. - Choose the readiness level from the size of the decision, and meet every item of it. - desflow records the seeds, the intervals, the designs, the inputs and the comparisons. The assumptions, the checks and the limits are yours to write. - Report the answer first, with its interval, then the six groups of STRESS-DES. - Share the model with an open licence, its software versions and its files. ______________________________________________________________________ ## Sources - The open book [HSMA: the little book of DES](https://des.hsma.co.uk/), its chapters [Model Readiness Checklist](https://des.hsma.co.uk/model_checklist.html), [STRESS-DES Reporting](https://des.hsma.co.uk/stress_des.html) and [The STARS Framework](https://des.hsma.co.uk/stars.html). The chapters are under the CC BY-NC-SA licence, so none of their text is copied here. We read the three and link them, and the lists above are our own summaries. - Monks, Currie, Onggo, Robinson, Kunc and Taylor, "Strengthening the reporting of empirical simulation studies: Introducing the STRESS guidelines" ([Journal of Simulation, 2019](https://doi.org/10.1080/17477778.2018.1442155)). - Monks, Harper and Mustafee, "Towards sharing tools and artefacts for reusable simulations in healthcare" ([Journal of Simulation, 2024](https://doi.org/10.1080/17477778.2024.2347882)). # Common Mistakes Most wrong simulation results come from a short list of mistakes, and most of them are made before the first run. This page explains eight, in the order they happen in a study. Each one shows what the mistake does to the packing shop, why, how to avoid it, and what the result looks like once it is avoided. The checks behind the figures are in [common_mistakes.py](https://github.com/jaehyeon-kim/desflow/blob/v1.3.0/docs/snippets/pages/common_mistakes.py), which runs each one with the builder and asserts each number the page quotes. ______________________________________________________________________ ## What You Will Learn - why a study needs one question, and a model only the detail that question needs; - what replacing an input by its mean, or choosing a distribution by habit, does to the waits; - why one run, or one run of each design, is not an answer; - why a steady-state question needs a warm-up; - why the orders of one run cannot give an interval. ______________________________________________________________________ ## No Clear Question ### In the Shop A shop model built to "see what happens" could include the pickers, the stock, the couriers and the breaks. Nothing says which of them matter, so nothing says when the model is finished. ### Why It Matters A model with no question grows, and its results cannot be judged, because there is no measure to judge them by. ### How to Use It Write one question before you write the model, with the measure that answers it, such as "how many packers keep the mean wait of the busy hour under 10 seconds?". [A Simulation Study](https://jaehyeon.me/desflow/latest/learn/concepts/a-simulation-study/#ask-one-question) shows how to write it. ### What the Result Means With the question written, each part of the model can be judged by whether it changes the answer. The shop's question needs the packers and the orders, and not the couriers. ______________________________________________________________________ ## Copying the Real System in Full ### In the Shop The busy-hour question depends on the arrivals, the packing times and the number of packers. The pickers, the stock and delivery are outside the shop's first model, and [A Flow of Tasks](https://jaehyeon.me/desflow/latest/learn/shop-logic/flow-of-tasks/index.md) adds picking only when a question needs it. ### Why It Matters A model with every detail of the real shop takes long to build, is hard to check, and needs data for each detail that nobody collected. More detail can also hide the factors that matter. ### How to Use It Ask of each part: would the answer change if it were different? If not, leave it out. [A Simulation Study](https://jaehyeon.me/desflow/latest/learn/concepts/a-simulation-study/#conceptual-model-and-data) writes this down as the conceptual model, and lets the question decide how much detail goes in. ### What the Result Means A small model that answers the question is easier to check and to explain. A part added later, when a new question needs it, is checked on its own. ______________________________________________________________________ ## Replacing a Distribution by Its Mean ### In the Shop Packing takes 1.5 seconds on average and an order arrives every 2.0 seconds on average, so it is tempting to put those two numbers in as constants. With one packer, constant gaps and constant packing times, the mean wait over 10 [replications](https://jaehyeon.me/desflow/latest/learn/concepts/output-analysis/#replications) is 0.00 seconds. With exponential gaps of the same mean and the same packing time, it is 2.18 seconds over the same 10 replications. ### Why It Matters Real orders do not come at even gaps, and that variation is what makes a queue. With constant inputs, each order arrives after the last one is packed, so no order ever waits. [Kingman's formula](https://jaehyeon.me/desflow/latest/learn/concepts/queueing-basics/#variation-lengthens-waits) shows the same: with no variation in the gaps or the packing times, the wait is zero. ### How to Use It Use the distribution you measured, not its mean. [Choosing Inputs](https://jaehyeon.me/desflow/latest/learn/inputs/choosing-inputs/index.md) compares candidate distributions for the packing time, and [Fitting the Inputs](https://jaehyeon.me/desflow/latest/learn/inputs/fit-the-inputs/index.md) fits them to measured times. ### What the Result Means A model whose waits are near zero while utilisation is high has probably lost its variation. In Choosing Inputs, the same mean packing time gives a mean wait from 1.88 seconds with constant times to 3.46 seconds with exponential ones. ______________________________________________________________________ ## Choosing a Normal or Uniform by Habit ### In the Shop A normal distribution with a mean of 1.5 seconds and a standard deviation of 1.0 is a tempting packing time. About 6.7% of 100,000 draws from it are below zero. ### Why It Matters A time cannot be negative. The model would have to clip the negative draws, which changes the mean, or fail. A uniform distribution has the opposite problem: it gives every value between its ends the same weight, which real times seldom have. ### How to Use It Fit a distribution to the data, and let a goodness-of-fit check and a plot say which family it is. [Input Fitting](https://jaehyeon.me/desflow/latest/user-guide/model-parts/input-fitting/index.md) does this, and [Fitting the Inputs](https://jaehyeon.me/desflow/latest/learn/inputs/fit-the-inputs/index.md) works an example. [A Simulation Study](https://jaehyeon.me/desflow/latest/learn/concepts/a-simulation-study/#aic-and-the-ks-test) explains the scores. ### What the Result Means With no data, a triangular distribution of the least, most likely and greatest values is a usual stand-in. Law's pitfall 18 warns against using one when data could be collected, because the greatest value is hard to choose and the long right tail of real times matters. Collect the data if you can. ______________________________________________________________________ ## Taking One Run as the Answer ### In the Shop Run the busy hour with three packers, constant packing and no warm-up 10 times with different seeds. The mean wait of a run ranges from 1.50 seconds, 23% below the mean, to 2.37 seconds, 22% above it, and the mean of the 10 is 1.93 seconds. ### Why It Matters One run is one sample. A report that gave one run alone could be that far off, and it would carry no sign of how far. ### How to Use It Run replications and report the mean with an interval. [Output Analysis](https://jaehyeon.me/desflow/latest/learn/concepts/output-analysis/#replications) explains replications and how many to use, and [Trusting Results](https://jaehyeon.me/desflow/latest/learn/studies/trusting-results/index.md) runs them for the shop. ### What the Result Means The pages of this site give several figures for the busy hour's mean wait, because each runs it in a different way. [Busy Hour Figures](https://jaehyeon.me/desflow/latest/learn/concepts/output-analysis/#busy-hour-figures) lists each figure and how it was run. ______________________________________________________________________ ## No Warm-up for a Steady State ### In the Shop Take one packer and an order about every 1.58 seconds on average. With 1.5 seconds of packing, the packer is busy 1.5 ÷ 1.58 = 95% of the time. Forty runs of 30 minutes from an empty shop give a mean wait of 11.6 ± 1.8 seconds. The formula for the long-run wait of this shop (M/D/1) gives 14.25 seconds, above the whole interval. ### Why It Matters A run starts with an empty shop, so the first orders find no queue, and the mean of a short run is biased low. The effect is largest when the shop is nearly full, because the queue then takes longest to reach its usual length. ### How to Use It For a steady-state question, leave out a warm-up and run long enough. [Output Analysis](https://jaehyeon.me/desflow/latest/learn/concepts/output-analysis/#one-run-starts-empty) explains how to choose the warm-up, and shows the setting in each form of the model. ### What the Result Means Forty runs of 20,000 seconds that each leave out their first 4,000 seconds give 13.3 ± 0.9 seconds. The interval now reaches 14.2 seconds, within 0.05 seconds of 14.25 seconds, so most of the bias is gone. Terminating questions do not need a warm-up, because the empty start is part of the question. ______________________________________________________________________ ## Comparing Designs With One Run Each ### In the Shop Packing in 1.45 seconds instead of 1.5 is a real improvement. Over 20 runs of each, with seeds spawned from 1 for the slower design and from 2 for the faster one, the mean wait is 1.98 seconds for the slower design and 1.40 seconds for the faster. Match the runs in order, first with first: in 3 of the 20 matches, the slower design's run had a mean wait at or below the faster design's run. ### Why It Matters In those 3 matches, one run of each design would have said the change did not help. The difference between two single runs is mostly the difference between their random numbers. ### How to Use It Compare designs with the same number of replications each and an interval on the difference. Use [common random numbers](https://jaehyeon.me/desflow/latest/learn/concepts/output-analysis/#comparing-designs) to reduce the random variation in the difference. [Comparing Designs](https://jaehyeon.me/desflow/latest/learn/studies/comparing-designs/index.md) does this on the shop. ### What the Result Means These runs are not paired, so they are not the runs of the paired comparison in Output Analysis, which runs both designs with the seeds spawned from 42. With pairing, the interval of the difference there is ± 0.05 seconds against ± 0.14 seconds without it. ______________________________________________________________________ ## Treating One Run's Statistics as Independent ### In the Shop In the busy hour, an order that waits long is usually followed by another that waits long, because the second waited in the same queue, behind the first. ### Why It Matters The mean wait of one run is a mean of values that depend on each other. The usual interval formula assumes independent values, so an interval built from the orders of one run is too narrow. ### How to Use It Build the interval from the replications, each of which is independent of the others. [Output Analysis](https://jaehyeon.me/desflow/latest/learn/concepts/output-analysis/#interval-and-half-width) shows how. ### What the Result Means An interval from replications says how far the mean may be from the true one. An interval from one run's orders claims a precision the run does not have. [Checking and Validating](https://jaehyeon.me/desflow/latest/learn/concepts/checking-and-validating/index.md) lists the checks that catch the other mistakes before a result is reported. ______________________________________________________________________ ## Key Takeaways - Write one question, and model only what its answer depends on. - Use measured distributions, not their means, and not a normal or uniform by habit. - Answer with replications and an interval, never with one run. - Leave out a warm-up for a steady-state question. - Compare designs with the same seeds and an interval on the difference. ______________________________________________________________________ ## Sources - Law, "Twenty-Three Critical Pitfalls in Simulation Modeling and How to Avoid Them" (Winter Simulation Conference, 2024), which we read. The list follows its pitfalls. - The examples are our own runs. # User Guide # User Guide Each page here describes one part of desflow: what it does, how to use it, how it works and its limits. Read a page when you need that part. To learn DES and desflow from the start, follow [Learn](https://jaehyeon.me/desflow/latest/learn/index.md) instead. To do one task step by step, see [How-To](https://jaehyeon.me/desflow/latest/how-to/index.md). | Group | What it covers | | ----------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------- | | [How desflow Works](https://jaehyeon.me/desflow/latest/user-guide/how-desflow-works/index.md) | how desflow is built: the parts that run a model, why each exists, and how a run moves through them | | [Writing a Model](https://jaehyeon.me/desflow/latest/user-guide/writing-a-model/index.md) | the three ways to write a model: a YAML blueprint, the builder API and the low-level API | | [Model Parts](https://jaehyeon.me/desflow/latest/user-guide/model-parts/index.md) | the parts a model is made of: arrivals and services, input fitting, task flow, and stores and containers | | [Tasks and Processes](https://jaehyeon.me/desflow/latest/user-guide/tasks-and-processes/index.md) | tasks, processes, the signals they wait for, and failures | | [Resources](https://jaehyeon.me/desflow/latest/user-guide/resources/index.md) | priority and preemption, tasks that hold several resources, and resource types of your own | | [Time and Pacing](https://jaehyeon.me/desflow/latest/user-guide/time-and-pacing/index.md) | the simulation clock, pacing against real time, and how long a run lasts | | [Results](https://jaehyeon.me/desflow/latest/user-guide/results/index.md) | what a run measures, replications and experiments | | [Live Runs and Connectors](https://jaehyeon.me/desflow/latest/user-guide/live-runs-and-connectors/index.md) | parameters that change during a run, and the connectors that bring changes in and write records out | # How desflow Works This page shows how desflow is built: the parts that run a model, why each one exists, and how a run moves through them. Each part links to the How It Works section that describes it in full. One run moves through the parts of desflow like this: Whichever way a model is written, it builds one environment, and one run goes the same way from there. The registry paths, the [records](https://jaehyeon.me/desflow/latest/reference/records-and-telemetry/index.md), the batching and the connectors are therefore the same in all three ways. [How It Works](#how-it-works) follows a model from its file or script to the environment. ______________________________________________________________________ ## What It Is desflow is built on [SimPy](https://simpy.readthedocs.io/). SimPy gives the event list, the clock, processes and resources, and desflow keeps all of them. SimPy leaves seven things to the modeller, and each part of desflow adds one of them: | Left to the modeller in SimPy | What desflow adds | Read | | --------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------- | | the code around a model: a class of parameters, an entity class, a model class and a loop over runs | three ways to write a model, each built on the one below | [Writing a Model](https://jaehyeon.me/desflow/latest/user-guide/writing-a-model/index.md) | | one pacing `factor`, fixed when the environment is made | one environment that runs history at full speed, then switches to the wall clock | [Time and Pacing](https://jaehyeon.me/desflow/latest/user-guide/time-and-pacing/#how-it-works) | | random times, drawn by the model's own code | ten checked distributions, each with a random stream of its own | [Arrivals and Services](https://jaehyeon.me/desflow/latest/user-guide/model-parts/arrivals-and-services/#how-it-works) | | parameters that only the model's code changes | a registry of named paths that connectors, scenarios and processes change during a run | [Live Parameters](https://jaehyeon.me/desflow/latest/user-guide/live-runs-and-connectors/live-parameters/#how-it-works) | | resources, stores and containers that keep the capacity they were made with | resources, stores and containers whose capacity follows the registry | [Resources](https://jaehyeon.me/desflow/latest/user-guide/resources/#how-it-works) | | output, which the model prints or logs | records of a fixed shape, written to sinks on a thread of their own | [Egress](https://jaehyeon.me/desflow/latest/user-guide/live-runs-and-connectors/egress/#how-it-works) | | statistics, replications and confidence intervals | statistics collected during the run, replications, experiments and `explain` | [Built-in Statistics](https://jaehyeon.me/desflow/latest/user-guide/results/statistics/#how-it-works) | [Coming from SimPy](https://jaehyeon.me/desflow/latest/simpy/coming-from-simpy/#what-desflow-changes) compares each change with plain SimPy. ______________________________________________________________________ ## How It Works Look first at how a model gets from a file or a script to a run, then at the parts the run holds: Each of the three ways ends in one `DynamicRealtimeEnvironment`. A YAML file is read by `blueprint`: `loader` reads the file, including `!python` and `!include`, `models` define and check each section, and `build` turns the sections into calls on `SimulationContext`; the arrow labelled calls the builder shows them. A builder script makes those calls itself, with the builder's methods and decorators. A low-level script makes neither: it builds the environment by hand and writes SimPy processes against it. [Writing a Model](https://jaehyeon.me/desflow/latest/user-guide/writing-a-model/index.md) helps choose between them. `SimulationContext` in `builder.context` collects what a model declares. `run()` checks the declarations and builds the environment, then starts the model's loops and processes and runs it, in the order [What `run()` Does](https://jaehyeon.me/desflow/latest/user-guide/tasks-and-processes/tasks/#what-run-does) lists. The environment holds the parts in the row under it: - **registry:** holds every live parameter ([Live Parameters](https://jaehyeon.me/desflow/latest/user-guide/live-runs-and-connectors/live-parameters/#how-it-works)). - **statistics:** collects the measures of the run while it goes on ([Built-in Statistics](https://jaehyeon.me/desflow/latest/user-guide/results/statistics/#how-it-works)). - **egress queue:** the records that tasks and processes publish are buffered for each sink, and full batches wait in a queue. `connectors/egress` writes from it, on a thread of its own, and the arrow points the way the records go ([Egress](https://jaehyeon.me/desflow/latest/user-guide/live-runs-and-connectors/egress/#how-it-works)). - **connectors/ingress:** read parameter changes from outside, on a thread of their own, and update the registry. The arrow points up, because a change reaches the model only through the registry; the environment applies each one from a queue ([Ingress](https://jaehyeon.me/desflow/latest/user-guide/live-runs-and-connectors/ingress/#how-it-works)). [Threads and Queues](#threads-and-queues) shows both queues. The group at the bottom holds the tools. `cli` is the `desflow` command and calls `loading`, the path by which `desflow run` and `desflow explain` turn a blueprint or a builder file into a context ([Command Line](https://jaehyeon.me/desflow/latest/cli/#how-it-works)). `analysis` runs a model many times for [replications](https://jaehyeon.me/desflow/latest/user-guide/results/replications/#how-it-works) and [experiments](https://jaehyeon.me/desflow/latest/user-guide/results/experiments/#how-it-works). `cli` and `explain` read a blueprint or a builder file; `analysis` also runs a low-level model, as a `LowLevelModel`, from Python. `explain` is in the last row of the table below. Each part is described in full on its own page. In short: | Part | How it works | Read | | -------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | Writing a model | A YAML blueprint, the builder and the low-level API are layers. `from_yaml` makes the calls a builder script makes, and the builder's `run()` makes the calls a low-level script writes by hand. | [YAML Blueprints](https://jaehyeon.me/desflow/latest/user-guide/writing-a-model/blueprints/#how-it-works), [What `run()` Does](https://jaehyeon.me/desflow/latest/user-guide/tasks-and-processes/tasks/#what-run-does) | | Environment and pacing | `DynamicRealtimeEnvironment` is SimPy's `RealtimeEnvironment` with the registry, the connectors and the statistics added. It runs without waiting at `factor: 0` and switches to real time at `go_live_at`. | [Time and Pacing](https://jaehyeon.me/desflow/latest/user-guide/time-and-pacing/#how-it-works) | | Random times | A distribution reads its parameters at each draw, so a change applies from the next draw. Each one has its own random stream, made from the run's seed and its registry path. | [Arrivals and Services](https://jaehyeon.me/desflow/latest/user-guide/model-parts/arrivals-and-services/#how-it-works) | | Registry | Every live value sits under a dot path, such as `Shop.service.packing.mean`. Each update is checked before it is stored. | [Live Parameters](https://jaehyeon.me/desflow/latest/user-guide/live-runs-and-connectors/live-parameters/#how-it-works) | | Resources, stores and containers | Each waits on its registry path, so its capacity changes during a run. A resource that shrinks lets its busy units finish. | [Resources](https://jaehyeon.me/desflow/latest/user-guide/resources/#how-it-works), [Stores and Containers](https://jaehyeon.me/desflow/latest/user-guide/model-parts/stores-and-containers/#how-it-works) | | Threads, ingress and egress | The SimPy thread runs the model. Ingress and egress run their connectors on threads of their own, each on an asyncio loop, so a network wait never stalls a simulation step. | [Threads and Queues](#threads-and-queues), which also compares these queues with the waiting lines of the model; [Ingress](https://jaehyeon.me/desflow/latest/user-guide/live-runs-and-connectors/ingress/#how-it-works), [Egress](https://jaehyeon.me/desflow/latest/user-guide/live-runs-and-connectors/egress/#how-it-works), [Write a Connector](https://jaehyeon.me/desflow/latest/how-to/records-and-kafka/write-a-connector/index.md) | | Measurement and explain | One statistics object collects readings while the run goes on. Replications run the model again for each seed and give a Student t interval. `desflow explain` applies queueing formulas to the model before anything runs. | [Built-in Statistics](https://jaehyeon.me/desflow/latest/user-guide/results/statistics/#how-it-works), [Replications](https://jaehyeon.me/desflow/latest/user-guide/results/replications/#how-it-works), [Experiments](https://jaehyeon.me/desflow/latest/user-guide/results/experiments/#how-it-works), [Command Line](https://jaehyeon.me/desflow/latest/cli/#how-it-works) | ### How a YAML File Becomes Builder Calls Follow the file down the left column, then look at the group on the right, which joins each section of the file to the builder call it becomes: - **loader** reads the file, replaces `${VAR}` with an environment variable, and resolves `!python` and `!include` ([YAML Blueprints](https://jaehyeon.me/desflow/latest/user-guide/writing-a-model/blueprints/#how-it-works)). It keeps the line each key came from, so an error names the line. - **models** checks each section and refuses an unknown key, so a misspelt key is reported, not ignored. - **build** makes one builder call for each entry, so a YAML file and a builder script that make the same calls build the same model. From `SimulationContext` on, a run goes as the next diagram shows. ### How a Builder Script Becomes a Run Look at the two halves: the top shows where the builder keeps what a script declares, and the group below shows what `run()` does with it, in order. `run()` is `start()` then `finish()`. A script that steps through a run itself calls `start()`, then `step()` or `advance()`, and ends the run with `finish()` or `close()`: `start()` checks the model, builds the run and starts it, and `finish()` runs it to its end and closes it. [What `run()` Does](https://jaehyeon.me/desflow/latest/user-guide/tasks-and-processes/tasks/#what-run-does) gives the steps in order. ### What a Low-Level Script Uses A low-level script uses the engine directly. Look at the top row for what the script calls, and at the row below it for what the environment holds: - **environment:** the script creates it, registers its parameters, calls `setup_stats`, `setup_ingress` and `setup_egress`, starts its processes with `env.process`, and calls `run()`. - **sampler:** draws every random time, with one random stream for each distribution ([Arrivals and Services](https://jaehyeon.me/desflow/latest/user-guide/model-parts/arrivals-and-services/#how-it-works)). - **DynamicResource:** a resource whose capacity follows its registry path ([Resources](https://jaehyeon.me/desflow/latest/user-guide/resources/#how-it-works)). - **rules:** the checks a blueprint and the builder share; the registry uses one of them to check a capacity before it stores it. - **expressions, families and replay** serve the builder and YAML: conditions and amounts, resources and signals made from a computed key, and arrivals read from a recorded file. [ARCHITECTURE.md](https://github.com/jaehyeon-kim/desflow/blob/v1.3.0/ARCHITECTURE.md) draws the same three diagrams as text, with every module. ______________________________________________________________________ ## Threads and Queues ### What the Environment Holds A `DynamicRealtimeEnvironment` is SimPy's `RealtimeEnvironment` with four additions: the registry at `env.registry`, the ingress connectors, the egress connectors with their buffers, and the statistics at `env.stats`. Whichever way a model is written, `SimulationContext.run()` builds this environment. ### Threads A run uses three threads, with queues between them. Records flow from the processes to the sinks, and parameter changes flow from the sources to the registry: - **SimPy thread:** runs the model. When a process publishes a record, the record goes into a buffer for each sink, and a full buffer is handed to that sink's queue. - **Egress thread:** runs the sinks' asyncio code, which drains the queues and writes to Kafka, files or databases, or keeps the records in memory, so network waits never stall a simulation step. - **Ingress thread:** runs the sources, which put `(path, value)` pairs on a queue. ### Two Kinds of Queue The word queue means two different things in desflow: - **A waiting line in the model** holds entities, such as orders waiting for a packer. A resource keeps its line in `queue`, ordered `fifo`, `lifo` or by `priority`, and a request past its `queue_limit` raises `QueueFull`. Stores and containers have lines of puts and gets that wait. These lines are what a study measures: their lengths and waits are in the records and the statistics. - **A hand-off queue** holds data on its way between the threads above. The ingress queue has no limit, and the ingress monitor applies it. Each sink has its own queue of at most `max_queued_batches` batches. When a sink's queue is full, the simulation waits, so a slow sink slows the run instead of building a backlog. When it stays full for `drain_stall_seconds`, the run stops rather than lose records. These queues change how fast the records arrive, never what they hold. ### Processes the Environment Starts Besides your own processes, the environment starts these, as events of its own that `step()` and `peek()` do not count: - an ingress monitor, which applies queued changes every 0.1 simulation seconds; - a lag monitor, which publishes `system.simulation.lag_seconds` every `lag_interval`, at a `factor` above 0 or after going live; - a timed flush per sink, at a `factor` above 0; - the statistics timer; - the warm-up reset. They share SimPy's one event queue with the model's events, so `run()` processes them in order with the model's events. A script that steps the model never sees them. `advance()` and `finish()` run them in the same way. An environment subclass that overrides `step()` sees every event inside `run()`, desflow's own included, and only the model's events when a script steps outside `run()`. ### SimPy and desflow SimPy's `RealtimeEnvironment` takes one `factor` for the whole run, and raises an error when the model falls behind the wall clock. desflow runs without waiting at `factor: 0`, switches to real time at `go_live_at`, and stamps every record with a logical time. A paced run is strict by default, as SimPy's is, and `strict: false` reports falling behind as telemetry instead. [SimPy and desflow](https://jaehyeon.me/desflow/latest/simpy/index.md) compares the two. ______________________________________________________________________ ## For Contributors A contributor who changes desflow itself can read [ARCHITECTURE.md](https://github.com/jaehyeon-kim/desflow/blob/v1.3.0/ARCHITECTURE.md), which holds the code map and the rules for imports. # Writing a Model desflow has three ways to write a simulation: a YAML blueprint, the builder API and the low-level API. This page says how they relate and which to choose. If you are new to desflow, start with [First Simulation](https://jaehyeon.me/desflow/latest/learn/first-model/first-simulation/index.md), which shows the same model in all three APIs side by side. Return here to look up a specific component. ______________________________________________________________________ ## What It Is The three are layers, not alternatives. Each layer writes the one below it for you: - **YAML blueprint:** a file. `SimulationContext.from_yaml`, which `desflow run` calls, reads it and makes the same builder calls a Python script would make, so the result is an ordinary `SimulationContext`. - **Builder API:** `SimulationContext` collects resources, distributions, tasks and connectors through its methods and decorators. Its `run()` compiles them into a `SimParameter`, builds the environment, registers the parameters and starts the processes. - **Low-level API:** you write that last step by hand: a `SimParameter`, a `DynamicRealtimeEnvironment` that registers it, and SimPy processes that use the environment's resources and publish records. Because each layer ends in the one below, the layers mix: a blueprint can reference Python written for the builder with `!python`, and a builder process can use the environment directly. ______________________________________________________________________ ## How to Use It | | YAML Blueprint | Builder API | Low-level API | | ------------------------ | -------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------ | -------------------------------------------------------------------- | | **Entry point** | `desflow run` or `SimulationContext.from_yaml` | `SimulationContext` | `DynamicRealtimeEnvironment` | | **What you write** | the simulation, declared in a file; Python only for logic YAML cannot express, referenced with `!python` | what the system looks like, with decorators for each task's steps | how every event and resource operates, step by step | | **What it does for you** | everything the builder does, and no Python to run | publishing each task's events, requesting resources, sampling times, routing between tasks, statistics | nothing: you queue, start, time out and release yourself | | **Typical use** | changing rates, capacities, connectors and timed experiments between runs without editing code | models whose logic is most of the program, and configuration built in code, for example from a loop | what the builder does not do, such as resources created during a run | ### Which to Choose - **YAML blueprint** when the configuration is what changes between runs: a new arrival rate, another packer, a different broker, a scripted experiment. A file is easy to review and to diff, a run is one command, and a blueprint has a scenario of timed changes on the simulation clock built in. Logic that YAML cannot express goes in a Python module beside the file, as [Call Python from YAML](https://jaehyeon.me/desflow/latest/how-to/tools/yaml-advanced/index.md) shows. - **Builder API** when most of the program is logic and you want it in one Python file, or when you build the configuration in code. - **Low-level API** when you need what the builder does not do, or full control of every event. [YAML Blueprints](https://jaehyeon.me/desflow/latest/user-guide/writing-a-model/blueprints/index.md), [Builder API](https://jaehyeon.me/desflow/latest/user-guide/writing-a-model/builder-api/index.md) and [Low-level API](https://jaehyeon.me/desflow/latest/user-guide/writing-a-model/low-level-api/index.md), the next three pages, describe each way in full. ______________________________________________________________________ ## How It Works Whichever way a model is written, it builds the same environment, and one run goes the same way from there. [How desflow Works](https://jaehyeon.me/desflow/latest/user-guide/how-desflow-works/index.md) shows that run and each part it passes through. # YAML Blueprints A YAML blueprint is a simulation written as a file. This page shows how to run one, how a file is read and checked, how to change settings per environment, and where an error points. [YAML Keys](https://jaehyeon.me/desflow/latest/reference/yaml-keys/index.md) lists every key a blueprint accepts. ______________________________________________________________________ ## What It Is A blueprint holds, as data, the builder calls that a Python script would make. Each section becomes the builder call of the same name: `resources` is `add_resource`, `tasks` is `@app.task`, `stats` is `with_stats`, and so on. There is no second way of building: `SimulationContext.from_yaml` makes those calls, in the order a script would, and returns an ordinary `SimulationContext`. A blueprint and a script that make the same calls produce the same simulation, and the tests check that the YAML, builder and low-level versions of every example publish the same records. Use Python for logic that YAML cannot express. Reference it with `!python`, as [Call Python from YAML](https://jaehyeon.me/desflow/latest/how-to/tools/yaml-advanced/index.md) shows. An editor completes keys and marks a misspelt key or a value of the wrong kind as you type, from the JSON Schema that `desflow schema` prints and this site publishes. [Set Up Your Editor](https://jaehyeon.me/desflow/latest/how-to/tools/set-up-your-editor/index.md) shows the setting. ______________________________________________________________________ ## How to Use It ### Run a Blueprint Run it from a shell with the `desflow` command, which the package installs. These lines use the local example: ```bash desflow examples get local --api yaml # downloads local/yaml/local.yaml cd local/yaml desflow run local.yaml # runs until run.until desflow run local.yaml --until 10min # overrides run.until desflow run local.yaml --seed 7 # overrides simulation.random_seed desflow examples # lists the other examples desflow --version ``` `--until` takes seconds or a duration such as `10 min`, `2 hours` or `1 week`. The command logs at INFO level, unless [Log Level](#log-level) sets another. `ConsoleEgress`, in its default `log` format, writes each batch at INFO, so its output is visible unless that level is `warning` or `error`. A run with no seed logs the seed it drew, with the command that repeats it. An invalid file prints its errors and exits with code 1. Or run it from Python: ```python from desflow import SimulationContext app = SimulationContext.from_yaml("local.yaml") app.run() # calls run.before, then runs until run.until ``` `run()` calls the blueprint's `run.before` functions first, and uses `run.until` when no `until` is passed. The builder methods and decorators still work on the context `from_yaml` returns. `load_context` loads a blueprint or a builder Python file by the same path, so a script that takes either kind of file needs no check of its own: ```python from desflow import load_context # A blueprint, or a builder Python file that defines a SimulationContext at # module level, from its folder: the one loader desflow run and explain use app = load_context(".", "local.yaml") ``` ### Log Level desflow logs under the `desflow` logger: the build, the start and the teardown at INFO, and problems at WARNING and ERROR. Its level sets how much of that a run shows: `log_level` under `simulation` takes `debug`, `info`, `warning` or `error`, or a placeholder, here read from an environment variable: ```yaml # Under simulation: how much desflow logs, one of debug, info, warning and error; # desflow run --log-level overrides it for one run log_level: ${SIM_LOG_LEVEL:-info} ``` The level is set when the context is built, so it applies to `SimulationContext.from_yaml()` and to `desflow run --sample` and `--stdout` too. A Python program shows the lines only when it sets up logging, such as `logging.basicConfig(level=logging.INFO)`. `desflow run FILE --log-level warning` overrides the key for one run, as `--until` overrides `run.until`. Without either, `desflow run` logs at INFO. The other commands, such as `desflow check` and `desflow explain`, log at WARNING whatever the file says. The context takes no argument for it: the script sets the level of the `desflow` logger with Python's `logging` module: ```python app = SimulationContext(sim_id="Shop", factor=0.0) # What simulation.log_level: warning sets in a blueprint logging.getLogger("desflow").setLevel(logging.WARNING) ``` ```python env = DynamicRealtimeEnvironment(factor=0.0) # The same logger: the environment and its connectors log under desflow logging.getLogger("desflow").setLevel(logging.WARNING) ``` `ConsoleEgress` in its default `log` format writes its records at INFO, so a level of `warning` or `error` hides them too. A JSON console writes at any level. `desflow run --replications` leaves out the INFO lines of each replication's build and teardown whatever the level, and their warnings too when the level is `error`. ### Preview the Records `desflow run FILE` builds the blueprint and runs it with its own sinks until `--until`, `run.until` or Ctrl+C. It takes a YAML file, and with `--sample` also a Python builder file, which prints its first events the same way. A builder file otherwise runs with `python FILE`. Two options print the records instead of sending them to the file's sinks: | Command | Behaviour | | ----------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `desflow run FILE --sample N` | Prints the first `N` events, then stops. `N` is 1 or more. The run is unpaced: `factor` is set to 0 and `go_live_at` is cleared. `logical_start_time` and `random_seed` are kept, so timestamps and values look as they would in the real run. Ingress entries and `run.before` are skipped. Telemetry records print between the events but are not counted, and `system.simulation.lag_seconds` is not printed. | | `desflow run FILE --stdout` | Prints every record of a normal run except the `system.simulation.lag_seconds` readings, which describe the wall clock, not the model. `factor`, `go_live_at`, `logical_start_time` and ingress are kept; `run.before` is skipped. | Both replace every egress entry with one `Console` of `format: json`, and a second one for labels when the file has a `when: labels` entry. A JSON console writes each record as one JSON line on stdout. The run's log stays on stderr, so `desflow run FILE --sample 10 | jq .value` reads only the records. A preview checks the whole file, but not the connectors it leaves out: - The structure, keys and names of the whole file are validated. - `run.before` is skipped, because its functions prepare the real sinks, such as creating topics. A warning on stderr says so when the file has any. - The connectors a preview replaces or skips are not built, so only their `type` is checked. Their `config` is checked only by a run that builds them, such as `desflow run FILE` without these options. | Combination | Result | | ----------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `--sample` with `--stdout` | Allowed. `--stdout` adds nothing. | | `--sample` with `--until`, or a file with `run.until` | The run ends at whichever comes first. When `until` comes first, stderr says `sample ended at until with k of N events`. A model that runs out of events first ends the sample too, with exit code 0 and `sample ended with no events left, with k of N events`. | | `--sample` on a file with `go_live_at` | A backfill-then-live file prints its first history events. `when: history` and `when: live` have no effect, because their entries are replaced. | | `--sample` on a file that publishes no events | It runs until `until` or Ctrl+C, printing telemetry. | | `--stdout` on a file with several egress entries | One console prints each record once. Per-entry `batch_size` and `flush_interval` are dropped with the entries, and the `batching` section applies. | | `--sample` or `--stdout` with `--replications` | Usage error, exit code 2: both print one run. | | `--sample 0` | Usage error, exit code 2. | [Command Line](https://jaehyeon.me/desflow/latest/cli/index.md) lists every command and option. ### Times and Durations A time in a blueprint is a number of seconds or a duration such as `90 s`, `10 min`, `2 hours` or `1 week`: `run.until`, a scenario step's `at`, `simulation.warmup`, a stats `interval`, and every time-valued distribution parameter. `rate` is the exception: it is a number per second. A text that is a plain number, such as `"5"` or `"1e-3"`, is that many seconds. A time place refuses NaN, `true` and a negative number, with the place named in the error. Infinity is refused where a time must end, such as `factor`, `initial_time`, a scenario `at` and a segment `every`, and elsewhere it means no limit. `factor` is a number, not a time, so `"2 min"` is refused. `logical_start_time` and `go_live_at` are instants: `now`, a signed duration from now such as `-1d` or `-10m`, or an ISO datetime such as `2026-01-01T00:00:00`. Both are read against one moment, when the file is loaded, so `-10m` and `now` are exactly ten minutes apart. `now`, the relative forms and an ISO datetime without an offset are read in `simulation.timezone`, whose default [Clocks and Pacing](https://jaehyeon.me/desflow/latest/user-guide/time-and-pacing/clocks-and-pacing/#time-zone) gives. ### Settings per Environment `${VAR}` in a value is replaced with the environment variable, so one file can serve several environments. `${VAR:-default}` uses the default when the variable is unset or empty, as in a shell, and `$${` writes a literal `${`. A default cannot hold another `${`, and the load refuses it. An unquoted value is read as YAML reads it after the replacement, so `factor: ${SIM_FACTOR:-0}` is the number 0. A quoted value stays a string, so `"${LIMIT:-5}"` is the text `5`: write a number or a boolean unquoted. An unset variable with no default stops the load, and the error names its line. ```yaml # Settings that change per environment, read from environment variables. # Run it with: SIM_FACTOR=1 desflow run environment.yaml simulation: sim_id: ${SIM_ID:-Shop} # An unquoted value is read after the replacement, so this is the number 0 factor: ${SIM_FACTOR:-0} # Read against the moment the file is loaded: a day of history up to now logical_start_time: -1d # Under simulation: timestamps written in Melbourne time, with its offset; the # start and now are read in it. UTC by default timezone: ${SIM_TIMEZONE:-Australia/Melbourne} # Under simulation: how far the run is behind the wall clock, every 10 s; by # default off at factor 0 and every second otherwise, and 0 turns it off lag_interval: 10 s # Under simulation: true by default for a paced run and false at factor 0; false # lets a live run go on when a slow sink makes it fall behind the wall clock strict: false # Under simulation: how much desflow logs, one of debug, info, warning and error; # desflow run --log-level overrides it for one run log_level: ${SIM_LOG_LEVEL:-info} egress: - {type: Console} resources: # Quoted, because ${...} inside {...} would end the mapping early; the check # turns the text into a number packers: {current_cap: "${PACKERS:-2}", max_cap: 5} run: # A duration, such as 1 week, or a number of seconds until: ${RUN_FOR:-1 hour} ``` The [Parquet example](https://jaehyeon.me/desflow/latest/gallery/simulation-models/parquet/index.md) switches from the local disk to S3 with five variables, and [Queues and Capacity](https://jaehyeon.me/desflow/latest/learn/first-model/queues-and-capacity/index.md) runs one file with several numbers of packers. ### Include a File `!include path` puts a mapping from another YAML file in place, such as the settings `desflow fit` writes: `packing: !include fitted/packing.yaml`. The path is relative to the file that names it. `!include {file: path, spawn: pack}` adds keys to the file's mapping, such as the task an arrival spawns. A key the file already has is refused, and the error names the key and both files. The file is read with the same loader, so `${VAR}`, `!python` and `!include` work in it. A file that includes itself, directly or through another file, is refused. [Input Fitting](https://jaehyeon.me/desflow/latest/user-guide/model-parts/input-fitting/#load-the-settings) shows it. ### Generated Values A value place takes a constant or a generator, a mapping with a `gen` key. The places are `payload`, `attributes`, `set`, a store's `items`, the `value` of an `on:` entry, a `fire`, a timeout and a scenario step, an interrupt's `cause`, and a scenario `record`. [Generators](https://jaehyeon.me/desflow/latest/generators/index.md) lists every kind, and [Generate Data](https://jaehyeon.me/desflow/latest/how-to/generate-data/choices-and-numbers/index.md) shows them in tasks. This blueprint builds an order record from most of them. The task's own keys come first: ```yaml # Named values, drawn in order once for each instance of the task when it starts, # because on_start is given. A generator reads one as {gen: var, name: ...} vars: quantity: {gen: integer, bounds: [1, 6]} unit_price: {gen: uniform, low: 5, high: 40, decimals: 2} ship_to: gen: object fields: city: {gen: one_of, choices: [Perth, Hobart]} postcode: {gen: integer, bounds: [1000, 9999]} # Drawn once for each entity and task, at its first use vars_once: region: {gen: one_of, choices: [north, south]} # Published as one event record when the task starts on_start: opened_at: {gen: now} # Drawn after the service, and may read the vars finish_vars: closed_at: {gen: now, offset: 1 min} # The key of the task's records, drawn at the first record key: {gen: sequence, start: 1, format: "order-{}"} # Rows kept for a lookup or aggregate of this task by other tasks history: 500 ``` The rules for where a generator counts: - **Depth.** In a `payload`, `set`, `attributes` or scenario `record`, a mapping with a `gen` key is a generator at any depth. A `gen` key directly under `set`, `attributes` or a `record` is a field name. A nested mapping keeps any key other than `gen`, such as a number or a date. - **Data.** `{gen: literal, value: ...}` keeps a mapping as data. A mapping with no `gen` key in an `on:` or `fire` value is data, and a generator nested in it, or a nested `gen` inside an `on:` value, is stored as written. A mapping or list in a `put.item` is read as a payload is, so a generator nested at any depth is evaluated as the put is made. - **Text.** Text in a value place stays text. `"attr.k * 3"` is that string, and `{gen: expr, expr: "attr.k * 3"}` evaluates it. - **Files.** A `row` reads its file from the blueprint's folder when the file loads. A cell of digits is a number, so leading zeros are lost: write them with `{gen: format, template: "{n:05d}"}`. - **Seeds.** Each generator draws from a random stream of its own, made from the run's seed and the generator's place in the file. Adding a field to a mapping moves no other generator's draws. Inserting an item into a list, a scenario step or an `on:` entry moves the draws of the items after it. Each `fake` has its own Faker, and a `sample` of a service draws from the generator's own stream, so the service's draws stay as they were. The payload of the same task uses the other kinds. Each block below is a part of the same file. Arithmetic takes a list of arguments, each a constant or a generator: `add`, `subtract`, `multiply`, `divide`, `min` and `max`. `decimals` rounds the result. `expr` evaluates an expression whose `names` are generators. ```yaml total: gen: add args: [{gen: var, name: unit_price}, 10] decimals: 1 discount: gen: subtract args: [100, {gen: var, name: quantity}] weight: gen: multiply args: [{gen: var, name: quantity}, 2.5] decimals: 1 share: gen: divide args: [{gen: var, name: quantity}, 4] decimals: 2 least: gen: min args: [{gen: var, name: quantity}, 5] most: gen: max args: [{gen: var, name: quantity}, 5] ``` ```yaml with_tax: gen: expr expr: "quantity * price * (1 + tax)" names: price: {gen: var, name: unit_price} tax: {gen: param, path: Shop.variables.tax_rate} decimals: 2 ``` `lower`, `upper` and `literal` give text. `literal` keeps a value as data, even a mapping that has a `gen` key. ```yaml region: gen: upper value: {gen: var, name: region} source: {gen: lower, value: WEB} note: {gen: literal, value: "n/a"} ``` `uniform` and `normal` draw numbers, and `sample` draws from a distribution or from a service of the file, with the service's own parameters. ```yaml price: {gen: uniform, low: 5, high: 40, decimals: 2} ``` ```yaml delivery_minutes: {gen: normal, mean: 120, std: 15, decimals: 1} ``` ```yaml wait: {gen: sample, service: packing, decimals: 1} retries: {gen: sample, dist: geometric, p: 0.5} fixed: {gen: sample, dist: constant, value: 3} ``` `one_of` picks one value and `pick` picks `count` different values. ```yaml colour: {gen: one_of, choices: [red, green, blue]} ``` ```yaml extras: {gen: pick, choices: [card, ribbon, box, tag], count: 2} ``` `weighted` picks by weight, from `options` or from a list of `value` and `weight`. ```yaml paid_by: gen: weighted options: {card: 60, cash: 40} priority: gen: weighted choices: - {value: normal, weight: 9} - {value: rush, weight: 1} ``` `sequence` counts from `start` in steps of `step`, starts again after `loop_after` values, and writes each with `format`. ```yaml number: {gen: sequence, start: 1000, step: 5, loop_after: 1000, format: "ord-{}"} ``` `uuid` gives version 4 or 7. ```yaml reference: {gen: uuid, version: 7} ``` `boolean` is true with probability `p`. ```yaml gift: {gen: boolean, p: 0.1} ``` `now` gives the logical time, and `offset` moves it. ```yaml due_at: {gen: now, offset: 1 hour} ``` `format_time` writes a time in a zone. ```yaml placed_at: gen: format_time time: {gen: now, offset: -1 h} format: "%H:%M" tz: Australia/Melbourne ``` `fake` calls a method of Faker, with `args` and `kwargs`, for a `locale`. ```yaml customer: {gen: fake, method: name, locale: en_AU} phone: {gen: fake, method: numerify, args: ["04## ### ###"]} email: gen: fake method: email kwargs: {domain: example.com} ``` `format` fills a `template` from `names` and the task's vars. It reads an attribute of the entity as `{attr.}`, and an item or field of one as `{attr.pair[0]}` or `{attr.delivery[slot]}`. A missing attribute fails the run with an error that names it. An arrival's `vars`, `key` and `count` run before the entity has attributes, so a template there that reads `attr` is refused when the blueprint loads. A name that starts with `_`, such as `{attr.__class__}`, is refused too. A `names` entry called `attr` is read in place of the attributes, as before 1.3.0. ```yaml code: gen: format template: "{region}-{n}" names: region: {gen: var, name: region} n: {gen: integer, bounds: [10, 99]} # An attribute of the entity, and a field of one parcel: {gen: format, template: "size {attr.size}, slot {attr.delivery[slot]}"} ``` `switch` and `when` choose a value from another. ```yaml band: gen: switch on: {gen: var, name: quantity} cases: - {max: 3, value: small} - {min: 3, max: 5, value: medium} default: large ``` ```yaml size_label: {gen: when, condition: "quantity > 3", then: large, else: small} ``` `repeat` makes a list. ```yaml scores: gen: repeat times: 3 value: {gen: integer, bounds: [1, 5]} ``` `var` and `attr` read a var and an attribute, or one `path` of it. `param` reads a live registry value, or one `field` of a mapping. `object` builds a mapping. ```yaml city: {gen: var, name: ship_to, path: city} size: {gen: attr, name: size} slot: {gen: attr, name: delivery, path: slot} ``` ```yaml tax_rate: {gen: param, path: Shop.variables.tax_rate} high: {gen: param, path: Shop.variables.limits, field: high} ``` ```yaml address: gen: object fields: street: {gen: fake, method: street_name} postcode: {gen: integer, bounds: [1000, 9999]} ``` `call` runs a function of your own, with `kwargs` worked out first. ```yaml gross: gen: call function: !python generated_values_logic.with_tax kwargs: price: {gen: var, name: unit_price} ``` `row` takes a row of a CSV or Parquet file, kept by `where`, chosen by the column `weight`, and ending as `on_end` says: ```yaml stocked: gen: row file: generated_values_products.csv where: stock > 0 weight: share on_end: loop ``` Any generator can be null, left out, or made to give each value once: ```yaml coupon: {gen: uuid, null_rate: 0.3} gift_card: {gen: integer, bounds: [1000, 9999], omit_rate: 0.5} rush_fee: {gen: integer, bounds: [1, 9], omit_when: "quantity < 4"} ticket: {gen: integer, bounds: [1, 1000000], unique: true} ``` The first records: ```text [EVT] {'sim_ts': 60.0, 'timestamp': '...', 'key': 'order-1', 'task': 'order', 'instance': 0, 'value': {'opened_at': '2026-01-01T00:01:00.000+00:00'}} [EVT] {'sim_ts': 60.0, 'timestamp': '...', 'key': 'order-1', 'task': 'order', 'instance': 0, 'value': {'total': 40.1, 'discount': 96, 'weight': 10.0, 'share': 1.0, 'least': 4, 'most': 5, 'with_tax': 144.53, 'region': 'NORTH', 'source': 'web', 'note': 'n/a', 'price': 33.28, 'delivery_minutes': 128.6, 'wait': 7.9, 'retries': 2, 'fixed': 3, 'colour': 'blue', 'extras': ['card', 'ribbon'], 'paid_by': 'cash', 'priority': 'normal', 'number': 'ord-1000', 'reference': '019b76db-9260-7231-91a4-52fc3a1a52b5', 'gift': False, 'due_at': '2026-01-01T01:01:00.000+00:00', 'placed_at': '10:01', 'customer': 'Amanda Rose', 'phone': '0454 631 168', 'email': 'wwhite@example.com', 'code': 'north-60', 'parcel': 'size 7, slot 9', 'band': 'medium', 'size_label': 'large', 'scores': [3, 2, 1], 'city': 'Hobart', 'size': 7, 'slot': 9, 'tax_rate': 0.2, 'high': 9, 'address': {'street': 'White Square', 'postcode': 6403}, 'gross': 36.13, 'stocked': {'sku': 'A-100', 'name': 'Mug', 'stock': 12, 'share': 5}, 'coupon': None, 'rush_fee': 2, 'ticket': 841764}} ``` `unique: true` also works on a value built only from vars, such as a `format` or an `expr` with no generator of its own that draws. When the value repeats, the task's `vars` and `finish_vars` are drawn again and the whole payload is made again, so every field of the record comes from the same draws. The rules: - A failed try gives back its `unique` values and its `sequence` numbers. Every other generator draws again. - After 1000 tries the task fails with the message a `unique` generator gives when its values run out. - A `unique` value that draws by itself, such as a `format` whose `names` hold an `integer`, draws again on its own and keeps the vars, as before. - A task with `on_start`, or with a `service_time` that reads a var, draws its `vars` before it finishes, and those are not drawn again. A `unique` value that reads only them fails at its first repeat, as before. - A payload with no `unique` value draws as before. ```yaml # A unique value built from vars: each review text is new, and when a text repeats, # the task's vars are drawn again and the whole record is made again. # # Run it with: desflow run docs/snippets/yaml/unique_reviews.yaml simulation: {sim_id: Shop, factor: 0, random_seed: 7} egress: - {type: Console} arrivals: reviews: {initial: 6, spawn: review} tasks: review: vars: opener: {gen: one_of, choices: [The, My]} product: {gen: one_of, choices: [kettle, lamp, radio]} payload: number: {gen: sequence, start: 1} product: {gen: var, name: product} text: {gen: format, template: "{opener} {product} works.", unique: true} ``` Each text is new, and each record's `product` is the product of its text: ```text [EVT] {'sim_ts': 0.0, 'timestamp': '...', 'key': 'reviews-1', 'task': 'review', 'instance': 0, 'value': {'number': 1, 'product': 'kettle', 'text': 'My kettle works.'}} [EVT] {'sim_ts': 0.0, 'timestamp': '...', 'key': 'reviews-2', 'task': 'review', 'instance': 1, 'value': {'number': 2, 'product': 'lamp', 'text': 'My lamp works.'}} [EVT] {'sim_ts': 0.0, 'timestamp': '...', 'key': 'reviews-3', 'task': 'review', 'instance': 2, 'value': {'number': 3, 'product': 'radio', 'text': 'The radio works.'}} [EVT] {'sim_ts': 0.0, 'timestamp': '...', 'key': 'reviews-4', 'task': 'review', 'instance': 3, 'value': {'number': 4, 'product': 'lamp', 'text': 'The lamp works.'}} [EVT] {'sim_ts': 0.0, 'timestamp': '...', 'key': 'reviews-5', 'task': 'review', 'instance': 4, 'value': {'number': 5, 'product': 'kettle', 'text': 'The kettle works.'}} [EVT] {'sim_ts': 0.0, 'timestamp': '...', 'key': 'reviews-6', 'task': 'review', 'instance': 5, 'value': {'number': 6, 'product': 'radio', 'text': 'My radio works.'}} ``` ### Names an Expression Reads An expression reads names, calls and operators, and nothing else. The names depend on where the expression sits, and [Task Flow](https://jaehyeon.me/desflow/latest/user-guide/model-parts/task-flow/index.md) shows them in a task: - **Run:** `t` (the clock), `registry["..."]`, `level.`, `users.`, `queue.`, `signal..count` and `.processed`, `done_count` in a `when` group, and `handle..triggered`, `.processed`, `.ok`, `.value` and `.alive` for an opened event. - **Entity and flow:** `attr.`, `payload.`, `process.key`, `process.flow_name`, `item` and `item_priority` after a `get`, `arg.` from the `args` of a `wait` `task` branch or a `spawn`, `cause.` in an interrupt, and `wait..done`. `wait.suspend.value` reads in the task that was suspended, and `cause.` in a task that `on_interrupt_run` reaches. - **Task that routed here:** `upstream.`, and `upstream.status` and `upstream.reason` in a task that `on_fail`, `on_renege` or `on_balk` reaches. - **Calls on the model:** `held(r)`, `waiting(r)`, `putting(x)` and `getting(x)` give lists of mappings with an `entity`. A resource entry also has `rank`, `time`, `preempt`, `key` and `since`, a store put has `item`, and a container has `amount`. `running(task[, cond])` is a count, and `peek()` is the time of the next event. - **Forms:** `[...]`, `{...}`, a list comprehension with one `for`, subscripts and slices, `is None`, `in`, and dotted reads at any depth. `payload['total']` is refused because `payload` is not a name by itself: write `payload.total`. `attr["class"]` reads an attribute whose name Python keeps as a word. - **Constants:** `pi` and `e`, from Python's `math` module. - **Functions:** `len`, `sum`, `sorted`, `range` (at most 1,000,000 items), `any`, `all`, `str`, `int`, `float`, `bool`, `abs`, one-argument and many-argument `min` and `max`, `round`, `floor`, `ceil`, `sqrt`, `exp`, `log`, `log10`, `sin`, `cos`, `tan`, `clamp(x, low, high)`, `has(attr.x)`, and `get_key(mapping, key, default)`, `set_key` and `drop_key`. `clamp(x, low, high)` gives `low` when `x` is below it, `high` when `x` is above it, and `x` otherwise. In this blueprint, `pi` draws a daily wave of demand, and `clamp` keeps a drawn delivery distance between 1 and 30 km: ```yaml # Expressions: the constants pi and e, and clamp to keep a value inside a range. # # Each order's demand index follows a daily wave, and its delivery distance is a drawn # number kept between 1 and 30 km. # # Run it with: desflow run docs/snippets/yaml/expression_functions.yaml simulation: {sim_id: Shop, factor: 0, random_seed: 7} egress: - {type: Console} arrivals: orders: {gap: 6 hours, max_events: 3, spawn: place_order} tasks: place_order: vars: drawn_km: {gen: normal, mean: 12, std: 15} payload: # One wave a day: 100 at midnight, 120 at 06:00 and 80 at 18:00 demand: {gen: expr, expr: "round(100 + 20 * sin(2 * pi * t / 86400), 1)"} # A drawn distance below 1 km becomes 1, and one above 30 km becomes 30 distance_km: {gen: expr, expr: "round(clamp(drawn_km, 1, 30), 1)"} run: {until: 1 day} ``` The first order's drawn distance is above 30 km, so it is published as 30: ```text [EVT] {'sim_ts': 21600.0, 'timestamp': '...', 'key': 'orders-1', 'task': 'place_order', 'instance': 0, 'value': {'demand': 120.0, 'distance_km': 30}} [EVT] {'sim_ts': 43200.0, 'timestamp': '...', 'key': 'orders-2', 'task': 'place_order', 'instance': 1, 'value': {'demand': 100.0, 'distance_km': 11.2}} [EVT] {'sim_ts': 64800.0, 'timestamp': '...', 'key': 'orders-3', 'task': 'place_order', 'instance': 2, 'value': {'demand': 80.0, 'distance_km': 17.8}} ``` The limits are these. One reading that makes more than 1,000,000 items in all is a named run failure. `%` on text and `**` with an integer power above 10000 are refused, and so is `**` with a negative base and a fractional exponent, `round(x, -n)` with a very large `n`, `clamp` with `low` above `high`, and an expression nested more than 200 levels. Text is allowed in comparisons, indexes, list and mapping entries, `+` and the key functions. `prod` and `sumprod` are reserved for a later release, and a var, loop name or generator `names` entry cannot take them or any other name an expression already uses. `pi`, `e` and `clamp` are the exception, because they came after 1.0: a var, loop name or `names` entry may take one of them. An expression that can read a var or entry called `pi` or `e` reads it in place of the constant, and `clamp(...)` always calls the function. A run place, such as an arrival's `gap`, cannot read the arrival's vars, so one that reads `pi` or `e` while the arrival has a var of that name is refused, as in 1.2.0. ### Run on Your Own Environment `simulation.environment` runs the model on your own subclass of `DynamicRealtimeEnvironment`, named with `!python`, as `SimulationContext(environment=...)` does in Python, for example `environment: !python my_model.TracingEnvironment`. A subclass that overrides `__init__` takes `**kwargs` and passes them on, because desflow builds it with the arguments it builds its own environment with. One that overrides `schedule` or `step` calls `super()`. When a script steps outside `run()`, `step` runs once per model event. Inside `run()`, it runs once per event, desflow's own events included. In a blueprint, the class is named under `simulation`. `CountingEnvironment` in `endings_logic.py` counts the events the run processes: ```yaml # Run on a subclass of DynamicRealtimeEnvironment, from endings_logic.py beside the # file environment: !python endings_logic.CountingEnvironment ``` ______________________________________________________________________ ## How It Works `from_yaml` makes the builder calls for you, so a blueprint gets everything [the builder does](https://jaehyeon.me/desflow/latest/user-guide/writing-a-model/builder-api/#how-it-works), and it checks the whole file before anything runs. A file is read and checked in five steps, and any step that fails stops the load with a `BlueprintError` before anything runs: 1. **Read the file.** `read_document` reads it with a subclass of `yaml.SafeLoader`. `${VAR}` is replaced while each scalar is read, `!python module.attribute` imports the module and returns the attribute, `!include path` reads a mapping from another YAML file relative to this one, and every key's line is kept in a source map. Every other node is built as `yaml.safe_load` would build it, except that the key `on` of a task, a signal, an experiment check and a `switch` is read as text, and so are the keys `yes`, `no`, `on` and `off` of a `switch`'s `cases` and a `weighted`'s `options`. A key written twice in one mapping is refused at its second line, and the error names both lines. Elsewhere, two keys that YAML reads as one value, such as `yes` and `true`, are refused the same way. 1. **Check every field.** The document is validated against the `Blueprint` model. Unknown keys are refused, so a misspelt key is reported rather than ignored. Every distribution is built as the builder would build it, so a parameter out of range, `true`, NaN, or one the family does not take, is refused here. Every expression place is checked at its line, a capacity below 0 is refused, and a refusal under a field that takes a name or a mapping reports only the member that matches, with no type or class name. Every relative time is read against one `now`. A `spawn` `after` and a `fire` `after` must be above 0. `simulation.environment` must be a subclass of `DynamicRealtimeEnvironment`. All validation errors are reported at once. 1. **Check the names.** Each name in the file must exist and fit where it is used: - Every service, resource, store, container and next task that a task names exists. - Every task's `spawn` and `on:` spawn names a task that does not share an arrival's name. - A `subscribe` names a task or a signal. - An `on:` fire names a signal, and an `on:` interrupt names a task. - An `on:` `fire ... from` names a signal or a task. The task must run on the same entity as the `on:` list. For a task's list, that is the entity of the task that holds the list. For a signal's list, it is the entity of a task that fires the signal. - Every `level.` in an expression names a store or a container, and every `users.` and `queue.` names a resource. - A name is used in one of resources, stores, containers and signals, and holds no dot or space. - A task's `priority` needs a resource with `queue: priority`. - Resources and stores have whole-number capacities. - An `on:` fire with `urgent`, `after` or `priority` names a signal with `once: true`. A `priority` is a whole number and is refused with `urgent`. - A `fail` is refused with `from`, and `defused` needs `fail`. A `fail_reason` needs a `fail` condition. - A `listen` names one of `signal` and `handle`, an `index` needs a `handle`, and the signal or handle is declared. - A `when` or a generator `value` in a signal's `on:` that reads `wait.` is refused, because a signal's entries run with no wait in scope. So is an `each.index` or `each.value` read outside the branch of an `each`. - A scenario step's interrupt `where` reads `wait.` only for a branch of the wait of the task it interrupts. - `simulation.environment` names a subclass of `DynamicRealtimeEnvironment`. 1. **Build the context.** The builder calls are made in the order a script would make them: the simulation, ingress, egress, batching, stats, resources, stores, containers, variables, services, arrivals, tasks, arrival loops, processes, telemetry and the scenario. 1. **Check the paths.** The parameters are registered into a scratch registry, with the code that the run uses. Every scenario `path`, and every `registry["..."]` that an expression reads, is then checked against the paths the run will have. Every scenario `value` must convert to the type its path holds. `!python module.attribute` imports `module` and returns its `attribute`: a function, a class, a dictionary or a constant. The longest prefix that is a module is imported, and the rest is read as attributes. The folder of the YAML file is added to the front of `sys.path`, so a module beside the blueprint is found from any working directory, and two blueprints in different folders that each have a `logic.py` use their own, also when one command loads both. The exception is a module that the process imported before it loaded its first blueprint, such as `random` or another standard library module: every blueprint uses that module, not a file of the same name beside it. Give a module beside a blueprint a name that no standard library module or installed package has. `${VAR}` is replaced inside a reference too. Every reference is resolved when the file is loaded, so a wrong one fails before the run starts, with the file and line: ______________________________________________________________________ ## Stability and Limits An error at any step is mapped back to its line through the source map. A time in a message reads `5` for a whole number, and a number in `{now:g}` form has six significant digits, so 1000000 reads `1e+06`: ```yaml # A blueprint with a mistake, for the YAML Blueprints page: pack_order has a priority, # but its resource serves its queue in the default order, fifo. simulation: {sim_id: Shop, factor: 0} resources: packers: {current_cap: 1, max_cap: 2} services: packing: {dist: constant, value: 1.5 s} arrivals: orders: {dist: exponential, rate: 0.5, spawn: pack_order} tasks: pack_order: service: packing resource: packers priority: 0 payload: {event_type: order_packed} ``` ```python try: SimulationContext.from_yaml("blueprint_error.yaml") except BlueprintError as error: print(f"Error: {error}") # what desflow run prints, before exiting with code 1 ``` ```text Error: blueprint_error.yaml:18: task 'pack_order' has a priority, but resource 'packers' does not set queue: priority; set it, or remove the priority ``` A blueprint covers configuration, including several resources per task (`resource: [picker, bench]` and `keep`), preemption (`preempt: true`) and breakdowns (`breakdown:`). These stay in Python: - **Values computed per entity.** A mapping payload is a constant, apart from three values added for each entity: the task id that `id_field` adds, the attributes that `attributes` adds, and the item a `get` took, which `item_field` adds. Random choices, derived fields and state carried between events are a Python payload or process, as [Call Python from YAML](https://jaehyeon.me/desflow/latest/how-to/tools/yaml-advanced/index.md) shows. A task's `priority` and a `get` or `put` amount can be an expression. `next` rules read attributes, payload fields, levels, registry values, the item a `get` took (`item.`), the wait's branches (`wait..done`) and signals (`signal..count`), as [Task Flow](https://jaehyeon.me/desflow/latest/user-guide/model-parts/task-flow/index.md) describes. - **Keys described where their subject is.** `seize`, `release`, `open`, `cancel` and handles are in [Task Flow](https://jaehyeon.me/desflow/latest/user-guide/model-parts/task-flow/index.md) and [Tasks and Processes](https://jaehyeon.me/desflow/latest/user-guide/tasks-and-processes/index.md). `batch` is in [Serve Entities Together](https://jaehyeon.me/desflow/latest/how-to/modelling/serve-entities-together/index.md). `family` and `members` are in [Resources](https://jaehyeon.me/desflow/latest/user-guide/resources/index.md). `{of, key}` and `{of, lowest}` references, `fire` with `fail`, and `listen` are in [Signals and Waiting](https://jaehyeon.me/desflow/latest/user-guide/tasks-and-processes/signals-and-waiting/index.md). `lookup`, `previous`, `upstream` and `aggregate` are in [Task Flow](https://jaehyeon.me/desflow/latest/user-guide/model-parts/task-flow/index.md). `breakdown.clock` is in [Priority and Preemption](https://jaehyeon.me/desflow/latest/user-guide/resources/priority-and-preemption/index.md). The arrival keys are in [Arrivals and Services](https://jaehyeon.me/desflow/latest/user-guide/model-parts/arrivals-and-services/index.md), and `run.segments`, `steps` and `sync` in [Run Length](https://jaehyeon.me/desflow/latest/user-guide/time-and-pacing/run-length/#run-in-segments). - **Entity keys.** An arrival's `key` and a task's `key` take text, a number or a generator, and the default is `-`. Only a key written as a Python function is builder only. - **One simulation per file.** A blueprint has one `sim_id`. `!include` puts a mapping from another file in place, such as fitted settings, but not a second simulation. ### Security A blueprint with no `!python` references is read entirely by `yaml.SafeLoader`, and loading it imports only the connector modules its `type` entries name. An `!include` reads another YAML file the same way and imports nothing itself. A file that references Python, directly or in a file it includes, runs the imports it names. Such a file needs the same trust as a Python script: run blueprints only from people whose scripts you would run. Every other node is built by `yaml.SafeLoader`, and only `!python` and `!include` are added to it. # Builder API This page writes a whole simulation as one Python file with the builder, `SimulationContext`: a shop that packs orders with boxes from stock, prints a label, and leaves the parcel for a courier. It builds on [Writing a Model](https://jaehyeon.me/desflow/latest/user-guide/writing-a-model/index.md), which places the builder between a blueprint and the low-level API, and on [Tasks and Processes](https://jaehyeon.me/desflow/latest/user-guide/tasks-and-processes/index.md), which describes what a task does. ______________________________________________________________________ ## What It Is The builder works in two phases. You describe the simulation with its methods and decorators, and nothing runs. `run()` then builds the environment and the connectors and starts the clock: Until `run()` builds the environment, the runtime helpers `context.spawn`, `context.call`, `context.signal`, `context.get_resource`, `context.get_store`, `context.get_container` and `context.env` raise `RuntimeError`. Loops, tasks and processes run only after that, so the helpers belong inside them. ______________________________________________________________________ ## How to Use It ### Create the Context The context names the simulation and sets its clock: `factor` for the pacing, `random_seed` for the draws, `logical_start_time` for the timestamps. It also takes `go_live_at` and `warmup`, which [Time and Pacing](https://jaehyeon.me/desflow/latest/user-guide/time-and-pacing/index.md) describes. ```python app = SimulationContext( sim_id="Shop", factor=0.0, # 0.0 unpaced, 1.0 real time random_seed=42, # the same draws on every run logical_start_time=datetime(2026, 10, 1, 9, 0), # what simulation time 0 is ) ``` ### Declare Resources, Stores and Containers A task holds a resource while it works. A container holds an amount and a store holds items, and tasks take from and add to both. `add_variable` registers any other live value. [Resources](https://jaehyeon.me/desflow/latest/user-guide/resources/index.md) and [Stores and Containers](https://jaehyeon.me/desflow/latest/user-guide/model-parts/stores-and-containers/index.md) describe each. ```python app.add_resource("packers", current_cap=2, max_cap=5) # 2 packers now, room for 5 app.add_container("boxes", current_cap=200, max_cap=200, level=100) # an amount app.add_store("parcels", current_cap=20, max_cap=50) # items, waiting for a courier app.add_variable("conveyor_speed", 1.5) # any other live value ``` ### Add Distributions Each service is a distribution, given its parameters by keyword. Each arrival is a distribution too, and [Start Them from Arrivals](#start-them-from-arrivals) adds it with the task it starts. A parameter out of range, or one the family does not take, raises `ValueError` here, before the run. [Arrivals and Services](https://jaehyeon.me/desflow/latest/user-guide/model-parts/arrivals-and-services/index.md) lists the twelve families. ```python app.add_service("packing", dist="triangular", low=1, mode=2, high=4) app.add_service("labelling", dist="constant", value=0.5) ``` ### Write the Tasks `@app.task` turns a function into a task: it publishes `queued`, waits for its resource and its `get`, publishes `started`, waits the service time, adds its `put`, and publishes what the function returns as the finished event. `next` names the task that follows, and the function receives `upstream`, `entity` or `item` when it declares them. [Task Flow](https://jaehyeon.me/desflow/latest/user-guide/model-parts/task-flow/index.md) covers rules and weights. ```python @app.task( service_id="packing", resource_id="packers", get={"container": "boxes", "amount": 1}, # one box, once it has a packer next="print_label", # the task that follows ) def pack_order(task_id: int): # The value of the finished event: exactly this dictionary return {"event_type": "order_packed"} @app.task(service_id="labelling", put={"store": "parcels"}) # a timed step def print_label(task_id: int, upstream): # upstream is what pack_order handed on; the payload becomes the parcel return {"event_type": "label_printed", "packed_by": upstream.task_id} @app.task(get={"store": "parcels"}) def collect(task_id: int, item): return {"event_type": "parcel_collected", "label": item["event_type"]} ``` ### Start Them from Arrivals `add_arrival` with `spawn=` is the builder form of YAML's `spawn`: each arrival starts the named task for its entity, keyed `orders-1`, `orders-2` and so on. The record's `instance` comes from the task's one counter, which `next` and other arrivals share, so no two runs of the task share an id. A `spawn` that names a task never added is refused when `run()` checks the model. ```python # An order every 2 s on average, keyed orders-1, ..., each starting pack_order app.add_arrival("orders", dist="exponential", rate=0.5, spawn="pack_order") app.add_arrival("couriers", dist="constant", value=10, spawn="collect") # every 10 s ``` `@app.arrival_loop` runs a generator of your own that waits with `context.wait_for_arrival` and starts tasks with `context.spawn`. A loop is needed only when it does more than start one task, such as choosing the task from the entity's attributes. [Tasks and Processes](https://jaehyeon.me/desflow/latest/user-guide/tasks-and-processes/tasks/#arrivals-start-tasks) shows a loop that does what `spawn=` does, written by hand. ### Arguments for the Keys of a Blueprint Every key of a [blueprint](https://jaehyeon.me/desflow/latest/user-guide/writing-a-model/blueprints/index.md) has a builder argument of the same meaning, except `simulation.log_level`. A script sets that level with `logging`, as [Log Level](https://jaehyeon.me/desflow/latest/user-guide/writing-a-model/blueprints/#log-level) shows. This script uses the ones that shape what an arrival and a task start with: ```python app = SimulationContext( sim_id="Shop", factor=0.0, random_seed=42, logical_start_time=datetime(2026, 1, 1, tzinfo=timezone.utc), ) app.add_egress(ConsoleEgress()) app.add_resource("packers", current_cap=1, max_cap=2) app.add_service("packing", dist="constant", value=20) app.add_arrival( "orders", gap="30 s", # a number, a duration, an expression or a generator first_at=5, # the first gap ends at 5 s; a time in the past arrives at once max_events=4, # stops itself after the fourth start; needs a spawn vars={"size": generator({"gen": "integer", "bounds": [1, 5]})}, # read by key key=generator({"gen": "sequence", "format": "order-{}"}), attributes={"size": generator({"gen": "var", "name": "size"})}, spawn="pack_order", ) ``` A generator is written with `generator({...})`, and a payload with `Template(...)`, both from `desflow.values`. `Template` takes `vars=` and `vars_once=` as a task's `vars` and `vars_once` do. The task side: ```python payload = Template( {"size": {"gen": "attr", "name": "size"}, "shift": {"gen": "var", "name": "shift"}}, vars={"label": {"gen": "uuid"}}, # drawn for each instance of the task vars_once={ "shift": {"gen": "one_of", "choices": ["early", "late"]} }, # for each entity ) @app.task( service_id="packing", resource_id="packers", history=100, # rows kept for a Template or an aggregate that looks this task up next="record", ) def pack_order(task_id: int): return payload @app.task() def record(task_id: int, upstream): return NO_RECORD # the task runs and publishes no finished record ``` The first order starts at 5 s, then one starts every 30 s, and the fourth is the last. The keys are `order-0` to `order-3`. `record` runs but publishes no finished record. A resource a task waits for can have its own queue order, a family of members, and a signal that wakes the task. This script holds a unit of `bench` by priority, gives up after 15 s, opens a request for one desk and cancels it, and listens for a defused signal: ```python app.add_resource("bench", current_cap=1, max_cap=1, queue="priority") # One desk for each key: desk[0] and desk[1], made when the run starts app.add_resource("desk", current_cap=1, family=True, members=2) app.add_signal("closing", once=True, defused=True) app.add_variable("closings_seen", 0) ``` ```python @app.task( # A name, or a mapping with priority, preempt and patience seize={"resource": "bench", "priority": 1, "preempt": "f", "patience": 15}, service_time=18, release="bench", # frees the oldest unit of bench the flow holds # A request for desk[1], opened as a handle, and cancelled again open={"spare": {"request": {"of": "desk", "key": 1}}}, cancel="spare", on_renege="gave_up", # the task a flow goes to after it leaves the line listen={ "signal": "closing", "on": [{"path": "Shop.variables.closings_seen", "value": 1}], }, ) def pack(task_id: int): return {"event_type": "packed"} @app.task() def gave_up(task_id: int, upstream): return {"event_type": "left", "key": upstream.key} ``` An order arrives every 10 s and packing takes 18 s, so the third order waits from 30 s, passes its patience of 15 s at 45 s, and goes to `gave_up` with a record `{'event_type': 'left', 'key': 'orders-3'}`. The other arguments follow the key of the same name: | Call | Arguments | | --------------------- | ------------------------------------------------------------------------------------------ | | `add_arrival` | `group`, `active`, `off_mode`, `initial`, and the distribution parameters. | | `add_arrival_replay` | `time`, `unit`, `fields`, `on_invalid`, `active`, `off_mode`, `attributes`, `key`, `vars`. | | `add_initial_arrival` | `initial` entities at the start, with `spawn`, `attributes`, `key`, `gap`, `vars`. | | `add_resource` | `queue`, `preempt`, `queue_limit`, `type`, `family`, `members`. | | `add_signal` | `once`, `on`, `family`, `members`, `defused`. | | `with_stats` | `level`, `interval`, `on_change`, `trace`. | | `add_readings` | `interval` and a mapping of reading names to expressions. | | `add_breakdown` | `resource`, `time_to_failure`, `repair`, `work`, `clock`. | | `add_egress` | `when`, `batch_size`, `flush_interval`, `envelope`. | A task takes the keys of a blueprint task as arguments too: - **`seize`, `release`, `open`, `cancel`, `signal`, `interrupt`, `resume`.** A name or the same mapping as the key. A request that `open` makes has a `preempted` attribute, which is true once a higher priority took the unit. - **`preempt`.** A boolean or a boolean word: `preempt="f"` is false, as in YAML. - **`on_interrupt`, `on_interrupt_next`, `on_interrupt_run`.** `on_interrupt_run` and `resume` take the same forms as the keys of those names. `on_renege`, `on_balk` and `on_fail` take no extra argument. - **`listen` and `fail_reason`.** `listen` is the mapping of the key. `fail_reason` is text, an expression or a generator. `add_signal(defused=True)` and the `on=` actions `fail`, `defused`, `priority` and `when` are the blueprint forms. - **`spawn`.** A mapping with `task`, `count` (a number, an expression or a function), `copy_attributes` and `args`. `count` as text reads the run and the names of the running process. - **`set_args`, `activate`, `deactivate`.** `set_args` writes values in the flow's own process arguments, after `set`. `activate` and `deactivate` switch on or off the arrivals the task names, in one name or a list. - **`batch`.** The batching mapping of the key. - **`history`, `Template` and `note_values`.** `history=` keeps rows for a task that a `Template` or an aggregate looks up. The builder does not scan a `Template` for the tasks it names, so `note_values("", template)` tells it to, and gives the `Template` the full gate: its `payload`, `vars` and `vars_once` are searched, and the start is dropped before the function runs. Without it, a `Template` with a `lookup` of a task with no row drops the start after the task function has returned it. By then the `queued` and `started` records have been published, the item of a `get` has been consumed, and the units and `wait` requests are given back. The builder refuses an unknown lookup target, a task `note_values` names that does not exist, and a cycle. `note_values(task, *places)` also takes generators written in your own code, but not a set or an iterator. - **`Transfer(item=)` and `Signal.processed`.** `Transfer(item=...)` is the item a store `put` adds: a constant, text or a generator, and `Signal.processed` is true once the signal has fired and its callbacks have run. A `row` generator written in a script, through `generator(spec)` or a `Template`, is read from the working directory at the call that adds it: `add_arrival`, `add_arrival_replay`, `add_initial_arrival`, `add_store`, `add_scenario`, `add_step`, `add_signal` and `task`. A missing or unusable file raises `ValueError` there, naming the generator's place and the file. A blueprint reads the same files from its own folder. A `row` gives a mapping, so a place that needs a number or text takes it only inside another generator. `with_stats(on_change=True)` also publishes a resource's readings right after each `request` and `release` call on it, and needs a level above `none`. `with_stats(trace=True)` publishes one `trace` record for each event the environment processes, to the sinks added with `add_egress(provider, when="trace")` and to no other, and `env.trace_events(False)` switches it off during a run. `add_breakdown(clock="calendar")` counts the time to failure from the start or the last repair, and `clock="busy"` counts it only while the resource holds a unit. `run(until, segments=..., steps=..., sync=...)` has the meaning of the YAML `run` keys, which [Run Length](https://jaehyeon.me/desflow/latest/user-guide/time-and-pacing/run-length/#run-in-segments) shows in the Builder tab. ### Measure the Run `with_stats` switches on the built-in statistics, published as telemetry. [Statistics](https://jaehyeon.me/desflow/latest/user-guide/results/statistics/index.md) lists the levels. ```python app.with_stats("typical", interval=30) # readings, counts, waits, every 30 s ``` ### Add a Process `add_process` is for anything that is not a task. It calls a generator with the context when the run starts. Here the process is a speed that drifts. ```python def speed_drift(context: SimulationContext, step: float): """Raises the conveyor speed a little every 10 simulation seconds.""" path = "Shop.variables.conveyor_speed" while True: yield context.env.timeout(10.0) speed = context.env.registry.get(path).value context.env.registry.update(path, speed + step) app.add_process(speed_drift, step=0.1) ``` ### Attach the Connectors `add_ingress` brings parameter changes in, and `add_egress` writes records out, each with its own batching if it needs it. [Ingress](https://jaehyeon.me/desflow/latest/user-guide/live-runs-and-connectors/ingress/index.md) and [Egress](https://jaehyeon.me/desflow/latest/user-guide/live-runs-and-connectors/egress/index.md) list the connectors. ```python app.add_ingress(LocalIngress(schedule=[(5.0, "Shop.resources.packers.current_cap", 3)])) app.add_egress(ConsoleEgress(), batch_size=100, flush_interval=1.0) app.with_batching(batch_size=1_000, flush_interval=5.0) # defaults for other sinks ``` `LocalIngress` counts its delays in wall-clock seconds, so the change to 3 packers is due 5 seconds after the run starts. This unpaced run ends in under a second, so the change never lands. At `factor=1.0`, it lands 5 seconds into the run. For a change at an exact simulation time, use a scenario step, `add_step(at, path=..., value=...)` or `add_scenario(steps)`, which [Live Parameters](https://jaehyeon.me/desflow/latest/user-guide/live-runs-and-connectors/live-parameters/#script-an-experiment) describes. A process that waits and then updates the registry, as `speed_drift` above does, also works. `compile_parameters()` returns the `SimParameter` that `run()` will register. Call it to check the registry paths before a run. A resource has three: `current_cap`, `max_cap` and `queue_limit`, which is `None` when unset. A limit changes through its path, `.resources..queue_limit`, in a scenario step, an `on:` action or a low-level `registry.update`, and not by assigning `queue_limit`, which is read-only. The new limit applies from the next request, and a smaller one removes nobody who waits. A resource with its own `PutQueue` has no `queue_limit` path: ```python paths = app.compile_parameters() # the SimParameter that run() registers ``` ### Run It ```python if __name__ == "__main__": logging.basicConfig( level=logging.INFO, format="%(levelname)s [%(asctime)s] %(message)s" ) app.run(until="2 min") ``` `app.on_change` takes callbacks that receive every parameter change of each run `start()` builds, as [Follow Every Change](https://jaehyeon.me/desflow/latest/user-guide/live-runs-and-connectors/live-parameters/#follow-every-change) shows. `ConsoleEgress` writes each batch of records in one INFO log call, one line per record, so the script switches logging on before it runs. Only the first line of a batch carries the logging format's prefix, such as the time and the level. The other lines are bare. The first events of the run: ```text [EVT] {'sim_ts': 0.6283113312939436, 'timestamp': '...', 'key': 'orders-1', 'task': 'pack_order', 'instance': 0, 'value': {'path_id': 'Shop.service.packing', 'sim_id': 'Shop', 'service': 'packing', 'status': 'queued'}} [EVT] {'sim_ts': 0.6283113312939436, 'timestamp': '...', 'key': 'orders-1', 'task': 'pack_order', 'instance': 0, 'value': {'path_id': 'Shop.service.packing', 'sim_id': 'Shop', 'service': 'packing', 'status': 'started'}} [EVT] {'sim_ts': 2.730810375595254, 'timestamp': '...', 'key': 'orders-1', 'task': 'pack_order', 'instance': 0, 'value': {'event_type': 'order_packed'}} [EVT] {'sim_ts': 2.730810375595254, 'timestamp': '...', 'key': 'orders-1', 'task': 'print_label', 'instance': 0, 'value': {'path_id': 'Shop.service.labelling', 'sim_id': 'Shop', 'service': 'labelling', 'status': 'started'}} [EVT] {'sim_ts': 3.230810375595254, 'timestamp': '...', 'key': 'orders-1', 'task': 'print_label', 'instance': 0, 'value': {'event_type': 'label_printed', 'packed_by': 0}} [EVT] {'sim_ts': 4.934338901219139, 'timestamp': '...', 'key': 'orders-2', 'task': 'pack_order', 'instance': 1, 'value': {'path_id': 'Shop.service.packing', 'sim_id': 'Shop', 'service': 'packing', 'status': 'queued'}} [EVT] {'sim_ts': 4.934338901219139, 'timestamp': '...', 'key': 'orders-2', 'task': 'pack_order', 'instance': 1, 'value': {'path_id': 'Shop.service.packing', 'sim_id': 'Shop', 'service': 'packing', 'status': 'started'}} [EVT] {'sim_ts': 5.0244486188135875, 'timestamp': '...', 'key': 'orders-3', 'task': 'pack_order', 'instance': 2, 'value': {'path_id': 'Shop.service.packing', 'sim_id': 'Shop', 'service': 'packing', 'status': 'queued'}} ``` ______________________________________________________________________ ## How It Works `run()` takes the steps a [low-level script](https://jaehyeon.me/desflow/latest/user-guide/writing-a-model/low-level-api/index.md) writes by hand, in the same order, which [What `run()` Does](https://jaehyeon.me/desflow/latest/user-guide/tasks-and-processes/tasks/#what-run-does) lists. It adds these: - **A seed for every run.** It makes `Sampler(seed=random_seed)`, and draws and logs a seed when there is none. - **Resources, stores and containers.** One for each `add_resource`, `add_store` and `add_container`, which `context.get_resource`, `get_store` and `get_container` return. `add_resource` takes a `type`, a subclass of `ResourceBase` to build the resource from ([Custom Resource Types](https://jaehyeon.me/desflow/latest/user-guide/resources/custom-resource-types/#custom-resource-types)). `add_store` and `add_container` take a `type` too, a subclass of `StoreBase` or `ContainerBase` ([Custom Store and Container Types](https://jaehyeon.me/desflow/latest/user-guide/model-parts/stores-and-containers/#custom-store-and-container-types)). A store or container with no `current_cap` and no `max_cap` has no limit. - **Tasks.** `@app.task` publishes `queued`, `started` and the finished event with the entity key, task and instance, reports each step to the statistics, takes and adds stock, and routes to the next task with a `Router`. - **Entities.** `context.wait_for_arrival` returns an `Entity` with its key and attributes. - **Names with the `sim_id`.** `context.publish(name, value)` puts the `sim_id` in front of the name. The low-level `env.publish_telemetry` uses the name as given. ______________________________________________________________________ ## Stability and Limits A mistake stops the script before the clock starts. A method raises `ValueError` when it is called with a value it cannot take: - an `environment` that is not a subclass of `DynamicRealtimeEnvironment`; - a `fire` action with `urgent` or `after` on a signal that is not `once=True` (raised at `start()`); - a negative `after`; - a distribution parameter out of range, or one its family does not take; - an unknown queue order; - a `current_cap` or `max_cap` that is not a whole number or infinity, or a `max_cap` below 1 given with no `current_cap`; - a `type` that is not a subclass of `ResourceBase`; - a negative `queue_limit`, or one on a `type` with a `PutQueue` of its own; - a task with a resource but no service, or a priority without a resource; - an unknown `on_interrupt`; - a second task with the same name; - a `spawn` with an `after` of 0 or less; - a `fire` action given both `value` and `from`; - a time that is NaN, `true` or negative where a time must not be (`factor`, `warmup`, `lag_interval`, a `patience`, a wait timeout, a segment `until`), and `factor` as text such as `"2 min"`, because it is a number; - a drain `limit` of 0, below 0 or NaN (infinity is no limit); - a batch size that is not a whole number of 1 or more, and an interval that is not above 0, in `with_batching` and `add_egress`; - a `current_cap`, `max_cap` or `queue_limit` below 0, and `true` or a fraction where a whole number is needed; - a distribution parameter that is `true`, NaN or infinity, or a negative `low` or value in a time distribution; - a rank or priority that is NaN, or text for a ranked queue or a resource priority; - a name used in two of resources, stores, containers and signals, or one that holds a dot, a space or a character that an expression reads as another, such as `µ` (a second `add_arrival` of one name replaces the first); - a `stop` on a signal family or a stop condition that reads `attr` or `payload`, an `activate` or `deactivate` of an arrival that is unknown, segment ends that do not increase, and a spawn `count` below 0. A `start()` that is refused leaves the open run as it was. `run()` then checks what each task names, before the clock or any connector starts. It raises `ValueError` for: - a resource, service, store, container, signal or task that was not added; - a priority on a resource that does not queue by priority; - a task that keeps a resource for a task that requests it in its `wait`; - a spawned task that shares an arrival's name; - a `fire` action's `from` that names both a signal and a task, or neither; - a `level.`, `users.`, `queue.`, `signal.`, `wait.` or `registry["..."]` that an expression reads but that does not exist. Two tasks that acquire resources in opposite orders load and log one WARNING, and `seize` counts as holding. The builder's limits are those of its tasks and its resources: - **Resources are fixed when the run starts.** `run()` creates every resource, store and container before the clock starts, and has no call to add one later. A process can add one through `context.env`, as [Add Resources Mid-run](https://jaehyeon.me/desflow/latest/how-to/modelling/dynamic-topology/index.md) shows. - **`advance()` needs a started run.** It raises `RuntimeError` before `start()`, after `close()` and after the run's own end, and `ValueError` for a time that is not after `now`. `step()` raises `RuntimeError` after the run's end too, and `peek()` gives infinity, so a loop of `peek()` and `step()` ends. [Run in Segments](https://jaehyeon.me/desflow/latest/user-guide/time-and-pacing/run-length/#run-in-segments) shows it. - **`strict` is left unset by default.** It is true when `factor` is above 0 or `go_live_at` is set, and false otherwise. [Strict Pacing](https://jaehyeon.me/desflow/latest/user-guide/time-and-pacing/clocks-and-pacing/#strict-pacing) gives what it does and its default in each API. - **`environment=` takes a subclass of `DynamicRealtimeEnvironment`.** The context builds it in `start()` with the same arguments it would give its own environment, so its `__init__` takes `**kwargs` and passes them on. - **A subscribe refuses a processed event.** `context.subscribe(event)` raises `RuntimeError` when the event has already happened, or when it is called outside a process. ______________________________________________________________________ The complete file, which the documentation tests run, is `docs/snippets/pages/builder.py`. [Low-level API](https://jaehyeon.me/desflow/latest/user-guide/writing-a-model/low-level-api/index.md) writes the same kind of model by hand. A blueprint makes the same builder calls from a file, as [YAML Blueprints](https://jaehyeon.me/desflow/latest/user-guide/writing-a-model/blueprints/index.md) describes. # Low-level API This page writes a simulation with SimPy and the environment directly: a packing team with a stock of boxes and a store of packed orders, every step written by hand. It builds on [SimPy and desflow](https://jaehyeon.me/desflow/latest/simpy/index.md), which describes the SimPy constructs, and on [Builder API](https://jaehyeon.me/desflow/latest/user-guide/writing-a-model/builder-api/index.md), which writes the same kind of model for you. ______________________________________________________________________ ## What It Is Use the low-level API when you need what the builder does not do: events and interactions of your own shape, such as a resource created while the run goes on in [Add Resources Mid-run](https://jaehyeon.me/desflow/latest/how-to/modelling/dynamic-topology/index.md). A builder or blueprint model can also start a low-level process with `add_process`, as [Tasks and Processes](https://jaehyeon.me/desflow/latest/user-guide/tasks-and-processes/processes/#how-it-works) shows. A low-level script takes these steps, in this order: ______________________________________________________________________ ## How to Use It ### Create the Environment ```python import logging from desflow import ( CapacityConfig, ConsoleEgress, ContainerConfig, DistributionConfig, DynamicContainer, DynamicRealtimeEnvironment, DynamicResource, DynamicStore, Sampler, SimParameter, time_to_seconds, ) ``` ```python env = DynamicRealtimeEnvironment(factor=0.0) # unpaced; 1.0 follows the wall clock ``` `factor` sets the pacing: `1.0` follows the wall clock, and `0.0` runs as fast as possible. `logical_start_time` and `go_live_at` work as [Time and Pacing](https://jaehyeon.me/desflow/latest/user-guide/time-and-pacing/index.md) describes. ### Register the Parameters ```python env.registry.register_sim_parameter( SimParameter( sim_id="Shop", # An order every 2 s on average (rate 0.5) arrival={"orders": DistributionConfig(dist="exponential", rate=0.5)}, service={"packing": DistributionConfig(dist="normal", mean=1.5, std=0.3)}, resources={"packers": CapacityConfig(current_cap=1, max_cap=3)}, containers={"boxes": ContainerConfig(current_cap=100, max_cap=100, level=100)}, stores={"finished": CapacityConfig(current_cap=50, max_cap=50)}, variables={"boxes_per_order": 1.0}, ) ) ``` One `SimParameter` holds every parameter of one simulation under its `sim_id`. Registering it gives each value a path, such as `Shop.arrival.orders.rate`, and only the registered paths exist. [Live Parameters](https://jaehyeon.me/desflow/latest/user-guide/live-runs-and-connectors/live-parameters/index.md) lists the paths. ### Attach the Connectors ```python env.setup_egress([ConsoleEgress()]) # starts the egress thread # env.setup_ingress([KafkaIngress(...)]) would start the ingress thread env.setup_stats("Shop", "basic", interval=60) # readings and counts every minute ``` `setup_egress` starts the egress thread, which writes every record the processes publish. `setup_ingress` starts the ingress thread for parameter changes from outside, and `setup_stats` switches on the built-in statistics. [Egress](https://jaehyeon.me/desflow/latest/user-guide/live-runs-and-connectors/egress/index.md) lists the arguments of `setup_egress`, including a [warm-up](https://jaehyeon.me/desflow/latest/learn/concepts/output-analysis/#one-run-starts-empty) and labels sinks. ### Create Resources, Containers and Stores ```python packers = DynamicResource(env, "Shop", "packers") # reads Shop.resources.packers.* boxes = DynamicContainer(env, "Shop", "boxes") # starts at its level, 100 finished = DynamicStore(env, "Shop", "finished") sampler = Sampler(seed=42) # a random stream per distribution, from one seed ``` Each one reads its capacity from the registry when it is created, so the parameters must be registered first. Each one also adds itself to the statistics. `Sampler(seed=42)` gives each registered distribution a random stream of its own, so a run repeats exactly, as [Arrivals and Services](https://jaehyeon.me/desflow/latest/user-guide/model-parts/arrivals-and-services/#seeding) describes. ### Write the Processes A process is a SimPy generator: it `yield`s to wait, and publishes records as it goes. This one does what `@app.task` does in the builder, with a box from stock and a store for the result. It publishes each event with the entity key, the task's name and its instance id, and reports each step to the statistics: ```python def order(env, key, task_id): """One order: queue for a packer, take a box, pack, then store the result.""" path_id = "Shop.service.packing" def publish(value): env.publish_event(key, value, task="pack_order", instance=task_id) publish( {"path_id": path_id, "sim_id": "Shop", "service": "packing", "status": "queued"} ) env.stats.task_queued("pack_order", task_id) # what @app.task reports for you with packers.request() as request: yield request count = env.registry.get("Shop.variables.boxes_per_order").value yield boxes.get(count) # waits if the stock is too low publish( { "path_id": path_id, "sim_id": "Shop", "service": "packing", "status": "started", } ) env.stats.task_started("pack_order", task_id) yield env.timeout(sampler.sample(env.registry.get_config(path_id))) yield finished.put({"order": key}) publish({"event_type": "order_packed"}) env.stats.task_finished("pack_order", task_id) env.stats.flow_finished("orders") ``` The service time is drawn once the order has a packer and a box, from the configuration the registry holds at that moment, so a change made while it waited still applies to it. The arrival loop keeps the configuration object rather than a copy of the rate. The registry changes that object in place when a new rate arrives, so the next draw uses the current rate. It gives each order its key, `orders-1`, `orders-2`: ```python def arrivals(env): gap = env.registry.get_config("Shop.arrival.orders") # the live config object task_id = 0 while True: yield env.timeout(sampler.sample(gap)) # each draw reads the current rate env.process(order(env, f"orders-{task_id + 1}", task_id)) # the entity key task_id += 1 ``` A reading of your own is a process that publishes at an interval. `publish_telemetry` uses the name exactly as given: ```python def telemetry(env): """A reading of your own, beside the built-in statistics.""" while True: env.publish_telemetry("Shop.boxes_per_packer", boxes.level / packers.capacity) yield env.timeout(10.0) ``` A process can also change the simulation itself, through the registry, as a connector or a scenario would: ```python def refill_and_rush(env): """Refills boxes every minute, and doubles arrivals after five minutes.""" while True: yield env.timeout(60.0) missing = boxes.capacity - boxes.level if missing > 0: # SimPy refuses a put of 0 yield boxes.put(missing) if env.now >= 300 and env.registry.get("Shop.arrival.orders.rate").value < 1.0: env.registry.update("Shop.arrival.orders.rate", 1.0) env.registry.update("Shop.resources.packers.current_cap", 2) ``` ### Start the Processes and Run ```python env.process(arrivals(env)) env.process(telemetry(env)) env.process(refill_and_rush(env)) ``` ```python logging.basicConfig( level=logging.INFO, format="%(levelname)s [%(asctime)s] %(message)s" ) try: env.run(until=time_to_seconds("10 min")) # until is in simulation seconds finally: env.teardown() # flushes the buffers and stops the threads ``` `ConsoleEgress` writes each record as a log line at INFO level, so logging is switched on first. `env.run` is SimPy's, so `until` is a number of simulation seconds. `time_to_seconds` converts a duration such as `"10 min"`. `teardown` in `finally` publishes the last statistics, flushes the last records and stops both threads, even when the run stops with Ctrl+C or an error. A script can run the model in segments by calling `env.run(until=...)` again, as in SimPy. `env.schedule(event, priority, delay)` is SimPy's own: `simpy.events.URGENT` puts an event before the `NORMAL` ones at its time. [Run Length](https://jaehyeon.me/desflow/latest/user-guide/time-and-pacing/run-length/#run-in-segments) covers segments, `strict`, `sync()` and `env.resume_pacing()`. An environment subclass is plain Python: `class Traced(DynamicRealtimeEnvironment)`, whose `__init__` takes `**kwargs` and passes them on, and whose `step` or `schedule` calls `super()`. Inside `run()`, `step` runs once per event, desflow's own events included. ### Low-level Forms of the Keys A script writes by hand what the keys of a blueprint do. These are the calls and attributes that match the arguments of the [Builder API](https://jaehyeon.me/desflow/latest/user-guide/writing-a-model/builder-api/#arguments-for-the-keys-of-a-blueprint): - **Generated values.** `ValueRuntime.value(spec, entity=None)` evaluates a typed generator from `desflow.values.generator`, or any value that holds one, now. Call it on the same object each time: a `sequence` counts and a `unique` choice refuses on it. A `row` generator is read from the working directory at the call, and a missing or unusable file raises `ValueError` naming the generator's place and the file. A `row` gives a mapping, so a place that needs a number or text takes it only inside another generator. - **Resources and signals.** `DynamicResourceRequest.preempted` is true once a request of a higher rank took the unit. `Signal.fire(value, urgent, after, priority)` and `Signal.fail(reason, urgent, after, priority, defused)` take a `priority`, and `fail` takes `defused`. `Signal.processed` is true once the latest firing's event has been processed. - **Transfers.** `Transfer(item=...)` is the item a store `put` adds. - **Trace.** `env.trace_events()` switches the event trace on, and `env.trace_events(False)` off. A trace record goes only to the sinks added as trace sinks. ### Read a Value, an Expression and a Trace `env.registry.get(path)` gives the registry's `DynamicValue` for a path. Its `value` is the value now, and `name` is the path: ```python env = DynamicRealtimeEnvironment(factor=0.0) env.registry.register_sim_parameter( SimParameter( sim_id="Shop", resources={"packers": CapacityConfig(current_cap=2, max_cap=5)}, ) ) packers: DynamicValue = env.registry.get("Shop.resources.packers.current_cap") print(packers.name, packers.value) ``` This prints `Shop.resources.packers.current_cap 2`. An `Expression` is parsed and checked when it is made, and `evaluate` reads its names from a `Scope`. A scope you make yourself holds only the parts you give it, here a payload and the time `t`: ```python rule = Expression("payload.total > 100 and t >= 60") scope = Scope(payload={"total": 120}, now=75.0) print(rule.evaluate(scope)) ``` This prints `True`. `read_trace` reads the arrivals of a trace, from a CSV or Parquet path or from a list of mappings, into a list of `Row` objects. Each has its `time`, its row `number` and the `fields` that become the entity's attributes: ```python rows: list[Row] = read_trace( [{"time": 0.5, "id": "a"}, {"time": 2.0, "id": "b"}], fields=["id"] ) for row in rows: print(row.number, row.time, row.fields) ``` This prints `1 0.5 {'id': 'a'}` and `2 2.0 {'id': 'b'}`. ______________________________________________________________________ ## How It Works The environment does little for you. It paces the clock, holds the registry, writes records on the egress thread and keeps the statistics that `setup_stats` switches on. Everything else is your code. [Builder API](https://jaehyeon.me/desflow/latest/user-guide/writing-a-model/builder-api/#how-it-works) lists what `SimulationContext.run()` writes for you on top of the same steps. The threads, the queues and the processes the environment starts on the SimPy thread are in [Threads and Queues](https://jaehyeon.me/desflow/latest/user-guide/how-desflow-works/#threads-and-queues). `env.step()` and `env.peek()` do not count those processes. ______________________________________________________________________ ## Stability and Limits Nothing is checked before the run as a whole. Each call checks only what it reads, when it runs: - **An unregistered path raises `KeyError`** when a resource, a process or a `registry.get` asks for it, so register the parameters before creating anything that reads them. - **A record without egress is dropped.** Until `setup_egress` runs, `publish_event` and `publish_telemetry` do nothing, without an error. - **A `Sampler()` with no seed draws nothing at random,** as [Arrivals and Services](https://jaehyeon.me/desflow/latest/user-guide/model-parts/arrivals-and-services/#how-it-works) explains, so give it a seed. - **`strict` is left unset by default.** It is true when `factor` is above 0 or `go_live_at` is set, and false otherwise. [Strict Pacing](https://jaehyeon.me/desflow/latest/user-guide/time-and-pacing/clocks-and-pacing/#strict-pacing) gives what it does in each API. - **An unhandled failure stops the run under `stop`.** `DynamicRealtimeEnvironment(on_unhandled_failure=...)` is `stop` by default, as a plain SimPy environment is. Under `stop`, a one-shot `Signal` failure that nobody waits for raises `SignalFailed`, and the run stops. Pass `"continue"` to defuse such a failure and let the run go on. A re-arming signal's failure is always defused, and `Signal.fail(reason, defused=True)` defuses one failure of a one-shot signal. A failure with an empty or 0 reason keeps that reason. An exception raised in a process stops the run under both settings. The keyword must be `stop` or `continue`. Beyond those, a process can do anything SimPy can model. ______________________________________________________________________ The complete file, which the documentation tests run, is `docs/snippets/pages/low_level.py`. [Builder API](https://jaehyeon.me/desflow/latest/user-guide/writing-a-model/builder-api/index.md) writes the same kind of model with less code. # Model Parts A model is made of a few kinds of parts. This page is the map: which block models what, and what it is called in each way of writing. Each block has a page of its own. ______________________________________________________________________ ## What It Is An **entity** is the thing that flows through a model: an order, a visitor, a support call. It enters through an arrival and does the work its task describes. While it works, it holds a resource, and it may take from or add to a store or container. Then it goes on to the next task. [What Is DES?](https://jaehyeon.me/desflow/latest/learn/what-is-des/index.md) explains discrete-event simulation, the kind of simulation these blocks build. Look at how the blocks connect: | Block | What it models | YAML | Builder | Low-level | Page | | ---------- | ----------------------------------------------------------------- | --------------------------- | ---------------------------------- | --------------------------------------------- | ------------------------------------------------------------------------------------------------------------------ | | Arrival | how often an entity enters, and what it starts with | `arrivals` | `add_arrival`, `@app.arrival_loop` | a process that waits for a drawn gap | [Arrivals and Services](https://jaehyeon.me/desflow/latest/user-guide/model-parts/arrivals-and-services/index.md) | | Service | how long a piece of work takes | `services` | `add_service` | a `DistributionConfig` drawn with a `Sampler` | [Arrivals and Services](https://jaehyeon.me/desflow/latest/user-guide/model-parts/arrivals-and-services/index.md) | | Task | what one entity does, with its events | `tasks` | `@app.task` | a SimPy process | [Tasks](https://jaehyeon.me/desflow/latest/user-guide/tasks-and-processes/tasks/index.md) | | Resource | packers, benches, lanes: whole units held by a task | `resources` | `add_resource` | `DynamicResource` | [Units and Queues](https://jaehyeon.me/desflow/latest/user-guide/resources/units-and-queues/index.md) | | Container | an amount, such as a stock of boxes, that tasks take and add | `containers` | `add_container` | `DynamicContainer` | [Stores and Containers](https://jaehyeon.me/desflow/latest/user-guide/model-parts/stores-and-containers/index.md) | | Store | items, such as parcels on a shelf, that tasks put and get | `stores` | `add_store` | `DynamicStore` | [Stores and Containers](https://jaehyeon.me/desflow/latest/user-guide/model-parts/stores-and-containers/index.md) | | Task flow | the task that follows a finished one, and what the entity carries | `next`, `attributes`, `set` | `next=`, `attributes=`, `set=` | `Router`, `Entity` | [Task Flow](https://jaehyeon.me/desflow/latest/user-guide/model-parts/task-flow/index.md) | | Process | anything else that runs over time: a break, a drift, a schedule | `processes` | `add_process` | `env.process` | [Processes](https://jaehyeon.me/desflow/latest/user-guide/tasks-and-processes/processes/index.md) | | Statistics | what the run measures about itself | `stats` | `with_stats` | `env.setup_stats`, `env.stats` | [Statistics](https://jaehyeon.me/desflow/latest/user-guide/results/statistics/index.md) | | Variable | any other live value, such as a speed | `variables` | `add_variable` | `SimParameter(variables=...)` | [Live Parameters](https://jaehyeon.me/desflow/latest/user-guide/live-runs-and-connectors/live-parameters/index.md) | The [shop tutorial](https://jaehyeon.me/desflow/latest/learn/first-model/first-simulation/index.md), in the Learn section, puts them together one at a time, in a small shop. ______________________________________________________________________ ## How to Use It A model declares its blocks, and its tasks use them by name. A task names its service and its resource, and an arrival names the task it starts. The table above gives each block's YAML key, builder call and low-level class. [Writing a Model](https://jaehyeon.me/desflow/latest/user-guide/writing-a-model/index.md) shows a whole model in each form. [Input Fitting](https://jaehyeon.me/desflow/latest/user-guide/model-parts/input-fitting/index.md) fits a service or an arrival to measured times, and writes the settings in a form a model loads. ______________________________________________________________________ ## How It Works When the run starts, `run()` builds the environment, registers every block's parameters in the registry, builds the resources, stores and containers, and starts the arrivals and processes. [What run() Does](https://jaehyeon.me/desflow/latest/user-guide/tasks-and-processes/tasks/#what-run-does) lists the steps in order. From then on, each block reads its live values from the registry: a distribution reads its parameters at each draw, and a resource follows its capacity path. # Arrivals and Services Two building blocks set the timing of every simulation. An **arrival** decides how often a new entity enters the model: an order, a visitor, a support call. A **service** decides how long a piece of work takes: packing an order, answering a call. Both are distributions of time, and each time one is needed, a value is drawn from the distribution with its current parameters. ______________________________________________________________________ ## What It Is | Block | Answers | Used by | Example | | ------- | -------------------------------------- | -------------------------------------------------- | ---------------------------------- | | Arrival | How long until the next entity? | the arrival loop, which starts a task for each one | an order every 2 s on average | | Service | How long does this piece of work take? | a task, while it holds its resource | 3 s of packing, give or take 0.5 s | An arrival draws each gap afresh from its distribution, so the gaps differ and entities arrive at uneven times. Look at the first five orders of the shop in [First Simulation](https://jaehyeon.me/desflow/latest/learn/first-model/first-simulation/index.md): ______________________________________________________________________ ## How to Use It Every distribution is a family, `dist`, and the parameters that family takes. There are twelve families: ten of times, and `poisson` and `geometric` for counts. A parameter outside its range, a missing one, or one the family does not take is refused when the model is built, with the YAML line when it comes from a blueprint. [Reference, Distributions](https://jaehyeon.me/desflow/latest/reference/distributions/index.md) lists every family with its parameters, rules, mean and variance. On this page, the table below names each family, the list under it gives each family's rules, and one example shows the form. | Family | Use it for | Parameters | | -------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------ | ------------------------------------------------- | | [`exponential`](https://jaehyeon.me/desflow/latest/reference/distributions/#exponential) | Gaps between arrivals that happen independently of each other: orders, calls, visits. Many short gaps and a few long ones, with mean `1 / rate`. | `rate`, or `mean` in its place | | [`normal`](https://jaehyeon.me/desflow/latest/reference/distributions/#normal) | Work with a typical time and a small, symmetric spread. | `mean`, `std` | | [`truncated_normal`](https://jaehyeon.me/desflow/latest/reference/distributions/#truncated_normal) | Work with a typical time and a hard minimum. | `mean`, `std`, `low` | | [`lognormal`](https://jaehyeon.me/desflow/latest/reference/distributions/#lognormal) | Times that are never negative and now and then much longer: repairs, support calls. | `mean`, `std` | | [`constant`](https://jaehyeon.me/desflow/latest/reference/distributions/#constant) | Fixed times: a conveyor, a setup, a step that takes no time. | `value` | | [`uniform`](https://jaehyeon.me/desflow/latest/reference/distributions/#uniform) | Any time in a range, all equally likely, when only the range is known. | `low`, `high` | | [`triangular`](https://jaehyeon.me/desflow/latest/reference/distributions/#triangular) | An expert's estimate: the shortest, the most likely and the longest time. | `low`, `mode`, `high` | | [`gamma`](https://jaehyeon.me/desflow/latest/reference/distributions/#gamma) | Times less variable than exponential. A whole-number shape is the Erlang distribution: that many exponential steps in a row. | `shape`, `scale` | | [`weibull`](https://jaehyeon.me/desflow/latest/reference/distributions/#weibull) | Time to failure: a shape below 1 fails early, a shape above 1 wears out. | `shape`, `scale` | | [`empirical`](https://jaehyeon.me/desflow/latest/reference/distributions/#empirical) | Times taken from real data, when no family fits. | `values` with `weights`, or `edges` with `counts` | | [`poisson`](https://jaehyeon.me/desflow/latest/reference/distributions/#poisson) | A count of events in a period, such as the orders in a minute: whole numbers from 0. | `mean` | | [`geometric`](https://jaehyeon.me/desflow/latest/reference/distributions/#geometric) | The number of tries up to and including the first success: whole numbers from 1. | `p` | The rules for each family's parameters: - `exponential`: `rate` above 0, in events per second: 0.5 is one every 2 seconds on average, 2.0 is two a second. `rate` is the one parameter that is not a time, so it takes no duration. In its place, `mean` gives the average gap, above 0, as seconds or a duration: `mean: 2` is `rate: 0.5`. Both, or neither, is refused. - `normal`: `mean`, and `std` 0 or more (0 when left out). A `std` of 0 gives the mean every time. A draw can be negative, and a draw below 0 is raised to 0. In a wide normal, these raised draws raise the mean, so use `truncated_normal` instead. - `truncated_normal`: `mean`, `std` 0 or more, and `low`, 0 when left out. With `std` 0, `mean` must be at least `low`. A draw below `low` is thrown away and drawn again, so no draws pile up at the limit. The mean is therefore the truncated distribution's own: 1.29 seconds for `mean: 1, std: 1, low: 0`. The higher `low` is above the mean, the fewer plain draws are kept. So when `low` is more than half a standard deviation above the mean, `truncated_normal` draws from an exponential proposal instead (Robert, 1995), which stays exact and fast for any `low`. - `lognormal`: `mean` above 0 and `std` 0 or more (0 when left out). Both describe the times you get, not the underlying normal. desflow converts them. - `constant`: `value` 0 or more. It uses no random number at all. A constant of 0 takes no time. - `uniform`: `low` and `high`, with `low < high`. The mean is halfway between them. - `triangular`: `low`, `mode` and `high`, all required, with `low <= mode <= high` and `low < high`. The mean is (low + mode + high) ÷ 3. - `gamma`: `shape` and `scale`, both above 0. The mean is shape × scale and the variance shape × scale². From a mean and a standard deviation: shape = (mean ÷ std)² and scale = std² ÷ mean, so a mean of 1.5 seconds with a std of 0.5 is shape 9 and scale 0.1667. - `weibull`: `shape` and `scale`, both above 0. The mean is scale × gamma(1 + 1 ÷ shape), where gamma is the gamma function. - `empirical`: either `values`, each equally likely unless the optional `weights` give one weight per value; or a histogram of `edges` and `counts`, with one count per bin. A histogram draw picks a bin in proportion to its count, then any time inside the bin, all equally likely. Weights and counts are 0 or more and add up to more than 0, and edges increase. The lists are taken when the model is loaded, so an `empirical` distribution has no registry path and does not change while the run goes on. - `poisson`: `mean` 0 or more. Every draw is a whole number from 0, and the mean and the variance are both `mean`. - `geometric`: `p` above 0 and at most 1. Every draw is a whole number from 1, with mean 1 ÷ `p`. `poisson` and `geometric` give counts, not times. Use them where a count is read, such as the `group` and `max_events` of an arrival in [Start Entities](#start-entities). A service or a gap that draws from them takes the count as seconds. `desflow dist` lists the families, and `desflow dist ` prints one family's parameters and rules. With `--mean` and `--std` it converts them to the family's parameters, so the gamma above needs no arithmetic. For an `exponential`, `--mean` alone gives the rate. `--p` sets the `p` of a `geometric`: ```bash desflow dist gamma --mean 1.5 --std 0.5 ``` ```text parameters: shape 9, scale 0.166667 YAML: {dist: gamma, shape: 9, scale: 0.166667} Python: dist="gamma", shape=9, scale=0.166667 ``` The last two lines are the service in a blueprint and in the builder. [Command Line](https://jaehyeon.me/desflow/latest/cli/#convert-parameters) shows the other conversions. Three of these families in a blueprint: a labelling time of at least 0.2 seconds, a station that fails more often as it wears, a histogram of measured packing times with three bins, and a scanning time of 0.5 seconds four times in five and 2 seconds otherwise: ```yaml # under services: a hard minimum, a time to failure, a histogram of data, and # weighted values labelling: {dist: truncated_normal, mean: 1 s, std: 1 s, low: 0.2 s} station_failure: {dist: weibull, shape: 1.5, scale: 10 min} measured_packing: {dist: empirical, edges: [1 s, 2 s, 3 s, 4 s], counts: [5, 3, 2]} scanning: {dist: empirical, values: [0.5 s, 2 s], weights: [4, 1]} ``` ```python # A hard minimum, a time to failure, a histogram of data, and weighted values app.add_service("labelling", dist="truncated_normal", mean=1.0, std=1.0, low=0.2) app.add_service("station_failure", dist="weibull", shape=1.5, scale=600) app.add_service( "measured_packing", dist="empirical", edges=[1, 2, 3, 4], counts=[5, 3, 2] ) app.add_service("scanning", dist="empirical", values=[0.5, 2], weights=[4, 1]) ``` Each is a `DistributionConfig` with the same parameters in seconds, such as `DistributionConfig(dist="weibull", shape=1.5, scale=600)`. An arrival or a service takes the same form for every family: `dist`, and the parameters in that family's row of the table. An exponential arrival, in the three ways to write it: ```yaml # under arrivals: an order every 2 seconds on average orders: {dist: exponential, rate: 0.5, spawn: pack} ``` ```python # An order every 2 s on average, each starting the task pack app.add_arrival("orders", dist="exponential", rate=0.5, spawn="pack") ``` ```python gap = DistributionConfig(dist="exponential", rate=0.5) # an order every 2 s on average ``` An exponential also takes `mean`, the average gap, in place of `rate`, so a gap of 6 minutes needs no arithmetic. desflow keeps `rate`, 1 ÷ 360, so its draws are those of the equal rate and its registry path is still `.rate`: ```yaml # under arrivals: a phone order every 6 minutes on average, given as the mean gap phone_orders: {dist: exponential, mean: 6 min, spawn: pack} ``` ```python # A phone order every 6 min (360 s) on average, given as the mean gap app.add_arrival("phone_orders", dist="exponential", mean=360, spawn="pack") ``` ```python # A phone order every 6 min (360 s) on average: the config keeps rate, 1 / 360 phone_gap = DistributionConfig(dist="exponential", mean=360) assert phone_gap.rate == 1 / 360 and phone_gap.mean is None ``` An arrival draws its gap from data in the same way. Here a batch arrives 1 second after the last one three times in four, and 5 seconds after it otherwise: ```yaml # under arrivals: a gap of 1 second three times in four, and 5 seconds otherwise batches: {dist: empirical, values: [1 s, 5 s], weights: [3, 1], spawn: pack} ``` ```python # A gap of 1 s three times in four, and 5 s otherwise app.add_arrival( "batches", dist="empirical", values=[1, 5], weights=[3, 1], spawn="pack" ) ``` `DistributionConfig(dist="empirical", values=[1, 5], weights=[3, 1])` is the gap. ### Durations In a blueprint, every time-valued parameter takes a duration as well as a number of seconds: `mean` (an exponential's too), `std`, `low`, `mode`, `high`, `scale` and `value`, and the `values` and `edges` of an `empirical`. A plain number is seconds, and so is text that is only a number, such as `'1e-3'` or `'5'`. `rate` stays a number per second. ```yaml # under services: every time-valued parameter takes a duration support_call: {dist: lognormal, mean: 5 min, std: 3 min} ``` The builder takes seconds: `app.add_service("support_call", dist="lognormal", mean=300, std=180)`. The low-level API takes seconds: `DistributionConfig(dist="lognormal", mean=300, std=180)`. ### Seeding A seed makes every draw the same on every run: ```yaml # The same draws on every run; leave it out to draw a seed and log it random_seed: 42 ``` `desflow run arrivals_services.yaml --seed 7` overrides it without editing the file. ```python # The same draws on every run; leave it out to draw a seed and log it app = SimulationContext(sim_id="Shop", factor=0.0, random_seed=42) ``` ```python sampler = Sampler(seed=42) # the same draws on every run ``` In the low-level API you draw yourself, from the current values: ```python seconds = sampler.sample(packing) # one draw, in seconds, from the current values ``` A run without a seed draws one and logs it, so it can be repeated: `desflow run` logs the command with `--seed`, and a builder run logs the value to pass as `random_seed`: ```text No random_seed was given, so this run uses 3166812249. Pass random_seed=3166812249 to repeat it. ``` A low-level `Sampler()` with no seed draws nothing at random, as [How It Works](#how-it-works) explains. [Randomness and Seeds](https://jaehyeon.me/desflow/latest/learn/first-model/randomness-and-seeds/index.md) shows seeds in use. ### Replay An arrival can take its times from recorded rows instead of a distribution. Each row of a CSV or Parquet file, or of a list of dicts, becomes one entity at the row's time. The fields named in `fields` become the entity's attributes. Here each row of `local_replay_orders.csv` is an order, at its time in seconds from the start of the run: ```yaml arrivals: orders: replay: # A CSV or Parquet file, relative to this blueprint path: ../local_replay_orders.csv time: time unit: s fields: [order_id, items] spawn: pack ``` ```python # A CSV or Parquet file, or a list of dicts .add_arrival_replay( "orders", TRACE, time="time", unit="s", fields=["order_id", "items"] ) ``` `add_arrival_replay` takes `spawn=` as `add_arrival` does, which starts the named task for each row. This example writes an `@app.arrival_loop` of its own instead, where `wait_for_arrival("orders")` waits for the next row. ```python def replay(env, sampler, packers): """Starts one order at each row's time, carrying the row's fields.""" rows = read_trace(TRACE, time="time", unit="s", fields=["order_id", "items"]) number = 0 # Rows with one time start in one step, as the blueprint starts them for time, same_time in itertools.groupby(rows, key=lambda row: row.time): yield env.timeout(time - env.now) for row in same_time: number += 1 key = f"orders-{number}" env.process(pack(env, sampler, packers, key, number - 1, row.fields)) ``` `read_trace` reads and checks the rows, and returns each with its simulation `time`, row `number` and `fields`. `unit` is `ms`, `s`, `min` or `h` from the start of the run, or `timestamp` for a date and time, placed on the run's clock from `logical_start_time`. The rows must be in time order, and the arrival follows these rules: - Rows at equal times arrive at that time, in the order of the file. - A row before the start stops the run, and rows at or after `until` never arrive. - A row without a valid time stops the run, unless `on_invalid` is `skip`, which leaves it out with a warning. - After the last row, the arrival stops and logs one INFO line. A CSV field is a number only when it is a CSV number: `1_0`, `nan` and `0x1` stay text, and as a time they are refused. A CSV file may start with a byte order mark. A row with more or fewer values than the header, and a header that names a column twice, are refused with the row or the column named. A Parquet file needs the `parquet` extra. A replayed arrival has no registry path. [Local Replay](https://jaehyeon.me/desflow/latest/learn/inputs/local-replay/index.md) compares a recorded morning with a model of it. ### Start Entities An arrival starts a new entity after each gap. These keys change when it starts, how many it starts and what each carries. Each is a blueprint key, and the builder's `add_arrival` takes the same names, apart from `count`, `keys` and `stagger`: - `gap` replaces `dist` when the gap is not a distribution: a number of seconds, a duration, an expression or a generator, read at the start of each gap, so it can read `registry[...]`, `level.` and `t`. An arrival takes exactly one of `dist`, `replay` and `gap`, and a boolean is refused in `gap` and `stagger`. - `first_at` is the simulation time of the first arrival, in place of a first gap. A time already past arrives at once. - `max_events` is how many times the arrival starts its task in all, read when the source starts. The last start draws no further gap. - `group` is how many entities one arrival starts, read once at each arrival, after the gap. A group of 0 or below starts nobody, draws no attributes and takes no key number, and the next gap still runs. It is not used with `count`, `keys` or `replay`. - `count` makes that many entities, each with a loop of its own that starts the task after each gap, and `stagger` is the time between the starts of two of them. `keys` lists the keys instead and gives the number, so it needs no `count`. `keys` may also be a mapping of each key to its own attributes, as the example after the tabs shows. - `key` is read once for each entity, for its key, and `vars` are named values read once for each entity before its attributes and key, which read them as bare names. The order at a start is `vars`, `attributes`, `key`. A start whose key belongs to a running entity of the arrival is skipped with a warning and counts as one. A constant `key` with a `count` above 1 is refused when the blueprint loads, because every entity would take the same key. - `initial` creates that many entities when the run is built, with the arrival's keys, before any gap passes. An arrival with `initial` alone needs no `dist`, `replay` or `gap`. - `active: false` starts a source off. The `activate` and `deactivate` of a task, an `on:` entry or a scenario step turn a source on and off, and each must name an arrival that has a `spawn`. Under `off_mode: drop`, the default, an arrival that falls while the source is off is lost and takes no key number. Under `restart`, the pending arrival is dropped when the source goes off, and `activate` starts a whole new gap. A second `add_arrival` of one name replaces the first entirely. `count`, `keys`, `max_events` and `stagger` need `spawn`, and `stagger` needs `count` or `keys`. `count`, `keys`, `first_at` and `stagger` do not apply to a replay. Every place here reads the run only: `attr`, `payload`, `item`, `wait`, `process` and a bare name are refused, and a `level`, a `signal`, a resource, a store and a registry name must exist. ```yaml arrivals: # A fixed gap, a first order at 5 s, and a number of orders drawn once: 4 on average orders: gap: 10 s first_at: 5 max_events: {gen: sample, dist: geometric, p: 0.25} # A var is drawn once for each order, and the attributes and the key read it vars: lane: {gen: integer, bounds: [1, 3]} attributes: lane: {gen: expr, expr: lane} spawn: pack # A party of orders at a time: its size is drawn at each arrival, and 0 starts nobody parties: dist: exponential rate: 0.05 group: {gen: sample, dist: poisson, mean: 2} spawn: pack # Three scanners, each a loop of its own, starting 2 s apart, with their own keys scanners: dist: constant value: 20 s count: 3 stagger: 2 s key: {gen: sequence, format: "scanner-{}"} spawn: scan # A source that starts off, and starts a whole new gap when it is turned on rush: {dist: exponential, rate: 0.5, active: false, off_mode: restart, spawn: pack} # One start at 60 s bell: {gap: 1 s, first_at: 60, max_events: 1, spawn: open_rush} # One start at 80 s lull: {gap: 1 s, first_at: 80, max_events: 1, spawn: close_rush} # Two orders that exist when the run starts regulars: {initial: 2, spawn: pack} # A gap of whole seconds, 4 on average walkins: {dist: geometric, p: 0.25, spawn: pack} ``` A service takes the same families. The count a `geometric` service draws is read as seconds: ```yaml services: packing: {dist: constant, value: 1.5 s} # Whole seconds with a fixed chance of 0.5 of ending at each: 2 s on average checking: {dist: geometric, p: 0.5} ``` ```yaml open_rush: payload: {event_type: rush_opened} # Turns the source of rush on as the task finishes activate: rush close_rush: payload: {event_type: rush_closed} # Turns the source of rush off again deactivate: rush ``` ```python # A fixed gap, a first order at 5 s, and a number of orders drawn once: 4 on average app.add_arrival( "orders", gap="10 s", first_at=5, max_events=generator({"gen": "sample", "dist": "geometric", "p": 0.25}), # A var is drawn once for each order, and the attributes and the key read it vars={"lane": generator({"gen": "integer", "bounds": [1, 3]})}, attributes={"lane": generator({"gen": "expr", "expr": "lane"})}, spawn="pack", ) # A party of orders at a time: its size is drawn at each arrival, and 0 starts nobody app.add_arrival( "parties", dist="exponential", rate=0.05, group=generator({"gen": "sample", "dist": "poisson", "mean": 2}), spawn="pack", ) # A source that starts off, and starts a whole new gap when it is turned on app.add_arrival( "rush", dist="exponential", rate=0.5, active=False, off_mode="restart", spawn="pack", ) # One start at 60 s app.add_arrival("bell", gap="1 s", first_at=60, max_events=1, spawn="open_rush") # One start at 80 s app.add_arrival("lull", gap="1 s", first_at=80, max_events=1, spawn="close_rush") # Two orders that exist when the run starts, then one every 50 s: the builder always # takes a dist or a gap app.add_arrival("regulars", dist="constant", value=50, initial=2, spawn="pack") # A gap of whole seconds, 4 on average app.add_arrival("walkins", dist="geometric", p=0.25, spawn="pack") ``` ```python # Turns the source of rush on as the task finishes @app.task(activate="rush") def open_rush(task_id): return {"event_type": "rush_opened"} # Turns the source of rush off again @app.task(deactivate="rush") def close_rush(task_id): return {"event_type": "rush_closed"} ``` The builder's `add_arrival` has no `count`, `keys` or `stagger`. It always takes a `dist` or a `gap`, so the `regulars` above also arrive every 50 seconds. An `@app.arrival_loop` starts entities itself: it waits with `context.wait_for_arrival("orders")`, which reads `gap`, `first_at`, `key` and `vars` as the page above describes, and starts a task for each entity. Entities that differ only in some attributes can be one arrival. Give `keys` as a mapping of each key to the attributes that differ, fixed values or generators. The rules: - Each entity starts with the arrival's `attributes`, and its key's values are merged over them, so a key's value wins. - A key that gives nothing (`kiosk:` or `kiosk: {}`) takes the arrival's attributes alone. - A key's generator draws from a sequence of its own, named by its place in the file, such as `arrivals.stores.keys.airport.footfall`, so adding a key does not change the draws of another. - The arrival's generators keep the one sequence that all its entities share, as with a list of keys, and so does the gap. - A `gen: attr` reads the attributes in the order they are merged: the arrival's first, then the key's new names. - Only a blueprint takes this form. ```yaml # Attributes for each key: three stores share one arrival, and each key gives only # the attributes that differ from the arrival's. # # Run it with: desflow run docs/snippets/yaml/keyed_attributes.yaml simulation: {sim_id: Shop, factor: 0, random_seed: 7} egress: - {type: Console} arrivals: stores: dist: constant value: 1 hour max_events: 2 spawn: report_sales # What every store starts with, unless its key gives another value attributes: {city: Sydney, staff: 4} keys: north: {city: Newcastle, footfall: 120} central: {staff: 9, footfall: 300} # Drawn once for the store, from a sequence of its own airport: footfall: {gen: integer, bounds: [200, 400]} tasks: report_sales: payload: store: {gen: entity} city: {gen: attr, name: city} staff: {gen: attr, name: staff} footfall: {gen: attr, name: footfall} run: {until: 3 hours} ``` The builder's `add_arrival` has no `keys`, so write this arrival in a blueprint, as the YAML tab shows, or add one arrival for each key. A low-level model gives its entities their attributes in its own `@app.arrival_loop`, as [Start Entities](#start-entities) describes, so it has no `keys`. The highlighted lines give every store a city and a staff count, and each key the values that differ from them. Each store keeps its attributes between its starts, so the airport's footfall is drawn once: ```text [EVT] {'sim_ts': 3600.0, 'timestamp': '...', 'key': 'north', 'task': 'report_sales', 'instance': 0, 'value': {'store': 'north', 'city': 'Newcastle', 'staff': 4, 'footfall': 120}} [EVT] {'sim_ts': 3600.0, 'timestamp': '...', 'key': 'central', 'task': 'report_sales', 'instance': 1, 'value': {'store': 'central', 'city': 'Sydney', 'staff': 9, 'footfall': 300}} [EVT] {'sim_ts': 3600.0, 'timestamp': '...', 'key': 'airport', 'task': 'report_sales', 'instance': 2, 'value': {'store': 'airport', 'city': 'Sydney', 'staff': 4, 'footfall': 398}} [EVT] {'sim_ts': 7200.0, 'timestamp': '...', 'key': 'north', 'task': 'report_sales', 'instance': 3, 'value': {'store': 'north', 'city': 'Newcastle', 'staff': 4, 'footfall': 120}} [EVT] {'sim_ts': 7200.0, 'timestamp': '...', 'key': 'central', 'task': 'report_sales', 'instance': 4, 'value': {'store': 'central', 'city': 'Sydney', 'staff': 9, 'footfall': 300}} [EVT] {'sim_ts': 7200.0, 'timestamp': '...', 'key': 'airport', 'task': 'report_sales', 'instance': 5, 'value': {'store': 'airport', 'city': 'Sydney', 'staff': 4, 'footfall': 398}} ``` ______________________________________________________________________ ## How It Works **One registry of distributions.** Every family is declared once, in `desflow.models.distributions.DISTRIBUTIONS`, with its parameters, its range rules, how to draw from it, its mean and variance, and what it gives with no random generator. The YAML models, the builder, `DistributionConfig`, the `Sampler` and the registry's live paths all read it, so they accept the same families and parameters. These are 200,000 draws from each of the ten families of times: **A draw reads the live configuration.** A `DistributionConfig` holds the family and its parameters. `Sampler.sample(config)` reads the parameters at the moment it is called, so a change made while the run goes on applies from the next draw. A task draws its service time once it has its resource and has published `started`. The arrival loop draws the next gap when it starts waiting. A draw below 0 is raised to 0, so a time is never negative. **One random stream per distribution.** A seeded `Sampler` makes one generator for each name: NumPy's `SeedSequence(seed, spawn_key=(the SHA-256 hash of the name, as eight 32-bit numbers))`. When the registry registers a distribution, it names it by its path without the sim id, such as `arrival.orders` or `service.packing`, and every draw from that distribution comes from that stream. Probability routing draws from `route.` in the same way, as [Task Flow](https://jaehyeon.me/desflow/latest/user-guide/model-parts/task-flow/index.md) describes. Each stream depends only on the seed and the distribution's name. Adding a distribution therefore leaves every other one's draws unchanged. The name leaves out the sim id, so renaming the simulation does not change them either: In the low-level API, a `DistributionConfig` that was never registered draws from the `Sampler`'s main generator instead. Your own code can take a stream of its own with `sampler.generator("")`: A blueprint and a builder model register every distribution, so each draws from its own stream. Code of your own takes a stream from `context.sampler.generator("")` once the run is built. A blueprint and a builder model register every distribution, so each draws from its own stream. Code of your own takes a stream from `context.sampler.generator("")` once the run is built. ```python # Each registered distribution draws from the stream named by its path without # the sim id; register the parameters, and sample() picks the stream registry = SimulationRegistry(simpy.Environment()) registry.register_sim_parameter(SimParameter(sim_id="Shop", arrival={"orders": gap})) assert gap.stream == "arrival.orders" stream = Sampler(seed=42).generator("arrival.orders") # the same seed, the same name assert stream is not None and sampler.sample(gap) == stream.exponential(2.0) ``` `Sampler(rng=np.random.default_rng(42))` draws the same numbers as `Sampler(seed=42)`, because the streams come from the generator's seed. **No random generator.** A `Sampler()` with neither a seed nor a generator draws nothing at random: every sample is the distribution's mean, or a constant's value. A run then uses the mean of every input and gives the same output each time, which suits a test. That output is not the model's average result: [variation lengthens waits](https://jaehyeon.me/desflow/latest/learn/concepts/queueing-basics/#variation-lengthens-waits), so a run on mean inputs gives shorter waits than random runs give on average. A `truncated_normal` gives its `mean` or its `low`, whichever is higher. A blueprint and a builder model always have a random generator: the `random_seed`, or a seed drawn and logged at the start. Draws at the mean are for a low-level test. A blueprint and a builder model always have a random generator: the `random_seed`, or a seed drawn and logged at the start. Draws at the mean are for a low-level test. ```python fixed = Sampler() # no random generator: every draw is the mean, or the value assert fixed.sample(packing) == 3.0 and fixed.sample(gap) == 2.0 assert fixed.sample(checking) == 1.5 # shape × scale ``` **SimPy and desflow.** SimPy has no distributions: a SimPy model draws its own times, usually with `random.expovariate(0.5)` for a gap of 2 seconds on average, and writes `yield env.timeout(...)` with the result. Nothing checks the parameters, a negative draw makes `timeout` raise, and the parameters are ordinary variables. desflow names each distribution and its parameters once, checks them, keeps them in the registry, and gives each a stream of its own. [SimPy and desflow](https://jaehyeon.me/desflow/latest/simpy/index.md) compares the two. ______________________________________________________________________ ## Under Live Changes Each scalar parameter a family takes has a path in the registry: `.arrival..rate` for an exponential arrival, given a `rate` or a `mean`, `.service..mean` and `.std` for a normal service, `.low`, `.mode` and `.high` for a triangular, `.shape` and `.scale` for a gamma or weibull, `.value` for a constant. A scenario, an ingress message or a process changes it while the run goes on, as [Live Parameters](https://jaehyeon.me/desflow/latest/user-guide/live-runs-and-connectors/live-parameters/index.md) explains: - The next draw uses the new value. An order already being packed keeps the time it drew, and the arrival already being waited for keeps its gap. - An update is checked on a copy of the configuration, by the same rules as at build. A value outside the range is refused with an error log line, and the old value stays: A scenario step or an ingress message with an out-of-range value is refused in the same way, with the same error log line. A scenario step or an ingress message with an out-of-range value is refused in the same way, with the same error log line. ```python packing_path = "Shop.service.packing.std" registry.register_sim_parameter( SimParameter(sim_id="Shop", service={"packing": packing}) ) registry.update(packing_path, -1.0) # refused with an error log line assert registry.get(packing_path).value == 0.5 # the old value stays ``` ```text Invalid value for 'Shop.service.packing.std': normal std must be 0 or more, got -1.0. Update ignored. ``` - The family is fixed when the model is built. There is no path that turns a `normal` into an `exponential`. An update to a parameter the family does not have, such as `.rate` on a normal, is refused as an unknown path, with a warning. - An `empirical` distribution has no paths: its lists are taken at load. ______________________________________________________________________ ## Stability and Limits - **Refused at build.** The same checks refuse a bad distribution when the model is built. A parameter that is NaN or infinity is refused with its name, at load and on a live update. `true` is refused at load, and a live update stores it as 1, as [Live Parameters](https://jaehyeon.me/desflow/latest/user-guide/live-runs-and-connectors/live-parameters/index.md) says. A negative `low` or `value` in a distribution of times (`uniform`, `triangular`, `truncated_normal` and `empirical`) is refused. So is a parameter whose draw would overflow: a `weibull` `shape`, a `lognormal` `mean` or a `poisson` `mean`. These three are an out-of-range `std`, a parameter `normal` does not take, and a `mode` above `high`: `desflow run` and `SimulationContext.from_yaml` refuse the same parameters, with the file, the line and the same message: `shop.yaml:3: services.packing: Value error, normal std must be 0 or more, got -1.0`. `app.add_service` and `app.add_arrival` raise the same `ValueError`, such as `normal std must be 0 or more, got -1.0`. ```python refused: List[Dict[str, Any]] = [ {"dist": "normal", "mean": 3.0, "std": -1.0}, # out of range {"dist": "normal", "mean": 3.0, "rate": 2.0}, # a parameter normal does not take {"dist": "triangular", "low": 1.0, "mode": 3.0, "high": 2.0}, # mode above high ] for parameters in refused: try: DistributionConfig(**parameters) except ValueError as error: print(error) ``` ```text normal std must be 0 or more, got -1.0 normal does not take rate; it takes mean, std triangular needs low <= mode <= high, got low 1.0, mode 3.0, high 2.0 ``` - **A wide `normal`.** When `std` is half of `mean`, 2.3% of draws fall below 0 and are raised to the floor. When `std` equals `mean`, 15.9% are. The raised draws push the average time up: the 200,000 draws of the normal panel in the chart above, with mean 1 and std 1, average 1.08, not 1. Use `truncated_normal`. - **A gap of 0.** A constant gap of 0 starts entities at one instant without end, so the run never ends and `until` does not stop it, as in SimPy. A service of 0 takes no time and does not stop the run. - **Rate against mean.** An exponential's `rate` is per second, not a mean gap: an order every 30 seconds is `rate: 0.0333` or `mean: 30`, not `rate: 30`. - **A seed and the timestamps.** A seed fixes the draws and so the simulation times, but each record's `timestamp` also depends on when the run started, unless `logical_start_time` is set, as [Time and Pacing](https://jaehyeon.me/desflow/latest/user-guide/time-and-pacing/index.md) explains. - **Spread lengthens queues.** Two models with the same mean times but a different spread have different queues: more spread means longer waits, as [Queues and Capacity](https://jaehyeon.me/desflow/latest/learn/first-model/queues-and-capacity/index.md) and [Choosing Inputs](https://jaehyeon.me/desflow/latest/learn/inputs/choosing-inputs/index.md) measure. ______________________________________________________________________ ## Example: Local Replay The `local-replay` example has one packer and the 40 orders of a recorded morning, which it replays from a CSV file at their times. The last order arrives at 73 seconds. It needs no Docker service and ends on its own after 120 simulation seconds. The tutorial page [Local Replay](https://jaehyeon.me/desflow/latest/learn/inputs/local-replay/index.md) teaches these features step by step. **Quick Start** `desflow examples get` downloads the example at the release you install, into a folder of its own. Pick uv or pip: ```bash # 1. Install uv tool install desflow # 2. Download the example desflow examples get local-replay --api yaml cd local-replay/yaml # 3. Run it desflow run local_replay.yaml ``` ```bash # 1. Install pip install desflow # 2. Download the example desflow examples get local-replay --api yaml cd local-replay/yaml # 3. Run it desflow run local_replay.yaml ``` **Quick Start** `desflow examples get` downloads the example at the release you install, into a folder of its own. Pick uv or pip: ```bash # 1. Install uv tool install desflow # 2. Download the example desflow examples get local-replay --api builder cd local-replay/builder # 3. Run it uv run --no-project --with desflow local_replay_example.py ``` ```bash # 1. Install pip install desflow # 2. Download the example desflow examples get local-replay --api builder cd local-replay/builder # 3. Run it python local_replay_example.py ``` **Quick Start** `desflow examples get` downloads the example at the release you install, into a folder of its own. Pick uv or pip: ```bash # 1. Install uv tool install desflow # 2. Download the example desflow examples get local-replay --api low-level cd local-replay/low-level # 3. Run it uv run --no-project --with desflow local_replay_example.py ``` ```bash # 1. Install pip install desflow # 2. Download the example desflow examples get local-replay --api low-level cd local-replay/low-level # 3. Run it python local_replay_example.py ``` # Input Fitting A model's distributions should come from data where data exists. Input fitting takes a column of measured times and fits every distribution family of times that desflow has. It checks each result, and also offers the data itself as an empirical distribution. It writes the chosen settings in a form a model loads. This page describes the command and the Python call, every option, each outcome and how to deal with it, and how the fitting is done. ______________________________________________________________________ ## What It Is `desflow fit` and `fit_column` fit the families of times of [Arrivals and Services](https://jaehyeon.me/desflow/latest/user-guide/model-parts/arrivals-and-services/index.md) to service durations or to the gaps between arrivals, by maximum likelihood with scipy. Maximum likelihood chooses the parameters under which the measured values are most probable. Each family's fit becomes one row of a table, with its parameters in seconds and its diagnostics, and the best is marked. [Fitting the Inputs](https://jaehyeon.me/desflow/latest/learn/inputs/fit-the-inputs/index.md) fits the shop's 40 packing times and shows why the best by the numbers still needs checking against the model's answer. [Fit a Distribution](https://jaehyeon.me/desflow/latest/how-to/analysis/fit-a-distribution/index.md) fits the gaps of an order log. Fitting needs the `fit` extra, which installs scipy and matplotlib: `pip install "desflow[fit]"`. A base install runs without the extra: desflow imports scipy and matplotlib only when a fit runs. ______________________________________________________________________ ## How to Use It ### Fit a Column The command fits a CSV column, prints the table, writes the best candidate's settings to `--out` and the plot to `--plot`. It exits with status 1 when no candidate is usable, and with status 2 when the input is invalid: ```bash # Fit the packing times, write the best fit and plot every candidate desflow fit packing_times.csv --column packing_seconds --unit s --lower 0 --out packing_fit.yaml --plot fit.png ``` In Python, `fit_column` does the same on a list of numbers: A blueprint holds the fit as a file: the YAML that `--out` wrote, which [Load the Settings](#load-the-settings) includes in the blueprint. ```python times = read_column(DATA, "packing_seconds") result = fit_column(times, unit="s", lower=0) print(result.text()) # every candidate, its status and diagnostics ``` ```python result = fit_column(read_column(DATA, "packing_seconds"), unit="s", lower=0) print(result.text()) # every candidate, its status and diagnostics PARAMS = SimParameter( sim_id="Shop", # An order every 1.25 s on average (rate 0.8) arrival={"orders": DistributionConfig(dist="exponential", rate=0.8)}, # The best candidate's settings, such as dist="triangular", low=0.546332 service={"packing": DistributionConfig(**result.settings())}, resources={"packers": CapacityConfig(current_cap=2, max_cap=4)}, ) ``` `read_column(path, column)`, imported with `from desflow.analysis import read_column`, reads one CSV column as text. `fit_column` takes any list of numbers or text, where an empty cell or None is a missing value. ### Options | Command option | `fit_column` argument | What it sets | Default | | -------------------- | --------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | --------------------- | | `--column` | | the CSV column to fit | required | | `--unit` | `unit` | the data's unit: `ms`, `s`, `min` or `h`; the settings are always in seconds | `s` | | `--candidates` | `candidates` | the families to try, such as `gamma,lognormal`; spaces around a name are ignored, and an unknown name is refused, quoted; `poisson` and `geometric` are skipped, as they count whole numbers | every family of times | | `--lower`, `--upper` | `lower`, `upper` | the plausible range, in the data's unit: a value outside it is invalid, and a family that can draw outside it is flagged; a NaN bound is refused | none | | `--bins` | `bins` | offer the empirical distribution as a histogram with this many bins | the values themselves | | `--min-count` | `min_count` | the fewest values a family is fitted to | 20 | | `--tolerance` | `tolerance` | how far a fitted mean and standard deviation may be from the data's, as a share of the data's; NaN and a negative number are refused | 0.25 | | `--drop-invalid` | `drop_invalid` | leave invalid values out, counted, rather than stopping | off | | `--out` | `result.yaml()` | write the best candidate's settings as YAML | | | `--plot` | `result.plot(path)` | draw the data against the best candidate | | A value is invalid when it is not a number, is not finite, or lies outside `--lower` and `--upper`. The table's first line counts the rows, and the values used, missing and invalid. ### Read the Result `fit_column` returns a `FitResult`: - **`table`:** one row per candidate, with `family`, `status`, `reason`, `parameters`, `log_likelihood`, `aic`, `ks_statistic`, `ks_p_value`, `bounds` and `best`. `aic` is the [AIC](https://jaehyeon.me/desflow/latest/learn/concepts/a-simulation-study/#aic-and-the-ks-test), where lower is better. - **`best`:** the best candidate's family. - **`settings(kind=None)`:** the settings of the best, or of the family `kind`, for `add_service(name, **settings)`. A family that is not usable is refused, and the error names those that are. - **`text()`:** the table as the command prints it. - **`yaml(kind=None)`:** the settings as the YAML file `--out` writes. - **`plot(path, kind=None)`:** the PNG `--plot` draws: the data's histogram over values generated from the candidate, and a Q-Q plot, which puts each sorted data value against the generated value at the same quantile. Points on the diagonal mean that the two agree. The settings are the same numbers the YAML file holds, so a script and a blueprint that load one fit draw the same values. A number has six significant digits, unless rounding would make the settings fail to load or move the mean or std by more than a thousandth of the std; then it keeps every digit. The lists of an empirical fit (`values`, `edges` and `counts`) keep every digit, because rounding would make close values equal. ### How the Best Is Chosen The best is the fitted family with the lowest [AIC](https://jaehyeon.me/desflow/latest/learn/concepts/a-simulation-study/#aic-and-the-ks-test) among those that cannot draw outside `--lower` and `--upper`. When every value is the same, it is `constant`. When no family within the bounds fitted, it is `empirical`, which never draws outside the data's range. Only when there is no empirical candidate is a fitted family that can draw outside the bounds chosen. A family that is rejected, did not fit or was skipped is never chosen. When two families' AIC are too close to tell them apart, as [AIC and the KS Test](https://jaehyeon.me/desflow/latest/learn/concepts/a-simulation-study/#aic-and-the-ks-test) explains, check what the choice changes in the model's answer, as [Fitting the Inputs](https://jaehyeon.me/desflow/latest/learn/inputs/fit-the-inputs/#does-the-choice-matter) does. ### Outcomes Each candidate ends with one status. Every one but `fitted` has a reason, and none stops the fit: | Status | Cause | What to do | | --------------------------- | ------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | | `skipped` | fewer values than `--min-count` | collect more data, or use the `empirical` candidate, which is still offered; lower `--min-count` only if the values are known to be typical | | `skipped` | a value of 0 or below, for `gamma`, `weibull` or `lognormal`, which are defined above 0 only | find out what the zeros are: rounding (record finer times), a different kind of event (remove it from the data), or real zero durations (use a family with no positive-only support, such as `exponential` or `truncated_normal`) | | `skipped` | `poisson` or `geometric` named in `--candidates`, with the reason " counts whole numbers, and fit tries families of times only" | fit the times with a family of times; the two families are for counts, not times | | `skipped` | every value is the same, so only `constant` and `empirical` are fitted | use `constant`, or check that the column is the one meant | | `skipped` | a value below `low`, for `truncated_normal`, whose `low` is `--lower`, or 0 | set `--lower` to the true lower bound | | `did not fit` | scipy's fit raised an error or its search did not settle; the reason is scipy's message | the data is far from that family's shape: choose another family; more data can help | | `rejected` | a fitted parameter is not finite or is out of the family's range | as for `did not fit` | | `rejected` | the fitted mean or standard deviation is more than `--tolerance` from the data's | look for outliers: correct or remove a value that is a recording error, and keep one that is real. `--upper` leaves out values above it only with `--drop-invalid`; without it, such a value stops the fit with status 2. With `--upper`, only the families bounded above, `uniform` and `triangular`, can be chosen as best, then `empirical`. Or use `--bins` for an empirical histogram | | `rejected` | a value lies where the family cannot draw | as for the zeros above | | `fitted` with a bounds note | the family can draw below `--lower` or above `--upper`, such as `normal` below 0 | it is chosen only when nothing within the bounds fits; prefer a family with the right support | The command fails only when no candidate is usable, `empirical` included. `empirical` is unusable only when there are no values, or when `--candidates` leaves it out. ### Load the Settings `!include` reads a mapping from another file, relative to the blueprint, so the file `--out` wrote is loaded and checked as if it were written in place: ```yaml services: # The fitted distribution, read from the file desflow fit wrote packing: !include packing_fit.yaml ``` An arrival also needs its `spawn`, so the include names the file and adds keys to it: `orders: !include {file: fitted/orders.yaml, spawn: pack}`. A key the fitted file already has is refused at the `!include` line, and the error names the key and both files. A YAML syntax error in the included file, or a file that is not a mapping, names that file and its line. A wrong key or value in it is reported at the blueprint's `!include` line, and so is a missing file. A file that includes itself, directly or through another, is refused at the `!include` that closes the loop. ```python # The best candidate's settings, such as dist="triangular", low=0.546332 .add_service("packing", **result.settings()) ``` `DistributionConfig(**result.settings())`, as the `fit` section above shows. ______________________________________________________________________ ## How It Works **Data first.** The values are read, and missing ones are counted and left out. Invalid ones are refused or, with `--drop-invalid`, counted and left out. They are converted to seconds. Then each family is checked against the data before it is fitted: enough values, positive values where the family needs them, and not a constant column. **Maximum likelihood, location at 0.** desflow's families have no location parameter: a gamma or a Weibull starts at 0. scipy can also fit a location, which moves the start of the distribution to wherever the data suggests. For the tutorials' 40 packing times plus one outlier of 120 seconds, a free location puts a gamma's start at 0.70 seconds, the smallest value, with a shape of 0.21 and a scale of 81. desflow has no parameter for that start. So the location of `exponential`, `gamma`, `weibull` and `lognormal` is fixed at 0, and each fit is converted to desflow's parameters: | Family | Fitted with | desflow's parameters | | ------------------ | -------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------- | | `exponential` | `scipy.stats.expon.fit(x, floc=0)` | `rate` = 1 ÷ scale | | `normal` | `scipy.stats.norm.fit(x)` | `mean`, `std` | | `lognormal` | `scipy.stats.lognorm.fit(x, floc=0)` | the variable's `mean` = scale × e^(s²/2) and `std` = mean × √(e^(s²) − 1) | | `truncated_normal` | the likelihood of `scipy.stats.truncnorm` with `low` fixed, maximised by `scipy.optimize.minimize` | `mean`, `std`, `low` | | `uniform` | `scipy.stats.uniform.fit(x)` | `low`, `high` | | `triangular` | `scipy.stats.triang.fit(x)` | `low`, `mode`, `high` | | `gamma` | `scipy.stats.gamma.fit(x, floc=0)` | `shape`, `scale` | | `weibull` | `scipy.stats.weibull_min.fit(x, floc=0)` | `shape`, `scale` | | `constant` | every value is the same | `value` | | `empirical` | the values, or `numpy.histogram` with `--bins` | `values`, or `edges` and `counts` | Each fit runs on its own, so one that fails is a row, not a crash. **Checks.** Every fitted result is checked before it can be chosen. Each parameter must be finite and within the family's rules, the same rules a blueprint's distribution is checked against. The family's mean and standard deviation, from desflow's own formulas, must be within `--tolerance` of the data's. A result that fails is `rejected` with the reason. Some bad fits still pass these checks. Fitted to a gamma, the three values 1.0, 1.0000001 and 1.0000002 give a shape of 1.4 × 10¹⁴ and a scale of 7.1 × 10⁻¹⁵, with the right mean and spread. `--min-count` guards against such fits: no family is fitted to fewer values than `--min-count`. **Diagnostics.** For each fitted family, the table gives the log-likelihood of the data and the AIC. The k in the AIC counts only the fitted parameters: a fixed location does not count. The table also gives the [Kolmogorov-Smirnov statistic](https://jaehyeon.me/desflow/latest/learn/concepts/a-simulation-study/#aic-and-the-ks-test) and p-value from `scipy.stats.kstest`. The p-value assumes the parameters were known in advance. They were estimated from the same data, so the p-value is approximate and tends to be too high. `empirical` has no AIC. **Plot.** The generated values are drawn through desflow's `Sampler`, seeded, with the same smallest delay a run applies, so the plot shows what a run draws and repeats exactly. ______________________________________________________________________ ## Stability and Limits - **Size of the extra.** These sizes were measured in new Python 3.12 environments on macOS. scipy 1.18.1 takes about 70 MB installed with uv, and about 100 MB with pip, which also compiles bytecode. Its download is 20 to 37 MB, depending on the platform. matplotlib and its dependencies, beyond the NumPy desflow already needs, add about 55 MB with uv and about 70 MB with pip. Fitting is not in the base install because of these sizes. - **Local files only.** The command reads a CSV file. Reading from a database or an object store, and automated selection beyond the lowest AIC, come later. - **A fit is not a validation.** A family that fits the data well can still change the model's answer, and a model whose inputs fit can still answer the question badly. Compare the model's output with the real system's, as [Experiment Results](https://jaehyeon.me/desflow/latest/user-guide/results/experiment-results/#compare-with-observed-values) does. - **One column at a time.** Each column is fitted on its own, so a dependence between two inputs, such as larger orders taking longer to pack, is not captured. ______________________________________________________________________ ## Example: Fitted Inputs The `fitting` example fits the 40 packing times of the tutorials and runs one hour of a two-packer shop with the fitted packing time. It needs no Docker service and ends on its own. The tutorial page [Fitting the Inputs](https://jaehyeon.me/desflow/latest/learn/inputs/fit-the-inputs/index.md) teaches these features step by step. **Quick Start** `desflow examples get` downloads the example at the release you install, into a folder of its own. Pick uv or pip: ```bash # 1. Install uv tool install "desflow[fit]" # 2. Download the example desflow examples get fitting --api yaml cd fitting/yaml # 3. Run it desflow fit ../packing_times.csv --column packing_seconds --lower 0 --out packing_fit.yaml && desflow run fitting.yaml ``` ```bash # 1. Install pip install "desflow[fit]" # 2. Download the example desflow examples get fitting --api yaml cd fitting/yaml # 3. Run it desflow fit ../packing_times.csv --column packing_seconds --lower 0 --out packing_fit.yaml && desflow run fitting.yaml ``` The file the fit writes, which the download already holds: ```yaml # Fitted by desflow fit from packing_times.csv, column packing_seconds: triangular, from # 40 values in s, written in seconds. dist: triangular low: 0.546332 mode: 1.2 high: 2.83766 ``` The whole blueprint is [`examples/yaml/fitting.yaml`](https://github.com/jaehyeon-kim/desflow/blob/v1.3.0/examples/yaml/fitting.yaml). **Quick Start** `desflow examples get` downloads the example at the release you install, into a folder of its own. Pick uv or pip: ```bash # 1. Install uv tool install "desflow[fit]" # 2. Download the example desflow examples get fitting --api builder cd fitting/builder # 3. Run it uv run --no-project --with "desflow[fit]" fitting_example.py ``` ```bash # 1. Install pip install "desflow[fit]" # 2. Download the example desflow examples get fitting --api builder cd fitting/builder # 3. Run it python fitting_example.py ``` The whole file is [`examples/builder/fitting_example.py`](https://github.com/jaehyeon-kim/desflow/blob/v1.3.0/examples/builder/fitting_example.py). **Quick Start** `desflow examples get` downloads the example at the release you install, into a folder of its own. Pick uv or pip: ```bash # 1. Install uv tool install "desflow[fit]" # 2. Download the example desflow examples get fitting --api low-level cd fitting/low-level # 3. Run it uv run --no-project --with "desflow[fit]" fitting_example.py ``` ```bash # 1. Install pip install "desflow[fit]" # 2. Download the example desflow examples get fitting --api low-level cd fitting/low-level # 3. Run it python fitting_example.py ``` The whole file is [`examples/low-level/fitting_example.py`](https://github.com/jaehyeon-kim/desflow/blob/v1.3.0/examples/low-level/fitting_example.py). # Task Flow An entity rarely leaves after completing just one task. An order is checked, perhaps wrapped as a gift, packed, sometimes packed again, and shipped. This page shows how a finished task chooses the next one, what the entity carries from task to task, and which values a task draws and reads on the way. ______________________________________________________________________ ## What It Is A **flow** is the sequence of tasks one entity passes through. Each task names what follows it: always the same task, the first of several rules whose condition holds, or a task drawn at random by weight. A rule can send the entity back to a task it has passed, for **rework**. A task that names nothing ends the flow. The entity keeps its key and its **attributes** through the whole flow, and every task can read them. Each task also has a **key** for its records, can draw **values** for its own use, and can read the **records** that earlier tasks published. [A Flow of Tasks](https://jaehyeon.me/desflow/latest/learn/shop-logic/flow-of-tasks/index.md) builds a pick, pack and ship flow step by step. ______________________________________________________________________ ## How to Use It ### Choose the Next Task `next` takes one of these forms: - **A task name**, `next: pack_order`: always that task. - **Rules**, `when` with an optional `default`: each rule is a condition and a task. Rules are tried in order. The first matching rule wins, and `default` applies if none matches. With no default and no matching rule, the flow ends. - **Weights**, below. - **In the builder, a function** that takes the `Upstream` and returns a task name or `None`. ```yaml check_order: payload: {total: 80} # Rules are tried in order; the first match wins. Otherwise, use the default. next: when: - {condition: "level.stock == 0", task: backorder} - {condition: "payload.total >= 100 or attr.gift == 1", task: wrap_gift} default: pack_order ``` ```python # Rules are tried in order; the first match wins. Otherwise, use the default. @app.task( next={ "when": [ {"condition": "level.stock == 0", "task": "backorder"}, { "condition": "payload.total >= 100 or attr.gift == 1", "task": "wrap_gift", }, ], "default": "pack_order", } ) def check_order(task_id: int): return {"total": 80} ``` ```python # The same rules as next, as a Router; choose() returns the next task's name route = Router( { "when": [{"condition": "attr.gift == 1", "task": "wrap_gift"}], "default": "pack_order", } ) order = Entity("orders-1", "orders", {"gift": 0}) # key, arrival, attributes finished = Upstream(0, order.key, order.attributes, {"total": 80}) assert route.choose(finished, env=None) == "pack_order" ``` A `Router` takes the same rules as `next`. When a task finishes, its process builds the `Upstream`, asks `route.choose(upstream, env, levels=...)` for the next task's name, and starts that task with the same entity. `env` lets a condition read `registry[...]` and `t`. `levels`, a mapping from store and container names to the objects, lets it read `level.`. The condition is evaluated when the task finishes, after its `set`. `payload.` reads the payload of the task that just finished, `attr.` the entity's attributes, `level.` a store's or container's level, and `registry["..."]` a live parameter. [How It Works](#how-it-works) lists everything a condition can use. ### Weights `weights` maps task names to numbers or expressions, and the next task is drawn in proportion to them. The draw comes from a random stream of the routing task's own, `route.`, so a seeded run repeats it and it changes no other draw: ```yaml pack_order: service: packing resource: packers get: {container: stock, amount: 1} payload: {event_type: order_packed} # A task drawn in proportion to its weight: one in ten is packed again next: weights: {ship_order: 9, pack_order: 1} ``` ```python # A task drawn in proportion to its weight: one in ten is packed again @app.task( service_id="packing", resource_id="packers", get={"container": "stock", "amount": 1}, next={"weights": {"ship_order": 9, "pack_order": 1}}, ) def pack_order(task_id: int): return {"event_type": "order_packed"} ``` ```python # Weights draw from a generator: the routing task's own stream, as the builder's do rework = Router({"weights": {"ship_order": 9, "pack_order": 1}}) rework.rng = Sampler(seed=42).generator("route.pack_order") choices = [rework.choose(finished) for _ in range(1000)] ``` A weight written as an expression is read when the task finishes. It may use `attr.`, `registry["..."]`, `level.`, `t` and the task's vars, as `weights: {ship_order: 9, pack_order: "attr.rework"}` does. A weight of infinity or `true` is refused when the blueprint loads. A weight below 0, or text that is not a number, fails the run with the weight's name. Weights that add up to 0 fail the run. ### Attributes An arrival gives each new entity its starting `attributes`, and a task's `set` changes them when the task finishes. Each entity gets its own copy. Attributes are not published: a condition reads them as `attr.`, and a payload includes them only when it asks. ```yaml arrivals: # Each order starts with these attributes, read as attr.gift # An order every 2 s on average (rate 0.5) orders: dist: exponential rate: 0.5 spawn: check_order attributes: {gift: 0} # A gift order every 10 s on average (rate 0.1) gifts: dist: exponential rate: 0.1 spawn: check_order attributes: {gift: 1} ``` ```yaml # Applied to the order's attributes when the task finishes set: {backordered: 1} ``` A task's `attributes` list adds the named attributes to a mapping payload, as `ship_order` does in the full blueprint, [`task_flow.yaml`](https://github.com/jaehyeon-kim/desflow/blob/v1.3.0/docs/snippets/yaml/task_flow.yaml). ```python # Each order starts with these attributes, read as attr.gift # An order every 2 s on average (rate 0.5) app.add_arrival("orders", dist="exponential", rate=0.5, attributes={"gift": 0}) # A gift order every 10 s on average (rate 0.1) app.add_arrival("gifts", dist="exponential", rate=0.1, attributes={"gift": 1}) ``` ```python # `set` is applied to the order's attributes when the task finishes @app.task(service_id="supplying", set={"backordered": 1}, next="check_order") def backorder(task_id: int): return {"event_type": "order_backordered"} ``` An `Entity(key, arrival, attributes)` carries them. The process updates `entity.attributes` itself after a task, as the low-level tab of [A Flow of Tasks](https://jaehyeon.me/desflow/latest/learn/shop-logic/flow-of-tasks/index.md) shows. ### Record Key and Fields Each arrival starts a new entity, keyed by the arrival's name and a counter from 1: `orders-1`, `orders-2`. Every event of every task in its flow carries that key as its record key, so a sink can follow one order through the whole flow. Kafka sends records with the same key to one partition, so it keeps one order's events in order. The builder can replace the key with a function of the counter: A blueprint arrival uses the default key. ```python # Keys ret-00001, ret-00002 instead of returns-1, from the counter, which starts at 1 # A return every 20 s on average (rate 0.05) app.add_arrival("returns", dist="exponential", rate=0.05, key=lambda n: f"ret-{n:05d}") ``` The process that creates each `Entity` gives it its key. Below are the finished events of `gifts-5` in [`task_flow.yaml`](https://github.com/jaehyeon-kim/desflow/blob/v1.3.0/docs/snippets/yaml/task_flow.yaml), the blueprint whose parts this page shows. The gift order is checked while the shelf has stock, so it is not backordered and its shipping record shows `backordered: None`. It is wrapped, packed and shipped, all under one key: ```text [EVT] {'sim_ts': 33.55388955498106, 'timestamp': '...', 'key': 'gifts-5', 'task': 'check_order', 'instance': 17, 'value': {'total': 80}} [EVT] {'sim_ts': 36.55388955498106, 'timestamp': '...', 'key': 'gifts-5', 'task': 'wrap_gift', 'instance': 3, 'value': {'event_type': 'gift_wrapped'}} [EVT] {'sim_ts': 38.05388955498106, 'timestamp': '...', 'key': 'gifts-5', 'task': 'pack_order', 'instance': 12, 'value': {'event_type': 'order_packed'}} [EVT] {'sim_ts': 39.55388955498106, 'timestamp': '...', 'key': 'gifts-5', 'task': 'pack_order', 'instance': 13, 'value': {'event_type': 'order_packed'}} [EVT] {'sim_ts': 39.55388955498106, 'timestamp': '...', 'key': 'gifts-5', 'task': 'ship_order', 'instance': 11, 'value': {'event_type': 'order_shipped', 'gift': 1, 'backordered': None}} ``` A task can also set the key of its own records. A blueprint task has these keys, and the builder's `@app.task` takes the same names: - `key_field` names a payload field. Its value becomes the key of the task's `finished` record, and so the Kafka message key. The `queued` and `started` records keep the entity's key. A payload without the field fails the run. - `key` is a value place for the key of all the task's records: text, a whole number or a generator. It is drawn once for each instance, at its first record, and written as text. Write `key` or `key_field`, not both. - `id_field` adds the task's instance id to a mapping payload under that name, `item_field` adds the item the task's store `get` took, and `attributes` adds the named entity attributes. They need a mapping payload, and a null payload fails the task. - `payload: null` publishes no `finished` record, and the task runs its other steps. It is refused together with a store `put`, `key_field`, `id_field`, `item_field`, `attributes` and a `payload.` read. ```yaml sign_up: payload: customer_id: {gen: sequence, format: "c-{}"} # The finished record carries the customer id as its key key_field: customer_id ``` ```python customer = Template( {"customer_id": {"gen": "sequence", "format": "c-{}"}}, name="tasks.sign_up" ) # The finished record carries the customer id as its key. A builder task keeps the # rows that a lookup reads only when it asks, with history @app.task(key_field="customer_id", history=1000) def sign_up(task_id): return customer ``` A process gives the key to `env.publish_event(key, value, ...)` itself, as the low-level tab of [Tasks](https://jaehyeon.me/desflow/latest/user-guide/tasks-and-processes/tasks/#a-task) shows, so it can publish any record under any key. ### Upstream A task started by `next` receives what the task before it handed on, the `Upstream`: the finished task's instance id, the entity's key and attributes, and the finished task's payload. A builder function gets it by declaring a parameter called `upstream`, and gets the entity by declaring `entity`. A function that declares neither is called without them. The first task of a flow gets `upstream=None`. A task that `on_fail`, `on_renege` or `on_balk` reaches reads the record that sent it there as `upstream.status` and, after a failure, `upstream.reason`. A blueprint task has no function to declare `upstream`. Its `payload` names the attributes it carries, its generators read the finished task's payload as `{gen: upstream, path: }`, and an expression reads it as `upstream.`. Its `next` conditions read the finished task's payload as `payload.` and the entity's attributes as `attr.`. ```python # A function declaring `upstream` receives what the previous task handed on, # and `entity` the order itself; a payload includes attributes only when it asks @app.task() def ship_order(task_id: int, upstream, entity): return { "event_type": "order_shipped", "packed_by": upstream.task_id, # the instance of pack_order before it "gift": entity.attributes.get("gift"), "backordered": entity.attributes.get("backordered"), } # A rule can also be a function of the Upstream, returning a task name or None @app.task(next=lambda upstream: "check_order" if upstream.payload["ok"] else None) def inspect_return(task_id: int): return {"ok": False} ``` A low-level process holds the order and its attributes itself. It can build an `Upstream` and call `Router.choose`, as in [Choose the Next Task](#choose-the-next-task), or decide the next step in plain Python. ### Values a Task Draws A task can draw values for its own use. They come in three groups: - `vars` are drawn in order, once for each instance of the task, and each can read the vars above it. - `vars_once` are drawn once for each entity and task, at the first use. A task that an entity runs again, as a rework does, keeps its `vars_once`. - `finish_vars` are drawn after the service and can read the vars. `on_start` values are published as one record when the task starts. A task that has `on_start` draws its `vars` when it starts. Without `on_start`, the task draws them after the service, just before it builds its payload, and a `service_time` that reads a var draws it first. A payload reads a var as `{gen: var, name: }`. The `expr` and `format` generators and the `put`, `fail`, `next.when` and `next.weights` expressions of the same task read it by its bare name. A wait timeout `value` may read `vars_once` names but no `vars`. A var name is an identifier that is not a name of the expression language (`all`, `any`, `len`, `sum`, `cause`, `waiting` and the others) and not the name of a var that is visible there. It is in one group only. A task that can end early (`patience`, `balk`, `wait`, `on_interrupt: abandon` or `queue_limit`) refuses an `on:` value that reads a var. ```yaml pack: service: packing resource: packers # Drawn once for each order, so a second packing keeps the box vars_once: box: {gen: one_of, choices: [small, large]} # Drawn for each packing, when it starts because on_start is written vars: weight: {gen: uniform, low: 0.5, high: 5, decimals: 1} # Published as one record when the packing starts on_start: weight: {gen: var, name: weight} # Drawn after the service, and able to read the values above finish_vars: fee: {gen: expr, expr: "round(weight * 0.4, 2)"} payload: box: {gen: var, name: box} weight: {gen: var, name: weight} fee: {gen: var, name: fee} # The total of the order that came here total: {gen: upstream, path: total} # One packing in ten is done again next: weights: {pack: 1, finish: 9} ``` ```python packed = Template( { "box": {"gen": "var", "name": "box"}, "weight": {"gen": "var", "name": "weight"}, "fee": {"gen": "var", "name": "fee"}, # The total of the order that came here "total": {"gen": "upstream", "path": "total"}, }, name="tasks.pack", ) @app.task( service_id="packing", resource_id="packers", # Drawn once for each order, so a second packing keeps the box vars_once={"box": {"gen": "one_of", "choices": ["small", "large"]}}, # Drawn for each packing, when it starts because on_start is written vars={"weight": {"gen": "uniform", "low": 0.5, "high": 5, "decimals": 1}}, # Published as one record when the packing starts on_start={"weight": {"gen": "var", "name": "weight"}}, # Drawn after the service, and able to read the values above finish_vars={"fee": {"gen": "expr", "expr": "round(weight * 0.4, 2)"}}, # One packing in ten is done again next={"weights": {"pack": 1, "finish": 9}}, ) def pack(task_id): return packed ``` A process draws its values with its own `Sampler` generators and keeps them in Python variables, so it has no groups to order. A generator it names, such as `sampler.generator("pack.weight")`, draws from its own stream of the run's seed. Every generator node draws from its own stream of the run's seed, so adding a value does not change the draws of the others. ### Read Earlier Records A task can read the records that tasks finished before it. A generator reads them, in place of a function that keeps its own list: - `lookup` takes a field of a row of another task's finished payloads, chosen at random unless `strategy` is `first` or `last`. `histogram` splits the rows, in the order they were written, into bins with a share each, `latest_by` keeps the newest row of each value of a field, and `distinct` draws without replacement inside one `repeat`. - `previous` takes a field of the last finished payload of the same task on the same stream. The stream is the arrival, or the entity for an arrival with `count` or `keys`. It gives null when there is none and no `default` is written. - `upstream` takes a field of the payload of the task that routed here. - `aggregate` gives the `mean`, `sum`, `min`, `max` or `count` of a field over the last rows of a task. `where`, an expression over the row's fields, keeps some of them. It does not wait for a row. A task keeps its last `history` finished payloads, one million by default, when a `lookup` or `aggregate` in the file names it or when `history` is written. [Look Up Other Records](https://jaehyeon.me/desflow/latest/how-to/generate-data/look-up-other-records/index.md) and [Build on the Last Value](https://jaehyeon.me/desflow/latest/how-to/generate-data/build-on-the-last-value/index.md) work through them. ```yaml place_order: # A value drawn here is read by name below vars: total: {gen: uniform, low: 5, high: 200, decimals: 2} payload: # A customer who signed up earlier customer_id: {gen: lookup, task: sign_up, path: customer_id} total: {gen: var, name: total} # This stream's last running_total plus this order's total running_total: gen: add args: - {gen: previous, path: running_total, default: 0} - {gen: var, name: total} next: pack ``` A generator that reads records can also set how long a task takes. These tasks run one after another. `deliver` takes the mean weight of the last 5 packings over 1 kg, `restock` the newest weight of one customer, and `inspect` two past weights drawn without replacement, mostly from the older part of the rows. `settle` takes as long as the last settling, and 2 seconds for the first, and `finish` as long as the settling before it: ```yaml deliver: # The mean weight of the last 5 packings over 1 kg, as seconds service_time: gen: aggregate task: pack path: weight last: 5 where: weight > 1 function: mean payload: {event_type: delivered} next: restock restock: # The newest weight of one customer, chosen from the newest row of each customer service_time: gen: lookup task: pack path: weight strategy: last latest_by: customer_id payload: {event_type: restocked} next: inspect inspect: # Two past weights, drawn without replacement, mostly from the older part of the # rows service_time: gen: expr expr: sum(weights) names: weights: gen: repeat times: 2 value: gen: lookup task: pack path: weight distinct: true histogram: - {bin: 2, frequency: 8} - {bin: 8, frequency: 2} payload: {event_type: inspected} next: settle settle: # As long as the last settling took, and 2 s for the first service_time: {gen: previous, path: took, default: 2} payload: took: {gen: uniform, low: 1, high: 3, decimals: 1} next: finish finish: # As long as the settling that came before took service_time: {gen: upstream, path: took} payload: {event_type: finished} ``` ```python order = Template( { # A customer who signed up earlier "customer_id": {"gen": "lookup", "task": "sign_up", "path": "customer_id"}, "total": {"gen": "var", "name": "total"}, # This stream's last running_total plus this order's total "running_total": { "gen": "add", "args": [ {"gen": "previous", "path": "running_total", "default": 0}, {"gen": "var", "name": "total"}, ], }, }, name="tasks.place_order", ) # A value drawn here is read by name below @app.task( history=10, vars={"total": {"gen": "uniform", "low": 5, "high": 200, "decimals": 2}}, next="pack", ) def place_order(task_id): return order ``` A process keeps the earlier values itself, in a list or a variable, and reads them where it needs them. A task whose generators look up another task does not start before that task has a row. An arrival, a `spawn` or a `next` that would start it is dropped, with one INFO line that gives the wait in simulation time, and a task that never started gets one more line at the end of the run. A dropped start runs none of the task's `on:` actions. A lookup in an arrival place fails when there is no row. In `where`, a field of the row wins over `t`. The blueprint is refused when it loads if no task starts the target of a lookup, if the path is not in the target's payload, if lookups form a cycle, if `previous` is outside a task, if `upstream` is in a task that no `next` reaches or that `on_fail` or `on_interrupt_next` also reaches, or if `distinct` is outside the value of a `repeat`. ### Carry Values and Switch Arrivals A task can write names of its own process with `set_args`. This task and the tasks that follow in the same flow read them as `arg.`. A child flow has its own, and a parent passes names to it with `args` on a `task` branch of its `wait` or on a `spawn`. A `spawn` evaluates `args` once for each child. A read of a name that was neither passed nor written is a run failure. `set_args` is read after `set`, so a payload reads the value from before the write. `activate` and `deactivate` turn the sources of the named arrivals on and off when the task finishes, after `set_args`. A scenario step turns them on and off at a set time instead, as [Script an Experiment](https://jaehyeon.me/desflow/latest/user-guide/live-runs-and-connectors/live-parameters/#script-an-experiment) shows. Each must name an arrival that has a `spawn`, and the blueprint and the builder refuse a name that is not an arrival. A source with `count` or `keys` obeys them too. Under `off_mode: drop` an arrival that falls while its source is off is lost and takes no key number. Under `restart` the source starts a whole new gap when it goes on. [Arrivals and Services](https://jaehyeon.me/desflow/latest/user-guide/model-parts/arrivals-and-services/index.md) describes the arrival keys. ```yaml close_shop: payload: {event_type: shop_closed} # Written now, and read as arg.closed_at by this task and the tasks after it set_args: closed_at: {gen: expr, expr: t} # Turn on the source of the night sign-ups, as the task finishes activate: night next: day_report day_report: payload: closed_at: {gen: expr, expr: arg.closed_at} mean_total: gen: aggregate task: place_order path: total last: 10 function: mean ``` ```python report = Template( { "closed_at": {"gen": "expr", "expr": "arg.closed_at"}, "mean_total": { "gen": "aggregate", "task": "place_order", "path": "total", "last": 10, "function": "mean", }, }, name="tasks.day_report", ) @app.task( # Written now, and read as arg.closed_at by this task and the tasks after it set_args={"closed_at": {"gen": "expr", "expr": "t"}}, # Turn on the source of the night sign-ups, as the task finishes activate="night", next="day_report", ) def close_shop(task_id): return {"event_type": "shop_closed"} @app.task() def day_report(task_id): return report ``` A process passes values to the next one as plain arguments, and decides in its own code which arrival processes keep running. Below are the records of `task_values.yaml` that these sections show: the first sign-up, keyed by its customer id; the first order, which looks up customer `c-0` and starts its running total; the packing of that order, with the `weight` published at its start and the finished record with the box, the weight, the fee and the order's total; and the day report that the shop's closing starts at 100 seconds. ```text [EVT] {'sim_ts': 42.95160161372071, 'timestamp': '...', 'key': 'c-0', 'task': 'sign_up', 'instance': 0, 'value': {'customer_id': 'c-0'}} [EVT] {'sim_ts': 43.408565140468134, 'timestamp': '...', 'key': 'orders-16', 'task': 'place_order', 'instance': 15, 'value': {'customer_id': 'c-0', 'total': 42.23, 'running_total': 42.23}} [EVT] {'sim_ts': 43.408565140468134, 'timestamp': '...', 'key': 'orders-16', 'task': 'pack', 'instance': 0, 'value': {'weight': 2.5}} [EVT] {'sim_ts': 44.908565140468134, 'timestamp': '...', 'key': 'orders-16', 'task': 'pack', 'instance': 0, 'value': {'box': 'small', 'weight': 2.5, 'fee': 1.0, 'total': 42.23}} [EVT] {'sim_ts': 100.0, 'timestamp': '...', 'key': 'closing-1', 'task': 'day_report', 'instance': 0, 'value': {'closed_at': 100.0, 'mean_total': 126.093}} ``` ______________________________________________________________________ ## How It Works **Conditions.** A condition is a Python expression, parsed with Python's `ast` module and checked against a list of what is allowed before it is ever evaluated. Nothing goes through `eval`. Each name carries its source as a prefix, so adding a payload field cannot change what an attribute of the same name means. [Names an Expression Reads](https://jaehyeon.me/desflow/latest/user-guide/writing-a-model/blueprints/#names-an-expression-reads) lists every name by the place an expression sits in: | Name | Value | | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | | `payload.`, `attr.`, `attr[""]` | a field of the payload of the task that just finished, an attribute of the entity, and an attribute whose name Python reads as a word | | `level.` | the level of a store or container | | `users.`, `queue.` | how many units of a resource are held, and how many requests wait for it ([Units and Queues](https://jaehyeon.me/desflow/latest/user-guide/resources/units-and-queues/#read-the-queue-and-users)) | | `putters.`, `getters.` | how many puts and gets wait at a store or container | | `count()`, `items()` | how many items a store holds, and the list of them ([Stores and Containers](https://jaehyeon.me/desflow/latest/user-guide/model-parts/stores-and-containers/#registry-paths-readings-and-conditions)) | | `item`, `item.`, `item_priority` | the item the task's store `get` took, a field of it at any depth, and the priority a priority store gave it ([Stores and Containers](https://jaehyeon.me/desflow/latest/user-guide/model-parts/stores-and-containers/#pick-an-item-or-give-up-waiting)) | | `arg.`, `cause.`, `upstream.` | a name `set_args` wrote or a parent passed, why the task was interrupted, and a field of the payload of the task that routed here | | `held()`, `waiting()` | the holders in grant order and the waiting requests in queue order, as mappings with `entity`, `rank`, `time`, `preempt` and `key`, and `since` for a holder | | `putting()`, `getting()` | the puts and gets waiting at a store or container, with `entity` and, for a put, `item` or `amount` | | `running()`, `running(, )` | how many instances of a task run, or meet the condition | | `wait..done`, `.ok`, `.value`, `signal..count`, `.ok`, `.value`, `.processed`, `handle..triggered`, `.processed`, `.ok`, `.value`, `.alive`, `done_count` | the task's wait, the signals, the names the task opened, and in the `when` of a wait group how many branches are done ([Signals and Waiting](https://jaehyeon.me/desflow/latest/user-guide/tasks-and-processes/signals-and-waiting/#wait-signals-and-child-flows)) | | `process.name`, `.instance`, `.target`, `.key`, `.flow_name` | the running process ([Processes](https://jaehyeon.me/desflow/latest/user-guide/tasks-and-processes/processes/#how-it-works)) | | `registry[""]` | a live parameter, written whole because its path contains dots | | `t`, `peek()` | the simulation time in seconds, and the time of the next scheduled event | | a var name | a var of the task, read bare in `put`, `fail`, `next.when`, `next.weights`, `expr` and `format` | It may also use numbers, text, `True`, `False` and `None`; the arithmetic `+`, `-`, `*`, `/`, `//`, `%` and `**` (a power above 10,000, or one with a result of more than 1,000,000 bits, is refused); the comparisons `<`, `<=`, `>`, `>=`, `==`, `!=`, `is None`, `in` and `not in`; `and`, `or`, `not` and `a if c else b`; list and mapping literals, subscripts, slices and one-clause list comprehensions; the constants `pi` and `e`; and the functions `abs`, `min`, `max`, `round`, `floor`, `ceil`, `sqrt`, `exp`, `log`, `log10`, `sin`, `cos`, `tan`, `clamp`, `len`, `sum`, `sorted`, `range`, `any`, `all`, `str`, `int`, `float`, `bool`, `has(attr.)`, `get_key`, `set_key` and `drop_key`. Text may be compared, indexed, added with `+` and passed to the key functions, and `%` on text is refused. One reading of an expression that makes more than 1,000,000 items in all is a named run failure. Anything else is refused with a message that names it: A blueprint condition that uses anything else is refused when the blueprint is built, with the same message. ```python for text in ("payload.total @ 2", "x > 1", "open('orders.csv')"): try: Expression(text) except ValueError as error: print(error) ``` A low-level `Router` takes these conditions, as in [Choose the Next Task](#choose-the-next-task), and a process can also decide in plain Python. ```text 'payload.total @ 2' uses the operator MatMult, which an expression cannot 'x > 1' uses the name 'x' (write payload., attr., level., users., queue., putters., getters., item., item, item_priority, arg., cause., upstream., count(), items(), held(), waiting(), putting(), getting(), running(), peek(), wait.., signal.., process., registry[""] or t), which an expression cannot 'open('orders.csv')' uses a Call other than count(), items(), has(attr.), held, waiting, putting, getting, peek, running, members or abs, min, max, len, sum, sorted, range, any, all, str, int, float, bool, get_key, set_key, drop_key, round, floor, ceil, sqrt, exp, log, log10, sin, cos, tan, clamp, which an expression cannot ``` A blueprint is checked when it loads, and each error names its YAML line. Every condition must parse, and every task a rule names must exist. Every `level.` must name a store or container, every `users.` and `queue.` a resource, every `putters.` and `getters.` a store or container, and every `count(...)` and `items(...)` a store. Every `registry["..."]` must be a path of the model. An `item.` in a place that no `get` reaches is refused. The builder makes the same checks when `run()` starts. A name that is missing when a condition is evaluated, such as a payload field, raises an error naming the expression. **Weights.** Weights that are numbers are turned into cumulative shares once. Weights that are expressions are read each time the task finishes. Each choice draws one uniform number from the routing task's stream and picks the task whose share it falls in. **Starting the Next Task.** When a task finishes, it applies `set`, builds the `Upstream` and asks its rules for the next task. It runs that task next, in the same SimPy process and the same step, with the same entity and the next instance id from the task's counter. An arrival that spawns the task uses the same counter, so no two runs of a task share an id. In SimPy terms, the next task is the next statement of one process. [SimPy and desflow](https://jaehyeon.me/desflow/latest/simpy/index.md) describes processes. ______________________________________________________________________ ## Stability and Limits - **Flow balance.** The rate into each task follows from the rates into the tasks before it and the routing shares. With weights of 9 to ship and 1 back to packing, one packing in ten sends the order back to be packed again. Every order is packed once, one in ten a second time, one in a hundred a third time, and so on. An order is therefore packed 1 + 0.1 + 0.01 + ... = 1 ÷ 0.9 = 1.11 times on average, so the packers see 11% more work than there are orders. Weights that are expressions give `desflow explain` no shares, so it reports no flow balance for them. - **Rework raises utilisation.** Work the load out with the rework included, as [Queues and Capacity](https://jaehyeon.me/desflow/latest/learn/first-model/queues-and-capacity/index.md) does, or a rework loop can push a resource past full use. [Queueing Basics](https://jaehyeon.me/desflow/latest/learn/concepts/queueing-basics/#utilisation) explains utilisation. - **Refused expressions.** A call other than the listed functions, a name without a source, `payload["total"]` (write `payload.total`), a comprehension with more than one clause or over a mapping, `lambda`, `~` and the shift operators are refused. `**` with a negative base and a fractional exponent, and `round(x, -n)` with a very large `n`, fail the run when the expression is evaluated, naming the expression. An expression nested more than 200 levels is refused when it is read. - **A loop needs time.** A loop of tasks that take no service time, resource, wait or get never lets the clock move. The run stops with an error that names the tasks after the flow has run 10,000 instances at one instant, as a resource breakdown does. Give one task of the loop a `service_time` above 0, or a way out in its `next` rules. - **One entity, one flow.** A task leads to at most one next task. Splitting one order into several, or joining several into one, comes after 1.0. - **`decide` is kept free.** The task key `decide` is kept for decisions sent from outside for one entity, planned after 1.0. Today it is refused like any unknown key. ______________________________________________________________________ ## Example: A Flow of Tasks In the `flow` example, orders are picked, gift orders are wrapped, one parcel in ten is packed again, and every order is shipped. Wrapping and shipping are timed steps. It needs no Docker service and ends on its own. The tutorial page [A Flow of Tasks](https://jaehyeon.me/desflow/latest/learn/shop-logic/flow-of-tasks/index.md) teaches these features step by step. **Quick Start** `desflow examples get` downloads the example at the release you install, into a folder of its own. Pick uv or pip: ```bash # 1. Install uv tool install desflow # 2. Download the example desflow examples get flow --api yaml cd flow/yaml # 3. Find the bottleneck, with no run desflow explain flow.yaml # 4. Run it desflow run flow.yaml ``` ```bash # 1. Install pip install desflow # 2. Download the example desflow examples get flow --api yaml cd flow/yaml # 3. Find the bottleneck, with no run desflow explain flow.yaml # 4. Run it desflow run flow.yaml ``` ```yaml tasks: pick: service: picking resource: pickers payload: {event_type: order_picked} # The first rule that holds wins; default catches the rest. next: when: - {condition: "attr.gift == 1", task: wrap} default: pack wrap: # A timed step: a service and no resource, so no queued event and no wait. service: wrapping payload: {event_type: gift_wrapped} # Applied to the entity's attributes when the task finishes. set: {wrapped: 1} next: pack pack: service: packing resource: packers payload: {event_type: order_packed} # Drawn from this task's own random sequence: one parcel in ten is packed again. next: weights: {ship: 9, pack: 1} ``` The whole file is [`examples/yaml/flow.yaml`](https://github.com/jaehyeon-kim/desflow/blob/v1.3.0/examples/yaml/flow.yaml). **Quick Start** `desflow examples get` downloads the example at the release you install, into a folder of its own. Pick uv or pip: ```bash # 1. Install uv tool install desflow # 2. Download the example desflow examples get flow --api builder cd flow/builder # 3. Run it uv run --no-project --with desflow flow_example.py ``` ```bash # 1. Install pip install desflow # 2. Download the example desflow examples get flow --api builder cd flow/builder # 3. Run it python flow_example.py ``` ```python @app.task( service_id="picking", resource_id="pickers", # The first rule that holds wins; default catches the rest next={"when": [{"condition": "attr.gift == 1", "task": "wrap"}], "default": "pack"}, ) def pick(task_id, context): """Picks the order's items.""" return {"event_type": "order_picked"} # A timed step: a service and no resource, so no queued event and no wait. # `set` is applied to the entity's attributes when the task finishes. @app.task(service_id="wrapping", set={"wrapped": 1}, next="pack") def wrap(task_id, context): """Wraps a gift.""" return {"event_type": "gift_wrapped"} # Drawn from this task's own random sequence: one parcel in ten is packed again @app.task( service_id="packing", resource_id="packers", next={"weights": {"ship": 9, "pack": 1}}, ) def pack(task_id, context): """Packs the order.""" return {"event_type": "order_packed"} ``` The whole file is [`examples/builder/flow_example.py`](https://github.com/jaehyeon-kim/desflow/blob/v1.3.0/examples/builder/flow_example.py). **Quick Start** `desflow examples get` downloads the example at the release you install, into a folder of its own. Pick uv or pip: ```bash # 1. Install uv tool install desflow # 2. Download the example desflow examples get flow --api low-level cd flow/low-level # 3. Run it uv run --no-project --with desflow flow_example.py ``` ```bash # 1. Install pip install desflow # 2. Download the example desflow examples get flow --api low-level cd flow/low-level # 3. Run it python flow_example.py ``` ```python ROUTES = { "pick": Router( {"when": [{"condition": "attr.gift == 1", "task": "wrap"}], "default": "pack"} ), "wrap": Router("pack"), # Weights draw from a generator, set in processes() "pack": Router({"weights": {"ship": 9, "pack": 1}}), "ship": Router(None), } SETS = {"wrap": {"wrapped": 1}} ``` The whole file is [`examples/low-level/flow_example.py`](https://github.com/jaehyeon-kim/desflow/blob/v1.3.0/examples/low-level/flow_example.py). # Stores and Containers: `DynamicStore` and `DynamicContainer` A resource is held and given back. Stores and containers hold things that tasks take away and add: items, or an amount. This page shows how to declare them, how tasks put and get, and what a live change does. ______________________________________________________________________ ## What It Is - A **store** holds items, each one a value of its own: parcels on a shelf waiting for a courier, orders in a buffer. A task puts an item in, and another takes the oldest out. - A **container** holds an amount: boxes in a bin, fuel in a tank, a stock level. A task takes some, and another adds some. Both have a capacity, or no limit. A task that takes waits while there is not enough, and a task that adds waits while there is no room. [Stock](https://jaehyeon.me/desflow/latest/learn/shop-logic/stock/index.md) uses a container in the shop. ______________________________________________________________________ ## How to Use It ### Declare Them A container has three settings. `current_cap` is its capacity, the largest amount it holds. `max_cap` is the largest capacity a live change can set. `level` is the amount it holds when the run starts, 0 when left out. A store has a `current_cap` and a `max_cap`, in whole items, and starts empty unless it lists `items` ([Start With Items and Serve by Priority](#start-with-items-and-serve-by-priority)). `run()` builds a `DynamicContainer` and a `DynamicStore` for each one the context declares. A store and a container cannot share a name, and no name is shared with a resource or a signal. A name with a dot or a space is refused, because an expression cannot name it, and so is a name with a character that an expression reads as another, such as `µ`. A capacity or `max_cap` below 0, `true`, or a fraction for a store's whole number is refused, naming the store or container, and so is a container `level` outside 0 to its capacity. A store's `priority` is `true` or `false`. ```yaml containers: # An amount: room for 100 boxes, 20 when the run starts stock: {current_cap: 100, max_cap: 100, level: 20} ``` ```yaml stores: # Items: room for 5 parcels, empty when the run starts parcels: {current_cap: 5, max_cap: 10} ``` ```python # An amount: room for 100 boxes, 20 when the run starts app.add_container("stock", current_cap=100, max_cap=100, level=20) ``` ```python # Items: room for 5 parcels, empty when the run starts app.add_store("parcels", current_cap=5, max_cap=10) ``` ```python env = DynamicRealtimeEnvironment(factor=0.0) env.registry.register_sim_parameter( SimParameter( sim_id="Shop", # An amount: room for 100 boxes, 20 when the run starts containers={"stock": ContainerConfig(current_cap=100, max_cap=100, level=20)}, # Items: room for 5 parcels, empty when the run starts stores={"parcels": CapacityConfig(current_cap=5, max_cap=10)}, ) ) stock = DynamicContainer(env, "Shop", "stock") # starts at the level above, 20 parcels = DynamicStore(env, "Shop", "parcels") ``` A `DynamicContainer` built with no `init` starts at the level its `ContainerConfig` gives. `init=` sets another. A store or container with no `current_cap` has no capacity limit, as `simpy.Store(env)` and `simpy.Container(env)` have: a put never waits for room. `current_cap: .inf` in YAML, or `float("inf")` in code, says the same. A `max_cap` alone gives the `current_cap`, and a `current_cap` alone gives the `max_cap`. A live update can give a store with no limit a capacity. A store's capacity is a whole number of items, so a live update with a fraction is refused and the old capacity stays. `.inf` or the text `"inf"` sets no limit again. A store or container with no limit publishes `capacity` as `null`. ### Take and Add A task takes with `get` and adds with `put`. For a container, each names the container and an `amount`. The amount can be a number, or an expression such as `payload.boxes` for a field of the previous task's payload. In the builder, it can also be a function of the task id and the previous task's payload. The amount is 1 when left out. For a store, each names the store. A `put` adds the task's finished payload as the item, or the value of its `item`, and a `get` takes the oldest item and passes it to the task's function as `item`. ```yaml pack_order: service: packing resource: packers # Takes the boxes the previous task's payload names, once it has a packer get: {container: stock, amount: payload.boxes} ``` ```yaml # Adds its finished payload to the store as an item put: {store: parcels} payload: {event_type: order_packed} ``` ```python # Takes the boxes the previous task's payload names, once it has a packer. # The amount is a number, an expression, or a function of the task id and the # previous task's payload, such as lambda task_id, payload: payload["boxes"]. @app.task( service_id="packing", resource_id="packers", get={"container": "stock", "amount": "payload.boxes"}, put={"store": "parcels"}, # adds the finished payload as an item ) def pack_order(task_id: int): return {"event_type": "order_packed"} # Takes the oldest parcel, waiting while the store is empty; `item` is that parcel @app.task(service_id="collecting", get={"store": "parcels"}) def collect(task_id: int, item): return {"event_type": "parcel_collected", "parcel": item["event_type"]} ``` ```python def pack(env, order_id): yield stock.get(2) # takes 2 boxes, waiting while fewer are left yield parcels.put({"order_id": order_id}) # waits while the store is full def collect_parcel(env): parcel = yield parcels.get() # waits while the store is empty print(f"collected order {parcel['order_id']}; {stock.level:g} boxes left") ``` `get(amount)`, `put(amount)`, `put(item)` and `get()` are SimPy events: yielding one waits until it succeeds, and a store's `get()` succeeds with the item. An `amount` that is not a finite number above 0 is refused, naming the container. A `put` with `item` adds that value in place of the payload: a constant, a mapping or a list, or a generator read as the put is made, including one nested in a mapping or a list. After a store `get`, the bare name `item` in an expression is the whole item the get took, and it lasts through the task's `next` chain. So `item: {gen: expr, expr: item}` puts the item that was taken into another store, and `item_priority` is the priority of the item a priority store gave. [Rank the Waiting Gets and Puts](#rank-the-waiting-gets-and-puts) shows both. A task with a resource gets its unit first and then takes its `get`, so it waits for stock while holding the unit. A task adds its `put` after its service time, then publishes the finished event. [Tasks and Processes](https://jaehyeon.me/desflow/latest/user-guide/tasks-and-processes/tasks/#what-apptask-does) lists every step. A `put` or `get` makes the task wait until it is granted. With `wait: false` (`"wait": False` in the builder), the task makes the request and goes on at once, as a SimPy `put` that is not yielded does. It publishes `finished` without waiting, and the request stays in the queue until it can be granted. Such a request follows these rules: - It is granted first in, first out, together with the requests that are waited for. - An interrupt, `on_interrupt: abandon` and `patience` never cancel it. - A run can end while it still waits, and a `drain` does not wait for it. - A `get` takes its item later and drops it. So it cannot use `item_field` or a function that declares `item`, and its `item.` can be read only in its own `filter`. - It is refused in a branch of a `wait`. The `pump` task of [Example: Fuel Dock](#example-fuel-dock) puts fuel into a tank this way. The third pump finds room for only 20 units of fuel, so its put stays queued. ### Start With Items and Serve by Priority A store can hold items when the run starts, such as parcels left from yesterday. `items` lists them in the order a get returns them. A store cannot start with more items than its `current_cap`: the blueprint or `add_store` is refused with the reason. A store with `priority` returns the item with the lowest `priority` value first, as SimPy's `PriorityStore` does. Its items are `[priority, item]` pairs, and a task's `put` gives each new item its `priority`. Items of equal priority come out in SimPy's heap order, which is not always the order they went in. A priority can be: - a number, or an expression such as `attr.priority` that gives one; - a list such as `[1, 2]`, ordered element by element, as a tuple is; - any other value that can be ordered against the others, such as a text. In the Low-level API a priority keeps the value it is given, so a text priority such as `"10"` sorts as text, before `"9"`. In the Builder and in YAML a string priority in a task put is an expression, so `"10"` gives the number 10, and a text priority such as `'P1'` comes from `attr.grade` or `payload.grade`. A starting item without a generator keeps its string priority as text. A number and a list, or a list and a tuple, in one store raise `ValueError` at the put that mixes them. A number and a text raise `TypeError` when the store compares the two, as in SimPy. ```yaml stores: parcels: current_cap: 10 max_cap: 10 # A courier takes the lowest priority value first; equal priorities leave in # SimPy's heap order priority: true # Left from yesterday: [priority, item] pairs, held before the first put items: - [2, {order: standard-0}] - [1, {order: express-0}] ``` ```yaml pack: # Each parcel's priority, read when it is put in the store put: {store: parcels, priority: attr.priority} payload: {order: standard} id_field: number ``` ```python app = SimulationContext(sim_id="Shop", factor=0.0) # A courier takes the lowest priority value first; equal priorities leave in # SimPy's heap order. # Left from yesterday: (priority, item) pairs, held before the first put. app.add_store( "parcels", current_cap=10, max_cap=10, priority=True, items=[(2, {"order": "standard-0"}), (1, {"order": "express-0"})], ) ``` A task's `put` takes the priority the same way: `put={"store": "parcels", "priority": "attr.priority"}`. ```python parcels = DynamicStore( env, "Shop", "parcels", priority=True, # Each pair is held as a PriorityItem items=[(2, {"order": "standard-0"}), (1, {"order": "express-0"})], ) def courier_process(env): first = yield parcels.get() # a PriorityItem; .item is the parcel print(f"collected {first.item['order']}") # A put of your own wraps the item the same way yield parcels.put(parcels.wrap({"order": "express-1"}, 1)) ``` A low-level priority store holds `simpy.PriorityItem`s. `wrap(item, priority)` returns a plain `PriorityItem(priority, item)`, the same as writing it by hand, and the builder and YAML use it. Equal priorities leave in SimPy's heap order either way. Assigning a list to a store's `items` replaces them, and a waiting get is served at the next put or get, not at the assignment. A `get` on a priority store takes no `priority` of its own and is refused with one: the item's priority decides the order. [Priorities](https://jaehyeon.me/desflow/latest/learn/shop-logic/priorities/index.md) compares priority storage with a resource's priority queue. ### Pick an Item, or Give Up Waiting A store `get` can take a `filter`, a condition that picks which item it takes, as SimPy's `FilterStore` does. The filter reads the item on offer as `item.`, and every name that other conditions read, such as `attr.area` for the entity's own attribute. The get takes the oldest item that matches, and waits while none does. A waiting get that matches nothing does not stop a later get from taking an item that matches it. A priority store takes no filter, because SimPy has no store that both ranks and filters. The blueprint or `run()` refuses a filter on one, and names the task. A task's `patience` covers its whole wait: for its `wait`, then its resource, then its `get`. When it runs out, the task publishes `reneged` and its get is cancelled, so it takes nothing later. In the low-level API, `cancel()` on a put or get event that has not succeeded takes it out of its queue, as in SimPy: a cancelled get takes nothing, and a cancelled put adds nothing. In YAML, `item_field` adds the item that the task's get took to its payload. A builder function receives the item as `item`: ```yaml tasks: pack: service: packing resource: packers # The parcel goes on the shelf as the payload, with its area. put: {store: parcels} payload: {event_type: order_packed} attributes: [area] collect: # The oldest parcel for the courier's own area. get: {store: parcels, filter: item.area == attr.area} # A courier leaves without a parcel after 20 seconds. patience: 20 s # The parcel the courier took, in the finished event. item_field: parcel payload: {event_type: parcel_collected} ``` ```python @app.task( # The oldest parcel for the courier's own area get={"store": "parcels", "filter": "item.area == attr.area"}, # A courier leaves without a parcel after 20 seconds patience=20, ) def collect(task_id, context, item): """`item` is the parcel the courier took.""" return {"event_type": "parcel_collected", "parcel": item} ``` A filter can also be a function of the item: `"filter": lambda parcel: parcel["area"] == "north"`. ```python def collect(env, sampler, shop, key, area, task_id): """Takes the oldest parcel for its own area, or leaves after 20 seconds.""" def publish(value): env.publish_event(key, value, task="collect", instance=task_id) flow = key.rsplit("-", 1)[0] env.stats.flow_started(flow) # the courier enters the shop publish({"status": "queued"}) env.stats.task_queued("collect", task_id) get = shop["parcels"].get(filter=lambda parcel: parcel["area"] == area) yield get | env.timeout(20) if not get.triggered: get.cancel() # out of the queue, so it takes no parcel later publish({"status": "reneged"}) env.stats.task_reneged("collect", task_id) env.stats.flow_ended(flow) return publish({"status": "started"}) env.stats.task_started("collect", task_id) publish({"event_type": "parcel_collected", "parcel": get.value}) env.stats.task_finished("collect", task_id) env.stats.flow_finished(flow) ``` A store or container `get` can be a branch of a `wait`, and a group `wait: {when: , of: {...}}` ends when the expression holds. It reads `done_count`, the number of branches done, and cancels the requests that did not win, as `any` does. [Wait, Signals and Child Flows](https://jaehyeon.me/desflow/latest/user-guide/tasks-and-processes/signals-and-waiting/#wait-signals-and-child-flows) describes the groups. `item.` can also be read in the task's `put` and `next`, after its get. [Filtered Inventory](https://jaehyeon.me/desflow/latest/learn/shop-logic/filtered-inventory/index.md) uses a filter and patience on a shelf of shirts. ### Rank the Waiting Gets and Puts Gets and puts that wait are served first in, first out. `get_queue` and `put_queue` rank them instead, on a store or a container, as a resource's `queue` ranks its requests: each is `{rank: , ties: fifo or lifo}`. The expression is read once as each get or put is made, in the scope of the task that makes it. A rank that is NaN or text fails the task, with a message that names the task and the value. The lowest rank is served first, and `ties` serves equal ranks oldest first (`fifo`, the default) or latest first (`lifo`). They rank the waiters, not the items: a store's `priority` still ranks the items. A `type` that sets its own order refuses both, as [Custom Store and Container Types](#custom-store-and-container-types) says. A container serves its waiting gets in queue order and stops at the first one its level cannot meet, as SimPy's `Container` does. A get that waits for more than the container holds therefore blocks the gets behind it, even a small one that the level could serve. ```yaml stores: # A shelf of two, served by priority. The puts that wait for room go in rank order, # and the latest of equal ranks goes first. The gets go in rank order too. returns: current_cap: 2 max_cap: 2 priority: true put_queue: {rank: attr.rank, ties: lifo} get_queue: {rank: attr.rank} archive: {} containers: # The gets and the puts that wait go in rank order, the oldest of equal ranks first stock: current_cap: 10 max_cap: 10 get_queue: {rank: attr.rank} put_queue: {rank: attr.rank} # A family of two containers, crates[0] and crates[1], made when the run starts crates: {current_cap: 5, max_cap: 5, family: true, members: 2} ``` ```yaml return_parcel: # The item put on the shelf is written here, and not the payload: a mapping, with # a generator inside it. The priority is read as the put is made. put: store: returns priority: attr.rank item: parcel: {gen: sequence} rank: {gen: attr, name: rank} # putting() lists the puts that wait for room at a store or container payload: event_type: parcel_returned waiting: {gen: expr, expr: "len(putting(returns))"} file_return: get: {store: returns} # item is the whole item the get took, and it goes into the archive as it is put: store: archive item: {gen: expr, expr: item} # item_priority is the priority of the item a priority store gave payload: event_type: parcel_filed priority: {gen: expr, expr: item_priority} ``` ```python # A shelf of two, served by priority. The puts that wait for room go in rank order, # and the latest of equal ranks goes first. The gets go in rank order too. app.add_store( "returns", current_cap=2, max_cap=2, priority=True, put_queue={"rank": "attr.rank", "ties": "lifo"}, get_queue={"rank": "attr.rank"}, ) app.add_store("archive") # The gets and the puts that wait go in rank order, the oldest of equal ranks first app.add_container( "stock", current_cap=10, max_cap=10, get_queue={"rank": "attr.rank"}, put_queue={"rank": "attr.rank"}, ) # A family of two containers, crates[0] and crates[1], made when the run starts app.add_container("crates", current_cap=5, max_cap=5, family=True, members=2) ``` ```python returned = Template( { "event_type": "parcel_returned", # putting() lists the puts that wait for room at a store or container "waiting": {"gen": "expr", "expr": "len(putting(returns))"}, }, name="tasks.return_parcel", ) @app.task( # The item put on the shelf is written here, and not the payload: a mapping, with # a generator inside it. The priority is read as the put is made. put={ "store": "returns", "priority": "attr.rank", "item": { "parcel": {"gen": "sequence"}, "rank": {"gen": "attr", "name": "rank"}, }, } ) def return_parcel(task_id): return returned filed = Template( { "event_type": "parcel_filed", # item_priority is the priority of the item a priority store gave "priority": {"gen": "expr", "expr": "item_priority"}, }, name="tasks.file_return", ) # item is the whole item the get took, and it goes into the archive as it is @app.task( get={"store": "returns"}, put={"store": "archive", "item": {"gen": "expr", "expr": "item"}}, ) def file_return(task_id): return filed ``` ```python env = DynamicRealtimeEnvironment(factor=0.0) env.registry.register_sim_parameter( SimParameter( sim_id="Shop", stores={"returns": CapacityConfig(current_cap=1, max_cap=1)} ) ) # The waiting puts go in rank order, and the latest of equal ranks goes first shelf = DynamicStore(env, "Shop", "returns", put_ties="lifo") taken = [] def filing(env): yield shelf.put("a") # fills the shelf of one for parcel, rank in (("b", 2), ("c", 1), ("d", 1)): shelf.put(parcel, rank=rank) # each waits for room, with its rank for _ in range(4): taken.append((yield shelf.get())) ``` `DynamicStore` and `DynamicContainer` take `get_ties` and `put_ties`, and a `get` or `put` takes the `rank` keyword. A get or put with no `rank` has rank 0. ### Custom Store and Container Types A store or container of your own class changes how items or amounts go in and out. Subclass `desflow.StoreBase` (a `simpy.Store`) or `desflow.ContainerBase` (a `simpy.Container`) and override `_do_put` or `_do_get`, set `PutQueue` or `GetQueue`, or bind `put` and `get` to event classes of your own, as in SimPy. The constructor is SimPy's, `(env, capacity=inf)` for a store and `(env, capacity=inf, init=0)` for a container. Name the class with `type: !python module.Class` in a blueprint, `type=` in `add_store` and `add_container`, or `type=` in `DynamicStore` and `DynamicContainer`. ```yaml stores: # A lane of your own type; it holds two trucks lane: {current_cap: 2, max_cap: 2, type: !python fuel_dock_types.Lane} containers: # A tank of 100: two pumps fill 80 of it, so the third put waits for room tank: {current_cap: 100, max_cap: 100} arrivals: diesel_trucks: dist: constant value: 3 spawn: park attributes: {fuel: diesel} petrol_trucks: dist: constant value: 5 spawn: park attributes: {fuel: petrol} crew: {dist: constant, value: 7, spawn: unload} tankers: {dist: constant, value: 4, spawn: pump} marshals: {dist: constant, value: 15, spawn: marshal} tasks: park: # The truck waits outside while the lane is full put: {store: lane} payload: {event_type: truck_parked} attributes: [fuel] unload: # The newest truck in the lane, because of the lane's type get: {store: lane} item_field: truck payload: {event_type: truck_unloaded} pump: # The tank truck starts the pump and leaves; it does not wait for the put put: {container: tank, amount: 40, wait: false} payload: {event_type: pump_started} marshal: # Waits until a truck is held outside the full lane wait: {condition: putters.lane >= 1} payload: {event_type: overflow_bay_called} ``` The class is in [`examples/yaml/advanced/fuel_dock_types.py`](https://github.com/jaehyeon-kim/desflow/blob/v1.3.0/examples/yaml/advanced/fuel_dock_types.py), next to the blueprint, which `!python` finds first. ```python class Lane(StoreBase): """A store that gives back the newest item, like trucks parked nose to tail.""" def _do_get(self, event): if self.items: event.succeed(self.items.pop()) app = ( SimulationContext(sim_id="Dock", factor=0, random_seed=42) .add_egress(ConsoleEgress()) # A lane of your own type; it holds two trucks .add_store("lane", current_cap=2, max_cap=2, type=Lane) # A tank of 100: two pumps fill 80 of it, so the third put waits for room .add_container("tank", current_cap=100, max_cap=100) .add_arrival( "diesel_trucks", dist="constant", value=3, attributes={"fuel": "diesel"} ) .add_arrival( "petrol_trucks", dist="constant", value=5, attributes={"fuel": "petrol"} ) .add_arrival("crew", dist="constant", value=7) .add_arrival("tankers", dist="constant", value=4) .add_arrival("marshals", dist="constant", value=15) ) # The truck waits outside while the lane is full @app.task(put={"store": "lane"}) def park(task_id, context, entity): return {"event_type": "truck_parked", "fuel": entity.attributes["fuel"]} # The newest truck in the lane, because of the lane's type @app.task(get={"store": "lane"}) def unload(task_id, context, item): return {"event_type": "truck_unloaded", "truck": item} # The tank truck starts the pump and leaves; it does not wait for the put @app.task(put={"container": "tank", "amount": 40, "wait": False}) def pump(task_id, context, entity): return {"event_type": "pump_started"} # Waits until a truck is held outside the full lane @app.task(wait={"condition": "putters.lane >= 1"}) def marshal(task_id, context, entity): return {"event_type": "overflow_bay_called"} ``` ```python class Lane(StoreBase): """A store that gives back the newest item, like trucks parked nose to tail.""" def _do_get(self, event): if self.items: event.succeed(self.items.pop()) def build(env): """Builds the lane and the tank, in the builder's order.""" return { # A lane of your own type; it holds two trucks "lane": DynamicStore(env, "Dock", "lane", type=Lane), # The tank holds 100, the capacity in the parameters "tank": DynamicContainer(env, "Dock", "tank"), } ``` A container type is written the same way, from `ContainerBase`. This bin counts the puts it grants, and a `Transfer` gives a task its `get` as an object, the form the dictionaries above are read into: `type` names the class in a module beside the file, here a copy of the bin in `shop_logic.py`: ```yaml # A container of your own class, from shop_logic.py beside the blueprint labels: {current_cap: 10, max_cap: 10, level: 10, type: !python shop_logic.CountedBin} ``` ```python class CountedBin(ContainerBase): """A container that counts the puts it grants.""" def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.restocks = 0 def _do_put(self, event): granted = super()._do_put(event) if event.triggered: self.restocks += 1 return granted app.add_container("labels", current_cap=10, level=10, type=CountedBin) # A task's get or put can also be a Transfer, built once and given to several tasks one_label = Transfer(container="labels", amount=1) @app.task(get=one_label) def print_label(task_id: int): return {"event_type": "label_printed"} ``` A low-level model builds an instance of the class itself, as the Low-level tab above builds the lane and the tank. The statistics and the conditions follow every change to a store's items or a container's level made by `_do_put` or `_do_get`, whether the override calls `super()` or not, and each change is reported to them once. `ContainerBase` compares the level before and after, so an override that returns `True` without changing the level reports nothing. A change to the length of `put_queue` or `get_queue` is reported to the conditions that read `putters.` or `getters.`. A queue class must support `len()` and `remove()`. A `cancel()` is reported from the event classes, so it works with a queue class of your own. A task's `put` stores its payload as the item, and its `get` passes the item on, unwrapped, whatever the type. A `type` cannot be given with `priority`: a type sets its own order, so subclass `StoreBase` and `simpy.PriorityStore` for a ranked store. A `get` with a `filter` needs a type that subclasses `simpy.FilterStore`, and a blueprint or `run()` without such a type is refused, naming the task. A live capacity update reaches a type of your own as it does the default. ### Registry Paths, Readings and Conditions A container has three registry paths, `.containers..current_cap`, `.max_cap` and `.level`. A store has `.stores..current_cap` and `.max_cap`. With statistics at the `minimal` level or above, each publishes four readings, such as `Shop.stats.containers.stock.level`: | Reading | Store | Container | | ----------------- | ---------------------------- | ------------------------------- | | `capacity` | items it can hold | largest amount | | `level` | items held | amount held | | `getters_waiting` | tasks waiting to get an item | tasks waiting to take an amount | | `putters_waiting` | tasks waiting to put an item | tasks waiting to add an amount | `basic` adds `level_avg`, the level averaged over time. [Statistics](https://jaehyeon.me/desflow/latest/user-guide/results/statistics/index.md) describes it. Below are the readings of [`stores_containers.yaml`](https://github.com/jaehyeon-kim/desflow/blob/v1.3.0/docs/snippets/yaml/stores_containers.yaml), the blueprint whose parts this page shows. They are taken at 30 and 40 simulation seconds, before and after the stock count that [Under Live Changes](#under-live-changes) shows: ```text [TEL] {'sim_ts': 30.0, 'timestamp': '...', 'path_id': 'Shop.stats.stores.parcels.level', 'value': 3} [TEL] {'sim_ts': 30.0, 'timestamp': '...', 'path_id': 'Shop.stats.stores.parcels.putters_waiting', 'value': 0} [TEL] {'sim_ts': 30.0, 'timestamp': '...', 'path_id': 'Shop.stats.containers.stock.level', 'value': 0} [TEL] {'sim_ts': 30.0, 'timestamp': '...', 'path_id': 'Shop.stats.containers.stock.getters_waiting', 'value': 2} [TEL] {'sim_ts': 40.0, 'timestamp': '...', 'path_id': 'Shop.stats.stores.parcels.level', 'value': 5} [TEL] {'sim_ts': 40.0, 'timestamp': '...', 'path_id': 'Shop.stats.stores.parcels.putters_waiting', 'value': 0} [TEL] {'sim_ts': 40.0, 'timestamp': '...', 'path_id': 'Shop.stats.containers.stock.level', 'value': 40} [TEL] {'sim_ts': 40.0, 'timestamp': '...', 'path_id': 'Shop.stats.containers.stock.getters_waiting', 'value': 0} ``` At 30 seconds the bin is empty and two orders wait for boxes. At 40 seconds the stock count has put 50 boxes in, those two have taken theirs, and the shelf of parcels is full, with no packed order waiting for room. A condition in a task's `next` reads a level as `level.`, so an order can go to backorder when `level.stock == 0`, as [Task Flow](https://jaehyeon.me/desflow/latest/user-guide/model-parts/task-flow/index.md) shows. A condition can also read how many tasks wait at a store or container, and what a store holds: | Name | Reads | | ------------------------------------------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `putters.`, `getters.` | the number of puts or gets waiting, not counting one that is granted at once, as the `putters_waiting` and `getters_waiting` readings; `len(put_queue)` and `len(get_queue)` in the low-level API | | `count()` | the number of items the store holds, as `level.` | | `count(, )` | how many items meet the condition, which reads `item.` of each | | `items()`, `items(, item.)` | the list of items, or that field of each; a priority store gives its items unwrapped | | `putting()`, `getting()` | the puts and gets that wait, as a list of mappings with `entity` and, for a put, `item` or `amount`; `len()` counts them, as `putters.` does | | `item`, `item_priority` | the whole item the task's store `get` took, and the priority a priority store gave it | | `peek()` | the simulation time of the next scheduled event, infinity when there is none | `in` and `not in` read an `items(...)` list, as in `payload.sku in items(shelf, item.sku)`, which is true while the shelf holds that sku. The store is a bare name, and `count` and `items` cannot be nested inside each other. The names are checked at load: each must name a store, and `putters.` and `getters.` may also name a container. A condition that reads one of these names is checked again when a put or get joins or leaves a queue. A condition that reads none of them, such as `level.stock == 0`, is not checked again for a queue change. A queue change is not a change of level, so `level_avg` does not move. The `marshal` task of [Example: Fuel Dock](#example-fuel-dock) waits on `putters.lane >= 1`. ______________________________________________________________________ ## How It Works A container keeps a level between 0 and its capacity, with a queue of getters and a queue of putters. A `get` succeeds as soon as the level covers its amount, and a `put` as soon as there is room for all of it. Until then, each waits in its queue, in the order it arrived: A store keeps a list of items, up to its capacity. A `put` adds an item at the end, and a `get` takes the first, so items leave in the order they came. A `get` with a filter takes the first item its filter accepts: **SimPy and desflow.** desflow builds on three SimPy classes. A container is SimPy's `Container`. A store is a `FilterStore`, which serves its gets as `Store` does while no waiting get has a filter. A priority store is a `PriorityStore`, which hands out the lowest item first. A full put that waits for room and an empty get that waits for an item or an amount are checked against plain SimPy in all three APIs. [SimPy Compatibility](https://jaehyeon.me/desflow/latest/simpy/compatibility/index.md) lists the checks. SimPy's capacities are fixed when they are created, and desflow's follow the registry. desflow also keeps the registry's `level` in step with every put and get, and reports each change to the statistics. [SimPy and desflow](https://jaehyeon.me/desflow/latest/simpy/index.md) compares the two. ______________________________________________________________________ ## Under Live Changes - **Capacity** follows `current_cap`, clamped to between 0 and `max_cap`. A higher capacity wakes waiting putters. A capacity below what is held destroys nothing: puts wait until enough has been taken. - **A container's level** is set by an update to its `level` path, as a stock count or a restock from outside would. The new level is clamped to between 0 and `current_cap`, with a warning, and it wakes both queues: a higher level serves waiting getters, and a lower one can make room for putters. - **A store or container with no limit** can be given a number as `current_cap` during a run, and `.inf` or the text `"inf"` sets no limit again. Lowering it destroys nothing, as the Capacity item above says. - **`current_cap` is the capacity, not a level.** A model that used a container's `current_cap` as a level, such as the wear of a roll, moves it to `level`. The stock count in [`stores_containers.yaml`](https://github.com/jaehyeon-kim/desflow/blob/v1.3.0/docs/snippets/yaml/stores_containers.yaml), in each way of writing: ```yaml scenario: # A stock count at 30 seconds: the level path sets what the container holds - {at: 30, path: Shop.containers.stock.level, value: 50} ``` ```python def stock_count(context: SimulationContext): """A stock count at 30 seconds: the level path sets what the container holds.""" yield context.env.timeout(30) context.env.registry.update("Shop.containers.stock.level", 50) app.add_process(stock_count) ``` ```python def stock_count_process(env): """A stock count: sets the level; waiting gets and puts are woken.""" yield env.timeout(30) env.registry.update("Shop.containers.stock.level", 50) ``` ______________________________________________________________________ ## Stability and Limits - **A container that never refills** blocks its getters for good, and a task that waits for stock while holding a resource blocks the resource too. Supply has to keep up with demand, as [Stock](https://jaehyeon.me/desflow/latest/learn/shop-logic/stock/index.md) shows. - **Whole items.** A store's capacity is a whole number or no limit, and it holds items, not amounts. - **A put or get with `wait: false`** is never cancelled, so a supply that outpaces its consumers grows the queue without end. A run drops what is still waiting when it ends. - **A filter checks every waiting get on each put.** For a store with many waiting gets and a filter that rarely matches, the work grows in proportion to both, as SimPy's `FilterStore` does. - **One store or container per get or put.** A task has at most one `get` and one `put`. ______________________________________________________________________ ## Example: Stock, Parcels and Express Orders The `stock` example combines a container and a store. Packing takes a box from a container and puts the parcel in a store, which starts with two parcels from yesterday. A courier collects the parcels. Express orders go first at the packers, and also at the courier, because the parcels store is a priority store. The stock runs out, so packing waits until a restock at 40 seconds sets the level to 30 boxes. It needs no Docker service and ends on its own. The tutorial page [Stock](https://jaehyeon.me/desflow/latest/learn/shop-logic/stock/index.md) teaches these features step by step. **Quick Start** `desflow examples get` downloads the example at the release you install, into a folder of its own. Pick uv or pip: ```bash # 1. Install uv tool install desflow # 2. Download the example desflow examples get stock --api yaml cd stock/yaml # 3. Run it desflow run stock.yaml ``` ```bash # 1. Install pip install desflow # 2. Download the example desflow examples get stock --api yaml cd stock/yaml # 3. Run it desflow run stock.yaml ``` ```yaml tasks: pack: service: packing resource: packers # Each order's own attribute, read when it joins the queue. priority: attr.priority # Takes one box once it has a packer, and waits while the stock is empty. get: {container: stock, amount: 1} # Puts the finished payload in the store as a parcel of the order's priority. put: {store: parcels, priority: attr.priority} payload: {event_type: order_packed} attributes: [priority] ``` The whole file is [`examples/yaml/stock.yaml`](https://github.com/jaehyeon-kim/desflow/blob/v1.3.0/examples/yaml/stock.yaml). **Quick Start** `desflow examples get` downloads the example at the release you install, into a folder of its own. Pick uv or pip: ```bash # 1. Install uv tool install desflow # 2. Download the example desflow examples get stock --api builder cd stock/builder # 3. Run it uv run --no-project --with desflow stock_example.py ``` ```bash # 1. Install pip install desflow # 2. Download the example desflow examples get stock --api builder cd stock/builder # 3. Run it python stock_example.py ``` ```python @app.task( service_id="packing", resource_id="packers", # Each order's own attribute, read when it joins the queue priority="attr.priority", # Takes one box once it has a packer, and waits while the stock is empty get={"container": "stock", "amount": 1}, # Puts the finished payload in the store as a parcel of the order's priority put={"store": "parcels", "priority": "attr.priority"}, ) def pack(task_id, context, entity): """Packs one order.""" return {"event_type": "order_packed", "priority": entity.attributes["priority"]} ``` The whole file is [`examples/builder/stock_example.py`](https://github.com/jaehyeon-kim/desflow/blob/v1.3.0/examples/builder/stock_example.py). **Quick Start** `desflow examples get` downloads the example at the release you install, into a folder of its own. Pick uv or pip: ```bash # 1. Install uv tool install desflow # 2. Download the example desflow examples get stock --api low-level cd stock/low-level # 3. Run it uv run --no-project --with desflow stock_example.py ``` ```bash # 1. Install pip install desflow # 2. Download the example desflow examples get stock --api low-level cd stock/low-level # 3. Run it python stock_example.py ``` ```python def pack(env, sampler, shop, key, priority, task_id): """Queued, a packer by priority, a box from stock, packing, then a parcel.""" path_id = "Shop.service.packing" def publish(value): env.publish_event(key, value, task="pack", instance=task_id) publish( {"path_id": path_id, "sim_id": "Shop", "service": "packing", "status": "queued"} ) env.stats.task_queued("pack", task_id) # counted as in progress with shop["packers"].request(priority=priority) as req: yield req # Waits while the stock is empty yield shop["stock"].get(1) publish( { "path_id": path_id, "sim_id": "Shop", "service": "packing", "status": "started", } ) env.stats.task_started("pack", task_id) payload = {"event_type": "order_packed", "priority": priority} yield env.timeout(sampler.sample(env.registry.get_config(path_id))) # Waits while the store is full; wrap ranks the parcel by its priority yield shop["parcels"].put(shop["parcels"].wrap(payload, priority)) publish(payload) env.stats.task_finished("pack", task_id) ``` The whole file is [`examples/low-level/stock_example.py`](https://github.com/jaehyeon-kim/desflow/blob/v1.3.0/examples/low-level/stock_example.py). ______________________________________________________________________ ## Example: Filtered Inventory The `filtered-inventory` example combines a filter and patience. Packed orders go on one shelf as parcels for the north or the south. Each courier takes the oldest parcel for its own area, or leaves without one after 20 seconds. It needs no Docker service and ends on its own after 120 simulation seconds. The tutorial page [Filtered Inventory](https://jaehyeon.me/desflow/latest/learn/shop-logic/filtered-inventory/index.md) teaches these features step by step. **Quick Start** `desflow examples get` downloads the example at the release you install, into a folder of its own. Pick uv or pip: ```bash # 1. Install uv tool install desflow # 2. Download the example desflow examples get filtered-inventory --api yaml cd filtered-inventory/yaml # 3. Run it desflow run filtered_inventory.yaml ``` ```bash # 1. Install pip install desflow # 2. Download the example desflow examples get filtered-inventory --api yaml cd filtered-inventory/yaml # 3. Run it desflow run filtered_inventory.yaml ``` The whole file is [`examples/yaml/filtered_inventory.yaml`](https://github.com/jaehyeon-kim/desflow/blob/v1.3.0/examples/yaml/filtered_inventory.yaml). **Quick Start** `desflow examples get` downloads the example at the release you install, into a folder of its own. Pick uv or pip: ```bash # 1. Install uv tool install desflow # 2. Download the example desflow examples get filtered-inventory --api builder cd filtered-inventory/builder # 3. Run it uv run --no-project --with desflow filtered_inventory_example.py ``` ```bash # 1. Install pip install desflow # 2. Download the example desflow examples get filtered-inventory --api builder cd filtered-inventory/builder # 3. Run it python filtered_inventory_example.py ``` The whole file is [`examples/builder/filtered_inventory_example.py`](https://github.com/jaehyeon-kim/desflow/blob/v1.3.0/examples/builder/filtered_inventory_example.py). **Quick Start** `desflow examples get` downloads the example at the release you install, into a folder of its own. Pick uv or pip: ```bash # 1. Install uv tool install desflow # 2. Download the example desflow examples get filtered-inventory --api low-level cd filtered-inventory/low-level # 3. Run it uv run --no-project --with desflow filtered_inventory_example.py ``` ```bash # 1. Install pip install desflow # 2. Download the example desflow examples get filtered-inventory --api low-level cd filtered-inventory/low-level # 3. Run it python filtered_inventory_example.py ``` The whole file is [`examples/low-level/filtered_inventory_example.py`](https://github.com/jaehyeon-kim/desflow/blob/v1.3.0/examples/low-level/filtered_inventory_example.py). ______________________________________________________________________ ## Example: Fuel Dock The `fuel-dock` example combines the parts of this page: - Fuel trucks wait in a lane of your own type, which gives back the newest truck first. - A crew unloads one truck every 7 seconds. - A tank truck puts fuel into a tank that holds 100 units, without waiting for the put. Once the tank is nearly full, the put waits in the tank's queue. - A marshal calls the overflow bay once a truck waits outside the full lane. It needs no Docker service and ends on its own after 40 simulation seconds. **Quick Start** `desflow examples get` downloads the example at the release you install, into a folder of its own. Pick uv or pip: ```bash # 1. Install uv tool install desflow # 2. Download the example desflow examples get fuel-dock --api yaml cd fuel-dock/yaml # 3. Run it desflow run fuel_dock.yaml ``` ```bash # 1. Install pip install desflow # 2. Download the example desflow examples get fuel-dock --api yaml cd fuel-dock/yaml # 3. Run it desflow run fuel_dock.yaml ``` The whole files are [`examples/yaml/advanced/fuel_dock.yaml`](https://github.com/jaehyeon-kim/desflow/blob/v1.3.0/examples/yaml/advanced/fuel_dock.yaml) and [`examples/yaml/advanced/fuel_dock_types.py`](https://github.com/jaehyeon-kim/desflow/blob/v1.3.0/examples/yaml/advanced/fuel_dock_types.py). **Quick Start** `desflow examples get` downloads the example at the release you install, into a folder of its own. Pick uv or pip: ```bash # 1. Install uv tool install desflow # 2. Download the example desflow examples get fuel-dock --api builder cd fuel-dock/builder # 3. Run it uv run --no-project --with desflow fuel_dock_example.py ``` ```bash # 1. Install pip install desflow # 2. Download the example desflow examples get fuel-dock --api builder cd fuel-dock/builder # 3. Run it python fuel_dock_example.py ``` The whole file is [`examples/builder/fuel_dock_example.py`](https://github.com/jaehyeon-kim/desflow/blob/v1.3.0/examples/builder/fuel_dock_example.py). **Quick Start** `desflow examples get` downloads the example at the release you install, into a folder of its own. Pick uv or pip: ```bash # 1. Install uv tool install desflow # 2. Download the example desflow examples get fuel-dock --api low-level cd fuel-dock/low-level # 3. Run it uv run --no-project --with desflow fuel_dock_example.py ``` ```bash # 1. Install pip install desflow # 2. Download the example desflow examples get fuel-dock --api low-level cd fuel-dock/low-level # 3. Run it python fuel_dock_example.py ``` The whole file is [`examples/low-level/fuel_dock_example.py`](https://github.com/jaehyeon-kim/desflow/blob/v1.3.0/examples/low-level/fuel_dock_example.py). # Tasks and Processes This page is the map of the section: what a task and a process are, and which page shows what. ______________________________________________________________________ ## What It Is A **task** is what one entity does: an order being packed, a return being logged. A **process** is anything else that runs over time: packers going on a break every hour, a speed that drifts, a shift plan. Both are SimPy generators, functions that `yield` to wait. The builder and YAML write the common ones for you, and the low-level API writes them by hand. ______________________________________________________________________ ## Pages in This Section - [Tasks](https://jaehyeon.me/desflow/latest/user-guide/tasks-and-processes/tasks/index.md): write a task, its keys, how an order leaves the line, what a task does when it is interrupted, what `run()` does and what a task does step by step. - [Processes](https://jaehyeon.me/desflow/latest/user-guide/tasks-and-processes/processes/index.md): run work alongside the tasks that belongs to no entity. - [Signals and Waiting](https://jaehyeon.me/desflow/latest/user-guide/tasks-and-processes/signals-and-waiting/index.md): wait for signals, conditions and child flows, start flows, and run actions when an event happens. - [Failures](https://jaehyeon.me/desflow/latest/user-guide/tasks-and-processes/failures/index.md): when a task fails, what a failure does, and what happens to one nobody handles. ______________________________________________________________________ ## How to Use It Pick the page by the job: | To do this | Read | | ----------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------- | | Write the work one order does, and the records it publishes | [Tasks](https://jaehyeon.me/desflow/latest/user-guide/tasks-and-processes/tasks/index.md) | | Let an order give up waiting, or turn it away | [Tasks](https://jaehyeon.me/desflow/latest/user-guide/tasks-and-processes/tasks/#leave-the-line) | | Choose what an order does after a task | [Task Flow](https://jaehyeon.me/desflow/latest/user-guide/model-parts/task-flow/index.md) | | Run a break, a drift or a schedule | [Processes](https://jaehyeon.me/desflow/latest/user-guide/tasks-and-processes/processes/index.md) | | Make a task wait for another task, a signal or a time | [Signals and Waiting](https://jaehyeon.me/desflow/latest/user-guide/tasks-and-processes/signals-and-waiting/index.md) | | Handle a task that cannot finish | [Failures](https://jaehyeon.me/desflow/latest/user-guide/tasks-and-processes/failures/index.md) | ______________________________________________________________________ ## How It Works `run()` builds the environment, registers the parameters, builds the resources, stores and containers, and starts the arrivals and processes. [What run() Does](https://jaehyeon.me/desflow/latest/user-guide/tasks-and-processes/tasks/#what-run-does) lists the steps in order, and [What @app.task Does](https://jaehyeon.me/desflow/latest/user-guide/tasks-and-processes/tasks/#what-apptask-does) lists the steps of one task. The diagram follows one task instance through its eight steps. Watch the box with the thick outline move along the steps, and the records it has published grow underneath. Each box names the keys that act at that step. A step whose keys the task does not set passes at once: a task with no `wait` does not wait, and a task with no `batch` joins no batch. The instance publishes `queued` when it has something to wait for: a resource, a `get`, a `wait`, a `seize` or a `batch`. It publishes `started` before its work, and `finished` or `failed` when it ends. A balk ends it at the first step with `balked`, and a renege ends it while it waits with `reneged`. The last step starts the next task as a new instance for the same entity, in the same SimPy process. # Tasks A **task** is what one entity does: an order being packed, a return being logged. This page shows how to write a task, which keys a task has, how an order leaves the line, what a task does when it is interrupted, what `run()` does with tasks, and what a task does step by step. [Processes](https://jaehyeon.me/desflow/latest/user-guide/tasks-and-processes/processes/index.md) shows work that does not belong to one entity. ______________________________________________________________________ ## What It Is A task is a SimPy generator: a function that `yield`s to wait. The builder and YAML write the common ones for you, and the low-level API writes them by hand. A task waits for what it needs, does its work for a sampled time, publishes an event at each step, and may lead to the next task. ______________________________________________________________________ ## How to Use It ### A Task A task with a service and a resource asks for a unit of the resource, holds it for a time drawn from the service, and releases it. A task with neither takes no time and holds nothing: it publishes its payload at once. Such a task suits a step that only records an event, such as logging a return. ```yaml tasks: pack_order: service: packing # how long the work takes resource: packers # what it holds while it works payload: {event_type: order_packed} # the finished event's value next: print_label # the task that follows; Task Flow has the other forms return_logged: # No service and no resource: publishes its payload at once payload: {event_type: return_logged} ``` A `payload` mapping may hold generated fields. This task adds a `delivery` to the finished event, standard for nine orders in ten and express for the tenth: ```yaml # A payload with generated fields: nine orders in ten are standard, one is express pack_with_delivery: service: packing resource: packers payload: event_type: order_packed delivery: gen: weighted options: {standard: 0.9, express: 0.1} ``` ```python @app.task(service_id="packing", resource_id="packers", next="print_label") def pack_order(task_id: int): # Runs when the order gets a packer, before the packing time. # The returned dict is the finished event's value. return {"event_type": "order_packed"} @app.task() # no service and no resource: publishes at once def return_logged(task_id: int): return {"event_type": "return_logged"} ``` The function is called with the task id and whatever the caller passes. It also receives `entity`, `upstream` and `item` by keyword when it declares a parameter of that name: the entity, what the previous task handed on, and what a store `get` took. A function that declares none of them is called without them. A function that returns a `Template` gives the same generated fields as the YAML tab: ```python # A payload with generated fields: nine orders in ten are standard, one is express delivery = Template( { "event_type": "order_packed", "delivery": {"gen": "weighted", "options": {"standard": 0.9, "express": 0.1}}, }, name="tasks.pack_with_delivery", ) @app.task(service_id="packing", resource_id="packers") def pack_with_delivery(task_id: int): return delivery ``` ```python def pack_order_process(env, sampler, packers, key, task_id, label_ids): """What @app.task does, by hand.""" path_id = "Shop.service.packing" def publish(value): env.publish_event(key, value, task="pack_order", instance=task_id) publish( {"path_id": path_id, "sim_id": "Shop", "service": "packing", "status": "queued"} ) with packers.request() as request: yield request publish( { "path_id": path_id, "sim_id": "Shop", "service": "packing", "status": "started", } ) payload = {"event_type": "order_packed"} yield env.timeout(sampler.sample(env.registry.get_config(path_id))) publish(payload) # next: print_label, a new instance for the same order yield from print_label_process(env, sampler, key, next(label_ids)) ``` This is ordinary SimPy: `packers.request()` waits for a unit, `env.timeout` waits the service time, and leaving the `with` block releases the unit. The `env.publish_event` call at each step produces the records. A task can also take from or add to a store or container (`get`, `put`), rank its requests (`priority`), and name the task that follows it (`next`). [Stores and Containers](https://jaehyeon.me/desflow/latest/user-guide/model-parts/stores-and-containers/index.md), [Units and Queues](https://jaehyeon.me/desflow/latest/user-guide/resources/units-and-queues/index.md) and [Task Flow](https://jaehyeon.me/desflow/latest/user-guide/model-parts/task-flow/index.md) describe each. ### A Timed Step A task with a `service` and no `resource` is a **timed step**: work that takes time but needs nothing that can be busy, such as printing a label or waiting for a supplier. It publishes `started` at once, with no `queued` event, waits the sampled time, and publishes its finished event. Its wait is 0. It is SimPy's `env.timeout`: the tests check that it ends at the same simulation time as a plain SimPy timeout in all three APIs ([SimPy Compatibility](https://jaehyeon.me/desflow/latest/simpy/compatibility/index.md)). ```yaml print_label: # A service and no resource: a timed step that starts at once service: labelling payload: {event_type: label_printed} ``` ```python @app.task(service_id="labelling") # a service and no resource: starts at once def print_label(task_id: int): return {"event_type": "label_printed"} ``` ```python def print_label_process(env, sampler, key, task_id): """A timed step: started at once, with no queued event.""" path_id = "Shop.service.labelling" def publish(value): env.publish_event(key, value, task="print_label", instance=task_id) publish( { "path_id": path_id, "sim_id": "Shop", "service": "labelling", "status": "started", } ) yield env.timeout(sampler.sample(env.registry.get_config(path_id))) publish({"event_type": "label_printed"}) ``` ### Arrivals Start Tasks An arrival starts one task per arrival. The loop draws a gap from the arrival's distribution, waits for that duration, starts a task for the new entity, and repeats. The task runs on its own while the loop waits for the next arrival. ```yaml arrivals: # Each arrival spawns one pack_order, and one return_logged # An order every 5 s on average (rate 0.2) orders: {dist: exponential, rate: 0.2, spawn: pack_order} # A return every 10 s on average (rate 0.1) returns: {dist: exponential, rate: 0.1, spawn: return_logged} ``` ```python # Each arrival starts one pack_order # An order every 5 s on average (rate 0.2) app.add_arrival("orders", dist="exponential", rate=0.2, spawn="pack_order") ``` `spawn=` starts the named task for each arrival's entity, whose key is the arrival name and a counter: `orders-1`, `orders-2`. The record's `instance` comes from the task's one counter, which `next` and other arrivals share, so no two runs of the task share an id. A `spawn` that names a task never added is refused when `run()` checks the model. `@app.arrival_loop` runs a generator of your own. The loop below starts one `return_logged` for each return, which is what `spawn="return_logged"` does in one argument, as the YAML tab writes it. A loop is needed only when it does more than start one task, such as choosing the task from the entity's attributes. `context.wait_for_arrival` returns the new `Entity`. Pass it to the task with `entity=`. A task called without one starts an entity of its own, keyed by the task's name and a counter, such as `return_logged-1`. The `task_id` becomes the record's `instance`. Take it from `context.next_instance`, the task's one counter. ```python # A return every 10 s on average (rate 0.1) app.add_arrival("returns", dist="exponential", rate=0.1) @app.arrival_loop("returns") def returns(context: SimulationContext): while True: # Draws the next gap, waits for it, and returns the new entity, keyed returns-1, ... parcel = yield context.wait_for_arrival("returns") task_id = context.next_instance("return_logged") # the task's one counter context.spawn(return_logged(task_id, entity=parcel)) # the loop goes on at once ``` ```python def orders_process(env, sampler, packers): """What an arrival with spawn does, by hand.""" gap = env.registry.get_config("Shop.arrival.orders") label_ids = itertools.count() task_id = 0 while True: yield env.timeout(sampler.sample(gap)) key = f"orders-{task_id + 1}" env.process(pack_order_process(env, sampler, packers, key, task_id, label_ids)) task_id += 1 ``` In the low-level API every loop is started once, before the run: ```python env.process(orders_process(env, sampler, packers)) # start each loop once env.process(breaks_process(env, "packers", every=50, duration=5)) ``` ### Task Keys A task has these keys. Each row names where the keys are described, and [YAML Keys](https://jaehyeon.me/desflow/latest/reference/yaml-keys/index.md) lists every key with its type. | Keys | What they set | Described in | | --------------------------------------------------------- | --------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------- | | `service`, `service_time`, `resource` | how long the work takes, and the resource it holds | [A Task](#a-task) and [Units and Queues](https://jaehyeon.me/desflow/latest/user-guide/resources/units-and-queues/index.md) | | `priority`, `preempt` | the task's place in a resource's line, and whether it may take a unit | [Priority and Preemption](https://jaehyeon.me/desflow/latest/user-guide/resources/priority-and-preemption/index.md) | | `keep`, `seize`, `release` | holding a unit across tasks, or from one step to another | [Several Resources](https://jaehyeon.me/desflow/latest/user-guide/resources/several-resources/index.md) | | `patience`, `balk`, `on_renege`, `on_balk` | leaving the line | [Leave the Line](#leave-the-line) | | `on_interrupt`, `on_interrupt_next`, `on_interrupt_run` | what the task does when it is interrupted | [Interrupts](#interrupts) | | `interrupt`, `subscribe` | interrupting other tasks, and being told when a flow ends | [Signals and Waiting](https://jaehyeon.me/desflow/latest/user-guide/tasks-and-processes/signals-and-waiting/index.md) | | `payload`, `id_field`, `item_field`, `attributes` | the value of the finished event | [A Task](#a-task) and [Task Flow](https://jaehyeon.me/desflow/latest/user-guide/model-parts/task-flow/#record-key-and-fields) | | `key`, `key_field` | the key of the task's records | [Task Flow](https://jaehyeon.me/desflow/latest/user-guide/model-parts/task-flow/#record-key-and-fields) | | `next`, `set`, `set_args`, `activate`, `deactivate` | where the entity goes next and what it carries | [Task Flow](https://jaehyeon.me/desflow/latest/user-guide/model-parts/task-flow/index.md) | | `vars`, `vars_once`, `on_start`, `finish_vars`, `history` | values drawn for the task, and the rows it keeps | [Task Flow](https://jaehyeon.me/desflow/latest/user-guide/model-parts/task-flow/#values-a-task-draws) | | `get`, `put` | taking from and adding to a store or container | [Stores and Containers](https://jaehyeon.me/desflow/latest/user-guide/model-parts/stores-and-containers/index.md) | | `wait`, `open`, `listen`, `cancel`, `resume` | waiting for, naming and watching events | [Signals and Waiting](https://jaehyeon.me/desflow/latest/user-guide/tasks-and-processes/signals-and-waiting/index.md) | | `signal`, `spawn`, `on` | what happens when the task ends | [Signals and Waiting](https://jaehyeon.me/desflow/latest/user-guide/tasks-and-processes/signals-and-waiting/index.md) | | `fail`, `fail_reason`, `on_fail` | when a task fails and where it goes | [Failures](https://jaehyeon.me/desflow/latest/user-guide/tasks-and-processes/failures/index.md) | | `batch` | serving several entities with one run of the service | [Serve Entities Together](https://jaehyeon.me/desflow/latest/how-to/modelling/serve-entities-together/index.md) | ### Leave the Line An order that waits too long may leave, and an order that finds the line long may not join it. Four keys set this: - `patience` is the longest the task waits for its `wait`, its resource and its `get`. It is a number of seconds, a duration such as `8 s`, an expression or a generator. A task whose patience runs out **reneges**: it publishes `reneged`, gives back what it holds and leaves. - `balk` is a condition read before the task joins the line. When it holds, the task publishes `balked` and leaves. A resource whose `queue_limit` is full makes the task balk too ([Units and Queues](https://jaehyeon.me/desflow/latest/user-guide/resources/units-and-queues/#queue-limit)). - `on_renege` and `on_balk` name the task that gets the entity next. Without them the flow ends. That task reads how the entity left as `upstream.status`, `reneged` or `balked`. This model has orders that give up after 8 seconds or do not join the line from 150 seconds on, and send both kinds to a follow-up task: ```yaml pack_order: service: packing resource: packers priority: 1 # The order leaves the line when it has waited 8 seconds patience: 8 s # The order does not join the line from 150 seconds on balk: t >= 150 # Where an order goes after it leaves the line; it reads upstream.status on_renege: follow_up on_balk: follow_up payload: {event_type: order_packed} follow_up: payload: event_type: order_left how: {gen: expr, expr: upstream.status} ``` ```python @app.task( service_id="packing", resource_id="packers", priority=1, patience="8 s", # the order leaves the line when it has waited 8 seconds balk="t >= 150", # the order does not join the line from 150 seconds on # Where an order goes after it leaves the line; it reads upstream.status on_renege="follow_up", on_balk="follow_up", ) def pack_order(task_id): return {"event_type": "order_packed"} order_left = Template( {"event_type": "order_left", "how": {"gen": "expr", "expr": "upstream.status"}}, name="tasks.follow_up", ) @app.task() def follow_up(task_id): return order_left ``` SimPy's reneging pattern races the request against a timeout: `result = yield request | env.timeout(patience)`, and `request.cancel()` when `request not in result`. A balk is an `if` before `packers.request()`. [Add Reneging and Balking](https://jaehyeon.me/desflow/latest/how-to/modelling/reneging-and-balking/index.md) shows both in the three forms, and [Patience](https://jaehyeon.me/desflow/latest/learn/shop-logic/patience/index.md) teaches them step by step. ### Interrupts A task is interrupted by a preemption, a breakdown, an `interrupt` action or a scenario step. `on_interrupt` says what it does next: | Value | What the task does | | --------- | ------------------------------------------------------------------------------------------------------------------ | | `resume` | The default. It goes on at once with a unit it still holds, or queues again, and then serves the time it had left. | | `restart` | The same, but it serves a new time, drawn from the same stream. | | `abandon` | It gives back every unit and ends, unless `on_interrupt_next` names a task for the entity to go to. | `on_interrupt_next` is for `abandon`. The task it names reads why the entity was interrupted as `cause.`: `by`, `usage_since` and `resource` after a preemption, `value` after an `interrupt`, and `left`, the service time that was left. `on_interrupt_run` is for `resume` and `restart`. It names a task that runs as a child flow of the same entity after each interrupt, and then the task goes on with the time it had left, or a new time under `restart`. It is the SimPy loop `try: yield env.timeout(left)` with `except Interrupt: yield from repair()`. The child reads `cause.` as a task reached by `on_interrupt_next` does. It is for work that holds no unit of its own, so it is refused with a `resource` and with a `request` in the `wait`. A gift order that loses its packer is packed by hand instead (`abandon`). A label that is interrupted by a jam is retooled and then printed with the time it had left (`on_interrupt_run`): ```yaml pack_gift: service: packing resource: packers priority: 1 # A gift that loses its packer gives it up and is packed by hand instead on_interrupt: abandon on_interrupt_next: pack_by_hand payload: {event_type: gift_packed} pack_by_hand: service: packing payload: {event_type: packed_by_hand} ``` ```yaml print_label: service: labelling # After an interrupt, retool runs as a child flow of the same entity, and then # the label goes on with the time it had left on_interrupt: resume on_interrupt_run: retool payload: {event_type: label_printed} retool: service: repairing payload: event_type: retooled left: {gen: expr, expr: cause.left} ``` ```python @app.task( service_id="packing", resource_id="packers", priority=1, # A gift that loses its packer gives it up and is packed by hand instead on_interrupt="abandon", on_interrupt_next="pack_by_hand", ) def pack_gift(task_id): return {"event_type": "gift_packed"} @app.task(service_id="packing") def pack_by_hand(task_id): return {"event_type": "packed_by_hand"} ``` ```python @app.task( service_id="labelling", # After an interrupt, retool runs as a child flow of the same entity, and then # the label goes on with the time it had left on_interrupt="resume", on_interrupt_run="retool", ) def print_label(task_id): return {"event_type": "label_printed"} retooled = Template( {"event_type": "retooled", "left": {"gen": "expr", "expr": "cause.left"}}, name="tasks.retool", ) @app.task(service_id="repairing") def retool(task_id): return retooled ``` The process catches `simpy.Interrupt`. For a preemption, its cause is SimPy's `Preempted`. A process that is preempted, or whose request still waits, cancels its request and asks again, and a process that holds its unit keeps the request. [Interruptions](https://jaehyeon.me/desflow/latest/learn/shop-logic/interruptions/index.md) shows the loop, and [Priority and Preemption](https://jaehyeon.me/desflow/latest/user-guide/resources/priority-and-preemption/index.md) says what takes a unit. ### Records of a Task Every event of a task carries three fields beside its value: `key`, the entity's key; `task`, the task's name; and `instance`, the number of this run of the task, counted from 0 for each task. The first order of the blueprint in [A Task](#a-task), packed and then labelled: ```text [EVT] {'sim_ts': 1.6063438520913942, 'timestamp': '...', 'key': 'orders-1', 'task': 'pack_order', 'instance': 0, 'value': {'path_id': 'Shop.service.packing', 'sim_id': 'Shop', 'service': 'packing', 'status': 'queued'}} [EVT] {'sim_ts': 1.6063438520913942, 'timestamp': '...', 'key': 'orders-1', 'task': 'pack_order', 'instance': 0, 'value': {'path_id': 'Shop.service.packing', 'sim_id': 'Shop', 'service': 'packing', 'status': 'started'}} [EVT] {'sim_ts': 5.58163205023515, 'timestamp': '...', 'key': 'orders-1', 'task': 'pack_order', 'instance': 0, 'value': {'event_type': 'order_packed'}} [EVT] {'sim_ts': 5.58163205023515, 'timestamp': '...', 'key': 'orders-1', 'task': 'print_label', 'instance': 0, 'value': {'path_id': 'Shop.service.labelling', 'sim_id': 'Shop', 'service': 'labelling', 'status': 'started'}} [EVT] {'sim_ts': 7.58163205023515, 'timestamp': '...', 'key': 'orders-1', 'task': 'print_label', 'instance': 0, 'value': {'event_type': 'label_printed'}} ``` All five events share the key `orders-1`, so an order can be followed through every task it passes. The finished event's value is exactly the payload. [Records and Telemetry](https://jaehyeon.me/desflow/latest/reference/records-and-telemetry/index.md) describes every field. ______________________________________________________________________ ## How It Works ### What run() Does `run()` builds everything the context describes and runs it, in this order: Until `run()` is called nothing exists but the description, and the runtime helpers that [Builder API](https://jaehyeon.me/desflow/latest/user-guide/writing-a-model/builder-api/index.md) lists raise `RuntimeError`. Teardown runs in a `finally` block, so the last statistics are published and every sink is flushed even when the run stops with an error or Ctrl+C. ### What @app.task Does `@app.task` turns your function into a SimPy process that does these steps, publishing a record at three of them: 1. If its `balk` condition holds, it publishes `balked` and stops. 1. It publishes `queued` if it has a `wait`, a resource or a `get`, and starts its `patience` timer, which runs only while it waits. It starts its `open` branches, makes its `listen` callbacks and runs its `cancel`. Then it asks for the units named by `seize`. 1. It waits until its `wait` ends. 1. It asks for the resource, in the resource's queue order, then takes its `get` from a store or container, waiting while there is not enough. 1. It publishes `started`, calls your function, and keeps what it returns as the payload. The payload is computed before the service time, so it can use the state of the simulation at that moment. 1. It waits the service time, drawn from the live distribution. 1. It adds its `put` to a store or container, waiting while there is no room, and checks its `fail` condition. 1. It publishes the payload as the finished event, or `failed`, and releases the resource. 1. It fires its `signal` (or fails it) and sends its `interrupt` action to the tasks it names. It applies `set` to the entity's attributes and `set_args` to the process's local names, and runs the `on:` actions. It frees the units named by `release`. A unit still held when the flow ends stays held, as in SimPy, so a flow that used `seize` writes `release` before it ends. 1. It starts the next task that its `next` chooses, or its `on_fail`, `on_renege` or `on_balk` task, as a new instance for the same entity. A YAML task and its `spawn` make the same task and arrival loop that the builder code above makes. The code that runs these steps is `TaskRun` in `desflow/builder/task.py`. In SimPy terms each flow of tasks is one process started with `env.process`, and each arrival loop is another. [SimPy and desflow](https://jaehyeon.me/desflow/latest/simpy/index.md) describes processes. A process outside a task runs as [Processes](https://jaehyeon.me/desflow/latest/user-guide/tasks-and-processes/processes/#how-it-works) describes. ______________________________________________________________________ ## Stability and Limits - **Resources are acquired in one order.** A task can hold several resources and hand one to the next task. Tasks that acquire two resources in opposite orders still load, and the model logs one WARNING, because two of them could then wait for each other for ever: [Several Resources](https://jaehyeon.me/desflow/latest/user-guide/resources/several-resources/#several-resources). - **`abandon` gives back everything.** An interrupted task cancels its waits. Under `resume` and `restart` it keeps a unit it holds through a plain interrupt and asks again only for a unit it lost, at the back of the line. A preemption or a breakdown takes the unit. Under `abandon` it releases every unit before it follows `on_interrupt_next`: [Interruptions](https://jaehyeon.me/desflow/latest/learn/shop-logic/interruptions/index.md). - **A finished event is exactly the payload.** It has no `status` or `path_id` unless the payload includes them. - **A condition branch checks after every change.** [Stability and Limits](https://jaehyeon.me/desflow/latest/user-guide/tasks-and-processes/signals-and-waiting/#stability-and-limits) says what that costs. - **Runtime helpers need a running simulation.** They raise `RuntimeError` before `run()`, as [Builder API](https://jaehyeon.me/desflow/latest/user-guide/writing-a-model/builder-api/index.md) lists. Call them inside a loop, task or process. # Processes A process runs alongside the [tasks](https://jaehyeon.me/desflow/latest/user-guide/tasks-and-processes/tasks/index.md). This page shows how to write one. ______________________________________________________________________ ## What It Is A process is anything in the shop that runs over time but is not one entity's work: a break for the packers, a drift in a parameter, a delivery schedule. An arrival starts one task per entity, while a process starts once, when the run starts, and runs alongside the tasks. A process can wait, change values in the registry, publish records or start tasks. ______________________________________________________________________ ## How to Use It ### A Process This process sends the packers on a 5-second break every 50 seconds: A blueprint writes this without Python. One entity exists when the run starts, and two tasks hand it to each other: each waits, writes the capacity with an `on:` action, and names the other as its `next`. ```yaml # One entity exists when the run starts and drives the breaks shifts: {initial: 1, spawn: take_break} ``` ```yaml # The packers go on a 5-second break every 50 seconds: wait, set the capacity with # on:, and hand over to the other task, which sets it back take_break: wait: {timeout: 50 s} on: - {path: Shop.resources.packers.current_cap, value: 0} payload: {event_type: break_started} next: end_break end_break: wait: {timeout: 5 s} on: - {path: Shop.resources.packers.current_cap, value: 1} payload: {event_type: break_ended} next: take_break ``` A `processes` entry names a Python function of your own, for work the keys cannot say: ```yaml processes: # Called as breaks(context, resource="packers", every=50, duration=5) - function: !python shop_logic.breaks kwargs: {resource: packers, every: 50, duration: 5} ``` ```python def breaks(context: SimulationContext, resource: str, every: float, duration: float): """Takes every packer off for a break of `duration` seconds every `every` seconds.""" path = f"{context.sim_id}.resources.{resource}.current_cap" registry = context.env.registry while True: yield context.env.timeout(every) normal = registry.get(path).value registry.update(path, 0) yield context.env.timeout(duration) registry.update(path, normal) app.add_process(breaks, resource="packers", every=50, duration=5) ``` ```python def breaks_process(env, resource: str, every: float, duration: float): """What add_process starts, by hand: a plain SimPy generator.""" path = f"Shop.resources.{resource}.current_cap" while True: yield env.timeout(every) normal = env.registry.get(path).value env.registry.update(path, 0) yield env.timeout(duration) env.registry.update(path, normal) ``` ______________________________________________________________________ ## How It Works `add_process(func, **kwargs)` starts `func(context, **kwargs)` when the run starts, and a YAML `processes` entry does the same with a `!python` function. Inside it, `context.env` is the `DynamicRealtimeEnvironment`, so a process can do anything a low-level script does: `context.env.timeout`, `context.env.registry.update`, `context.env.publish_event`. A process is how low-level code joins a builder or YAML model. `context.env.active_process` is the running SimPy process. Its `name` is the task's name, because a task's process is named after the task. Its `target` is the event it waits on now, or None once it has ended. A condition reads the same three values as `process.name`, `process.instance` (the task's instance id, the `instance` field of its records) and `process.target`, a string such as `timeout`, `signal.`, `task.`, `condition`, `resource.`, `get.`, `put.` or `service`. In a task's own expressions they name that task. In an `interrupt` or `running` `where`, they name each instance tested. ______________________________________________________________________ ## Stability and Limits - **A process is not an entity.** It has no key, no `instance` and no records of its own unless it publishes them. Work that one entity does is a [task](https://jaehyeon.me/desflow/latest/user-guide/tasks-and-processes/tasks/index.md). - **A capacity of 0 stops new work only.** Setting `current_cap` to 0 does not stop the work in progress: [Units and Queues](https://jaehyeon.me/desflow/latest/user-guide/resources/units-and-queues/#under-live-changes) explains what happens to busy units when a capacity drops. ______________________________________________________________________ ## Example: Process Interaction The `process-interaction` example combines a child flow, a failure that `on_fail` handles, and orders that wait for a courier's signal or a time limit. It needs no Docker service and ends on its own after 300 simulation seconds. The tutorial page [Process Interaction](https://jaehyeon.me/desflow/latest/learn/shop-logic/process-interaction/index.md) teaches these features step by step. **Quick Start** `desflow examples get` downloads the example at the release you install, into a folder of its own. Pick uv or pip: ```bash # 1. Install uv tool install desflow # 2. Download the example desflow examples get process-interaction --api yaml cd process-interaction/yaml # 3. Find the bottleneck, with no run desflow explain process_interaction.yaml # 4. Run it desflow run process_interaction.yaml ``` ```bash # 1. Install pip install desflow # 2. Download the example desflow examples get process-interaction --api yaml cd process-interaction/yaml # 3. Find the bottleneck, with no run desflow explain process_interaction.yaml # 4. Run it desflow run process_interaction.yaml ``` The whole file is [`examples/yaml/process_interaction.yaml`](https://github.com/jaehyeon-kim/desflow/blob/v1.3.0/examples/yaml/process_interaction.yaml). **Quick Start** `desflow examples get` downloads the example at the release you install, into a folder of its own. Pick uv or pip: ```bash # 1. Install uv tool install desflow # 2. Download the example desflow examples get process-interaction --api builder cd process-interaction/builder # 3. Run it uv run --no-project --with desflow process_interaction_example.py ``` ```bash # 1. Install pip install desflow # 2. Download the example desflow examples get process-interaction --api builder cd process-interaction/builder # 3. Run it python process_interaction_example.py ``` The whole file is [`examples/builder/process_interaction_example.py`](https://github.com/jaehyeon-kim/desflow/blob/v1.3.0/examples/builder/process_interaction_example.py). **Quick Start** `desflow examples get` downloads the example at the release you install, into a folder of its own. Pick uv or pip: ```bash # 1. Install uv tool install desflow # 2. Download the example desflow examples get process-interaction --api low-level cd process-interaction/low-level # 3. Run it uv run --no-project --with desflow process_interaction_example.py ``` ```bash # 1. Install pip install desflow # 2. Download the example desflow examples get process-interaction --api low-level cd process-interaction/low-level # 3. Run it python process_interaction_example.py ``` The whole file is [`examples/low-level/process_interaction_example.py`](https://github.com/jaehyeon-kim/desflow/blob/v1.3.0/examples/low-level/process_interaction_example.py). # Signals and Waiting A [task](https://jaehyeon.me/desflow/latest/user-guide/tasks-and-processes/tasks/index.md) can wait for signals, conditions and child flows, start other flows and run actions when an event happens. This page shows each. The tutorial page [Process Interaction](https://jaehyeon.me/desflow/latest/learn/shop-logic/process-interaction/index.md) teaches these features step by step. ______________________________________________________________________ ## What It Is In a shop, work often depends on other work. An order waits until its parts are picked, a courier leaves once an order is packed, and a guard is told when an alarm round ends. desflow models this with four tools: a wait that a task makes before it asks for its resource, signals that tasks fire, flows that a task starts without waiting for them, and actions that run when an event happens. ______________________________________________________________________ ## How to Use It ### Wait, Signals and Child Flows A task can wait for something before it queues for its resource: its `wait`. A wait has one branch, or a group of several named branches: `any`, `all` or `at_least`. A branch can itself be a group, so waits nest. An empty `any` or `all` succeeds at once. In SimPy, `AnyOf` waits for the first event and `AllOf` for every event, and a `Condition` with a count rule does what `at_least` does. [Wait for One or All](https://jaehyeon.me/desflow/latest/how-to/modelling/wait-for-one-or-all/index.md) shows the groups. A leaf branch is one of: | Branch | Waits for | Its value | | --------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------- | | `{signal: name}` | the next firing of a signal declared under `signals` (builder `add_signal`) | the firing's value, the payload of the task that fired it | | `{task: name}` | a **child flow**: that task, started for the same entity with its own instance id, and the tasks its `next` leads to, until the flow ends | the last task's finished payload | | `{timeout: 40 s}`, or `{timeout: {after: 40 s, value: ...}}` | a time; `value` is carried to the waiter, as SimPy's `env.timeout(delay, value)` | `None`, or the `value` given | | `{condition: level.stock >= 5}` | a condition to hold, checked when the wait starts and again after every store or container change, change in a queue that the condition reads, registry update, signal firing and finished task | `True` | | `{request: name}` | a unit of a resource; a won unit is held through the service and given back when the task ends | the request | | `{get: {store: name}}` or `{get: {container: name, amount: 2}}` | an item or an amount, as a task `get` does | the item taken | | `{put: {store: name}}` or `{put: {container: name, amount: 2}}` | room to add the payload of the task before it, or an amount | none | | `{running: {task: name, where: ...}}` | every running instance of a task, on the waiter's entity and on the entities it spawned, to end, which is the end of that instance and not of its flow's process; `where` narrows them, read in each instance's scope; with `whole_flow: true` it is the end of the whole flow the instance belongs to, as `yield process` waits for a SimPy process, and the value is the flow's last payload; it selects the flows running when the wait begins, and a flow that has ended only while an instance of a task with such a wait was running and still is, so a run that waits now and then keeps no ended flow; when none match, the wait is done at once | the one instance's finished payload, or a mapping from instance id to payload for several, in start order | A `running` branch waits for tasks already running. Here an order waits for the delivery it started, unless the delivery has already left with the van: ```yaml # Wait until every flow of the deliver task has ended, unless it has left with the # van wait: running: {task: deliver, where: process.target != 'service', whole_flow: true} ``` `@app.task(wait=...)` takes the same mapping as a dict: `wait={"running": {"task": "deliver", "where": "process.target != 'service'"}}`. A low-level process waits for another by yielding it, as SimPy's `yield process` does. A single branch is named after its signal, task or resource, or `timeout`, `condition`, `get` or `put`. A `put` branch draws its `item` as a task's `put` does, and `payload: null` together with a store `put` in a `wait` or an `open` is refused when the blueprint loads, because there is no payload for the put to carry. After the wait, each branch has three values: - `wait..done` says whether the branch happened before the wait ended. - `wait..ok` says whether it succeeded. - `wait..value` (or `.value.`) is its value. `next`, `fail` and amounts read these values, and a builder function that declares `wait` receives them as a mapping. A group can also end on an expression: `wait: {when: , of: {...}}` is done when the expression holds. It reads `wait..done`, `.ok` and `.value` of each branch, and `done_count`, the number of branches done. Like `any`, a `when` group cancels the requests that did not win. [Wait for One or All](https://jaehyeon.me/desflow/latest/how-to/modelling/wait-for-one-or-all/index.md) shows the groups with their ties and failures. A task fires a signal with `signal: name` when it finishes, with its payload as the value. Any condition reads the signal as `signal..count`, `.ok` and `.value`. The `process-interaction` example waits for a child flow, then for the first of a courier's signal and a time limit: ```yaml check: # Starts the child flow inspect and waits for it to end. wait: {task: inspect} payload: {event_type: order_checked} next: dispatch inspect: service: inspecting payload: {event_type: inspected} # A gift fails inspection; on_fail sends it to wrap, and the flow goes on. fail: attr.gift == 1 fail_reason: gift needs wrapping on_fail: wrap wrap: service: wrapping payload: {event_type: wrapped} ``` ```yaml dispatch: # The courier's departure, or 40 seconds, whichever comes first. wait: any: courier: {signal: courier_left} limit: {timeout: 40 s} payload: {event_type: dispatched} next: when: - {condition: wait.courier.done, task: by_courier} default: by_post ``` ```yaml courier: payload: {event_type: courier_left} # Fires courier_left with this payload; every order waiting for it resumes. signal: courier_left ``` A child flow can take values from its parent. `args` are read in the parent's scope when the child starts, and the child reads each as `arg.`: ```yaml # Start a child flow of label_box for this entity, with the box number as arg.box wait: any: child: task: label_box args: {box: 7} limit: {timeout: 30 s} ``` ```python # Starts the child flow inspect and waits for it to end @app.task(wait={"task": "inspect"}, next="dispatch") def check(task_id, context): return {"event_type": "order_checked"} # A gift fails inspection; on_fail sends it to wrap, and the flow goes on @app.task( service_id="inspecting", fail="attr.gift == 1", fail_reason="gift needs wrapping", on_fail="wrap", ) def inspect(task_id, context): return {"event_type": "inspected"} @app.task(service_id="wrapping") def wrap(task_id, context): return {"event_type": "wrapped"} ``` ```python # The courier's departure, or 40 seconds, whichever comes first @app.task( wait={"any": {"courier": {"signal": "courier_left"}, "limit": {"timeout": 40}}}, next={ "when": [{"condition": "wait.courier.done", "task": "by_courier"}], "default": "by_post", }, ) def dispatch(task_id, context): return {"event_type": "dispatched"} ``` ```python # Fires courier_left with this payload; every order waiting for it resumes @app.task(signal="courier_left") def courier(task_id, context): return {"event_type": "courier_left"} ``` `context.signal(name)` returns the `Signal`, which a process can fire, fail or wait for. `context.call(task, entity=...)` starts a child flow from a process and returns its SimPy process, which a process can yield. `context.spawn` returns the process it starts too, so `is_alive`, `triggered`, `ok` and `value` inspect it, as in SimPy. ```python def check(shop, key, arrival): """Starts the child process inspect and waits for it to end.""" env, stats, task_id = shop.env, shop.env.stats, shop.next_id("check") shop.publish(key, "check", task_id, {"status": "queued"}) stats.task_queued("check", task_id) yield env.process(inspect(shop, key, arrival)) shop.publish(key, "check", task_id, {"status": "started"}) stats.task_started("check", task_id) shop.publish(key, "check", task_id, {"event_type": "order_checked"}) stats.task_finished("check", task_id) yield from dispatch(shop, key, arrival) def inspect(shop, key, arrival): """A gift fails inspection and is wrapped instead; returns the last payload.""" env, stats, task_id = shop.env, shop.env.stats, shop.next_id("inspect") path_id = "Shop.service.inspecting" shop.publish( key, "inspect", task_id, { "path_id": path_id, "sim_id": "Shop", "service": "inspecting", "status": "started", }, ) stats.task_started("inspect", task_id) yield env.timeout(shop.service("inspecting")[1]) if GIFT[arrival] == 1: failed = { "path_id": path_id, "sim_id": "Shop", "service": "inspecting", "status": "failed", "reason": "gift needs wrapping", } shop.publish(key, "inspect", task_id, failed) stats.task_failed("inspect", task_id) return (yield env.process(wrap(shop, key))) payload = {"event_type": "inspected"} shop.publish(key, "inspect", task_id, payload) stats.task_finished("inspect", task_id) return payload def wrap(shop, key): env, stats, task_id = shop.env, shop.env.stats, shop.next_id("wrap") path_id = "Shop.service.wrapping" shop.publish( key, "wrap", task_id, { "path_id": path_id, "sim_id": "Shop", "service": "wrapping", "status": "started", }, ) stats.task_started("wrap", task_id) yield env.timeout(shop.service("wrapping")[1]) payload = {"event_type": "wrapped"} shop.publish(key, "wrap", task_id, payload) stats.task_finished("wrap", task_id) return payload ``` ```python def dispatch(shop, key, arrival): """The courier's departure, or 40 seconds, whichever comes first.""" env, stats, task_id = shop.env, shop.env.stats, shop.next_id("dispatch") shop.publish(key, "dispatch", task_id, {"status": "queued"}) stats.task_queued("dispatch", task_id) courier = shop.courier_left.wait() done = yield env.any_of([courier, env.timeout(40)]) shop.publish(key, "dispatch", task_id, {"status": "started"}) stats.task_started("dispatch", task_id) shop.publish(key, "dispatch", task_id, {"event_type": "dispatched"}) stats.task_finished("dispatch", task_id) task = "by_courier" if courier in done else "by_post" yield from send(shop, key, arrival, task) ``` ```python def courier(shop, key): """Fires courier_left; every order waiting for it resumes.""" task_id = shop.next_id("courier") shop.env.stats.flow_started("couriers") payload = {"event_type": "courier_left"} shop.publish(key, "courier", task_id, payload) shop.env.stats.task_finished("courier", task_id) shop.courier_left.fire(payload) shop.env.stats.flow_finished("couriers") yield shop.env.timeout(0) ``` The low-level API is plain SimPy here: a child is `env.process(...)`, its value is what it returns, and `env.any_of` and `env.all_of` wait for the first or for every event. `Signal(env, name)` is the named event the builder and YAML use. `env.watch_changes(check)` calls `check` after every change a condition can read. `env.watch_changes(check, queues=True)` also calls it after a change in the number of puts or gets waiting at a store or container. ### One-Shot Signals A signal is one-shot by default, as SimPy's `Event` is. It fires once, so a task that waits for it after it has fired resumes at once, and a second firing is refused. A closing-time signal is a one-shot: `signals: {closing: {}}`. `once` is `true` or `false`, and the builder refuses anything else. A signal that fires more than once is written `once: false` (builder `add_signal(name, once=False)`, low-level `Signal(env, name, once=False)`). It re-arms after each firing, so a waiter that starts later waits for the next. The courier signal of the example above is one that re-arms. ### Park a Task Until Another Resumes It A task that waits with `suspend: true` parks until another task wakes it. The waking task writes `resume: {task, where, value, limit}`: it wakes the parked instances of `task` that `where` selects, oldest first, at most `limit` of them (`limit: 0` wakes nobody). `value` is read once for each `resume`, and a woken instance reads it as `wait.suspend.value`. `suspend` stands alone or in a group, and not in `open`. A `limit` below 0 is refused when the blueprint loads. An interrupt of a parked instance follows its `on_interrupt`. Three orders park, and a truck wakes the two oldest: ```yaml simulation: {sim_id: Shop, factor: 0} arrivals: orders: {dist: constant, value: 1, max_events: 3, spawn: hold} trucks: {dist: constant, value: 5, first_at: 5, max_events: 1, spawn: unload} tasks: # Parks until a resume wakes it; wait.suspend.value is the value of that resume hold: wait: {suspend: true} payload: event_type: released by: {gen: expr, expr: wait.suspend.value} # Wakes the two oldest parked orders; the third stays parked unload: resume: {task: hold, limit: 2, value: truck-1} payload: {event_type: unloaded} run: {until: 10} ``` `@app.task(wait={"suspend": True})` parks a task and `@app.task(resume={"task": "hold", "limit": 2, "value": "truck-1"})` wakes it. [Wait for One or All](https://jaehyeon.me/desflow/latest/how-to/modelling/wait-for-one-or-all/#park-a-task-until-another-resumes-it) runs both. A parked process yields an event of its own, and the waking process calls `succeed(value)` on it, as SimPy code does. ### Wait for a Computed Number of Branches `wait: {each: ..., group: ..., branch: ...}` makes the same `branch` once for each element of `each`, when the wait starts. `each` is a whole number, a list, an expression written as text, or any generator, and is read once. Inside `branch`, `each.index` counts from 0, and `each.value` is the element, or the index when `each` is a number. `group` is `all`, the default, `any`, `{at_least: }` or `{when: }`. The results are `wait..values` and `wait..flags`, lists in the order of the elements. Here an order packs three boxes of 2, 5 and 9 seconds, and goes on when two are packed: ```yaml simulation: {sim_id: Shop, factor: 0} arrivals: orders: {initial: 1, spawn: order} tasks: order: wait: all: boxes: each: [2, 5, 9] # one branch for each element group: {at_least: 2} # done when two branches are branch: # each.value is the element timeout: {after: each.value} payload: event_type: packed flags: {gen: expr, expr: wait.boxes.flags} # which branches were done run: {until: 30} ``` The group of an `each` can also be a `when` expression, which reads only `done_count`: ```yaml # Pack three boxes and go on when two are done; the group reads only done_count wait: all: boxes: each: [2, 5, 9] group: {when: done_count >= 2} branch: timeout: {after: each.value} ``` `@app.task(wait={"each": [2, 5, 9], ...})` takes the same mapping. [Wait for One or All](https://jaehyeon.me/desflow/latest/how-to/modelling/wait-for-one-or-all/#wait-for-a-computed-number-of-branches) shows it in the three forms. A Low-level process makes the timeouts itself and waits on a `Condition` with the count it wants, as that page shows. These rules hold for `each`: - The `branch` is one leaf: a signal, task, timeout, request, get, put or handle. A group as the branch is refused. - A literal `each: 2.0` is refused, and an `each` that computes 2.0 fails the run. - An empty `each` succeeds at once under every group. - The `when` of an `each` group reads only `done_count`. A reference to `wait.`, its `values` or its `flags` is refused when the file loads. Read the flags in the payload or the task function after the wait. - `each.index` and `each.value` are read only in the `branch`. A read in a `when` group, an `at_least` count, an `on` entry or a `listen` is refused when the file loads. - A request of an `each` that is still queued is cancelled when the task ends. - `subscribe` refuses an `each` branch. - After a `resume` the wait keeps every leaf's event and reads no reference or index again. After a `restart` it reads `each` again. A granted request is kept for the leaf of the same name that asks for the same resource, and any other kept grant is given back and its leaf asks again. ### Name an Event and Cancel It `open` starts wait branches at once without waiting for them, and names each, so a later step can wait for it (`wait: {handle: name}`), cancel it (`cancel: name`), release its unit (`release: {handle: name}`) or interrupt it. A handle's state is read as `handle..triggered`, `.processed`, `.ok`, `.value` and `.alive`. This order asks for three packers at once, packs with the first it gets, and cancels the other two requests: ```yaml simulation: {sim_id: Shop, factor: 0} resources: packers: {current_cap: 1} arrivals: orders: {initial: 1, spawn: order} late: {dist: constant, value: 1, first_at: 1, max_events: 1, spawn: late_order} tasks: order: open: # three requests, made at once pool: each: 3 branch: {request: packers} wait: {handle: pool, index: 0} # the first of them service_time: 2 cancel: pool # the requests not yet granted: the second and the third release: {handle: pool, index: 0} # the unit of the first, when the task ends payload: event_type: packed granted: {gen: expr, expr: handle.pool.flags} late_order: resource: packers service_time: 1 payload: {event_type: late_packed} run: {until: 30} ``` A handle names one element of an `each` as `{handle: name, index: }`. `listen`, `interrupt`, `cancel` and `release` take that form. Here a task opens three child flows and two requests for a van. It hears the second child flow end, stops the third, gives up the second request and gives back the first: ```yaml # Open three child flows and two requests for a van, without waiting for them open: boxes: each: 3 branch: task: label_box args: box: {gen: expr, expr: each.index} seats: each: 2 branch: {request: vans} # Hear the end of the second child flow listen: handle: boxes index: 1 on: - fire: {signal: second_done} service_time: 1 s # Stop the third child flow, give up the second request, and give back the first interrupt: {handle: boxes, index: 2, cause: stop} cancel: {handle: seats, index: 1} release: {handle: seats, index: 0} ``` `@app.task(open={...}, wait={"handle": "pool", "index": 0}, cancel="pool")` takes the same mappings. [Wait for One or All](https://jaehyeon.me/desflow/latest/how-to/modelling/wait-for-one-or-all/index.md) shows the pool in the three forms. The requests are SimPy requests held in a list: `requests = [packers.request() for _ in range(3)]`, then `yield requests[0]` and `request.cancel()` on the others. ### Pick a Member of a Family A resource, store, container or signal with `family: true` is a family: each member is an ordinary one named after the family and its key in brackets, such as `desk[2]`. `members` makes that many when the run starts, and a member not made yet is made at its first use. A name place takes `{of: , key: }` for the member with that key, or `{of: , lowest: }` for the member whose expression is lowest, read with `member.key`, `member.users`, `member.queue`, `member.level`, `member.count`, `member.putters` and `member.getters`. This works in `resource`, `seize`, `release`, a `request` branch, `get`, `put`, `signal`, `subscribe.signal`, `fire.signal` and `run.stop.signal`. A reference is not allowed in `keep`. The desks of a shop are a family, and each customer has a reply signal: ```yaml serve: # The member of the family with the fewest users and waiting requests resource: {of: desk, lowest: "member.users + member.queue"} service: serving payload: {event_type: served} next: thank ``` ```yaml thank: # Fires this customer's own signal, and no other customer's on: - fire: signal: {of: reply, key: attr.number} value: thanks payload: {event_type: thanked} ``` The same mappings go to `resource=`, `wait=`, `on=` and the other arguments. `add_resource("desk", family=True, members=3)` and `add_signal("reply", family=True, once=True)` declare the families. A family is a dictionary of ordinary objects that your code keeps, such as `desks[number % 3]`. A member is read in a condition as `users.desk[k]`, `queue.desk[k]`, `level.c[k]`, `putters.c[k]`, `getters.c[k]`, `signal.reply[k].count`, `held(desk[k])` and `waiting(desk[k])`. `members(desk)` lists the members made so far. A read of a member not made yet gives what a new member gives, and makes nothing. [Units and Queues](https://jaehyeon.me/desflow/latest/user-guide/resources/units-and-queues/#make-a-family-of-resources) describes the capacity of a member. ### Start a Flow Without Waiting A task's `spawn` starts another task as a **new entity**, keyed `-n`, and goes on at once, as SimPy's `env.process` starts a process without yielding it. A courier that leaves once an order is packed is a spawn: `spawn: {task: courier}` on the pack task, or `@app.task(spawn={"task": "courier"})`. A process spawns a generator with `context.spawn(generator)`. The spawned entity is an entity like any other: - It enters and leaves the model as any entity does, so a drain waits for it. - It counts as a flow of its own, under the spawned task's name. - Its records carry its own key, and the spawning entity's key is read as `attr.parent`. A spawned task cannot share its name with an arrival, because their flow statistics and entity numbers would merge. `spawn: {task: courier, after: 3 s}` starts the new entity 3 seconds after the task finishes, as SimPy's `start_delayed` does. `context.spawn(generator, delay=3)` does the same for a process. A drain that ends during the delay ends the run before the spawned entity starts, as it does for an arrival not yet due. An `after` of 0 or less is refused. `count` starts that many entities at once: a whole number, an expression or a generator, read once in the parent's step. A written `count` below 0 is refused at load, and an expression or a generator that gives 0 or less starts none. Each new entity has its own key, and `copy_attributes: true` gives each a copy of the parent's attributes: ```yaml # Two deliveries start for each packed order spawn: {task: deliver, count: 2} ``` `@app.task(spawn={"task": "deliver", "count": 2})` takes the same mapping. A process calls `context.spawn(generator)` once for each entity it starts. A task's `interrupt` runs when the task finishes, as a `spawn` does. Here the task that closes the shop interrupts each order still being checked, and starts a sweep 2 seconds later: ```yaml # When the shop closes: stop each order still being checked, and start a sweep # 2 seconds later interrupt: {task: check, where: "process.target == 'service'", cause: closing} spawn: {task: sweep, after: 2 s} ``` `@app.task(interrupt=..., spawn=...)` takes the same two mappings as dicts. A low-level process calls `process.interrupt(cause)` on each process it stops, and starts the sweep with `env.process` after a timeout of 2 seconds. ### Be Told When a Flow Ends A task's `subscribe` asks to be interrupted when something happens, rather than pausing for it. `subscribe: {task: charger}` starts the `charger` child flow, and interrupts the task when that flow ends, with the cause `{"event": "charger", "value": }`. The task then follows its `on_interrupt`, as it does for any interrupt. The subscription belongs to the flow's process, so after a hand-on the interrupt reaches the next task. `context.subscribe(event)` subscribes a process to any SimPy event, a process included, as SimPy's `subscribe_at` does. It refuses an event that has already happened. ### Actions When an Event Happens An `on:` list runs actions when a signal fires or a task ends. The list belongs to a task or to a signal. On a signal, the actions run before any waiter, as a SimPy callback runs when its event fires. On a task, they run in the step the task ends, before its next task starts, as a statement at the end of a SimPy process's step does. A `next` condition on the same task still reads the old values, because the next task is chosen before the actions run, and the next task reads the new ones. They run when the task ends by finishing, balking, reneging, abandoning, or failing in a way `on_fail` or `fail` handles. A task that ends in a run failure runs no `on:` action, because nothing runs after an uncaught exception in SimPy. A run failure is an error that stops the run: a `next` condition that cannot be evaluated, a wait that fails because its child did, or a task function that raises, when no `on_fail` handles it. Each entry is one of: - `fire: {signal: name}` fires a signal. `value` fires it with a literal value. `from: name` copies an outcome instead. For a signal, it copies the signal's latest outcome. For a task, it copies the finished payload, or the failure reason, of the last instance of that task to end on the entity. SimPy's `trigger` copies another event's outcome in the same way. With nothing to copy yet it fires nothing and logs a warning. `value` and `from` together are refused. On a one-shot signal, `urgent: true` makes the waiters resume before the other events at their time, as SimPy's `URGENT` priority orders them. `after: 5 s` fires it 5 seconds from now, as `env.schedule(event, priority, delay)` does. The signal counts as fired at once, so a second `fire` is refused. A drain does not count the entity that fired it as waiting for the later firing. `priority` is a whole number that orders the events at one time, as `env.schedule(event, priority)` does: 1 is the default and 0 is what `urgent: true` gives. It is refused with `urgent`, works with `after`, and is refused on a signal that re-arms. On a signal that re-arms (`once: false`), `urgent` and `after` are refused at build too. `fail: true` fails the signal with `value` as the reason, and a waiter receives the failure, as with SimPy's `Event.fail`; `fail` with `from` is refused. A one-shot signal's failure that no task waits for stops the run under `on_unhandled_failure: stop`, as a failed SimPy event does, unless `defused: true` stands beside `fail`, which does what `event.defused = True` does. `signals..defused: true` defuses every failure of that signal, and a failure of a signal that re-arms is always defused. An entry may also carry `when: `, which skips the entry when it is false. - `spawn: {task, after}` starts a new entity, as the `spawn` key does. - `interrupt: {task, where, cause}` interrupts running instances, as a task's `interrupt` does. - `path` with `value` sets a registry value, as a scenario step does. - `resume: {task, where, value, limit}` wakes parked instances, as the `resume` key does. The same closing task with an `on:` list: it stops the packing by hand, makes the orders come every 6 seconds, and fires a one-shot `reminder` with a value 5 seconds later: ```yaml # However the task ends: stop the packing by hand, make the orders come every # 6 seconds, and remind the couriers 5 seconds later on: - interrupt: {task: pack_by_hand, cause: closing} - {path: Shop.arrival.orders.value, value: 6} - fire: {signal: reminder, value: last parcels, after: 5 s} ``` `@app.task(on=[...])` takes the same list of mappings. A low-level model adds a callback to the event, as SimPy's `event.callbacks` runs one when the event fires. A one-shot `closing` signal with an `on:` action that fires `last_call` before the other events at closing time: ```yaml closing: once: true on: # Tell the couriers before anything else that happens at closing time - fire: {signal: last_call, urgent: true} last_call: {once: true} ``` `app.add_signal("closing", once=True, on=[{"fire": {"signal": "last_call", "urgent": True}}])` declares the same signal, and `app.add_signal("last_call", once=True)` the other. A low-level model schedules the event with SimPy's `URGENT` priority, `env.schedule(event, URGENT)`. A task's `listen` adds callbacks to the next firing of a signal, of a family member (`signal: {of: reply, key: ...}`) or of an opened event (`handle: name`, with `index` for an element of an `each`), when the task starts and before its wait. It is `event.callbacks.append(f)`: the callbacks run in the order they were added, before the waiters added later, and each entry may carry a `when`. A signal whose firing was processed already takes no callback, and the task fails, as `event.callbacks.append` raises. An entry cannot read `item.`, because `listen` attaches before the task's `get`. A flow that wants to keep listening listens again. This task logs each closing, whatever else it does: ```yaml watch: # Adds a callback to the next firing of closing, before the task waits listen: signal: closing on: - fire: {signal: logged, value: closing seen} wait: {signal: closing} payload: {event_type: watched} ``` A task with an `on:` list that fails a signal, and runs one entry only when a condition holds: ```yaml on: # Fail the till signal with a reason; waiters receive the failure, and a failure # that nobody waits for is defused, so it does not stop the run - fire: {signal: till, fail: true, defused: true, value: the till did not balance} # Run this entry only when the condition holds - when: t >= 10 fire: {signal: reminder, value: last parcels, priority: 2, after: 3 s} ``` The signals of that model are declared in the mapping form. `defused: true` on a signal does what `defused: true` on a `fire` does for every failure of that signal, and `family` with `members` makes three signals, `lane[0]` to `lane[2]`, when the run starts: ```yaml signals: closing: {once: true} till: {once: true} reminder: {once: true} # Every failure of this signal is defused, so none of them stops the run logged: {once: true, defused: true} # A family of signals: one for each lane, numbered 0 to 2 lane: {family: true, members: 3} ``` An `on:` list also turns an arrival on (`activate`) or off (`deactivate`), and wakes parked orders (`resume`, with a `task` and a `where` that keeps the instances it holds for): ```yaml reopen: on: # Turn the rush source on, turn the walk-in source off, and wake the parked # orders of vip customers - {activate: rush} - {deactivate: walkins} - resume: {task: parked, where: attr.vip} payload: {event_type: reopened} ``` `@app.task(listen={"signal": "closing", "on": [...]})` and `@app.task(on=[...])` take the same mappings, and `app.add_signal("logged", once=True, defused=True)` and `app.add_signal("lane", family=True, members=3)` declare the signals. `event.callbacks.append(fn)` adds the callback, as SimPy code does. ______________________________________________________________________ ## How It Works The task publishes `queued` when its wait starts, so the wait counts in its wait statistics. Its `patience` covers the wait as well as its resource and its `get`. When an `any` wait ends, its losing signal, timeout and condition branches are dropped. Its losing child flows keep running, as SimPy leaves processes running. [Wait for One or All](https://jaehyeon.me/desflow/latest/how-to/modelling/wait-for-one-or-all/index.md) shows ties and failures. A wait for signals, tasks and times holds no resource. Waiting for all of several such things reserves nothing: the task asks for its resource only after the wait. A drain waits for a task's `on:` actions and for the `on:` actions of signals its tasks fire, so a final task that fires a signal with `on:` actions leaves only after they have run. ______________________________________________________________________ ## Stability and Limits - **A condition is checked after every change.** A `condition` branch is checked again after every change it can read, which the table in [Wait, Signals and Child Flows](#wait-signals-and-child-flows) lists, and so is the `check` of `env.watch_changes` in the low-level API. In a model with many waits on conditions and many changes, the work grows in proportion to both. ______________________________________________________________________ ## Example: Process Events The `process-events` example combines the event features of this page: - A guard starts an alarm round and is told when it ends (`subscribe`). - A packed order fires the `ready` signal from its own payload, for a waiting shipper (an `on:` action with `fire ... from`). - A one-shot `closing` signal has an `on:` action that spawns a sweep one second later (`spawn` with `after`). The arrival gaps are set so that each of these happens once. It needs no Docker service and ends on its own after 12 simulation seconds. ```yaml signals: # ready re-arms; the one-shot closing fires once and spawns a sweep ready: {once: false} closing: once: true on: - spawn: {task: sweep, after: 1 s} arrivals: orders: {dist: constant, value: 6, spawn: pack} shippers: {dist: constant, value: 7, spawn: ship} closers: {dist: constant, value: 9, spawn: close} guards: {dist: constant, value: 8, spawn: guard} tasks: # A packed order fires ready from its own finished payload; a shipper reads it pack: service: packing payload: {event_type: order_packed} on: - fire: {signal: ready, from: pack} ship: wait: {signal: ready} payload: {event_type: order_shipped} # Fires the one-shot closing when the shop closes close: signal: closing payload: {event_type: shop_closed} sweep: service: sweeping payload: {event_type: floor_swept} # The guard starts an alarm round and is interrupted when it ends guard: service: guarding subscribe: {task: alarm} on_interrupt: abandon payload: {event_type: shift_done} alarm: service: alarming payload: {event_type: alarm_rang} ``` ```python app = ( SimulationContext(sim_id="Shop", factor=0, random_seed=42) .add_egress(ConsoleEgress()) .add_service("packing", dist="constant", value=2) .add_service("alarming", dist="constant", value=2) .add_service("sweeping", dist="constant", value=1) .add_service("guarding", dist="constant", value=100) # A plain signal re-arms; the one-shot closing fires once and spawns a sweep .add_signal("ready", once=False) .add_signal("closing", once=True, on=[{"spawn": {"task": "sweep", "after": 1}}]) .add_arrival("orders", dist="constant", value=6) .add_arrival("shippers", dist="constant", value=7) .add_arrival("closers", dist="constant", value=9) .add_arrival("guards", dist="constant", value=8) ) # A packed order fires ready from its own finished payload; a shipper reads it @app.task(service_id="packing", on=[{"fire": {"signal": "ready", "from": "pack"}}]) def pack(task_id): return {"event_type": "order_packed"} @app.task(wait={"signal": "ready"}) def ship(task_id): return {"event_type": "order_shipped"} # Fires the one-shot closing when the shop closes @app.task(signal="closing") def close(task_id): return {"event_type": "shop_closed"} @app.task(service_id="sweeping") def sweep(task_id): return {"event_type": "floor_swept"} # The guard starts an alarm round and is interrupted when it ends @app.task(service_id="guarding", subscribe={"task": "alarm"}, on_interrupt="abandon") def guard(task_id): return {"event_type": "shift_done"} @app.task(service_id="alarming") def alarm(task_id): return {"event_type": "alarm_rang"} ``` The low-level version uses plain SimPy for each of these: a `Signal`, an interrupt handled by `env.any_of`, and `simpy.util.start_delayed`. The whole file is in the Low-level tab of the Quick Start below. Run the example in the form you use: **Quick Start** `desflow examples get` downloads the example at the release you install, into a folder of its own. Pick uv or pip: ```bash # 1. Install uv tool install desflow # 2. Download the example desflow examples get process-events --api yaml cd process-events/yaml # 3. Run it desflow run process_events.yaml ``` ```bash # 1. Install pip install desflow # 2. Download the example desflow examples get process-events --api yaml cd process-events/yaml # 3. Run it desflow run process_events.yaml ``` The whole file is [`examples/yaml/process_events.yaml`](https://github.com/jaehyeon-kim/desflow/blob/v1.3.0/examples/yaml/process_events.yaml). **Quick Start** `desflow examples get` downloads the example at the release you install, into a folder of its own. Pick uv or pip: ```bash # 1. Install uv tool install desflow # 2. Download the example desflow examples get process-events --api builder cd process-events/builder # 3. Run it uv run --no-project --with desflow process_events_example.py ``` ```bash # 1. Install pip install desflow # 2. Download the example desflow examples get process-events --api builder cd process-events/builder # 3. Run it python process_events_example.py ``` The whole file is [`examples/builder/process_events_example.py`](https://github.com/jaehyeon-kim/desflow/blob/v1.3.0/examples/builder/process_events_example.py). **Quick Start** `desflow examples get` downloads the example at the release you install, into a folder of its own. Pick uv or pip: ```bash # 1. Install uv tool install desflow # 2. Download the example desflow examples get process-events --api low-level cd process-events/low-level # 3. Run it uv run --no-project --with desflow process_events_example.py ``` ```bash # 1. Install pip install desflow # 2. Download the example desflow examples get process-events --api low-level cd process-events/low-level # 3. Run it python process_events_example.py ``` The whole file is [`examples/low-level/process_events_example.py`](https://github.com/jaehyeon-kim/desflow/blob/v1.3.0/examples/low-level/process_events_example.py). # Failures This page shows when a [task](https://jaehyeon.me/desflow/latest/user-guide/tasks-and-processes/tasks/index.md) fails and what happens next. ______________________________________________________________________ ## What It Is A failure is a task that does not finish its work: an order that fails its check, a wait that fails, code that raises an error. desflow records it, then sends the entity to a task that handles it, or ends the entity's flow. A task fails in these cases: - Its `fail` condition holds after its service. `fail` reads the task's own payload as `payload.`, as `next` does. - The wait it needs fails, or the child flow it waits for fails. - A step raises an error, or an expression cannot be evaluated: a `service_time`, a `payload` field, a `gen: expr`. A builder task's function that raises an exception fails it too. ______________________________________________________________________ ## How to Use It ### Declare a Failure A task declares when it fails with `fail`, why with `fail_reason`, and where the entity goes with `on_fail`. `fail_reason` is text, a number or a generator read when the task fails. A reason of `None`, such as a generator that returns nothing, falls back to the text of the `fail` condition, and an empty text or 0 stays as the reason. An error in the generator fails the task, with the error's type and place as the reason. The task that `on_fail` names reads the failure as `upstream.status` (`failed`) and `upstream.reason`. `on_fail` needs no `fail`: a failed wait, a failed child flow, a step that raises and an expression that cannot be evaluated go to it too. ```yaml pack: service: packing resource: packers # The task fails when this condition holds after its service fail: t > 12 # The reason is text, a number or a generator fail_reason: after the cut-off # Where the order goes after a failure; it reads upstream.status and upstream.reason on_fail: refund payload: {event_type: packed} refund: payload: event_type: refunded why: {gen: expr, expr: upstream.reason} ``` ```yaml check: # The wait fails when the child flow fails; on_fail needs no fail condition wait: {task: inspect} on_fail: hold payload: {event_type: checked} inspect: service: packing fail: t > 12 fail_reason: failed inspection payload: {event_type: inspected} hold: payload: event_type: held why: {gen: expr, expr: upstream.reason} ``` `@app.task(fail="t > 12", fail_reason="after the cut-off", on_fail="refund")` takes the same keys, and keeps an empty or 0 reason as YAML does. The Builder tab of [Handle a Failure Nobody Handles](#handle-a-failure-nobody-handles) runs a task that fails with no `on_fail`. A process catches the exception of the child it yields, as SimPy code does: `try: yield env.process(inspect())` with `except Exception as error:`. It then starts what `on_fail` would start. ### Handle a Failure Nobody Handles `run.on_unhandled_failure` sets what happens to a failure of a task, child flow or one-shot signal that nobody handles. It has two values: - `stop`, the default in YAML, the builder and the low-level API: the failure stops the run, as plain SimPy does. A root task that fails with no `on_fail` raises an exception, and so does a one-shot signal failed with nobody waiting. The exception reaches the caller of `run()`. - `continue`: the failure is marked as handled (SimPy calls this defused), and the run goes on. A data generator should not stop on one failed order. The builder and YAML switch to `continue` with `run(on_unhandled_failure="continue")` or `run: {on_unhandled_failure: continue}`, and the low-level API with `DynamicRealtimeEnvironment(on_unhandled_failure="continue")`. In the low-level API, an exception raised in a process always reaches the process that yields it, and one nobody handles stops the run, as in SimPy. One signal failure can be defused alone with `defused` ([Signals and Waiting](https://jaehyeon.me/desflow/latest/user-guide/tasks-and-processes/signals-and-waiting/#actions-when-an-event-happens)). Under `run`: ```yaml # stop, the default, raises a failure nobody handles to the caller of run(); # continue defuses it and the run goes on on_unhandled_failure: continue ``` Under `stop`, the failure reaches the caller of `run()` as an exception. `TaskFailed` names the task and the reason, and this prints `pack failed: after the cut-off`: ```python # Under stop, the first failure that no on_fail handles reaches the caller of run() try: shop().run(until=60, on_unhandled_failure="stop") except TaskFailed as failure: print(f"{failure.task} failed: {failure.reason}") ``` `stop` is the default. `DynamicRealtimeEnvironment(on_unhandled_failure="continue")` switches to `continue`. A run that stops on a signal raises `SignalFailed` when the signal fails, as [Run Length](https://jaehyeon.me/desflow/latest/user-guide/time-and-pacing/run-length/#stop-early) describes: `run.stop` names the signal. When the signal fails, `desflow run` reports the reason and exits with an error. This prints `closing failed: the till did not balance`: ```python # A run that stops on a signal raises the reason the signal failed with. The packing # failures are left to continue, so only the signal ends the run try: shop().run(until=60, on_unhandled_failure="continue", stop={"signal": "closing"}) except SignalFailed as failure: print(f"{failure.signal} failed: {failure.reason}") ``` `env.run(until=event)` on the signal's event raises the exception the event failed with, as in SimPy. ______________________________________________________________________ ## How It Works A failed task then does three things, in order: 1. It publishes `failed` instead of its finished payload, with a `reason`: the condition's text, or its `fail_reason`. 1. It fails its `signal`, so every task waiting for the signal fails too. 1. It goes to its `on_fail` task. Without `on_fail`, the entity's flow ends, and a child flow fails the task waiting for it, with the same reason. A failure nobody handles then follows `on_unhandled_failure`. At the `basic` statistics level and above, each failure is counted as `tasks..failed`, and each flow that ends in one as `flows..failed`. The `inspect` task of the example in [Signals and Waiting](https://jaehyeon.me/desflow/latest/user-guide/tasks-and-processes/signals-and-waiting/#wait-signals-and-child-flows) fails a gift and sends it to be wrapped. # Resources This page is the map of the section: what a resource is, and which page shows what. ______________________________________________________________________ ## What It Is A resource is a number of identical units: packers, packing benches, checkout lanes, loading bays. A task asks for one unit, waits in the resource's queue while every unit is busy, holds the unit while it works, and gives it back. How many units there are is the resource's capacity, and it can change while the run goes on, as when packers go on a break. ______________________________________________________________________ ## Pages in This Section - [Units and Queues](https://jaehyeon.me/desflow/latest/user-guide/resources/units-and-queues/index.md): declare a resource, order its queue, limit the line, read who holds a unit, and see what a change of capacity does. - [Priority and Preemption](https://jaehyeon.me/desflow/latest/user-guide/resources/priority-and-preemption/index.md): rank waiting requests by task priority or an expression, let a more urgent request take a unit from a less urgent task, and fail a resource at random. A lower `priority` value is more urgent. - [Several Resources](https://jaehyeon.me/desflow/latest/user-guide/resources/several-resources/index.md): hold several resources in one task, and the order in which tasks acquire them. - [Custom Resource Types](https://jaehyeon.me/desflow/latest/user-guide/resources/custom-resource-types/index.md): change how a resource grants units with your own class. ______________________________________________________________________ ## How to Use It Pick the page by the job: | To do this | Read | | -------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | Give a task a resource and set how many units there are | [Units and Queues](https://jaehyeon.me/desflow/latest/user-guide/resources/units-and-queues/#declare-a-resource) | | Let an order give up waiting, or turn it away from a long line | [Tasks](https://jaehyeon.me/desflow/latest/user-guide/tasks-and-processes/tasks/#leave-the-line) and [Queue Limit](https://jaehyeon.me/desflow/latest/user-guide/resources/units-and-queues/#queue-limit) | | Serve urgent work first, or let it take a unit | [Priority and Preemption](https://jaehyeon.me/desflow/latest/user-guide/resources/priority-and-preemption/index.md) | | Hold a picker and a bench together | [Several Resources](https://jaehyeon.me/desflow/latest/user-guide/resources/several-resources/index.md) | | Take packers off the floor for a time | [Units and Queues](https://jaehyeon.me/desflow/latest/user-guide/resources/units-and-queues/#under-live-changes) | | Grant units by a rule of your own | [Custom Resource Types](https://jaehyeon.me/desflow/latest/user-guide/resources/custom-resource-types/index.md) | ______________________________________________________________________ ## How It Works A resource keeps a line of waiting requests and a list of the requests that hold a unit, as SimPy's `Resource` does, and follows its capacity in the registry. [How It Works](https://jaehyeon.me/desflow/latest/user-guide/resources/units-and-queues/#how-it-works) on Units and Queues describes the grant. Amounts and items that tasks take and add, rather than hold, are [Stores and Containers](https://jaehyeon.me/desflow/latest/user-guide/model-parts/stores-and-containers/index.md). # Units and Queues A resource is what an entity must hold while it works, and may have to wait for. This page shows how to declare one, how its queue is ordered, how it hands out units, and what happens when its capacity changes during a run. The class behind it is `DynamicResource`. ______________________________________________________________________ ## What It Is A resource is a number of identical units: packers, packing benches, checkout lanes, loading bays. A task asks for one unit, waits in the resource's queue while every unit is busy, holds the unit while it works, and gives it back. How many units there are is the resource's capacity, and it can change while the run goes on, as when packers go on a break. ______________________________________________________________________ ## How to Use It ### Declare a Resource Two whole numbers set the size of a resource, and both may be left out: - `current_cap` is the number of units now. Left out, it is 1, so `packers: {}` is a resource of one unit, as `simpy.Resource(env)` is. - `max_cap` is the most units a live change can set. Left out, it equals `current_cap`. `current_cap: .inf` (`float("inf")` in Python) is a resource with no limit. Every request is granted at once, `capacity` is published as `null` and `utilization` as 0. A capacity or `queue_limit` below 0, `true` or a fraction for a whole number is refused, naming the resource. A name used by two of the resources, stores, containers and signals is refused too, because they are one set of names, and so is a name with a dot or a space, which an expression cannot name, or with a character that an expression reads as another, such as `µ`. `queue_limit` sets the most requests that may wait, as [Queue Limit](#queue-limit) describes. `run()` builds a `DynamicResource` for each resource the context declares. In the low-level API you build it yourself, after registering the parameters. A resource of one unit needs no registration at all: ```yaml resources: # fifo (the default), lifo or priority; priority serves the lowest number first, # and equal priorities first in, first out packers: {current_cap: 1, max_cap: 4, queue: priority} ``` ```python app = SimulationContext(sim_id="Shop", factor=0.0) # fifo (the default), lifo or priority app.add_resource("packers", current_cap=1, max_cap=4, queue="priority") ``` ```python packers = DynamicResource(env, "Shop", "packers") # capacity from the registry: 2 def order(env, order_id): with packers.request() as request: yield request # waits until a unit is free yield env.timeout(10.0) # holds the unit for 10 s # leaving the with block releases the unit ``` `packers.request()` is an event that happens when a unit is granted, and leaving the `with` block gives the unit back. A request whose `with` block is left before it is granted, for example after a timeout, is cancelled and never takes a unit. ### Queue Order `queue` sets the order in which a resource serves the requests waiting for it: - `fifo`, the default: the oldest first; - `lifo`: the newest first; - `priority`: the lowest priority number first, and the oldest first among equal priorities. Four requests that join while the only unit is busy are served in these orders: `queue` sits beside the capacity: `packers: {current_cap: 1, queue: lifo}`. `app.add_resource("packers", current_cap=1, queue="lifo")`. ```python def served_order(queue): """Four requests join while the only bench is busy; returns who is served when.""" env = DynamicRealtimeEnvironment(factor=0.0) env.registry.register_sim_parameter( SimParameter( sim_id="Shop", resources={"benches": CapacityConfig(current_cap=1, max_cap=1)}, ) ) bench = DynamicResource(env, "Shop", "benches", queue=queue) served = [] def use(name, priority, after=0.0): yield env.timeout(after) # The priority counts only under the priority order with bench.request(priority=priority) as request: yield request served.append(name) yield env.timeout(1.0) env.process(use("first", 1)) # takes the bench at once for name, priority in [ ("orders-1", 1), ("express-1", 0), ("orders-2", 1), ("express-2", 0), ]: env.process(use(name, priority, after=0.1)) # all join while it is busy env.run(until=10) return served[1:] for queue in ("fifo", "lifo", "priority"): print(f"{queue:<8} {', '.join(served_order(queue))}") ``` ```text fifo orders-1, express-1, orders-2, express-2 lifo express-2, orders-2, express-1, orders-1 priority express-1, express-2, orders-1, orders-2 capacity 2, in use 4 ``` The last line is a capacity drop, which [Under Live Changes](#under-live-changes) describes below. The same four requests, drawn: ### Queue Limit `queue_limit` sets the most requests that may wait for a resource. With a limit of 5, a request made while five requests wait already is refused, as SimPy's `SortedQueue(maxlen=5)` does. Set it with `queue_limit: 5` in a blueprint, `add_resource(..., queue_limit=5)` in the builder, or the same argument of `DynamicResource`. The refusal comes before a grant or a preemption, so a limit of 0 refuses every request. A task that is refused **balks**: it leaves without being served. It gives back the units it holds, publishes `balked` with the name of the resource, counts as balked and ends its flow. When it balks depends on how it asked: - A task whose first resource is the limited one, with no wait before it, balks before it publishes `queued`. - A `request` branch of a `wait`, in an `any` or an `all`, fails the wait at once, with SimPy's message "Cannot append event. Queue is full.". - A `request` branch that has won its wait and then loses the unit to preemption asks for a unit again. The task balks if the line is full then. It reneges, that is, leaves the line, if its patience runs out while it waits, as for a `resource:` unit. - In the low-level API, `request()` raises `QueueFull` (in `desflow.resources`), a `RuntimeError` with that message. Your process catches it as it would catch a balk condition. A request that reneges or is cancelled leaves the line and makes room for the next. A limit can change during a run through the registry path `.resources..queue_limit`, set by a scenario step, an `on:` action or a low-level `registry.update`. It applies from the next request, a smaller limit removes nobody who waits, and `null` is no limit. A resource with a `PutQueue` of its own has no such path. A limit is changed through the path and not by assigning `queue_limit`, which is read-only. [Refuse to Join](https://jaehyeon.me/desflow/latest/learn/shop-logic/patience/#refuse-to-join) shows the other way an order balks, by a condition of its own. In a blueprint, `queue_limit` sits beside the capacity. `packers` has the default of one unit, and refuses a fourth waiting request: ```yaml resources: # No capacity: one unit. At most 3 requests wait; a fourth is refused. packers: {queue_limit: 3} # No limit: every request is granted at once benches: {current_cap: .inf} ``` `app.add_resource("packers", queue_limit=3)` and `app.add_resource("benches", current_cap=float("inf"))`. `DynamicResource(env, "Shop", "packers", queue_limit=3)`. ### Cancel and Release A task leaves a queue when its patience runs out, when it is interrupted, or under `on_interrupt: abandon`. It then cancels its request, so the request is never granted later. Once a unit is granted, the task gives it back when it finishes, under `on_interrupt: abandon`, and when it is preempted (the preempting task has it then). A plain interrupt under `resume` or `restart` leaves the unit with the task. In the low-level API these are SimPy's calls: ```python held = packers.request() # granted at once: the packer was free waiting = packers.request() # waits behind it waiting.cancel() # leaves the queue at once; it is never granted held.cancel() # granted already, so this releases nothing, as in SimPy assert packers.in_use == 1 and packers.queue == [] released = packers.release(held) # gives the packer back assert released.request is held # the release is an event that holds its request packers.release(held) # a second release does nothing ``` `request.cancel()` takes a waiting request out of the queue, and does nothing to a granted one. `packers.release(request)` gives a granted unit back once. Releasing it again, or releasing a request that was never granted, gives nothing back. A release is an event, a `DynamicRelease`, as SimPy's `Release` is. Its `request` is the request it releases (with no request, the oldest unit held). It is triggered as soon as it is made, and the next waiting request is granted one event later, when the release is processed. A `with` block does both on its way out, as in SimPy. ### Read the Queue and Users A resource counts the units held and the requests waiting. In a condition, `users.` is how many units are held, and `queue.` is how many requests wait. A task can therefore turn an order away when the line is long, or wait until nobody holds a unit. The names are checked when the blueprint loads, as `level.` is: ```yaml tasks: pack_order: service: packing resource: packers # Turn an order away when two are waiting already balk: queue.packers >= 2 payload: {event_type: order_packed} close_up: # Wait until nobody holds a packer wait: {condition: users.packers < 1} payload: {event_type: packers_idle} ``` `context.get_resource("packers")` returns the running `DynamicResource`. Its `count` is the number of units held. `users` lists the requests that hold them, in the order of their grants. `queue` lists the waiting requests in the order they will be served, so `queue[0]` is served next. A request has `usage_since`, the time it was granted its unit, and `proc`, the process that made it. A task's process has the task's name. ```python def look(context): """A process of the model: reads the packers every 30 seconds.""" packers = context.get_resource("packers") while True: yield context.env.timeout(30) held = [ request.proc.name for request in packers.users ] # the tasks holding a unit seen.append((packers.count, len(packers.queue), held)) app.add_process(look) ``` ```python requests = [packers.request() for _ in range(4)] # two are granted, two wait assert packers.count == len(packers.users) == 2 # the units held now assert packers.users == requests[:2] # the granted requests, in the order of the grants assert len(packers.queue) == 2 # the requests waiting assert packers.queue[0] is requests[2] # the next to be served assert packers.users[0].usage_since == 0.0 # when this request was granted its unit ``` `count` is the same as `in_use`, SimPy's name for it. `queue` is a list of the waiting requests, in service order. ### Make a Family of Resources A resource with `family: true` is a family. Each member is an ordinary resource named after the family and its key in brackets, such as `desk[3]` or `desk['a.b']`. `members` makes that many when the run starts, and a member not made yet is made at its first use. A capacity written as text is read once, when the member is made, in the scope of the entity that makes it; a family with `members` reads the run, so `attr.` is refused there. A family's name alone in a place that wants a name is refused when the blueprint loads, and so is a declared name that starts with the family's name and a bracket. A registry path takes a bracketed part as one part, such as `S.resources.desk['a.b'].current_cap`. A scenario step or an `on:` action on a member's path is refused when the member has no such attribute, or when the family can never have the member: a family with `members: 2` makes only `desk[0]` and `desk[1]`, unless a task names the family with a `key`. It ends the run with `KeyError` when a task makes the member at its first use and it is not made yet at the step's time. A task picks a member with `{of: desk, key: ...}` or `{of: desk, lowest: ...}` ([Pick a Member of a Family](https://jaehyeon.me/desflow/latest/user-guide/tasks-and-processes/signals-and-waiting/#pick-a-member-of-a-family)). ```yaml resources: # Three desks, desk[0] to desk[2], each an ordinary resource of one unit desk: {family: true, members: 3, current_cap: 1} ``` `app.add_resource("desk", family=True, members=3, current_cap=1)` declares the same family. A family is a dictionary of resources that your code keeps, one `DynamicResource` for each key. ### Registry Paths and Readings Each resource has three registry paths, `.resources..current_cap`, `.max_cap` and `.queue_limit` (`None` when unset), which a scenario, an ingress message or a process can change. A live write is checked by the path's rule. `compile_parameters()` returns a `ResourceConfig` for a resource, which holds all three. [Live Parameters](https://jaehyeon.me/desflow/latest/user-guide/live-runs-and-connectors/live-parameters/index.md) explains how. A resource that breaks down adds `.breakdown..time_to_failure` and `.repair`, its two distributions. With statistics at the `minimal` level or above, each resource publishes four readings, such as `Shop.stats.resources.packers.utilization`: - `capacity`: the number of units, or `null` for a resource with no limit. - `in_use`: the units held by tasks. - `queue_length`: the requests waiting. - `utilization`: the units in use as a percentage of the capacity, or 0 for a resource with no limit. A resource that breaks down adds `down`, which is 1 while it is down. [Statistics](https://jaehyeon.me/desflow/latest/user-guide/results/statistics/index.md) lists what the other levels add, among them `downtime` and `failures`. ______________________________________________________________________ ## How It Works A `DynamicResource` grants units the way SimPy's `Resource` does, with two lists. `queue` holds the waiting requests, ranked by the queue order and then by a sequence number, so requests that rank the same are served in the order they arrived. `users` holds the granted requests. A request is granted when it is made if a unit is free and nothing waits ahead of it. Otherwise it waits, and each release grants the head of the queue when its release event is processed, one event later, as SimPy's `Release` does: Because each step is the one SimPy takes, two events at the same simulation time are granted in SimPy's order. A patience whose event comes before the grant at the same instant reneges, and this holds on a `request` branch of a `wait` too. This is SimPy's reneging pattern, `result = yield request | env.timeout(patience)` with `request not in result` when the patience wins. `in_use` counts `users`: it goes up when a request is granted and down when a unit is released. A waiting request leaves the queue at once when it is cancelled. A `with` block cancels it when the block is left before the grant, and `request.cancel()` does the same by hand. `packers.release(request)` gives a granted unit back. Cancelling a granted request releases nothing, and releasing a request twice, or one never granted, gives nothing back, as in SimPy. Every release still tries the head of the queue when its release event is processed, as SimPy's does: when a request that reneged was the head, the request behind it may then be granted or preempt a user. **SimPy and desflow.** SimPy's `Resource` serves requests in the order they arrive, and `PriorityResource` by priority. Both take their capacity when they are created and keep it: `capacity` has no setter, so assigning a new one raises `AttributeError` (SimPy 4.1). desflow builds its own resource, so that the capacity can follow the registry and the queue order can be chosen. The `request()` call and the `with` block are SimPy's, so code written for SimPy works unchanged. [SimPy and desflow](https://jaehyeon.me/desflow/latest/simpy/index.md) compares the two. ______________________________________________________________________ ## Under Live Changes A change to `current_cap` takes effect at once, without stopping any work: - **Growing** grants waiting requests at once, up to the new capacity. - **Shrinking** stops nothing. The units still busy above the new capacity are owed: each one given back brings the busy count down, and no waiting task starts until the busy count is within the new capacity. - **Growing again** before the owed units are given back cancels them first, so only the rest of the rise grants waiting requests. - A `current_cap` outside 0 to `max_cap` is clamped to that range, with a warning. - **Lowering `max_cap`** lowers the capacity with it. A `current_cap` above the new `max_cap` is stored as `max_cap`, with a warning. - **During a repair** the capacity is 0 and `current_cap` keeps the planned value. A change to it sets the capacity the resource returns to and does not end the repair. The example below takes three of five packers off the floor while four orders are being packed: the capacity is 2 at once, and `in_use` stays 4 until two orders finish. The animation steps through it: A scenario step makes the same change at a set time: `scenario: [{at: 5, path: Shop.resources.packers.current_cap, value: 2}]`. [Live Parameters](https://jaehyeon.me/desflow/latest/user-guide/live-runs-and-connectors/live-parameters/#script-an-experiment) explains the steps. `app.add_scenario([{"at": 5, "path": "Shop.resources.packers.current_cap", "value": 2}])` makes the same change at a set time. ```python def capacity_drop(env): """Takes 3 of 5 packers off the floor at t=5 s. Orders being packed are not stopped.""" env.registry.update("Shop.resources.packers.current_cap", 5) yield env.timeout(5.0) env.registry.update("Shop.resources.packers.current_cap", 2) yield env.timeout(0.1) # the resource applies the change in its own process print(f"capacity {packers.capacity}, in use {packers.in_use}") ``` Until the owed units finish, `in_use` is above `capacity`, and the `utilization` reading is above 100%. ______________________________________________________________________ ## Stability and Limits - **Utilisation decides waits.** A resource whose load is at or above its capacity has a queue that grows for as long as the run lasts. [Queues and Capacity](https://jaehyeon.me/desflow/latest/learn/first-model/queues-and-capacity/index.md) shows how to work it out, and [Queueing Basics](https://jaehyeon.me/desflow/latest/learn/concepts/queueing-basics/#utilisation) explains utilisation. - **Priority needs `queue: priority`.** A task priority on a resource of another order, or on one with a `rank`, is a load error, while a low-level request's priority is ignored under `fifo` and `lifo`. - **Priority can starve.** Under `priority`, a request with a high number is served only when no lower number is waiting. If the low numbers alone keep the resource busy, it is never served. - **One order of acquisition.** A model whose tasks acquire two resources in opposite orders loads and logs one WARNING. [Several Resources](https://jaehyeon.me/desflow/latest/user-guide/resources/several-resources/#several-resources) explains why. - **A shrink never stops work.** Lowering `current_cap` lets busy units finish. Work in progress stops only for an interrupt, a preemption or a breakdown: [Interruptions](https://jaehyeon.me/desflow/latest/learn/shop-logic/interruptions/index.md), and [Model Breakdowns](https://jaehyeon.me/desflow/latest/how-to/modelling/breakdowns/index.md) for a machine that fails. - **A preempted task queues again.** With `resume` or `restart` it joins the back of its priority among the waiting requests, as a new SimPy request does. The time it waited before counts in its wait. Amounts and items that tasks take and add, rather than hold, are [Stores and Containers](https://jaehyeon.me/desflow/latest/user-guide/model-parts/stores-and-containers/index.md). # Priority and Preemption This page covers three features of a [resource](https://jaehyeon.me/desflow/latest/user-guide/resources/units-and-queues/index.md). Task priority ranks the waiting requests: a lower `priority` value is served first. Preemption lets a request take a unit from a task whose `priority` value is higher than its own. A breakdown takes every unit away until a repair. ______________________________________________________________________ ## What It Is In a shop, some work cannot wait its turn. An express order goes before regular ones, an urgent job takes a packer from a routine one, and a machine breaks down and must be repaired. Priority orders the waiting line, preemption lets an urgent task take a unit that is in use, and a breakdown takes a resource out of service for a time. ______________________________________________________________________ ## How to Use It ### Task Priority Under `queue: priority`, waiting requests are served by priority, not in the order they arrived. A lower `priority` value is served first, and a task with no `priority` ranks 0, as a SimPy `PriorityRequest` does. Requests with equal priorities are served first in, first out, as in SimPy's `PriorityResource`. A task's priority can be: - a number, the same for every run of the task; - an expression, read when the task joins the queue, such as `attr.tier` for the entity's attribute `tier`, or `payload.` for the previous task's payload; - in the builder, a function of the task id and the entity's attributes. A priority cannot read the task's own payload, because the payload does not exist yet when the request joins the queue. For a rule that ranks by an expression of the run, see [Rank the Line by an Expression](#rank-the-line-by-an-expression). ```yaml tasks: pack_order: service: packing resource: packers # A number, or an expression read when the order joins the queue priority: attr.tier payload: {event_type: order_packed} ``` ```python app = ( SimulationContext(sim_id="Shop", factor=0.0, random_seed=42) .add_resource("packers", current_cap=1, max_cap=4, queue="priority") .add_service("packing", dist="constant", value=1.5) # An order every 2 s on average (rate 0.5) .add_arrival("orders", dist="exponential", rate=0.5, attributes={"tier": 2}) ) # Each order's own priority, from its attributes, when it joins the queue; # a number or an expression such as "attr.tier" works too @app.task( service_id="packing", resource_id="packers", priority=lambda task_id, attributes: attributes["tier"], ) def pack_order(task_id: int): return {"event_type": "order_packed"} ``` A low-level process passes the priority to the request: `packers.request(priority=entity.attributes["tier"])`, as the queue-order example above does. A request with no priority has priority 0. A resource whose queue is `fifo` or `lifo` ignores it. A `priority` on a task whose resource does not have `queue: priority` is refused when the blueprint loads, or when `run()` starts. A priority that is NaN or text fails the task, with a message that names the task and the value. [Priorities](https://jaehyeon.me/desflow/latest/learn/shop-logic/priorities/index.md) shows what priority does to waits. ### Preemption On a resource with `preempt: true`, which needs `queue: priority`, a request does not always wait for a unit to come free. When every unit is busy, it takes a unit from a task with a higher `priority` value, as SimPy's `PreemptiveResource` does. That task is **preempted**: it loses the unit before its service ends. The task with the highest `priority` value loses it, and only when that value is higher than the new request's. Among tasks with equal values, the one that asked last loses it. A task with the same priority as the new request keeps its unit. A task with `preempt: false` never takes a unit this way. Look at an express request that arrives while both packers serve regular orders: The request of a preempted task is marked as preempted. If the unit belonged to a flow that has ended, the preemption fails the flow that asked, as SimPy's `RuntimeError` does. A `seize` unit is asked for again under `resume` and `restart`. The preempted task publishes `preempted` with the resource's name, the key of the entity that took the unit (`preempted_by`) and the time the task was granted the unit (`usage_since`). It then follows its `on_interrupt`: `resume`, `restart` or `abandon`, and `on_interrupt_run` or `on_interrupt_next` where the task names one ([Interrupts](https://jaehyeon.me/desflow/latest/user-guide/tasks-and-processes/tasks/#interrupts), and the tutorial [Interruptions](https://jaehyeon.me/desflow/latest/learn/shop-logic/interruptions/index.md)). The `interruptions` example lets express orders preempt regular ones: ```yaml # A lower priority value takes the packer from a higher one. packers: {current_cap: 1, max_cap: 4, queue: priority, preempt: true} ``` ```yaml tasks: pack: service: packing resource: packers priority: attr.priority # A preempted order queues again and serves what it had left; an interrupted one # goes on with its packer. on_interrupt: resume payload: {event_type: order_packed} attributes: [priority] ``` ```python # A lower priority value takes the packer from a higher one .add_resource("packers", current_cap=1, max_cap=4, queue="priority", preempt=True) ``` ```python @app.task( service_id="packing", resource_id="packers", priority="attr.priority", # A preempted order queues again and serves what it had left; an interrupted one # goes on with its packer on_interrupt="resume", ) def pack(task_id, context, entity): return {"event_type": "order_packed", "priority": entity.attributes["priority"]} ``` ```python def pack(env, sampler, shop, key, priority, task_id): """Packs one order; a preemption sends it back to the queue with the packing time it had left, and an interrupt keeps its packer, as `on_interrupt` does.""" path_id = "Shop.service.packing" def publish(value): env.publish_event(key, value, task="pack", instance=task_id) env.stats.flow_started(key.rsplit("-", 1)[0]) # the order enters the shop publish( {"path_id": path_id, "sim_id": "Shop", "service": "packing", "status": "queued"} ) env.stats.task_queued("pack", task_id) remaining, started = None, False shop["packing"].append(env.active_process) shop["keys"][env.active_process] = key request = None while True: if request is None: request = shop["packers"].request(priority=priority) since = None try: if not request.processed: yield request if not started: started = True publish( { "path_id": path_id, "sim_id": "Shop", "service": "packing", "status": "started", } ) env.stats.task_started("pack", task_id) else: publish( { "path_id": path_id, "sim_id": "Shop", "service": "packing", "status": "resumed", } ) env.stats.task_resumed("pack", task_id) if remaining is None: remaining = sampler.sample(env.registry.get_config(path_id)) since = env.now yield env.timeout(remaining) payload = {"event_type": "order_packed", "priority": priority} publish(payload) env.stats.task_finished("pack", task_id) shop["packers"].release(request) break except simpy.Interrupt as interrupt: if since is not None: remaining -= env.now - since if request not in shop["packers"].users: # Queued, or preempted: ask again. A unit still held is kept. request.cancel() request = None if isinstance(interrupt.cause, Preempted): value = { "path_id": path_id, "sim_id": "Shop", "service": "packing", "status": "preempted", "resource": "packers", "preempted_by": shop["keys"].get(interrupt.cause.by), "usage_since": interrupt.cause.usage_since, } publish(value) env.stats.task_interrupted("pack", task_id, preempted=True) else: value = { "path_id": path_id, "sim_id": "Shop", "service": "packing", "status": "interrupted", } publish({**value, "cause": interrupt.cause}) env.stats.task_interrupted("pack", task_id) shop["packing"].remove(env.active_process) del shop["keys"][env.active_process] env.stats.flow_finished(key.rsplit("-", 1)[0]) ``` `DynamicResource(env, "Shop", "packers", queue="priority", preempt=True)` builds the resource, and `request(priority, preempt=True)` asks for a unit. The process that loses its unit receives `simpy.Interrupt` with a SimPy `Preempted` cause, whose `resource`, `by` (the process that took the unit) and `usage_since` say what happened. A gift order with `preempt: false` is served before any regular order that waits. But it waits for the packer to be free, rather than take it from a regular order being packed: ```yaml pack_gift: service: packing resource: packers # Served before any regular order that waits, but waits for the packer to be free priority: 0 preempt: false payload: {event_type: gift_packed} ``` `@app.task(..., priority=0, preempt=False)` sets the same on a builder task. `request(priority=0, preempt=False)` asks for a unit without taking one from a lower-priority order. ### Rank the Line by an Expression `queue: {rank, ties}` ranks the line by an expression instead of a task `priority`. `rank` is read as each request is made, in the scope of the task that makes it, and the lowest rank is served first. `ties` orders equal ranks: `fifo`, the default, serves the oldest first, and `lifo` the latest first. It changes the order of the line only, not who preempts. A task `priority` for a resource that has a `rank` is refused when the blueprint loads. `preempt` on a resource can be a rule, `preempt: {when, victim}`. `when` is tested when a request finds no free unit, and the request takes a unit if it holds. `victim` gives each holder a value, and the holder with the highest value is the one `when` is tested on, the first granted among equals. Both read `request.rank`, `request.time`, `request.preempt` and `request.key`, and `holder.rank`, `holder.time`, `holder.preempt`, `holder.key`, `holder.since` and `holder.attr.`. A `preempt` on a task, a `seize` or a `request` mapping is a boolean, a word such as `"t"` or an expression. A `request: {resource, priority, preempt}` branch of a wait gives each branch its own rank. A mapping that leaves out `priority` or `preempt` is SimPy's `request()`, with priority 0 and preempt true, and does not take the task's values. A rank or priority that is NaN or text is refused naming the holder and the task. ```yaml resources: packers: current_cap: 1 max_cap: 3 # The line is ranked by an expression read as each request joins; the lowest rank # is served first, and equal ranks are served the latest first queue: {rank: attr.tier, ties: lifo} # A request takes a unit only from a holder whose rank is 2 or more above its own preempt: {when: "holder.rank - request.rank >= 2", victim: holder.rank} ``` `app.add_resource("packers", queue={"rank": "attr.tier", "ties": "lifo"}, preempt={"when": "...", "victim": "..."})` takes the same mappings. A request carries its priority, and a subclass of `ResourceBase` decides the order and who is taken ([Custom Resource Types](https://jaehyeon.me/desflow/latest/user-guide/resources/custom-resource-types/index.md)). ### Read Who Holds a Unit An expression reads the holders and the line of a resource: `held(r)` lists the requests that hold a unit and `waiting(r)` the requests in line, each a mapping with `entity`, `rank`, `time`, `preempt`, `key` and `since`. A task that an `on_interrupt_next` edge reaches reads why it was interrupted as `cause.by`, `cause.usage_since` and `cause.left`; `cause.` is refused where no `on_interrupt_next` edge reaches the task. ```yaml payload: event_type: packed # held(r) lists the units in use and waiting(r) the requests in line, each with # its entity, rank and time in_use: {gen: expr, expr: "len(held(packers))"} waiting: {gen: expr, expr: "len(waiting(packers))"} ``` A task function reads the resource directly, as [Units and Queues](https://jaehyeon.me/desflow/latest/user-guide/resources/units-and-queues/#read-the-queue-and-users) shows; a `Template` takes the same expressions as the YAML tab. `packers.users` and `packers.queue` are the lists, and a request has `usage_since`. ### Breakdowns A `breakdown` makes a resource fail at random and be repaired. `time_to_failure` is the time from the start, or from a repair, to the next failure. With `clock: calendar`, the default, it counts all simulation time from the start or the last repair, busy or idle. With `clock: busy` it counts only the time a unit is in use, and a `seize`, a `resource:`, a wait `request` and an `open` unit all count as in use. A custom resource type calls the base `_do_put` and `_do_get`, which wake `when_busy()` and `when_idle()`, so its busy time counts too. `repair` is how long a repair takes. While the resource is down its effective capacity is 0 and no request is granted: ```yaml resources: station: current_cap: 2 max_cap: 3 breakdown: # Calendar time from a repair, or the start, to the next failure. # A failure every 60 s on average (rate 0.0167) time_to_failure: {dist: exponential, rate: 0.0167} repair: {dist: uniform, low: 5 s, high: 15 s} # The orders being packed are interrupted, and follow their on_interrupt. work: interrupt ``` ```python .add_resource("station", current_cap=2, max_cap=3) .add_breakdown( "station", # Calendar time from a repair, or the start, to the next failure # A failure every 60 s on average (rate 0.0167) time_to_failure={"dist": "exponential", "rate": 0.0167}, repair={"dist": "uniform", "low": 5, "high": 15}, # The orders being packed are interrupted, and follow their on_interrupt work="interrupt", ) ``` ```python breakdowns={ "station": BreakdownConfig( # Calendar time from a repair, or the start, to the next failure # A failure every 60 s on average (rate 0.0167) time_to_failure=DistributionConfig(dist="exponential", rate=0.0167), repair=DistributionConfig(dist="uniform", low=5, high=15), # The orders being packed are interrupted work="interrupt", ) }, ``` Start `run_breakdowns(env, station, sampler, work="interrupt")` as a SimPy process beside the arrivals. `station.fail()` and `station.repair()` put a resource down and back by hand. A resource can set the clock in the three forms: `clock: busy` under `breakdown` in YAML, `add_breakdown(clock="busy")` in the Builder, and `run_breakdowns(clock="busy")` or `BreakdownConfig(clock="busy")` in the Low-level API. [Model Breakdowns](https://jaehyeon.me/desflow/latest/how-to/modelling/breakdowns/#count-only-the-time-the-station-works) shows each. `work` says what happens to the tasks being served. Under `interrupt`, the default, each task is interrupted with the cause `breakdown` and follows its `on_interrupt`. Under `finish`, the tasks finish their work. Each failure and repair publishes an event keyed by the resource's name, with `status` `down` or `repaired` and `reason: failure`. [Model Breakdowns](https://jaehyeon.me/desflow/latest/how-to/modelling/breakdowns/index.md) checks the downtime of the example, and [Interruptions](https://jaehyeon.me/desflow/latest/learn/shop-logic/interruptions/index.md) explains `on_interrupt`. ______________________________________________________________________ ## How It Works SimPy ranks a request by `(priority, time, not preempt)`. So among requests with equal priorities made at the same time, a request that may preempt goes before one with `preempt: false`. The tests check it, ties included, in all three APIs ([SimPy Compatibility](https://jaehyeon.me/desflow/latest/simpy/compatibility/index.md)). SimPy's exact rule SimPy sorts the tasks holding a unit by `(priority, request time, may not preempt)`. The task that sorts last loses its unit, but only when it also sorts after the new request. A task with the same priority asked earlier than the new request, so it sorts before it and keeps its unit. The one exception is a task with the same priority that asked at the same moment, with `preempt: false`: it sorts after a request that may preempt, and loses its unit. ______________________________________________________________________ ## Example: Interruptions In the `interruptions` example, express orders preempt regular ones, and a fire drill at 60 seconds interrupts the order being packed. Each interrupted order resumes with the packing time it had left. It needs no Docker service and ends on its own after 120 simulation seconds. The tutorial page [Interruptions](https://jaehyeon.me/desflow/latest/learn/shop-logic/interruptions/index.md) teaches these features step by step. **Quick Start** `desflow examples get` downloads the example at the release you install, into a folder of its own. Pick uv or pip: ```bash # 1. Install uv tool install desflow # 2. Download the example desflow examples get interruptions --api yaml cd interruptions/yaml # 3. Run it desflow run interruptions.yaml ``` ```bash # 1. Install pip install desflow # 2. Download the example desflow examples get interruptions --api yaml cd interruptions/yaml # 3. Run it desflow run interruptions.yaml ``` The whole file is [`examples/yaml/interruptions.yaml`](https://github.com/jaehyeon-kim/desflow/blob/v1.3.0/examples/yaml/interruptions.yaml). **Quick Start** `desflow examples get` downloads the example at the release you install, into a folder of its own. Pick uv or pip: ```bash # 1. Install uv tool install desflow # 2. Download the example desflow examples get interruptions --api builder cd interruptions/builder # 3. Run it uv run --no-project --with desflow interruptions_example.py ``` ```bash # 1. Install pip install desflow # 2. Download the example desflow examples get interruptions --api builder cd interruptions/builder # 3. Run it python interruptions_example.py ``` The whole file is [`examples/builder/interruptions_example.py`](https://github.com/jaehyeon-kim/desflow/blob/v1.3.0/examples/builder/interruptions_example.py). **Quick Start** `desflow examples get` downloads the example at the release you install, into a folder of its own. Pick uv or pip: ```bash # 1. Install uv tool install desflow # 2. Download the example desflow examples get interruptions --api low-level cd interruptions/low-level # 3. Run it uv run --no-project --with desflow interruptions_example.py ``` ```bash # 1. Install pip install desflow # 2. Download the example desflow examples get interruptions --api low-level cd interruptions/low-level # 3. Run it python interruptions_example.py ``` The whole file is [`examples/low-level/interruptions_example.py`](https://github.com/jaehyeon-kim/desflow/blob/v1.3.0/examples/low-level/interruptions_example.py). # Several Resources A task can hold more than one [resource](https://jaehyeon.me/desflow/latest/user-guide/resources/units-and-queues/index.md) at once. This page shows how. ______________________________________________________________________ ## What It Is Some work needs more than one resource at a time: an order needs a picker and a bench, and a patient needs a doctor and a room. A task can hold several resources at once, or keep a unit and hand it to the next task of its flow. ______________________________________________________________________ ## How to Use It A task can hold several resources at once: `resource: [picker, bench]` asks for a picker, then, while it holds the picker, for the bench. The task is served once it holds all of them, and it releases all of them when it finishes. While it waits for the bench, it holds the picker. The units are granted one at a time, never together, so a task can hold some of its resources while it waits for the rest. `patience` covers the whole acquisition. A plain interrupt keeps the units already held and asks again only for the one it waits for, and `on_interrupt: abandon` gives every unit back. A task can also hand a unit to the next task of its flow with `keep`: the next task holds it from the start and gives it back once it publishes `started`. An order can therefore keep the picker until it is on the packing bench, as [Hand Off to a Resource](https://jaehyeon.me/desflow/latest/how-to/modelling/multi-resource-handoffs/index.md) shows step by step. A task that reneges, whose wait fails with no `on_fail`, or that has no next task gives it back when it ends. If the unit is preempted while the next task holds it, that task is interrupted and follows its `on_interrupt`. The unit a task keeps stays with the entity until that next task starts. A child flow started by `wait: {task: ...}` gives back only the units its own tasks asked for. The `competing-resources` example does both: ```yaml tasks: pick: service: picking resource: picker # The picker stays with the order until pack has started. keep: [picker] payload: {event_type: order_picked} next: pack pack: service: packing resource: bench payload: {event_type: order_packed} wrap: service: wrapping # Holds the picker, then the bench too: acquired in this order. resource: [picker, bench] payload: {event_type: gift_wrapped} ``` ```python # The picker stays with the order until pack has started @app.task(service_id="picking", resource_id="picker", keep=["picker"], next="pack") def pick(task_id, context): return {"event_type": "order_picked"} @app.task(service_id="packing", resource_id="bench") def pack(task_id, context): return {"event_type": "order_packed"} # Holds the picker, then the bench too: acquired in this order @app.task(service_id="wrapping", resource_id=["picker", "bench"]) def wrap(task_id, context): return {"event_type": "gift_wrapped"} ``` ```python def pick(shop, key): """Picks an order and keeps the picker for pack, which gives it back.""" env, stats = shop.env, shop.env.stats task_id, publish, status, duration = shop.step(key, "pick", "picking") stats.flow_started("orders") # the order enters the shop status("queued") stats.task_queued("pick", task_id) picker = shop.picker.request() yield picker status("started") stats.task_started("pick", task_id) yield env.timeout(duration()) publish({"event_type": "order_picked"}) stats.task_finished("pick", task_id) yield from pack(shop, key, picker) def pack(shop, key, picker): env, stats = shop.env, shop.env.stats task_id, publish, status, duration = shop.step(key, "pack", "packing") status("queued") stats.task_queued("pack", task_id) with shop.bench.request() as bench: yield bench status("started") stats.task_started("pack", task_id) shop.picker.release(picker) # the order is on the bench yield env.timeout(duration()) publish({"event_type": "order_packed"}) stats.task_finished("pack", task_id) stats.flow_finished("orders") def wrap(shop, key): """Holds the picker, then the bench too: acquired in this order.""" env, stats = shop.env, shop.env.stats task_id, publish, status, duration = shop.step(key, "wrap", "wrapping") stats.flow_started("gifts") status("queued") stats.task_queued("wrap", task_id) with shop.picker.request() as picker: yield picker with shop.bench.request() as bench: yield bench status("started") stats.task_started("wrap", task_id) yield env.timeout(duration()) publish({"event_type": "gift_wrapped"}) stats.task_finished("wrap", task_id) stats.flow_finished("gifts") ``` In the low-level API several resources are nested requests, and a handoff is a request released by the next process. ### Hold a Unit Between Steps `seize` asks for a unit at the start of a task and keeps it until a `release`, in this task or a later one of the flow, so the unit is held across steps that name no `resource`. `seize` is a resource name, or `{resource, priority, preempt, patience}`. `release` frees the oldest unit of a resource that the flow holds from a `seize` or an `open`, and does nothing when it holds none. A unit still held when the flow ends stays held, as in SimPy, so a flow writes `release` before it ends. A unit lost to a preemption is asked for again under `resume` and `restart`, and is gone under `abandon`. `release` also takes `{handle: name}` for one opened request and `{resource, task, where}` for the units that other flows of a task hold. A `priority` on a `seize` needs the resource to set `queue: priority`, as `picker` does here. The `clear` task below frees the picker from every rush order that holds it. ```yaml tasks: pick: service: picking # Asks for the picker now, with priority 1 and without taking the unit from # another order, and keeps it across the next task seize: {resource: picker, priority: 1, preempt: false} payload: {event_type: order_picked} next: pack pack: service: packing resource: bench # Gives the picker back once the order is on the bench release: picker payload: {event_type: order_packed} # Frees the picker from every rush order that still holds it clear: release: {resource: picker, task: pick, where: attr.rush} payload: {event_type: picker_cleared} ``` `@app.task(seize="picker")` and `@app.task(release="picker")` take the same values. The process holds the request itself: `picker = shop.picker.request()` and `yield picker`, then `shop.picker.release(picker)` when the order is on the bench. ______________________________________________________________________ ## How It Works **One order of acquisition.** Two tasks that acquire the same two resources in opposite orders can each hold one and wait for ever for the other. desflow loads such a model and logs one WARNING, from the logger `desflow.builder.context`, that names both tasks. A unit held with `seize` counts as held. Every task should acquire shared resources in one order. The rule also covers `keep` handoffs and the `request` branches of a wait, and a `keep` for a request branch of a wait is still refused when the model is built ([Wait for a Unit, an Item or Room](https://jaehyeon.me/desflow/latest/how-to/modelling/wait-for-one-or-all/#wait-for-a-unit-an-item-or-room)). [Competing Resources](https://jaehyeon.me/desflow/latest/learn/shop-logic/competing-resources/index.md) shows what a partial holding costs. ______________________________________________________________________ ## Example: Competing Resources In the `competing-resources` example, orders keep the picker until they are on the bench, and gifts hold the picker and the bench together. It needs no Docker service and ends on its own after 120 simulation seconds. The tutorial page [Competing Resources](https://jaehyeon.me/desflow/latest/learn/shop-logic/competing-resources/index.md) teaches these features step by step. **Quick Start** `desflow examples get` downloads the example at the release you install, into a folder of its own. Pick uv or pip: ```bash # 1. Install uv tool install desflow # 2. Download the example desflow examples get competing-resources --api yaml cd competing-resources/yaml # 3. Run it desflow run competing_resources.yaml ``` ```bash # 1. Install pip install desflow # 2. Download the example desflow examples get competing-resources --api yaml cd competing-resources/yaml # 3. Run it desflow run competing_resources.yaml ``` The whole file is [`examples/yaml/competing_resources.yaml`](https://github.com/jaehyeon-kim/desflow/blob/v1.3.0/examples/yaml/competing_resources.yaml). **Quick Start** `desflow examples get` downloads the example at the release you install, into a folder of its own. Pick uv or pip: ```bash # 1. Install uv tool install desflow # 2. Download the example desflow examples get competing-resources --api builder cd competing-resources/builder # 3. Run it uv run --no-project --with desflow competing_resources_example.py ``` ```bash # 1. Install pip install desflow # 2. Download the example desflow examples get competing-resources --api builder cd competing-resources/builder # 3. Run it python competing_resources_example.py ``` The whole file is [`examples/builder/competing_resources_example.py`](https://github.com/jaehyeon-kim/desflow/blob/v1.3.0/examples/builder/competing_resources_example.py). **Quick Start** `desflow examples get` downloads the example at the release you install, into a folder of its own. Pick uv or pip: ```bash # 1. Install uv tool install desflow # 2. Download the example desflow examples get competing-resources --api low-level cd competing-resources/low-level # 3. Run it uv run --no-project --with desflow competing_resources_example.py ``` ```bash # 1. Install pip install desflow # 2. Download the example desflow examples get competing-resources --api low-level cd competing-resources/low-level # 3. Run it python competing_resources_example.py ``` The whole file is [`examples/low-level/competing_resources_example.py`](https://github.com/jaehyeon-kim/desflow/blob/v1.3.0/examples/low-level/competing_resources_example.py). # Custom Resource Types A [resource](https://jaehyeon.me/desflow/latest/user-guide/resources/units-and-queues/index.md) can grant its units by a rule of your own. This page shows how to write one. ______________________________________________________________________ ## What It Is Some shops grant their units by a rule of their own, such as sharing a packer between customer classes by weight. A custom resource type replaces the rule by which a resource grants its units, and keeps the capacity that follows the registry. ______________________________________________________________________ ## How to Use It To change how a resource grants units, subclass `ResourceBase` and name the class in `type`. `ResourceBase` is built on the hooks of SimPy's `BaseResource`, as a subclass of SimPy's `Resource` is. A subclass can change these: - Override `_do_put(request)` to decide when a request is granted, and `_do_get(release)` to decide what a release gives back. An override calls the base method, which wakes `when_busy()` and `when_idle()`, so a breakdown that counts busy time still works. - Set `PutQueue` to the class of the waiting line. It can be SimPy's `SortedQueue`, written `staticmethod(functools.partial(SortedQueue, maxlen=2))`. On a store or container, a `type` that sets its own queues refuses `get_queue` and `put_queue`. - Set `request` to `BoundClass(MyRequest)`, for a request class that subclasses `DynamicResourceRequest`, or set `release` the same way, for a release class that subclasses `DynamicRelease`. Both base classes are in `desflow.resources`. A request or release class calls the base constructor, which publishes the `on_change` reading. This resource keeps how long each request waited: ```yaml resources: # A subclass of ResourceBase that keeps how long each request waited packers: {current_cap: 1, max_cap: 4, type: !python shop_logic.LoggedPackers} ``` The class is in `shop_logic.py`, beside the blueprint: ```python class LoggedPackers(ResourceBase): """A resource that keeps how long each request waited before it was granted.""" def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.waits = [] def _do_put(self, request): super()._do_put(request) if request.triggered: # the request was granted just now self.waits.append(self.env.now - request.time) ``` ```python app = SimulationContext(sim_id="Shop", factor=0.0) app.add_resource("packers", current_cap=1, max_cap=4, type=LoggedPackers) ``` The class is the one the Low-level tab shows. ```python class LoggedPackers(ResourceBase): """A resource that keeps how long each request waited before it was granted.""" def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.waits = [] def _do_put(self, request): super()._do_put(request) if request.triggered: # the request was granted just now self.waits.append(self.env.now - request.time) ``` ```python env = DynamicRealtimeEnvironment(factor=0.0) env.registry.register_sim_parameter( SimParameter( sim_id="Shop", resources={"packers": CapacityConfig(current_cap=1, max_cap=4)} ) ) packers = LoggedPackers(env, "Shop", "packers") def order(env): with packers.request() as request: yield request yield env.timeout(2.0) ``` ______________________________________________________________________ ## How It Works `DynamicResource` is `ResourceBase` with nothing changed. The constructor is `DynamicResource`'s, because the resource reads its capacity from the registry. A subclass that defines `__init__` therefore takes `*args, **kwargs` and passes them on. A `PutQueue` of your own sets its own order and length, so it takes no `queue_limit`. The tests run each of these beside the same SimPy subclass in all three APIs. # Time and Pacing A run has two clocks of its own, simulation time and logical time. A run can follow the wall clock, ignore it, or ignore it at first and follow it later. This page shows how to read the current time and which parts of the environment run on each thread. [Clocks and Pacing](https://jaehyeon.me/desflow/latest/user-guide/time-and-pacing/clocks-and-pacing/index.md) shows the clock settings, and [Run Length](https://jaehyeon.me/desflow/latest/user-guide/time-and-pacing/run-length/index.md) shows the [warm-up](https://jaehyeon.me/desflow/latest/learn/concepts/output-analysis/#one-run-starts-empty) and how long a run lasts. ______________________________________________________________________ ## What It Is **Simulation time** is the number of seconds SimPy has advanced, starting at `initial_time`, 0 by default. Every record carries it as `sim_ts`. **Logical time** is the date and time a record carries as `timestamp`: `logical_start_time` plus the simulation time. `factor` sets how simulation time relates to the wall clock, and `go_live_at` switches that relation once during a run. One hour of simulation time is one hour of logical time, and takes as long on the wall clock as `factor` says: The settings are the same on `DynamicRealtimeEnvironment`, on `SimulationContext` and in the `simulation` section of a blueprint. ______________________________________________________________________ ## Pages in This Section - [Clocks and Pacing](https://jaehyeon.me/desflow/latest/user-guide/time-and-pacing/clocks-and-pacing/index.md): the logical start time, the time zone, the factor, going live, the lag and strict pacing. - [Run Length](https://jaehyeon.me/desflow/latest/user-guide/time-and-pacing/run-length/index.md): the warm-up, the initial time, how long a run lasts, stopping early, draining, stepping and running in segments. ______________________________________________________________________ ## How to Use It ### Read the Current Time `t` is the simulation clock in a condition or an expression, the value of `context.env.now` in the builder and `env.now` in the low-level API. A route or a balk can depend on it, such as `next: {when: [{condition: "t < 110", task: early}], default: late}`. A `wait: {condition: ...}` that reads `t` is not a timer. A condition is checked again only after a change of state, not as time passes. To wait for a time, use a `timeout` branch. ______________________________________________________________________ ## How It Works Before each event, the environment checks the logical clock. Until `go_live_at` it paces the run at `factor`, and from there at one simulation second per real second. [Clocks and Pacing](https://jaehyeon.me/desflow/latest/user-guide/time-and-pacing/clocks-and-pacing/#how-it-works) describes how the pacing switches during a run, and [Run Length](https://jaehyeon.me/desflow/latest/user-guide/time-and-pacing/run-length/#how-it-works) how the model and the run end. The threads that run a model, the two kinds of queue and the processes the environment starts are in [How desflow Works](https://jaehyeon.me/desflow/latest/user-guide/how-desflow-works/#threads-and-queues). [SimPy and desflow](https://jaehyeon.me/desflow/latest/simpy/index.md) compares the two environments. ______________________________________________________________________ ## Stability and Limits - **A run with no `until` ends when no model event is left.** A run with an arrival, a sink or an ingress connector never runs out of events, so it needs `until`, a `stop` or Ctrl+C, as [Run Length](https://jaehyeon.me/desflow/latest/user-guide/time-and-pacing/run-length/#run-length_1) explains. - **At `factor: 0`** no timed flush runs, so records leave a buffer when it reaches `batch_size` and at teardown, as [Egress](https://jaehyeon.me/desflow/latest/user-guide/live-runs-and-connectors/egress/index.md) explains. `LocalIngress` follows the wall clock, so its changes can land after an unpaced run has ended. A scenario follows the simulation clock. No `system.simulation.lag_seconds` is published unless `lag_interval` is set, and it reads 0. - **`warmup` drops, `go_live_at` routes.** Records before a warm-up are gone. Records before `go_live_at` go to the sinks that take history. - **A model slower than the wall clock** falls behind at `factor: 1.0` and does not catch up by skipping events. `lag_seconds` shows by how much. # Clocks and Pacing This page shows the clock settings of a run, described in [Time and Pacing](https://jaehyeon.me/desflow/latest/user-guide/time-and-pacing/index.md): the logical start time, the time zone, the factor, going live, the lag and strict pacing. ______________________________________________________________________ ## What It Is A run's records carry dates and times, as the events of a real shop would. The logical start time and the time zone set those dates. The factor sets how fast the run goes against the wall clock: a backfill of last week runs without waiting, and a live demo runs in step with the wall clock. Going live switches from the first to the second within one run. ______________________________________________________________________ ## How to Use It ### Logical Start Time `logical_start_time` is the date and time that simulation time 0 maps to. Without it, the run uses the moment the environment is created. A run with a backdated start writes history: `logical_start_time` under `simulation` takes `now`, a signed duration or an ISO datetime. This blueprint starts a day before the file is loaded: ```yaml # Read against the moment the file is loaded: a day of history up to now logical_start_time: -1d ``` ```python app = SimulationContext( sim_id="Shop", factor=0.0, logical_start_time=datetime.now(timezone.utc) - timedelta(days=7), # a week ) ``` `DynamicRealtimeEnvironment(logical_start_time=...)` takes the same datetime. A datetime without an offset is read in the run's time zone, described next. In a blueprint it takes `now`, a signed duration such as `-7d`, or an ISO datetime, as [YAML Blueprints](https://jaehyeon.me/desflow/latest/user-guide/writing-a-model/blueprints/#times-and-durations) describes. ### Time Zone `timezone` names the zone that record timestamps are written in, as an IANA name such as `Australia/Melbourne`. Every `timestamp` carries the offset of its moment, such as `2026-10-03T12:00:00.000+10:00`, or `+00:00` in UTC. By default the zone is that of `logical_start_time` when it has one, and UTC otherwise. A `logical_start_time` or `go_live_at` without an offset, `now`, and the default start are read in that zone: ```yaml # Under simulation: timestamps written in Melbourne time, with its offset; the # start and now are read in it. UTC by default timezone: ${SIM_TIMEZONE:-Australia/Melbourne} ``` ```python # Timestamps in Melbourne time, with their offset: 2026-10-03T12:00:00.000+10:00 melbourne = SimulationContext( sim_id="Shop", factor=0.0, timezone="Australia/Melbourne", logical_start_time=datetime(2026, 10, 3, 12, 0), # read in Melbourne time ) ``` ```python zoned = DynamicRealtimeEnvironment( factor=0.0, timezone="Australia/Melbourne", logical_start_time=datetime(2026, 10, 3, 12, 0), ) print(zoned.start_datetime) # 2026-10-03 12:00:00+10:00 ``` The clock runs in UTC, so a daylight-saving change in the zone never adds or drops simulation time. In Melbourne, the clocks went forward an hour on 4 October 2026. A run of 24 simulation hours from 12:00 on 3 October therefore ends at 13:00 on 4 October, `2026-10-04T13:00:00.000+11:00`. A replayed timestamp without an offset is read in the zone too. ### Factor The wall-clock duration of a stretch of the run is its simulation duration times `factor`: `factor` under `simulation`, here read from an environment variable: ```yaml # An unquoted value is read after the replacement, so this is the number 0 factor: ${SIM_FACTOR:-0} ``` `SimulationContext(sim_id="Shop", factor=1.0)` takes the same number. ```python live = DynamicRealtimeEnvironment(factor=1.0) # 1 simulated second takes 1 real second twice_as_fast = DynamicRealtimeEnvironment(factor=0.5) # takes half a real second unpaced = DynamicRealtimeEnvironment(factor=0.0) # takes no real time at all ``` - `factor: 1.0` follows the wall clock: a process that waits 5 simulation seconds waits 5 real seconds. It suits a live twin feeding a dashboard. - `factor: 0` does not wait at all: the run goes as fast as the machine allows. It suits history, tests and experiments. At `factor: 0` each event is processed by SimPy's own `Environment.step`, without the real-time arithmetic. `strict` left unset is false here, because there is no wall clock to fall behind. A pending `go_live_at` is still checked before each event, and pacing starts at it. ### Go Live `factor` applies until the logical clock reaches `go_live_at`, and from that instant the run is paced at one simulation second per real second. With a backdated `logical_start_time` and `factor: 0`, one run writes the history as fast as it can, then keeps going in real time: ```yaml # A day of history at factor 0, then 1 simulated second per real second from now; # when: history and when: live split the records at this instant logical_start_time: -1d go_live_at: now ``` `SimulationContext(factor=0.0, logical_start_time=..., go_live_at=...)` takes the same two times as datetimes. ```python go_live_at = datetime.now(timezone.utc) env = DynamicRealtimeEnvironment( factor=0.0, # until go_live_at logical_start_time=go_live_at - timedelta(days=7), go_live_at=go_live_at, # from here, 1 simulated second per real second ) ``` A sink with `when: history` receives the records stamped before `go_live_at`, and one with `when: live` the rest, so the two halves can go to different places: **Why one run rather than two.** A demo of a data lake beside a live stream usually needs two datasets: a backdated history sitting in a lake, and a live stream arriving now. They have to be the same shop, with the same packers, the same distributions and the same task ids, or the join between them is meaningless. Producing them needs two values of `factor` that conflict. History needs `factor=0.0`, so that a week of events is generated as fast as the machine allows. A live tail needs `factor=1.0`, so that events arrive at one simulated second per real second. Without `go_live_at`, the only way to get both is to start two processes with the same `random_seed` and the same `logical_start_time`, one fast-forwarding into Parquet and one pacing into Kafka. That costs: - A second full execution of the same simulation, so the history is generated twice. - The seed and the start instant are written in two places, which have to be edited together. If one changes and the other does not, the two halves stop being the same shop, with no error. - Nothing makes the two halves meet. Each process decides on its own where its half ends, so the two halves can overlap or leave a gap. `go_live_at` replaces both processes with one. The run generates history unpaced up to that logical instant, then switches to real-time pacing and keeps going. There is one seed, one start instant and one instant where history ends and the live tail begins. **Three settings.** Three separate settings make up the feature, and each answers a different question. | Setting | Question it answers | | -------------------- | ------------------------------------------------------------------------------- | | `logical_start_time` | Where does the logical clock start? Set it in the past to backdate the history. | | `go_live_at` | At which logical instant does pacing stop being `factor` and become real time? | | `when` on a sink | Which sink receives each record? | They are independent. `go_live_at` changes pacing only. It never routes a record. `when` routes records only. It never changes pacing. Used together, they give the history and the live stream from one run. In a blueprint, `when: history` and `when: live` compare each record's timestamp with `go_live_at` themselves. A Python predicate has to compare with the same instant. Otherwise the records switch sinks at a different instant from the one where the pacing switches. On a `DynamicRealtimeEnvironment`, `env.factor` reports the run's `factor`, such as `0.0`, until the logical clock reaches `go_live_at`, and `1.0` afterwards. [Parquet History, Kafka Live](https://jaehyeon.me/desflow/latest/gallery/simulation-models/backfill-live/index.md) builds such a run. ### Lag At a `factor` above 0 the run follows the wall clock, and `system.simulation.lag_seconds` says how many seconds it is behind its pace, as telemetry. A run that keeps its pace reads about 0 at any `factor`, and the reading grows when the run falls behind. `lag_interval` sets how often it is published, in simulation seconds or a duration. By default, it is published every simulation second at a `factor` above 0. At `factor: 0` it is off by default, because such a run has no pace to fall behind, and a `lag_interval` that turns it on reads 0. A run at `factor: 0` that goes live starts publishing it at the go-live instant. A `lag_interval` of 0 turns it off: ```yaml # Under simulation: how far the run is behind the wall clock, every 10 s; by # default off at factor 0 and every second otherwise, and 0 turns it off lag_interval: 10 s ``` ```python # system.simulation.lag_seconds every 10 simulation seconds; 0 turns it off paced = SimulationContext(sim_id="Shop", factor=1.0, lag_interval="10 s") ``` ```python # The low-level API sets it with the sinks; the default "auto" is off at factor 0 # env.setup_egress(sinks, lag_monitor_interval=10) ``` ### Strict Pacing A paced step that starts more than `factor` real seconds late has fallen behind the wall clock. With `strict` on, the run raises `RuntimeError` (`Simulation too slow for real time (1.500s).`), as SimPy's `RealtimeEnvironment` does. With `strict` off, the run goes on and `system.simulation.lag_seconds` reports the delay. A run that leaves `strict` unset gets the same default in every API: - **Paced run:** `strict` is true at a `factor` above 0, and when the run has a `go_live_at`. - **Unpaced run:** `strict` is false at `factor: 0` with no `go_live_at`, because an unpaced run has no wall clock to fall behind. `SimulationContext(strict=None)` and `DynamicRealtimeEnvironment(strict=None)` are the defaults, and `simulation.strict` left out of a blueprint means the same. Write `strict: false` for a live run with a sink that can block, so the run goes on when the sink is slow. An explicit `strict: true` is checked at `factor: 0` with no `go_live_at` too, and raises at the first step after the wall clock has moved, as SimPy's check does. ```yaml # Under simulation: true by default for a paced run and false at factor 0; false # lets a live run go on when a slow sink makes it fall behind the wall clock strict: false ``` ```python # A paced run is strict unless it says otherwise; false lets a live run go on when a # slow sink makes it fall behind the wall clock tolerant = SimulationContext(sim_id="Shop", factor=1.0, strict=False) ``` ```python # Left unset, strict is true at a factor above 0 and false at factor 0, as SimPy's # RealtimeEnvironment would raise at the first step of an unpaced script raising = DynamicRealtimeEnvironment(factor=1.0) unpaced_strict = DynamicRealtimeEnvironment(factor=0.0) low_level_tolerant = DynamicRealtimeEnvironment(factor=1.0, strict=False) ``` Before `go_live_at`, `strict` is never checked, whatever its value. After a pause, SimPy's `env.sync()` moves only the wall-clock anchor to now. The next event would then wait `factor` seconds for each simulation second since `env_start`. `env_start` is the start of the run, the go-live instant once the run has gone live, or the last `resume_pacing()`. `env.resume_pacing()` moves both anchors, so the next event waits `factor` seconds for each simulation second after `now`: A context from `SimulationContext.from_yaml` runs in segments as the builder does, and resumes pacing with `app.env.resume_pacing()` in the same way. The builder's environment is `app.env`. Call `app.env.resume_pacing()` before the next `advance()` of a run in segments, as [Run in Segments](https://jaehyeon.me/desflow/latest/user-guide/time-and-pacing/run-length/#run-in-segments) describes. ```python paused = DynamicRealtimeEnvironment(factor=0.01, strict=False) # 1.0 follows the clock paused.run(until=10) # ... a pause, such as a stop in a debugger: the wall clock is now ahead of the run paused.resume_pacing() # from here, factor real seconds per simulation second paused.run(until=20) ``` ______________________________________________________________________ ## How It Works **Pacing and the switch.** Before each event, the environment checks the logical clock. At the first event at or after `go_live_at`, it sets the factor to 1.0 and moves its two anchors, `env_start` and `real_start`, so that the go-live instant counts as now. Without this move, the first paced event would wait on the wall clock for the whole backfill. The switch happens once, and always sets the factor to 1.0. A `go_live_at` at or before `logical_start_time` paces the whole run, with a warning. A run that ends before its `go_live_at` stays unpaced. A `go_live_at` or `logical_start_time` without an offset is read in the run's time zone, so the two can be compared whichever way each is written. ______________________________________________________________________ ## Stability and Limits The limits of this page are listed with those of the whole section, in [Stability and Limits](https://jaehyeon.me/desflow/latest/user-guide/time-and-pacing/#stability-and-limits) on the Time and Pacing page. # Run Length This page shows how a run starts and ends, described in [Time and Pacing](https://jaehyeon.me/desflow/latest/user-guide/time-and-pacing/index.md): the [warm-up](https://jaehyeon.me/desflow/latest/learn/concepts/output-analysis/#one-run-starts-empty), the initial time, the run length, stopping early, draining, stepping and running in segments. ______________________________________________________________________ ## What It Is A study decides how long to watch the shop: a working day that ends at closing time, or a long run that leaves out its empty start. These settings decide when a run starts measuring, when it stops, and what happens to the orders still in the shop at the end. ______________________________________________________________________ ## How to Use It ### Warm-up `warmup` leaves the start of a run out of what it reports. It is one time per run, in simulation seconds or a duration. No sink receives a record or telemetry stamped before it, and the built-in statistics are reset once at that moment, so they describe the rest of the run. A run without it sends everything, which is what a data generator usually wants. ```yaml # Records and statistics start after the first 2 minutes; 0 keeps everything warmup: ${WARMUP:-2 min} ``` ```python # No sink receives a record stamped before 10 minutes, and the statistics restart then measured = SimulationContext(sim_id="Shop", factor=0.0, warmup="10 min") # In the low-level API, the warm-up is set with the sinks: # env.setup_egress(sinks, warmup=600) ``` The warm-up is an argument of the sinks, because it is the sinks that leave records out: `env.setup_egress(sinks, warmup=600)`. A run with no sink has no records to leave out. When the warm-up is set through the builder, the statistics are also reset at it. The warm-up drops early records. `go_live_at` drops nothing, and only decides which sink gets each record. [Trusting Results](https://jaehyeon.me/desflow/latest/learn/studies/trusting-results/index.md) shows how to choose a warm-up length. ### Initial Time `initial_time` is the reading of the simulation clock when the run starts, 0 when left out, in seconds or as a duration. A model of a shift that starts at 8 in the morning can start its clock at 8 hours. Every event time, every record's `sim_ts` and `until` then read that clock. A record's `timestamp` is still `logical_start_time` plus `sim_ts`, to within 1 millisecond, because `timestamp` is written to the millisecond and the rest is cut off: ```yaml simulation: sim_id: Shop factor: 0 # The clock starts at 8 h, so the first order at 8 h 10 min is at sim_ts 29400 initial_time: 8 h ``` ```python # The clock starts at 8 hours: event times, sim_ts and until all read it shift = SimulationContext(sim_id="Shop", factor=0.0, initial_time="8 h") ``` ```python # The clock starts at 8 hours, in seconds, as in SimPy's Environment(initial_time=) morning = DynamicRealtimeEnvironment(factor=0.0, initial_time=8 * 3600) ``` `until` is a clock reading too, so a run with `initial_time: 8 h` and `until: 16 h` lasts 8 hours. A scenario step's `at` and the `warmup` are different: they are lengths of time from the start of the run. Look at where each falls on the clock of that run: With `initial_time: 8 h`, a step at `30 min` applies at 8.5 hours, and a warm-up of `10 min` ends at 8 hours 10 minutes. The state the run starts with holds from the initial time, before the first arrival: a resource's `current_cap`, a container's `level`, a store's `items` and an arrival's `attributes`. The tests check each against plain SimPy ([SimPy Compatibility](https://jaehyeon.me/desflow/latest/simpy/compatibility/index.md)). ### Run Length `until` is in simulation seconds. `run()` and a blueprint's `run.until` also take a duration such as `"10 min"`, `"8 hours"` or `"1 week"`. A month counts as 30 days and a year as 365. `desflow run FILE --until TIME` overrides `run.until` for one run, without editing the file: `desflow run shop.yaml --until "10 min"` runs `shop.yaml` for 10 simulation minutes, whatever its `run.until` says. ```yaml run: # A duration, such as 1 week, or a number of seconds until: ${RUN_FOR:-1 hour} ``` ```python app.add_resource("packers", current_cap=1, max_cap=1) app.run(until="1 week") # 604,800 simulation seconds; a number is seconds too ``` `env.run(until=604800)` takes seconds only, as SimPy's `run` does. The run stops at `until` before any event due at exactly that time, as SimPy's `run(until=...)` does: an order due at the horizon never arrives, and a task due to finish there stays unfinished. Statistics published at teardown read the model at `until`. Events due at the same time run by priority, and then in the order they were scheduled (SimPy 4.1.2, `core.py`: `schedule` and `run`; `URGENT` and `NORMAL` in `events.py`). A priority of 0 is urgent and 1 is the default. `run(until=...)` schedules its stop at urgent priority, so the stop comes before the ordinary events due at that time. A `fire` action with a `priority` takes part in the same order, and its `after` gives the delay. How a scenario step or a change from an ingress connector ranks among them is in [Live Parameters](https://jaehyeon.me/desflow/latest/user-guide/live-runs-and-connectors/live-parameters/#script-an-experiment). Here two orders are packed at 5 seconds, and one is due at the horizon of 10 seconds: A blueprint has no way to schedule a bare event. Its `fire` action takes `priority` and `after`, as [Signals and Waiting](https://jaehyeon.me/desflow/latest/user-guide/tasks-and-processes/signals-and-waiting/index.md) describes, and the Low-level tab shows the order with three processes. The builder schedules no bare event either. `Signal.fire(priority=...)` and the `fire` action of `task(on=...)` take the same priority, and the Low-level tab shows the order with three processes. ```python ties = DynamicRealtimeEnvironment(factor=0.0) packed = [] def pack(name, seconds): yield ties.timeout(seconds) packed.append(name) ties.process(pack("first", 5)) ties.process(pack("second", 5)) # due at the same time: runs after "first" ties.process(pack("at the horizon", 10)) ties.run(until=10) print(packed) # ['first', 'second']: nothing due at 10 runs ``` Without `until`, a run ends when no model event is left, as SimPy's does. The events of desflow's own, such as the statistics timer and the flush timers, repeat for as long as the run lasts, so they never keep it going. A run with an arrival never runs out of model events, and a run that waits for changes from an ingress connector has none of its own. Give such a run an `until`, a `stop` or a drain, or stop it with Ctrl+C. ### Stop Early `stop` ends the run before `until` when something happens. It takes these forms: - `{signal: name}` ends the run at the next firing of a signal. `{signal: {of: family, key: expression}}` names one member of a family of signals. desflow reads the key once, as the run starts, outside every task, so a key that reads `attr.` is refused when the file loads. - `{condition: ...}` ends it at the first moment a condition holds. The condition is checked after every change of a level, a capacity, a registry value or a signal, and after every finished task. - In the builder, `run(stop=...)` also takes a signal's name, or a function of the context that returns any SimPy event, such as `lambda context: context.env.timeout(30)`. The function is called once the run is built. - In the low-level API, the same is SimPy's `env.run(until=event)`. The run ends at whichever comes first, `stop` or `until`, and no other event at that moment runs after it. When both fall at the same moment, `until` ends the run, as SimPy's own `until` would. `run()` and `finish()` return what SimPy's `env.run(until=event)` returns: the value of the event that ended the run: | What ended the run | Value returned | | ------------------------------------------------------------ | -------------------------------------------------------------------------- | | A `stop` on a signal | the signal's value, such as the finished payload of the task that fired it | | A `stop` on a condition | `True` | | A `stop` on a function's event | the event's own value | | `until`, a drain, or `until` and the stop at the same moment | `None` | If the signal fails, the run still closes, and the sinks receive their records. Then `run()` raises the `SignalFailed` the signal failed with, as SimPy raises the exception of a failed event. `desflow run` reports it and exits with an error. ### Drain A fixed horizon cuts the run at `until` with orders still in the shop. A **drain** stops the arrivals at `until` and keeps running until every entity in the model has left. Set it with `drain: true`, or with `drain: {limit: 1 h}` to stop at the latest 1 hour after `until`. `desflow run --drain` sets it from the command line. The environment's own processes, such as the statistics timer, never hold a drain open. The `end-conditions` example closes the shop at 120 seconds, drains for at most a minute, and stops at once if the boxes run out: ```yaml run: # No new orders after closing time. until: 120 # Then pack the orders in the shop, for at most 60 seconds. drain: {limit: 60} # Stop at once when the last box is taken. stop: {condition: level.boxes == 0} ``` ```python app.run( # No new orders after closing time until=120, # Then pack the orders in the shop, for at most 60 seconds drain={"limit": 60}, # Stop at once when the last box is taken stop={"condition": "level.boxes == 0"}, ) ``` `context.stop_arrivals()` stops the arrival loops by hand, as a drain does at `until`. ```python def run_to_end(env, shop, source): """Runs to closing time, then drains for at most 60 s, or until no boxes are left.""" out_of_boxes = env.event() def check(): if shop["boxes"].level == 0 and not out_of_boxes.triggered: out_of_boxes.succeed() env.watch_changes(check) # Closing time, unless the boxes run out first, which ends the run at once env.run(until=env.timeout(120) | out_of_boxes) if out_of_boxes.triggered: return source.interrupt() # no new orders after closing time packed = env.all_of([p for p in shop["orders"] if p.is_alive]) env.run(until=packed | env.timeout(60) | out_of_boxes) ``` The low-level API writes a drain as SimPy does: interrupt the source process, then run until all the admitted processes end. An arrival with `max_events` stops itself after its last start. An arrival with `count` or `keys` has one loop for each entity, and `stop_arrivals()` and a drain end all of them. The run ends when the loops have stopped and the flows have drained. With statistics at `basic` or above, `flows..started`, `finished` and `in_system` say how many entities entered, left and are still in the model. From `minimal`, `tasks..in_progress` says how many instances of each task are queued or being served. [End Conditions](https://jaehyeon.me/desflow/latest/learn/first-model/end-conditions/index.md) compares a fixed horizon with a drain, and `desflow examples get end-conditions` downloads this model in all three forms. ### Step and Peek `start()` builds everything `run()` builds and starts every process, with the clock still at its start. Two methods then move through the model one event at a time, as SimPy's `env.step()` and `env.peek()` do: - `step()` processes the next event of the model. - `peek()` gives the time of the next event, or infinity when none is left. Both count only the model's events, so a script steps the model as it would in SimPy. The events desflow adds do not count: the statistics timer, the flush timers, the lag and ingress monitors, and a resource's capacity watcher. `peek()` skips them, and `step()` runs those due before the model's next event in the same call. When only desflow's events are left, `step()` raises `EmptySchedule` and `peek()` gives infinity. `finish()` and `run()` still process them. Once a `row` generator with `on_end: stop`, or the last entry of `run.segments`, has ended the run, `step()` raises `RuntimeError`, as `advance()` does, and `peek()` gives infinity, so a loop of `peek()` and `step()` ends. The blueprint reads the same clock after each model event: `run: {steps: true}` publishes `system.simulation.step`, with the step number, `now` and `peek`, and `run: {sync: true}` calls `env.sync()` as the run starts. The builder takes `run(steps=True, sync=True)`, and a run with `steps` takes no `segments`, `stop` or `drain`: ```yaml run: until: 1 min # system.simulation.step after each model event steps: true # env.sync() as the run starts sync: true ``` ```python stepper = SimulationContext(sim_id="Shop", factor=0.0) stepper.add_arrival("orders", dist="constant", value=20, spawn="tick") @stepper.task() def tick(task_id): return {"event_type": "order_packed"} # system.simulation.step after each model event, and env.sync() as the run starts stepper.run(until="1 min", steps=True, sync=True) ``` The low-level API reads `env.now` and `env.peek()` in a loop of `env.step()`, as SimPy does. The first readings of the blueprint, with the order the model made at each step: ```text [TEL] {'sim_ts': 0.0, 'timestamp': '...', 'path_id': 'system.simulation.step', 'value': {'step': 1, 'now': 0, 'peek': 20.0}} [TEL] {'sim_ts': 20.0, 'timestamp': '...', 'path_id': 'system.simulation.step', 'value': {'step': 2, 'now': 20.0, 'peek': 20.0}} [EVT] {'sim_ts': 20.0, 'timestamp': '...', 'key': 'orders-1', 'task': 'pack_order', 'instance': 0, 'value': {'event_type': 'order_packed'}} [TEL] {'sim_ts': 20.0, 'timestamp': '...', 'path_id': 'system.simulation.step', 'value': {'step': 3, 'now': 20.0, 'peek': 20.0}} [TEL] {'sim_ts': 20.0, 'timestamp': '...', 'path_id': 'system.simulation.step', 'value': {'step': 4, 'now': 20.0, 'peek': 40.0}} [TEL] {'sim_ts': 40.0, 'timestamp': '...', 'path_id': 'system.simulation.step', 'value': {'step': 5, 'now': 40.0, 'peek': 40.0}} [EVT] {'sim_ts': 40.0, 'timestamp': '...', 'key': 'orders-2', 'task': 'pack_order', 'instance': 1, 'value': {'event_type': 'order_packed'}} ``` `finish()` runs a started run on to the end that `run()` would reach (`until`, the `stop` or the end of the drain), then closes it. `run()` is `start()` followed by `finish()`. After `advance()` or `step()`, `finish()` closes the run as follows: - When the clock has reached `until` or passed it, and there is no `stop` or `drain`, `finish()` closes the run at once, as a run that ended at `until` does. - When `step()` brought the clock to exactly `until`, the records hold the run's records, which end with the final statistics. They also hold the records of the events at `until` that `step()` processed, as in SimPy. A statistics reading due at `until` is not published again, and the close adds only the values that changed after it. - After steps past `until`, the run closes where the steps stopped, with the final statistics at that time. `close()` ends the run where it is. A context from `from_yaml` steps the same way: `SimulationContext.from_yaml("shop.yaml")` returns a context with the same `start()`, `peek()`, `step()` and `close()`, as the Builder tab shows. ```python def every_ten(context): while True: yield context.env.timeout(10) stepped = SimulationContext(sim_id="Shop", factor=0.0).add_process(every_ten) stepped.start() # builds everything run() builds; the clock is still at 0 while stepped.peek() < 30: # the time of the next event stepped.step() # processes the next model event, after desflow's own events due before it print(f"stopped before {stepped.peek()} at {stepped.env.now}") stepped.close() # the teardown run() does at its end ``` `env.peek()` and `env.step()` on a `DynamicRealtimeEnvironment` skip desflow's own events in the same way, and `env.run(until=...)` runs on from where the steps stopped. It prints `stopped before 30 at 20`. Stepping does not stop at `until`: compare `peek()` with the time you want to stop at. ### Run in Segments `advance(until)` runs a started run up to a time and returns with the run still open, so a script can read the model, change it with `context.env`, or wait, then run the next segment. `finish()` runs on to the end, as it does after `start()`: `run.segments` lists the parts. A segment ends at an `until` or when a `stop` holds, and `{}` runs to the end. `look` names a task whose new entity reads the model where the segment stops, before any event due at that time runs. The task must take no time: a `look` task with a service time, or a wait that does not end at once, stops the run with an error that names it. `sync: true` on a segment moves the wall-clock anchor to the start of the segment. After each segment the run publishes `system.simulation.segment` with the segment's `index`, `now` and `peek`, which is null when no model event is left: ```yaml tasks: pack_order: service: packing resource: packers payload: {event_type: order_packed} # An order of this task reads the model where a segment stops, before any event due # at that time runs look: payload: event_type: queue_read waiting: {gen: expr, expr: queue.packers} ``` ```yaml run: until: 3 min segments: - {until: 1 min, look: look} # Ends at the first moment 4 orders wait; sync re-anchors the wall clock for the # segment, which changes nothing at factor 0 - stop: {condition: queue.packers >= 4} look: look sync: true # No end of its own: runs to the end of the run - {} ``` The readings of the first two segments: ```text [EVT] {'sim_ts': 60.0, 'timestamp': '...', 'key': 'look-1', 'task': 'look', 'instance': 0, 'value': {'event_type': 'queue_read', 'waiting': 1}} [TEL] {'sim_ts': 60.0, 'timestamp': '...', 'path_id': 'system.simulation.segment', 'value': {'index': 0, 'now': 60.0, 'peek': 60.0}} [EVT] {'sim_ts': 180.0, 'timestamp': '...', 'key': 'look-2', 'task': 'look', 'instance': 1, 'value': {'event_type': 'queue_read', 'waiting': 2}} [TEL] {'sim_ts': 180.0, 'timestamp': '...', 'path_id': 'system.simulation.segment', 'value': {'index': 1, 'now': 180.0, 'peek': 180.0}} ``` The second segment ends at 180 seconds, the end of the run, because 4 orders never waited at one moment in this run, so its `stop` condition did not apply. `segments: {every: 30 s}` makes equal parts up to `until`, which must be finite. A list whose last entry has an `until` or a `stop` and a run with no `until` end there, and a last entry `{}` runs to the end: ```yaml run: until: 2 min # A segment every 30 seconds up to until segments: {every: 30 s} ``` `run(segments=[...])` takes the same entries as dictionaries. `advance()` runs a started run in parts by hand: ```python shop = SimulationContext(sim_id="Shop", factor=0.0, random_seed=42) shop.add_resource("packers", current_cap=1) shop.add_service("packing", dist="constant", value=40) shop.add_arrival("orders", dist="exponential", rate=0.05, spawn="pack_order") @shop.task(service_id="packing", resource_id="packers") def pack_order(task_id): return {"event_type": "order_packed"} @shop.task() def look(task_id): """An order of this task reads the model where a segment stops.""" return { "event_type": "queue_read", "waiting": len(shop.get_resource("packers").queue), } shop.run( until="3 min", segments=[ {"until": "1 min", "look": "look"}, {"stop": {"condition": "queue.packers >= 4"}, "look": "look", "sync": True}, {}, # no end of its own: runs to the end of the run ], ) ``` ```python def pulse(context): while True: yield context.env.timeout(10) segmented = SimulationContext(sim_id="Shop", factor=0.0).add_process(pulse) segmented.start(until=60) segmented.advance(25) # runs the model to 25; the events at 25 wait for the next call segmented.advance("40 s") # a duration is seconds from the start, not from now print(f"paused at {segmented.env.now}") segmented.finish() # on to start()'s until, 60, and closes ``` Call `env.run(until=...)` again for each segment, as in SimPy. The records are the same as those of one run. It prints `paused at 40.0`. A run in segments gives the same records as one `run()`, the telemetry and statistics included, because nothing is flushed at a segment boundary. The same holds for a script that calls `env.run(until=...)` again on a low-level environment, as in SimPy. A few rules: - `until` is a reading of the simulation clock after `now`, in seconds or as a duration such as `"10 min"`. It can also be an event, as the third rule in this list describes. A time that is not after `now` raises `ValueError`, as SimPy does. `advance()` before `start()` or after `close()` raises `RuntimeError`. - The run stops at the earlier of `until` and its own end: `start()`'s `until`, the `stop` or the end of a drain. A later `advance()` raises `RuntimeError`, so call `finish()` or `close()`. `finish()` returns the end's value: `None` for `until` or a drain, and the stop's value for a stop. For a failed stop, it raises the stop's exception again. - `until` may be an event, such as `context.signal("gate").wait()`: the run stops where the event fires and returns its value, and the next `advance()` goes on, as SimPy's `env.run(until=event)` does. - The event that ends a segment stays in the queue: `peek()` gives the segment's time and `step()` processes it. - `advance()` does not move the wall-clock anchor. A paced run that waited between segments is behind when it goes on, so call `env.resume_pacing()` first. ### Set Up Before the Run `run.before` lists functions called with no arguments, once, at the start of `run()`. Connectors already create what they write to when they can: Kafka its event and telemetry topics, Postgres the tables under `tables`, and Parquet and JSONL their folders. `run.before` is for any other setup, such as creating the topics of a router. Put such setup in a function rather than at the top of the module. The module is imported when the file is loaded, so its top-level code runs even when a blueprint is loaded and never run. This function creates the folder `events` when the run starts: ```yaml run: {until: 1 min, before: [!python run_before_logic.make_output_folder]} ``` ```python """Python for docs/snippets/yaml/run_before.yaml: a setup function.""" import os def make_output_folder() -> None: """Called once by run.before, when the run starts, not when the file is loaded.""" os.makedirs("events", exist_ok=True) ``` The Builder API has no `run.before`: call the function before `run()`, as the [YAML form](#set-up-before-the-run) calls it. The low-level API has no `run.before`: call the function before `env.run()`, as the [YAML form](#set-up-before-the-run) calls it. ______________________________________________________________________ ## How It Works **The end of the model and the end of the run.** The model ends when the clock stops: at `until`, at a `stop`, or when a drain empties the model. The run ends after that, at `close()`, which `run()` calls in a `finally` block. `close()` publishes the last statistics, still stamped at the time the model ended. It then flushes and stops the egress connectors, and then stops the ingress connectors. A sink may take a while to drain its queue, but no record it receives is later than the model's end. ______________________________________________________________________ ## Stability and Limits The limits of this page are listed with those of the whole section, in [Stability and Limits](https://jaehyeon.me/desflow/latest/user-guide/time-and-pacing/#stability-and-limits) on the Time and Pacing page. ______________________________________________________________________ ## Example: End Conditions The `end-conditions` example shows a drain after closing time, a stop when the boxes run out, and the counts of orders still in the shop. It needs no Docker service and ends on its own. The tutorial page [End Conditions](https://jaehyeon.me/desflow/latest/learn/first-model/end-conditions/index.md) teaches these features step by step. **Quick Start** `desflow examples get` downloads the example at the release you install, into a folder of its own. Pick uv or pip: ```bash # 1. Install uv tool install desflow # 2. Download the example desflow examples get end-conditions --api yaml cd end-conditions/yaml # 3. Run it desflow run end_conditions.yaml ``` ```bash # 1. Install pip install desflow # 2. Download the example desflow examples get end-conditions --api yaml cd end-conditions/yaml # 3. Run it desflow run end_conditions.yaml ``` The whole file is [`examples/yaml/end_conditions.yaml`](https://github.com/jaehyeon-kim/desflow/blob/v1.3.0/examples/yaml/end_conditions.yaml). **Quick Start** `desflow examples get` downloads the example at the release you install, into a folder of its own. Pick uv or pip: ```bash # 1. Install uv tool install desflow # 2. Download the example desflow examples get end-conditions --api builder cd end-conditions/builder # 3. Run it uv run --no-project --with desflow end_conditions_example.py ``` ```bash # 1. Install pip install desflow # 2. Download the example desflow examples get end-conditions --api builder cd end-conditions/builder # 3. Run it python end_conditions_example.py ``` The whole file is [`examples/builder/end_conditions_example.py`](https://github.com/jaehyeon-kim/desflow/blob/v1.3.0/examples/builder/end_conditions_example.py). **Quick Start** `desflow examples get` downloads the example at the release you install, into a folder of its own. Pick uv or pip: ```bash # 1. Install uv tool install desflow # 2. Download the example desflow examples get end-conditions --api low-level cd end-conditions/low-level # 3. Run it uv run --no-project --with desflow end_conditions_example.py ``` ```bash # 1. Install pip install desflow # 2. Download the example desflow examples get end-conditions --api low-level cd end-conditions/low-level # 3. Run it python end_conditions_example.py ``` The whole file is [`examples/low-level/end_conditions_example.py`](https://github.com/jaehyeon-kim/desflow/blob/v1.3.0/examples/low-level/end_conditions_example.py). # Results A run publishes records, and it can also measure itself. One run gives one sample, many runs give an interval, and several designs give a comparison. The pages of this section go from one run to a whole study. ______________________________________________________________________ ## What It Is - **Statistics** are collected during one run: how busy each resource was, how long tasks waited, how many entities finished. A warm-up period can be left out. - **Replications** run the same model with many seeds and give each statistic a mean and a 95% interval. - **Experiments** run replications of several designs, compare the designs seed by seed, check them against bounds and observed values, and write the results and a report to files. ______________________________________________________________________ ## Pages in This Section - [Built-in Statistics](https://jaehyeon.me/desflow/latest/user-guide/results/statistics/index.md): how to switch the statistics on, what each level publishes and costs, how each value is computed, and how to add readings of your own. - [Replications](https://jaehyeon.me/desflow/latest/user-guide/results/replications/index.md): how to run replications from the command line and from Python, what they return and send to the sinks, and how the seeds and intervals are made. - [Experiments](https://jaehyeon.me/desflow/latest/user-guide/results/experiments/index.md): the experiment file, the Python call and every setting. - [Experiment Results](https://jaehyeon.me/desflow/latest/user-guide/results/experiment-results/index.md): what an experiment compares, checks and writes, and its report. ______________________________________________________________________ ## How to Use It - For one run, switch the statistics on with `stats` in YAML or `with_stats` in the builder. - For an interval, run replications with `desflow run --replications`. - To compare designs, run an experiment with `desflow experiment`. ______________________________________________________________________ ## How It Works Each layer uses the one below it. The statistics measure one run while it goes on. Replications build the model again for each seed, run it unpaced with no ingress and no egress, read the statistics at the end of each run, and give a Student t interval over the runs. An experiment runs replications for each design and compares the designs seed by seed. # Built-in Statistics A run can measure itself: how busy each resource was, how long tasks waited, how many entities finished. This page shows how to switch the statistics on, what each level publishes and costs, how each value is computed, and how to add readings of your own. ______________________________________________________________________ ## What It Is The built-in statistics are measures that desflow keeps while the run goes on and publishes as telemetry, under fixed names such as `Shop.stats.tasks.pack_order.wait_mean`. They need no code of yours in the builder or YAML, and they reach every sink like any other telemetry. They are off by default, because most runs only generate data. [Measuring a Run](https://jaehyeon.me/desflow/latest/learn/first-model/measuring-a-run/index.md) reads them on the shop. ______________________________________________________________________ ## How to Use It ### Choose a Level A level switches them on. Each level publishes what the levels before it publish, and answers one more question: | Level | Question | Adds | | --------- | --------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `none` | | nothing; the default | | `minimal` | What is happening now? | resources: `capacity`, `in_use`, `queue_length`, `utilization`, and `down` for one that breaks down; stores and containers: `capacity`, `level`, `getters_waiting`, `putters_waiting`; tasks: `in_progress` | | `basic` | How much got done, and how busy was it? | tasks and flows: `finished`; flows: `started` and `in_system`; tasks: `balked`, `reneged`, `failed`, `interrupted`, `preempted` and `resumed`, and flows: `failed`, once one happens; resources: `utilization_avg`, `queue_length_avg`, and `downtime` and `failures` for one that breaks down; stores and containers: `level_avg` | | `typical` | How long did tasks take? | tasks: `wait_mean`, `wait_max`, `service_mean`, `service_max` | | `all` | How long did the slowest take? | tasks: `wait_p50`, `wait_p95`, `wait_p99`, `service_p50`, `service_p95`, `service_p99` | They are published every `interval` of simulation time, 10 seconds when it is not given. The first publication comes one interval after the start, and one more comes at the end of the run. When the timer has already published at the end's time, the end publishes only the values that changed since: ```yaml # none (the default), minimal, basic, typical or all, each adding to the one before; # published every interval of simulation time and once at the end stats: {level: typical, interval: 1 min} ``` `stats: typical` is the short form, with the 10-second interval. The interval takes seconds or a duration. ```python # none (the default), minimal, basic, typical or all, each adding to the one before; # published every interval of simulation seconds and once at the end app.with_stats("typical", interval=60) ``` ```python env.setup_stats("Shop", "typical", interval=60) # before or after the resources ``` Resources, stores and containers add themselves to `env.stats` when they are built. Tasks are your own processes, so each reports its steps: ```python # A low-level task reports its own steps to the statistics env.stats.task_queued("pack_order", task_id) with packers.request() as request: yield request env.stats.task_started("pack_order", task_id) yield env.timeout(sampler.sample(env.registry.get_config(path_id))) env.stats.task_finished("pack_order", task_id) env.stats.flow_finished("orders") # the order leaves the shop ``` ### Publish at Each Change The readings of a resource are published every `interval`. With `on_change`, a resource also publishes them right after each request and each release on it, so a change between two intervals is on record. It needs a level above `none`, because it publishes the readings that level selects. A grant that a release makes later, and a cancel, publish none of their own. ```yaml # The readings of level minimal, and one more set after each request and release stats: {level: minimal, on_change: true} ``` ```python # The readings of level minimal, and one more set after each request and release on_change.with_stats("minimal", on_change=True) ``` ```python env.stats.on_change = True # a reading after each request and release ``` ### Trace the Events `trace` publishes one record of the kind `trace` for each event the environment is about to process, with the value `{priority, event_id, event}`. Only a sink with `when: trace` receives it, and that sink receives nothing else. A `stats` mapping with only `trace` may leave out `level`, which is then `none`. A blueprint with a `when: trace` sink and no `stats.trace` is refused when it loads. [Records and Telemetry](https://jaehyeon.me/desflow/latest/reference/records-and-telemetry/index.md) shows the record. ```yaml egress: # Only a sink with when: trace receives the trace records - {type: Console, when: trace} # With only trace set, the level is none stats: {trace: true} ``` ```python # Only a sink with when="trace" receives the trace records trace.add_egress(ConsoleEgress(), when="trace") trace.with_stats("none", trace=True) ``` ```python env.setup_egress([sink], traces=[True]) # a trace sink gets only the trace env.trace_events() ``` ### Read the Names Every statistic is published as telemetry named `.stats...`, where the kind is `resources`, `stores`, `containers`, `tasks` or `flows`. A flow is named by the arrival that started its entities: `Shop.stats.flows.orders.finished` counts the orders that left the model. [Reference, Statistics](https://jaehyeon.me/desflow/latest/reference/statistics/index.md) lists every name with what it measures. Below are the statistics that [`statistics.yaml`](https://github.com/jaehyeon-kim/desflow/blob/v1.3.0/docs/snippets/yaml/statistics.yaml), the blueprint whose `levels` part is shown above, publishes at the end of its two-minute run: ```text [TEL] {'sim_ts': 120.0, 'timestamp': '...', 'path_id': 'Shop.stats.resources.packers.capacity', 'value': 2} [TEL] {'sim_ts': 120.0, 'timestamp': '...', 'path_id': 'Shop.stats.resources.packers.in_use', 'value': 2} [TEL] {'sim_ts': 120.0, 'timestamp': '...', 'path_id': 'Shop.stats.resources.packers.queue_length', 'value': 1} [TEL] {'sim_ts': 120.0, 'timestamp': '...', 'path_id': 'Shop.stats.resources.packers.utilization', 'value': 100.0} [TEL] {'sim_ts': 120.0, 'timestamp': '...', 'path_id': 'Shop.stats.resources.packers.utilization_avg', 'value': 60.18894483201572} [TEL] {'sim_ts': 120.0, 'timestamp': '...', 'path_id': 'Shop.stats.resources.packers.queue_length_avg', 'value': 0.2614487300647045} [TEL] {'sim_ts': 120.0, 'timestamp': '...', 'path_id': 'Shop.stats.tasks.pack_order.in_progress', 'value': 3} [TEL] {'sim_ts': 120.0, 'timestamp': '...', 'path_id': 'Shop.stats.tasks.pack_order.finished', 'value': 53} [TEL] {'sim_ts': 120.0, 'timestamp': '...', 'path_id': 'Shop.stats.tasks.pack_order.wait_mean', 'value': 0.5197319258327968} [TEL] {'sim_ts': 120.0, 'timestamp': '...', 'path_id': 'Shop.stats.tasks.pack_order.wait_max', 'value': 3.499903738251632} [TEL] {'sim_ts': 120.0, 'timestamp': '...', 'path_id': 'Shop.stats.tasks.pack_order.service_mean', 'value': 2.649184782997398} [TEL] {'sim_ts': 120.0, 'timestamp': '...', 'path_id': 'Shop.stats.tasks.pack_order.service_max', 'value': 7.591874747378057} [TEL] {'sim_ts': 120.0, 'timestamp': '...', 'path_id': 'Shop.stats.flows.orders.finished', 'value': 53} [TEL] {'sim_ts': 120.0, 'timestamp': '...', 'path_id': 'Shop.stats.flows.orders.started', 'value': 56} [TEL] {'sim_ts': 120.0, 'timestamp': '...', 'path_id': 'Shop.stats.flows.orders.in_system', 'value': 3} ``` The same values can be read by name, during or after the run: `desflow run --stdout` prints the same values as telemetry records, as above. `app.env.stats.readings()` gives the same values, by name, during or after the run. ```python # Every statistic the level publishes, by its published name readings = env.stats.readings() print(f"mean wait {readings['Shop.stats.tasks.pack_order.wait_mean']:.2f} s") ``` ### Which Entities a Count Covers When the statistics are read, every entity that has arrived belongs to one population. Each population has its own counts, published from `basic` unless the table says otherwise. A mean wait or service time covers only the instances that reached that step, so report the counts beside it: | Population | Which entities | Counts | | ---------------- | -------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | completed | left the model after their last task | `flows..finished`; `tasks..finished` per task | | still present | started and not yet ended when the statistics are read | `flows..in_system`; `tasks..in_progress`, the instances queued or started, from `minimal` | | rejected | refused to join a queue, as their `balk` held | `tasks..balked` | | abandoned | left a queue when their `patience` ran out, or ended by an interrupt under `on_interrupt: abandon` | `tasks..reneged`; an abandoned flow leaves `in_system` without adding to `finished` or `failed`, and `tasks..interrupted` counts the interrupts | | failed | ended in a failure that no `on_fail` handled | `flows..failed`; `tasks..failed` counts failed instances | | warm-up-crossing | started before the warm-up ended and ended after it | in `finished` but not in `started`; an instance still queued at the end of the warm-up adds its whole wait, and one in service adds its whole service time and no wait; an instance that started before the warm-up ended, was preempted and resumes after it adds no wait for the time since the preemption, because its first wait belongs to the statistics that the reset replaced | An entity a task spawns ([Start a Flow Without Waiting](https://jaehyeon.me/desflow/latest/user-guide/tasks-and-processes/signals-and-waiting/#start-a-flow-without-waiting)) counts as a flow of its own under the spawned task's name. So `flows..*` and `tasks..*` cover it as they cover any arrival's flow. The spawning entity's key is in `attr.parent`. Without a [warm-up](https://jaehyeon.me/desflow/latest/learn/concepts/output-analysis/#one-run-starts-empty), `started` is `finished` plus `in_system` plus the entities that balked, reneged, failed or were abandoned. A warm-up starts `started`, `finished`, `failed` and the outcome counts again from zero, and leaves `in_system` and `in_progress` as they are. After a warm-up, `finished` also counts the warm-up-crossing entities, which `started` leaves out, so `finished` can be larger than `started`. [End Conditions](https://jaehyeon.me/desflow/latest/learn/first-model/end-conditions/index.md) counts each population of a run. ### Add Readings of Your Own Anything else is a custom reading: a value that is published at an interval of simulation time as `.`. In YAML, a `telemetry` entry gives each reading as an expression. An expression can read a resource's queue, a registry value and the time `t`. It cannot read an entity or a task. ```yaml telemetry: # Readings of your own: two expressions, evaluated every 30 seconds - interval: 30 readings: waiting_per_packer: "queue.packers / max(registry['Shop.resources.packers.current_cap'], 1)" arrival_rate: "registry['Shop.arrival.orders.rate']" ``` ```python # Readings of your own: two expressions, evaluated every 30 seconds readings.add_readings( 30, { "waiting_per_packer": "queue.packers / max(registry['Shop.resources.packers.current_cap'], 1)", "arrival_rate": "registry['Shop.arrival.orders.rate']", }, ) ``` A process that loops, publishes with `env.publish_telemetry(name, value)` and waits with `env.timeout(interval)` does the same. Each reading is published at the start and then every `interval`, in the order given. The readings divide by the planned capacity, `registry['Shop.resources.packers.current_cap']`, because the expression language has no name for the live capacity. For a resource that breaks down, the planned and the live capacity differ while it is down. Keep a function for a reading that an expression cannot make. The function runs at an interval and publishes with `context.publish(name, value)`: ```yaml telemetry: # Readings of your own: called as packers_report(context) every 30 seconds - {interval: 30, function: !python shop_logic.packers_report} ``` The function is in `shop_logic.py`, beside the blueprint: ```python def packers_report(context): """A custom reading: orders waiting per packer, and the live arrival rate.""" packers = context.get_resource("packers") waiting = len(packers.queue) context.publish("waiting_per_packer", waiting / max(packers.capacity, 1)) rate = context.env.registry.get(f"{context.sim_id}.arrival.orders.rate").value context.publish("arrival_rate", rate) # as Shop.arrival_rate ``` ```python @app.telemetry_loop(interval=30.0) def packers_report(context: SimulationContext): """Readings of your own: orders waiting per packer, and the live arrival rate.""" packers = context.get_resource("packers") waiting = len(packers.queue) context.publish("waiting_per_packer", waiting / max(packers.capacity, 1)) rate = context.env.registry.get("Shop.arrival.orders.rate").value context.publish("arrival_rate", rate) # as Shop.arrival_rate ``` A process that loops, publishes with `env.publish_telemetry(name, value)` and waits with `env.timeout(interval)` does the same. ______________________________________________________________________ ## How It Works The environment keeps one `Statistics` object, `env.stats`, which collects nothing until a level above `none` is set. Its timer publishes every value at each interval, and the teardown publishes them once more. When the timer has already published at the teardown's time, the teardown publishes only the values that changed since. **Readings now.** `capacity`, `in_use`, `queue_length` and `level` are read from the object at the moment of publishing. `in_use` counts the units held by tasks, and a capacity drop does not take busy units away. After a drop, `in_use` can therefore be above `capacity`, and `utilization` (`in_use ÷ capacity × 100`) can be above 100%. At a capacity of 0 with units still held, `utilization` is 100. A resource with no limit (`current_cap: .inf`) publishes `capacity` as `null` and a `utilization` of 0. A store or container with no limit publishes its `capacity` as `null` too. **Breakdowns.** A resource with a `breakdown` reads `down` now: 1 while it is down, 0 otherwise. `downtime` adds the length of each down period, and of one still going on. `failures` adds one at each failure. [Model Breakdowns](https://jaehyeon.me/desflow/latest/how-to/modelling/breakdowns/index.md) checks both against the events. **Averages over time.** `utilization_avg`, `queue_length_avg` and `level_avg` weigh each value by how long it lasted. Each resource, store and container reports every change, and the statistics add the area under the value since the last change, so the average is exact at any moment rather than sampled: **Counts.** `finished` adds one when a task instance finishes, and a flow's `finished` adds one when an entity's last task has no next task. A flow's `started` adds one when an entity's first task instance begins, before its balk check and its queue, whether or not it is then served. An entity that the `spawn` key or an `on:` spawn action starts is counted at the spawn when the spawn has no `after`. With an `after`, it is counted when the spawned task starts, after the delay. `in_system` is the number of the flow's entities in the model now: started, and not yet finished, failed or gone. [Which Entities a Count Covers](#which-entities-a-count-covers) shows how `started` adds up. A task's `in_progress` is the number of its instances queued or started and not yet ended, now. A low-level process reports an entity's start with `env.stats.flow_started(arrival)`. It reports an entity that leaves without finishing or failing with `env.stats.flow_ended(arrival)`. A task's `balked` adds one when an instance refuses to join its queue, `reneged` when one leaves the queue after its patience, and `failed` when one fails ([Failures](https://jaehyeon.me/desflow/latest/user-guide/tasks-and-processes/failures/#failures)). A flow's `failed` adds one when an entity's flow ends in a failure no `on_fail` handles. `interrupted` and `preempted` add one for each interrupt or preemption an instance receives, and `resumed` when it is served again. Each is published once it is above 0. A balked, reneged or failed instance adds no wait or service time. An interrupted instance that resumes adds one wait, the sum of all its waits, and one service time, the time it was served. A low-level process counts them with `env.stats.task_balked(task, instance)`, `env.stats.task_reneged(task, instance)`, `env.stats.task_failed(task, instance)`, `env.stats.flow_failed(arrival)`, `env.stats.task_interrupted(task, instance, preempted=...)` and `env.stats.task_resumed(task, instance)`. **Wait and service.** The wait of a task instance runs from its `queued` step to its `started` step, and its service from `started` to finished. A task that never queues, such as a timed step, waits 0. `typical` keeps only a count, a total and a maximum of each, so the memory they use does not grow with the run. `all` keeps every observation and computes the percentiles exactly with NumPy's `percentile` at each publication, so its memory grows with the number of tasks. **Warm-up.** A run's `warmup` resets every statistic once, at that time: the averages start again from zero area, and the counts and observations from zero. An instance that was queued before the reset and starts after it counts with its whole wait. [Time and Pacing](https://jaehyeon.me/desflow/latest/user-guide/time-and-pacing/index.md) describes the warm-up. ______________________________________________________________________ ## Stability and Limits - **Cost.** `minimal` reads a few values at each publication. `basic` adds a little work at every change of a resource, store or container. `typical` adds a little at every task step. `all` keeps every wait and service time in memory for the whole run. Use it for runs of thousands of tasks, not for a generator that runs for days. - **One way to get resource readings.** Before 0.21.0, a `telemetry` entry could publish `.` by name. That shortcut is gone: `stats: minimal` publishes the same readings, under `Shop.stats.resources..`. `telemetry` now takes only readings and functions, for values of your own. - **One run is one sample.** The statistics describe one run with one seed. Values from the same run are not independent of each other, and another seed gives other values. [Replications](https://jaehyeon.me/desflow/latest/learn/concepts/output-analysis/#replications) give independent values. [Trusting Results](https://jaehyeon.me/desflow/latest/learn/studies/trusting-results/index.md) shows what that means for a result, and [Replications](https://jaehyeon.me/desflow/latest/user-guide/results/replications/index.md) run a model with many seeds. - **A task appears once it has run.** At `typical` and `all`, a task's statistics are published from the first time it starts. At `basic`, they are published from the first time it finishes. ______________________________________________________________________ ## Example: Measuring a Run The `measuring` example publishes every statistic of the packers and the pack task every 5 minutes of simulation time, and leaves out a 3-minute warm-up. When packing slows down, it sends a ground-truth record to a sink of its own. It needs no Docker service and ends on its own. The tutorial page [Measuring a Run](https://jaehyeon.me/desflow/latest/learn/first-model/measuring-a-run/index.md) teaches these features step by step. **Quick Start** `desflow examples get` downloads the example at the release you install, into a folder of its own. Pick uv or pip: ```bash # 1. Install uv tool install desflow # 2. Download the example desflow examples get measuring --api yaml cd measuring/yaml # 3. Run it desflow run measuring.yaml ``` ```bash # 1. Install pip install desflow # 2. Download the example desflow examples get measuring --api yaml cd measuring/yaml # 3. Run it desflow run measuring.yaml ``` ```yaml # Every level: readings, counts and time averages, mean and maximum wait and service, # and their 50th, 95th and 99th percentiles, such as Shop.stats.tasks.pack.wait_p95. stats: {level: all, interval: 5 min} scenario: # Packing slows from 4 to 4.8 seconds on average. The record is the ground truth. - at: 12 min path: Shop.service.packing.scale value: 1.2 record: {fault: slow_packing, cause: new packing material} ``` The whole file is [`examples/yaml/measuring.yaml`](https://github.com/jaehyeon-kim/desflow/blob/v1.3.0/examples/yaml/measuring.yaml). **Quick Start** `desflow examples get` downloads the example at the release you install, into a folder of its own. Pick uv or pip: ```bash # 1. Install uv tool install desflow # 2. Download the example desflow examples get measuring --api builder cd measuring/builder # 3. Run it uv run --no-project --with desflow measuring_example.py ``` ```bash # 1. Install pip install desflow # 2. Download the example desflow examples get measuring --api builder cd measuring/builder # 3. Run it python measuring_example.py ``` ```python def slow_packing(context): """Packing slows from 4 to 4.8 seconds on average at 12 minutes, with its label.""" yield context.env.timeout(720) path = "Shop.service.packing.scale" registry = context.env.registry old = registry.get(path).value registry.update(path, 1.2) context.env.publish_label( {"fault": "slow_packing", "cause": "new packing material"}, path=path, old=old, new=registry.get(path).value, ) app.add_process(slow_packing) ``` The whole file is [`examples/builder/measuring_example.py`](https://github.com/jaehyeon-kim/desflow/blob/v1.3.0/examples/builder/measuring_example.py). **Quick Start** `desflow examples get` downloads the example at the release you install, into a folder of its own. Pick uv or pip: ```bash # 1. Install uv tool install desflow # 2. Download the example desflow examples get measuring --api low-level cd measuring/low-level # 3. Run it uv run --no-project --with desflow measuring_example.py ``` ```bash # 1. Install pip install desflow # 2. Download the example desflow examples get measuring --api low-level cd measuring/low-level # 3. Run it python measuring_example.py ``` ```python # Every level, published every 5 minutes, such as Shop.stats.tasks.pack.wait_p95 env.setup_stats("Shop", "all", interval=300) # The second sink receives the ground-truth records, and nothing else env.setup_egress( [ConsoleEgress(), ConsoleEgress()], labels=[False, True], warmup=WARMUP ) ``` The whole file is [`examples/low-level/measuring_example.py`](https://github.com/jaehyeon-kim/desflow/blob/v1.3.0/examples/low-level/measuring_example.py). # Replications One run of a model is one sample: another seed draws other times and gives other values. [Replications](https://jaehyeon.me/desflow/latest/learn/concepts/output-analysis/#replications) run the same model with many seeds and summarise each built-in statistic with a mean and a [95% interval](https://jaehyeon.me/desflow/latest/learn/concepts/output-analysis/#interval-and-half-width). This page shows how to run them from the command line and from Python, in each of the three ways to write a model, what they return and send to the sinks, and how the seeds and intervals are made. ______________________________________________________________________ ## What It Is A replication is one run of the model with a seed of its own. N replications give N independent values of each [built-in statistic](https://jaehyeon.me/desflow/latest/user-guide/results/statistics/index.md), such as the mean wait of a task. Their mean is the estimate, and the **half-width** of its 95% interval says how precise it is: with 95% confidence, the true value lies within the mean plus or minus the half-width. [Trusting Results](https://jaehyeon.me/desflow/latest/learn/studies/trusting-results/index.md) shows on the shop why one run is not an answer and how to choose the number of replications. ______________________________________________________________________ ## How to Use It ### Run Replications Give the model, the number of replications, the seed they are spawned from and the time the arrivals stop: ```bash desflow run replications.yaml --replications 20 --measure tasks.pack.wait_mean ``` `--seed` overrides `simulation.random_seed`, and `--until` overrides `run.until`, as for one run. `--level` sets the confidence level (0.95 when it is not given), `--workers` sets how many replications run at once, each in its own process, and `--drain` drains every replication, as `run.drain: true` does. The command prints the summary, the seed of each replication and the command that repeats one. The blueprint's own `warmup` applies to every replication: ```yaml # The replications' seeds are spawned from this one; --seed overrides it random_seed: 42 warmup: 3 min ``` ```python # shop is a function returning a new SimulationContext, called once per run result = replicate(shop, 3, seed=42, until="1 h", warmup="3 min", measures=MEASURES) ``` `shop` is a function with no arguments that returns a new `SimulationContext`, such as [the example's](https://github.com/jaehyeon-kim/desflow/blob/v1.3.0/examples/builder/replications_example.py), because each replication starts from a new context. A blueprint path works here too. ```python def model(env, sampler): """Builds the shop in the environment it is given, drawing from sampler.""" env.registry.register_sim_parameter(PARAMS) env.process(orders(env, sampler, DynamicResource(env, "Shop", "packers"))) def low_level(): shop = LowLevelModel(model, sim_id="Shop") return replicate(shop, 3, seed=42, until=3600, warmup=180, measures=MEASURES) ``` `LowLevelModel` takes a function that builds the model, given an environment and a sampler, and the `sim_id` that the model's statistics are published under. The function registers the parameters, builds the resources and starts the processes. It sets up no statistics, because `replicate` does, and it sets up no sinks. Its tasks report their steps to `env.stats`, as [Statistics](https://jaehyeon.me/desflow/latest/user-guide/results/statistics/index.md) shows. `replicate` takes these options: | Option | What it sets | Default | | ----------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------- | | `n` | how many replications, 2 or more | | | `seed` | the seed the replications' seeds are spawned from, a whole number of 0 or more and not `true`; None draws one and logs it | | | `until` | where each replication's arrivals stop, in seconds or a duration such as `"1 h"`; the replication ends there unless `stop` ends it earlier or `drain` runs on | a blueprint's `run.until` | | `stop` | ends each replication when it happens, as for `run()`: `{"signal": name}`, a signal's name, or `{"condition": "..."}`; for a `LowLevelModel`, a function of the environment that returns the event | a blueprint's `run.stop` | | `drain` | at `until`, stop the arrivals and run each replication on until no entity is left: `True`, or `{"limit": "1 h"}`; a `LowLevelModel` is drained when its function returns its arrival processes and reports its entities with `env.stats.flow_started` and `flow_finished` | a blueprint's `run.drain` | | `warmup` | the end of each replication's warm-up | the model's own | | `measures` | the statistics to summarise | every statistic the run publishes, at least up to `typical` | | `level` | the confidence level of the half-widths | 0.95 | | `workers` | how many replications run at once, each in its own process | 1 | | `overrides` | registry paths and the values every replication starts with, such as `{"Shop.resources.packers.current_cap": 3}`, set in the order given; a value the registry would refuse or clamp is refused, so a `max_cap` below the current `current_cap` needs `current_cap` set first | none | ### Choose the Measures A measure is a statistic's published name without the sim id and `stats`, such as `tasks.pack.wait_mean` for `Shop.stats.tasks.pack.wait_mean`. [Reference, Statistics](https://jaehyeon.me/desflow/latest/reference/statistics/index.md) lists them. Each replication keeps the statistics level its measures need, whatever level the model sets: `basic` for counts and time averages, `typical` for means and maxima of waits and services, and `all` for percentiles. A higher level the model sets stays. A name that no replication publishes is refused, with the names the model does publish. The exception is a count that the statistics leave out while it is 0: a task's `in_progress`, `finished`, `balked`, `reneged`, `failed`, `interrupted`, `preempted` and `resumed`, and a flow's `finished`, `started`, `in_system` and `failed`. Such a count is 0 in a replication that did not publish it, also when no replication published it, once a replication published another statistic of the same task or flow. A name of a task or flow that no replication published anything of is still refused. `desflow test`, an experiment's counts and `desflow explain --verify` read these counts the same way. A mean with no observation in a replication, such as the wait of a task that never started, is refused with the replication's number rather than left out. ### Read the Result `replicate`, imported with `from desflow import replicate`, returns a `Replications`. Its `summary` has one row per measure: a mapping with `measure`, `n`, `mean`, `half_width` and `level`. The interval runs from `mean - half_width` to `mean + half_width`. Its `table` has one row per replication and measure, with the replication's number and seed, and `seeds` lists the seeds in order: ```python print(result.summary_text()) # each measure's n, mean and half-width for row in result.summary: # measure, n, mean, half_width and level low, high = row["mean"] - row["half_width"], row["mean"] + row["half_width"] print(f"{row['measure']}: {low:.2f} to {high:.2f} ({row['level']:.0%})") print(result.seeds) # replication i ran with seeds[i - 1] for row in result.table: # one row per replication and measure print(row["replication"], row["seed"], row["measure"], row["value"]) ``` The summary of the three replications above: ```text measure n mean half-width (95%) tasks.pack.wait_mean 3 4.327 1.776 resources.packers.utilization_avg 3 80.55 4.613 ``` Three replications give a wide interval. [Trusting Results](https://jaehyeon.me/desflow/latest/learn/studies/trusting-results/#choose-the-precision) shows how to choose enough. ### Write the Result to a File `desflow run --summary PATH` writes the result to one JSON file when the replications end. A program that runs desflow, such as a task in a pipeline, then reads the numbers from the file instead of the printed table. A folder in the path that does not exist is created: ```bash desflow run replications.yaml --replications 3 --measure tasks.pack.wait_mean --summary result.json ``` The file these three replications write, with the versions shown as `...`: ```text { "command": "desflow run", "model": { "form": "yaml", "source": "replications.yaml", "sha256": "162f01a2a9e561a706ec2b5e3dd4848b2b06a628334acc2bbd697289f6f5e833", "sim_id": "Shop" }, "versions": { "desflow": "...", "simpy": "...", "numpy": "...", "python": "..." }, "settings": { "until": 3600.0, "drain": false, "seed": 42, "replications": 3, "level": 0.95, "measures": [ "tasks.pack.wait_mean" ], "workers": 1, "variables": {} }, "seeds": [ 2684470948, 4091952314, 233227757 ], "summary": [ { "statistic": "tasks.pack.wait_mean", "unit": "s", "population": "started instances", "n": 3, "mean": 4.327455004, "half_width": 1.775561705, "low": 2.5518933, "high": 6.103016709, "level": 0.95 } ], "results": [ { "replication": 1, "seed": 2684470948, "statistic": "tasks.pack.wait_mean", "unit": "s", "population": "started instances", "value": 4.074824798 }, { "replication": 2, "seed": 4091952314, "statistic": "tasks.pack.wait_mean", "unit": "s", "population": "started instances", "value": 3.77331804 }, { "replication": 3, "seed": 233227757, "statistic": "tasks.pack.wait_mean", "unit": "s", "population": "started instances", "value": 5.134222175 } ] } ``` The file holds these keys, in this order: - `command`: `desflow run`. - `model`: the form, the file as given, the file's SHA-256 and the sim id, as in an experiment's `experiment.json` ([Experiment Results](https://jaehyeon.me/desflow/latest/user-guide/results/experiment-results/index.md)). - `versions`: the versions of desflow, SimPy, NumPy and Python that ran it. - `settings`: `until` in seconds, `drain`, `seed`, `replications`, `level`, `measures` (null for every statistic), `workers`, and the `--var` values as `variables`. - `seeds`: the seed of each replication, in order. - `summary`: one row per measure, with the columns of `summary.csv` for one design: `statistic`, `unit`, `population`, `n`, `mean`, `half_width`, `low`, `high` and `level`. - `results`: one row per replication and measure, with the columns of `results.csv` for one design, without `kind`: `replication`, `seed`, `statistic`, `unit`, `population` and `value`. Without `--replications`, `--summary` writes the statistics of the single run. `seeds`, `summary` and `results` are replaced by `end_time`, the simulation time the run ended at, and `statistics`, one row per statistic with `statistic`, `unit`, `population` and `value`. A single run collects no statistics unless its blueprint sets `stats`, so with `--summary` it keeps every statistic up to `typical`, as replications do. A model with sinks then also sends them the statistics telemetry that `stats: typical` publishes. The file is written only when the run ends with exit code 0. It is written to a temporary file beside it, then moved into place, so a reader never sees half a file. A file already at PATH is removed when the run starts, so a run that fails, or is stopped with Ctrl+C or SIGTERM, leaves no file to be read as its result, and a stopped run says so on stderr. `--summary` works with `--stdout`, and is refused with `--sample` and `--watch`. ### Repeat One Replication Each replication's seed is a plain integer, recorded in `seeds` and in every row of the table. Any replication can therefore be repeated on its own, with the same end time, drain and [warm-up](https://jaehyeon.me/desflow/latest/learn/concepts/output-analysis/#one-run-starts-empty): `desflow run shop.yaml --seed `, `random_seed` in a builder context, or `Sampler(seed=...)` in the low-level API. That run publishes its event records, which replications do not. ### What the Sinks Receive When the model has sinks, a blueprint's `egress` or a builder's `add_egress`, they receive the result once, as telemetry stamped at the end time: each replication's value, then each measure's mean, half-width and count. A low-level model has no sinks of its own. Below are the records a Console sink receives from the three replications above, with each value rounded to 10 significant digits because the last digits differ between platforms: ```text [TEL] {'sim_ts': 3600.0, 'timestamp': '...', 'path_id': 'Shop.stats.tasks.pack.wait_mean.replication.1', 'value': 4.074824798} [TEL] {'sim_ts': 3600.0, 'timestamp': '...', 'path_id': 'Shop.stats.tasks.pack.wait_mean.replication.2', 'value': 3.77331804} [TEL] {'sim_ts': 3600.0, 'timestamp': '...', 'path_id': 'Shop.stats.tasks.pack.wait_mean.replication.3', 'value': 5.134222175} [TEL] {'sim_ts': 3600.0, 'timestamp': '...', 'path_id': 'Shop.stats.resources.packers.utilization_avg.replication.1', 'value': 78.48408509} [TEL] {'sim_ts': 3600.0, 'timestamp': '...', 'path_id': 'Shop.stats.resources.packers.utilization_avg.replication.2', 'value': 81.07923191} [TEL] {'sim_ts': 3600.0, 'timestamp': '...', 'path_id': 'Shop.stats.resources.packers.utilization_avg.replication.3', 'value': 82.08253291} [TEL] {'sim_ts': 3600.0, 'timestamp': '...', 'path_id': 'Shop.stats.tasks.pack.wait_mean.mean', 'value': 4.327455004} [TEL] {'sim_ts': 3600.0, 'timestamp': '...', 'path_id': 'Shop.stats.tasks.pack.wait_mean.half_width', 'value': 1.775561705} [TEL] {'sim_ts': 3600.0, 'timestamp': '...', 'path_id': 'Shop.stats.tasks.pack.wait_mean.n', 'value': 3} [TEL] {'sim_ts': 3600.0, 'timestamp': '...', 'path_id': 'Shop.stats.resources.packers.utilization_avg.mean', 'value': 80.54861664} [TEL] {'sim_ts': 3600.0, 'timestamp': '...', 'path_id': 'Shop.stats.resources.packers.utilization_avg.half_width', 'value': 4.61299164} [TEL] {'sim_ts': 3600.0, 'timestamp': '...', 'path_id': 'Shop.stats.resources.packers.utilization_avg.n', 'value': 3} ``` [Records and Telemetry](https://jaehyeon.me/desflow/latest/reference/records-and-telemetry/#telemetry-names) lists the names. ______________________________________________________________________ ## How It Works **Seeds.** The replications' seeds are `numpy.random.SeedSequence(seed).spawn(n)`, each turned into one plain integer. The same seed gives the same list, and a longer list starts with the shorter one, so 40 replications begin with the 10 that `n=10` runs. Within a replication each distribution draws from a random sequence of its own, as in any run ([Randomness and Seeds](https://jaehyeon.me/desflow/latest/learn/first-model/randomness-and-seeds/index.md)). **One replication.** Each replication builds the model again: it reads the blueprint, calls the factory, or calls the low-level function with a new environment and sampler. It runs unpaced, at `factor` 0, with no ingress, no egress and no statistics timer. It applies the warm-up and the `overrides` before the clock starts, and reads `env.stats.readings()` at its end. A blueprint's `run.before` functions run once per replication, and once more when the model has sinks, for the build that sends them the result. **Intervals.** The half-width is t × s ÷ √n. Here s is the sample standard deviation of the n values, and t is the Student t quantile at (1 + level) ÷ 2 with n − 1 degrees of freedom. desflow computes the quantile itself, by bisection on the t distribution's cumulative probability, so replications need nothing beyond a base install. The tests check it against a published table. **Workers.** With `workers` above 1, replications run in a pool of that many processes. Each process imports the model. The model must therefore be a blueprint path or a function defined at the top of a module. A lambda, or a function defined inside another function, is refused with that reason. The values are the same as with one worker. **Sinks.** When the model has sinks, it is built once more after the last replication, with its sinks, without its ingress, and with the clock at the end time. This build is not run. Its own statistics are switched off, so the sinks receive only the result. A model without sinks is not built again. ______________________________________________________________________ ## Stability and Limits - **No event records.** Replications send no event records: the orders of twenty replications, each with its own seed, would mix in one sink and could not be told apart. Repeat one replication with its seed to get its records. - **Independent seeds only.** Every replication of one call has its own seed. Comparing two designs with the same seeds, and checking that their random streams line up, is an experiment's job ([Experiments](https://jaehyeon.me/desflow/latest/user-guide/results/experiments/index.md)). - **Same model each time.** A builder factory must return a new context on every call. A context that has run keeps its entity counters and is not a new replication. - **Built-in statistics only.** A replication summarises the built-in statistics at its end. Readings of your own, published with `context.publish`, are not summarised. - **Steady state and terminating runs.** The warm-up applies to each replication. A run with a natural start and end, such as a shop day, keeps its empty start and needs no warm-up. [Output Analysis](https://jaehyeon.me/desflow/latest/learn/concepts/output-analysis/#terminating-or-steady-state) explains the two kinds of run. ______________________________________________________________________ ## Example: Replications The `replications` example runs one hour of the shop 20 times, with seeds spawned from 42 and a 3-minute warm-up, and prints the mean and half-width of every statistic up to `typical`. It needs no Docker service and ends on its own. The tutorial page [Trusting Results](https://jaehyeon.me/desflow/latest/learn/studies/trusting-results/index.md) teaches these features step by step. **Quick Start** `desflow examples get` downloads the example at the release you install, into a folder of its own. Pick uv or pip: ```bash # 1. Install uv tool install desflow # 2. Download the example desflow examples get replications --api yaml cd replications/yaml # 3. Find the bottleneck, with no run desflow explain replications.yaml # 4. Run it desflow run replications.yaml --replications 20 ``` ```bash # 1. Install pip install desflow # 2. Download the example desflow examples get replications --api yaml cd replications/yaml # 3. Find the bottleneck, with no run desflow explain replications.yaml # 4. Run it desflow run replications.yaml --replications 20 ``` ```yaml # The replications' seeds are spawned from this one; --seed overrides it random_seed: 42 warmup: 3 min ``` The whole file is [`examples/yaml/replications.yaml`](https://github.com/jaehyeon-kim/desflow/blob/v1.3.0/examples/yaml/replications.yaml). **Quick Start** `desflow examples get` downloads the example at the release you install, into a folder of its own. Pick uv or pip: ```bash # 1. Install uv tool install desflow # 2. Download the example desflow examples get replications --api builder cd replications/builder # 3. Run it uv run --no-project --with desflow replications_example.py ``` ```bash # 1. Install pip install desflow # 2. Download the example desflow examples get replications --api builder cd replications/builder # 3. Run it python replications_example.py ``` ```python # 20 seeds spawned from 42; each replication runs unpaced, with no sinks result = replicate(shop, 20, seed=42, until="1 h") print(result.summary_text()) # Any replication repeats on its own: run shop() with its seed print("replication seeds:", result.seeds) ``` The whole file is [`examples/builder/replications_example.py`](https://github.com/jaehyeon-kim/desflow/blob/v1.3.0/examples/builder/replications_example.py). **Quick Start** `desflow examples get` downloads the example at the release you install, into a folder of its own. Pick uv or pip: ```bash # 1. Install uv tool install desflow # 2. Download the example desflow examples get replications --api low-level cd replications/low-level # 3. Run it uv run --no-project --with desflow replications_example.py ``` ```bash # 1. Install pip install desflow # 2. Download the example desflow examples get replications --api low-level cd replications/low-level # 3. Run it python replications_example.py ``` ```python # 20 seeds spawned from 42; each replication runs unpaced, with no sinks shop = LowLevelModel(model, sim_id="Shop") result = replicate(shop, 20, seed=42, until=3600, warmup=WARMUP) print(result.summary_text()) # Any replication repeats on its own: call model with Sampler(seed=...) print("replication seeds:", result.seeds) ``` The whole file is [`examples/low-level/replications_example.py`](https://github.com/jaehyeon-kim/desflow/blob/v1.3.0/examples/low-level/replications_example.py). # Experiments An experiment answers a question with many runs rather than one. It runs several designs of a model, each with [replications](https://jaehyeon.me/desflow/latest/learn/concepts/output-analysis/#replications). It compares the designs seed by seed, checks them against bounds, and places them beside values observed in the real system. It writes its results and a report to files. This page describes the experiment file, the Python call and every setting. [Experiment Results](https://jaehyeon.me/desflow/latest/user-guide/results/experiment-results/index.md) describes the files an experiment writes and its report. It runs on one machine and needs no server. ______________________________________________________________________ ## What It Is A **design** is the model with some registry values changed before the clock starts: a variant, or a variant at one point of a sweep. An experiment runs every design with the same number of [replications](https://jaehyeon.me/desflow/latest/user-guide/results/replications/index.md), reads the built-in statistics at the end of each run, and summarises each with a mean and a [95% interval](https://jaehyeon.me/desflow/latest/learn/concepts/output-analysis/#interval-and-half-width). [Comparing Designs](https://jaehyeon.me/desflow/latest/learn/studies/comparing-designs/index.md) and [Parameter Sweeps](https://jaehyeon.me/desflow/latest/learn/studies/parameter-sweeps/index.md) use one on the shop. ______________________________________________________________________ ## Reading the Results The next page, [Experiment Results](https://jaehyeon.me/desflow/latest/user-guide/results/experiment-results/index.md), shows how to compare designs, check results against bounds, place observed values beside them, and read the files and the report. ______________________________________________________________________ ## How to Use It ### Write an Experiment An experiment names its model, how long and how often to run it, what to measure, the designs and what to compare and check. In a file: ```yaml # An experiment in YAML: does a third packer keep the mean wait under 2 seconds? # # The YAML version of experiment_example.py, which --api builder downloads. The model is # experiment_shop.yaml. The experiment runs one hour of it 20 times with two packers # and 20 times with three, with the same seeds, after a 3-minute warm-up. It # compares the two designs seed by seed, checks the three-packer design against a # 2-second bound, and compares the two-packer design with the mean wait observed in # the real shop. It writes its artifacts and report to results/packers, and exits 1 # if the check fails. # # Needs no containers. # Run it with: desflow experiment experiment.yaml experiment: packers question: Does a third packer keep the mean wait under 2 seconds? model: experiment_shop.yaml assumptions: - Orders arrive at random, at a steady rate, through the hour. - Every packer works at the same speed. inputs: {Shop.service.packing: 40 packing times measured at the bench} until: 1 h warmup: 3 min replications: 20 seed: 42 # Both designs run with the same 20 seeds, so they are compared seed by seed pairing: common measures: [tasks.pack.wait_mean, resources.packers.utilization_avg] variants: two: {} three: {Shop.resources.packers.current_cap: 3} compare: - {baseline: two, variant: three} checks: # The upper end of the interval must be under 2 seconds - {measure: tasks.pack.wait_mean, variant: three, max: 2} observed: # The mean wait measured in the real shop, which has two packers file: ../observed_waits.csv variant: two limits: [One hour of steady demand; the rest of the day is not modelled.] output: results/packers ``` In Python the same settings are a mapping, and the model is a blueprint path, a builder factory or a `LowLevelModel`. The table lists every setting: | Setting | What it sets | Default | | -------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------- | | `experiment` | the experiment's name, one folder name with no `/` or `\`, because the files go to `results/` | required | | `question` | the question the experiment answers, the report's first section | not stated | | `model` | a blueprint path, such as `experiment_shop.yaml`; to build the model in code instead, `!python module.function`, a function returning a new `SimulationContext`, or `{function: !python module.function, sim_id: Shop}`, a [low-level function](https://jaehyeon.me/desflow/latest/user-guide/results/replications/#run-replications) | required | | `assumptions` | sentences the report lists | none | | `inputs` | each distribution's registry path, such as `Shop.service.packing`, and where its values came from | none | | `until` | where each run's arrivals stop, in seconds or a duration such as `8 h`; the run ends there unless `stop` ends it earlier or `drain` runs on | required | | `stop` | ends each run when it happens: `{signal: name}` or `{condition: "..."}`; for a low-level model, given in Python, a function of the environment that returns the event | a blueprint's `run.stop` | | `drain` | at `until`, stop the arrivals and run on until the model is empty: `true`, or `{limit: 1 h}`; a low-level model is drained when its function returns its arrival processes | a blueprint's `run.drain` | | `warmup` | each run's warm-up | the model's own | | `replications` | runs of each design, 2 or more | required | | `seed` | the seed every run's seed is spawned from: a whole number of 0 or more, not `true` | required | | `level` | the confidence level of every interval | 0.95 | | `pairing` | `common` or `independent` | `common` | | `measures` | the statistics to summarise, such as `tasks.pack.wait_mean`; a name given twice counts once | required | | `variants` | each variant's name and the registry values it sets | `{base: {}}` | | `sweep` | registry paths and the values each takes | none | | `compare` | pairs of variants, `{baseline: ..., variant: ...}` | none | | `checks` | bounds on measures, `{measure, variant, max, min, on}`, with `min` not above `max` | none | | `observed` | `{file: ..., variant: ...}`, values measured in the real system | none | | `limits` | sentences the report lists | none | | `output` | the folder the files are written to | `results/` | | `workers` | how many runs go at once, each in its own process | 1 | A key the experiment does not know is refused with its line, as in a blueprint. In a file, the paths of the model, the observed file and `output` are read from the experiment file's folder. In a Python mapping, they are read from the working directory. ### Run It ```bash desflow experiment experiment.yaml ``` `--output` writes the files to another folder. The command exits with status 1 when a check fails, after writing every file, and with status 2 when the experiment is invalid. ```python EXPERIMENT = { "experiment": "packers", "model": shop, # a blueprint path, a builder factory or a LowLevelModel "until": "1 h", "warmup": "3 min", "replications": 10, "seed": 42, "measures": ["tasks.pack.wait_mean"], "variants": {"two": {}, "three": {"Shop.resources.packers.current_cap": 3}}, # A sweep would run every variant at each rate, an order every 2.86, 2.5 or # 2.22 seconds on average: 6 designs # "sweep": {"Shop.arrival.orders.rate": [0.35, 0.4, 0.45]}, "compare": [{"baseline": "two", "variant": "three"}], "checks": [{"measure": "tasks.pack.wait_mean", "variant": "two", "max": 2}], } try: result = run_experiment(EXPERIMENT) # writes results/packers, then checks except CheckFailed as failed: result = failed.result # every file is written before it is raised print(failed) ``` `run_experiment` takes an experiment file, a mapping or an `ExperimentSpec`, and returns an `ExperimentResult`. With `raise_on_failure=False` a failed check raises nothing, and `result.failed` lists it. `output=` writes the files to another folder. The same call takes `LowLevelModel(model, sim_id="Shop")` as the model. Here `model` is a function that builds the shop from an environment and a sampler, as the [example](#example-an-experiment) shows. The result holds every row the files hold: ```python for row in result.summary: # one row per design and statistic, counts included print(row["design"], row["statistic"], row["mean"], row["half_width"]) for row in result.comparisons: # the variant minus the baseline, seed by seed print(row["measure"], row["difference"], row["half_width"]) print([row["design"] for row in result.failed]) # the failed checks print(result.output / "report.md") ``` ### Variants and Sweeps Each variant sets registry paths before the clock starts, as a live update would. Paths are set in the order the variant lists them, so a variant that lowers `max_cap` below the model's `current_cap` sets `current_cap` first. The experiment stops before anything runs, with an error that names the variant's line, when a variant sets: - a path the model does not have; - a value the registry refuses, or lowers to its limit, such as a capacity above `max_cap`. A sweep runs every variant at every combination of its paths' values. So one variant and one swept path with three values give three designs: a one-factor sensitivity experiment, which changes one input to see how much the answer changes. A path is set by a variant or by the sweep, not both. A design's name is its variant followed by its swept values, such as `three Shop.arrival.orders.rate=0.5` (an order every 2 seconds on average). ### Pairing and Random Streams With `pairing: common`, every design runs with the same seeds. A design's replication 3 and another design's replication 3 then meet the same arrivals and service times, so most of the random variation cancels in their difference ([Comparing Designs](https://jaehyeon.me/desflow/latest/learn/studies/comparing-designs/#compare-two-designs)). With `pairing: independent`, each design's seeds are spawned from a seed of its own, and `compare` is refused. The same seeds pair two runs only where both draw from the same random streams. Each distribution has a stream of its own, named by its registry path without the sim id, such as `service.packing`. The experiment records the streams each run drew from, and each comparison lists the streams both designs used and any that only one used. A stream only one design uses, such as a gift-wrap step only one design has, is not [paired](https://jaehyeon.me/desflow/latest/learn/concepts/output-analysis/#comparing-designs). ______________________________________________________________________ ## How It Works **Before running.** The experiment builds the model once without running it, records its compiled parameters, and refuses an `inputs` path that is not a distribution. It then builds each design the same way, so a bad registry path or value fails before any run. It reads the observed file and refuses a row that does not match its measure. **Runs.** Each design runs its replications as [Replications](https://jaehyeon.me/desflow/latest/user-guide/results/replications/#how-it-works) describes: each run builds the model again, unpaced, with no ingress and no egress, and reads the statistics at its end. The statistics level is the lowest that publishes every measure, and at least `basic`, so the counts are there. A low-level model's parameters are put back after each replication, so the next replication never starts from a variant's value or a live change left by the one before. **Intervals.** Every interval, of a design's mean and of a difference, is the Student t interval of [Replications](https://jaehyeon.me/desflow/latest/user-guide/results/replications/#how-it-works), at the experiment's `level`. ______________________________________________________________________ ## Stability and Limits - **Finite designs only.** Variants and sweeps list their values. Latin hypercube designs, sampling uncertain inputs and searching for the best design are not part of an experiment. - **No event records.** An experiment writes its files and sends nothing to the model's sinks. Run one design with one seed to see its records. - **End of a run.** A run ends at `until`, unless `stop` ends it earlier or `drain` runs it on until the model is empty. A blueprint's own `run.stop` and `run.drain` apply when the experiment does not set them. Entities still in the model at the end are not finished, so a count of finished entities leaves them out. The Counts section of the report ([Read the Report](https://jaehyeon.me/desflow/latest/user-guide/results/experiment-results/#read-the-report)) shows what each design started, finished and left. - **Observed values are outputs.** The observed comparison is a check of the model's output against the real system's for the question asked. It does not fit inputs, and one value inside an interval does not make a model valid for every question. - **One machine.** `workers` runs replications in parallel processes on one machine. There is no distributed or server executor. ______________________________________________________________________ ## Example: An Experiment The `experiment` example is the experiment above. It runs one hour of the shop with two packers and with three, 20 replications of each with the same seeds. It makes one comparison and one check, and places the mean wait observed in the real shop beside the result. Its shop is not the busy hour of the tutorials: an order arrives every 2.5 seconds on average and packing takes 4 seconds on average, so its waits differ from theirs. The example needs no Docker service and ends on its own. The tutorial page [Comparing Designs](https://jaehyeon.me/desflow/latest/learn/studies/comparing-designs/index.md) teaches these features step by step. **Quick Start** `desflow examples get` downloads the example at the release you install, into a folder of its own. Pick uv or pip: ```bash # 1. Install uv tool install desflow # 2. Download the example desflow examples get experiment --api yaml cd experiment/yaml # 3. Find the bottleneck, with no run desflow explain experiment_shop.yaml # 4. Run it desflow experiment experiment.yaml ``` ```bash # 1. Install pip install desflow # 2. Download the example desflow examples get experiment --api yaml cd experiment/yaml # 3. Find the bottleneck, with no run desflow explain experiment_shop.yaml # 4. Run it desflow experiment experiment.yaml ``` The model is `experiment_shop.yaml`, beside the experiment file: ```yaml # The model of the experiment in experiment.yaml: one hour of the shop. # # The YAML version of the shop function in experiment_example.py, which --api builder # downloads. Two packers, orders every 2.5 seconds on average and a packing time of 4 # seconds on average. It has no sinks and no statistics level: the experiment runs it # without sinks and keeps the statistics its measures need. # # Needs no containers. # Run the experiment with: desflow experiment experiment.yaml simulation: sim_id: Shop factor: 0 # The experiment gives each run its own seed; 42 is for a run on its own. random_seed: 42 resources: packers: {current_cap: 2, max_cap: 4} services: # A mean of 4 seconds (shape times scale). packing: {dist: gamma, shape: 4, scale: 1} arrivals: # An order every 2.5 s on average (rate 0.4) orders: {dist: exponential, rate: 0.4, spawn: pack} tasks: pack: service: packing resource: packers payload: {event_type: order_packed} ``` **Quick Start** `desflow examples get` downloads the example at the release you install, into a folder of its own. Pick uv or pip: ```bash # 1. Install uv tool install desflow # 2. Download the example desflow examples get experiment --api builder cd experiment/builder # 3. Run it uv run --no-project --with desflow experiment_example.py ``` ```bash # 1. Install pip install desflow # 2. Download the example desflow examples get experiment --api builder cd experiment/builder # 3. Run it python experiment_example.py ``` ```python # Both designs run with the same 20 seeds, so they are compared seed by seed "pairing": "common", "measures": ["tasks.pack.wait_mean", "resources.packers.utilization_avg"], "variants": {"two": {}, "three": {"Shop.resources.packers.current_cap": 3}}, "compare": [{"baseline": "two", "variant": "three"}], # The upper end of the interval must be under 2 seconds "checks": [{"measure": "tasks.pack.wait_mean", "variant": "three", "max": 2}], # The mean wait measured in the real shop, which has two packers "observed": {"file": str(HERE.parent / "observed_waits.csv"), "variant": "two"}, ``` The whole file is [`examples/builder/experiment_example.py`](https://github.com/jaehyeon-kim/desflow/blob/v1.3.0/examples/builder/experiment_example.py). **Quick Start** `desflow examples get` downloads the example at the release you install, into a folder of its own. Pick uv or pip: ```bash # 1. Install uv tool install desflow # 2. Download the example desflow examples get experiment --api low-level cd experiment/low-level # 3. Run it uv run --no-project --with desflow experiment_example.py ``` ```bash # 1. Install pip install desflow # 2. Download the example desflow examples get experiment --api low-level cd experiment/low-level # 3. Run it python experiment_example.py ``` ```python # Both designs run with the same 20 seeds, so they are compared seed by seed "pairing": "common", "measures": ["tasks.pack.wait_mean", "resources.packers.utilization_avg"], "variants": {"two": {}, "three": {"Shop.resources.packers.current_cap": 3}}, "compare": [{"baseline": "two", "variant": "three"}], # The upper end of the interval must be under 2 seconds "checks": [{"measure": "tasks.pack.wait_mean", "variant": "three", "max": 2}], # The mean wait measured in the real shop, which has two packers "observed": {"file": str(HERE.parent / "observed_waits.csv"), "variant": "two"}, ``` The whole file is [`examples/low-level/experiment_example.py`](https://github.com/jaehyeon-kim/desflow/blob/v1.3.0/examples/low-level/experiment_example.py). # Experiment Results This page shows what an [experiment](https://jaehyeon.me/desflow/latest/user-guide/results/experiments/index.md) compares, checks and writes: the comparison of designs, the checks, the observed values, the files and the report. The tutorial page [Parameter Sweeps](https://jaehyeon.me/desflow/latest/learn/studies/parameter-sweeps/index.md) teaches these features step by step. ______________________________________________________________________ ## What It Is An experiment gives the numbers that answer a question about the shop: which design keeps the wait under a target, how much one design differs from another, and whether the model agrees with values measured in the real shop. It writes them to files and a report. ______________________________________________________________________ ## How to Use It ### Compare Designs For each measure and each sweep point, a `compare` pair gives three things: the variant's value minus the baseline's in each [replication](https://jaehyeon.me/desflow/latest/learn/concepts/output-analysis/#replications), the mean of those differences, and the mean's [Student t](https://jaehyeon.me/desflow/latest/learn/concepts/output-analysis/#interval-and-half-width) half-width. An interval that does not contain 0 says the designs differ at that confidence level. ### Check Results A check bounds one measure of one variant, or of every variant when `variant` is left out: - **`max` and `min`:** the bound, or both for a range. - **`on: interval`**, the default, compares the far end of the interval with the bound: the upper end with `max` and the lower end with `min`. A mean below the bound only by chance does not pass. - **`on: mean`** compares the mean, for a quick look, not a decision. A check whose measure is not in `measures` is refused. The experiment writes every file before it reports a failed check, so the report shows what failed. ### Compare With Observed Values `observed` names a CSV of values measured in the real system, with the columns `measure`, `value`, `unit`, `population` and `horizon`. Each row is placed beside the simulated interval of `variant` (the first variant when it is not given), and the report says whether the value lies inside it. That interval is for a mean, so one observed period can lie outside it while the model is right, as [Checking and Validating](https://jaehyeon.me/desflow/latest/learn/concepts/checking-and-validating/#compare-with-the-real-shop) explains. A value means something only beside a simulated value of the same kind, so the experiment refuses a row whose unit, population or horizon differs from the measure's: | Statistic | Unit | Population | | --------------------------------------------------------- | ------------------------------------ | ------------------------------- | | `wait_*` of a task, recorded when an instance starts work | `s` | `started instances` | | `service_*` of a task, recorded when an instance finishes | `s` | `finished instances` | | `utilization` and `utilization_avg` | `percent` | `end of run` and `time average` | | `downtime` of a resource | `s` | `sum over the horizon` | | other `*_avg`, such as `queue_length_avg` | `count`, or `amount` for a container | `time average` | | task and flow counts, such as `finished` and `started` | `count` | `count over the horizon` | | `in_system` of a flow and `in_progress` of a task | `count` | `end of run` | | other readings, such as `queue_length` | `count`, or `amount` for a container | `end of run` | The horizon is `until` minus the [warm-up](https://jaehyeon.me/desflow/latest/learn/concepts/output-analysis/#one-run-starts-empty), in seconds or a duration such as `57 min`. The horizon describes a run that ends at `until`, so with a `stop` or a `drain`, the observed values must cover the same entities as the simulated ones. The observed comparison checks the model's output against the real system's. It does not fit an input distribution, which [Input Fitting](https://jaehyeon.me/desflow/latest/user-guide/model-parts/input-fitting/index.md) covers. ### Files An experiment writes six files to its output folder: | File | Holds | | ----------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | | `experiment.json` | the settings, the question, assumptions, inputs and limits; the model's source and its SHA-256, its sim id and its compiled parameters; desflow, SimPy, NumPy and Python versions; each design's registry values, seeds and the streams each run drew from; the counts' names; the observed comparison | | `results.csv` | one row per design, replication and statistic: `design`, `variant`, a column per swept path, `replication`, `seed`, `statistic`, `kind` (`measure` or `count`), `unit`, `population` and `value` | | `summary.csv` | one row per design and statistic: `unit`, `population`, `n`, `mean`, `half_width`, `low`, `high` and `level` | | `comparisons.csv` | one row per compared pair, sweep point and measure: both means, `difference`, `half_width`, `low`, `high`, and the streams in `streams_both`, `streams_baseline_only` and `streams_variant_only` | | `checks.csv` | one row per check, design and bound: `on`, `bound`, `limit`, the checked `value` and `passed` | | `report.md` | the report, built from the five files above | ### Read the Report `report.md` has the sections below, and a section with nothing to report says so: - Question, Model and Assumptions. - Inputs and Provenance: every distribution of the model with its parameters, and its provenance from `inputs` or "not stated". - Run Settings. - Counts: the mean of each count the statistics publish, such as finished orders, for each design. - Results, with the population each measure is taken over. - Comparisons, Checks, Observed Comparison and Limits. - Missing Inputs: what the experiment does not state, such as an input without a provenance. The report names it rather than filling it in. The middle of the example's report follows. It is for the example's own shop, not the busy hour of the tutorials: ```text ## Results Each measure's mean over the replications, with its 95% confidence interval. | Design | Measure | Population | Mean | Half-width | Interval | n | |---|---|---|---|---|---|---| | two | `tasks.pack.wait_mean` | started instances | 4.524 | 0.5731 | 3.951 to 5.097 | 20 | | two | `resources.packers.utilization_avg` | time average | 80.14 | 1.104 | 79.04 to 81.25 | 20 | | three | `tasks.pack.wait_mean` | started instances | 0.534 | 0.0476 | 0.4864 to 0.5816 | 20 | | three | `resources.packers.utilization_avg` | time average | 53.46 | 0.7236 | 52.73 to 54.18 | 20 | ## Comparisons Each difference is the variant's value minus the baseline's, seed by seed, with the confidence interval of the mean difference. | Baseline | Variant | Measure | Difference | Half-width | Interval | Random streams | |---|---|---|---|---|---|---| | two | three | `tasks.pack.wait_mean` | -3.99 | 0.5316 | -4.521 to -3.458 | 2 shared | | two | three | `resources.packers.utilization_avg` | -26.69 | 0.39 | -27.08 to -26.3 | 2 shared | ## Checks Checks passed: 1 of 1. | Design | Measure | Checked | Bound | Value | Result | |---|---|---|---|---|---| | three | `tasks.pack.wait_mean` | the upper end | max 2 | 0.5816 | passed | ## Observed Comparison | Design | Measure | Observed | Unit | Simulated interval | Inside | |---|---|---|---|---|---| | two | `tasks.pack.wait_mean` | 4.6 | s | 3.951 to 5.097 | yes | ``` `desflow report results/packers` builds the report again from the other five files, such as after editing `experiment.json` by hand. ______________________________________________________________________ ## How It Works Each replication of each design gives one row per statistic in `results.csv`, and `summary.csv` holds each design's mean and interval over its replications. A comparison pairs the replications of two designs that ran with the same seed, so the two runs of a pair draw the same times wherever they share a random stream. `comparisons.csv` holds the mean difference and its interval, and lists the streams both designs drew from and those only one did. The checks and the observed comparison read these intervals. `report.md` is built from the other five files. The experiment writes every file before it reports a failed check, so the report shows what failed. # Live Runs and Connectors A live run changes its parameters while it runs and sends its records out as they happen. Three parts do this: the registry of live parameters, the ingress connectors that change them, and the egress connectors that write the records. The diagram on [How desflow Works](https://jaehyeon.me/desflow/latest/user-guide/how-desflow-works/index.md) shows how one run moves through them. ______________________________________________________________________ ## What It Is - **Live parameters** sit in the registry under named paths, such as `Shop.service.packing.mean`. An arrival rate, a number of packers or a stock level can change while the run goes on. - **Ingress** connectors bring those changes in from outside: from a file you edit, Kafka, Redis, PostgreSQL or a local schedule. - **Egress** connectors, or sinks, write the records the run publishes: to the console, Kafka, Redis, PostgreSQL, Parquet or JSON Lines files, or Iceberg tables, or keep them in memory as tables for the Python program that runs the model. ______________________________________________________________________ ## Pages in This Section - [Live Parameters](https://jaehyeon.me/desflow/latest/user-guide/live-runs-and-connectors/live-parameters/index.md): how to name a parameter, the ways to change it, how to record what a change was for, and what happens to a value once it arrives. - [Ingress](https://jaehyeon.me/desflow/latest/user-guide/live-runs-and-connectors/ingress/index.md): each source connector, the message it reads, how to send one, and when the change lands. - [Egress](https://jaehyeon.me/desflow/latest/user-guide/live-runs-and-connectors/egress/index.md): each sink, how to choose which records each one gets, and how records travel from a task to a sink. ______________________________________________________________________ ## How to Use It - A value that should change during a run is a registry path, such as a service's mean or a resource's capacity, or a `variables` entry for any other value. - An `ingress` entry in YAML, or `add_ingress` in the builder, adds a source of changes. - An `egress` entry, or `add_egress`, adds a sink. ______________________________________________________________________ ## How It Works A run uses three threads. The ingress thread runs the sources, which put `(path, value)` pairs on a queue, and the ingress monitor applies them to the registry every 0.1 simulation seconds. The SimPy thread runs the model, which follows each change: a distribution uses the new parameters from its next draw, and a resource changes its capacity. Each record the model publishes goes into a buffer for each sink, and the egress thread writes full batches to the sinks. [How desflow Works](https://jaehyeon.me/desflow/latest/user-guide/how-desflow-works/#threads-and-queues) shows the threads and the queues between them. # Live Parameters: `SimulationRegistry` Every parameter of a run can change while the run goes on: an arrival rate, a number of packers, a stock level. This page shows how to name a parameter, the ways to change it, how to record what a change was for, and what happens to a value once it arrives. ______________________________________________________________________ ## What It Is Every run has one `SimulationRegistry`, at `env.registry`. It maps dot-notation paths, such as `Shop.resources.packers.current_cap`, to the values the simulation reads. A scenario, an ingress connector or a process changes a parameter by updating its path, and the simulation follows the change without restarting. Changing a parameter takes three steps: The tutorial page [Live Changes](https://jaehyeon.me/desflow/latest/learn/running-live/live-changes/index.md) teaches these features step by step. ______________________________________________________________________ ## How to Use It ### Find the Path A path is the `sim_id`, the kind of parameter, its name and the field: | Declared with | Paths | | ------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | an arrival or a service | `.arrival..` and `.service..`, one per scalar parameter of its family: `.rate` for an exponential, `.mean` and `.std` for a normal, `.low`, `.mode` and `.high` for a triangular, and so on; an `empirical` has none | | a resource | `.resources..current_cap`, `.max_cap` and `.queue_limit` (`None` while the resource has no limit) | | a container | `.containers..current_cap`, `.max_cap` and `.level` | | a store | `.stores..current_cap` and `.max_cap` | | a breakdown of a resource | `.breakdown..time_to_failure.` and `.breakdown..repair.`, one per scalar parameter of each distribution's family, as for a service | | a variable | `.variables.` | [Arrivals and Services](https://jaehyeon.me/desflow/latest/user-guide/model-parts/arrivals-and-services/index.md) lists each family's parameters. An update to a path that does not exist, including a parameter the family does not take, is logged as a warning and ignored, so a misspelt path changes nothing. A blueprint's paths follow from the names it declares, as the table above shows. To list them with their starting values, load it with `SimulationContext.from_yaml` and call `registry_paths()` on the context it returns, as the Builder tab does. `compile_parameters()` returns the `SimParameter` a `SimulationContext` will register, which shows the names to use. A resource appears in it as a `ResourceConfig` with `current_cap`, `max_cap` and `queue_limit`: ```python print(app.compile_parameters()) ``` `registry_paths()` returns the paths a run will register with their starting values, in the order a run registers them. It runs no model code and starts no connector. A capacity with no limit has the value `math.inf`, which JSON cannot hold, so convert it before you write JSON: ```python print(app.registry_paths()) ``` You register the parameters yourself, and read a value with `registry.get(path).value`: ```python params = SimParameter( sim_id="Shop", # An order every 2 s on average (rate 0.5) arrival={"orders": DistributionConfig(dist="exponential", rate=0.5)}, service={"packing": DistributionConfig(dist="normal", mean=3.0, std=0.5)}, resources={"packers": CapacityConfig(current_cap=2, max_cap=5)}, containers={"stock": ContainerConfig(current_cap=100, max_cap=100, level=40)}, variables={"conveyor_speed": 1.5}, ) env = DynamicRealtimeEnvironment(factor=0.0) env.registry.register_sim_parameter(params) # Registered paths include: # Shop.arrival.orders.rate # Shop.service.packing.mean, Shop.service.packing.std # Shop.resources.packers.current_cap, .max_cap and .queue_limit (None: no limit) # Shop.containers.stock.current_cap, .max_cap and .level # Shop.variables.conveyor_speed print(env.registry.get("Shop.resources.packers.current_cap").value) # 2 ``` ### Send a Value Each source of a change suits a different job and lands at a different moment: | Source | Use it for | Lands at | | ----------------------------------------------------------------------------- | ------------------------------------------------------- | --------------------------------- | | a scenario: YAML `scenario`, builder `add_scenario`, low-level `run_scenario` | an experiment that must repeat exactly | the exact simulation time given | | `LocalIngress` | a local run with changes after set wall-clock delays | a wall-clock delay from the start | | `FileIngress` | a local run steered by editing a file | within one poll of the save | | `KafkaIngress`, `RedisIngress`, `PostgresIngress` | an operator or another program steering a running model | when the message arrives | | a process calling `env.registry.update` or `env.registry.change` | a change that depends on the state of the simulation | when the process makes it | [Ingress](https://jaehyeon.me/desflow/latest/user-guide/live-runs-and-connectors/ingress/index.md) gives the message each connector reads. A process changes a value directly: A blueprint's process function, listed under `processes`, calls the same `registry.update` on `context.env.registry`, as [Processes](https://jaehyeon.me/desflow/latest/user-guide/tasks-and-processes/processes/#a-process) shows. A builder process calls the same `registry.update` on `context.env.registry`, as [Processes](https://jaehyeon.me/desflow/latest/user-guide/tasks-and-processes/processes/#a-process) shows. ```python env.registry.update("Shop.resources.packers.current_cap", 3) # applied env.registry.update("Shop.resources.packers.current_cap", 9) # stored as 5, the max_cap env.registry.update("Shop.service.packing.std", -1.0) # refused, the old 0.5 stays env.registry.update("Shop.resources.lath.current_cap", 3) # no such path: ignored env.registry.update("Shop.service.packing.rate", 2.0) # normal has no rate: ignored env.registry.update("Shop.containers.stock.level", 150) # stored as 100, the capacity ``` ### Know What a Path Accepts Each path checks a value by its own rule before it stores it: - A resource's or a store's `max_cap`, and a resource's `queue_limit`, are whole numbers of 0 or more, and a `current_cap` is a whole number, stored clamped to 0 to `max_cap` with a warning. Text is accepted only if the whole text is such a number, so `"6"` is 6 and `"abc"` is refused. A store capacity with a fraction, such as 2.5, is refused and not rounded down. A `queue_limit` of `None` means no limit. - A container's `level` is a finite number. A level above the capacity is stored as the capacity. - A path that holds true or false takes `true`, `false` or that text. Any other text is refused. `true` written over a path that holds a number is stored as 1. A resource's limit changes through its path. `DynamicResource.queue_limit` is a read-only property that shows the value now, so assigning to it raises `AttributeError`. An `on:` entry with a `path` needs a `value`, and so does a scenario step with a `path`. A value that the path's rule refuses, such as `many` for a capacity, is refused when the blueprint loads, with the line of the entry. A path that is not in the registry is logged as a warning with the entry's line. `registry.change`, which a process calls, raises `ParamRejected` for a value that breaks these rules. The next section shows it. ```python # Each path checks a value by its own rule; `change` raises where `update` logs env.registry.update("Shop.resources.packers.max_cap", "6") # text of a whole number: 6 env.registry.update( "Shop.resources.packers.queue_limit", 4 ) # a limit: whole, 0 or more env.registry.update("Shop.resources.packers.queue_limit", None) # no limit again env.registry.update("Shop.resources.packers.current_cap", 2.5) # refused: not whole env.registry.update("Shop.containers.stock.level", float("nan")) # refused: not finite ``` ### Know Whether a Change Was Refused `update` logs a refused value and goes on, so its caller cannot tell whether the value landed. `registry.change(path, value)` runs the same checks and returns a `ParamChange` for an accepted value. For a refused value it raises `ParamRejected`, a `ValueError` whose `path`, `value` and `reason` say what the registry refused. A value that the registry converts or clamps is accepted, and `new` shows the value it stored. A `ParamChange` has these fields: - `path`: the path that changed. - `old`: the value before the change. - `new`: the value stored. - `requested`: the value asked for. - `at`: the simulation time of the change. - `source`, `actor` and `reason`: who made the change and why, which `change` takes as keywords. Its `changed` property is True when `new` differs from `old`. A blueprint's process function, listed under `processes`, calls the same `registry.change` on `context.env.registry`, as [Processes](https://jaehyeon.me/desflow/latest/user-guide/tasks-and-processes/processes/#a-process) shows for `update`. A builder process calls the same `registry.change` on `context.env.registry`, as [Processes](https://jaehyeon.me/desflow/latest/user-guide/tasks-and-processes/processes/#a-process) shows for `update`. ```python change = env.registry.change( "Shop.resources.packers.current_cap", 4, source="user", actor="alice", reason="two packers are on leave", ) print(change.old, change.new, change.changed) # 5 4 True try: env.registry.change("Shop.service.packing.std", -1.0) except ParamRejected as exc: # invalid value for 'Shop.service.packing.std': normal std must be 0 or more ... print(exc.reason) ``` ### Follow Every Change `on_change` is a list of callbacks. The registry calls each one with the `ParamChange` of every accepted change, in the order they were added, after it has stored the value. A change that leaves the value as it was is reported too, with `changed` False. A lower `max_cap` that lowers the `current_cap` beside it gives two changes, the `current_cap` first. A callback that raises is logged, and the other callbacks still run. The `source` and `actor` of a change say where it came from: - An ingress connector's change has the source `"ingress"` and the connector's class name as actor, such as `LocalIngress`. - A scenario step has the source `"scenario"`. - The overrides of `start()` have the `source`, `actor` and `reason` that `start()` takes. - A change that a process or an `on:` action makes has no source unless the process passes one. The context that `SimulationContext.from_yaml` returns takes the callbacks on `context.on_change`. `app.on_change` takes the same callbacks for every run `start()` builds, as [Builder API](https://jaehyeon.me/desflow/latest/user-guide/writing-a-model/builder-api/#run-it) says. ```python changes: list = [] env.registry.on_change.append(changes.append) # called with every accepted change env.registry.update("Shop.resources.packers.current_cap", 3, source="user") # Shop.resources.packers.current_cap 4 3 print(changes[0].path, changes[0].old, changes[0].new) ``` ### Script an Experiment A blueprint's `scenario` lists changes, each with the simulation time it applies at. Here a second packer starts at 30 seconds. From one minute, orders arrive twice as fast: the average gap between orders falls from 5 seconds to 2.5 seconds (`rate` from 0.2 to 0.4). The extra packer leaves at two minutes: ```yaml # The first blueprint with a scripted experiment: a second packer starts at 30 s. # From 1 min, orders arrive twice as fast: the average gap falls from 5 s to 2.5 s # (rate 0.2 to 0.4). The extra packer leaves at 2 min. Every change lands at # exactly that simulation time, on every run. simulation: {sim_id: Shop, factor: 0, random_seed: 1} egress: - {type: Console} resources: packers: {current_cap: 1, max_cap: 3} services: packing: {dist: normal, mean: 4 s, std: 1 s} arrivals: # An order every 5 s on average (rate 0.2), 2.5 s from 1 min orders: {dist: exponential, rate: 0.2, spawn: pack_order} tasks: pack_order: service: packing resource: packers payload: {event_type: order_packed} # The packers' capacity and queue every 10 seconds, to see each change land stats: minimal scenario: - {at: 30, path: Shop.resources.packers.current_cap, value: 2} - {at: 1 min, path: Shop.arrival.orders.rate, value: 0.4} - {at: 2 min, path: Shop.resources.packers.current_cap, value: 1} run: {until: 3 min} ``` `add_scenario` takes the same steps as a list of mappings, as [Vary Arrivals by Time](https://jaehyeon.me/desflow/latest/how-to/modelling/time-varying-arrivals/#steps) shows. `run_scenario` takes the same steps as a list of mappings, and runs as a SimPy process, as [Vary Arrivals by Time](https://jaehyeon.me/desflow/latest/how-to/modelling/time-varying-arrivals/#steps) shows. The builder and the low-level API take the same steps, as a list of mappings. [Vary Arrivals by Time](https://jaehyeon.me/desflow/latest/how-to/modelling/time-varying-arrivals/#steps) shows one schedule in each API. A scenario is not a connector. It is a SimPy process that waits on the simulation clock, so each step lands at exactly its `at`, on every run and at any `factor`, including 0. Its steps follow these rules, and [Vary Arrivals by Time](https://jaehyeon.me/desflow/latest/how-to/modelling/time-varying-arrivals/#boundaries) shows each case: - A step applies before every other event at its time, so an arrival gap drawn at that moment uses the new value. - Steps at the same time apply in the order written. - A step at or after `until` never applies. - A scenario's paths and values are checked before the run, as [Stability and Limits](#stability-and-limits) says. A step also turns an arrival on or off, as a task's `activate` and `deactivate` do: `activate` or `deactivate` takes an arrival name, or a list of them, in place of `path` and `value`. Each must be an arrival with a `spawn`, and a step that has both a `path` and a switch is refused when the blueprint loads. A `record` on such a step publishes a label with no path, old or new value, so name the arrival in the `record`. Here the phone line closes at one minute and opens again at two, while web orders keep arriving: ```yaml # A scenario step that turns an arrival off and on: the phone line closes at 1 min # and opens again at 2 min, while web orders keep arriving. # # Run it with: desflow run docs/snippets/yaml/scenario_switch.yaml simulation: {sim_id: Shop, factor: 0, random_seed: 3} egress: - {type: Console} arrivals: web_orders: {dist: exponential, mean: 20 s, spawn: place_order} phone_orders: {dist: exponential, mean: 20 s, spawn: place_order} tasks: place_order: payload: {event_type: order_placed} scenario: - {at: 1 min, deactivate: phone_orders} - {at: 2 min, activate: phone_orders} run: {until: 3 min} ``` `add_step(60, deactivate="phone_orders")` and `add_step(120, activate="phone_orders")` add the same steps, and `add_scenario` takes `activate` and `deactivate` in its mappings. A low-level model has no arrival sources to turn on or off: its arrivals are SimPy processes of its own, which stop themselves. `run_scenario` takes `switch`, a function of the names and `True` or `False`, which the builder passes. No phone order arrives between 60 and 120 seconds: ```text [EVT] {'sim_ts': 18.264006173899638, 'timestamp': '...', 'key': 'phone_orders-1', 'task': 'place_order', 'instance': 1, 'value': {'event_type': 'order_placed'}} [EVT] {'sim_ts': 19.85578493577281, 'timestamp': '...', 'key': 'phone_orders-2', 'task': 'place_order', 'instance': 2, 'value': {'event_type': 'order_placed'}} [EVT] {'sim_ts': 139.70428939404243, 'timestamp': '...', 'key': 'phone_orders-3', 'task': 'place_order', 'instance': 12, 'value': {'event_type': 'order_placed'}} [EVT] {'sim_ts': 160.45539863386455, 'timestamp': '...', 'key': 'phone_orders-4', 'task': 'place_order', 'instance': 13, 'value': {'event_type': 'order_placed'}} [EVT] {'sim_ts': 162.24733156198488, 'timestamp': '...', 'key': 'phone_orders-5', 'task': 'place_order', 'instance': 15, 'value': {'event_type': 'order_placed'}} [EVT] {'sim_ts': 175.39337133463846, 'timestamp': '...', 'key': 'phone_orders-6', 'task': 'place_order', 'instance': 16, 'value': {'event_type': 'order_placed'}} ``` `LocalIngress` waits on the wall clock instead, and an unknown path is only logged when it is due. A scenario and an ingress connector can run together, so a scripted baseline can run while an operator changes values over Kafka. When both change the same path, the later write wins. ### Record What a Change Was For A detector or an agent that watches the data is scored against what really happened. A scenario step with a `record` publishes a **ground-truth record** of it: `stream_type: "label"`, with the step's `path`, the value before (`old`) and after (`new`), and the step's `record` mapping as `label`. A step can have a `record` and no `path`, for something that happened outside the model, and then `path`, `old` and `new` are null. ```yaml scenario: # Changes the rate and publishes a ground-truth record of the change - at: 30 path: Shop.arrival.orders.rate value: 1.5 record: {fault: order_surge, cause: flash sale} # A record with no change, such as a fault planted outside the model - at: 45 record: {fault: label_printer_offline} ``` `add_scenario` takes the same steps, `record` included. A process publishes a label itself with `context.env.publish_label(label, path=..., old=..., new=...)`. `run_scenario` takes the same steps, `record` included. A process publishes a label itself with `env.publish_label(label, path=..., old=..., new=...)`. Labels go only to sinks with `when: labels`, and those sinks receive nothing else. The labels therefore never reach the pipeline under test, and a scorer reads them apart from the data. [Choose What Each Sink Gets](https://jaehyeon.me/desflow/latest/user-guide/live-runs-and-connectors/egress/#choose-what-each-sink-gets) shows the sinks of this blueprint. The labels sink writes one file per batch under `labels/`, such as `labels/labels_1a2b3c4d.jsonl`, with one line per label: ```text {"stream_type":"label","sim_ts":30.0,"timestamp":"...","path":"Shop.arrival.orders.rate","old":0.5,"new":1.5,"label":{"fault":"order_surge","cause":"flash sale"}} {"stream_type":"label","sim_ts":45.0,"timestamp":"...","path":null,"old":null,"new":null,"label":{"fault":"label_printer_offline"}} ``` In Python, `env.publish_label(label, path=..., old=..., new=...)` publishes one, and `add_egress(sink, when="labels")` or `setup_egress(..., labels=[...])` makes a labels sink, as the [measuring example](https://jaehyeon.me/desflow/latest/user-guide/results/statistics/#example-measuring-a-run) shows. ______________________________________________________________________ ## How It Works **Registration.** `run()`, or `register_sim_parameter` in the low-level API, flattens the `SimParameter` into the registry. The registry holds one `DynamicValue` per path, with the value and a change signal. Beside them, it keeps the configuration objects that the paths belong to, such as each `DistributionConfig`. **An update.** `registry.update(path, value)` and `registry.change(path, value)` apply one change by the same checks. `update` logs a refused value, and `change` raises `ParamRejected`. The checks run in order, and an accepted value reaches the parts that read it: - A path that does not exist is logged as a warning, and the update is ignored. - A value of another type is converted to the type the path holds, so the string `"5"` sent to an integer path becomes 5. Python's conversion is used, so 2.5 sent to an integer path becomes 2. A value that cannot be converted is logged as an error and ignored. - A distribution parameter is checked on a copy of its configuration, by the rules used at build. One out of range is logged as an error, and the old value stays. - A `current_cap` outside 0 to `max_cap`, or a container `level` outside 0 to `current_cap`, is stored clamped to that range, with a warning. A lower `max_cap` clamps the stored `current_cap` the same way. - A value equal to the current one gives no change signal. - Otherwise the value is stored, and the attribute of the configuration object is set too, found by splitting the path at its last dot: `Shop.service.packing.mean` sets `mean` on the object at `Shop.service.packing`. The `Sampler` reads that object at every draw, so it sees the new value. - Then each `on_change` callback receives the change, in the order they were added; a callback that raises is logged and the others still run. **Change Signal.** Each value has a SimPy `Store` with one slot as its signal. An update puts a token in it if it is empty, and `wait_for_change()` waits for that token. The slot holds one token, so several changes before a waiter wakes give one signal, and only one waiting process takes it. Resources, stores and containers already wait on their own paths, and a token that your process takes does not reach them. Wait only on paths that nothing else waits on, such as variables: Waiting on a change needs process code: a process function listed under `processes` waits on `context.env.registry` in the same way, as [Processes](https://jaehyeon.me/desflow/latest/user-guide/tasks-and-processes/processes/#a-process) shows for a process. A builder process waits on `context.env.registry` in the same way, as [Processes](https://jaehyeon.me/desflow/latest/user-guide/tasks-and-processes/processes/#a-process) shows for a process. ```python def watch_speed(env): """Logs the conveyor speed every time it changes.""" speed = env.registry.get("Shop.variables.conveyor_speed") while True: yield speed.wait_for_change() print(f"t={env.now}: conveyor speed is now {speed.value}") env.process(watch_speed(env)) ``` A container's level also changes with every put and get. The registry keeps that level, so a reader sees it, but does not signal the container again. ______________________________________________________________________ ## Under Live Changes What follows a change: - **Distributions.** The next draw uses the new value. The arrival already being waited for keeps its gap, and a task that has drawn its service time keeps it. - **Resources, stores and containers.** The capacity follows at once, and a container's level follows its path, as [Resources](https://jaehyeon.me/desflow/latest/user-guide/resources/units-and-queues/#under-live-changes) and [Stores and Containers](https://jaehyeon.me/desflow/latest/user-guide/model-parts/stores-and-containers/#under-live-changes) describe. - **Variables.** The new value is stored, and a process reads it with `env.registry.get(path).value`. A change is easiest to see in the telemetry. With `stats: minimal`, the scenario above shows the second packer land: ```text [TEL] {'sim_ts': 20.0, 'timestamp': '...', 'path_id': 'Shop.stats.resources.packers.capacity', 'value': 1} [TEL] {'sim_ts': 30.0, 'timestamp': '...', 'path_id': 'Shop.stats.resources.packers.capacity', 'value': 1} [TEL] {'sim_ts': 40.0, 'timestamp': '...', 'path_id': 'Shop.stats.resources.packers.capacity', 'value': 2} ``` The reading at 30 seconds still shows 1. The resource applies a change within the same simulation instant, but after the step that made it. The reading was taken before that. The builder publishes the same readings with `with_stats`: `stats: minimal` in the blueprint above publishes these readings every 10 seconds. ```python # The packers' capacity, in use, queue and utilization every 2 seconds app.with_stats("minimal", interval=2.0) ``` `env.setup_stats("Shop", "minimal", interval=2.0)` publishes the same readings, as [Statistics](https://jaehyeon.me/desflow/latest/user-guide/results/statistics/index.md) shows. ______________________________________________________________________ ## Stability and Limits - **An unknown path is a warning, not an error,** for an ingress message or a process that calls `update`; `change` raises `ParamRejected`. The paths of a scenario and of every `on:` action, and a scenario's values, are checked when the model loads. - **A scenario's values are checked before the run.** Every path and value of a blueprint's scenario is checked against the model's registry when the file loads, so a misspelt path, a path on a family member the family can never have (`desk[7]` of a family with `members: 2` that no task picks by `key`), or a refused value stops the load with its line. A member that a task can make at its first use is accepted, and a step on it before it is made ends the run with `KeyError`. `start()` checks them again with its overrides, and that is where a builder model's scenario is checked. A run still stops with `ParamRejected` at a step's time when an ingress message, an `on:` action or a process has changed a related value before the step, because the check cannot know those values. A low-level `run_scenario` checks nothing in advance, so it raises `ParamRejected` whenever it reaches a refused value. - **A family is fixed.** There is no path that turns a `normal` into an `exponential`. That is a new model. - **Several changes, one signal.** A process waiting on a path wakes once for several changes made before it runs, and reads the latest value. - **Ingress lands on the wall clock.** A message's change lands at whatever simulation time the run has reached when it arrives. A change that must happen at an exact simulation time needs a scenario step. # Ingress An ingress connector brings parameter changes into a running simulation from outside: from a file you edit, Kafka, Redis, PostgreSQL or a local schedule. This page shows each connector, the message it reads, how to send one, and when the change lands. ______________________________________________________________________ ## What It Is An ingress connector listens to a source while the run goes on. Every message it reads is one change: a registry `path` and its new `value`, the same two names a scenario step uses. The change reaches the registry, and the simulation follows it, as [Live Parameters](https://jaehyeon.me/desflow/latest/user-guide/live-runs-and-connectors/live-parameters/index.md) describes. Five ingress connectors bring changes in. The eight connectors described on [Egress](https://jaehyeon.me/desflow/latest/user-guide/live-runs-and-connectors/egress/index.md) write records out or keep them in memory: The tutorial page [Live Changes](https://jaehyeon.me/desflow/latest/learn/running-live/live-changes/index.md) teaches these features step by step. ______________________________________________________________________ ## How to Use It Each connector is attached with `add_ingress` in the builder, passed to `env.setup_ingress` in the low-level API, or listed under `ingress` in a blueprint with its `type` and `config`. In a blueprint, `type` is one of the short names below, or a `!python` class from another package. `config` holds the constructor's arguments. A connector's module is imported only when a blueprint names it. A missing package stops the load with its line and the `pip install` command. [YAML Keys](https://jaehyeon.me/desflow/latest/reference/yaml-keys/#ingress) lists the keys of an ingress entry. | Connector | `type` | Source | Message | Extra | | ----------------- | ---------- | ---------------------- | ----------------------------------------------------------------- | ---------- | | `LocalIngress` | `Local` | a schedule in the code | `(delay in wall-clock seconds, path, value)` | none | | `FileIngress` | `File` | a YAML file you edit | `path: value` lines | none | | `KafkaIngress` | `Kafka` | a topic | a JSON object `{"path": ..., "value": ...}` | `kafka` | | `RedisIngress` | `Redis` | a Pub/Sub channel | the same JSON object | `redis` | | `PostgresIngress` | `Postgres` | a table, polled | a row with the columns `path` and `value`, the value as JSON text | `postgres` | ### Local Schedule `LocalIngress` applies changes after set delays in wall-clock seconds from the start of the run. It suits a local run. For a change at an exact simulation time, use a scenario step. ```yaml # 10 wall-clock seconds after the start, set the packers capacity to 3 - type: Local config: {schedule: [[10.0, Shop.resources.packers.current_cap, 3]]} ``` ```python # 10 wall-clock seconds after the start, set the packers capacity to 3 app.add_ingress( LocalIngress(schedule=[(10.0, "Shop.resources.packers.current_cap", 3)]) ) ``` The low-level API passes the same `LocalIngress` to `env.setup_ingress`, in its list of connectors, as [Low-level API](https://jaehyeon.me/desflow/latest/user-guide/writing-a-model/low-level-api/#attach-the-connectors) shows. ### File `FileIngress` watches a local YAML file of `path: value` lines and applies a line when you edit it. It needs no service and no extra, so it is the quickest way to change a parameter while a local run goes. It checks the file's modification time every `poll` wall-clock seconds, 1 by default, and reads the file only when the time has changed. An entry is applied when it first appears or when its value differs from the last valid read. The file as it stands when the run starts counts as a first read, so the entries in it apply at the start. A save that changes no value applies nothing, and an entry whose value is NaN is not applied again when you edit the file, because two NaN values count as the same. An entry you remove changes nothing, and the model keeps the value it has. A file that does not exist yet is waited for. ```yaml # Applies an entry of params.yaml when it first appears or its value changes - type: File config: {path: params.yaml, poll: 1.0} ``` ```python # Applies an entry of params.yaml when it first appears or its value changes app.add_ingress(FileIngress("params.yaml", poll=1.0)) ``` The low-level API passes the same `FileIngress` to `env.setup_ingress`, in its list of connectors, as [Low-level API](https://jaehyeon.me/desflow/latest/user-guide/writing-a-model/low-level-api/#attach-the-connectors) shows. The file holds one registry path on each line, with its new value: ```text Shop.resources.packers.current_cap: 3 Shop.arrival.orders.rate: 0.5 ``` A relative `path` is relative to the folder the run starts in. ### Kafka `KafkaIngress` consumes a topic and reads each message as a JSON object with `path` and `value`, or through a deserializer of your own, such as Avro, JSON Schema or Protobuf, as [Use Avro and Pydantic](https://jaehyeon.me/desflow/latest/how-to/records-and-kafka/avro-and-pydantic/index.md) and [JSON Schema and Protobuf](https://jaehyeon.me/desflow/latest/how-to/records-and-kafka/json-schema-and-protobuf/index.md) show. [Connect to Secure Kafka](https://jaehyeon.me/desflow/latest/how-to/records-and-kafka/kafka-security/index.md) connects it to a secured cluster. At the start of a run, `KafkaIngress` creates its topic when it is missing, as `KafkaEgress` does. A consumer that starts before any producer therefore does not wait for a topic that is not there. `topic_policy` sets this: `create` is the default, `drop_and_create` deletes the topic and creates it again, and `manual` creates nothing and keeps the behaviour before 1.0, when the ingress never created its topic. A `desflow run --stdout` run keeps its ingress, so it applies the ingress's `topic_policy` too: it creates the control topic, and with `drop_and_create` it deletes and recreates it. A `--sample` run leaves the ingress out. ```yaml # Reads {"path": ..., "value": ...} messages from the sim-config topic - type: Kafka config: topic: sim-config bootstrap_servers: ${KAFKA_BOOTSTRAP_SERVERS:-127.0.0.1:9092} ``` ```python # Reads {"path": ..., "value": ...} messages from the sim-config topic app.add_ingress(KafkaIngress(topic="sim-config", bootstrap_servers="127.0.0.1:9092")) ``` The low-level API passes the same `KafkaIngress` to `env.setup_ingress`, in its list of connectors, as [Low-level API](https://jaehyeon.me/desflow/latest/user-guide/writing-a-model/low-level-api/#attach-the-connectors) shows. `KafkaAdminConnector.send_config(topic, path, value)` sends one such message. The [Kafka example](https://jaehyeon.me/desflow/latest/gallery/simulation-models/kafka/index.md) listens on `sim-config`, and this sets its number of packers: A blueprint has no sender of its own. Send the message from Python, as the Builder tab shows, or from any Kafka client, as below. ```python """Sets the packers capacity of the running Kafka example. `KafkaAdminConnector.send_config` publishes `{"path": ..., "value": ...}` to the topic `KafkaIngress` reads, `sim-config` in the example. Call `set_packer_capacity(3)` while the example runs. """ import asyncio from desflow import KafkaAdminConnector def set_packer_capacity(value: int) -> None: admin = KafkaAdminConnector(bootstrap_servers="127.0.0.1:9092") asyncio.run( admin.send_config("sim-config", "Shop.resources.packers.current_cap", value) ) ``` The sender does not depend on how the model is written: use the function the Builder tab shows. From any Kafka client, the message is the JSON object itself: ```python async def send_with_kafka(rate: float) -> None: """A JSON object with path and value, to the topic KafkaIngress reads.""" from aiokafka import AIOKafkaProducer producer = AIOKafkaProducer(bootstrap_servers="127.0.0.1:9092") await producer.start() try: message = {"path": "Shop.arrival.orders.rate", "value": rate} await producer.send_and_wait("sim-config", json.dumps(message).encode()) finally: await producer.stop() ``` ### Redis `RedisIngress` subscribes to a Pub/Sub channel and reads each message as the same JSON object. ```yaml # Reads {"path": ..., "value": ...} messages from a Pub/Sub channel - type: Redis config: url: redis://user:password@127.0.0.1:6379/0 channel_name: simulation_params ``` ```python # Reads {"path": ..., "value": ...} messages from a Pub/Sub channel app.add_ingress( RedisIngress( "redis://user:password@127.0.0.1:6379/0", channel_name="simulation_params" ) ) ``` The low-level API passes the same `RedisIngress` to `env.setup_ingress`, in its list of connectors, as [Low-level API](https://jaehyeon.me/desflow/latest/user-guide/writing-a-model/low-level-api/#attach-the-connectors) shows. ```python async def send_with_redis(rate: float) -> None: """The same JSON object, published to the channel RedisIngress subscribes to.""" import redis.asyncio as redis client = redis.from_url("redis://user:password@127.0.0.1:6379/0") message = {"path": "Shop.arrival.orders.rate", "value": rate} await client.publish("simulation_params", json.dumps(message)) await client.aclose() ``` With the [Redis example](https://jaehyeon.me/desflow/latest/gallery/simulation-models/redis/index.md) running, `valkey-cli` sends one from a shell: ```bash # Change the order arrival rate of the running simulation docker exec -it valkey valkey-cli --user user --pass password PUBLISH simulation_params '{"path": "Shop.arrival.orders.rate", "value": 10.0}' ``` ### PostgreSQL `PostgresIngress` polls a table, `simulation_params` by default, every `poll_interval` seconds, 2 by default. It creates the table when it is missing, with the columns `id`, `path`, `value`, `is_applied` and `created_at`, and first its schema when the name has one that the database does not have, such as `dashboard` in `dashboard.params`. It applies the rows in two steps: 1. At the start, it applies the latest applied value of each path, in the order the changes were made, so a restarted run resumes from the last settings. A `current_cap` that was made after a `max_cap` is applied after it, so the new maximum clamps it as it did the first time. 1. At each poll, it applies every row whose `is_applied` is false and marks it true, so the table keeps the history of every change. `value` is read as JSON, and as plain text when it is not JSON. The connection string names `odctl`, the database that the odctl `postgres` profile creates, with the user `user` and the password `password`. ```yaml # Applies new rows (path, value) of simulation_params, checking every 2 seconds - type: Postgres config: connection_dsn: postgresql://user:password@127.0.0.1:5432/odctl table_name: simulation_params poll_interval: 2.0 ``` ```python # Applies new rows (path, value) of simulation_params, checking every 2 seconds app.add_ingress( PostgresIngress( "postgresql://user:password@127.0.0.1:5432/odctl", table_name="simulation_params", poll_interval=2.0, ) ) ``` The low-level API passes the same `PostgresIngress` to `env.setup_ingress`, in its list of connectors, as [Low-level API](https://jaehyeon.me/desflow/latest/user-guide/writing-a-model/low-level-api/#attach-the-connectors) shows. ```python async def send_with_postgres(rate: float) -> None: """A row in the table PostgresIngress polls; value is JSON text.""" import asyncpg conn = await asyncpg.connect("postgresql://user:password@127.0.0.1:5432/odctl") try: await conn.execute( "INSERT INTO simulation_params (path, value) VALUES ($1, $2)", "Shop.arrival.orders.rate", json.dumps(rate), ) finally: await conn.close() ``` With the [PostgreSQL example](https://jaehyeon.me/desflow/latest/gallery/simulation-models/postgres/index.md) running, `psql` adds one from a shell: ```bash # Change the order arrival rate of the running simulation docker exec -it postgres psql -U user -d odctl -c "INSERT INTO simulation_params (path, value) VALUES ('Shop.arrival.orders.rate', '5.0');" ``` ______________________________________________________________________ ## How It Works The connectors run on the ingress thread, apart from the simulation. Each reads its source, turns every message into a `(path, value)` pair with one shared check, and puts it on a queue. A SimPy process, the ingress monitor, applies everything queued every 0.1 simulation seconds: At `factor: 1.0`, 0.1 simulation seconds take 0.1 real seconds, so a change lands within 0.1 seconds of arriving. The simulation time it lands at depends on when it arrives, so two runs with the same seed and the same messages can differ. A change that must land at an exact simulation time needs a scenario step. A connector is a class with one method, `async run(queue)`, so a source desflow does not have takes one class to write: [Write a Connector](https://jaehyeon.me/desflow/latest/how-to/records-and-kafka/write-a-connector/index.md) shows how. ______________________________________________________________________ ## Stability and Limits - **A bad message is skipped.** A message that cannot be decoded, that is not an object, or that lacks a non-empty `path` or a non-null `value` is logged as one WARNING line and skipped, and the run goes on. A PostgreSQL row like that is marked applied, so it is read once. A path the model does not have is a warning from the registry. A schema registry that refuses a Kafka deserializer's credentials or access stops `KafkaIngress` instead, as [Connect to Secure Kafka](https://jaehyeon.me/desflow/latest/how-to/records-and-kafka/kafka-security/#connect-to-a-secured-schema-registry) describes. - **Old keys get a hint.** Before 0.21.0, Kafka read `path_id`, and Redis and PostgreSQL read `param_path` and `param_value`. A message with the old keys is skipped with a line that says so, such as this one, which `parse_change` gives for a Kafka message written for 0.20.0: ```text Skipped a Kafka ingress message: expected a non-empty path and a non-null value, got {'path_id': 'Shop.arrival.orders.rate', 'value': 1.0}; path_id, param_path and param_value were renamed to path and value in desflow 0.21.0 ``` - **Old PostgreSQL columns.** A table created before 0.21.0 has the columns `param_path` and `param_value`. Reading it fails with an error line that gives the two statements to rename them: ```sql ALTER TABLE simulation_params RENAME COLUMN param_path TO path; ALTER TABLE simulation_params RENAME COLUMN param_value TO value; ``` - **An invalid file is skipped.** An empty file, which an editor can leave for a moment while it saves, is skipped with no log line. A file that is not valid YAML, or is not a mapping, is logged as one WARNING line that names the file and the parser's error, and nothing from that read is applied. The next valid read is compared with the last valid one. An entry with an empty path or a null value is logged as one WARNING line and skipped, as for the other connectors. - **`LocalIngress` follows the wall clock,** so at `factor: 0` an unpaced run can end before its first change. `FileIngress` does too. - **Ingress needs an `until`.** A run that only waits for ingress has no model event of its own, so without `until` it ends at once. Set `until`, and Ctrl+C then stops the run before it reaches that time, as [Run Length](https://jaehyeon.me/desflow/latest/user-guide/time-and-pacing/run-length/#run-length_1) explains. ______________________________________________________________________ ## Example: File Steering The `file` example has a shop with one packer and more orders than one packer can pack. A `File` connector reads `params.yaml`, whose one line sets the packers' capacity. Change the 1 to 5 while the run goes and save the file. The statistics, published every 2 seconds, show the capacity change and the queue shrink. It needs no Docker service and ends on its own after 60 seconds of real time. Each tab shows how the example attaches the connector, then how to download and run it. ```yaml ingress: # A relative path is relative to the folder the command runs in - type: File config: {path: ../params.yaml} ``` **Quick Start** `desflow examples get` downloads the example at the release you install, into a folder of its own. Pick uv or pip: ```bash # 1. Install uv tool install desflow # 2. Download the example desflow examples get file --api yaml cd file/yaml # 3. Run it desflow run file.yaml ``` ```bash # 1. Install pip install desflow # 2. Download the example desflow examples get file --api yaml cd file/yaml # 3. Run it desflow run file.yaml ``` ```python # Applies an entry of the file when it first appears or its value changes .add_ingress(FileIngress(PARAMS_FILE)) ``` **Quick Start** `desflow examples get` downloads the example at the release you install, into a folder of its own. Pick uv or pip: ```bash # 1. Install uv tool install desflow # 2. Download the example desflow examples get file --api builder cd file/builder # 3. Run it uv run --no-project --with desflow file_example.py ``` ```bash # 1. Install pip install desflow # 2. Download the example desflow examples get file --api builder cd file/builder # 3. Run it python file_example.py ``` ```python # Applies an entry of the file when it first appears or its value changes env.setup_ingress([FileIngress(PARAMS_FILE)]) ``` **Quick Start** `desflow examples get` downloads the example at the release you install, into a folder of its own. Pick uv or pip: ```bash # 1. Install uv tool install desflow # 2. Download the example desflow examples get file --api low-level cd file/low-level # 3. Run it uv run --no-project --with desflow file_example.py ``` ```bash # 1. Install pip install desflow # 2. Download the example desflow examples get file --api low-level cd file/low-level # 3. Run it python file_example.py ``` # Egress, Batching and Delivery An egress connector, or sink, writes the records a run publishes: to the console, Kafka, Redis, PostgreSQL, Parquet or JSON Lines files, or Iceberg tables. One sink keeps them in memory as tables for the Python program that runs the model. This page shows each sink, how to choose which records each one gets, and how records travel from a task to a sink. ______________________________________________________________________ ## What It Is A run publishes three kinds of record in the ordinary case: **events**, such as a task's `queued`, `started` and finished; **telemetry**, single values such as the statistics; and **labels**, the ground-truth records of what a scenario changed. Every sink receives every event and every telemetry record, unless its `when` says otherwise. Labels go only to sinks that ask for them. A run can publish a fourth kind, **trace**, one record for each event the environment processes, only when `stats.trace` is set, and only to a sink with `when: trace`. [Records and Telemetry](https://jaehyeon.me/desflow/latest/reference/records-and-telemetry/index.md) shows each record's shape and what each sink writes. The tutorial page [Streaming Out](https://jaehyeon.me/desflow/latest/learn/running-live/streaming-out/index.md) teaches these features step by step. ______________________________________________________________________ ## How to Use It Each sink is listed under `egress` in a blueprint with its `type` and `config`, attached with `add_egress` in the builder, or passed to `env.setup_egress` in the low-level API. In the builder snippets below, `app` is a `SimulationContext`. In a blueprint, `type` is one of the short names below, or a `!python` class from another package. A connector's module is imported only when a blueprint names it, so a blueprint that uses Kafka does not need the PostgreSQL driver. Parquet and JSON Lines are the exception: they import PyArrow when they start writing. A missing package stops the load with its line and the `pip install` command. | `type` | Class | Extra | | ---------- | ---------------------- | ---------- | | `Console` | `ConsoleEgress` | none | | `Kafka` | `KafkaEgress` | `kafka` | | `Parquet` | `ParquetStorageEgress` | `parquet` | | `Jsonl` | `JsonlStorageEgress` | `parquet` | | `Iceberg` | `IcebergStorageEgress` | `iceberg` | | `Postgres` | `PostgresEgress` | `postgres` | | `Redis` | `RedisEgress` | `redis` | | `InMemory` | `InMemoryEgress` | `parquet` | `InMemory` is Python only: a blueprint that names it is refused, as [In Memory](#in-memory) explains. `config` holds the constructor's arguments. Settings that Python takes as objects are plain values there: a Parquet or JSON Lines `filesystem` is a mapping with `type: local`, `s3`, `gcs` or `azure`, and an Iceberg `catalog` is a mapping of PyIceberg properties. A Postgres `tables` mapping creates its tables when the run starts. Each table maps to `columns`, a mapping of column name to SQL type, and an optional `primary_key`. An ISO time string bound for a timestamp or date column of Iceberg or PostgreSQL is converted before the write. [YAML Keys](https://jaehyeon.me/desflow/latest/reference/yaml-keys/#egress) lists the keys of an egress entry. ### Console `ConsoleEgress` has two formats. The default, `log`, logs each batch at INFO level with one call, one line per record: - Each line starts with `[EVT]` for an event, `[TEL]` for telemetry or `[LBL]` for a label. A trace record, which only a `when: trace` sink receives, starts with `[EVT]` too. - `desflow run` prints these lines as they are. Its other log lines start with the time, level and logger name. - In a script, the logging format the script sets, such as the time and level, starts only the first line of each batch. One call per batch is much faster than one call per record. In the measurements on [Tune Performance](https://jaehyeon.me/desflow/latest/how-to/tools/performance-tuning/index.md), a run that logged each record with its own call took about 50 percent longer in total. ```yaml - {type: Console} ``` ```python app.add_egress(ConsoleEgress()) ``` The low-level API passes the same `ConsoleEgress()` to `env.setup_egress`, in its list of sinks, as [Low-level API](https://jaehyeon.me/desflow/latest/user-guide/writing-a-model/low-level-api/#attach-the-connectors) shows. With `format="json"`, `ConsoleEgress` writes each record to stdout as one JSON line instead: the record as published, with its `stream_type`. Another program can then read the records. It writes at any log level, because the records are output, not a log. Python's logging writes to stderr by default, so the log stays apart from the records, and a pipe such as `| jq .key` reads only the records. In a blueprint it is `type: Console` with `config: {format: json}`. `desflow run --sample` and `--stdout` print through it in place of the file's sinks, as [YAML Blueprints](https://jaehyeon.me/desflow/latest/user-guide/writing-a-model/blueprints/#preview-the-records) describes. ```yaml # One JSON line per record on stdout, stream_type included - type: Console config: {format: json} ``` ```python # One JSON line per record on stdout, stream_type included app.add_egress(ConsoleEgress(format="json")) ``` The low-level API passes the same `ConsoleEgress(format="json")` to `env.setup_egress`, in its list of sinks, as [Low-level API](https://jaehyeon.me/desflow/latest/user-guide/writing-a-model/low-level-api/#attach-the-connectors) shows. A consumer can check each line against the record schema: `EventPayload`, `TelemetryPayload` and `LabelPayload` are the Pydantic models of the three stream types, as [Records and Telemetry](https://jaehyeon.me/desflow/latest/reference/records-and-telemetry/index.md) describes: ```python # The model of each stream type; a record with a missing or mistyped field raises SCHEMAS = {"event": EventPayload, "telemetry": TelemetryPayload, "label": LabelPayload} for line in printed.getvalue().splitlines(): record = json.loads(line) SCHEMAS[record["stream_type"]].model_validate(record) ``` The `trace` record has no model in `SCHEMAS`. A consumer reads it as a record whose `value` is a mapping with the keys `priority`, `event_id` and `event`. ### Kafka `KafkaEgress` sends events to `event_topic` and telemetry to `telemetry_topic`, keyed by the record's `key` or `path_id`. Kafka sends all records with one key to one partition, so all events of one entity stay in order. `KafkaEgress` creates both topics when the run starts, with one partition each, if they do not exist. With a `topic_router`, it creates neither of them, and only the topics named in `topics`. [Route Records to Topics](https://jaehyeon.me/desflow/latest/how-to/records-and-kafka/complex-routing/index.md) sends records to other topics, and [Connect to Secure Kafka](https://jaehyeon.me/desflow/latest/how-to/records-and-kafka/kafka-security/index.md) connects to a cluster that uses SASL, mTLS, OAuth or AWS IAM. ```yaml - type: Kafka config: bootstrap_servers: ${KAFKA_BOOTSTRAP_SERVERS:-127.0.0.1:9092} event_topic: sim-events telemetry_topic: sim-telemetry ``` ```python app.add_egress( KafkaEgress( bootstrap_servers="127.0.0.1:9092", event_topic="sim-events", telemetry_topic="sim-telemetry", ) ) ``` The low-level API passes the same `KafkaEgress` to `env.setup_egress`, in its list of sinks, as [Low-level API](https://jaehyeon.me/desflow/latest/user-guide/writing-a-model/low-level-api/#attach-the-connectors) shows. **Topics.** `topic_policy` says what the sink does with its topics when the run starts. It is a word, or a mapping of `mode`, `partitions`, `replication_factor` and `topic_configs`: - `create`, the default, creates a missing topic and leaves an existing one as it is, with one partition, a replication factor of 1 and no settings of its own. - `drop_and_create` deletes the topic and creates it again, so each run starts with an empty topic. - `manual` creates nothing. The policy covers the event topic and the telemetry topic. `topics` gives settings to other topics by name, each with the keys of `topic_policy` on top of the policy. A topic named there is created by the sink, also when a record chooses it with `__topic__` or a `topic_router`. A `topics` value must be a mapping, and a key that is not a policy key is refused when the blueprint loads. ```yaml # The policy covers the event and telemetry topics: three partitions each, with a # retention setting. sim-audit is created too, with one partition of its own - type: Kafka config: bootstrap_servers: ${KAFKA_BOOTSTRAP_SERVERS:-127.0.0.1:9092} event_topic: sim-events telemetry_topic: sim-telemetry topic_policy: mode: create partitions: 3 topic_configs: {retention.ms: 3600000} topics: sim-audit: {partitions: 1} ``` `KafkaEgress` takes the same `topic_policy` and `topics` as arguments. The low-level API passes the same `KafkaEgress(topic_policy=..., topics=...)` to `env.setup_egress`. An event whose `value` has a `__topic__` key goes to the topic it names, and the key is removed from the message. A `topic_router` wins over `__topic__`, and telemetry always goes to `telemetry_topic`. The sink also takes a `serializer` (a mapping with a `type` of `confluent_avro`, `confluent_json_schema`, `confluent_protobuf`, `glue_avro`, `glue_json_schema` or `glue_protobuf`, with the options of that type, such as `schema`, `schema_file`, `descriptor_file` and `message`), `ssl` and `sasl_oauth_token_provider` (`{type: aws_msk_iam, region: ...}`), and `serializer` can also be set for one topic under `topics`. In a blueprint, a `schema_file`, a `descriptor_file`, the `verify` and `cert` files of a serializer and the files of `ssl` are read from the blueprint's folder, as an `!include` is, so `desflow run sub/shop.yaml` and `cd sub && desflow run shop.yaml` read the same files. The Builder reads them from the working directory. [Use Schema Serializers](https://jaehyeon.me/desflow/latest/how-to/records-and-kafka/json-schema-and-protobuf/index.md) and [Connect to Secure Kafka](https://jaehyeon.me/desflow/latest/how-to/records-and-kafka/kafka-security/index.md) use these options. The registry options of the Avro serializers (`auth`, `verify`, `cert`, `headers`, `proxy`, `timeout` and `max_retries`) are in the step [Connect to a Secured Schema Registry](https://jaehyeon.me/desflow/latest/how-to/records-and-kafka/kafka-security/#connect-to-a-secured-schema-registry). ### Parquet and JSON Lines `ParquetStorageEgress` and `JsonlStorageEgress` write each batch as a file of its own, on a local disk, S3-compatible storage, Google Cloud Storage or Azure Blob Storage, through PyArrow. Without a `path_router`, each event is one flat row in `default_path`, with its `value` mapping unpacked into columns, and telemetry is left out. A Parquet file has a column for every key of any row in its batch, and a mapping value becomes a struct column. A later batch can change the columns: - A key that first appears in a later batch adds a column to the later files. A reader that combines the columns of all the files reads it as null in the earlier rows. - An integer column that a later batch gives a float becomes a double in the later files. - A nested key that first appears later is dropped, because the first batch with a mapping value fixes the keys of its struct column. The first batch sets the type of each column. A number in the first batch is read as a double for the `value` of a telemetry record, for the `now` and `peek` of a `run.steps` or `run.segments` reading, and for `usage_since`, so a later fraction is kept. A statistic (a number) and an event or a reading (a mapping) cannot share a file, because the `value` column has one type. Send them to different files with a `path_router`, because the default route writes no telemetry. A batch that cannot be written is logged at ERROR, and the sink goes on with the next one. **Routing by `__path__`.** An event whose `value` has a `__path__` key is written to the file path it names, and the key is removed from the row. A `path_router` wins over `__path__`, and a record with no `__path__` goes to `default_path`. `__path__` is relative to the working directory or to the sink's `filesystem`, and it is not placed under the folder of `default_path`. A path built with `{gen: format_time, format: "folder/%Y-%m-%d.jsonl"}` gives each simulated day its own files, `folder/2026-01-01_.jsonl`, with one file for each flush. [Write to Cloud Storage](https://jaehyeon.me/desflow/latest/how-to/storage-and-tables/cloud-storage/index.md) runs it. **File names.** `default_path`, and any path a `path_router` returns or `__path__` names, is a file name prefix, not a folder. Each batch is written as a file of its own, `_<8 hex digits>`, in the path's folder, so `output/events.parquet` gives files such as `output/events_1a2b3c4d.parquet`. Give the extension in the path: `output/events` gives files with none. The folder is created on the first write. **Columns of a finished event.** A task's `queued` and `started` events carry `path_id` and `status`. Its finished event's value is the task's payload only. So in a finished event's row, `path_id` and `status` are null unless the payload has them. The [Parquet example](https://jaehyeon.me/desflow/latest/gallery/simulation-models/parquet/index.md) adds them to its payload for that reason. ```yaml # Parquet files on the local disk, output/events_<8 hex digits>.parquet - type: Parquet config: {default_path: output/events.parquet} # JSON Lines files on S3-compatible storage, here SeaweedFS from odctl; a mapping # becomes PyArrow's S3FileSystem - type: Jsonl config: default_path: warehouse/events.jsonl filesystem: type: s3 access_key: user secret_key: password endpoint_override: 127.0.0.1:8333 scheme: http ``` ```python # Parquet files on the local disk, output/events_<8 hex digits>.parquet app.add_egress(ParquetStorageEgress(default_path="output/events.parquet")) # JSON Lines files on S3-compatible storage, here SeaweedFS from odctl seaweedfs = fs.S3FileSystem( access_key="user", secret_key="password", endpoint_override="127.0.0.1:8333", scheme="http", ) app.add_egress( JsonlStorageEgress(default_path="warehouse/events.jsonl", filesystem=seaweedfs) ) ``` The low-level API passes the same sinks to `env.setup_egress`, in its list of sinks, as [Low-level API](https://jaehyeon.me/desflow/latest/user-guide/writing-a-model/low-level-api/#attach-the-connectors) shows. Read the files back as one table with `pyarrow.dataset`, which reads every file in the folder: ```python def read_events(folder="output"): """Every file the sink wrote under `folder`, as one table.""" import pyarrow.dataset as ds # format="json" reads the files of a JsonlStorageEgress the same way return ds.dataset(folder, format="parquet").to_table() ``` A second run adds its files beside the first run's, so reading the folder then counts both runs. Give each run a folder of its own, or clear the folder before a run. **Filesystems.** `filesystem` is a PyArrow `FileSystem` object, or a mapping that desflow builds into one when the run starts. The mapping's `type` picks the class, and its other keys are the arguments of that class: | `type` | PyArrow class | Credentials | | --------------------- | ----------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `local` (the default) | `LocalFileSystem` | none | | `s3` | `S3FileSystem` | `access_key` and `secret_key`; without them, the standard AWS settings | | `gcs` | `GcsFileSystem` | `anonymous: true`; or `access_token` with `credential_token_expiration`; without them, Google's default credentials | | `azure` | `AzureFileSystem` | `account_name`, always; with it `account_key`, or `sas_token` (pyarrow 20.0.0 or later), or `client_id`, `client_secret` and `tenant_id` (pyarrow 21.0.0 or later); with `account_name` alone, Azure's default credentials | An `endpoint_override` that starts with `http://` or `https://` also sets `scheme`, for `s3` and `gcs`, unless `scheme` is given. `azure` has no `endpoint_override`: `blob_storage_authority` and `blob_storage_scheme` point it at an emulator such as Azurite. For `gcs`, `credential_token_expiration` is an ISO 8601 time, quoted or not, which desflow converts to UTC, and `retry_time_limit` is a number of seconds, because YAML has no duration type. A key whose value is empty is left out. PyArrow has `AzureFileSystem` from 16.0.0, the release the `parquet` extra requires. `sas_token` and the client credentials need the later releases the table names. PyPI's pyarrow wheels for Windows include it only from 24.0.0. The same two sinks write to Google Cloud Storage and Azure Blob Storage when `filesystem` is a mapping. [Write to Cloud Storage](https://jaehyeon.me/desflow/latest/how-to/storage-and-tables/cloud-storage/index.md) runs a shop against each store, from start to end: ```yaml # Parquet files on Google Cloud Storage, with Google's default credentials - type: Parquet config: default_path: my-bucket/events.parquet # type: gcs makes PyArrow's GcsFileSystem; without credentials it uses Google's # default ones filesystem: {type: gcs} # JSON Lines files on Azure Blob Storage, with Azure's default credentials - type: Jsonl config: default_path: my-container/events.jsonl # type: azure makes PyArrow's AzureFileSystem; without a key it uses Azure's # default credentials filesystem: {type: azure, account_name: myaccount} ``` ```python # Parquet files on Google Cloud Storage, with Google's default credentials cloud.add_egress( ParquetStorageEgress( default_path="my-bucket/events.parquet", filesystem={"type": "gcs"}, ) ) # JSON Lines files on Azure Blob Storage, with Azure's default credentials cloud.add_egress( JsonlStorageEgress( default_path="my-container/events.jsonl", filesystem={"type": "azure", "account_name": "myaccount"}, ) ) ``` The low-level API passes the same sinks to `env.setup_egress`, in its list of sinks, as [Low-level API](https://jaehyeon.me/desflow/latest/user-guide/writing-a-model/low-level-api/#attach-the-connectors) shows. ### Redis `RedisEgress` appends each record to a Redis Stream with `XADD`, as one `payload` field holding the record as JSON. A `__stream__` key in the record's value picks the stream, and is removed before writing. ```yaml # XADD to the events stream, unless a record's value names another in __stream__ - type: Redis config: {url: redis://user:password@127.0.0.1:6379/0, stream_name: events} ``` ```python # XADD to the events stream, unless a record's value names another in __stream__ app.add_egress( RedisEgress("redis://user:password@127.0.0.1:6379/0", stream_name="events") ) ``` The low-level API passes the same `RedisEgress` to `env.setup_egress`, in its list of sinks, as [Low-level API](https://jaehyeon.me/desflow/latest/user-guide/writing-a-model/low-level-api/#attach-the-connectors) shows. ### PostgreSQL `PostgresEgress` inserts records into a table in batches. It writes only the records whose value is a mapping, and the labels on a labels sink, each label as `sim_ts`, `timestamp`, `path`, `old`, `new` and `label`. A record's row is its value, changed in four ways: - The record's `sim_ts`, `timestamp`, `key` (as `event_id`) and `path_id` are added, and replace fields of the same name. - Its `task` and `instance` are added too, but a value field of the same name keeps its own value. - Keys with no matching column are dropped. - A `__table__` key sends the record only to the sink whose `table_name` matches. The columns are those of the one table that the name resolves to, as PostgreSQL reads it in the `CREATE TABLE` and `INSERT` statements. A name with capitals reads the table with the lower-case name (PostgreSQL folds only the letters `A` to `Z`, so `Ärger` stays `Ärger`), and a name with no schema reads the first table of that name on the `search_path`. `table_policy` says what the sink does about the tables in `tables` when the run starts: `create`, the default, creates the schema of a qualified name and the table when they do not exist, `drop_and_create` also drops the table first, and `manual` creates nothing. The connection string names `odctl`, the database that the odctl `postgres` profile creates, with the user `user` and the password `password`. ```yaml - type: Postgres config: connection_dsn: postgresql://user:password@127.0.0.1:5432/odctl table_name: orders ``` ```python dsn = "postgresql://user:password@127.0.0.1:5432/odctl" app.add_egress(PostgresEgress(dsn, table_name="orders")) ``` The low-level API passes the same `PostgresEgress` to `env.setup_egress`, in its list of sinks, as [Low-level API](https://jaehyeon.me/desflow/latest/user-guide/writing-a-model/low-level-api/#attach-the-connectors) shows. By default a record whose key already exists is skipped. `upsert_keys` updates that row instead, for a model that changes rows it wrote earlier, such as an order moving from packed to shipped. The key columns, a list or one column name, need a unique index. An update sets only the columns the record carries, and within one flush the last record for a key wins. A record that has no value for a key column, or a null there, is skipped, and one warning at the end of each flush says how many were skipped and why. ```yaml - type: Postgres config: connection_dsn: postgresql://user:password@127.0.0.1:5432/odctl table_name: orders upsert_keys: [order_id] ``` ```python app.add_egress(PostgresEgress(dsn, table_name="orders", upsert_keys=["order_id"])) ``` The low-level API passes the same `PostgresEgress` to `env.setup_egress`, in its list of sinks, as [Low-level API](https://jaehyeon.me/desflow/latest/user-guide/writing-a-model/low-level-api/#attach-the-connectors) shows. ### Iceberg `IcebergStorageEgress` appends records to an Apache Iceberg table through a catalog. One flush is one commit, so this sink needs a large `batch_size` of its own: every commit writes new metadata, and many small commits slow down queries. A table the sink creates takes its columns from the records: - The first batch gives a column for every key that has a value in some row. - A key that is null in every row waits for a batch that gives it a value, because Iceberg has no null type. An example is `task` in a low-level event published without one. - A key that first appears in a later batch is added as an optional column, unless the table is named in `schemas`, which keeps the columns it gives. A table with `upsert_keys` that is not named in `schemas` refuses that batch instead, so name every column of an upsert table in `schemas`. The first batch sets the type of each column. A whole number in the first batch gives an integer column, except that a telemetry `value`, the `now` and `peek` of a `run.steps` or `run.segments` reading and `usage_since` are read as doubles. A batch with a fraction for an integer column is logged at ERROR and its rows are not written. No value is truncated. Iceberg cannot change a `long` column to a double later, so a column that takes fractions is named in `schemas` before the table is created, such as `schemas: {shop.events: {key: string, v: double}}`: a table named there is created with exactly the columns listed, and every batch is cast to them. A statistic (a number) and an event or a reading (a mapping) need different tables, because the `value` column has one type. Send them apart with a `table_router`, because the default route writes no telemetry. [Write to Iceberg Tables](https://jaehyeon.me/desflow/latest/how-to/storage-and-tables/iceberg-tables/index.md) runs a batch that is lost and the fix. An event whose `value` has a `__table__` key, a `namespace.table` name, is written to that table, and the key is removed. A `table_router` wins over `__table__`, and a record with no `__table__` goes to `default_table`. An event that Postgres and Iceberg both receive and that has a `__table__` without a namespace is skipped by Iceberg with the warning "names no namespace", and the other records of the batch are written. Give Iceberg a `table_router`, or write `namespace.table` in the key. `table_policy` says what the sink does about a table at its first write, and every run of a context applies it again: `create`, the default, creates the namespace and the table when they do not exist, `drop_and_create` drops the table and creates it again once for each run, and `manual` creates nothing and fails the write if the table is missing. Each run also makes its own connection pool or client, in its own event loop, and makes the sink's folders again. ```yaml # Each run starts with an empty table: dropped and created again at the first write - type: Iceberg config: default_table: sim.events table_policy: drop_and_create catalog: name: odctl type: rest uri: http://127.0.0.1:8181 warehouse: s3://warehouse/ batch_size: 200000 ``` `IcebergStorageEgress` takes the same `table_policy` as an argument. The low-level API passes the same `IcebergStorageEgress(table_policy=...)` to `env.setup_egress`. **Catalogs.** `catalog` is a PyIceberg `Catalog` object, or a mapping of PyIceberg catalog properties that desflow passes to `load_catalog` on the first write. The mapping's optional `name` key names the catalog. Each catalog below has a test that writes through it: | Catalog | `type` | Tested against | | ----------------- | ------ | -------------------------------------- | | REST | `rest` | the odctl `catalog` profile | | SQL on SQLite | `sql` | the unit tests, with a database file | | SQL on PostgreSQL | `sql` | the odctl `postgres` profile | | Glue | `glue` | Floci, an AWS emulator, not AWS itself | The properties of each catalog are listed in [PyIceberg's configuration](https://py.iceberg.apache.org/configuration/). [Write to Iceberg Tables](https://jaehyeon.me/desflow/latest/how-to/storage-and-tables/iceberg-tables/index.md) runs a shop through each catalog, from start to end. ```yaml # A mapping of PyIceberg catalog properties, here the REST catalog of odctl. # One commit per flush, so this sink gets a large batch of its own - type: Iceberg config: default_table: sim.events catalog: name: odctl type: rest uri: http://127.0.0.1:8181 warehouse: s3://warehouse/ s3.endpoint: http://127.0.0.1:8333 s3.access-key-id: user s3.secret-access-key: password s3.region: us-east-1 batch_size: 200000 ``` ```python catalog = RestCatalog( "odctl", uri="http://127.0.0.1:8181", warehouse="s3://warehouse/", **{ "s3.endpoint": "http://127.0.0.1:8333", "s3.access-key-id": "user", "s3.secret-access-key": "password", "s3.region": "us-east-1", }, ) # One commit per flush, so this sink gets a large batch of its own app.add_egress( IcebergStorageEgress(catalog=catalog, default_table="sim.events"), batch_size=200_000, ) ``` The low-level API passes the same `IcebergStorageEgress` to `env.setup_egress`, in its list of sinks, and gives its batch size in `batch_sizes`, as [Batch Size and Flush Interval](#batch-size-and-flush-interval) shows. A SQL catalog on SQLite needs no service, so it suits a first run. Its database file and the table files are under one folder: ```yaml # The catalog's database and the table files are under the folder iceberg/ - type: Iceberg config: default_table: sim.events # The folder iceberg/ must exist before the run catalog: name: local type: sql uri: sqlite:///iceberg/catalog.db warehouse: file://${PWD}/iceberg/warehouse ``` ```python # The catalog's database and the table files are under the folder iceberg/ folder = Path("iceberg").resolve() folder.mkdir(exist_ok=True) catalog = { "name": "local", "type": "sql", "uri": f"sqlite:///{folder}/catalog.db", "warehouse": f"file://{folder}/warehouse", } app.add_egress(IcebergStorageEgress(catalog=catalog, default_table="sim.events")) ``` The low-level API passes the same `IcebergStorageEgress` to `env.setup_egress`, in its list of sinks, as [Low-level API](https://jaehyeon.me/desflow/latest/user-guide/writing-a-model/low-level-api/#attach-the-connectors) shows. `upsert_keys` upserts on key columns instead of appending, and each table takes a list of columns or one column name. A seeded model rerun over the same window writes rows with the same keys, so the upsert replaces those rows instead of duplicating them. An upsert reads the matching rows first, replaces whole rows, never deletes, and needs pyiceberg 0.9.0 or later. A table with `upsert_keys` cannot gain a column, because the matching rows in the old data files lack it. When a table with `upsert_keys` is not named in `schemas`, a batch that brings a column the table lacks is logged as an error that names the table and the columns, and is not written. A table named in `schemas` writes only the columns listed there and leaves any other field out. Name every column in `schemas` before the table is created. A record that lacks a key column, or holds null in it, is skipped, and one warning at the end of each flush says how many were skipped and why. An entry that names its tables in `schemas`, `locations` or `upsert_keys` needs no `default_table` and no router. ```yaml - type: Iceberg config: default_table: sim.orders upsert_keys: {sim.orders: [order_id]} catalog: name: odctl type: rest uri: http://127.0.0.1:8181 warehouse: s3://warehouse/ batch_size: 200000 ``` ```python app.add_egress( IcebergStorageEgress( catalog=catalog, default_table="sim.orders", upsert_keys={"sim.orders": ["order_id"]}, ), batch_size=200_000, ) ``` The low-level API passes the same `IcebergStorageEgress` to `env.setup_egress`, in its list of sinks, and gives its batch size in `batch_sizes`, as [Batch Size and Flush Interval](#batch-size-and-flush-interval) shows. ### In Memory `InMemoryEgress` keeps a run's records in the Python program that runs the model, and returns them as `pyarrow` tables after the run, so a program can use them in the same process with no file or service. `sink.table(name)` returns one destination and `sink.tables()` every destination that holds records. Each record goes to the destination of its stream type: `events`, `telemetry`, and `labels` or `trace` on a sink with `when` set to `labels` or `trace`. An event is one flat row with its payload as columns, as the Parquet sink writes it. A telemetry record keeps its `value`, by the rule [Records and Telemetry](https://jaehyeon.me/desflow/latest/reference/records-and-telemetry/index.md) gives for this sink: a statistic's is a double, and the readings of `run.steps` and `run.segments`, whose `value` is a mapping, go to a destination of their own, `steps`. The columns come from every record, so a key that first appears later still gets its column. The sink empties its tables when a run starts. It needs pyarrow, from the `parquet` extra. A blueprint cannot name the sink: `type: InMemory` is refused, because `desflow run` has no program to hand the tables to. Load the blueprint in Python with `SimulationContext.from_yaml()`, then add the sink with `add_egress()`: ```python from keep_records_in_memory import show from desflow import InMemoryEgress, SimulationContext sink = InMemoryEgress() app = SimulationContext.from_yaml("keep_records_in_memory.yaml") app.add_egress(sink) if __name__ == "__main__": app.run() # until 120, from the blueprint show(sink) ``` The builder adds it as any other sink, `app.add_egress(sink)`, and reads `sink.table()` after `app.run()`. The low-level API passes the sink to `env.setup_egress`, in its list of sinks, and reads `sink.table()` after `env.teardown()`, which hands the sink the last records. [Keep Records in Memory](https://jaehyeon.me/desflow/latest/how-to/storage-and-tables/keep-records-in-memory/index.md) runs the three forms and converts the tables to pandas. ### Choose What Each Sink Gets Every sink receives every event and telemetry record. `when` narrows that down: - **A function** taking one record and returning True to send it to this sink, in the builder or as `!python` in a blueprint. - **`events` and `telemetry`**, in a blueprint: only the event records, or only the telemetry records. - **`{expr: ...}`**, in a blueprint: an expression over the record, written with `record.stream_type` (`event` or `telemetry`), `record.key`, `record.task` and `record.value.`. The sink receives the record when the expression is true. A name the record lacks reads as null, so an equality with it is false. An ordering comparison such as `record.value.amount > 100` fails the run on the first record that has no `amount`, so write `record.stream_type == 'event' and ...` first. `t` is refused in a `when` expression. - **`history` and `live`**, in a blueprint: the records stamped before `simulation.go_live_at`, and the rest, as [Clocks and Pacing](https://jaehyeon.me/desflow/latest/user-guide/time-and-pacing/clocks-and-pacing/#go-live) describes. - **`trace`**: the event trace of `stats.trace`, and nothing else. [Built-in Statistics](https://jaehyeon.me/desflow/latest/user-guide/results/statistics/#trace-the-events) sets it up. A run with a `trace` sink and no `stats.trace` is refused when it loads. - **`labels`**: the ground-truth labels, and nothing else. No other sink receives a label, so data and labels always reach different sinks. [Live Parameters](https://jaehyeon.me/desflow/latest/user-guide/live-runs-and-connectors/live-parameters/#record-what-a-change-was-for) describes them. ```yaml egress: # Small and often for this sink; the other uses the defaults - {type: Console, batch_size: 50, flush_interval: 0.5} # Only the records stamped before go_live_at - {type: Console, when: history} ``` ```python app.add_egress(stream).add_egress(lake) # both receive every record ``` ```python # A record's timestamp is an ISO string with its zone offset, so read it as a time hot_from = datetime.now(timezone.utc) def is_hot(record) -> bool: return datetime.fromisoformat(record["timestamp"]) >= hot_from app.add_egress(stream, when=is_hot) # hot tail app.add_egress(lake, when=lambda r: not is_hot(r)) # cold history app.add_egress(audit) # no predicate: everything ``` `setup_egress` takes the functions in `predicates`, one for each sink by position, as [Batch Size and Flush Interval](#batch-size-and-flush-interval) shows. The `events`, `telemetry` and `{expr}` forms are YAML forms: ```yaml # Only the event records - {type: Console, when: events} # Only the telemetry records - {type: Console, when: telemetry} # Only the events that carry an amount over 100 - type: Console when: {expr: "record.stream_type == 'event' and record.value.amount > 100"} ``` `add_egress(sink, when=...)` takes a function, as above. A function can test `record["stream_type"]` and `record["value"]` for the same result. `predicates` in `setup_egress` takes the same functions. A labels sink gets the ground-truth labels and nothing else: ```yaml egress: # The data under test: events and telemetry, and no label - {type: Console} # The labels only, for a scorer that checks what a detector found - type: Jsonl config: {default_path: labels/labels.jsonl} when: labels ``` ```python app.add_egress(stream) # events and telemetry, never a label app.add_egress(audit, when="labels") # ground-truth labels, and nothing else ``` `labels` in `setup_egress` marks each labels sink with True, by position, as [Batch Size and Flush Interval](#batch-size-and-flush-interval) shows. A file sink such as this one writes one file per batch under `labels/`, such as `labels/labels_1a2b3c4d.jsonl`. A run's `warmup` applies to every sink: none receives a record or telemetry stamped before it. [Run Length](https://jaehyeon.me/desflow/latest/user-guide/time-and-pacing/run-length/#warm-up) describes it. ### Write the Value Alone A sink normally writes each record with its envelope: `stream_type`, `sim_ts`, `timestamp`, `key`, `task` and `instance` around the event's `value`. With `envelope: false` on the entry, the sink writes each event's `value` alone and receives no telemetry record and no `queued` or `started` record of a task. A label record of a `when: labels` entry is not changed. The Console `json` format writes the value alone too. - A Kafka sink sends the value as the message, with the record's key as the message key. A null value is sent as a tombstone, a message with the key and a null value, which a compacted topic reads as a delete of that key. A `topic_router` still receives the whole record. - A Redis sink sends a value that is not a mapping as JSON, a null included. - A storage, Iceberg or PostgreSQL sink skips a value that is not a mapping, with one warning. A task's `key_field` names the payload field whose value becomes the key of its finished event, and so the Kafka message key. The `queued` and `started` records keep the entity's key, and a payload without the field fails the run. [Task Flow](https://jaehyeon.me/desflow/latest/user-guide/model-parts/task-flow/#record-key-and-fields) describes the key. ```yaml egress: # Each event's value alone is written: no telemetry, and no queued or started record - {type: Console, envelope: false} ``` A Kafka sink takes the key in the same way. The value alone is the message, and a null value is sent as a tombstone: ```yaml # The value of each event alone is the message: no telemetry, no queued or started # record, and a null value is sent as a tombstone - type: Kafka config: bootstrap_servers: ${KAFKA_BOOTSTRAP_SERVERS:-127.0.0.1:9092} event_topic: sim-orders envelope: false ``` `app.add_egress(sink, envelope=False)` does the same. `setup_egress` takes `envelopes`, a list with True or False for each sink, by position. ### Batch Size and Flush Interval A sink receives records in batches. A batch is handed over when it holds `batch_size` records, or when `flush_interval` simulation seconds have passed, whichever comes first. At `factor: 0`, the timer does not start until a `go_live_at` switches the run to real time, because simulation time is not tied to the wall clock before then. | Setting | Default | Set with | | --------------------- | ---------------------- | -------------------------------------------- | | `batch_size` | 500 | `with_batching`, or per sink on `add_egress` | | `flush_interval` | 1.0 simulation seconds | `with_batching`, or per sink on `add_egress` | | `max_queued_batches` | 2000 | `with_batching` | | `drain_stall_seconds` | 30.0 seconds | `with_batching` | A size is a whole number of 1 or more and an interval is above 0. YAML and the Builder refuse `true`, 0, a negative number and NaN. `with_batching` sets the defaults, and each sink can have its own size and interval. A stream sink needs small, frequent batches to keep latency down. A file or lake sink needs large ones, because each batch becomes one file, and for Iceberg one commit. ```yaml # The delivery settings of the Egress page, as a blueprint. # Run it with: desflow run batching.yaml simulation: sim_id: Shop factor: 0 # A day of history at factor 0, then 1 simulated second per real second from now; # when: history and when: live split the records at this instant logical_start_time: -1d go_live_at: now # Defaults for every egress, the arguments of with_batching batching: batch_size: 500 flush_interval: 1.0 max_queued_batches: 2000 drain_stall_seconds: 30 egress: # Small and often for this sink; the other uses the defaults - {type: Console, batch_size: 50, flush_interval: 0.5} # Only the records stamped before go_live_at - {type: Console, when: history} resources: packers: {current_cap: 1, max_cap: 1} run: {until: 60} ``` ```python app.with_batching( batch_size=5_000, # records per batch flush_interval=1.0, # simulation seconds; not used at factor=0 max_queued_batches=2_000, # a full queue makes the simulation wait drain_stall_seconds=30.0, # how long teardown waits for a queue that stopped ) ``` ```python app.with_batching(batch_size=500, flush_interval=1.0) # the default for every sink app.add_egress(stream, batch_size=50, flush_interval=0.5) # small and often app.add_egress(lake, batch_size=200_000) # large files, the default interval ``` The lists are matched to the sinks by position, and `None` means the default: ```python env = DynamicRealtimeEnvironment(factor=0.0) env.setup_egress( [stream, lake], batch_size=500, # defaults for every provider flush_interval=1.0, predicates=[None, lambda r: r["stream_type"] == "event"], # by position batch_sizes=[50, None], # None: the default flush_intervals=[0.5, None], labels=[False, False], # True makes a provider a labels sink warmup=None, # simulation seconds before which no provider gets a record ) ``` `setup_egress` also takes `lag_monitor_interval`, the simulation seconds between `system.simulation.lag_seconds` records. Its default, `"auto"`, is off at `factor` 0 and 1.0 simulation seconds otherwise. A run that goes live starts it at the go-live instant. `None` or 0 turns it off. The builder and YAML set it with `lag_interval`, as [Clocks and Pacing](https://jaehyeon.me/desflow/latest/user-guide/time-and-pacing/clocks-and-pacing/#lag) describes. ______________________________________________________________________ ## How It Works A published record goes through the same steps for each sink: 1. `publish_event`, `publish_telemetry` or `publish_label` builds the record as a plain dictionary. 1. Each sink tests it once. A labels sink takes only labels, and only a labels sink takes a label. No sink takes a record stamped before the [warm-up](https://jaehyeon.me/desflow/latest/learn/concepts/output-analysis/#one-run-starts-empty). Then the sink applies its `when`. 1. The record goes into that sink's buffer. When the buffer reaches `batch_size`, or the sink's timer fires, the buffer is handed to the sink's queue as one batch. 1. The egress thread takes batches from each queue and writes them with the sink's connector. A connector is a class with one method, `async run(queue)`, so a sink desflow does not have takes one class to write: [Write a Connector](https://jaehyeon.me/desflow/latest/how-to/records-and-kafka/write-a-connector/index.md) shows how. Each sink has its own buffer and its own queue. All sinks run as tasks on one thread, so a sink that waits with `await` does not hold up the others. A sink that blocks the thread holds up every sink. Memory holds each sink's buffer and the batches waiting in its queue. A record that several sinks take is stored once. A queue holds at most `max_queued_batches` batches. When it is full, the simulation waits for room, so a sink that cannot keep up slows the run instead of building a backlog. When a queue stays full for `drain_stall_seconds`, the sink has stopped consuming, and the run raises `RuntimeError` rather than losing records. **Teardown** flushes every buffer, then waits for the queues to drain. It keeps waiting while they shrink, and gives up only when they have not shrunk for `drain_stall_seconds`. Records still queued then are lost, and a warning names the sinks that held them. ______________________________________________________________________ ## Stability and Limits - **A slow sink slows the run.** The run slows on purpose: otherwise a backlog would build that teardown would have to throw away. - **Size or interval, whichever comes first.** The effective batch is the smaller of `batch_size` and what arrives in one `flush_interval`, so a large size with a short interval never fills. A warning says so once, after one sink has flushed on its timer 20 times in a row with less than a quarter of its `batch_size`. - **A labels sink receives only labels,** and a data sink never receives one. A label sent to a Kafka sink goes to its `event_topic` with no key. - **Records matching no sink are not written anywhere,** which is how `when` drops them. - **An in-memory sink holds every record of a run** until the next run starts, so a long run at a high rate needs a file sink instead. - **At `factor: 0`**, records leave a buffer only when it is full and at teardown. # How-To # How-To Each page here does one task, step by step, with code that you can run. To see what a part of desflow does and all its options, see the [User Guide](https://jaehyeon.me/desflow/latest/user-guide/index.md). For a complete model to download and run, see the [Gallery](https://jaehyeon.me/desflow/latest/gallery/index.md). ## Modelling | Task | What you do | | --------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------- | | [Vary Arrivals by Time](https://jaehyeon.me/desflow/latest/how-to/modelling/time-varying-arrivals/index.md) | change the arrival rate and the staffing at set times | | [Add Reneging and Balking](https://jaehyeon.me/desflow/latest/how-to/modelling/reneging-and-balking/index.md) | give a task a time limit on its wait, or a condition that stops it joining | | [Wait for One or All](https://jaehyeon.me/desflow/latest/how-to/modelling/wait-for-one-or-all/index.md) | wait for the first of several things, for all of them, for a computed number of them, or for a resume | | [Hand Off to a Resource](https://jaehyeon.me/desflow/latest/how-to/modelling/multi-resource-handoffs/index.md) | pass an order from one resource to the next without letting go of the first too early | | [Share Work by Weight](https://jaehyeon.me/desflow/latest/how-to/modelling/share-by-weight/index.md) | share one resource between classes of work by weight | | [Model Breakdowns](https://jaehyeon.me/desflow/latest/how-to/modelling/breakdowns/index.md) | make a resource fail at random, count only its busy time, and check its downtime | | [Add Resources Mid-run](https://jaehyeon.me/desflow/latest/how-to/modelling/dynamic-topology/index.md) | add a resource during a run, or give a resource with no units its units at a set time | | [Switch a Task On Mid-run](https://jaehyeon.me/desflow/latest/how-to/modelling/switch-a-task-on/index.md) | send work to a task declared from the start once a scenario step changes its route's weight | | [Serve Entities Together](https://jaehyeon.me/desflow/latest/how-to/modelling/serve-entities-together/index.md) | serve several entities with one run of a resource, in a batch | ## Generate Data | Task | What you do | | ------------------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------- | | [Send Data to a Sink](https://jaehyeon.me/desflow/latest/how-to/generate-data/send-data-to-a-sink/index.md) | write generated orders to the console, Kafka, PostgreSQL or a file | | [Extend Payloads](https://jaehyeon.me/desflow/latest/how-to/generate-data/realistic-fields/index.md) | fill a payload with names, emails and cities that look real, and keep related fields together with one row of a file | | [Choices and Numbers](https://jaehyeon.me/desflow/latest/how-to/generate-data/choices-and-numbers/index.md) | pick values with set odds and draw numbers from a range or a bell curve | | [Timestamps and Gaps](https://jaehyeon.me/desflow/latest/how-to/generate-data/timestamps-and-gaps/index.md) | put times into records and make the gaps between records vary | | [Stop After a Count](https://jaehyeon.me/desflow/latest/how-to/generate-data/stop-after-a-count/index.md) | end a run after a set number of records | | [Many Entities](https://jaehyeon.me/desflow/latest/how-to/generate-data/many-entities/index.md) | start many entities from one arrival, each with its own key and values | | [Build on the Last Value](https://jaehyeon.me/desflow/latest/how-to/generate-data/build-on-the-last-value/index.md) | make each value depend on the one before it | | [Skewed Keys](https://jaehyeon.me/desflow/latest/how-to/generate-data/skewed-keys/index.md) | make a few keys carry most of the records | | [Change State Over Time](https://jaehyeon.me/desflow/latest/how-to/generate-data/change-state-over-time/index.md) | write a state machine as tasks | | [Look Up Other Records](https://jaehyeon.me/desflow/latest/how-to/generate-data/look-up-other-records/index.md) | join records as they are made | | [Join Across Sinks](https://jaehyeon.me/desflow/latest/how-to/generate-data/join-across-sinks/index.md) | write the ids of one kind of record to one sink and use them in another | | [Change the Schema](https://jaehyeon.me/desflow/latest/how-to/generate-data/change-the-schema/index.md) | add, rename and retype a field at known times | ## Other Groups | Group | What it covers | | --------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | [Records and Kafka](https://jaehyeon.me/desflow/latest/how-to/records-and-kafka/complex-routing/index.md) | records routed to Kafka topics, Avro, JSON Schema, Protobuf and Pydantic records, secure Kafka connections, connectors of your own, and datasets of a size you choose | | [Storage and Tables](https://jaehyeon.me/desflow/latest/how-to/storage-and-tables/cloud-storage/index.md) | Parquet and JSON Lines files on S3, Google Cloud Storage and Azure Blob Storage, Iceberg tables through REST, SQL and Glue catalogs, and a run's records kept in memory as pyarrow tables | | [Analysis](https://jaehyeon.me/desflow/latest/how-to/analysis/fit-a-distribution/index.md) | distributions fitted to measured times, checks against the queueing formulas, tests for a model, and a run's event log, analysed and animated | | [Tools](https://jaehyeon.me/desflow/latest/how-to/tools/yaml-advanced/index.md) | Python logic in a blueprint, completion and checks for blueprints in an editor, and the fastest data generation | | [Gallery](https://jaehyeon.me/desflow/latest/gallery/index.md) | complete models and data sets to download and run: data sets and event streams, processes with queues, a local simulation, a Kafka digital twin, history written fast to Parquet or Iceberg, PostgreSQL, Redis, history then live records, and related records | # Vary Arrivals by Time Change the arrival rate and the staffing at set times, such as a rush at lunch or a second packer for an afternoon, and know exactly which events a change reaches. ______________________________________________________________________ ## Before You Start - [Changing Demand](https://jaehyeon.me/desflow/latest/learn/inputs/changing-demand/index.md) asks what a rush does to waits. - [Live Parameters](https://jaehyeon.me/desflow/latest/user-guide/live-runs-and-connectors/live-parameters/index.md) explains registry paths and scenario steps. ______________________________________________________________________ ## Steps ### Find the Path of Each Parameter Find the registry path of each parameter that changes: `Shop.arrival.orders.rate` for an exponential arrival, `Shop.resources.packers.current_cap` for the number of packers. ### Write One Step for Each Change Write one step for each change, with the simulation time it applies at, `at`, in seconds or as a duration such as `20 min`. The blueprint of the same name in [Changing Demand](https://jaehyeon.me/desflow/latest/learn/inputs/changing-demand/index.md) runs for an hour and packs in a constant 1.5 seconds. Its rush lasts from 20 to 40 minutes, with an order every 1.11 seconds on average (`rate: 0.9`). The example below, `examples/yaml/changing_demand.yaml`, runs for 5 minutes, and packing takes 1 to 3 seconds, most often 2 (a triangular distribution). From 120 to 180 seconds orders arrive twice as fast, an order every 1.25 seconds on average (`rate: 0.8`), and a second packer works for that time: ```yaml scenario: # The rush: twice the orders, and a second packer, from 120 to 180 seconds - {at: 120, path: Shop.arrival.orders.rate, value: 0.8} - {at: 120, path: Shop.resources.packers.current_cap, value: 2} - {at: 180, path: Shop.arrival.orders.rate, value: 0.4} - {at: 180, path: Shop.resources.packers.current_cap, value: 1} ``` ```python # The rush: twice the orders, and a second packer, from 120 to 180 seconds app.add_scenario( [ {"at": 120, "path": "Shop.arrival.orders.rate", "value": 0.8}, {"at": 120, "path": "Shop.resources.packers.current_cap", "value": 2}, {"at": 180, "path": "Shop.arrival.orders.rate", "value": 0.4}, {"at": 180, "path": "Shop.resources.packers.current_cap", "value": 1}, ] ) ``` `add_step(at, path=..., value=...)` adds one step. A step can also carry a `record`, a ground-truth label, an `interrupt`, or an `activate` or `deactivate` that turns an arrival on or off. ```python # The rush: twice the orders, and a second packer, from 120 to 180 seconds SCHEDULE = [ {"at": 120, "path": "Shop.arrival.orders.rate", "value": 0.8}, {"at": 120, "path": "Shop.resources.packers.current_cap", "value": 2}, {"at": 180, "path": "Shop.arrival.orders.rate", "value": 0.4}, {"at": 180, "path": "Shop.resources.packers.current_cap", "value": 1}, ] ``` `run_scenario(env, SCHEDULE, until=300)` is the SimPy process that applies the steps. Start it with `env.process`, beside the arrivals. ### Return Each Parameter to Its Usual Value Return each parameter to its usual value with a later step. A schedule does not repeat on its own. The example does it at 180 seconds. The steps change the registry, so everything that reads the path follows: the next arrival gap is drawn from the new rate, and the packers grant or owe units as on [Resources](https://jaehyeon.me/desflow/latest/user-guide/resources/units-and-queues/#under-live-changes). ______________________________________________________________________ ## Check the Result Run the `changing_demand` example below and read its statistics, published every 60 seconds. `Shop.stats.resources.packers.capacity` is 1 at 120 seconds, 2 at 180 seconds, and 1 again at 240 seconds, so the second packer worked from 120 to 180 seconds. The reading at 120 seconds still shows 1 because the packers apply a capacity change in a process of their own, which runs after the statistics reading due at that time. ### Boundaries A step that applies at the same time as another event has to come first or second, and a run that ends at a step's time has to apply it or not. Both are settled the way SimPy settles its own end time: - **A step at time t applies before every other event at t.** It is scheduled as an urgent event, as SimPy's `run(until=t)` is. So an arrival at t draws its next gap from the new value. - **Steps at the same time apply in the order written.** - **A step at or after `until` never applies,** as an event due at exactly `until` does not run. This shop has an order every 10 seconds, and a step at 30 seconds that makes the gap 5 seconds. The blueprint publishes an event as each order arrives, and the scripts collect the arrival times: ```yaml simulation: {sim_id: Shop, factor: 0} egress: - {type: Console} arrivals: orders: {dist: constant, value: 10 s, spawn: arrive} tasks: # No service and no resource: it publishes its payload as the order arrives arrive: payload: {event_type: order_arrived} scenario: - {at: 30 s, path: Shop.arrival.orders.value, value: 5} run: {until: 50 s} ``` ```python def arrivals(until: float) -> tuple: """Orders every 10 s, every 5 s from 30 s: the arrival times, and the gap in force at the end.""" app = ( SimulationContext("Shop", factor=0) .add_arrival("orders", dist="constant", value=10) .add_step(30, path="Shop.arrival.orders.value", value=5) ) times = [] @app.arrival_loop("orders") def order_loop(context): while True: yield context.wait_for_arrival("orders") times.append(context.env.now) app.run(until=until) return times, app.env.registry.get("Shop.arrival.orders.value").value ``` ```python def arrivals(until: float) -> tuple: """Orders every 10 s, every 5 s from 30 s: the arrival times, and the gap in force at the end.""" env = DynamicRealtimeEnvironment(factor=0) env.registry.register_sim_parameter( SimParameter( sim_id="Shop", arrival={"orders": DistributionConfig(dist="constant", value=10)}, ) ) sampler, times = Sampler(seed=1), [] def orders(): gap = env.registry.get_config("Shop.arrival.orders") while True: yield env.timeout(sampler.sample(gap)) times.append(env.now) steps = [{"at": 30, "path": "Shop.arrival.orders.value", "value": 5}] env.process(run_scenario(env, steps, until=until)) env.process(orders()) env.run(until=until) env.teardown() return times, env.registry.get("Shop.arrival.orders.value").value ``` `desflow run time_varying_arrivals.yaml` and `arrivals(50)` give arrivals at 10, 20, **30, 35**, 40 and 45 seconds, and the gap in force at the end is 5 seconds: the order that arrived at 30 drew its gap after the step. With `--until 30`, or `arrivals(30)`, the arrivals are at 10 and 20 seconds, and the gap in force at the end is 10 seconds. The step at 30 is at `until`, so it never applies. The arrival due at 30 never happens either. ______________________________________________________________________ ## Example The `changing_demand` example is the model above: one packer, an order every 2.5 seconds on average (`rate: 0.4`), and a rush with a second packer from 120 to 180 seconds. It needs no Docker service and ends on its own after 300 simulation seconds. **Quick Start** `desflow examples get` downloads the example at the release you install, into a folder of its own. Pick uv or pip: ```bash # 1. Install uv tool install desflow # 2. Download the example desflow examples get changing-demand --api yaml cd changing-demand/yaml # 3. Run it desflow run changing_demand.yaml ``` ```bash # 1. Install pip install desflow # 2. Download the example desflow examples get changing-demand --api yaml cd changing-demand/yaml # 3. Run it desflow run changing_demand.yaml ``` **Quick Start** `desflow examples get` downloads the example at the release you install, into a folder of its own. Pick uv or pip: ```bash # 1. Install uv tool install desflow # 2. Download the example desflow examples get changing-demand --api builder cd changing-demand/builder # 3. Run it uv run --no-project --with desflow changing_demand_example.py ``` ```bash # 1. Install pip install desflow # 2. Download the example desflow examples get changing-demand --api builder cd changing-demand/builder # 3. Run it python changing_demand_example.py ``` **Quick Start** `desflow examples get` downloads the example at the release you install, into a folder of its own. Pick uv or pip: ```bash # 1. Install uv tool install desflow # 2. Download the example desflow examples get changing-demand --api low-level cd changing-demand/low-level # 3. Run it uv run --no-project --with desflow changing_demand_example.py ``` ```bash # 1. Install pip install desflow # 2. Download the example desflow examples get changing-demand --api low-level cd changing-demand/low-level # 3. Run it python changing_demand_example.py ``` # Add Reneging and Balking Give a task a time limit on its wait, a condition that stops it joining at all, or both, and account for every entity afterwards. ______________________________________________________________________ ## Before You Start - [Patience](https://jaehyeon.me/desflow/latest/learn/shop-logic/patience/index.md) explains both ideas. - [Resources](https://jaehyeon.me/desflow/latest/user-guide/resources/#how-it-works) explains how a request is granted. ______________________________________________________________________ ## Steps ### Leave After a Wait and Refuse to Join Two settings let a task leave without being served: - **Reneging:** a task's `patience` is how long it may wait before it leaves the queue and publishes `reneged`. - **Balking:** a task's `balk` is a condition checked before it joins the queue. When the condition holds, the task publishes `balked` and never requests the resource. Patience covers the task's `wait`, then its resource and then its `get`. It counts waiting time only and pauses while the task is served, so a task that is preempted and queues again goes on with the time it has left. A get that gives up is cancelled, so it takes nothing later. Here each order brings its own patience as an attribute, which its arrival sets with `attributes:`, and no order joins after the courier's last collection at 100 seconds: ```yaml arrivals: orders: dist: exponential rate: 0.5 spawn: pack attributes: {patience: 20} walk_ins: dist: exponential rate: 0.1 spawn: pack attributes: {patience: 10} tasks: pack: service: packing resource: packers # Each order's own patience: it leaves the queue when it runs out. patience: attr.patience # No new orders once the courier has made its last collection. balk: t >= 100 payload: {event_type: order_packed} ``` ```python @app.task( service_id="packing", resource_id="packers", # Each order's own patience: it leaves the queue when it runs out patience="attr.patience", # No new orders once the courier has made its last collection balk="t >= 100", ) def pack(task_id, context): """Packs one order.""" return {"event_type": "order_packed"} ``` ```python def pack(env, sampler, packers, key, patience, task_id): """Balks after 100 s; otherwise waits at most `patience` for a packer.""" path_id = "Shop.service.packing" def publish(value): env.publish_event(key, value, task="pack", instance=task_id) flow = key.rsplit("-", 1)[0] env.stats.flow_started(flow) # the order enters the shop # No new orders once the courier has made its last collection if env.now >= 100: publish( { "path_id": path_id, "sim_id": "Shop", "service": "packing", "status": "balked", } ) env.stats.task_balked("pack", task_id) env.stats.flow_ended(flow) return publish( {"path_id": path_id, "sim_id": "Shop", "service": "packing", "status": "queued"} ) env.stats.task_queued("pack", task_id) with packers.request() as req: # Each order's own patience: it leaves the queue when it runs out result = yield req | env.timeout(patience) if req not in result: publish( { "path_id": path_id, "sim_id": "Shop", "service": "packing", "status": "reneged", } ) env.stats.task_reneged("pack", task_id) env.stats.flow_ended(flow) return publish( { "path_id": path_id, "sim_id": "Shop", "service": "packing", "status": "started", } ) env.stats.task_started("pack", task_id) yield env.timeout(sampler.sample(env.registry.get_config(path_id))) publish({"event_type": "order_packed"}) env.stats.task_finished("pack", task_id) env.stats.flow_finished(flow) ``` A low-level process writes both by hand: an `if` before the request, and SimPy's `result = yield request | env.timeout(patience)`, which resumes when either event is processed. `request not in result` tells that the patience came first. Leaving the `with` block takes a waiting request out of the queue at once, so it is never granted later. `patience` takes seconds, a duration such as `30 s`, an expression such as `attr.patience`, or in the builder a function of the task id and the entity's attributes. `balk` takes any condition an expression can write, such as `level.stock == 0`. ### Go On After Leaving An order that reneges or balks publishes `reneged` or `balked`, and its flow ends there. `on_renege` and `on_balk` name a task for it to go on to instead. `on_renege` needs `patience`, and `on_balk` needs `balk`, `resource`, `seize` or `open`. The task they name reads the status of the task the order left as `upstream.status`, which is `reneged` or `balked`, and the Builder takes both as arguments of `task`. One packer packs for 3 seconds and an order arrives every second, with a patience of 4 seconds. No order joins from 8 seconds on. Both ways of leaving go to the same task, `follow_up`, which records how the order left: ```yaml pack: service: packing resource: packers patience: 4 balk: t >= 8 # Where an order goes after it leaves the line, by reneging or by balking on_renege: follow_up on_balk: follow_up payload: {event_type: order_packed} follow_up: payload: event_type: order_left # reneged or balked: the status of the task the order came from how: {gen: expr, expr: upstream.status} ``` ```python @app.task( name="pack", service_id="packing", resource_id="packers", patience=4, balk="t >= 8", # Where an order goes after it leaves the line, by reneging or by balking on_renege="follow_up", on_balk="follow_up", ) def pack(task_id): """Packs one order.""" return {"event_type": "order_packed"} # reneged or balked: the status of the task the order came from follow_up_payload = Template( {"event_type": "order_left", "how": {"gen": "expr", "expr": "upstream.status"}}, name="tasks.follow_up", ) @app.task(name="follow_up") def follow_up(task_id): """Records how the order left the line.""" return follow_up_payload ``` ```python def follow_up(key, how): """Records how the order left the line.""" value = {"event_type": "order_left", "how": how} env.publish_event(key, value, task="follow_up", instance=sent["follow_up"]) sent["follow_up"] += 1 def pack(number): key = f"orders-{number}" if env.now >= 8: # balk: t >= 8 follow_up(key, "balked") return with packers.request() as unit: # SimPy's request | timeout: the patience is 4 seconds result = yield unit | env.timeout(4) if unit not in result: follow_up(key, "reneged") return yield env.timeout( sampler.sample(env.registry.get_config("Shop.service.packing")) ) env.publish_event( key, {"event_type": "order_packed"}, task="pack", instance=number - 1 ) ``` A low-level process has no `on_renege`. It calls the follow-up itself where it leaves the line, and `follow_up` publishes the record. Of the 12 orders, 4 are packed (1, 2, 4 and 7), 3 renege (3, 5 and 6) and 5 balk (8 to 12). Each of the 8 that leave publishes an `order_left` record from `follow_up` with its `how`. Run the YAML file from the root of a clone of the repository and keep the records of `follow_up`: ```bash git clone https://github.com/jaehyeon-kim/desflow.git cd desflow desflow run docs/snippets/yaml/reneging_follow_up.yaml --sample 100 | grep order_left ``` It prints one record for each of the 8 orders that left, with the order's key and its `how` after the time it left: ```text {"stream_type":"event","sim_ts":7.0,"timestamp":"...","key":"orders-3","task":"follow_up","instance":0,"value":{"event_type":"order_left","how":"reneged"}} {"stream_type":"event","sim_ts":8.0,"timestamp":"...","key":"orders-8","task":"follow_up","instance":1,"value":{"event_type":"order_left","how":"balked"}} {"stream_type":"event","sim_ts":9.0,"timestamp":"...","key":"orders-9","task":"follow_up","instance":2,"value":{"event_type":"order_left","how":"balked"}} {"stream_type":"event","sim_ts":9.0,"timestamp":"...","key":"orders-5","task":"follow_up","instance":3,"value":{"event_type":"order_left","how":"reneged"}} {"stream_type":"event","sim_ts":10.0,"timestamp":"...","key":"orders-10","task":"follow_up","instance":4,"value":{"event_type":"order_left","how":"balked"}} {"stream_type":"event","sim_ts":10.0,"timestamp":"...","key":"orders-6","task":"follow_up","instance":5,"value":{"event_type":"order_left","how":"reneged"}} {"stream_type":"event","sim_ts":11.0,"timestamp":"...","key":"orders-11","task":"follow_up","instance":6,"value":{"event_type":"order_left","how":"balked"}} {"stream_type":"event","sim_ts":12.0,"timestamp":"...","key":"orders-12","task":"follow_up","instance":7,"value":{"event_type":"order_left","how":"balked"}} ``` The Builder and Low-level scripts, `reneging_follow_up.py` and `reneging_follow_up_low_level.py`, publish the same records, which a test checks. ### Settle a Tie Between a Grant and a Patience A unit can come free at the same instant a waiting order's patience runs out. Plain SimPy settles this with no rule of its own: the wait ends with whichever event is processed first, and the order is served only when its request is in the result. The unit is granted by an event that the holder's release schedules at the instant of the release. The patience's timeout was scheduled when the order began to wait, so it comes first. desflow grants units with the same events SimPy uses, so it gives the same answer: - an order that arrived at 3 with a patience of 3, while the holder started at 0 with 6 seconds of service, reneges at 6; - an order that arrived at 0 with a patience of 6, just after the holder, reneges at 6 as well; - an order that arrived at 3 with a patience of 4 is served, because the unit is granted at 6 and the patience ends at 7. Each form runs both from one script, `check_reneging.py`, made of the blocks in this section and the next, in order. It starts with the imports of the standard library and a class that keeps every record the model publishes. The imports of desflow follow the class, in the line `from desflow import CapacityConfig, DynamicRealtimeEnvironment, DynamicResource, Sampler, SimParameter, SimulationContext`: ```python import asyncio import importlib.util import queue import shutil import tempfile from collections import Counter from pathlib import Path class Capture: """An egress that keeps every record it receives.""" def __init__(self): self.records = [] async def run(self, egress_queue): try: while True: try: self.records.extend(egress_queue.get_nowait()) except queue.Empty: await asyncio.sleep(0.005) except asyncio.CancelledError: pass ``` The function `_outcome` tells what the order did, from the records of its `pack` task: ```python def _outcome(records: list) -> str: """What the order did: reneged if any record of its pack task says so.""" statuses = [ r["value"].get("status") for r in records if r["stream_type"] == "event" and r["task"] == "pack" ] return "reneged" if "reneged" in statuses else "served" ``` The YAML form replays the two arrivals at their times from CSV files. Save its blueprint as `reneging_tie.yaml` beside the script: ```yaml simulation: {sim_id: Shop, factor: 0} resources: packers: {current_cap: 1, max_cap: 1} services: hold: {dist: constant, value: 6} packing: {dist: constant, value: 1} arrivals: holders: replay: {path: holders.csv} spawn: holder orders: replay: {path: orders.csv} spawn: pack tasks: holder: service: hold resource: packers payload: {event_type: held} pack: service: packing resource: packers patience: attr.patience # from the patience column of orders.csv payload: {event_type: order_packed} run: {until: 8} ``` `tie_yaml` replays the holder at 0 and the order from CSV files beside the blueprint: ```python def tie_yaml( waiter_at: float, patience: float, blueprint: str = "reneging_tie.yaml", ) -> str: """The same, with the blueprint and the two arrivals replayed from CSV files.""" with tempfile.TemporaryDirectory() as tmp: folder = Path(tmp) shutil.copy(blueprint, folder / "reneging_tie.yaml") (folder / "holders.csv").write_text("time\n0\n") (folder / "orders.csv").write_text(f"time,patience\n{waiter_at},{patience}\n") app = SimulationContext.from_yaml(folder / "reneging_tie.yaml") capture = Capture() app.add_egress(capture) app.run() # until 8, from the blueprint return _outcome(capture.records) ``` ```python def tie(waiter_at: float, patience: float) -> str: """The outcome of an order whose patience may end when the packer comes free.""" app = SimulationContext("Shop", factor=0) app.add_resource("packers", current_cap=1, max_cap=1) app.add_service("hold", dist="constant", value=6) app.add_service("packing", dist="constant", value=1) capture = Capture() app.add_egress(capture) @app.task(service_id="hold", resource_id="packers") def holder(task_id): return {"event_type": "held"} @app.task(service_id="packing", resource_id="packers", patience=patience) def pack(task_id): return {"event_type": "order_packed"} def script(context): context.spawn(holder(0)) # takes the packer at 0 and keeps it until 6 if waiter_at: yield context.env.timeout(waiter_at) context.spawn(pack(0)) yield context.env.timeout(0) app.add_process(script) app.run(until=8) return _outcome(capture.records) ``` ```python def tie_low_level(waiter_at: float, patience: float) -> str: """The same, with SimPy's request | timeout.""" env = DynamicRealtimeEnvironment(factor=0) env.registry.register_sim_parameter( SimParameter( sim_id="Shop", resources={"packers": CapacityConfig(current_cap=1, max_cap=1)}, ) ) capture = Capture() env.setup_egress([capture]) packers = DynamicResource(env, "Shop", "packers") def holder(): with packers.request() as unit: yield unit yield env.timeout(6) # keeps the packer until 6 def pack(): if waiter_at: # at 0, its patience starts before the holder's service yield env.timeout(waiter_at) with packers.request() as unit: result = yield unit | env.timeout(patience) if unit not in result: env.publish_event("orders-1", {"status": "reneged"}, "pack", 0) return yield env.timeout(1) env.publish_event("orders-1", {"event_type": "order_packed"}, "pack", 0) env.process(holder()) env.process(pack()) env.run(until=8) env.teardown() return _outcome(capture.records) ``` In each form, an order arriving at 3 with a patience of 3, or at 0 with a patience of 6, reneges, and one arriving at 3 with a patience of 4 is served. A model that must not depend on this order can avoid exact ties, for example by drawing patience from a distribution. ______________________________________________________________________ ## Check the Result Every order that arrives ends in one of four places: packed, reneged, balked, or still in the shop when the run ends, waiting (`queued`) or being packed (`started`). The last event of each entity key says which. With statistics at `basic` or above, the `finished`, `reneged` and `balked` counts must match those events. This function checks them, and is the same for every form: ```python def balance(records: list, stats: dict) -> Counter: """Every order that arrived, by what became of it.""" last = {} for record in records: if record["stream_type"] == "event": value = record["value"] last[record["key"]] = value.get("status", value.get("event_type")) outcome = Counter(last.values()) # queued or started: still in the shop when the run ended name = "Shop.stats.tasks.pack.{}".format assert outcome["order_packed"] == stats[name("finished")] assert outcome["reneged"] == stats.get(name("reneged"), 0) assert outcome["balked"] == stats.get(name("balked"), 0) return outcome ``` Each form runs the example below for 120 seconds with a capturing egress, and passes what it captured to `balance`. Run `desflow examples get patience` in the folder of the script first. The forms read the example from `patience/yaml/`, `patience/builder/` and `patience/low-level/`, and a function loads an example file without running it: ```python def _example(path: str): """Loads an example script as a module, without running it.""" spec = importlib.util.spec_from_file_location("patience_example", path) assert spec is not None and spec.loader is not None module = importlib.util.module_from_spec(spec) spec.loader.exec_module(module) return module ``` ```python def yaml_form(path: str = "patience/yaml/patience.yaml") -> Counter: app = SimulationContext.from_yaml(path) capture = Capture() app.add_egress(capture) app.run() # until 120, from the blueprint return balance(capture.records, app.env.stats.readings()) ``` ```python def builder_form(path: str = "patience/builder/patience_example.py") -> Counter: app = _example(path).app capture = Capture() app.add_egress(capture) app.run(until=120) return balance(capture.records, app.env.stats.readings()) ``` ```python def low_level_form(path: str = "patience/low-level/patience_example.py") -> Counter: example = _example(path) env = DynamicRealtimeEnvironment(factor=0) env.registry.register_sim_parameter(example.PARAMS) capture = Capture() env.setup_egress([capture]) env.setup_stats("Shop", "basic", interval=30.0) packers = example.build(env) for process in example.processes(env, Sampler(seed=42), packers): env.process(process) env.run(until=120) env.teardown() # publishes the last statistics and flushes the capture return balance(capture.records, env.stats.readings()) ``` Last, the script prints the results of the ties and of the three forms. The example also prints its events, so keep the lines that start with `check:`: ```python if __name__ == "__main__": print("check: arrives at 3, patience 3:", tie(3, 3)) print("check: arrives at 0, patience 6:", tie(0, 6)) print("check: arrives at 3, patience 4:", tie(3, 4)) print("check: the same in YAML:", tie_yaml(3, 3), tie_yaml(0, 6), tie_yaml(3, 4)) print( "check: the same, low-level:", tie_low_level(3, 3), tie_low_level(0, 6), tie_low_level(3, 4), ) for form in (yaml_form, builder_form, low_level_form): print("check:", dict(form())) ``` ```bash # With uv uv run --no-project --with desflow check_reneging.py | grep "^check:" # With pip pip install desflow python check_reneging.py | grep "^check:" ``` ```text check: arrives at 3, patience 3: reneged check: arrives at 0, patience 6: reneged check: arrives at 3, patience 4: served check: the same in YAML: reneged reneged served check: the same, low-level: reneged reneged served check: {'order_packed': 51, 'reneged': 13, 'balked': 5} check: {'order_packed': 51, 'reneged': 13, 'balked': 5} check: {'order_packed': 51, 'reneged': 13, 'balked': 5} ``` Each form returns 51 packed, 13 reneged and 5 balked, 69 orders in all, and no order is still in the shop. A mean wait counts only the orders that were served, so report the reneged and balked counts beside it. ______________________________________________________________________ ## Example The `patience` example is the model above: one packer, online orders with a patience of 20 seconds and walk-in orders with 10, and no new orders from 100 seconds. It needs no Docker service and ends on its own after 120 simulation seconds. **Quick Start** `desflow examples get` downloads the example at the release you install, into a folder of its own. Pick uv or pip: ```bash # 1. Install uv tool install desflow # 2. Download the example desflow examples get patience --api yaml cd patience/yaml # 3. Run it desflow run patience.yaml ``` ```bash # 1. Install pip install desflow # 2. Download the example desflow examples get patience --api yaml cd patience/yaml # 3. Run it desflow run patience.yaml ``` **Quick Start** `desflow examples get` downloads the example at the release you install, into a folder of its own. Pick uv or pip: ```bash # 1. Install uv tool install desflow # 2. Download the example desflow examples get patience --api builder cd patience/builder # 3. Run it uv run --no-project --with desflow patience_example.py ``` ```bash # 1. Install pip install desflow # 2. Download the example desflow examples get patience --api builder cd patience/builder # 3. Run it python patience_example.py ``` **Quick Start** `desflow examples get` downloads the example at the release you install, into a folder of its own. Pick uv or pip: ```bash # 1. Install uv tool install desflow # 2. Download the example desflow examples get patience --api low-level cd patience/low-level # 3. Run it uv run --no-project --with desflow patience_example.py ``` ```bash # 1. Install pip install desflow # 2. Download the example desflow examples get patience --api low-level cd patience/low-level # 3. Run it python patience_example.py ``` # Wait for One or All Make a task wait for the first of several things, or for all of them, and read which happened. ______________________________________________________________________ ## Before You Start - [Process Interaction](https://jaehyeon.me/desflow/latest/learn/shop-logic/process-interaction/index.md) introduces signals and a wait with a limit. - [Signals and Waiting](https://jaehyeon.me/desflow/latest/user-guide/tasks-and-processes/signals-and-waiting/#wait-signals-and-child-flows) lists every kind of branch. ______________________________________________________________________ ## Steps The Builder and YAML blocks in the steps are functions of one script, `wait_for_one_or_all.py`, in the order the blocks appear. Its start, which the functions share, is below. The line `from desflow import Entity, SimulationContext` follows it, and `_shop` is the first function of the first Builder block: ```python import asyncio import queue import shutil import tempfile from pathlib import Path class Capture: """An egress that keeps every event it receives.""" def __init__(self): self.events = [] async def run(self, egress_queue): try: while True: try: batch = egress_queue.get_nowait() self.events += [r for r in batch if r["stream_type"] == "event"] except queue.Empty: await asyncio.sleep(0.005) except asyncio.CancelledError: pass def _events(task: str, capture: Capture) -> list: return [e for e in capture.events if e["task"] == task] ``` The YAML blocks read their files from the folder of the script. Save each blueprint under the name in its title, `wait_first.yaml`, `wait_tie.yaml`, `wait_all.yaml`, `wait_suspend.yaml`, `wait_each.yaml` and `wait_pool.yaml`. The Low-level blocks are functions of a second script, `wait_for_one_or_all_low_level.py`, which [Check the Result](#check-the-result) completes. ### Wait for the First `wait: {any: {...}}` ends when the first branch happens, as SimPy's `AnyOf` (`a | b`) does. Name each branch. After the wait, `wait..done` says which happened. Here an order waits for a restock or 30 seconds. A builder function that declares `wait` reads the branches. A blueprint's payload reads `wait..done` in a `gen: expr` field: ```yaml simulation: {sim_id: Shop, factor: 0} signals: [restocked] arrivals: orders: replay: {path: orders.csv} spawn: order restocks: replay: {path: restocks.csv} spawn: restock tasks: order: wait: any: stock: {signal: restocked} limit: {timeout: 30} # wait..done is true for each branch that was done when the wait ended payload: event_type: resumed done: stock: {gen: expr, expr: wait.stock.done} limit: {gen: expr, expr: wait.limit.done} restock: signal: restocked payload: {boxes: 6} run: {until: 60} ``` `first_yaml(gap)` replays the order at 0 and the restock at `gap` from CSV files: ```python def run_blueprint(blueprint: Path, arrivals: dict) -> Capture: """Runs a blueprint with its arrivals replayed from CSV files beside it. `arrivals` maps each file to its rows, such as {"orders.csv": "time\\n0\\n"}. """ with tempfile.TemporaryDirectory() as tmp: folder = Path(tmp) shutil.copy(blueprint, folder) for file, rows in arrivals.items(): (folder / file).write_text(rows) app = SimulationContext.from_yaml(folder / blueprint.name) capture = Capture() app.add_egress(capture) app.run() # until the blueprint's run.until return capture def first_yaml(gap: float, blueprint="wait_first.yaml") -> dict: capture = run_blueprint( Path(blueprint), {"orders.csv": "time\n0\n", "restocks.csv": f"time\n{gap}\n"}, ) return _events("order", capture)[-1]["value"]["done"] def two_at_once_yaml(blueprint="wait_tie.yaml") -> dict: capture = run_blueprint( Path(blueprint), { "orders.csv": "time\n0\n", "boxes.csv": "time\n5\n", "labels.csv": "time\n5\n", }, ) return _events("order", capture)[-1]["value"]["done"] def all_with_a_failure_yaml(blueprint="wait_all.yaml") -> list: capture = run_blueprint( Path(blueprint), {"orders.csv": "time\n0\n", "restocks.csv": "time,broken\n2,1\n"}, ) return [ (e["sim_ts"], e["task"], e["value"].get("status", "finished")) for e in capture.events if e["task"] in ("order", "inspect") and e["value"].get("status") != "started" ] def suspend_and_resume_yaml(blueprint="wait_suspend.yaml") -> list: capture = run_blueprint(Path(blueprint), {}) return [ (e["sim_ts"], e["value"]["by"]) for e in _events("hold", capture) if e["value"].get("event_type") == "released" ] def each_of_three_yaml(blueprint="wait_each.yaml") -> tuple: packed = _events("order", run_blueprint(Path(blueprint), {}))[-1] return packed["sim_ts"], packed["value"]["flags"] def _pool_result(capture: Capture) -> tuple: """(time the order is packed, its granted flags, time the next order is packed), with None for a record that never comes.""" packed = [e for e in _events("order", capture) if "granted" in e["value"]] late = [e for e in _events("late_order", capture) if "event_type" in e["value"]] return ( packed[0]["sim_ts"], packed[0]["value"]["granted"], late[0]["sim_ts"] if late else None, ) def pool_of_requests_yaml(blueprint="wait_pool.yaml") -> tuple: return _pool_result(run_blueprint(Path(blueprint), {})) ``` ```python def _shop(): app = SimulationContext("Shop", factor=0) capture = Capture() app.add_egress(capture) return app, capture def first(gap: float) -> dict: """Which branches were done when the order's wait ended.""" app, capture = _shop() app.add_signal("restocked") seen = {} @app.task( wait={"any": {"stock": {"signal": "restocked"}, "limit": {"timeout": 30}}} ) def order(task_id, wait): # `wait` holds each branch's done, ok and value seen.update({name: branch["done"] for name, branch in wait.items()}) return {"event_type": "resumed"} @app.task(signal="restocked") def restock(task_id): return {"boxes": 6} def script(context): context.spawn(order(0)) yield context.env.timeout(gap) context.spawn(restock(0)) app.add_process(script) app.run(until=60) return seen ``` ```python def first(gap: float) -> dict: """Which branches were done when the order's wait ended.""" env = DynamicRealtimeEnvironment(factor=0) restocked = Signal(env, "restocked") seen = {} def order(): branches = {"stock": restocked.wait(), "limit": env.timeout(30)} done = yield env.any_of(list(branches.values())) # The value of AnyOf holds the events that had happened seen.update({name: event in done for name, event in branches.items()}) def restock(): yield env.timeout(gap) restocked.fire({"boxes": 6}) env.process(order()) env.process(restock()) env.run(until=60) env.teardown() return seen ``` With the restock at 10 seconds, every form returns `{"stock": True, "limit": False}`: the restock came first. With the restock at 50 seconds, it returns `{"stock": False, "limit": True}`. To route on the branch that happened, give the task a `next` with `condition: wait.stock.done`, as the [example](#check-the-result) does. When an `any` wait ends, its losing branches are cleaned up: a signal, timeout or condition branch is dropped, so it does nothing later. A losing child flow (`{task: name}`) keeps running to its end, as SimPy leaves a process running when nothing waits for it. ### Read Both Branches When They Tie Two branches can happen at the same simulation time. SimPy's `AnyOf` holds every event processed before the `AnyOf` itself, so both are in its value, and desflow reports both as done: ```yaml simulation: {sim_id: Shop, factor: 0} signals: [boxes, labels] arrivals: orders: replay: {path: orders.csv} spawn: order box_deliveries: replay: {path: boxes.csv} spawn: deliver_boxes label_deliveries: replay: {path: labels.csv} spawn: deliver_labels tasks: order: wait: any: boxes: {signal: boxes} labels: {signal: labels} payload: event_type: resumed done: boxes: {gen: expr, expr: wait.boxes.done} labels: {gen: expr, expr: wait.labels.done} deliver_boxes: signal: boxes payload: {item: boxes} deliver_labels: signal: labels payload: {item: labels} run: {until: 10} ``` `two_at_once_yaml()` runs it with `run_blueprint`, as `first_yaml` does. ```python def two_at_once() -> dict: """Two signals fire at the same instant: both branches are done.""" app, capture = _shop() app.add_signal("boxes").add_signal("labels") seen = {} @app.task( wait={"any": {"boxes": {"signal": "boxes"}, "labels": {"signal": "labels"}}} ) def order(task_id, wait): seen.update({name: branch["done"] for name, branch in wait.items()}) return {"event_type": "resumed"} @app.task(signal="boxes") def deliver_boxes(task_id): return {"item": "boxes"} @app.task(signal="labels") def deliver_labels(task_id): return {"item": "labels"} def script(context): context.spawn(order(0)) yield context.env.timeout(5) context.spawn(deliver_boxes(0)) context.spawn(deliver_labels(0)) app.add_process(script) app.run(until=10) return seen ``` ```python def two_at_once() -> dict: """Two signals fire at the same instant: both branches are done.""" env = DynamicRealtimeEnvironment(factor=0) boxes, labels = Signal(env, "boxes"), Signal(env, "labels") seen = {} def order(): branches = {"boxes": boxes.wait(), "labels": labels.wait()} done = yield env.any_of(list(branches.values())) seen.update({name: event in done for name, event in branches.items()}) def deliver(): yield env.timeout(5) boxes.fire({"item": "boxes"}) labels.fire({"item": "labels"}) env.process(order()) env.process(deliver()) env.run(until=10) env.teardown() return seen ``` Every form returns `{"boxes": True, "labels": True}`. A model that routes on one branch should therefore check that branch, not assume that only one is done. ### Wait for All `wait: {all: {...}}` ends when every branch has happened, as SimPy's `AllOf` (`a & b`) does. If a branch fails first, the wait fails at once, with that branch's reason, and the task publishes `failed`. Branches still pending are cleaned up as for `any`, so a child flow runs on. Here the restock fails at 2 while the inspection, a child flow, runs until 4: ```yaml simulation: {sim_id: Shop, factor: 0} signals: [restocked] services: inspecting: {dist: constant, value: 4} arrivals: orders: replay: {path: orders.csv} spawn: order restocks: replay: {path: restocks.csv} spawn: restock tasks: order: wait: all: stock: {signal: restocked} check: {task: inspect} payload: {event_type: resumed} inspect: service: inspecting payload: {event_type: inspected} restock: signal: restocked fail: attr.broken == 1 # from the broken column of restocks.csv fail_reason: broken delivery payload: {boxes: 6} run: {until: 10, on_unhandled_failure: continue} ``` `all_with_a_failure_yaml()` runs it with `run_blueprint`, with the restock at 2 marked broken in its CSV file. ```python def all_with_a_failure() -> list: """(time, task, status) of the order and its inspection: the restock fails at 2, the order fails at once, and the inspection, still running, ends at 4.""" app, capture = _shop() app.add_signal("restocked") app.add_service("inspecting", dist="constant", value=4) @app.task( wait={"all": {"stock": {"signal": "restocked"}, "check": {"task": "inspect"}}} ) def order(task_id): return {"event_type": "resumed"} @app.task(service_id="inspecting") def inspect(task_id): return {"event_type": "inspected"} @app.task( signal="restocked", fail="attr.broken == 1", fail_reason="broken delivery" ) def restock(task_id): return {"boxes": 6} def script(context): context.spawn(order(0)) yield context.env.timeout(2) delivery = Entity("restocks-1", "restocks", {"broken": 1}) context.spawn(restock(0, entity=delivery)) app.add_process(script) app.run(until=10, on_unhandled_failure="continue") return [ (e["sim_ts"], e["task"], e["value"].get("status", "finished")) for e in capture.events if e["task"] in ("order", "inspect") and e["value"].get("status") != "started" ] ``` ```python def all_with_a_failure() -> list: """(time, task, status) of the order and its inspection: the restock fails at 2, the order fails at once, and the inspection, still running, ends at 4.""" env = DynamicRealtimeEnvironment(factor=0) restocked = Signal(env, "restocked") seen = [] def inspect(): yield env.timeout(4) seen.append((env.now, "inspect", "finished")) def order(): seen.append((env.now, "order", "queued")) try: yield env.all_of([restocked.wait(), env.process(inspect())]) except SignalFailed: # A failed branch fails the AllOf at once; the inspection runs on seen.append((env.now, "order", "failed")) def restock(): yield env.timeout(2) restocked.fail("broken delivery") env.process(order()) env.process(restock()) env.run(until=10) env.teardown() return seen ``` Every form returns `[(0.0, "order", "queued"), (2.0, "order", "failed"), (4.0, "inspect", "finished")]`. The order's failure goes to its `on_fail` task when it has one, and otherwise ends its flow. `on_fail` needs no `fail` condition: a failed wait is enough to send the task there. A step or an expression of the task that cannot run, such as a `service_time`, a payload field or a `gen: expr`, fails the task in the same way. The task that `on_fail` names reads `upstream.status`, which is `failed`, and `upstream.reason`. In the low-level form, the failed signal raises `SignalFailed` in the order. The restock's failure is one that no task handles, and a run stops at the first such failure unless `run.on_unhandled_failure` is `continue`. The blueprint sets `run: {until: 10, on_unhandled_failure: continue}`, and the Builder passes `on_unhandled_failure="continue"` to `run`. The low-level form needs no setting, because the order catches `SignalFailed`. A wait for signals, tasks and times never holds a resource. Waiting for all of several things that each free up a resource does not grant the resources together: the task asks for its resource only after the wait, and another task can take the unit in between. To hold several resources at once, list them on the task, `resource: [picker, bench]`, as [Several Resources](https://jaehyeon.me/desflow/latest/user-guide/resources/several-resources/#several-resources) describes. ### Nest Any and All A branch of an `any` or an `all` may itself be an `any` or an `all`, so a wait nests to any depth. This wait is done when the invoice is printed and either two boxes are taken or 5 seconds pass: ```yaml # Go on once the invoice is printed and either two boxes are taken or 5 seconds pass wait: all: invoice: {timeout: 4 s} either: any: boxes: get: {container: boxes, amount: 2} limit: {timeout: 5 s} ``` `@app.task(wait=...)` takes the same mapping as a dict. The low-level form is `yield (boxes | limit) & invoice`. Each branch name in the tree is unique. `wait.` reads any node, whether a group or a leaf. For example, `wait.either.done` is true once the inner `any` is done, and `wait.either.value` maps its done leaves to their values. ### Wait for Some of Them `wait: {at_least: 2, of: {a: ..., b: ..., c: ...}}` is done when at least two of its branches are done. SimPy's `Condition` with a count rule does the same. `at_least` is a whole number of 1 or more, and an `at_least` above the number of branches is refused when the file loads. An empty `of` succeeds at once, whatever the count. In a blueprint, an order waits for both its label and its invoice: ```yaml # Go on once both the label and the invoice are printed wait: all: label: {timeout: 2 s} invoice: {timeout: 4 s} ``` `@app.task(wait=...)` takes the same mapping as a dict. The low-level form is `yield env.all_of([label, invoice])`, SimPy's `AllOf`. It then waits for two of three checks: ```yaml # Go on once two of the three checks have answered wait: at_least: 2 of: stock: {timeout: 1 s} payment: {timeout: 3 s} address: {timeout: 6 s} ``` `@app.task(wait=...)` takes the same mapping as a dict. The low-level form is `Condition(env, lambda events, count: count >= 2, [a, b, c])`. `wait: {when: , of: {...}}` is done when the expression holds. It is read each time a branch of `of` is processed, and once at the start for a branch that is processed already, as SimPy's `Condition(env, evaluate, events)` does. It reads `wait..done`, `.ok` and `.value` of each branch, and `done_count`. A branch that fails fails the wait, and an empty `of` succeeds at once. ```yaml # Go on when the expression holds, read each time a branch is processed wait: when: done_count >= 2 and wait.stock.done of: stock: {timeout: 1 s} payment: {timeout: 3 s} address: {timeout: 6 s} ``` `@app.task(wait=...)` takes the same mapping as a dict. The low-level form is a `Condition` whose function reads the count and the events, as above. The wait ends at 3 seconds, when the payment is the second branch done and the stock is one of them. The address check, which takes 6 seconds, is not done. ### Wait for a Unit, an Item or Room A branch may also be a resource `request`, a store or container `get`, or a `put`. A task can then wait for the first of a unit, an item, a signal or a time. A branch of each kind does this when it wins: - A `request` holds its unit through the task's service and gives it back when the task ends, as a listed `resource` does. Its `wait..value` is the request. - A `get` takes an item, and `wait..value` is that item. - A `put` adds the payload of the task before it, or `None` for the first task of a flow. A single branch is named after its resource for a `request`, and `get` or `put` otherwise. An `any` ends when its first branch is granted. Only a branch processed before the wait ended is won. A request, get or put granted at the same instant, after the wait's condition was processed, is not won: the item of a get is lost, and the unit of a request stays with the task and goes back when the task ends. A request not yet granted is cancelled, so it holds nothing. An interrupt with `on_interrupt: restart` during the wait starts the branches again. A `request` branch that holds its unit keeps it, and the other branches start again. A `request` branch that is still queued keeps its place in the line under `resume` and asks again at the back under `restart`. A unit granted at the instant of the interrupt stays held. An item a get already took is used by neither the old nor the new branch, because SimPy cannot put a taken item back. This wait is for a packer or a time limit, and gives up the packer request if the limit comes first: ```yaml # A packer asked for with priority 1 and without taking the unit from another order, # or give up after 30 seconds; a packer won is held through packing wait: any: unit: request: {resource: packers, priority: 1, preempt: false} limit: {timeout: 30 s} ``` `@app.task(wait=...)` takes the same mapping as a dict. The low-level form is `yield unit | env.timeout(30)`, as [Add Reneging and Balking](https://jaehyeon.me/desflow/latest/how-to/modelling/reneging-and-balking/#leave-after-a-wait-and-refuse-to-join) does. A `get` branch with a time limit, whose `value` says why the wait ended: ```yaml # Two boxes, or go on without them after 5 seconds with the value "no boxes" wait: any: boxes: get: {container: boxes, amount: 2} limit: timeout: {after: 5 s, value: no boxes} ``` `@app.task(wait=...)` takes the same mapping as a dict. The low-level form is `yield boxes.get(2) | env.timeout(5)`. A `put` branch on its own: ```yaml # Put the closed order's payload on the shelf, waiting while the shelf is full wait: put: {store: shelf} ``` `@app.task(wait=...)` takes the same mapping as a dict. The low-level form is `yield shelf.put(item)`. Requests in a wait count in the [order of acquisition](https://jaehyeon.me/desflow/latest/user-guide/resources/several-resources/#several-resources): they come before the task's `resource` list. How a wait makes its requests depends on the group: - Under an `all`, or an `at_least` of 2 or more, the requests are made together. The first one granted is held while the others are waited for, so no other task can acquire two of them one after the other, in either order. - A single `request` branch of an `any` holds nothing while the `any` waits, and ends the `any` when it is granted. So such branches set no order. - A group branch of an `any`, such as an `all` of two requests, can hold a unit before the `any` is won. So its requests are made together with those of the other branches. A model whose tasks acquire two resources in opposite orders loads and logs one WARNING, and a `seize` counts as holding. A task that keeps a resource for a next task that requests it in its wait is still refused when the model is built, because the request would wait behind the unit kept for it. ### Park a Task Until Another Resumes It `wait: {suspend: true}` parks the task until a `resume` of another task wakes it. The rules of `resume` and of an interrupt that reaches a parked task are in [Park a Task Until Another Resumes It](https://jaehyeon.me/desflow/latest/user-guide/tasks-and-processes/signals-and-waiting/#park-a-task-until-another-resumes-it). Here three orders park, at 1, 2 and 3 seconds, and a truck at 5 seconds wakes the two oldest: ```yaml simulation: {sim_id: Shop, factor: 0} arrivals: orders: {dist: constant, value: 1, max_events: 3, spawn: hold} trucks: {dist: constant, value: 5, first_at: 5, max_events: 1, spawn: unload} tasks: # Parks until a resume wakes it; wait.suspend.value is the value of that resume hold: wait: {suspend: true} payload: event_type: released by: {gen: expr, expr: wait.suspend.value} # Wakes the two oldest parked orders; the third stays parked unload: resume: {task: hold, limit: 2, value: truck-1} payload: {event_type: unloaded} run: {until: 10} ``` ```python def suspend_and_resume() -> list: """(time, value) of each order a truck woke: it wakes the two oldest of three.""" app, capture = _shop() woken = [] @app.task(wait={"suspend": True}) def hold(task_id, wait): # wait["suspend"]["value"] is the value of the resume that woke the order woken.append((float(app.env.now), wait["suspend"]["value"])) return {"event_type": "released"} @app.task(resume={"task": "hold", "limit": 2, "value": "truck-1"}) def unload(task_id): return {"event_type": "unloaded"} def script(context): for number in range(3): yield context.env.timeout(1) context.spawn(hold(number)) yield context.env.timeout(2) context.spawn(unload(0)) app.add_process(script) app.run(until=10) return woken ``` ```python def suspend_and_resume() -> list: """(time, value) of each order a truck woke: it wakes the two oldest of three.""" env = DynamicRealtimeEnvironment(factor=0) parked = [] # the event each parked order waits for, oldest first woken = [] def hold(): wake = env.event() parked.append(wake) value = yield wake # the value of the succeed() that wakes it woken.append((env.now, value)) def orders(): for _ in range(3): yield env.timeout(1) env.process(hold()) def truck(): yield env.timeout(5) for wake in parked[:2]: # the oldest first wake.succeed("truck-1") env.process(orders()) env.process(truck()) env.run(until=10) env.teardown() return woken ``` Every form wakes the first two orders at 5 seconds, with the value `truck-1`. The third stays parked until the run ends. The low-level form is SimPy's `event.succeed(value)` on the event that each process waits for. ### Wait for a Computed Number of Branches `wait: {each: ..., group: ..., branch: ...}` makes the same `branch` once for each element of `each`, when the wait starts. The rules of `each`, `group` and `branch` are in [Wait for a Computed Number of Branches](https://jaehyeon.me/desflow/latest/user-guide/tasks-and-processes/signals-and-waiting/#wait-for-a-computed-number-of-branches). Here an order packs three boxes of 2, 5 and 9 seconds, and goes on when two are packed: ```yaml simulation: {sim_id: Shop, factor: 0} arrivals: orders: {initial: 1, spawn: order} tasks: order: wait: all: boxes: each: [2, 5, 9] # one branch for each element group: {at_least: 2} # done when two branches are branch: # each.value is the element timeout: {after: each.value} payload: event_type: packed flags: {gen: expr, expr: wait.boxes.flags} # which branches were done run: {until: 30} ``` ```python def each_of_three() -> tuple: """(time, flags) of an order that packs three boxes, of 2, 5 and 9 seconds, and goes on when two are packed.""" app, capture = _shop() seen = {} @app.task( wait={ "all": { "boxes": { "each": [2, 5, 9], "group": {"at_least": 2}, "branch": {"timeout": {"after": "each.value"}}, } } } ) def order(task_id, wait): seen["done"] = (float(app.env.now), wait["boxes"]["flags"]) return {"event_type": "packed"} def script(context): context.spawn(order(0)) yield context.env.timeout(0) app.add_process(script) app.run(until=30) return seen["done"] ``` ```python from simpy.events import Condition def each_of_three() -> tuple: """(time, flags) of an order that packs three boxes, of 2, 5 and 9 seconds, and goes on when two are packed.""" env = DynamicRealtimeEnvironment(factor=0) seen = {} def order(): boxes = [env.timeout(seconds) for seconds in (2, 5, 9)] done = yield Condition(env, lambda events, count: count >= 2, boxes) seen["done"] = (env.now, [box in done for box in boxes]) env.process(order()) env.run(until=30) env.teardown() return seen["done"] ``` Every form goes on at 5 seconds, and the flags are `[True, True, False]`. In SimPy, a `Condition` over the list of timeouts does the same: its count rule ends the wait at the second box. `open` takes the same form, `open: {pool: {each: ..., branch: ...}}`, and starts the branches without waiting for them. A later `wait: {handle: pool, index: 0}`, `cancel`, `release` or `interrupt` names one element with `{handle: pool, index: }`, and `cancel: pool` cancels every element not yet granted. `cancel` works on requests, gets and puts, and `interrupt` on child flows. A `handle` leaf with an `index` waits for the element it first resolved, after a resume and after a restart. `handle.pool.values` and `handle.pool.flags` read the results. Here an order asks for three packers at once and packs with the first it is given. It cancels the two requests that were not granted and releases the first unit by name. A second order arrives at 1 second and asks for a packer: ```yaml simulation: {sim_id: Shop, factor: 0} resources: packers: {current_cap: 1} arrivals: orders: {initial: 1, spawn: order} late: {dist: constant, value: 1, first_at: 1, max_events: 1, spawn: late_order} tasks: order: open: # three requests, made at once pool: each: 3 branch: {request: packers} wait: {handle: pool, index: 0} # the first of them service_time: 2 cancel: pool # the requests not yet granted: the second and the third release: {handle: pool, index: 0} # the unit of the first, when the task ends payload: event_type: packed granted: {gen: expr, expr: handle.pool.flags} late_order: resource: packers service_time: 1 payload: {event_type: late_packed} run: {until: 30} ``` ```python def pool_of_requests() -> tuple: """(time, granted, time of the next order) of an order that asks for three packers at once, packs with the first it gets and cancels the other two requests. A second order arrives at 1 s and asks for a packer.""" from desflow.values import Template app, capture = _shop() app.add_resource("packers", current_cap=1) packed = Template( { "event_type": "packed", "granted": {"gen": "expr", "expr": "handle.pool.flags"}, }, name="tasks.order", ) @app.task( open={"pool": {"each": 3, "branch": {"request": "packers"}}}, wait={"handle": "pool", "index": 0}, service_time=2, cancel="pool", # the requests not yet granted: the second and the third release={"handle": "pool", "index": 0}, ) def order(task_id): return packed @app.task(resource_id="packers", service_time=1) def late_order(task_id): return {"event_type": "late_packed"} def script(context): context.spawn(order(0)) yield context.env.timeout(1) context.spawn(late_order(0)) app.add_process(script) app.run(until=30) return _pool_result(capture) ``` ```python from simpy import Resource def pool_of_requests() -> tuple: """(time, granted, time of the next order) of an order that asks for three packers at once, packs with the first it gets and cancels the other two requests. A second order arrives at 1 s and asks for a packer.""" env = DynamicRealtimeEnvironment(factor=0) packers = Resource(env, capacity=1) seen: dict = {"late": None} def order(): pool = [packers.request() for _ in range(3)] yield pool[0] yield env.timeout(2) # the service for request in pool[1:]: request.cancel() # a request not granted leaves the line packers.release(pool[0]) seen["done"] = (env.now, [request.triggered for request in pool]) def late_order(): yield env.timeout(1) with packers.request() as request: yield request yield env.timeout(1) seen["late"] = env.now env.process(order()) env.process(late_order()) env.run(until=30) env.teardown() finished, granted = seen["done"] return finished, granted, seen["late"] ``` Every form returns the time the first order finishes, the flags of its three requests and the time the second order finishes: `(2.0, [True, False, False], 3.0)`, with whole numbers in the Low-level form. Only the first request was granted. The cancel takes the other two out of the line, so the second order gets the unit at 2 seconds and finishes at 3. Without the `cancel`, the release would hand the unit to the second request, which nothing would ever release, and the second order would wait for ever. `cancel: {handle: pool, index: 1}` cancels one element, but it would leave the third request in the line, with the same result. ### Wait for Nothing An `any` or an `all` with no branches is accepted, and succeeds at once with an empty value. A task whose wait is `{any: {}}` or `{all: {}}` goes on in the step it starts, as SimPy's `env.any_of([])` and `env.all_of([])` do. With a `patience` of 0 the wait still wins. The empty wait succeeds the instant it is built, so it is already processed when the task resumes. The task therefore does not renege. ______________________________________________________________________ ## Check the Result The script prints the result of every step above. The Builder and YAML functions end the script with: ```python if __name__ == "__main__": print("check: restock after 10 s:", first(10)) print("check: restock after 50 s:", first(50)) print("check: two at once:", two_at_once()) print("check: all, with a failure:", all_with_a_failure()) print("check: the same in YAML:", first_yaml(10), first_yaml(50)) print("check: two at once in YAML:", two_at_once_yaml()) print("check: all, with a failure, in YAML:", all_with_a_failure_yaml()) print("check: suspend and resume:", suspend_and_resume()) print("check: suspend and resume, in YAML:", suspend_and_resume_yaml()) print("check: two of three boxes:", each_of_three()) print("check: two of three boxes, in YAML:", each_of_three_yaml()) print("check: the first of three packers:", pool_of_requests()) print("check: the first of three packers, in YAML:", pool_of_requests_yaml()) ``` Run it in the folder with the script and the six blueprints, and keep the lines that start with `check:`: ```bash # With uv uv run --no-project --with desflow wait_for_one_or_all.py | grep "^check:" # With pip pip install desflow python wait_for_one_or_all.py | grep "^check:" ``` ```text check: restock after 10 s: {'stock': True, 'limit': False} check: restock after 50 s: {'stock': False, 'limit': True} check: two at once: {'boxes': True, 'labels': True} check: all, with a failure: [(0.0, 'order', 'queued'), (2.0, 'order', 'failed'), (4.0, 'inspect', 'finished')] check: the same in YAML: {'stock': True, 'limit': False} {'stock': False, 'limit': True} check: two at once in YAML: {'boxes': True, 'labels': True} check: all, with a failure, in YAML: [(0.0, 'order', 'queued'), (2.0, 'order', 'failed'), (4.0, 'inspect', 'finished')] check: suspend and resume: [(5.0, 'truck-1'), (5.0, 'truck-1')] check: suspend and resume, in YAML: [(5.0, 'truck-1'), (5.0, 'truck-1')] check: two of three boxes: (5.0, [True, True, False]) check: two of three boxes, in YAML: (5.0, [True, True, False]) check: the first of three packers: (2.0, [True, False, False], 3.0) check: the first of three packers, in YAML: (2.0, [True, False, False], 3.0) ``` The Low-level script, `wait_for_one_or_all_low_level.py`, starts with the line `from desflow import DynamicRealtimeEnvironment, Signal, SignalFailed`, followed by the six Low-level functions in the order they appear above. It ends with: ```python if __name__ == "__main__": print("restock after 10 s:", first(10)) print("restock after 50 s:", first(50)) print("two at once:", two_at_once()) print("all, with a failure:", all_with_a_failure()) print("suspend and resume:", suspend_and_resume()) print("two of three boxes:", each_of_three()) print("the first of three packers:", pool_of_requests()) ``` It needs no blueprint. Run it: ```bash # With uv uv run --no-project --with desflow wait_for_one_or_all_low_level.py # With pip pip install desflow python wait_for_one_or_all_low_level.py ``` ```text restock after 10 s: {'stock': True, 'limit': False} restock after 50 s: {'stock': False, 'limit': True} two at once: {'boxes': True, 'labels': True} all, with a failure: [(0, 'order', 'queued'), (2, 'order', 'failed'), (4, 'inspect', 'finished')] suspend and resume: [(5, 'truck-1'), (5, 'truck-1')] two of three boxes: (5, [True, True, False]) the first of three packers: (2, [True, False, False], 3) ``` The low-level form prints the times without a decimal point, because its timeouts are whole numbers. The example is a shop where each order waits for a restock or 30 seconds, whichever comes first. A restock waits for both its delivery, which takes 10 seconds, and a stock count, which takes 20 seconds. Orders arrive about every 10 seconds, and a delivery every minute. The `restocked` signal fires once for each restock, so it is declared with `once: false`: a signal is one-shot by default, and a second firing stops the run. Its files are in [Full Files](#full-files). Save the form you use in a folder of its own, and run it: The records go to the terminal as JSON lines. Keep the last count of each task and the time of each restock: ```bash desflow run wait_for_one_or_all_example.yaml --stdout > records.jsonl grep -oE '"path_id":"Shop.stats.tasks.(pack|refund).finished","value":[0-9]+' records.jsonl | tail -n 2 grep '"event_type":"restocked"' records.jsonl | grep -oE '"sim_ts":[0-9.]+' ``` ```text "path_id":"Shop.stats.tasks.refund.finished","value":19 "path_id":"Shop.stats.tasks.pack.finished","value":22 "sim_ts":80.0 "sim_ts":140.0 "sim_ts":200.0 "sim_ts":260.0 "sim_ts":320.0 "sim_ts":380.0 "sim_ts":440.0 "sim_ts":500.0 "sim_ts":560.0 ``` ```bash uv run --no-project --with desflow wait_for_one_or_all_example.py ``` ```text {'pack': 22, 'refund': 19, 'restocked_at': [80.0, 140.0, 200.0, 260.0, 320.0, 380.0, 440.0, 500.0, 560.0]} ``` ```bash uv run --no-project --with desflow wait_for_one_or_all_example_low_level.py ``` ```text {'pack': 22, 'refund': 19, 'restocked_at': [80, 140, 200, 260, 320, 380, 440, 500, 560]} ``` Each form runs once for 10 simulation minutes at `factor=0`: 22 orders are packed after a restock and 19 are refunded at the time limit. The restocks come at 80, 140 and so on to 560 seconds. Each comes 20 seconds after its delivery starts, because the wait for all ends with the stock count, the longer of its two branches. With `any` in place of `all`, each restock would come after the 10-second delivery instead, and more orders would be packed. The `process-interaction` example waits for a child flow, then for the first of a courier's signal and a time limit. [Processes](https://jaehyeon.me/desflow/latest/user-guide/tasks-and-processes/processes/#example-process-interaction) shows how to download and run it. ______________________________________________________________________ ## Full Files Full files ```yaml # The Wait for One or All guide: a shop where orders wait for a restock or a time # limit, as wait_for_one_or_all_example.py builds it. Run it with: # desflow run wait_for_one_or_all_example.yaml simulation: {sim_id: Shop, factor: 0, random_seed: 42} signals: restocked: {once: false} arrivals: orders: {dist: exponential, rate: 0.1, spawn: order} deliveries: {dist: constant, value: 60, spawn: restock} services: counting: {dist: constant, value: 20} tasks: # Each order waits for the next restock or 30 seconds, whichever comes first order: wait: any: stock: {signal: restocked} limit: {timeout: 30} payload: {event_type: waited} next: when: - {condition: wait.stock.done, task: pack} default: refund pack: payload: {event_type: packed} refund: payload: {event_type: refunded} # A restock waits for its delivery, 10 seconds, and a stock count, a child flow # of 20 seconds; when both are done it finishes and fires restocked restock: wait: all: delivery: {timeout: 10} count: {task: count_stock} signal: restocked payload: {event_type: restocked} count_stock: service: counting payload: {event_type: counted} stats: basic run: {until: 10 min} ``` ```python """Wait for one or all: a shop where orders wait for a restock or a time limit. Each order waits for the next restock or 30 seconds, whichever comes first, and is packed after a restock or refunded at the limit. A restock waits for both its delivery and a stock count, then fires the signal the orders wait for. The script runs 10 minutes at factor 0 and prints how many orders were packed and refunded, and the times of the restocks: python wait_for_one_or_all_example.py. """ from desflow import SimulationContext app = ( SimulationContext(sim_id="Shop", factor=0, random_seed=42) .add_arrival("orders", dist="exponential", rate=0.1, spawn="order") .add_arrival("deliveries", dist="constant", value=60, spawn="restock") .add_service("counting", dist="constant", value=20) .add_signal("restocked", once=False) .with_stats("basic") ) # Each order waits for the next restock or 30 seconds, whichever comes first @app.task( wait={"any": {"stock": {"signal": "restocked"}, "limit": {"timeout": 30}}}, next={ "when": [{"condition": "wait.stock.done", "task": "pack"}], "default": "refund", }, ) def order(task_id): return {"event_type": "waited"} @app.task() def pack(task_id): return {"event_type": "packed"} @app.task() def refund(task_id): return {"event_type": "refunded"} restocked_at = [] # the time of each restock # A restock waits for its delivery, 10 seconds, and a stock count, a child flow of # 20 seconds; when both are done it finishes and fires restocked @app.task( wait={"all": {"delivery": {"timeout": 10}, "count": {"task": "count_stock"}}}, signal="restocked", ) def restock(task_id): restocked_at.append(app.env.now) return {"event_type": "restocked"} @app.task(service_id="counting") def count_stock(task_id): return {"event_type": "counted"} def outcome() -> dict: """Runs 10 minutes and returns the orders packed and refunded, and the times of the restocks.""" app.run(until="10 min") readings = app.env.stats.readings() counts = { task: readings[f"Shop.stats.tasks.{task}.finished"] for task in ("pack", "refund") } return {**counts, "restocked_at": restocked_at} if __name__ == "__main__": print(outcome()) ``` ```python """Wait for one or all, low-level API: a shop where orders wait for a restock or a time limit. The low-level version of wait_for_one_or_all_example.py. Each order waits for the next restock or 30 seconds, whichever comes first, and is packed after a restock or refunded at the limit. A restock waits for both its delivery and a stock count, then fires the signal the orders wait for. The script runs 10 minutes at factor 0 and prints how many orders were packed and refunded, and the times of the restocks: python wait_for_one_or_all_example_low_level.py. """ import itertools from desflow import ( DistributionConfig, DynamicRealtimeEnvironment, Sampler, SimParameter, Signal, ) PARAMS = SimParameter( sim_id="Shop", arrival={"orders": DistributionConfig(dist="exponential", rate=0.1)}, ) def outcome() -> dict: """Runs 10 minutes and returns the orders packed and refunded, and the times of the restocks.""" env = DynamicRealtimeEnvironment(factor=0) env.registry.register_sim_parameter(PARAMS) restocked = Signal(env, "restocked", once=False) counts = {"pack": 0, "refund": 0} restocked_at = [] # the time of each restock # Each order waits for the next restock or 30 seconds, whichever comes first def order(): stock = restocked.wait() done = yield env.any_of([stock, env.timeout(30)]) counts["pack" if stock in done else "refund"] += 1 def count_stock(): yield env.timeout(20) # A restock waits for its delivery, 10 seconds, and a stock count, a child # process of 20 seconds; when both are done it fires restocked def restock(): yield env.all_of([env.timeout(10), env.process(count_stock())]) restocked_at.append(env.now) restocked.fire() def orders(sampler): gap = env.registry.get_config("Shop.arrival.orders") while True: yield env.timeout(sampler.sample(gap)) env.process(order()) def deliveries(): for _ in itertools.count(): yield env.timeout(60) env.process(restock()) env.process(orders(Sampler(seed=42))) env.process(deliveries()) env.run(until=600) env.teardown() return {**counts, "restocked_at": restocked_at} if __name__ == "__main__": print(outcome()) ``` # Hand Off to a Resource A handoff passes an order from one resource to the next without letting go of the first too early. Here a picker carries each order to a packing bench. The picker stays with the order until the bench is free. For a moment the order holds both resources, and then it releases the picker. ______________________________________________________________________ ## Before You Start - [Competing Resources](https://jaehyeon.me/desflow/latest/learn/shop-logic/competing-resources/index.md) measures what holding two resources costs. - [Several Resources](https://jaehyeon.me/desflow/latest/user-guide/resources/several-resources/#several-resources) describes `keep` and the rule on the order of acquisition. ______________________________________________________________________ ## Steps ### Keep the Picker When the First Task Ends Give the first task the resource and `keep` it: `pick` holds the picker and hands it to the next task. ### Ask for the Bench While Holding the Picker Give the next task the second resource: `pack` waits for the bench while the order still holds the picker, and gives the picker back once it publishes `started`. In the low-level API, `pick` passes its granted request to `pack`, which releases it in place of a `with` block: ```yaml # The picker carries the order to the bench and stays with it until it is on the # bench: keep hands the picker to the next task instead of releasing it pick: service: walking resource: picker keep: [picker] payload: {event_type: order_picked} next: pack # pack gives the picker back as soon as it publishes started pack: service: packing resource: bench payload: {event_type: order_packed} ``` ```python # The picker carries the order to the bench and stays with it until it is on the # bench: keep hands the picker to the next task instead of releasing it @app.task(service_id="walking", resource_id="picker", keep=["picker"], next="pack") def pick(task_id: int): return {"event_type": "order_picked"} # pack gives the picker back as soon as it publishes started @app.task(service_id="packing", resource_id="bench") def pack(task_id: int): return {"event_type": "order_packed"} ``` ```python def pick(env, shop, key): """Carries the order to the bench, and hands the picker to pack.""" task_id, path_id = next(shop["ids"]["pick"]), "Shop.service.walking" env.publish_event( key, { "path_id": path_id, "sim_id": "Shop", "service": "walking", "status": "queued", }, "pick", task_id, ) picker = shop["picker"].request() yield picker env.publish_event( key, { "path_id": path_id, "sim_id": "Shop", "service": "walking", "status": "started", }, "pick", task_id, ) yield env.timeout(shop["sampler"].sample(env.registry.get_config(path_id))) env.publish_event(key, {"event_type": "order_picked"}, "pick", task_id) yield from pack(env, shop, key, picker) # the order still holds the picker def pack(env, shop, key, picker): """Waits for the bench while holding the picker, then gives the picker back.""" task_id, path_id = next(shop["ids"]["pack"]), "Shop.service.packing" env.publish_event( key, { "path_id": path_id, "sim_id": "Shop", "service": "packing", "status": "queued", }, "pack", task_id, ) with shop["bench"].request() as bench: yield bench env.publish_event( key, { "path_id": path_id, "sim_id": "Shop", "service": "packing", "status": "started", }, "pack", task_id, ) shop["picker"].release(picker) # the order is on the bench yield env.timeout(shop["sampler"].sample(env.registry.get_config(path_id))) env.publish_event(key, {"event_type": "order_packed"}, "pack", task_id) ``` ### Acquire the Resources in the Same Order Acquire the two resources in the same order everywhere. A task that takes the bench first and the picker second does not stop the model from loading: the model logs one WARNING, from the logger `desflow.builder.context`, because two orders could then wait for each other for ever. A resource held with `seize` counts as held for this check. ### Know When the Kept Unit Goes Back Know when the kept unit goes back. The picker stays held until `pack` starts. A child flow that a task starts with `wait: {task: ...}` gives back only the units its own tasks asked for, so it never gives back a unit that its parent kept. ______________________________________________________________________ ## Check the Result Save the files from [Full Files](#full-files) and run `desflow run multi_resource_handoffs.yaml`, `python multi_resource_handoffs.py` or `python multi_resource_handoffs_low_level.py`. Each runs 30 simulated seconds at once and prints each event, and the three print the same events, because they use the same seed, 42. Each order is queued for the picker, picked, queued for the bench and packed, in that order. Orders arrive about once a second, and the one bench takes 4 seconds to pack each, so it can pack only one order every 4 seconds. The bench is therefore the [bottleneck](https://jaehyeon.me/desflow/latest/learn/concepts/queueing-basics/#flow-balance-and-the-bottleneck): an order that waits for the bench keeps the picker, and the orders behind it wait for the picker. A task that needs both resources for the whole of its work lists them instead, `resource: [picker, bench]`. The `competing-resources` example on [Several Resources](https://jaehyeon.me/desflow/latest/user-guide/resources/several-resources/#example-competing-resources) has both kinds. ______________________________________________________________________ ## Full Files Full files ```yaml # The Hand Off to a Resource guide: a picker carries each order to the packing bench # and stays with it until the bench is free. # Run it with: desflow run multi_resource_handoffs.yaml simulation: {sim_id: Shop, factor: 0, random_seed: 42} egress: - {type: Console} resources: picker: {current_cap: 1, max_cap: 1} bench: {current_cap: 1, max_cap: 1} services: # The picker takes 1 s to carry an order to the bench, and packing takes 4 s walking: {dist: constant, value: 1 s} packing: {dist: constant, value: 4 s} arrivals: orders: {dist: exponential, rate: 1.0, spawn: pick} tasks: # The picker carries the order to the bench and stays with it until it is on the # bench: keep hands the picker to the next task instead of releasing it pick: service: walking resource: picker keep: [picker] payload: {event_type: order_picked} next: pack # pack gives the picker back as soon as it publishes started pack: service: packing resource: bench payload: {event_type: order_packed} run: {until: 30 s} ``` ```python import logging from desflow import ConsoleEgress, SimulationContext logging.basicConfig(level=logging.INFO) app = ( SimulationContext(sim_id="Shop", factor=0, random_seed=42) .add_resource("picker", current_cap=1, max_cap=1) .add_resource("bench", current_cap=1, max_cap=1) # The picker takes 1 s to carry an order to the bench, and packing takes 4 s .add_service("walking", dist="constant", value=1.0) .add_service("packing", dist="constant", value=4.0) .add_arrival("orders", dist="exponential", rate=1.0) .add_egress(ConsoleEgress()) ) # The picker carries the order to the bench and stays with it until it is on the # bench: keep hands the picker to the next task instead of releasing it @app.task(service_id="walking", resource_id="picker", keep=["picker"], next="pack") def pick(task_id: int): return {"event_type": "order_picked"} # pack gives the picker back as soon as it publishes started @app.task(service_id="packing", resource_id="bench") def pack(task_id: int): return {"event_type": "order_packed"} @app.arrival_loop("orders") def arrival_loop(context: SimulationContext): while True: order = yield context.wait_for_arrival("orders") context.spawn(pick(context.next_instance("pick"), entity=order)) if __name__ == "__main__": app.run(until=30.0) ``` ```python """The Hand Off to a Resource guide, low-level API. The low-level version of multi_resource_handoffs.py: pick requests the picker and passes the granted request to pack, which releases it once the order is on the bench. python multi_resource_handoffs_low_level.py runs 30 simulated seconds at once. """ import itertools import logging from desflow import ( CapacityConfig, ConsoleEgress, DistributionConfig, DynamicRealtimeEnvironment, DynamicResource, Sampler, SimParameter, ) logging.basicConfig(level=logging.INFO) PARAMS = SimParameter( sim_id="Shop", arrival={"orders": DistributionConfig(dist="exponential", rate=1.0)}, service={ # The picker takes 1 s to carry an order to the bench, and packing takes 4 s "walking": DistributionConfig(dist="constant", value=1.0), "packing": DistributionConfig(dist="constant", value=4.0), }, resources={ "picker": CapacityConfig(current_cap=1, max_cap=1), "bench": CapacityConfig(current_cap=1, max_cap=1), }, ) def pick(env, shop, key): """Carries the order to the bench, and hands the picker to pack.""" task_id, path_id = next(shop["ids"]["pick"]), "Shop.service.walking" env.publish_event( key, { "path_id": path_id, "sim_id": "Shop", "service": "walking", "status": "queued", }, "pick", task_id, ) picker = shop["picker"].request() yield picker env.publish_event( key, { "path_id": path_id, "sim_id": "Shop", "service": "walking", "status": "started", }, "pick", task_id, ) yield env.timeout(shop["sampler"].sample(env.registry.get_config(path_id))) env.publish_event(key, {"event_type": "order_picked"}, "pick", task_id) yield from pack(env, shop, key, picker) # the order still holds the picker def pack(env, shop, key, picker): """Waits for the bench while holding the picker, then gives the picker back.""" task_id, path_id = next(shop["ids"]["pack"]), "Shop.service.packing" env.publish_event( key, { "path_id": path_id, "sim_id": "Shop", "service": "packing", "status": "queued", }, "pack", task_id, ) with shop["bench"].request() as bench: yield bench env.publish_event( key, { "path_id": path_id, "sim_id": "Shop", "service": "packing", "status": "started", }, "pack", task_id, ) shop["picker"].release(picker) # the order is on the bench yield env.timeout(shop["sampler"].sample(env.registry.get_config(path_id))) env.publish_event(key, {"event_type": "order_packed"}, "pack", task_id) def orders(env, shop): """Starts pick for every order, keyed orders-1, orders-2 and so on.""" gap = env.registry.get_config("Shop.arrival.orders") for number in itertools.count(1): yield env.timeout(shop["sampler"].sample(gap)) env.process(pick(env, shop, f"orders-{number}")) def run(until=30.0, factor=0, egress=None): env = DynamicRealtimeEnvironment(factor=factor) env.registry.register_sim_parameter(PARAMS) env.setup_egress(egress or [ConsoleEgress()]) shop = { "picker": DynamicResource(env, "Shop", "picker"), "bench": DynamicResource(env, "Shop", "bench"), "sampler": Sampler(seed=42), "ids": {"pick": itertools.count(), "pack": itertools.count()}, } env.process(orders(env, shop)) try: env.run(until=until) finally: env.teardown() if __name__ == "__main__": run() ``` # Share Work by Weight Share one resource between classes of work by weight, so that a class of weight 3 is served three times for each time a class of weight 1 is served while both wait. A priority queue serves the lowest priority value first, so a class with a higher value waits for as long as a class with a lower value has work. A weight gives each class its share instead. ______________________________________________________________________ ## Before You Start - [Custom Resource Types](https://jaehyeon.me/desflow/latest/user-guide/resources/custom-resource-types/index.md) shows how to subclass `ResourceBase`. - [Priority and Preemption](https://jaehyeon.me/desflow/latest/user-guide/resources/priority-and-preemption/#task-priority) explains how a task sets a priority. ______________________________________________________________________ ## Steps ### Choose the Weights Each class has a weight. Here tier 1 weighs 3 and tier 2 weighs 1: ```python # Tier 1 is served three times for each time tier 2 is served WEIGHTS = {1: 3, 2: 1} ``` ### Order the Waiting Line A resource keeps its waiting requests in its `PutQueue`. `ResourceBase` creates the queue with no arguments, and a request joins it with `append`. Write a queue that gives each request a **finish tag**, a number that sets its turn, and keeps the requests sorted by it. The queue follows three rules: 1. A request's finish tag is the later of the queue's clock and its class's last tag, plus 1 divided by the class's weight. 1. The queue serves the smallest tag first. Requests with equal tags leave in the order they arrived, which the counter `arrived` keeps. 1. When a request is granted, the queue takes its tag as the clock. A class of weight 3 therefore gets tags a third as far apart as a class of weight 1, so it is served three times as often: ```python class FinishTagQueue(list): """Waiting requests in the order of their finish tags, smallest first. A request's tag is where its class would finish it if every class had its share: the later of the queue's clock and the class's last tag, plus 1 divided by the class's weight. Equal tags leave in the order the requests arrived. """ def __init__(self): super().__init__() self.clock = Fraction(0) # the tag of the request granted last self.last = {} # the last tag given to each class self.arrived = itertools.count() def append(self, request): tier = request.priority # set by `priority: attr.tier`, not by _rank start = max(self.clock, self.last.get(tier, Fraction(0))) tag = start + Fraction(1, WEIGHTS[tier]) self.last[tier] = tag request.tag = (tag, next(self.arrived)) bisect.insort(self, request, key=lambda waiting: waiting.tag) def pop(self, index=-1): request = super().pop(index) self.clock = request.tag[0] # a grant moves the clock to its tag return request ``` The class of a request is its `priority`, which the task sets. The queue reads it there, not from the rank `ResourceBase` computes for the request, which this queue does not use. Fractions keep the tags exact, so two tags that should be equal compare as equal. The tags assume that every request holds the packer for the same time, as here, where every order takes 1 second to pack. ### Make the Resource Subclass `ResourceBase` and set `PutQueue`. The resource also keeps the tier of each grant, so a test can read the order: ```python class WeightedPackers(ResourceBase): """A resource that grants its units by weight and keeps the tier of each grant.""" PutQueue = FinishTagQueue def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.granted = [] def _do_put(self, request): super()._do_put(request) if request.triggered: # the request was granted just now self.granted.append(request.priority) ``` ### Use It A task sets the class with its `priority`, and the loader refuses a task priority on a resource that does not set `queue: priority`. So set `queue: priority` beside `type`. This queue orders its waiting requests itself and ignores the order that setting names. ```yaml resources: # queue: priority lets a task set a priority; the class orders the waiting requests # itself packers: current_cap: 1 max_cap: 4 queue: priority type: !python share_by_weight_logic.WeightedPackers ``` The class is in `share_by_weight_logic.py`, beside the blueprint. The task takes the tier from the order's attributes: ```yaml tasks: pack_order: service: packing resource: packers priority: attr.tier # the tier of the order is the class of its request payload: {event_type: order_packed} ``` The nine orders arrive at time 0, from `share_by_weight_orders.csv`, one row each: ```text time,tier 0,2 0,1 0,1 0,1 0,1 0,1 0,1 0,2 0,2 ``` ```python app = ( SimulationContext(sim_id="Shop", factor=0, random_seed=42) .add_service("packing", dist="constant", value=1.0) .add_arrival_replay( "orders", [{"time": 0, "tier": tier} for tier in TIERS], fields=["tier"] ) ) # queue="priority" lets a task set a priority; the class orders the waiting requests itself app.add_resource( "packers", current_cap=1, max_cap=4, queue="priority", type=WeightedPackers ) # The tier of the order is the class of its request @app.task(service_id="packing", resource_id="packers", priority="attr.tier") def pack_order(task_id: int): return {"event_type": "order_packed"} @app.arrival_loop("orders") def order_generator(context: SimulationContext): task_id = 0 while True: order = yield context.wait_for_arrival("orders") context.spawn(pack_order(task_id, entity=order)) task_id += 1 ``` The class is the one the YAML tab shows. ```python env = DynamicRealtimeEnvironment(factor=0.0) env.registry.register_sim_parameter( SimParameter( sim_id="Shop", service={"packing": DistributionConfig(dist="constant", value=1.0)}, resources={"packers": CapacityConfig(current_cap=1, max_cap=4)}, ) ) packers = WeightedPackers(env, "Shop", "packers", queue="priority") def order(env, tier): # The tier is the priority of the request with packers.request(priority=tier) as request: yield request yield env.timeout(1.0) for tier in TIERS: env.process(order(env, tier)) ``` The class is the one the YAML tab shows. ______________________________________________________________________ ## Check the Result Look at the tags the queue gives the orders, on a line from 1 to 3: The first order is tier 2. It takes the packer at once, with tag 1, and the clock becomes 1. The six orders of tier 1 then get tags 4/3, 5/3, 2, 7/3, 8/3 and 3, and the two of tier 2 get 2 and 3. The smallest tag goes first, and where two tags are equal, tier 1 arrived first. So after the first order the packer grants **1, 1, 1, 2, 1, 1, 1, 2**: three of tier 1 for each of tier 2. First in, first out would grant 1, 1, 1, 1, 1, 1, 2, 2. The resource keeps the tier of each grant in `granted`. `python share_by_weight.py` prints it for the YAML and builder forms, and `python share_by_weight_low_level.py` for the low-level form. All three grant the order worked out here. The queue leaves out three things. A request that leaves the queue before it is granted keeps the tag it took, so its class does not get that share back. A class not in `WEIGHTS` raises `KeyError` when its first request joins. Do not set `preempt`: preemption ranks users by priority, here the tier, so a tier 1 order would take the packer from tier 2 whatever the weights. ______________________________________________________________________ ## Full Files Every form uses the class in `share_by_weight_logic.py` unchanged. Put it, the blueprint and the orders file in one folder with the scripts, and run them from there. Full files ```python """Python for share_by_weight.yaml: a packer that shares its time between classes by weight, as the Share Work by Weight guide builds it.""" import bisect import itertools from fractions import Fraction from desflow import ResourceBase # Tier 1 is served three times for each time tier 2 is served WEIGHTS = {1: 3, 2: 1} class FinishTagQueue(list): """Waiting requests in the order of their finish tags, smallest first. A request's tag is where its class would finish it if every class had its share: the later of the queue's clock and the class's last tag, plus 1 divided by the class's weight. Equal tags leave in the order the requests arrived. """ def __init__(self): super().__init__() self.clock = Fraction(0) # the tag of the request granted last self.last = {} # the last tag given to each class self.arrived = itertools.count() def append(self, request): tier = request.priority # set by `priority: attr.tier`, not by _rank start = max(self.clock, self.last.get(tier, Fraction(0))) tag = start + Fraction(1, WEIGHTS[tier]) self.last[tier] = tag request.tag = (tag, next(self.arrived)) bisect.insort(self, request, key=lambda waiting: waiting.tag) def pop(self, index=-1): request = super().pop(index) self.clock = request.tag[0] # a grant moves the clock to its tag return request class WeightedPackers(ResourceBase): """A resource that grants its units by weight and keeps the tier of each grant.""" PutQueue = FinishTagQueue def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.granted = [] def _do_put(self, request): super()._do_put(request) if request.triggered: # the request was granted just now self.granted.append(request.priority) ``` ```yaml # The Share Work by Weight guide: one packer shared between two tiers of orders by # weight. Run it with: desflow run share_by_weight.yaml simulation: {sim_id: Shop, factor: 0, random_seed: 42} resources: # queue: priority lets a task set a priority; the class orders the waiting requests # itself packers: current_cap: 1 max_cap: 4 queue: priority type: !python share_by_weight_logic.WeightedPackers services: packing: {dist: constant, value: 1 s} # Nine orders at time 0, each with a tier arrivals: orders: replay: {path: share_by_weight_orders.csv, time: time, unit: s} spawn: pack_order tasks: pack_order: service: packing resource: packers priority: attr.tier # the tier of the order is the class of its request payload: {event_type: order_packed} egress: - {type: Console} run: {until: 20 s} ``` ```text time,tier 0,2 0,1 0,1 0,1 0,1 0,1 0,1 0,2 0,2 ``` ```python """Share Work by Weight: one packer shared between two tiers of orders, 3 to 1. Nine orders arrive at time 0: the first is tier 2, then six of tier 1, then two more of tier 2. The first takes the packer and the rest wait. The packer grants the waiting orders by weight, three of tier 1 for each of tier 2. `builder_form` runs the shop with the builder and `yaml_form` runs share_by_weight.yaml, which loads as a context; share_by_weight_low_level.py is the low-level API. Each returns the tier of each order in the order the packer granted them. """ import logging import sys from pathlib import Path from desflow import SimulationContext HERE = Path(__file__).resolve().parent sys.path.insert(0, str(HERE)) # share_by_weight_logic.py is beside the blueprint from share_by_weight_logic import WeightedPackers # noqa: E402 logging.basicConfig( level=logging.WARNING, format="%(levelname)s [%(asctime)s] %(message)s" ) # The tier of each order, in the order the orders arrive TIERS = [2, 1, 1, 1, 1, 1, 1, 2, 2] def yaml_form(): """The blueprint beside the class.""" app = SimulationContext.from_yaml(HERE / "share_by_weight.yaml") app.run() return app.get_resource("packers").granted def builder_form(): """The same shop with the builder.""" app = ( SimulationContext(sim_id="Shop", factor=0, random_seed=42) .add_service("packing", dist="constant", value=1.0) .add_arrival_replay( "orders", [{"time": 0, "tier": tier} for tier in TIERS], fields=["tier"] ) ) # queue="priority" lets a task set a priority; the class orders the waiting requests itself app.add_resource( "packers", current_cap=1, max_cap=4, queue="priority", type=WeightedPackers ) # The tier of the order is the class of its request @app.task(service_id="packing", resource_id="packers", priority="attr.tier") def pack_order(task_id: int): return {"event_type": "order_packed"} @app.arrival_loop("orders") def order_generator(context: SimulationContext): task_id = 0 while True: order = yield context.wait_for_arrival("orders") context.spawn(pack_order(task_id, entity=order)) task_id += 1 app.run(until=20) return app.get_resource("packers").granted if __name__ == "__main__": for form in (yaml_form, builder_form): print(f"{form.__name__:15} {form()}") ``` ```python """Share Work by Weight, low-level API: one packer shared between two tiers of orders, 3 to 1. The low-level version of share_by_weight.py: nine orders at time 0, the first of tier 2, then six of tier 1, then two more of tier 2. `low_level_form` returns the tier of each order in the order the packer granted them. """ import logging import sys from pathlib import Path from desflow import ( CapacityConfig, DistributionConfig, DynamicRealtimeEnvironment, SimParameter, ) HERE = Path(__file__).resolve().parent sys.path.insert(0, str(HERE)) # share_by_weight_logic.py is beside the blueprint from share_by_weight_logic import WeightedPackers # noqa: E402 logging.basicConfig( level=logging.WARNING, format="%(levelname)s [%(asctime)s] %(message)s" ) # The tier of each order, in the order the orders arrive TIERS = [2, 1, 1, 1, 1, 1, 1, 2, 2] def low_level_form(): """The same shop with the environment and the resource.""" env = DynamicRealtimeEnvironment(factor=0.0) env.registry.register_sim_parameter( SimParameter( sim_id="Shop", service={"packing": DistributionConfig(dist="constant", value=1.0)}, resources={"packers": CapacityConfig(current_cap=1, max_cap=4)}, ) ) packers = WeightedPackers(env, "Shop", "packers", queue="priority") def order(env, tier): # The tier is the priority of the request with packers.request(priority=tier) as request: yield request yield env.timeout(1.0) for tier in TIERS: env.process(order(env, tier)) env.run(until=20) return packers.granted if __name__ == "__main__": print(f"{'low_level_form':15} {low_level_form()}") ``` # Model Breakdowns Make a resource fail at random and be repaired, decide what happens to the work it was doing, and check how long it was down. ______________________________________________________________________ ## Before You Start - [Interruptions](https://jaehyeon.me/desflow/latest/learn/shop-logic/interruptions/index.md) explains `on_interrupt`. - [Priority and Preemption](https://jaehyeon.me/desflow/latest/user-guide/resources/priority-and-preemption/#breakdowns) describes the down state. ______________________________________________________________________ ## Steps ### Give the Resource a Breakdown Give the resource a `breakdown` with two distributions: `time_to_failure`, the time from the start or from a repair to the next failure, and `repair`, how long a repair takes. Here a packing station of two units fails about once a minute on average (`rate: 0.0167`) and takes 5 to 15 seconds to repair: ```yaml resources: station: current_cap: 2 max_cap: 3 breakdown: # Calendar time from a repair, or the start, to the next failure. # A failure every 60 s on average (rate 0.0167) time_to_failure: {dist: exponential, rate: 0.0167} repair: {dist: uniform, low: 5 s, high: 15 s} # The orders being packed are interrupted, and follow their on_interrupt. work: interrupt ``` ```python .add_resource("station", current_cap=2, max_cap=3) .add_breakdown( "station", # Calendar time from a repair, or the start, to the next failure # A failure every 60 s on average (rate 0.0167) time_to_failure={"dist": "exponential", "rate": 0.0167}, repair={"dist": "uniform", "low": 5, "high": 15}, # The orders being packed are interrupted, and follow their on_interrupt work="interrupt", ) ``` ```python breakdowns={ "station": BreakdownConfig( # Calendar time from a repair, or the start, to the next failure # A failure every 60 s on average (rate 0.0167) time_to_failure=DistributionConfig(dist="exponential", rate=0.0167), repair=DistributionConfig(dist="uniform", low=5, high=15), # The orders being packed are interrupted work="interrupt", ) }, ``` The breakdowns run as a SimPy process, started beside the arrivals: ```python def processes(env, sampler, station): """The breakdowns and the arrivals, in the builder's order.""" return [ # A SimPy process: down at each failure, repaired after each repair time run_breakdowns(env, station, sampler, work="interrupt"), order_generator(env, sampler, station), ] ``` An interrupted order catches `simpy.Interrupt`, whose cause is `"breakdown"`, gives back its request and asks again, as the full file shows. With the default `clock: calendar`, the next failure is drawn at the start and after each repair, and the time to it passes whether the station is busy or idle. A failure works as follows: - All the station's units fail together. Its capacity is 0 until the repair ends, so no order starts. - Its `current_cap` keeps the planned value. A scenario step or an ingress message that changes it during the repair sets the capacity the station returns to. It does not end the repair. - The station publishes an event keyed by its name at each failure, `{"status": "down", "reason": "failure"}`, and at each repair, `{"status": "repaired", "reason": "failure"}`. The two distributions are registry paths, `Shop.breakdown.station.time_to_failure` and `.repair`, so a live change can make failures more or less frequent. The two cannot both always give 0, because the station would then fail and be repaired for ever at one instant. The load refuses a pair that always gives 0. A live change that makes both 0 stops the run with an error that names the station. So does a pair that gives only 0 although its distribution has a spread, such as a normal time whose mean is many times its std below 0: the run stops after 10,000 failures at one instant. A breakdown that lets work finish and then holds the resource for a fixed time each day is a capacity schedule. [Vary Arrivals by Time](https://jaehyeon.me/desflow/latest/how-to/modelling/time-varying-arrivals/index.md) writes it as scenario steps. ### Choose What Happens to the Work in Service Choose `work`: `interrupt`, the default, stops the tasks being served when the resource fails. `finish` lets them finish and stops only new work. ### Choose What an Interrupted Order Does With `interrupt`, give the task an `on_interrupt`: `resume` packs what was left after the repair, `restart` packs again from the start, and `abandon` ends the order. ### Count Only the Time the Station Works Choose the failure `clock`. `calendar`, the default, counts the time to failure whether the station is busy or idle. `clock: busy` counts it only while at least one unit of the resource is in use, so an idle station does not wear out. The time to failure is still drawn once for each cycle. A task's `resource`, a `seize`, a wait `request` and an `open` unit all count as in use. A time to failure of 0 fails at the grant of the first unit. The clock waits for two events of the resource. `when_busy()` succeeds when the resource next holds a unit after holding none, and `when_idle()` succeeds when it next holds none after holding one. A station that is down keeps the units its users hold, so it is not idle until they are given back. Here a station fails after 5 seconds of work. One order arrives at 10 seconds and takes 8, and `work: finish` lets it finish: ```yaml resources: station: current_cap: 1 breakdown: time_to_failure: {dist: constant, value: 5} repair: {dist: constant, value: 2} work: finish # Count the time to failure only while a unit is in use. The default, calendar, # counts it from the start or the last repair, busy or idle. clock: busy ``` ```python app.add_breakdown( "station", time_to_failure={"dist": "constant", "value": 5}, repair={"dist": "constant", "value": 2}, work="finish", # Count the time to failure only while a unit is in use. The default, # "calendar", counts it from the start or the last repair, busy or idle. clock=clock, ) ``` ```python breakdowns={ "station": BreakdownConfig( time_to_failure=DistributionConfig(dist="constant", value=5), repair=DistributionConfig(dist="constant", value=2), work="finish", # Count the time to failure only while a unit is in use. The default, # "calendar", counts it from the start or the last repair. clock=clock, ) }, ``` The process that fails and repairs the station takes the same `clock`: ```python # A SimPy process that puts the station down at each failure and repairs it; # clock is passed to it as well as set in the config env.process( run_breakdowns(env, station, Sampler(seed=42), work="finish", clock=clock) ) ``` In the Builder and Low-level blocks, `clock` is the argument of the function that builds the model: `"busy"` or `"calendar"`. With the busy clock, every form puts the station down at 15 seconds, 5 seconds into the order, and repairs it at 17 seconds: `[(15.0, 'down'), (17.0, 'repaired')]`. With `clock: calendar`, the same station fails at 5, 12, 19 and 26 seconds, mostly while it is idle. ______________________________________________________________________ ## Check the Result Download the example's three forms into the folder you work in with `desflow examples get breakdowns`. The check is a script, `check_breakdowns.py`, made of the blocks below in order. It reads the example from `breakdowns/yaml/`, `breakdowns/builder/` and `breakdowns/low-level/`, so run it from the folder where you ran the command. With statistics at `minimal` or above, the station publishes `down`: 1 while it is down and 0 otherwise. From `basic` it also publishes `downtime`, the seconds it has been down, and `failures`, how many times it has failed. The script starts with a class that keeps every record the example publishes, and a function that loads an example file without running it. The imports of desflow follow the class, in the line `from desflow import DynamicRealtimeEnvironment, Sampler, SimulationContext`: ```python import asyncio import importlib.util import queue class Capture: """An egress that keeps every record it receives.""" def __init__(self): self.records = [] async def run(self, egress_queue): try: while True: try: self.records.extend(egress_queue.get_nowait()) except queue.Empty: await asyncio.sleep(0.005) except asyncio.CancelledError: pass ``` ```python def _example(path: str): """Loads an example script as a module, without running it.""" spec = importlib.util.spec_from_file_location("breakdowns_example", path) assert spec is not None and spec.loader is not None module = importlib.util.module_from_spec(spec) spec.loader.exec_module(module) return module ``` The next function takes the records of a run, its end time and its statistics, finds the down periods from the events, and checks both counts against them. It is the same for every form: ```python def availability(records: list, end: float, stats: dict) -> dict: """The down periods of the station, checked against its statistics.""" periods, outcomes = [], {"interrupted": 0, "resumed": 0, "order_packed": 0} for record in records: if record["stream_type"] != "event": continue value = record["value"] status = value.get("status", value.get("event_type")) if record["key"] == "station" and status == "down": periods.append([record["sim_ts"], None]) elif record["key"] == "station" and status == "repaired": periods[-1][1] = record["sim_ts"] elif status in outcomes: outcomes[status] += 1 # A repair still going on at the end counts up to the end downtime = sum((repaired or end) - down for down, repaired in periods) name = "Shop.stats.resources.station.{}".format assert stats[name("failures")] == len(periods) # Records round times to the millisecond assert abs(stats[name("downtime")] - downtime) < 0.01 return { "periods": [(round(d, 1), r if r is None else round(r, 1)) for d, r in periods], "downtime": round(downtime, 1), "share_down": round(downtime / end, 3), **outcomes, } ``` The YAML and builder forms add a capturing egress beside the example's own. The low-level form builds the example's environment with the capture as its only egress. Each passes what it captured to `availability`: ```python def yaml_form(path: str = "breakdowns/yaml/breakdowns.yaml") -> dict: app = SimulationContext.from_yaml(path) capture = Capture() app.add_egress(capture) app.run() # until 300, from the blueprint return availability(capture.records, app.env.now, app.env.stats.readings()) ``` ```python def builder_form(path: str = "breakdowns/builder/breakdowns_example.py") -> dict: app = _example(path).app capture = Capture() app.add_egress(capture) app.run(until=300) return availability(capture.records, app.env.now, app.env.stats.readings()) ``` ```python def low_level_form(path: str = "breakdowns/low-level/breakdowns_example.py") -> dict: example = _example(path) env = DynamicRealtimeEnvironment(factor=0) env.registry.register_sim_parameter(example.PARAMS) capture = Capture() env.setup_egress([capture]) env.setup_stats("Shop", "basic", interval=60.0) station = example.build(env) for process in example.processes(env, Sampler(seed=42), station): env.process(process) env.run(until=300) env.teardown() # publishes the last statistics and flushes the capture return availability(capture.records, env.now, env.stats.readings()) ``` Last, the script runs the three forms. Run it, and keep the lines that start with a brace, because the example also prints each of its events: ```python if __name__ == "__main__": for form in (yaml_form, builder_form, low_level_form): print(form()) ``` ```bash # With uv uv run --no-project --with desflow check_breakdowns.py | grep "^{" # With pip pip install desflow python check_breakdowns.py | grep "^{" ``` ```text {'periods': [(5.6, 10.9), (63.5, 73.0), (98.7, 105.1), (187.4, 199.3), (217.4, 222.9)], 'downtime': 38.6, 'share_down': 0.129, 'interrupted': 8, 'resumed': 8, 'order_packed': 169} {'periods': [(5.6, 10.9), (63.5, 73.0), (98.7, 105.1), (187.4, 199.3), (217.4, 222.9)], 'downtime': 38.6, 'share_down': 0.129, 'interrupted': 8, 'resumed': 8, 'order_packed': 169} {'periods': [(5.6, 10.9), (63.5, 73.0), (98.7, 105.1), (187.4, 199.3), (217.4, 222.9)], 'downtime': 38.6, 'share_down': 0.129, 'interrupted': 8, 'resumed': 8, 'order_packed': 169} ``` For one 300-second run of the example, every form returns five down periods. The first is from 5.6 to 10.9 seconds. Together they give **38.6** seconds of downtime in 300, or 12.9 percent. **8** orders are interrupted, and all 8 resume after a repair. Report the downtime beside the waits: a station that is down 12.9 percent of the time has that much less capacity, and its waits grow as on [Queues and Capacity](https://jaehyeon.me/desflow/latest/learn/first-model/queues-and-capacity/index.md). ______________________________________________________________________ ## Example The `breakdowns` example is the model above: two units at a packing station, an order every 1.67 seconds on average (`rate: 0.6`), and every order packed once the station is back. It needs no Docker service and ends on its own after 300 simulation seconds. **Quick Start** `desflow examples get` downloads the example at the release you install, into a folder of its own. Pick uv or pip: ```bash # 1. Install uv tool install desflow # 2. Download the example desflow examples get breakdowns --api yaml cd breakdowns/yaml # 3. Run it desflow run breakdowns.yaml ``` ```bash # 1. Install pip install desflow # 2. Download the example desflow examples get breakdowns --api yaml cd breakdowns/yaml # 3. Run it desflow run breakdowns.yaml ``` **Quick Start** `desflow examples get` downloads the example at the release you install, into a folder of its own. Pick uv or pip: ```bash # 1. Install uv tool install desflow # 2. Download the example desflow examples get breakdowns --api builder cd breakdowns/builder # 3. Run it uv run --no-project --with desflow breakdowns_example.py ``` ```bash # 1. Install pip install desflow # 2. Download the example desflow examples get breakdowns --api builder cd breakdowns/builder # 3. Run it python breakdowns_example.py ``` **Quick Start** `desflow examples get` downloads the example at the release you install, into a folder of its own. Pick uv or pip: ```bash # 1. Install uv tool install desflow # 2. Download the example desflow examples get breakdowns --api low-level cd breakdowns/low-level # 3. Run it uv run --no-project --with desflow breakdowns_example.py ``` ```bash # 1. Install pip install desflow # 2. Download the example desflow examples get breakdowns --api low-level cd breakdowns/low-level # 3. Run it python breakdowns_example.py ``` # Add Resources Mid-run Sometimes the layout itself changes during a run: a dock opens a new bay, or a shop adds a gift wrapping station. Here a supervisor process adds gift wrappers at 12 seconds, and from then on new jobs go to the wrappers as well as the packers. A blueprint and the builder create their resources before the clock starts and have no setting that adds one later. A process can add one, because it has the environment. A low-level script adds one the same way. When you know the resource in advance, you can declare it with no units and give it units in a scenario step, as the last step shows. ______________________________________________________________________ ## Before You Start - [Low-level API](https://jaehyeon.me/desflow/latest/user-guide/writing-a-model/low-level-api/index.md) explains how to register parameters and create resources. - [Live Parameters](https://jaehyeon.me/desflow/latest/user-guide/live-runs-and-connectors/live-parameters/index.md) explains the registry paths a resource reads. - [Processes](https://jaehyeon.me/desflow/latest/user-guide/tasks-and-processes/processes/index.md) shows how a blueprint and the builder run a process. ______________________________________________________________________ ## Steps ### Keep the Resources in a Mapping Keep the resources that exist in a mapping, so the process that starts new work also finds a resource added later. ### Register a Parameter for the New Resource When the layout changes, register a `SimParameter` that holds only the new resource. The registry adds its paths, here `Shop.resources.wrappers.current_cap`, `Shop.resources.wrappers.max_cap` and `Shop.resources.wrappers.queue_limit`, which is `None` while the resource has no limit. A limit is changed through the path: `queue_limit` on the resource is read only. ### Create the Resource and Add It Create the `DynamicResource` for it, which reads its capacity from those paths, and add it to the mapping. ### Start Work on the New Resource Start work on it as on any other resource. The code below does all four. In a blueprint and in the builder, the supervisor is a process that receives the context, and `context.env` is the environment. In the low-level API it is a SimPy process of the script: ```yaml simulation: {sim_id: Shop, factor: 0} egress: - {type: Console} resources: packers: {current_cap: 1, max_cap: 5} processes: # Called as supervisor(context); it adds the wrappers during the run - {function: !python dynamic_topology_logic.supervisor} run: {until: 20 s} ``` `dynamic_topology_logic.py` beside it holds the supervisor: ```python def supervisor(context): """Starts a job on every resource each round, and adds the wrappers at 12 s.""" env = context.env # the environment, as a low-level script has it resources = {"packers": context.get_resource("packers")} job_id = 0 while True: yield env.timeout(NEW_JOBS_EVERY) if env.now >= ADD_WRAPPERS_AT and "wrappers" not in resources: env.registry.register_sim_parameter( SimParameter( sim_id="Shop", resources={"wrappers": CapacityConfig(current_cap=2, max_cap=5)}, ) ) resources["wrappers"] = DynamicResource(env, "Shop", "wrappers") env.publish_event( "supervisor", { "status": "wrappers_added", "capacity": resources["wrappers"].capacity, }, ) for name in list(resources): env.process(worker(env, resources, name, job_id)) job_id += 1 ``` ```python app = ( SimulationContext(sim_id="Shop", factor=0) .add_egress(ConsoleEgress()) .add_resource("packers", current_cap=1, max_cap=5) # Called as supervisor(context); it adds the wrappers during the run .add_process(supervisor) ) ``` `supervisor` is the function in `dynamic_topology_logic.py`, which the YAML tab shows. ```python # Give the gift wrappers their registry paths, then create the resource # that reads its capacity from them. env.registry.register_sim_parameter( SimParameter( sim_id="Shop", resources={"wrappers": CapacityConfig(current_cap=2, max_cap=5)}, ) ) resources["wrappers"] = DynamicResource(env, "Shop", "wrappers") ``` ### Declare the Resource With No Units Instead When the resource is known before the run, declare it with `current_cap: 0` and give it units with a scenario step. A job that asks for the wrappers waits in the line until the step raises `current_cap`. No process is needed, so a blueprint can do it alone. The step's `record` publishes what it did at that time, as a ground-truth record to a sink with `when: labels`. All three forms give the step the same `record`: ```yaml resources: packers: {current_cap: 1, max_cap: 5} # No units yet: a job that asks for one waits wrappers: {current_cap: 0, max_cap: 5} scenario: # At 12 seconds the wrappers get 2 units, and the step records what it did - at: 12 path: Shop.resources.wrappers.current_cap value: 2 record: {status: wrappers_added, capacity: 2} ``` ```python # No units yet: a job that asks for one waits app.add_resource("wrappers", current_cap=0, max_cap=5) # At 12 seconds the wrappers get 2 units, and the step records what it did app.add_scenario( [ { "at": 12, "path": "Shop.resources.wrappers.current_cap", "value": 2, "record": {"status": "wrappers_added", "capacity": 2}, } ] ) ``` ```python PARAMS = SimParameter( sim_id="Shop", resources={ "packers": CapacityConfig(current_cap=1, max_cap=5), # No units yet: a job that asks for one waits "wrappers": CapacityConfig(current_cap=0, max_cap=5), }, ) # At 12 seconds the wrappers get 2 units, and the step records what it did SCHEDULE = [ { "at": 12, "path": "Shop.resources.wrappers.current_cap", "value": 2, "record": {"status": "wrappers_added", "capacity": 2}, } ] ``` Every form finishes the same jobs: the packers at 7, 11, 15 and 19 seconds, and the wrappers at 15 and 19 seconds. Use the process of the steps above when the resource, or its name, is not known until the run is under way. ______________________________________________________________________ ## Check the Result Run `desflow run dynamic_topology.yaml`, `python dynamic_topology_builder.py` or `python dynamic_topology.py`. Each runs 20 simulated seconds at once, and the three print the same events: - Every 4 seconds the supervisor starts one job on each resource it has. Each job publishes `queued`, `started` and `finished` with the resource it used, and takes 3 seconds. - At 12 seconds the supervisor publishes `{"status": "wrappers_added", "capacity": 2}`, and `wrappers-2` starts in the same round. - Each run ends with `env.teardown()`, which writes the records still in the buffers. `run()` calls it for the blueprint and the builder. The wrappers' capacity is live like any other. A scenario, a connector or a process can change `Shop.resources.wrappers.current_cap` once the path exists, as [Live Parameters](https://jaehyeon.me/desflow/latest/user-guide/live-runs-and-connectors/live-parameters/index.md) describes. ______________________________________________________________________ ## Full Files Full files ```yaml # The Add Resources Mid-run guide: a supervisor adds gift wrappers at 12 seconds. # Run it with: desflow run dynamic_topology.yaml, beside dynamic_topology_logic.py simulation: {sim_id: Shop, factor: 0} egress: - {type: Console} resources: packers: {current_cap: 1, max_cap: 5} processes: # Called as supervisor(context); it adds the wrappers during the run - {function: !python dynamic_topology_logic.supervisor} run: {until: 20 s} ``` ```python """The Add Resources Mid-run guide: the supervisor process of the blueprint and the builder, which adds the gift wrappers during the run. dynamic_topology.yaml names `supervisor` with !python, and dynamic_topology_builder.py adds it with add_process. """ from desflow import CapacityConfig, DynamicResource, SimParameter WORK = 3.0 # seconds each job takes NEW_JOBS_EVERY = 4.0 # seconds between rounds of new jobs ADD_WRAPPERS_AT = 12.0 # simulation time at which the gift wrappers are added def worker(env, resources, name, job_id): resource = resources[name] key = f"{name}-{job_id}" env.publish_event(key, {"resource": name, "status": "queued"}) with resource.request() as req: yield req env.publish_event(key, {"resource": name, "status": "started"}) yield env.timeout(WORK) env.publish_event(key, {"resource": name, "status": "finished"}) def supervisor(context): """Starts a job on every resource each round, and adds the wrappers at 12 s.""" env = context.env # the environment, as a low-level script has it resources = {"packers": context.get_resource("packers")} job_id = 0 while True: yield env.timeout(NEW_JOBS_EVERY) if env.now >= ADD_WRAPPERS_AT and "wrappers" not in resources: env.registry.register_sim_parameter( SimParameter( sim_id="Shop", resources={"wrappers": CapacityConfig(current_cap=2, max_cap=5)}, ) ) resources["wrappers"] = DynamicResource(env, "Shop", "wrappers") env.publish_event( "supervisor", { "status": "wrappers_added", "capacity": resources["wrappers"].capacity, }, ) for name in list(resources): env.process(worker(env, resources, name, job_id)) job_id += 1 ``` ```python """The Add Resources Mid-run guide, builder API: a supervisor adds gift wrappers at 12 seconds. Run it with: python dynamic_topology_builder.py, beside dynamic_topology_logic.py """ import logging from desflow import ConsoleEgress, SimulationContext from dynamic_topology_logic import supervisor logging.basicConfig(level=logging.INFO) app = ( SimulationContext(sim_id="Shop", factor=0) .add_egress(ConsoleEgress()) .add_resource("packers", current_cap=1, max_cap=5) # Called as supervisor(context); it adds the wrappers during the run .add_process(supervisor) ) if __name__ == "__main__": app.run(until=20.0) ``` It imports `supervisor` from `dynamic_topology_logic.py`, which the YAML tab shows. ```python import logging from desflow import ( CapacityConfig, ConsoleEgress, DynamicRealtimeEnvironment, DynamicResource, SimParameter, ) logging.basicConfig(level=logging.INFO) WORK = 3.0 # seconds each job takes NEW_JOBS_EVERY = 4.0 # seconds between rounds of new jobs ADD_WRAPPERS_AT = 12.0 # simulation time at which the gift wrappers are added PARAMS = SimParameter( sim_id="Shop", resources={"packers": CapacityConfig(current_cap=1, max_cap=5)}, ) def worker(env, resources, name, job_id): resource = resources[name] key = f"{name}-{job_id}" env.publish_event(key, {"resource": name, "status": "queued"}) with resource.request() as req: yield req env.publish_event(key, {"resource": name, "status": "started"}) yield env.timeout(WORK) env.publish_event(key, {"resource": name, "status": "finished"}) def supervisor(env, resources): job_id = 0 while True: yield env.timeout(NEW_JOBS_EVERY) if env.now >= ADD_WRAPPERS_AT and "wrappers" not in resources: # Give the gift wrappers their registry paths, then create the resource # that reads its capacity from them. env.registry.register_sim_parameter( SimParameter( sim_id="Shop", resources={"wrappers": CapacityConfig(current_cap=2, max_cap=5)}, ) ) resources["wrappers"] = DynamicResource(env, "Shop", "wrappers") env.publish_event( "supervisor", { "status": "wrappers_added", "capacity": resources["wrappers"].capacity, }, ) # One new job for every resource that exists now. for name in list(resources): env.process(worker(env, resources, name, job_id)) job_id += 1 def run(until=20.0, factor=0): env = DynamicRealtimeEnvironment(factor=factor) env.registry.register_sim_parameter(PARAMS) env.setup_egress([ConsoleEgress()]) resources = {"packers": DynamicResource(env, "Shop", "packers")} env.process(supervisor(env, resources)) try: env.run(until=until) finally: env.teardown() # flushes the buffers and stops the threads return resources if __name__ == "__main__": run() ``` # Switch a Task On Mid-run Sometimes the work itself changes during a run: from 1 minute, the shop gift wraps some orders after packing. Declare the new task from the start, route to it with a weight read from the registry, and change that weight with a scenario step. The weight starts at 0, so no order reaches the task until the step. A blueprint and the builder create their tasks before the clock starts and have no setting that adds one later. A task declared from the start publishes nothing while no order is routed to it, so this page needs no process and no Python in the blueprint. To add a resource during a run instead, see [Add Resources Mid-run](https://jaehyeon.me/desflow/latest/how-to/modelling/dynamic-topology/index.md). ______________________________________________________________________ ## Before You Start - [Task Flow](https://jaehyeon.me/desflow/latest/user-guide/model-parts/task-flow/#weights) explains `next.weights` and the expressions a weight can be. - [Live Parameters](https://jaehyeon.me/desflow/latest/user-guide/live-runs-and-connectors/live-parameters/#find-the-path) explains the registry paths, such as `Shop.variables.wrap_weight`. - [Script an Experiment](https://jaehyeon.me/desflow/latest/user-guide/live-runs-and-connectors/live-parameters/#script-an-experiment) explains scenario steps. ______________________________________________________________________ ## Steps ### Declare the Switch and the New Task Declare a variable that holds the new task's weight, here `wrap_weight` at 0. Declare the new task's resource and service too, as for any other task: the wrappers have a unit from the start, and it stays idle until the switch. ```yaml # The switch: a weight of 0 sends no order to wrap_gift variables: {wrap_weight: 0} resources: packers: {current_cap: 1, max_cap: 1} # The new task's resource exists from the start, unused until the switch wrappers: {current_cap: 1, max_cap: 1} services: packing: {dist: constant, value: 2 s} wrapping: {dist: constant, value: 3 s} ``` ```python # The switch: a weight of 0 sends no order to wrap_gift .add_variable("wrap_weight", 0) .add_resource("packers", current_cap=1, max_cap=1) # The new task's resource exists from the start, unused until the switch .add_resource("wrappers", current_cap=1, max_cap=1) .add_service("packing", dist="constant", value="2 s") .add_service("wrapping", dist="constant", value="3 s") ``` ```python PARAMS = SimParameter( sim_id="Shop", arrival={"orders": DistributionConfig(dist="constant", value=5.0)}, service={ "packing": DistributionConfig(dist="constant", value=2.0), "wrapping": DistributionConfig(dist="constant", value=3.0), }, resources={ "packers": CapacityConfig(current_cap=1, max_cap=1), # The new task's resource exists from the start, unused until the switch "wrappers": CapacityConfig(current_cap=1, max_cap=1), }, # The switch: a weight of 0 sends no order to wrap_gift variables={"wrap_weight": 0}, ) ``` ### Route to the Task by the Switch Give the task before it a weight for the new task that reads the variable: `registry["Shop.variables.wrap_weight"]`. The expression is read each time an order is packed, so a change lands on the next order. Before the switch the weights are 3 to 0 and every order ships. After it they are 3 to 1, so one order in four is wrapped on average. In the low-level API, a `Router` with the same rules chooses the next task, and `choose(..., env=env)` gives it the registry. ```yaml pack_order: service: packing resource: packers payload: {event_type: order_packed} next: # Read when each order is packed: 3 to 0 before the switch, 3 to 1 after it weights: {ship_order: 3, wrap_gift: 'registry["Shop.variables.wrap_weight"]'} wrap_gift: service: wrapping resource: wrappers payload: {event_type: gift_wrapped} next: ship_order ``` ```python @app.task( service_id="packing", resource_id="packers", # Read when each order is packed: 3 to 0 before the switch, 3 to 1 after it next={ "weights": { "ship_order": 3, "wrap_gift": 'registry["Shop.variables.wrap_weight"]', } }, ) def pack_order(task_id: int): return {"event_type": "order_packed"} @app.task(service_id="wrapping", resource_id="wrappers", next="ship_order") def wrap_gift(task_id: int): return {"event_type": "gift_wrapped"} ``` ```python # Read when each order is packed: 3 to 0 before the switch, 3 to 1 after it ROUTE = { "weights": {"ship_order": 3, "wrap_gift": 'registry["Shop.variables.wrap_weight"]'} } ``` ### Turn It On With a Scenario Step A scenario step sets the variable at 1 minute. Its `record` publishes what it did at that time, as a ground-truth record to a sink with `when: labels`. To retire the old route as well, give `ship_order` a weight that reads a second variable, and set that variable to 0 with another step. ```yaml # At 1 minute wrapping starts, and the step records what it did scenario: - at: 1 min path: Shop.variables.wrap_weight value: 1 record: {intervention: gift_wrapping_on} ``` ```python # At 1 minute wrapping starts, and the step records what it did app.add_scenario( [ { "at": "1 min", "path": "Shop.variables.wrap_weight", "value": 1, "record": {"intervention": "gift_wrapping_on"}, } ] ) ``` ```python # At 1 minute wrapping starts, and the step records what it did SCHEDULE = [ { "at": 60, "path": "Shop.variables.wrap_weight", "value": 1, "record": {"intervention": "gift_wrapping_on"}, } ] ``` ______________________________________________________________________ ## Check the Result Run `desflow run switch_a_task_on.yaml`, `python switch_a_task_on_builder.py` or `python switch_a_task_on_low_level.py`. Each runs 5 simulated minutes at once, with an order every 5 seconds: - Before 1 minute, every order goes from `pack_order` to `ship_order`, and no `gift_wrapped` event appears. - From 1 minute, 48 orders are packed and 9 of them are wrapped, the first `orders-12` at 65 seconds. The weights give one in four on average; this one run of 48 orders wraps 9. - The wrapped orders are the same in every form, because each draws the route from the routing task's own random stream, `route.pack_order`, with the same seed. ______________________________________________________________________ ## Full Files Full files ```yaml # The Switch a Task On Mid-run guide: from 1 minute, one order in four is gift wrapped. # Run it with: desflow run switch_a_task_on.yaml simulation: {sim_id: Shop, factor: 0, random_seed: 42} egress: - {type: Console} # The switch: a weight of 0 sends no order to wrap_gift variables: {wrap_weight: 0} resources: packers: {current_cap: 1, max_cap: 1} # The new task's resource exists from the start, unused until the switch wrappers: {current_cap: 1, max_cap: 1} services: packing: {dist: constant, value: 2 s} wrapping: {dist: constant, value: 3 s} arrivals: orders: {dist: constant, value: 5 s, spawn: pack_order} tasks: pack_order: service: packing resource: packers payload: {event_type: order_packed} next: # Read when each order is packed: 3 to 0 before the switch, 3 to 1 after it weights: {ship_order: 3, wrap_gift: 'registry["Shop.variables.wrap_weight"]'} wrap_gift: service: wrapping resource: wrappers payload: {event_type: gift_wrapped} next: ship_order ship_order: payload: {event_type: order_shipped} # At 1 minute wrapping starts, and the step records what it did scenario: - at: 1 min path: Shop.variables.wrap_weight value: 1 record: {intervention: gift_wrapping_on} run: {until: 5 min} ``` ```python """The Switch a Task On Mid-run guide, Builder API: from 1 minute, one order in four is gift wrapped after packing. `build()` returns the app. Run it with: python switch_a_task_on_builder.py, which runs the shop for 5 simulated minutes and prints its events, as switch_a_task_on.yaml does. """ import logging from desflow import ConsoleEgress, SimulationContext logging.basicConfig(level=logging.INFO) def build() -> SimulationContext: """The shop, with gift wrapping declared from the start and switched on at 1 min.""" app = ( SimulationContext(sim_id="Shop", factor=0, random_seed=42) .add_egress(ConsoleEgress()) # The switch: a weight of 0 sends no order to wrap_gift .add_variable("wrap_weight", 0) .add_resource("packers", current_cap=1, max_cap=1) # The new task's resource exists from the start, unused until the switch .add_resource("wrappers", current_cap=1, max_cap=1) .add_service("packing", dist="constant", value="2 s") .add_service("wrapping", dist="constant", value="3 s") .add_arrival("orders", dist="constant", value="5 s", spawn="pack_order") ) @app.task( service_id="packing", resource_id="packers", # Read when each order is packed: 3 to 0 before the switch, 3 to 1 after it next={ "weights": { "ship_order": 3, "wrap_gift": 'registry["Shop.variables.wrap_weight"]', } }, ) def pack_order(task_id: int): return {"event_type": "order_packed"} @app.task(service_id="wrapping", resource_id="wrappers", next="ship_order") def wrap_gift(task_id: int): return {"event_type": "gift_wrapped"} @app.task() def ship_order(task_id: int): return {"event_type": "order_shipped"} # At 1 minute wrapping starts, and the step records what it did app.add_scenario( [ { "at": "1 min", "path": "Shop.variables.wrap_weight", "value": 1, "record": {"intervention": "gift_wrapping_on"}, } ] ) return app if __name__ == "__main__": build().run(until=300) ``` ```python """The Switch a Task On Mid-run guide, low-level API: from 1 minute, one order in four is gift wrapped after packing. The low-level version of switch_a_task_on_builder.py: a Router reads the weight from the registry each time an order is packed, and `run_scenario` changes it at 1 minute. python switch_a_task_on_low_level.py runs 5 simulated minutes at once. """ import itertools import logging from desflow import ( CapacityConfig, ConsoleEgress, DistributionConfig, DynamicRealtimeEnvironment, DynamicResource, Router, Sampler, SimParameter, Upstream, run_scenario, ) logging.basicConfig(level=logging.INFO) UNTIL = 300 PARAMS = SimParameter( sim_id="Shop", arrival={"orders": DistributionConfig(dist="constant", value=5.0)}, service={ "packing": DistributionConfig(dist="constant", value=2.0), "wrapping": DistributionConfig(dist="constant", value=3.0), }, resources={ "packers": CapacityConfig(current_cap=1, max_cap=1), # The new task's resource exists from the start, unused until the switch "wrappers": CapacityConfig(current_cap=1, max_cap=1), }, # The switch: a weight of 0 sends no order to wrap_gift variables={"wrap_weight": 0}, ) # Read when each order is packed: 3 to 0 before the switch, 3 to 1 after it ROUTE = { "weights": {"ship_order": 3, "wrap_gift": 'registry["Shop.variables.wrap_weight"]'} } # At 1 minute wrapping starts, and the step records what it did SCHEDULE = [ { "at": 60, "path": "Shop.variables.wrap_weight", "value": 1, "record": {"intervention": "gift_wrapping_on"}, } ] def build(env: DynamicRealtimeEnvironment) -> None: """Starts the orders and the scenario on an environment that has PARAMS.""" sampler = Sampler(seed=42) route = Router(ROUTE) # The routing task's own stream, as the blueprint and the builder draw from route.rng = sampler.generator("route.pack_order") shop = { "packers": DynamicResource(env, "Shop", "packers"), "wrappers": DynamicResource(env, "Shop", "wrappers"), } ids = { name: itertools.count() for name in ("pack_order", "wrap_gift", "ship_order") } def serve(key, task, service, resource, payload): task_id = next(ids[task]) env.publish_event(key, {"status": "queued"}, task, task_id) with shop[resource].request() as request: yield request env.publish_event(key, {"status": "started"}, task, task_id) path = f"Shop.service.{service}" yield env.timeout(sampler.sample(env.registry.get_config(path))) env.publish_event(key, payload, task, task_id) return task_id def order(key): task_id = yield from serve( key, "pack_order", "packing", "packers", {"event_type": "order_packed"} ) packed = Upstream(task_id, key, {}, {"event_type": "order_packed"}) if route.choose(packed, env=env) == "wrap_gift": yield from serve( key, "wrap_gift", "wrapping", "wrappers", {"event_type": "gift_wrapped"} ) env.publish_event( key, {"event_type": "order_shipped"}, "ship_order", next(ids["ship_order"]) ) def orders(): gap = env.registry.get_config("Shop.arrival.orders") for number in itertools.count(1): yield env.timeout(sampler.sample(gap)) env.process(order(f"orders-{number}")) env.process(orders()) env.process(run_scenario(env, SCHEDULE, until=UNTIL)) def run(egress=None): env = DynamicRealtimeEnvironment(factor=0) env.registry.register_sim_parameter(PARAMS) env.setup_egress(egress or [ConsoleEgress()]) build(env) try: env.run(until=UNTIL) finally: env.teardown() if __name__ == "__main__": run() ``` # Serve Entities Together Serve several entities with one run of a resource, such as an oven that bakes a tray of loaves at a time. The entities wait together in a batch, the resource serves the whole batch once, and each entity then goes on by itself. ______________________________________________________________________ ## Before You Start - [Several Resources](https://jaehyeon.me/desflow/latest/user-guide/resources/several-resources/#several-resources) describes how a task holds a resource and what its queue does. - [Tasks and Processes](https://jaehyeon.me/desflow/latest/user-guide/tasks-and-processes/index.md) describes `next`, which each member keeps. [Add Reneging and Balking](https://jaehyeon.me/desflow/latest/how-to/modelling/reneging-and-balking/index.md) shows `patience` and [Interruptions](https://jaehyeon.me/desflow/latest/learn/shop-logic/interruptions/index.md) shows `on_interrupt`, which each member keeps too. ______________________________________________________________________ ## Steps ### Group the Entities in a Batch `batch: {size, timeout, close_when, name}` makes the entities that start the task wait together. The batch closes when `size` members have joined, or `timeout` after its first member, whichever comes first. The task's `resource` and service then run once for the whole batch. Every member publishes `started` at the close, and goes on with its own payload and its own `next`, in the order the members joined. `size` is a number, or text that is read as an expression for the first member when it joins. A size of 1 or less closes the batch at its first member. `timeout` is a duration. Here seven orders arrive 1 second apart, and an oven bakes them in batches of 3, or sooner when 2.5 seconds pass. The oven takes 4 seconds for a batch: ```yaml bake: # The batch closes with 3 members, or 2.5 seconds after its first member # name defaults to the task's name; tasks with the same name share one open batch batch: {name: oven_run, size: 3, timeout: 2.5} resource: oven # one run of the oven serves the whole batch service_time: 4 payload: {event_type: baked} ``` ```python # The batch closes with 3 members, or 2.5 seconds after its first member @app.task( batch={"size": 3, "timeout": 2.5}, resource_id="oven", # one run of the oven serves the whole batch service_time=4, ) def bake(task_id): return {"event_type": "baked"} ``` ```python def closes_by_size(batch): return len(batch["members"]) == SIZE def close(batch): if not batch["closed"].triggered: batch["closed"].succeed() open_batch.clear() def timer(batch): yield env.timeout(TIMEOUT) # 2.5 seconds after the first member close(batch) def member(key, batch): batch["members"].append(key) if closes(batch): # tested each time a member joins close(batch) yield batch["closed"] seen.append((env.now, key, "started")) # every member, at the close if key == batch["members"][0]: # The first member runs the oven once for the whole batch with oven.request() as request: yield request yield env.timeout(SERVICE) batch["served"].succeed() yield batch["served"] seen.append((env.now, key, "baked")) # every member goes on by itself ``` The Low-level form has no batch to call, so the script keeps a list of members and an event that closes it. `closes_by_size` is the test made each time a member joins. The first member runs the oven once, and every member waits for that run to end. ### Close a Batch by an Expression `close_when` is an expression that is read each time a member joins. It reads `batch.size`, the number of members, and `batch.age`, the seconds since the first member joined. Neither name works anywhere else. Because the expression is read only when a member joins, a batch does not close by `batch.age` alone while no new member joins. Add a `timeout` to a batch that must close without one. ```yaml # Close with 2 members once the first has waited 2 seconds, or at 5 members batch: {size: 5, close_when: batch.size >= 2 and batch.age >= 2} ``` `@app.task(batch=...)` takes the same mapping as a dict: `batch={"size": 5, "close_when": "batch.size >= 2 and batch.age >= 2"}`. ```python def closes_by_expression(batch): """batch.size >= 2 and batch.age >= 2, or 5 members.""" size = len(batch["members"]) age = env.now - batch["since"] # seconds since the first member joined return size == 5 or (size >= 2 and age >= 2) ``` `member` calls this function each time a member joins, in place of `closes_by_size`, and the batch has no timer. Run the Builder script as `python serve_together.py close_when` to print these lines; the YAML file and the Low-level script give the same: ```text check: (3.0, 'orders-1', 'started') check: (3.0, 'orders-2', 'started') check: (3.0, 'orders-3', 'started') check: (6.0, 'orders-4', 'started') check: (6.0, 'orders-5', 'started') check: (6.0, 'orders-6', 'started') check: (7.0, 'orders-1', 'baked') check: (7.0, 'orders-2', 'baked') check: (7.0, 'orders-3', 'baked') check: (11.0, 'orders-4', 'baked') check: (11.0, 'orders-5', 'baked') check: (11.0, 'orders-6', 'baked') ``` The batch closes at the first join after its first member has waited 2 seconds, which is the third order, at 3 seconds. The second batch closes at 6 in the same way, and the oven bakes it from 7 to 11. The seventh order joins a new batch at 7 and waits for ever, because the batch has no `timeout` and no member joins after it. ### Share a Batch Between Tasks `name` names the batch, and it defaults to the name of the task. Tasks that use the same `name` share one open batch, so a batch can hold bread and rolls together. They must have the same `size`, `timeout`, `close_when`, `resource` and service (`service` or `service_time`). A file in which they differ is refused when it loads, and the message names both tasks. Values are compared by what they mean, so a generator written the same way, an expression with other spacing and a number written as text agree. ### Know What Happens to a Member Each member keeps its own `on_interrupt`, `patience`, payload and `next`. - An interrupt before the close takes the member out of the batch. Under `resume` and `restart` it joins again at the back, its wait counts the time it spent in the batch, and it publishes `interrupted` and no `resumed`. - After the close, the member that serves the batch publishes `interrupted` when it is interrupted while it waits for the unit, under `resume` or `restart`, and publishes `resumed` when it is granted the unit. - Any other member of a closed batch publishes `interrupted` and `resumed` at the same instant, and goes on waiting to be served by the member that serves. - Under `on_interrupt: abandon` a member leaves the batch, and `size` counts the members that are left. If the member that serves leaves, the next member serves, and its service starts again. - A member's `patience` counts until the batch closes. A member that reneges leaves the batch. A closed batch does not renege while its service runs. - A member that balks at a full line leaves, the next member asks for the unit, and it balks too. - A failure of a member's task fails that member once, and it goes to its own `on_fail`. A batch takes no `get`, `seize`, `open` or `cancel`. ______________________________________________________________________ ## Check the Result Run the Builder script, and keep the lines that start with `check:`. Each line is the time, the order and the status of one record: ```bash # With uv uv run --no-project --with desflow serve_together.py # With pip pip install desflow python serve_together.py ``` ```text check: (3.0, 'orders-1', 'started') check: (3.0, 'orders-2', 'started') check: (3.0, 'orders-3', 'started') check: (6.0, 'orders-4', 'started') check: (6.0, 'orders-5', 'started') check: (6.0, 'orders-6', 'started') check: (7.0, 'orders-1', 'baked') check: (7.0, 'orders-2', 'baked') check: (7.0, 'orders-3', 'baked') check: (9.5, 'orders-7', 'started') check: (11.0, 'orders-4', 'baked') check: (11.0, 'orders-5', 'baked') check: (11.0, 'orders-6', 'baked') check: (15.0, 'orders-7', 'baked') ``` The first batch closes at 3 seconds, when its third order joins. The second closes at 6, and its members publish `started` then, but the oven is busy until 7, so they finish at 11. The seventh order is alone, so its batch closes at 9.5, 2.5 seconds after it joined, and the oven bakes it from 11 to 15. Run `serve_together_low_level.py` for the Low-level form. It prints the same rows, with whole numbers for the times it gets from whole-number timeouts, such as `(3, 'orders-1', 'started')`. ______________________________________________________________________ ## Full Files Full files ```yaml # The Serve Entities Together guide: seven orders arrive 1 second apart, and an # oven bakes them in batches of 3, or sooner when 2.5 seconds pass. Run it with: # desflow run serve_together.yaml --stdout simulation: {sim_id: Bakery, factor: 0, random_seed: 42} resources: oven: {current_cap: 1} arrivals: orders: {dist: constant, value: 1, max_events: 7, spawn: bake} tasks: bake: # The batch closes with 3 members, or 2.5 seconds after its first member # name defaults to the task's name; tasks with the same name share one open batch batch: {name: oven_run, size: 3, timeout: 2.5} resource: oven # one run of the oven serves the whole batch service_time: 4 payload: {event_type: baked} run: {until: 30} ``` ```python """The Serve Entities Together guide, builder API: seven orders arrive 1 second apart, and an oven bakes them in batches of 3, or sooner when 2.5 seconds pass. `batch_records(blueprint)` returns the (time, key, status) of each `started` and `baked` record; with a path, it runs that blueprint, and without one, it builds the model, with a batch that closes by an expression when `close_when` is true. """ import asyncio import queue import sys from desflow import SimulationContext class Capture: """An egress that keeps every event it receives.""" def __init__(self): self.events = [] async def run(self, egress_queue): try: while True: try: batch = egress_queue.get_nowait() self.events += [r for r in batch if r["stream_type"] == "event"] except queue.Empty: await asyncio.sleep(0.005) except asyncio.CancelledError: pass def _app() -> SimulationContext: app = SimulationContext("Bakery", factor=0) app.add_resource("oven", current_cap=1) app.add_arrival("orders", "constant", value=1, max_events=7, spawn="bake") return app def build() -> SimulationContext: app = _app() # The batch closes with 3 members, or 2.5 seconds after its first member @app.task( batch={"size": 3, "timeout": 2.5}, resource_id="oven", # one run of the oven serves the whole batch service_time=4, ) def bake(task_id): return {"event_type": "baked"} return app def build_close_when() -> SimulationContext: app = _app() # Close with 2 members once the first has waited 2 seconds, or at 5 members @app.task( batch={"size": 5, "close_when": "batch.size >= 2 and batch.age >= 2"}, resource_id="oven", service_time=4, ) def bake(task_id): return {"event_type": "baked"} return app def batch_records(blueprint: str = "", close_when: bool = False) -> list: if blueprint: app = SimulationContext.from_yaml(blueprint) else: app = build_close_when() if close_when else build() capture = Capture() app.add_egress(capture) app.run(until=30) return sorted( (e["sim_ts"], e["key"], e["value"].get("status", "baked")) for e in capture.events if e["value"].get("status", "baked") in ("started", "baked") ) if __name__ == "__main__": for row in batch_records(close_when="close_when" in sys.argv[1:]): print("check:", row) ``` ```python """The Serve Entities Together guide, low-level API: seven orders arrive 1 second apart, and an oven bakes them in batches of 3, or sooner when 2.5 seconds pass. SimPy has no batch, so a batch is a list of members and an event that closes it. `batch_records()` returns the (time, key, status) of each `started` and `baked` record, for a batch that closes by size and timeout, or by an expression when `close_when` is true. """ from simpy import Resource from desflow import DynamicRealtimeEnvironment SIZE = 3 # members that close a batch TIMEOUT = 2.5 # seconds after the first member that close it SERVICE = 4 # seconds the oven takes for a whole batch def batch_records(close_when: bool = False) -> list: env = DynamicRealtimeEnvironment(factor=0) oven = Resource(env, capacity=1) seen = [] open_batch: list = [] # the batch that still takes members: none, or one def closes_by_size(batch): return len(batch["members"]) == SIZE def close(batch): if not batch["closed"].triggered: batch["closed"].succeed() open_batch.clear() def timer(batch): yield env.timeout(TIMEOUT) # 2.5 seconds after the first member close(batch) def member(key, batch): batch["members"].append(key) if closes(batch): # tested each time a member joins close(batch) yield batch["closed"] seen.append((env.now, key, "started")) # every member, at the close if key == batch["members"][0]: # The first member runs the oven once for the whole batch with oven.request() as request: yield request yield env.timeout(SERVICE) batch["served"].succeed() yield batch["served"] seen.append((env.now, key, "baked")) # every member goes on by itself def closes_by_expression(batch): """batch.size >= 2 and batch.age >= 2, or 5 members.""" size = len(batch["members"]) age = env.now - batch["since"] # seconds since the first member joined return size == 5 or (size >= 2 and age >= 2) closes = closes_by_expression if close_when else closes_by_size def orders(): for number in range(1, 8): yield env.timeout(1) if not open_batch: batch = { "members": [], "since": env.now, "closed": env.event(), "served": env.event(), } open_batch.append(batch) if not close_when: env.process(timer(batch)) env.process(member(f"orders-{number}", open_batch[0])) env.process(orders()) env.run(until=30) env.teardown() return sorted(seen) if __name__ == "__main__": for row in batch_records(): print("check:", row) ``` # Send Data to a Sink Generate orders and write them to the console, a Kafka topic, a PostgreSQL table or a JSON Lines file. The model is the same for every sink, and only the egress changes. ______________________________________________________________________ ## Before You Start - The commands run from the root of a clone of the repository, where the files are in `docs/snippets/generate-data/`. The Full Files block of this page holds the same files, for a reader who saves them by hand. ```bash git clone https://github.com/jaehyeon-kim/desflow.git cd desflow ``` - [First Simulation](https://jaehyeon.me/desflow/latest/learn/first-model/first-simulation/index.md) explains arrivals, tasks and the records a run writes. - [Streaming Out](https://jaehyeon.me/desflow/latest/learn/running-live/streaming-out/index.md) shows the record each run writes, and [Egress, Batching and Delivery](https://jaehyeon.me/desflow/latest/user-guide/live-runs-and-connectors/egress/index.md) lists every sink and its settings. - The console needs nothing. The Kafka sink needs `pip install "desflow[kafka]"` and a broker (`odctl up kafka-lite`), the PostgreSQL sink needs `pip install "desflow[postgres]"` and a database (`odctl up postgres`), and the file sink needs `pip install "desflow[parquet]"`. The Builder and Low-level files import all four sinks, so they need the `kafka` and `postgres` extras even for the console, and the `parquet` extra for the file sink. ______________________________________________________________________ ## Steps ### Describe the Arrival An arrival starts one order about every second: `dist: exponential` with `rate: 1` draws gaps that average 1 second, and `spawn: order` names the task each arrival starts. ```yaml arrivals: orders: {dist: exponential, rate: 1, spawn: order} ``` ```python app.add_arrival("orders", "exponential", rate=1, spawn="order") ``` ```python sampler = Sampler(seed=42) customer = sampler.generator("tasks.order.payload.customer_id") total = sampler.generator("tasks.order.payload.total") orders_gap = DistributionConfig(dist="exponential", rate=1) # The random sequence the blueprint's draw uses orders_gap.stream = "arrival.orders" ``` `Sampler(seed=42)` supplies every draw: a random generator for each payload field and for the gap. The `stream` line names the random sequence the blueprint uses for this arrival, so the three forms draw the same gaps. ### Generate the Payload The `payload` of a task maps each field to a generator. [`sequence`](https://jaehyeon.me/desflow/latest/generators/text-and-ids/sequence/index.md) numbers the orders from 1, [`integer`](https://jaehyeon.me/desflow/latest/generators/random-numbers/integer/index.md) draws a customer from 1 to 100, and [`uniform`](https://jaehyeon.me/desflow/latest/generators/random-numbers/uniform/index.md) draws a total from 5 to 200 with 2 decimals. ```yaml tasks: order: payload: order_id: {gen: sequence, start: 1} customer_id: {gen: integer, bounds: [1, 100]} total: {gen: uniform, low: 5, high: 200, decimals: 2} ``` ```python order_payload = Template( { "order_id": {"gen": "sequence", "start": 1}, "customer_id": {"gen": "integer", "bounds": [1, 100]}, "total": {"gen": "uniform", "low": 5, "high": 200, "decimals": 2}, }, name="tasks.order", ) @app.task(name="order") def order(task_id): """Gives one order record.""" return order_payload ``` ```python def orders_source(): number = 0 while True: yield env.timeout(sampler.sample(orders_gap)) number += 1 payload = { "order_id": number, "customer_id": int(customer.integers(1, 100 + 1)), "total": round(float(total.uniform(5, 200)), 2), } env.publish_event( f"orders-{number}", payload, task="order", instance=number - 1 ) env.process(orders_source()) ``` A Low-level script has no payload mapping. It draws each value and passes the finished dictionary to `env.publish_event`. ### Choose the Sink The egress decides where the records go. `send_data_to_kafka.yaml`, `send_data_to_postgres.yaml` and `send_data_to_a_file.yaml` are the console file with another `egress` section, and each Python file holds the four sinks as functions. ```yaml egress: - {type: Console} ``` ```yaml egress: - type: Kafka config: bootstrap_servers: ${KAFKA_BOOTSTRAP_SERVERS:-localhost:9092} event_topic: orders ``` ```yaml egress: - type: Postgres config: connection_dsn: postgresql://user:password@127.0.0.1:5432/odctl tables: orders: columns: {order_id: INT, customer_id: INT, total: REAL} primary_key: order_id ``` ```yaml egress: - type: Jsonl config: default_path: ${DEST_PATH:-data}/orders.jsonl ``` ```python def console_sink() -> ConsoleEgress: """Prints each record.""" return ConsoleEgress() def kafka_sink() -> KafkaEgress: """Writes the records to the topic `orders`.""" return KafkaEgress( bootstrap_servers=os.environ.get("KAFKA_BOOTSTRAP_SERVERS", "localhost:9092"), event_topic="orders", ) def postgres_sink() -> PostgresEgress: """Writes each record as a row of the table `orders`.""" return PostgresEgress( DSN, tables={ "orders": { "columns": {"order_id": "INT", "customer_id": "INT", "total": "REAL"}, "primary_key": "order_id", } }, ) def file_sink() -> JsonlStorageEgress: """Writes the records to a JSON Lines file.""" return JsonlStorageEgress( default_path=f"{os.environ.get('DEST_PATH', 'data')}/orders.jsonl" ) ``` `build(sink)` takes one of these functions and uses the console when it gets none, so `build(kafka_sink).run(until=UNTIL)` writes to Kafka. The `SINK` environment variable of Check the Result picks one of them when the file runs as a script. ```python def console_sink() -> ConsoleEgress: """Prints each record.""" return ConsoleEgress() def kafka_sink() -> KafkaEgress: """Writes the records to the topic `orders`.""" return KafkaEgress( bootstrap_servers=os.environ.get("KAFKA_BOOTSTRAP_SERVERS", "localhost:9092"), event_topic="orders", ) def postgres_sink() -> PostgresEgress: """Writes each record as a row of the table `orders`.""" return PostgresEgress( DSN, tables={ "orders": { "columns": {"order_id": "INT", "customer_id": "INT", "total": "REAL"}, "primary_key": "order_id", } }, ) def file_sink() -> JsonlStorageEgress: """Writes the records to a JSON Lines file.""" return JsonlStorageEgress( default_path=f"{os.environ.get('DEST_PATH', 'data')}/orders.jsonl" ) ``` `run(sink)` takes one of these functions in the same way and calls `env.setup_egress` with it. The `SINK` environment variable of Check the Result picks one of them when the file runs as a script. ______________________________________________________________________ ## Check the Result Run the console model for 10 simulated seconds and print its first 5 records. Orders count from 1, every customer is from 1 to 100 and every total is from 5 to 200. ```bash desflow run docs/snippets/generate-data/send_data_to_a_sink.yaml --sample 5 desflow run docs/snippets/generate-data/send_data_to_kafka.yaml desflow run docs/snippets/generate-data/send_data_to_postgres.yaml desflow run docs/snippets/generate-data/send_data_to_a_file.yaml ``` The first command prints the records. Each of the other three runs one sink and prints log lines only. Read the records back from the sink. Run these after the run, with the service from [Before You Start](#before-you-start) still up for Kafka and PostgreSQL: ```bash # Kafka: the first three records of the topic orders docker exec kafka /opt/kafka/bin/kafka-console-consumer.sh \ --bootstrap-server localhost:9092 --topic orders --from-beginning --max-messages 3 # PostgreSQL: the number of rows of the table orders docker exec postgres psql -U user -d odctl -c "SELECT count(*) FROM orders;" # File: the number of records in the files of the folder data cat data/orders_*.jsonl | wc -l ``` A run of 10 simulated seconds writes 7 records, so the PostgreSQL count and the file count are 7 after one run. A second run appends to the topic and adds a new file to the folder, and PostgreSQL skips an order number the table already holds, so the count stays at 7 until you drop the table. ```bash python docs/snippets/generate-data/send_data_to_a_sink_builder.py SINK=kafka python docs/snippets/generate-data/send_data_to_a_sink_builder.py SINK=postgres python docs/snippets/generate-data/send_data_to_a_sink_builder.py SINK=file python docs/snippets/generate-data/send_data_to_a_sink_builder.py ``` `SINK` names one of the four functions of the Steps section, and the console is the default. The console run prints every record of the run as an `[EVT]` line with the same fields and values. The other three print log lines only. Read the records back from the sink. Run these after the run, with the service from [Before You Start](#before-you-start) still up for Kafka and PostgreSQL: ```bash # Kafka: the first three records of the topic orders docker exec kafka /opt/kafka/bin/kafka-console-consumer.sh \ --bootstrap-server localhost:9092 --topic orders --from-beginning --max-messages 3 # PostgreSQL: the number of rows of the table orders docker exec postgres psql -U user -d odctl -c "SELECT count(*) FROM orders;" # File: the number of records in the files of the folder data cat data/orders_*.jsonl | wc -l ``` A run of 10 simulated seconds writes 7 records, so the PostgreSQL count and the file count are 7 after one run. A second run appends to the topic and adds a new file to the folder, and PostgreSQL skips an order number the table already holds, so the count stays at 7 until you drop the table. ```bash python docs/snippets/generate-data/send_data_to_a_sink_low_level.py SINK=kafka python docs/snippets/generate-data/send_data_to_a_sink_low_level.py SINK=postgres python docs/snippets/generate-data/send_data_to_a_sink_low_level.py SINK=file python docs/snippets/generate-data/send_data_to_a_sink_low_level.py ``` `SINK` names one of the four functions of the Steps section, and the console is the default. The console run prints every record of the run as an `[EVT]` line with the same fields and values. The other three print log lines only. Read the records back from the sink. Run these after the run, with the service from [Before You Start](#before-you-start) still up for Kafka and PostgreSQL: ```bash # Kafka: the first three records of the topic orders docker exec kafka /opt/kafka/bin/kafka-console-consumer.sh \ --bootstrap-server localhost:9092 --topic orders --from-beginning --max-messages 3 # PostgreSQL: the number of rows of the table orders docker exec postgres psql -U user -d odctl -c "SELECT count(*) FROM orders;" # File: the number of records in the files of the folder data cat data/orders_*.jsonl | wc -l ``` A run of 10 simulated seconds writes 7 records, so the PostgreSQL count and the file count are 7 after one run. A second run appends to the topic and adds a new file to the folder, and PostgreSQL skips an order number the table already holds, so the count stays at 7 until you drop the table. ```text {"stream_type":"event","sim_ts":0.3141556656469718,"timestamp":"...","key":"orders-1","task":"order","instance":0,"value":{"order_id":1,"customer_id":95,"total":161.55}} {"stream_type":"event","sim_ts":2.4671694506095694,"timestamp":"...","key":"orders-2","task":"order","instance":1,"value":{"order_id":2,"customer_id":67,"total":177.63}} {"stream_type":"event","sim_ts":2.5122243094067938,"timestamp":"...","key":"orders-3","task":"order","instance":2,"value":{"order_id":3,"customer_id":26,"total":59.25}} {"stream_type":"event","sim_ts":3.124962891934927,"timestamp":"...","key":"orders-4","task":"order","instance":3,"value":{"order_id":4,"customer_id":67,"total":141.25}} {"stream_type":"event","sim_ts":4.773803932004462,"timestamp":"...","key":"orders-5","task":"order","instance":4,"value":{"order_id":5,"customer_id":84,"total":15.19}} ``` The Kafka, PostgreSQL and file models write these same records to their sink. Kafka receives them on the topic `orders` and PostgreSQL writes a row of the table `orders` for each, with `order_id` as the primary key. The file model writes the records as flat rows of JSON Lines files named `data/orders_<8 hex digits>.jsonl`, one file for each batch, as [Egress, Batching and Delivery](https://jaehyeon.me/desflow/latest/user-guide/live-runs-and-connectors/egress/index.md) sets out for file names. `DEST_PATH` sets another folder. ______________________________________________________________________ ## Full Files Full files ```yaml # Send data to a sink: one arrival, one generated payload, written to the console. # # An order arrives about once a second. Its record holds an order number, a customer # and a total. The Console egress prints each record. The files send_data_to_kafka.yaml, # send_data_to_postgres.yaml and send_data_to_a_file.yaml are this file with another # egress. # # Needs: nothing. # Run it with: desflow run docs/snippets/generate-data/send_data_to_a_sink.yaml simulation: sim_id: Shop factor: 0 random_seed: 42 logical_start_time: 2026-01-01T00:00:00 egress: - {type: Console} arrivals: orders: {dist: exponential, rate: 1, spawn: order} tasks: order: payload: order_id: {gen: sequence, start: 1} customer_id: {gen: integer, bounds: [1, 100]} total: {gen: uniform, low: 5, high: 200, decimals: 2} run: {until: 10} ``` ```yaml # Send data to a sink: the orders of send_data_to_a_sink.yaml, written to a Kafka topic. # # Only the egress differs from that file. # # Needs: a broker, with odctl up kafka-lite, and the kafka extra. # KAFKA_BOOTSTRAP_SERVERS sets the broker address. # Run it with: desflow run docs/snippets/generate-data/send_data_to_kafka.yaml simulation: sim_id: Shop factor: 0 random_seed: 42 logical_start_time: 2026-01-01T00:00:00 egress: - type: Kafka config: bootstrap_servers: ${KAFKA_BOOTSTRAP_SERVERS:-localhost:9092} event_topic: orders arrivals: orders: {dist: exponential, rate: 1, spawn: order} tasks: order: payload: order_id: {gen: sequence, start: 1} customer_id: {gen: integer, bounds: [1, 100]} total: {gen: uniform, low: 5, high: 200, decimals: 2} run: {until: 10} ``` ```yaml # Send data to a sink: the orders of send_data_to_a_sink.yaml, written to a PostgreSQL # table. # # Only the egress differs from that file. # # Needs: a database, with odctl up postgres, and the postgres extra. # Run it with: desflow run docs/snippets/generate-data/send_data_to_postgres.yaml simulation: sim_id: Shop factor: 0 random_seed: 42 logical_start_time: 2026-01-01T00:00:00 egress: - type: Postgres config: connection_dsn: postgresql://user:password@127.0.0.1:5432/odctl tables: orders: columns: {order_id: INT, customer_id: INT, total: REAL} primary_key: order_id arrivals: orders: {dist: exponential, rate: 1, spawn: order} tasks: order: payload: order_id: {gen: sequence, start: 1} customer_id: {gen: integer, bounds: [1, 100]} total: {gen: uniform, low: 5, high: 200, decimals: 2} run: {until: 10} ``` ```yaml # Send data to a sink: the orders of send_data_to_a_sink.yaml, written to a JSON # Lines file. # # Only the egress differs from that file. # # Needs: the parquet extra, which holds the file writers. DEST_PATH sets the folder # (data by default). # Run it with: desflow run docs/snippets/generate-data/send_data_to_a_file.yaml simulation: sim_id: Shop factor: 0 random_seed: 42 logical_start_time: 2026-01-01T00:00:00 egress: - type: Jsonl config: default_path: ${DEST_PATH:-data}/orders.jsonl arrivals: orders: {dist: exponential, rate: 1, spawn: order} tasks: order: payload: order_id: {gen: sequence, start: 1} customer_id: {gen: integer, bounds: [1, 100]} total: {gen: uniform, low: 5, high: 200, decimals: 2} run: {until: 10} ``` ```python """Send data to a sink: one arrival, one generated payload, builder API. The builder version of `send_data_to_a_sink.yaml`: an order about every second, written to the console, and to Kafka, PostgreSQL or a JSON Lines file when `sink` is another function of the file. Needs: the kafka and postgres extras, because the file imports every sink, and the parquet extra for the file sink. The console needs no service. The Kafka sink needs a broker (odctl up kafka-lite) and the PostgreSQL sink a database (odctl up postgres). Run it with: python docs/snippets/generate-data/send_data_to_a_sink_builder.py SINK sets the sink: console (the default), kafka, postgres or file. """ import logging import os from datetime import datetime, timezone from desflow import ( ConsoleEgress, JsonlStorageEgress, KafkaEgress, PostgresEgress, SimulationContext, ) from desflow.values import Template UNTIL = 10 DSN = "postgresql://user:password@127.0.0.1:5432/odctl" def console_sink() -> ConsoleEgress: """Prints each record.""" return ConsoleEgress() def kafka_sink() -> KafkaEgress: """Writes the records to the topic `orders`.""" return KafkaEgress( bootstrap_servers=os.environ.get("KAFKA_BOOTSTRAP_SERVERS", "localhost:9092"), event_topic="orders", ) def postgres_sink() -> PostgresEgress: """Writes each record as a row of the table `orders`.""" return PostgresEgress( DSN, tables={ "orders": { "columns": {"order_id": "INT", "customer_id": "INT", "total": "REAL"}, "primary_key": "order_id", } }, ) def file_sink() -> JsonlStorageEgress: """Writes the records to a JSON Lines file.""" return JsonlStorageEgress( default_path=f"{os.environ.get('DEST_PATH', 'data')}/orders.jsonl" ) SINKS = { "console": console_sink, "kafka": kafka_sink, "postgres": postgres_sink, "file": file_sink, } def build(sink=console_sink) -> SimulationContext: """Builds the model, with the egress that `sink` makes.""" app = SimulationContext( sim_id="Shop", factor=0, random_seed=42, logical_start_time=datetime(2026, 1, 1, tzinfo=timezone.utc), ) app.add_egress(sink()) app.add_arrival("orders", "exponential", rate=1, spawn="order") order_payload = Template( { "order_id": {"gen": "sequence", "start": 1}, "customer_id": {"gen": "integer", "bounds": [1, 100]}, "total": {"gen": "uniform", "low": 5, "high": 200, "decimals": 2}, }, name="tasks.order", ) @app.task(name="order") def order(task_id): """Gives one order record.""" return order_payload return app if __name__ == "__main__": logging.basicConfig(level=logging.INFO, format="%(levelname)s %(message)s") build(SINKS[os.environ.get("SINK", "console")]).run(until=UNTIL) ``` ```python """Send data to a sink: one arrival, one generated payload, low-level API. The low-level version of `send_data_to_a_sink.yaml`: plain SimPy on a `DynamicRealtimeEnvironment`, which publishes each record with `publish_event`. Each draw is made with `Sampler`, from the random sequence the blueprint's generator at that place uses, so the draws are the blueprint's. The four sinks are functions, and `run` takes one of them. Needs: the kafka and postgres extras, because the file imports every sink, and the parquet extra for the file sink. The console needs no service. The Kafka sink needs a broker (odctl up kafka-lite) and the PostgreSQL sink a database (odctl up postgres). Run it with: python docs/snippets/generate-data/send_data_to_a_sink_low_level.py SINK sets the sink: console (the default), kafka, postgres or file. """ import logging import os from datetime import datetime, timezone from desflow import ( ConsoleEgress, DistributionConfig, DynamicRealtimeEnvironment, JsonlStorageEgress, KafkaEgress, PostgresEgress, Sampler, ) UNTIL = 10 DSN = "postgresql://user:password@127.0.0.1:5432/odctl" def console_sink() -> ConsoleEgress: """Prints each record.""" return ConsoleEgress() def kafka_sink() -> KafkaEgress: """Writes the records to the topic `orders`.""" return KafkaEgress( bootstrap_servers=os.environ.get("KAFKA_BOOTSTRAP_SERVERS", "localhost:9092"), event_topic="orders", ) def postgres_sink() -> PostgresEgress: """Writes each record as a row of the table `orders`.""" return PostgresEgress( DSN, tables={ "orders": { "columns": {"order_id": "INT", "customer_id": "INT", "total": "REAL"}, "primary_key": "order_id", } }, ) def file_sink() -> JsonlStorageEgress: """Writes the records to a JSON Lines file.""" return JsonlStorageEgress( default_path=f"{os.environ.get('DEST_PATH', 'data')}/orders.jsonl" ) START = datetime(2026, 1, 1, tzinfo=timezone.utc) ENVIRONMENT: dict = {"logical_start_time": START, "timezone": "UTC"} def build(env: DynamicRealtimeEnvironment) -> None: """Starts the arrivals on `env`.""" sampler = Sampler(seed=42) customer = sampler.generator("tasks.order.payload.customer_id") total = sampler.generator("tasks.order.payload.total") orders_gap = DistributionConfig(dist="exponential", rate=1) # The random sequence the blueprint's draw uses orders_gap.stream = "arrival.orders" def orders_source(): number = 0 while True: yield env.timeout(sampler.sample(orders_gap)) number += 1 payload = { "order_id": number, "customer_id": int(customer.integers(1, 100 + 1)), "total": round(float(total.uniform(5, 200)), 2), } env.publish_event( f"orders-{number}", payload, task="order", instance=number - 1 ) env.process(orders_source()) SINKS = { "console": console_sink, "kafka": kafka_sink, "postgres": postgres_sink, "file": file_sink, } def run(sink=console_sink) -> None: """Runs the model unpaced into the egress that `sink` makes.""" env = DynamicRealtimeEnvironment(factor=0, **ENVIRONMENT) env.setup_egress([sink()]) build(env) try: env.run(until=UNTIL) finally: env.teardown() if __name__ == "__main__": logging.basicConfig(level=logging.INFO, format="%(levelname)s %(message)s") run(SINKS[os.environ.get("SINK", "console")]) ``` # Extend Payloads Extend a payload beyond plain numbers: fill fields with values that look real, such as names, emails, cities and jobs, and keep the fields that belong together consistent, such as a product's sku, title and price. ______________________________________________________________________ ## Before You Start - The commands run from the root of a clone of the repository, where the files are in `docs/snippets/generate-data/`. The Full Files block of this page holds the same files, for a reader who saves them by hand. ```bash git clone https://github.com/jaehyeon-kim/desflow.git cd desflow ``` - [First Simulation](https://jaehyeon.me/desflow/latest/learn/first-model/first-simulation/index.md) explains arrivals, tasks and the records a run writes. - [Generate the Payload](https://jaehyeon.me/desflow/latest/how-to/generate-data/send-data-to-a-sink/#generate-the-payload) explains how a payload maps each field to a generator, and the rest of that page shows how to write the records to Kafka, PostgreSQL or a file. This page writes them to the console. - Install the Faker library: `pip install "desflow[fake]"`. - [`fake`](https://jaehyeon.me/desflow/latest/generators/text-and-ids/fake/index.md) and [`row`](https://jaehyeon.me/desflow/latest/generators/related-records/row/index.md) list the keys of the two generators this page uses. ______________________________________________________________________ ## Steps ### Describe the Arrival A customer signs up about every 2 seconds: `rate: 0.5` is a gap that averages 2 seconds. ```yaml arrivals: signups: {dist: exponential, rate: 0.5, spawn: signup} ``` ```python app.add_arrival("signups", "exponential", rate=0.5, spawn="signup") ``` ```python signups_gap = DistributionConfig(dist="exponential", rate=0.5) # The random sequence the blueprint's draw uses signups_gap.stream = "arrival.signups" ``` ### Draw Names and Places A `fake` field calls one method of the [Faker](https://faker.readthedocs.io/en/master/providers.html) library by name: `name`, `email`, `city` and `job` here. Any other method of Faker's providers works the same way, such as `phone_number` or `company`. `locale: de_DE` draws a field in the German locale, so `german_city` is a German town. A Faker method that reads today's date, such as `date_of_birth`, would change the records from day to day, so this model uses none. ```yaml tasks: signup: payload: customer_id: {gen: sequence, start: 1} name: {gen: fake, method: name} email: {gen: fake, method: email} city: {gen: fake, method: city} german_city: {gen: fake, method: city, locale: de_DE} job: {gen: fake, method: job} favourite: {gen: row, file: realistic_fields_products.csv, weight: popularity} ``` ```python signup_payload = Template( { "customer_id": {"gen": "sequence", "start": 1}, "name": {"gen": "fake", "method": "name"}, "email": {"gen": "fake", "method": "email"}, "city": {"gen": "fake", "method": "city"}, "german_city": {"gen": "fake", "method": "city", "locale": "de_DE"}, "job": {"gen": "fake", "method": "job"}, "favourite": {"gen": "row", "file": CSV, "weight": "popularity"}, }, name="tasks.signup", ) @app.task(name="signup") def signup(task_id): """Gives one signup record.""" return signup_payload ``` ```python sampler = Sampler(seed=42) def faker(place, locale="en_US"): """A Faker seeded from the random sequence of the generator at `place`.""" fake = Faker(locale) fake.seed_instance(int(sampler.generator(place + "#fake").integers(2**32))) return fake name = faker("tasks.signup.payload.name") email = faker("tasks.signup.payload.email") city = faker("tasks.signup.payload.city") german_city = faker("tasks.signup.payload.german_city", "de_DE") job = faker("tasks.signup.payload.job") # A cell of digits is a number, as the `row` generator reads it with CSV.open(encoding="utf-8") as file: products: list = [ { "sku": row["sku"], "title": row["title"], "price": float(row["price"]), "popularity": int(row["popularity"]), } for row in csv.DictReader(file) ] total = sum(product["popularity"] for product in products) shares = [product["popularity"] / total for product in products] favourite = sampler.generator("tasks.signup.payload.favourite") ``` ```python def signups_source(): number = 0 while True: yield env.timeout(sampler.sample(signups_gap)) number += 1 payload = { "customer_id": number, "name": name.name(), "email": email.email(), "city": city.city(), "german_city": german_city.city(), "job": job.job(), "favourite": dict( products[int(favourite.choice(len(products), p=shares))] ), } env.publish_event( f"signups-{number}", payload, task="signup", instance=number - 1 ) env.process(signups_source()) ``` Each `fake` field has a Faker of its own, seeded from the random sequence named by the field's place with `#fake` added. The Low-level file builds one Faker for each field in the same way, and a fixed seed gives the same names every run. ### Keep Related Fields Together [`row`](https://jaehyeon.me/desflow/latest/generators/related-records/row/index.md) draws one row of a CSV or Parquet file, so the fields of one row always arrive together. Here each row is a product, so the sku, the title and the price always belong to the same product. `weight: popularity` draws the rows in proportion to the popularity column, so the notebook, with 12 of the 30 points in the file, is the favourite of 12 customers in 30 on average. ```text sku,title,price,popularity P-100,Desk lamp,24.90,5 P-101,Notebook,4.50,12 P-102,Water bottle,16.00,8 P-103,Backpack,59.00,3 P-104,Headphones,89.00,2 ``` The Builder and Low-level files name the CSV file by a path beside the file, because a Builder `row` file is read from the working directory. The Low-level file reads the file itself with `csv.DictReader` and draws a row by its share of the popularity. ______________________________________________________________________ ## Check the Result Run the model for 20 simulated seconds and print its first 3 records. Each record has a name, an email, a city, a German city, a job and a product. ```bash desflow run docs/snippets/generate-data/realistic_fields.yaml --sample 3 ``` ```bash python docs/snippets/generate-data/realistic_fields_builder.py ``` This prints every record of the run as an `[EVT]` line with the same fields and values. ```bash python docs/snippets/generate-data/realistic_fields_low_level.py ``` This prints every record of the run as an `[EVT]` line with the same fields and values. ```text {"stream_type":"event","sim_ts":8.590320322744143,"timestamp":"...","key":"signups-1","task":"signup","instance":0,"value":{"customer_id":1,"name":"Mr. Roy Castro","email":"candacestevens@example.net","city":"South Jeremy","german_city":"Görlitz","job":"Librarian, public","favourite":{"sku":"P-101","title":"Notebook","price":4.5,"popularity":12}}} {"stream_type":"event","sim_ts":10.844439604632683,"timestamp":"...","key":"signups-2","task":"signup","instance":1,"value":{"customer_id":2,"name":"James Mclaughlin","email":"vlang@example.org","city":"West Heatherton","german_city":"Bremervörde","job":"Optician, dispensing","favourite":{"sku":"P-102","title":"Water bottle","price":16.0,"popularity":8}}} {"stream_type":"event","sim_ts":16.652088685514833,"timestamp":"...","key":"signups-3","task":"signup","instance":2,"value":{"customer_id":3,"name":"Emily Simmons","email":"gnichols@example.com","city":"Jenniferfurt","german_city":"Weißwasser","job":"Cabin crew","favourite":{"sku":"P-100","title":"Desk lamp","price":24.9,"popularity":5}}} ``` The names depend on the version of Faker that the lock file pins, so a different version writes other names. The records stay the same from run to run for one version. ______________________________________________________________________ ## Full Files Full files ```yaml # Extend payloads: Faker names, emails and places, and products from a CSV file. # # A customer signs up about every 2 seconds. Their name, email, city and job come # from Faker, one `fake` generator for each field, and `german_city` is a city drawn # in the German locale (`de_DE`). A Faker method that reads today's date would change # the records from day to day, so this file uses none. The product is one row of # realistic_fields_products.csv, chosen by the popularity column, so the sku, title and # price stay together. # # Needs: the fake extra. # Run it with: desflow run docs/snippets/generate-data/realistic_fields.yaml simulation: sim_id: Shop factor: 0 random_seed: 42 logical_start_time: 2026-01-01T00:00:00 egress: - {type: Console} arrivals: signups: {dist: exponential, rate: 0.5, spawn: signup} tasks: signup: payload: customer_id: {gen: sequence, start: 1} name: {gen: fake, method: name} email: {gen: fake, method: email} city: {gen: fake, method: city} german_city: {gen: fake, method: city, locale: de_DE} job: {gen: fake, method: job} favourite: {gen: row, file: realistic_fields_products.csv, weight: popularity} run: {until: 20} ``` ```text sku,title,price,popularity P-100,Desk lamp,24.90,5 P-101,Notebook,4.50,12 P-102,Water bottle,16.00,8 P-103,Backpack,59.00,3 P-104,Headphones,89.00,2 ``` ```python """Extend payloads: Faker names, emails and places, and products from a CSV file. The builder version of `realistic_fields.yaml`: a customer signs up about every 2 seconds, with fields from Faker and a product from a CSV file. Needs: the fake extra. Run it with: python docs/snippets/generate-data/realistic_fields_builder.py """ import logging from datetime import datetime, timezone from pathlib import Path from desflow import ConsoleEgress, SimulationContext from desflow.values import Template CSV = str(Path(__file__).with_name("realistic_fields_products.csv")) UNTIL = 20 def build() -> SimulationContext: """Builds the model.""" app = SimulationContext( sim_id="Shop", factor=0, random_seed=42, logical_start_time=datetime(2026, 1, 1, tzinfo=timezone.utc), ) app.add_egress(ConsoleEgress()) app.add_arrival("signups", "exponential", rate=0.5, spawn="signup") signup_payload = Template( { "customer_id": {"gen": "sequence", "start": 1}, "name": {"gen": "fake", "method": "name"}, "email": {"gen": "fake", "method": "email"}, "city": {"gen": "fake", "method": "city"}, "german_city": {"gen": "fake", "method": "city", "locale": "de_DE"}, "job": {"gen": "fake", "method": "job"}, "favourite": {"gen": "row", "file": CSV, "weight": "popularity"}, }, name="tasks.signup", ) @app.task(name="signup") def signup(task_id): """Gives one signup record.""" return signup_payload return app if __name__ == "__main__": logging.basicConfig(level=logging.INFO, format="%(levelname)s %(message)s") build().run(until=UNTIL) ``` ```python """Extend payloads: Faker names, emails and places, and products from a CSV file. The low-level version of `realistic_fields.yaml`: plain SimPy on a `DynamicRealtimeEnvironment`, which publishes each record with `publish_event`. Each field has a Faker of its own, seeded from the random sequence the blueprint's generator at that place uses (its place with `#fake` added), and the product is one row of the CSV file read with the `csv` module, chosen by `Sampler.generator()` with the popularity column as the weights. Needs: the fake extra. Run it with: python docs/snippets/generate-data/realistic_fields_low_level.py """ import csv import logging from datetime import datetime, timezone from pathlib import Path from faker import Faker from desflow import ( ConsoleEgress, DistributionConfig, DynamicRealtimeEnvironment, Sampler, ) CSV = Path(__file__).with_name("realistic_fields_products.csv") UNTIL = 20 START = datetime(2026, 1, 1, tzinfo=timezone.utc) ENVIRONMENT: dict = {"logical_start_time": START, "timezone": "UTC"} def build(env: DynamicRealtimeEnvironment) -> None: """Starts the arrival on `env`.""" sampler = Sampler(seed=42) def faker(place, locale="en_US"): """A Faker seeded from the random sequence of the generator at `place`.""" fake = Faker(locale) fake.seed_instance(int(sampler.generator(place + "#fake").integers(2**32))) return fake name = faker("tasks.signup.payload.name") email = faker("tasks.signup.payload.email") city = faker("tasks.signup.payload.city") german_city = faker("tasks.signup.payload.german_city", "de_DE") job = faker("tasks.signup.payload.job") # A cell of digits is a number, as the `row` generator reads it with CSV.open(encoding="utf-8") as file: products: list = [ { "sku": row["sku"], "title": row["title"], "price": float(row["price"]), "popularity": int(row["popularity"]), } for row in csv.DictReader(file) ] total = sum(product["popularity"] for product in products) shares = [product["popularity"] / total for product in products] favourite = sampler.generator("tasks.signup.payload.favourite") signups_gap = DistributionConfig(dist="exponential", rate=0.5) # The random sequence the blueprint's draw uses signups_gap.stream = "arrival.signups" def signups_source(): number = 0 while True: yield env.timeout(sampler.sample(signups_gap)) number += 1 payload = { "customer_id": number, "name": name.name(), "email": email.email(), "city": city.city(), "german_city": german_city.city(), "job": job.job(), "favourite": dict( products[int(favourite.choice(len(products), p=shares))] ), } env.publish_event( f"signups-{number}", payload, task="signup", instance=number - 1 ) env.process(signups_source()) def run() -> None: """Runs the model unpaced into the console.""" env = DynamicRealtimeEnvironment(factor=0, **ENVIRONMENT) env.setup_egress([ConsoleEgress()]) build(env) try: env.run(until=UNTIL) finally: env.teardown() if __name__ == "__main__": logging.basicConfig(level=logging.INFO, format="%(levelname)s %(message)s") run() ``` # Choices and Numbers Pick a value from a list with set odds and draw numbers from a range or a bell curve: a payment method that is card 60 times in 100, and a purchase with a price, an item count, a delivery time, a channel and a gift flag. ______________________________________________________________________ ## Before You Start - The commands run from the root of a clone of the repository, where the files are in `docs/snippets/generate-data/`. The Full Files block of this page holds the same files, for a reader who saves them by hand. ```bash git clone https://github.com/jaehyeon-kim/desflow.git cd desflow ``` - [First Simulation](https://jaehyeon.me/desflow/latest/learn/first-model/first-simulation/index.md) explains arrivals, tasks and the records a run writes. - [Generators](https://jaehyeon.me/desflow/latest/generators/index.md) lists every generator kind and its keys. - [Randomness and Seeds](https://jaehyeon.me/desflow/latest/learn/first-model/randomness-and-seeds/index.md) explains why a fixed seed gives the same draws in each run. ______________________________________________________________________ ## Steps ### Describe the Arrivals A payment arrives every second (`dist: constant`), and a purchase arrives about once a second (`dist: exponential` with `rate: 1`). Each arrival starts the task it names in `spawn`. ```yaml arrivals: payments: {dist: constant, value: 1, spawn: payment} purchases: {dist: exponential, rate: 1, spawn: purchase} ``` ```python app.add_arrival("payments", "constant", value=1, spawn="payment") app.add_arrival("purchases", "exponential", rate=1, spawn="purchase") ``` ```python sampler = Sampler(seed=42) method = sampler.generator("tasks.payment.payload.method") price = sampler.generator("tasks.purchase.payload.price") items = sampler.generator("tasks.purchase.payload.items") delivery = sampler.generator("tasks.purchase.payload.delivery_minutes") channel = sampler.generator("tasks.purchase.payload.channel") gift = sampler.generator("tasks.purchase.payload.gift") payments_gap = DistributionConfig(dist="constant", value=1) # The random sequence the blueprint's draw uses payments_gap.stream = "arrival.payments" purchases_gap = DistributionConfig(dist="exponential", rate=1) purchases_gap.stream = "arrival.purchases" sent = {"payment": 0, "purchase": 0} ``` `Sampler(seed=42)` supplies every draw: a random generator for each payload field and for the gap. The `stream` line names the random sequence the blueprint uses for this arrival, so the three forms draw the same gaps. ### Choose and Draw Each field of a payload names one generator: - [`weighted`](https://jaehyeon.me/desflow/latest/generators/choices/weighted/index.md) chooses from `options` in proportion to their weights, so a payment is paid by card 60 times in 100. - [`uniform`](https://jaehyeon.me/desflow/latest/generators/random-numbers/uniform/index.md) draws a price between 1 and 250, and `decimals: 2` rounds it to cents. - [`integer`](https://jaehyeon.me/desflow/latest/generators/random-numbers/integer/index.md) draws a whole number of items from 1 to 5, both ends included. - [`normal`](https://jaehyeon.me/desflow/latest/generators/random-numbers/normal/index.md) draws a delivery time around 120 minutes with a standard deviation of 15. - [`one_of`](https://jaehyeon.me/desflow/latest/generators/choices/one-of/index.md) chooses a channel with equal chance. - [`boolean`](https://jaehyeon.me/desflow/latest/generators/random-numbers/boolean/index.md) with `p: 0.1` is true for 1 purchase in 10. ```yaml tasks: payment: payload: method: gen: weighted options: {card: 60, cash: 40} purchase: payload: price: {gen: uniform, low: 1, high: 250, decimals: 2} items: {gen: integer, bounds: [1, 5]} delivery_minutes: {gen: normal, mean: 120, std: 15, decimals: 1} channel: {gen: one_of, choices: [web, app, store]} gift: {gen: boolean, p: 0.1} ``` ```python payment_payload = Template( {"method": {"gen": "weighted", "options": {"card": 60, "cash": 40}}}, name="tasks.payment", ) @app.task(name="payment") def payment(task_id): """Gives one payment record.""" return payment_payload purchase_payload = Template( { "price": {"gen": "uniform", "low": 1, "high": 250, "decimals": 2}, "items": {"gen": "integer", "bounds": [1, 5]}, "delivery_minutes": { "gen": "normal", "mean": 120, "std": 15, "decimals": 1, }, "channel": {"gen": "one_of", "choices": ["web", "app", "store"]}, "gift": {"gen": "boolean", "p": 0.1}, }, name="tasks.purchase", ) @app.task(name="purchase") def purchase(task_id): """Gives one purchase record.""" return purchase_payload ``` ```python def publish(task, payload): """Publishes a finished payload.""" env.publish_event( f"{task}s-{sent[task] + 1}", payload, task=task, instance=sent[task] ) sent[task] += 1 def payments_source(): while True: yield env.timeout(sampler.sample(payments_gap)) # Weights 60 and 40: card takes the draws below 60 of 100 card = method.random() * (60 + 40) < 60 publish("payment", {"method": "card" if card else "cash"}) def purchases_source(): while True: yield env.timeout(sampler.sample(purchases_gap)) publish( "purchase", { "price": round(float(price.uniform(1, 250)), 2), "items": int(items.integers(1, 5 + 1)), "delivery_minutes": round(float(delivery.normal(120, 15)), 1), "channel": CHANNELS[int(channel.integers(len(CHANNELS)))], "gift": bool(gift.random() < 0.1), }, ) env.process(payments_source()) env.process(purchases_source()) ``` The Low-level file writes the weighted choice out as the generator makes it: a point drawn in the total weight of 100 is card when it is below 60. ______________________________________________________________________ ## Check the Result Run the model for 30 simulated seconds and print its first 5 records. A payment is `card` or `cash`, and a purchase has a price from 1 to 250, 1 to 5 items, a delivery time in minutes, a channel and a gift flag. ```bash desflow run docs/snippets/generate-data/choices_and_numbers.yaml --sample 5 ``` ```bash python docs/snippets/generate-data/choices_and_numbers_builder.py ``` This prints every record of the run as an `[EVT]` line with the same fields and values. ```bash python docs/snippets/generate-data/choices_and_numbers_low_level.py ``` This prints every record of the run as an `[EVT]` line with the same fields and values. ```text {"stream_type":"event","sim_ts":0.0481932736040453,"timestamp":"...","key":"purchases-1","task":"purchase","instance":0,"value":{"price":207.6,"items":3,"delivery_minutes":129.4,"channel":"app","gift":false}} {"stream_type":"event","sim_ts":0.28749618102439023,"timestamp":"...","key":"purchases-2","task":"purchase","instance":1,"value":{"price":7.37,"items":4,"delivery_minutes":116.1,"channel":"app","gift":false}} {"stream_type":"event","sim_ts":0.3531899394224852,"timestamp":"...","key":"purchases-3","task":"purchase","instance":2,"value":{"price":85.27,"items":5,"delivery_minutes":135.1,"channel":"web","gift":false}} {"stream_type":"event","sim_ts":1.0,"timestamp":"...","key":"payments-1","task":"payment","instance":0,"value":{"method":"cash"}} {"stream_type":"event","sim_ts":1.3952758689946312,"timestamp":"...","key":"purchases-4","task":"purchase","instance":3,"value":{"price":95.97,"items":4,"delivery_minutes":100.3,"channel":"web","gift":false}} ``` Over a long run the shares follow the settings. The docs test runs the model for 10,000 simulated seconds: about 60 payments in 100 are by card, the prices reach both ends of 1 to 250, the delivery times average 120 minutes with a standard deviation of 15, and about 1 purchase in 10 is a gift. ______________________________________________________________________ ## Full Files Full files ```yaml # Choices and numbers: weighted choices and drawn numbers. # # A payment arrives every second. 60 percent are paid by card and the rest in cash. A # purchase arrives about once a second. A purchase has a price between 1 and 250, a # whole number of items from 1 to 5, a delivery time that is normal around 120 minutes, # a channel chosen with equal chance, and a `gift` flag that is true for 1 in 10. # # Needs: nothing. # Run it with: desflow run docs/snippets/generate-data/choices_and_numbers.yaml simulation: sim_id: Shop factor: 0 random_seed: 42 logical_start_time: 2026-01-01T00:00:00 egress: - {type: Console} arrivals: payments: {dist: constant, value: 1, spawn: payment} purchases: {dist: exponential, rate: 1, spawn: purchase} tasks: payment: payload: method: gen: weighted options: {card: 60, cash: 40} purchase: payload: price: {gen: uniform, low: 1, high: 250, decimals: 2} items: {gen: integer, bounds: [1, 5]} delivery_minutes: {gen: normal, mean: 120, std: 15, decimals: 1} channel: {gen: one_of, choices: [web, app, store]} gift: {gen: boolean, p: 0.1} run: {until: 30} ``` ```python """Choices and numbers: weighted choices and drawn numbers, builder API. The builder version of `choices_and_numbers.yaml`: a payment every second, 60 percent by card, and purchases with drawn numbers. Needs: nothing. Run it with: python docs/snippets/generate-data/choices_and_numbers_builder.py """ import logging from datetime import datetime, timezone from desflow import ConsoleEgress, SimulationContext from desflow.values import Template UNTIL = 30 def build() -> SimulationContext: """Builds the model.""" app = SimulationContext( sim_id="Shop", factor=0, random_seed=42, logical_start_time=datetime(2026, 1, 1, tzinfo=timezone.utc), ) app.add_egress(ConsoleEgress()) app.add_arrival("payments", "constant", value=1, spawn="payment") app.add_arrival("purchases", "exponential", rate=1, spawn="purchase") payment_payload = Template( {"method": {"gen": "weighted", "options": {"card": 60, "cash": 40}}}, name="tasks.payment", ) @app.task(name="payment") def payment(task_id): """Gives one payment record.""" return payment_payload purchase_payload = Template( { "price": {"gen": "uniform", "low": 1, "high": 250, "decimals": 2}, "items": {"gen": "integer", "bounds": [1, 5]}, "delivery_minutes": { "gen": "normal", "mean": 120, "std": 15, "decimals": 1, }, "channel": {"gen": "one_of", "choices": ["web", "app", "store"]}, "gift": {"gen": "boolean", "p": 0.1}, }, name="tasks.purchase", ) @app.task(name="purchase") def purchase(task_id): """Gives one purchase record.""" return purchase_payload return app if __name__ == "__main__": logging.basicConfig(level=logging.INFO, format="%(levelname)s %(message)s") build().run(until=UNTIL) ``` ```python """Choices and numbers: weighted choices and drawn numbers, low-level API. The low-level version of `choices_and_numbers.yaml`: plain SimPy on a `DynamicRealtimeEnvironment`, which publishes each record with `publish_event`. Each draw is made with `Sampler`, from the random sequence the blueprint's generator at that place uses, so the draws are the blueprint's. The weighted choice is written out as its generator makes it: a point drawn in the total weight of 100 is card when it is below 60. Needs: nothing. Run it with: python docs/snippets/generate-data/choices_and_numbers_low_level.py """ import logging from datetime import datetime, timezone from desflow import ( ConsoleEgress, DistributionConfig, DynamicRealtimeEnvironment, Sampler, ) UNTIL = 30 START = datetime(2026, 1, 1, tzinfo=timezone.utc) ENVIRONMENT: dict = {"logical_start_time": START, "timezone": "UTC"} CHANNELS = ["web", "app", "store"] def build(env: DynamicRealtimeEnvironment) -> None: """Starts the arrivals on `env`.""" sampler = Sampler(seed=42) method = sampler.generator("tasks.payment.payload.method") price = sampler.generator("tasks.purchase.payload.price") items = sampler.generator("tasks.purchase.payload.items") delivery = sampler.generator("tasks.purchase.payload.delivery_minutes") channel = sampler.generator("tasks.purchase.payload.channel") gift = sampler.generator("tasks.purchase.payload.gift") payments_gap = DistributionConfig(dist="constant", value=1) # The random sequence the blueprint's draw uses payments_gap.stream = "arrival.payments" purchases_gap = DistributionConfig(dist="exponential", rate=1) purchases_gap.stream = "arrival.purchases" sent = {"payment": 0, "purchase": 0} def publish(task, payload): """Publishes a finished payload.""" env.publish_event( f"{task}s-{sent[task] + 1}", payload, task=task, instance=sent[task] ) sent[task] += 1 def payments_source(): while True: yield env.timeout(sampler.sample(payments_gap)) # Weights 60 and 40: card takes the draws below 60 of 100 card = method.random() * (60 + 40) < 60 publish("payment", {"method": "card" if card else "cash"}) def purchases_source(): while True: yield env.timeout(sampler.sample(purchases_gap)) publish( "purchase", { "price": round(float(price.uniform(1, 250)), 2), "items": int(items.integers(1, 5 + 1)), "delivery_minutes": round(float(delivery.normal(120, 15)), 1), "channel": CHANNELS[int(channel.integers(len(CHANNELS)))], "gift": bool(gift.random() < 0.1), }, ) env.process(payments_source()) env.process(purchases_source()) def run() -> None: """Runs the model unpaced into the console.""" env = DynamicRealtimeEnvironment(factor=0, **ENVIRONMENT) env.setup_egress([ConsoleEgress()]) build(env) try: env.run(until=UNTIL) finally: env.teardown() if __name__ == "__main__": logging.basicConfig(level=logging.INFO, format="%(levelname)s %(message)s") run() ``` # Timestamps and Gaps Put times into records and make the gaps between records vary: an order about every 0.4 seconds, with the time it was placed, a delivery date up to 2 days later, and the same time in milliseconds since 1970. ______________________________________________________________________ ## Before You Start - The commands run from the root of a clone of the repository, where the files are in `docs/snippets/generate-data/`. The Full Files block of this page holds the same files, for a reader who saves them by hand. ```bash git clone https://github.com/jaehyeon-kim/desflow.git cd desflow ``` - [First Simulation](https://jaehyeon.me/desflow/latest/learn/first-model/first-simulation/index.md) explains arrivals, tasks and the records a run writes. - [Arrivals and Services](https://jaehyeon.me/desflow/latest/user-guide/model-parts/arrivals-and-services/index.md) lists the distributions an arrival can use, and [`now`](https://jaehyeon.me/desflow/latest/generators/time/now/index.md) and [`format_time`](https://jaehyeon.me/desflow/latest/generators/time/format-time/index.md) list the keys of the two time generators. ______________________________________________________________________ ## Steps ### Draw the Gaps An arrival takes its gaps from `dist` or from `gap`. A `gap` is a number of seconds, a duration, an expression or a generator, and it is read at the start of each gap. A `normal` generator with a mean of 0.4 and a standard deviation of 0.03 gives an order about every 0.4 seconds, and each gap differs by a few hundredths of a second. ```yaml arrivals: orders: gap: {gen: normal, mean: 0.4, std: 0.03} spawn: order ``` ```python app.add_arrival( "orders", gap=generator({"gen": "normal", "mean": 0.4, "std": 0.03}), spawn="order", ) ``` ```python sampler = Sampler(seed=42) gap = sampler.generator("arrivals.orders.gap") offset = sampler.generator("tasks.order.payload.deliver_by.offset") ``` ### Write the Times [`now`](https://jaehyeon.me/desflow/latest/generators/time/now/index.md) gives the time of the record: the `logical_start_time` of the run plus the simulation time. `offset` adds seconds, and here a draw between 0 and 172,800 seconds (2 days) makes the delivery date. [`format_time`](https://jaehyeon.me/desflow/latest/generators/time/format-time/index.md) with `format: epoch_ms` writes the same time as a number of milliseconds since 1970. An offset below 0 gives an earlier time. ```yaml tasks: order: payload: placed_at: {gen: now} deliver_by: gen: now offset: {gen: uniform, low: 0, high: 172800} epoch_ms: {gen: format_time, format: epoch_ms} ``` ```python order_payload = Template( { "placed_at": {"gen": "now"}, "deliver_by": { "gen": "now", "offset": {"gen": "uniform", "low": 0, "high": 172800}, }, "epoch_ms": {"gen": "format_time", "format": "epoch_ms"}, }, name="tasks.order", ) @app.task(name="order") def order(task_id): """Gives one order record.""" return order_payload ``` ```python def order_time(seconds=0.0): """The logical time now plus `seconds`, as the environment counts it.""" return env.start_datetime + timedelta(seconds=env.now + seconds) def orders_source(): for number in itertools.count(1): yield env.timeout(float(gap.normal(0.4, 0.03))) now = order_time() deliver_by = order_time(float(offset.uniform(0, 172800))) payload = { "placed_at": now.isoformat(timespec="milliseconds"), "deliver_by": deliver_by.isoformat(timespec="milliseconds"), "epoch_ms": int((now - EPOCH) // timedelta(milliseconds=1)), } env.publish_event( f"orders-{number}", payload, task="order", instance=number - 1 ) env.process(orders_source()) ``` The Low-level file computes each time itself, from `env.start_datetime` and `env.now`. ______________________________________________________________________ ## Check the Result Run the model for 10 simulated seconds and print its first 3 records. `placed_at` is the logical start time plus the record's `sim_ts`, `deliver_by` is up to 2 days after it, and `epoch_ms` counts from 1 January 1970. ```bash desflow run docs/snippets/generate-data/timestamps_and_gaps.yaml --sample 3 ``` ```bash python docs/snippets/generate-data/timestamps_and_gaps_builder.py ``` This prints every record of the run as an `[EVT]` line with the same fields and values. ```bash python docs/snippets/generate-data/timestamps_and_gaps_low_level.py ``` This prints every record of the run as an `[EVT]` line with the same fields and values. ```text {"stream_type":"event","sim_ts":0.4011254569293608,"timestamp":"...","key":"orders-1","task":"order","instance":0,"value":{"placed_at":"2026-01-01T00:00:00.401+00:00","deliver_by":"2026-01-02T16:48:58.408+00:00","epoch_ms":1767225600401}} {"stream_type":"event","sim_ts":0.8052480450909607,"timestamp":"...","key":"orders-2","task":"order","instance":1,"value":{"placed_at":"2026-01-01T00:00:00.805+00:00","deliver_by":"2026-01-01T18:49:05.992+00:00","epoch_ms":1767225600805}} {"stream_type":"event","sim_ts":1.2311827841058256,"timestamp":"...","key":"orders-3","task":"order","instance":2,"value":{"placed_at":"2026-01-01T00:00:01.231+00:00","deliver_by":"2026-01-01T10:51:01.624+00:00","epoch_ms":1767225601231}} ``` The times repeat from run to run, because `now` counts from the fixed `logical_start_time` and not from the wall clock. The docs test runs the model for 2,000 simulated seconds: the gaps average 0.4 seconds with a standard deviation of 0.03, and `deliver_by` reaches both ends of 0 to 2 days after `placed_at`. ______________________________________________________________________ ## Full Files Full files ```yaml # Timestamps and gaps: generated times and random gaps between records. # # An order event arrives on average every 0.4 s, with a gap drawn from a normal # distribution with a standard deviation of 30 ms, so the gaps vary around 0.4 s. Each # order holds the time it was placed, a delivery date up to 2 days later, and the same # time as a number of milliseconds since 1970. An offset below 0 gives an earlier time. # # Needs: nothing. # Run it with: desflow run docs/snippets/generate-data/timestamps_and_gaps.yaml simulation: sim_id: Shop factor: 0 random_seed: 42 logical_start_time: 2026-01-01T00:00:00 egress: - {type: Console} arrivals: orders: gap: {gen: normal, mean: 0.4, std: 0.03} spawn: order tasks: order: payload: placed_at: {gen: now} deliver_by: gen: now offset: {gen: uniform, low: 0, high: 172800} epoch_ms: {gen: format_time, format: epoch_ms} run: {until: 10} ``` ```python """Timestamps and gaps: generated times and random gaps between records, builder API. The builder version of `timestamps_and_gaps.yaml`: an order on average every 0.4 s with a random gap, each with generated times. Needs: nothing. Run it with: python docs/snippets/generate-data/timestamps_and_gaps_builder.py """ import logging from datetime import datetime, timezone from desflow import ConsoleEgress, SimulationContext from desflow.values import Template, generator UNTIL = 10 def build() -> SimulationContext: """Builds the model.""" app = SimulationContext( sim_id="Shop", factor=0, random_seed=42, logical_start_time=datetime(2026, 1, 1, tzinfo=timezone.utc), ) app.add_egress(ConsoleEgress()) app.add_arrival( "orders", gap=generator({"gen": "normal", "mean": 0.4, "std": 0.03}), spawn="order", ) order_payload = Template( { "placed_at": {"gen": "now"}, "deliver_by": { "gen": "now", "offset": {"gen": "uniform", "low": 0, "high": 172800}, }, "epoch_ms": {"gen": "format_time", "format": "epoch_ms"}, }, name="tasks.order", ) @app.task(name="order") def order(task_id): """Gives one order record.""" return order_payload return app if __name__ == "__main__": logging.basicConfig(level=logging.INFO, format="%(levelname)s %(message)s") build().run(until=UNTIL) ``` ```python """Timestamps and gaps: generated times and random gaps between records, low-level API. The low-level version of `timestamps_and_gaps.yaml`: plain SimPy on a `DynamicRealtimeEnvironment`, which publishes each record with `publish_event`. The gap and the delivery date are drawn with `Sampler`, from the random sequence the blueprint's generator at that place uses, so the draws are the blueprint's. The times come from the environment: the start time plus the simulation time, written as the blueprint's `now` and `format_time` write them. Needs: nothing. Run it with: python docs/snippets/generate-data/timestamps_and_gaps_low_level.py """ import itertools import logging from datetime import datetime, timedelta, timezone from desflow import ConsoleEgress, DynamicRealtimeEnvironment, Sampler UNTIL = 10 START = datetime(2026, 1, 1, tzinfo=timezone.utc) ENVIRONMENT: dict = {"logical_start_time": START, "timezone": "UTC"} EPOCH = datetime(1970, 1, 1, tzinfo=timezone.utc) def build(env: DynamicRealtimeEnvironment) -> None: """Starts the arrival on `env`.""" sampler = Sampler(seed=42) gap = sampler.generator("arrivals.orders.gap") offset = sampler.generator("tasks.order.payload.deliver_by.offset") def order_time(seconds=0.0): """The logical time now plus `seconds`, as the environment counts it.""" return env.start_datetime + timedelta(seconds=env.now + seconds) def orders_source(): for number in itertools.count(1): yield env.timeout(float(gap.normal(0.4, 0.03))) now = order_time() deliver_by = order_time(float(offset.uniform(0, 172800))) payload = { "placed_at": now.isoformat(timespec="milliseconds"), "deliver_by": deliver_by.isoformat(timespec="milliseconds"), "epoch_ms": int((now - EPOCH) // timedelta(milliseconds=1)), } env.publish_event( f"orders-{number}", payload, task="order", instance=number - 1 ) env.process(orders_source()) def run() -> None: """Runs the model unpaced into the console.""" env = DynamicRealtimeEnvironment(factor=0, **ENVIRONMENT) env.setup_egress([ConsoleEgress()]) build(env) try: env.run(until=UNTIL) finally: env.teardown() if __name__ == "__main__": logging.basicConfig(level=logging.INFO, format="%(levelname)s %(message)s") run() ``` # Stop After a Count End a run after exactly 12 records, with no time limit: `max_events` stops the arrival, and the run ends when the last record is written. ______________________________________________________________________ ## Before You Start - The commands run from the root of a clone of the repository, where the files are in `docs/snippets/generate-data/`. The Full Files block of this page holds the same files, for a reader who saves them by hand. ```bash git clone https://github.com/jaehyeon-kim/desflow.git cd desflow ``` - [First Simulation](https://jaehyeon.me/desflow/latest/learn/first-model/first-simulation/index.md) explains arrivals, tasks and the records a run writes. - [End Conditions](https://jaehyeon.me/desflow/latest/learn/first-model/end-conditions/index.md) lists every way a run ends, and [Run Length](https://jaehyeon.me/desflow/latest/user-guide/time-and-pacing/run-length/index.md) explains `until` and the other limits. ______________________________________________________________________ ## Steps ### Limit the Arrival `max_events: 12` is how many times the arrival starts its task in all. An order arrives every 2 seconds, so the 12th arrives at 24 seconds, and the arrival then stops. ```yaml arrivals: orders: {dist: constant, value: 2, spawn: order, max_events: 12} ``` ```python app.add_arrival("orders", "constant", value=2, spawn="order", max_events=12) ``` ```python sampler = Sampler(seed=42) orders_gap = DistributionConfig(dist="constant", value=2) # The random sequence the blueprint's draw uses orders_gap.stream = "arrival.orders" ``` A Low-level script has no `max_events`. Its source loops over `range(1, 13)` and ends after the 12th record. ### Leave Out the End Time The task numbers each order with `sequence`, so the records show the count. The blueprint has no `run` section, and the Builder and Low-level files set no `until`, so the run ends when the last record is written. ```yaml tasks: order: payload: order_id: {gen: sequence, start: 1} ``` ```python order_payload = Template( {"order_id": {"gen": "sequence", "start": 1}}, name="tasks.order" ) @app.task(name="order") def order(task_id): """Gives one order record.""" return order_payload ``` ```python def orders_source(): for number in range(1, 13): yield env.timeout(sampler.sample(orders_gap)) env.publish_event( f"orders-{number}", {"order_id": number}, task="order", instance=number - 1, ) env.process(orders_source()) ``` ______________________________________________________________________ ## Check the Result Run the model and print its first 5 records. The `order_id` runs from 1, and the records come every 2 seconds. ```bash desflow run docs/snippets/generate-data/stop_after_a_count.yaml --sample 5 ``` ```bash python docs/snippets/generate-data/stop_after_a_count_builder.py ``` This prints every record of the run as an `[EVT]` line with the same fields and values. ```bash python docs/snippets/generate-data/stop_after_a_count_low_level.py ``` This prints every record of the run as an `[EVT]` line with the same fields and values. ```text {"stream_type":"event","sim_ts":2.0,"timestamp":"...","key":"orders-1","task":"order","instance":0,"value":{"order_id":1}} {"stream_type":"event","sim_ts":4.0,"timestamp":"...","key":"orders-2","task":"order","instance":1,"value":{"order_id":2}} {"stream_type":"event","sim_ts":6.0,"timestamp":"...","key":"orders-3","task":"order","instance":2,"value":{"order_id":3}} {"stream_type":"event","sim_ts":8.0,"timestamp":"...","key":"orders-4","task":"order","instance":3,"value":{"order_id":4}} {"stream_type":"event","sim_ts":10.0,"timestamp":"...","key":"orders-5","task":"order","instance":4,"value":{"order_id":5}} ``` The run ends with order 12 at 24 seconds. The docs test also runs the model to 1,000 seconds and still gets 12 records, and the Builder file with no `until` gets 12 too. ______________________________________________________________________ ## Full Files Full files ```yaml # Stop after a count: an arrival that ends after exactly 12 records. # # An order arrives every 2 seconds, and `max_events` ends the arrival after 12. The run # has no `until`, so it ends when the last record is written. # # Needs: nothing. # Run it with: desflow run docs/snippets/generate-data/stop_after_a_count.yaml simulation: sim_id: Shop factor: 0 random_seed: 42 logical_start_time: 2026-01-01T00:00:00 egress: - {type: Console} arrivals: orders: {dist: constant, value: 2, spawn: order, max_events: 12} tasks: order: payload: order_id: {gen: sequence, start: 1} ``` ```python """Stop after a count: an arrival that ends after exactly 12 records, builder API. The builder version of `stop_after_a_count.yaml`: an order every 2 seconds, ended by `max_events` after 12. Needs: nothing. Run it with: python docs/snippets/generate-data/stop_after_a_count_builder.py """ import logging from datetime import datetime, timezone from desflow import ConsoleEgress, SimulationContext from desflow.values import Template UNTIL = None def build() -> SimulationContext: """Builds the model.""" app = SimulationContext( sim_id="Shop", factor=0, random_seed=42, logical_start_time=datetime(2026, 1, 1, tzinfo=timezone.utc), ) app.add_egress(ConsoleEgress()) app.add_arrival("orders", "constant", value=2, spawn="order", max_events=12) order_payload = Template( {"order_id": {"gen": "sequence", "start": 1}}, name="tasks.order" ) @app.task(name="order") def order(task_id): """Gives one order record.""" return order_payload return app if __name__ == "__main__": logging.basicConfig(level=logging.INFO, format="%(levelname)s %(message)s") build().run() ``` ```python """Stop after a count: an arrival that ends after exactly 12 records, low-level API. The low-level version of `stop_after_a_count.yaml`: plain SimPy on a `DynamicRealtimeEnvironment`, which publishes each record with `publish_event`. The arrival loop runs 12 times and then ends, so the run ends when the last record is written. Needs: nothing. Run it with: python docs/snippets/generate-data/stop_after_a_count_low_level.py """ import logging from datetime import datetime, timezone from desflow import ( ConsoleEgress, DistributionConfig, DynamicRealtimeEnvironment, Sampler, ) UNTIL = None START = datetime(2026, 1, 1, tzinfo=timezone.utc) ENVIRONMENT: dict = {"logical_start_time": START, "timezone": "UTC"} def build(env: DynamicRealtimeEnvironment) -> None: """Starts the arrival on `env`.""" sampler = Sampler(seed=42) orders_gap = DistributionConfig(dist="constant", value=2) # The random sequence the blueprint's draw uses orders_gap.stream = "arrival.orders" def orders_source(): for number in range(1, 13): yield env.timeout(sampler.sample(orders_gap)) env.publish_event( f"orders-{number}", {"order_id": number}, task="order", instance=number - 1, ) env.process(orders_source()) def run() -> None: """Runs the model unpaced into the console.""" env = DynamicRealtimeEnvironment(factor=0, **ENVIRONMENT) env.setup_egress([ConsoleEgress()]) build(env) try: env.run(until=UNTIL) finally: env.teardown() if __name__ == "__main__": logging.basicConfig(level=logging.INFO, format="%(levelname)s %(message)s") run() ``` # Many Entities Start many entities from one arrival, each with its own key and its own values: ten tills that report their takings every minute, and three warehouses named in a list. ______________________________________________________________________ ## Before You Start - The commands run from the root of a clone of the repository, where the files are in `docs/snippets/generate-data/`. The Full Files block of this page holds the same files, for a reader who saves them by hand. ```bash git clone https://github.com/jaehyeon-kim/desflow.git cd desflow ``` - [First Simulation](https://jaehyeon.me/desflow/latest/learn/first-model/first-simulation/index.md) explains arrivals, tasks and the records a run writes. - [Arrivals and Services](https://jaehyeon.me/desflow/latest/user-guide/model-parts/arrivals-and-services/index.md) lists the keys of an arrival, and [`entity`](https://jaehyeon.me/desflow/latest/generators/model-state/entity/index.md) lists the generator that reads an entity's key. ______________________________________________________________________ ## Steps ### Start Entities with a Count `count: 10` starts ten entities from the one arrival, and each reports every 60 seconds. `key` is a generator read once for each entity, and `sequence` with `format: "till-{}"` names them `till-1` to `till-10`. ```yaml arrivals: tills: dist: constant value: 60 spawn: report count: 10 key: {gen: sequence, start: 1, format: "till-{}"} ``` ```python # A blueprint's `count: 10` is ten arrivals here, each with the key of its till for number in range(1, 11): app.add_arrival( f"tills{number}", "constant", value=60, spawn="report", key=lambda n, number=number: f"till-{number}", ) ``` A Builder arrival has no `count`, so the file adds one arrival for each till, each with its own key. ```python sampler = Sampler(seed=42) takings = sampler.generator("tasks.report.payload.takings") tills_gap = DistributionConfig(dist="constant", value=60) # The random sequence the blueprint's draw uses tills_gap.stream = "arrival.tills" sent = {"report": 0} ``` A Low-level script starts one process for each till. ### Read the Entity's Key [`entity`](https://jaehyeon.me/desflow/latest/generators/model-state/entity/index.md) writes the entity's key into the payload, next to a takings figure that each till draws for itself. The key is also the record key, so a Kafka topic keeps all the records of one till in one partition, in order. ```yaml tasks: report: payload: till: {gen: entity} takings: {gen: normal, mean: 400, std: 60, decimals: 2} ``` ```python report_payload = Template( { "till": {"gen": "entity"}, "takings": {"gen": "normal", "mean": 400, "std": 60, "decimals": 2}, }, name="tasks.report", ) @app.task(name="report") def report(task_id): """Gives one report record.""" return report_payload ``` ```python def till(key): while True: yield env.timeout(sampler.sample(tills_gap)) payload = { "till": key, "takings": round(float(takings.normal(400, 60)), 2), } env.publish_event(key, payload, task="report", instance=sent["report"]) sent["report"] += 1 for number in range(1, 11): env.process(till(f"till-{number}")) ``` ### Start Entities from a List of Keys `keys` is a list of names instead of a count, and it starts one entity for each name. Three warehouses report the orders waiting every 2 seconds under their own names. ```yaml arrivals: warehouses: {dist: constant, value: 2, spawn: report, keys: [north, south, east]} ``` ```yaml tasks: report: payload: warehouse: {gen: entity} orders_waiting: {gen: integer, bounds: [0, 40]} ``` ```python # A blueprint's `keys` is one arrival for each name here, each with its own key for name in ["north", "south", "east"]: app.add_arrival( f"warehouses-{name}", "constant", value=2, spawn="report", key=lambda n, name=name: name, ) ``` As with `count`, a Builder arrival has no `keys`, so the file adds one arrival for each name. ```python report_payload = Template( { "warehouse": {"gen": "entity"}, "orders_waiting": {"gen": "integer", "bounds": [0, 40]}, }, name="tasks.report", ) @app.task(name="report") def report(task_id): """Gives one report record.""" return report_payload ``` ```python sampler = Sampler(seed=42) waiting = sampler.generator("tasks.report.payload.orders_waiting") warehouses_gap = DistributionConfig(dist="constant", value=2) # The random sequence the blueprint's draw uses warehouses_gap.stream = "arrival.warehouses" sent = {"report": 0} ``` ```python def warehouse(key): while True: yield env.timeout(sampler.sample(warehouses_gap)) payload = { "warehouse": key, "orders_waiting": int(waiting.integers(0, 40 + 1)), } env.publish_event(key, payload, task="report", instance=sent["report"]) sent["report"] += 1 for key in ["north", "south", "east"]: env.process(warehouse(key)) ``` ______________________________________________________________________ ## Check the Result Run the first model for 300 simulated seconds and print its first 3 records. All ten tills report at 60 seconds, each under its own key, and again at 120, 180 and 240 seconds, which makes 40 records. The run ends at 300 seconds before the reports due at that time. ```bash desflow run docs/snippets/generate-data/many_entities.yaml --sample 3 ``` ```bash python docs/snippets/generate-data/many_entities_builder.py ``` This prints every record of the run as an `[EVT]` line with the same fields and values. ```bash python docs/snippets/generate-data/many_entities_low_level.py ``` This prints every record of the run as an `[EVT]` line with the same fields and values. ```text {"stream_type":"event","sim_ts":60.0,"timestamp":"...","key":"till-1","task":"report","instance":0,"value":{"till":"till-1","takings":446.41}} {"stream_type":"event","sim_ts":60.0,"timestamp":"...","key":"till-2","task":"report","instance":1,"value":{"till":"till-2","takings":297.08}} {"stream_type":"event","sim_ts":60.0,"timestamp":"...","key":"till-3","task":"report","instance":2,"value":{"till":"till-3","takings":434.26}} ``` The model with `keys` reports in the order of the list, and the first 4 records are the three warehouses at 2 seconds and the first again at 4 seconds. ```bash desflow run docs/snippets/generate-data/many_entities_named.yaml --sample 4 ``` ```bash python docs/snippets/generate-data/many_entities_named_builder.py ``` ```bash python docs/snippets/generate-data/many_entities_named_low_level.py ``` ```text {"stream_type":"event","sim_ts":2.0,"timestamp":"...","key":"north","task":"report","instance":0,"value":{"warehouse":"north","orders_waiting":22}} {"stream_type":"event","sim_ts":2.0,"timestamp":"...","key":"south","task":"report","instance":1,"value":{"warehouse":"south","orders_waiting":20}} {"stream_type":"event","sim_ts":2.0,"timestamp":"...","key":"east","task":"report","instance":2,"value":{"warehouse":"east","orders_waiting":2}} {"stream_type":"event","sim_ts":4.0,"timestamp":"...","key":"north","task":"report","instance":3,"value":{"warehouse":"north","orders_waiting":4}} ``` ______________________________________________________________________ ## Full Files Full files ```yaml # Many entities: ten tills, each with its own key, report their takings every minute. # # `count: 10` starts ten entities from the one arrival, and `key` gives each its own # key, till-1 to till-10, which the task reads with `entity`. The key is the record key # too, so a Kafka topic puts each till's records in one partition, in order. # # Needs: nothing. # Run it with: desflow run docs/snippets/generate-data/many_entities.yaml simulation: sim_id: Shop factor: 0 random_seed: 42 logical_start_time: 2026-01-01T00:00:00 egress: - {type: Console} arrivals: tills: dist: constant value: 60 spawn: report count: 10 key: {gen: sequence, start: 1, format: "till-{}"} tasks: report: payload: till: {gen: entity} takings: {gen: normal, mean: 400, std: 60, decimals: 2} run: {until: 300} ``` ```yaml # Many entities, by name: one entity for each key in a list. # # `keys` starts one entity for each name, here three warehouses, and each reports the # orders waiting every 2 seconds under its own name. # # Needs: nothing. # Run it with: desflow run docs/snippets/generate-data/many_entities_named.yaml simulation: sim_id: Shop factor: 0 random_seed: 42 logical_start_time: 2026-01-01T00:00:00 egress: - {type: Console} arrivals: warehouses: {dist: constant, value: 2, spawn: report, keys: [north, south, east]} tasks: report: payload: warehouse: {gen: entity} orders_waiting: {gen: integer, bounds: [0, 40]} run: {until: 10} ``` ```python """Many entities: ten tills, each with its own key, builder API. The builder version of `many_entities.yaml`: ten tills, each with its own key, report their takings every minute. Each till is its own arrival, because `add_arrival` has no `count`. Needs: nothing. Run it with: python docs/snippets/generate-data/many_entities_builder.py """ import logging from datetime import datetime, timezone from desflow import ConsoleEgress, SimulationContext from desflow.values import Template UNTIL = 300 def build() -> SimulationContext: """Builds the model.""" app = SimulationContext( sim_id="Shop", factor=0, random_seed=42, logical_start_time=datetime(2026, 1, 1, tzinfo=timezone.utc), ) app.add_egress(ConsoleEgress()) # A blueprint's `count: 10` is ten arrivals here, each with the key of its till for number in range(1, 11): app.add_arrival( f"tills{number}", "constant", value=60, spawn="report", key=lambda n, number=number: f"till-{number}", ) report_payload = Template( { "till": {"gen": "entity"}, "takings": {"gen": "normal", "mean": 400, "std": 60, "decimals": 2}, }, name="tasks.report", ) @app.task(name="report") def report(task_id): """Gives one report record.""" return report_payload return app if __name__ == "__main__": logging.basicConfig(level=logging.INFO, format="%(levelname)s %(message)s") build().run(until=UNTIL) ``` ```python """Many entities, by name: one entity for each key in a list, builder API. The builder version of `many_entities_named.yaml`: three warehouses, each with its own name, report the orders waiting every 2 seconds. Each warehouse is its own arrival, because `add_arrival` has no `keys`. Needs: nothing. Run it with: python docs/snippets/generate-data/many_entities_named_builder.py """ import logging from datetime import datetime, timezone from desflow import ConsoleEgress, SimulationContext from desflow.values import Template UNTIL = 10 def build() -> SimulationContext: """Builds the model.""" app = SimulationContext( sim_id="Shop", factor=0, random_seed=42, logical_start_time=datetime(2026, 1, 1, tzinfo=timezone.utc), ) app.add_egress(ConsoleEgress()) # A blueprint's `keys` is one arrival for each name here, each with its own key for name in ["north", "south", "east"]: app.add_arrival( f"warehouses-{name}", "constant", value=2, spawn="report", key=lambda n, name=name: name, ) report_payload = Template( { "warehouse": {"gen": "entity"}, "orders_waiting": {"gen": "integer", "bounds": [0, 40]}, }, name="tasks.report", ) @app.task(name="report") def report(task_id): """Gives one report record.""" return report_payload return app if __name__ == "__main__": logging.basicConfig(level=logging.INFO, format="%(levelname)s %(message)s") build().run(until=UNTIL) ``` ```python """Many entities: ten tills, each with its own key, low-level API. The low-level version of `many_entities.yaml`: plain SimPy on a `DynamicRealtimeEnvironment`, which publishes each record with `publish_event`. Each till is one process with its own key. Each draw is made with `Sampler`, from the random sequence the blueprint's generator at that place uses, so the draws are the blueprint's, and the ten tills share that one sequence. Needs: nothing. Run it with: python docs/snippets/generate-data/many_entities_low_level.py """ import logging from datetime import datetime, timezone from desflow import ( ConsoleEgress, DistributionConfig, DynamicRealtimeEnvironment, Sampler, ) UNTIL = 300 START = datetime(2026, 1, 1, tzinfo=timezone.utc) ENVIRONMENT: dict = {"logical_start_time": START, "timezone": "UTC"} def build(env: DynamicRealtimeEnvironment) -> None: """Starts the ten tills on `env`.""" sampler = Sampler(seed=42) takings = sampler.generator("tasks.report.payload.takings") tills_gap = DistributionConfig(dist="constant", value=60) # The random sequence the blueprint's draw uses tills_gap.stream = "arrival.tills" sent = {"report": 0} def till(key): while True: yield env.timeout(sampler.sample(tills_gap)) payload = { "till": key, "takings": round(float(takings.normal(400, 60)), 2), } env.publish_event(key, payload, task="report", instance=sent["report"]) sent["report"] += 1 for number in range(1, 11): env.process(till(f"till-{number}")) def run() -> None: """Runs the model unpaced into the console.""" env = DynamicRealtimeEnvironment(factor=0, **ENVIRONMENT) env.setup_egress([ConsoleEgress()]) build(env) try: env.run(until=UNTIL) finally: env.teardown() if __name__ == "__main__": logging.basicConfig(level=logging.INFO, format="%(levelname)s %(message)s") run() ``` ```python """Many entities, by name: one entity for each key in a list, low-level API. The low-level version of `many_entities_named.yaml`: plain SimPy on a `DynamicRealtimeEnvironment`, which publishes each record with `publish_event`. Each warehouse is one process with its own name. Each draw is made with `Sampler`, from the random sequence the blueprint's generator at that place uses, so the draws are the blueprint's, and the three warehouses share that one sequence. Needs: nothing. Run it with: python docs/snippets/generate-data/many_entities_named_low_level.py """ import logging from datetime import datetime, timezone from desflow import ( ConsoleEgress, DistributionConfig, DynamicRealtimeEnvironment, Sampler, ) UNTIL = 10 START = datetime(2026, 1, 1, tzinfo=timezone.utc) ENVIRONMENT: dict = {"logical_start_time": START, "timezone": "UTC"} def build(env: DynamicRealtimeEnvironment) -> None: """Starts the three warehouses on `env`.""" sampler = Sampler(seed=42) waiting = sampler.generator("tasks.report.payload.orders_waiting") warehouses_gap = DistributionConfig(dist="constant", value=2) # The random sequence the blueprint's draw uses warehouses_gap.stream = "arrival.warehouses" sent = {"report": 0} def warehouse(key): while True: yield env.timeout(sampler.sample(warehouses_gap)) payload = { "warehouse": key, "orders_waiting": int(waiting.integers(0, 40 + 1)), } env.publish_event(key, payload, task="report", instance=sent["report"]) sent["report"] += 1 for key in ["north", "south", "east"]: env.process(warehouse(key)) def run() -> None: """Runs the model unpaced into the console.""" env = DynamicRealtimeEnvironment(factor=0, **ENVIRONMENT) env.setup_egress([ConsoleEgress()]) build(env) try: env.run(until=UNTIL) finally: env.teardown() if __name__ == "__main__": logging.basicConfig(level=logging.INFO, format="%(levelname)s %(message)s") run() ``` # Build on the Last Value Make each value depend on the one before it, as a price that drifts: five products are priced every second, and each price is the product's last price plus a small step. ______________________________________________________________________ ## Before You Start - The commands run from the root of a clone of the repository, where the files are in `docs/snippets/generate-data/`. The Full Files block of this page holds the same files, for a reader who saves them by hand. ```bash git clone https://github.com/jaehyeon-kim/desflow.git cd desflow ``` - [First Simulation](https://jaehyeon.me/desflow/latest/learn/first-model/first-simulation/index.md) explains arrivals, tasks and the records a run writes. - [`previous`](https://jaehyeon.me/desflow/latest/generators/related-records/previous/index.md) lists the keys of the generator that reads the last value, and [`add`](https://jaehyeon.me/desflow/latest/generators/maths/add/index.md), [`min`](https://jaehyeon.me/desflow/latest/generators/maths/min/index.md) and [`max`](https://jaehyeon.me/desflow/latest/generators/maths/max/index.md) list the generators that combine values. ______________________________________________________________________ ## Steps ### Start Five Products `count: 5` starts five products from one arrival, and each is priced every second. Each keeps its own last payload, so `previous` reads the last value of the same field for the same product. ```yaml arrivals: prices: dist: constant value: 1 spawn: price count: 5 key: {gen: sequence, format: "product-{}"} ``` ```python # A blueprint's `count: 5` is five arrivals here, each with the key of its product for number in range(5): app.add_arrival( f"prices{number}", "constant", value=1, spawn="price", key=lambda n, number=number: f"product-{number}", ) ``` A Builder arrival has no `count`, so the file adds one arrival for each product. ```python sampler = Sampler(seed=42) # The places of the two draws in the blueprint name their random sequences step = sampler.generator("tasks.price.payload.price.args.1") drift = sampler.generator("tasks.price.payload.stock.args.1.args.1.args.1") last: dict = {} # product key -> its last price and stock, 20 and 250 at first counts = {"price": 0} ``` `Sampler(seed=42)` makes the two draws. Each generator is named by the place of its draw in the blueprint, so the steps are the blueprint's. A product is priced every second, so there is no gap to draw. ### Read the Last Value `previous` with `path: price` reads the product's last price. `default: 20` is the value before the first record. [`add`](https://jaehyeon.me/desflow/latest/generators/maths/add/index.md) adds a draw between -1 and 1, so the price drifts by up to 1 each second. The stock level adds a normal step to its last value, and [`min`](https://jaehyeon.me/desflow/latest/generators/maths/min/index.md) and [`max`](https://jaehyeon.me/desflow/latest/generators/maths/max/index.md) keep it between 0 and 500 units. ```yaml tasks: price: payload: product: {gen: entity} price: gen: add args: - {gen: previous, path: price, default: 20} - {gen: uniform, low: -1, high: 1} decimals: 2 stock: gen: max args: - 0 - gen: min args: - 500 - gen: add args: - {gen: previous, path: stock, default: 250} - {gen: normal, mean: 0, std: 40} decimals: 0 ``` ```python price_payload = Template( { "product": {"gen": "entity"}, "price": { "gen": "add", "args": [ {"gen": "previous", "path": "price", "default": 20}, {"gen": "uniform", "low": -1, "high": 1}, ], "decimals": 2, }, "stock": { "gen": "max", "args": [ 0, { "gen": "min", "args": [ 500, { "gen": "add", "args": [ { "gen": "previous", "path": "stock", "default": 250, }, {"gen": "normal", "mean": 0, "std": 40}, ], }, ], }, ], "decimals": 0, }, }, name="tasks.price", ) @app.task(name="price") def price(task_id): """Gives one price record.""" return price_payload ``` ```python def product(number): key = f"product-{number}" while True: yield env.timeout(1) price, stock = last.get(key, (20, 250)) price = round(price + step.uniform(-1, 1), 2) stock = int(round(max(0, min(500, stock + float(drift.normal(0, 40)))))) last[key] = (price, stock) env.publish_event( key, {"product": key, "price": price, "stock": stock}, task="price", instance=counts["price"], ) counts["price"] += 1 for number in range(5): env.process(product(number)) ``` A Low-level script keeps each product's last values itself, in the dictionary `last`, because `previous` cannot be read outside a task. It draws the two steps from `Sampler.generator` for the places the blueprint uses, so the draws are the blueprint's. ______________________________________________________________________ ## Check the Result Run the model for 30 simulated seconds and print its first 6 records. The five products are priced at 1 second, each near 20, and `product-0` is priced again at 2 seconds within 1 of its first price. ```bash desflow run docs/snippets/generate-data/build_on_the_last_value.yaml --sample 6 ``` ```bash python docs/snippets/generate-data/build_on_the_last_value_builder.py ``` This prints every record of the run as an `[EVT]` line with the same fields and values. ```bash python docs/snippets/generate-data/build_on_the_last_value_low_level.py ``` This prints every record of the run as an `[EVT]` line with the same fields and values. ```text {"stream_type":"event","sim_ts":1.0,"timestamp":"...","key":"product-0","task":"price","instance":0,"value":{"product":"product-0","price":20.07,"stock":260}} {"stream_type":"event","sim_ts":1.0,"timestamp":"...","key":"product-1","task":"price","instance":1,"value":{"product":"product-1","price":19.78,"stock":218}} {"stream_type":"event","sim_ts":1.0,"timestamp":"...","key":"product-2","task":"price","instance":2,"value":{"product":"product-2","price":20.29,"stock":323}} {"stream_type":"event","sim_ts":1.0,"timestamp":"...","key":"product-3","task":"price","instance":3,"value":{"product":"product-3","price":20.99,"stock":219}} {"stream_type":"event","sim_ts":1.0,"timestamp":"...","key":"product-4","task":"price","instance":4,"value":{"product":"product-4","price":19.28,"stock":271}} {"stream_type":"event","sim_ts":2.0,"timestamp":"...","key":"product-0","task":"price","instance":5,"value":{"product":"product-0","price":20.15,"stock":243}} ``` The docs test runs the model for 5,000 simulated seconds: no price differs from the product's last price by more than 1, and the stock reaches both 0 and 500 but never leaves that range. ______________________________________________________________________ ## Full Files Full files ```yaml # Build on the last value: prices that drift from the previous price. # # Five products are priced once a second. Each price is the product's last price plus a # draw between -1 and 1, starting from 20. Each stock level adds a normal step to the # last one and stays between 0 and 500 units. `previous` reads the last value of the # same field of the same product, because with `count` each product keeps its own last # payload. # # Needs: nothing. # Run it with: desflow run docs/snippets/generate-data/build_on_the_last_value.yaml simulation: sim_id: Shop factor: 0 random_seed: 42 logical_start_time: 2026-01-01T00:00:00 egress: - {type: Console} arrivals: prices: dist: constant value: 1 spawn: price count: 5 key: {gen: sequence, format: "product-{}"} tasks: price: payload: product: {gen: entity} price: gen: add args: - {gen: previous, path: price, default: 20} - {gen: uniform, low: -1, high: 1} decimals: 2 stock: gen: max args: - 0 - gen: min args: - 500 - gen: add args: - {gen: previous, path: stock, default: 250} - {gen: normal, mean: 0, std: 40} decimals: 0 run: {until: 30} ``` ```python """Build on the last value: prices that drift from the previous price, builder API. The builder version of `build_on_the_last_value.yaml`: five products, each with the key of its product, are priced once a second for 30 seconds. `previous` reads the last value of the field that the same product published. Needs: nothing. Run it with: python docs/snippets/generate-data/build_on_the_last_value_builder.py """ import logging from datetime import datetime, timezone from desflow import ConsoleEgress, SimulationContext from desflow.values import Template UNTIL = 30 def build() -> SimulationContext: """Builds the products.""" app = SimulationContext( sim_id="Shop", factor=0, random_seed=42, logical_start_time=datetime(2026, 1, 1, tzinfo=timezone.utc), ) app.add_egress(ConsoleEgress()) # A blueprint's `count: 5` is five arrivals here, each with the key of its product for number in range(5): app.add_arrival( f"prices{number}", "constant", value=1, spawn="price", key=lambda n, number=number: f"product-{number}", ) price_payload = Template( { "product": {"gen": "entity"}, "price": { "gen": "add", "args": [ {"gen": "previous", "path": "price", "default": 20}, {"gen": "uniform", "low": -1, "high": 1}, ], "decimals": 2, }, "stock": { "gen": "max", "args": [ 0, { "gen": "min", "args": [ 500, { "gen": "add", "args": [ { "gen": "previous", "path": "stock", "default": 250, }, {"gen": "normal", "mean": 0, "std": 40}, ], }, ], }, ], "decimals": 0, }, }, name="tasks.price", ) @app.task(name="price") def price(task_id): """Gives one price record.""" return price_payload return app if __name__ == "__main__": logging.basicConfig(level=logging.INFO, format="%(levelname)s %(message)s") build().run(until=UNTIL) ``` ```python """Build on the last value: prices that drift from the previous price, low-level API. The low-level version of `build_on_the_last_value.yaml`: plain SimPy on a `DynamicRealtimeEnvironment`, which publishes each record with `publish_event`. A low-level model keeps each product's last price and stock itself, and draws each step from the random sequence the blueprint's generator uses, with `Sampler`. Needs: nothing. Run it with: python docs/snippets/generate-data/build_on_the_last_value_low_level.py """ import logging from datetime import datetime, timezone from desflow import ConsoleEgress, DynamicRealtimeEnvironment, Sampler UNTIL = 30 START = datetime(2026, 1, 1, tzinfo=timezone.utc) ENVIRONMENT: dict = {"logical_start_time": START, "timezone": "UTC"} def build(env: DynamicRealtimeEnvironment) -> None: """Starts the five products on `env`.""" sampler = Sampler(seed=42) # The places of the two draws in the blueprint name their random sequences step = sampler.generator("tasks.price.payload.price.args.1") drift = sampler.generator("tasks.price.payload.stock.args.1.args.1.args.1") last: dict = {} # product key -> its last price and stock, 20 and 250 at first counts = {"price": 0} def product(number): key = f"product-{number}" while True: yield env.timeout(1) price, stock = last.get(key, (20, 250)) price = round(price + step.uniform(-1, 1), 2) stock = int(round(max(0, min(500, stock + float(drift.normal(0, 40)))))) last[key] = (price, stock) env.publish_event( key, {"product": key, "price": price, "stock": stock}, task="price", instance=counts["price"], ) counts["price"] += 1 for number in range(5): env.process(product(number)) def run() -> None: """Runs the model unpaced into the console.""" env = DynamicRealtimeEnvironment(factor=0, **ENVIRONMENT) env.setup_egress([ConsoleEgress()]) build(env) try: env.run(until=UNTIL) finally: env.teardown() if __name__ == "__main__": logging.basicConfig(level=logging.INFO, format="%(levelname)s %(message)s") run() ``` # Skewed Keys Make a few keys carry most of the records: 5 of 25 customers place 75 orders in 100, and the customer is the record key, so a Kafka topic puts the busy customers' records in a few partitions. ______________________________________________________________________ ## Before You Start - The commands run from the root of a clone of the repository, where the files are in `docs/snippets/generate-data/`. The Full Files block of this page holds the same files, for a reader who saves them by hand. ```bash git clone https://github.com/jaehyeon-kim/desflow.git cd desflow ``` - [First Simulation](https://jaehyeon.me/desflow/latest/learn/first-model/first-simulation/index.md) explains arrivals, tasks and the records a run writes. - [`when`](https://jaehyeon.me/desflow/latest/generators/conditions/when/index.md) and [`boolean`](https://jaehyeon.me/desflow/latest/generators/random-numbers/boolean/index.md) list the keys of the two generators that make the skew. ______________________________________________________________________ ## Steps ### Describe the Arrival An order arrives every second. ```yaml arrivals: orders: {dist: constant, value: 1, spawn: order} ``` ```python app.add_arrival("orders", "constant", value=1, spawn="order") ``` ```python sampler = Sampler(seed=42) busy = sampler.generator("tasks.order.vars.busy") busy_customer = sampler.generator("tasks.order.payload.customer_id.then") quiet_customer = sampler.generator("tasks.order.payload.customer_id.else") orders_gap = DistributionConfig(dist="constant", value=1) # The random sequence the blueprint's draw uses orders_gap.stream = "arrival.orders" ``` `Sampler(seed=42)` supplies every draw: a random generator for each payload field and for the gap. The `stream` line names the random sequence the blueprint uses for this arrival, so the three forms draw the same gaps. ### Skew the Customers A `vars` entry is drawn once for each order before its payload, and the payload reads it by name. `busy` is a [`boolean`](https://jaehyeon.me/desflow/latest/generators/random-numbers/boolean/index.md) that is true 75 times in 100. [`when`](https://jaehyeon.me/desflow/latest/generators/conditions/when/index.md) then draws the customer from the 5 busy customers (1 to 5) if `busy` is true, and from the other 20 (6 to 25) if it is not. `key_field: customer_id` makes that field the record key. ```yaml tasks: order: vars: busy: {gen: boolean, p: 0.75} key_field: customer_id payload: order_id: {gen: sequence, start: 1} customer_id: gen: when condition: busy then: {gen: integer, bounds: [1, 5]} else: {gen: integer, bounds: [6, 25]} ``` ```python order_payload = Template( { "order_id": {"gen": "sequence", "start": 1}, "customer_id": { "gen": "when", "condition": "busy", "then": {"gen": "integer", "bounds": [1, 5]}, "else": {"gen": "integer", "bounds": [6, 25]}, }, }, name="tasks.order", vars={"busy": {"gen": "boolean", "p": 0.75}}, ) @app.task(name="order", key_field="customer_id") def order(task_id): """Gives one order record.""" return order_payload ``` ```python def orders_source(): number = 0 while True: yield env.timeout(sampler.sample(orders_gap)) number += 1 if busy.random() < 0.75: customer_id = int(busy_customer.integers(1, 5 + 1)) else: customer_id = int(quiet_customer.integers(6, 25 + 1)) env.publish_event( str(customer_id), # the record key, as the task's key_field gives it {"order_id": number, "customer_id": customer_id}, task="order", instance=number - 1, ) env.process(orders_source()) ``` ______________________________________________________________________ ## Check the Result Run the model for 1,000 simulated seconds, print its first 6 records and read the key of each. The `key` of a record is its `customer_id` as text. ```bash desflow run docs/snippets/generate-data/skewed_keys.yaml --sample 6 ``` ```bash python docs/snippets/generate-data/skewed_keys_builder.py ``` This prints every record of the run as an `[EVT]` line with the same fields and values. ```bash python docs/snippets/generate-data/skewed_keys_low_level.py ``` This prints every record of the run as an `[EVT]` line with the same fields and values. ```text {"stream_type":"event","sim_ts":1.0,"timestamp":"...","key":"1","task":"order","instance":0,"value":{"order_id":1,"customer_id":1}} {"stream_type":"event","sim_ts":2.0,"timestamp":"...","key":"3","task":"order","instance":1,"value":{"order_id":2,"customer_id":3}} {"stream_type":"event","sim_ts":3.0,"timestamp":"...","key":"5","task":"order","instance":2,"value":{"order_id":3,"customer_id":5}} {"stream_type":"event","sim_ts":4.0,"timestamp":"...","key":"20","task":"order","instance":3,"value":{"order_id":4,"customer_id":20}} {"stream_type":"event","sim_ts":5.0,"timestamp":"...","key":"2","task":"order","instance":4,"value":{"order_id":5,"customer_id":2}} {"stream_type":"event","sim_ts":6.0,"timestamp":"...","key":"1","task":"order","instance":5,"value":{"order_id":6,"customer_id":1}} ``` The docs test runs the model for 10,000 simulated seconds and counts the orders: customers 1 to 5 place about 75 percent of them, each about 15 percent, and customers 6 to 25 place the rest. ______________________________________________________________________ ## Full Files Full files ```yaml # Skewed keys: 5 of 25 customers place 75 percent of the orders. # # An order arrives every second. A draw that is true 75 percent of the time makes the # order come from one of 5 busy customers out of 25, and the rest come from the other # 20. `key_field` makes the customer the record key, so a Kafka topic puts the busy # customers' records in a few partitions. # # Needs: nothing. # Run it with: desflow run docs/snippets/generate-data/skewed_keys.yaml simulation: sim_id: Shop factor: 0 random_seed: 42 logical_start_time: 2026-01-01T00:00:00 egress: - {type: Console} arrivals: orders: {dist: constant, value: 1, spawn: order} tasks: order: vars: busy: {gen: boolean, p: 0.75} key_field: customer_id payload: order_id: {gen: sequence, start: 1} customer_id: gen: when condition: busy then: {gen: integer, bounds: [1, 5]} else: {gen: integer, bounds: [6, 25]} run: {until: 1000} ``` ```python """Skewed keys: 5 of 25 customers place 75 percent of the orders, builder API. The builder version of `skewed_keys.yaml`: an order every second, 75 percent from the 5 busy customers of 25, with the customer as the key. Needs: nothing. Run it with: python docs/snippets/generate-data/skewed_keys_builder.py """ import logging from datetime import datetime, timezone from desflow import ConsoleEgress, SimulationContext from desflow.values import Template UNTIL = 1000 def build() -> SimulationContext: """Builds the model.""" app = SimulationContext( sim_id="Shop", factor=0, random_seed=42, logical_start_time=datetime(2026, 1, 1, tzinfo=timezone.utc), ) app.add_egress(ConsoleEgress()) app.add_arrival("orders", "constant", value=1, spawn="order") order_payload = Template( { "order_id": {"gen": "sequence", "start": 1}, "customer_id": { "gen": "when", "condition": "busy", "then": {"gen": "integer", "bounds": [1, 5]}, "else": {"gen": "integer", "bounds": [6, 25]}, }, }, name="tasks.order", vars={"busy": {"gen": "boolean", "p": 0.75}}, ) @app.task(name="order", key_field="customer_id") def order(task_id): """Gives one order record.""" return order_payload return app if __name__ == "__main__": logging.basicConfig(level=logging.INFO, format="%(levelname)s %(message)s") build().run(until=UNTIL) ``` ```python """Skewed keys: 5 of 25 customers place 75 percent of the orders, low-level API. The low-level version of `skewed_keys.yaml`: plain SimPy on a `DynamicRealtimeEnvironment`, which publishes each record with `publish_event`. Each draw is made with `Sampler`, from the random sequence the blueprint's generator at that place uses, so the draws are the blueprint's. A draw that is true 75 percent of the time picks the busy customers, and the customer is the record key. Needs: nothing. Run it with: python docs/snippets/generate-data/skewed_keys_low_level.py """ import logging from datetime import datetime, timezone from desflow import ( ConsoleEgress, DistributionConfig, DynamicRealtimeEnvironment, Sampler, ) UNTIL = 1000 START = datetime(2026, 1, 1, tzinfo=timezone.utc) ENVIRONMENT: dict = {"logical_start_time": START, "timezone": "UTC"} def build(env: DynamicRealtimeEnvironment) -> None: """Starts the arrival on `env`.""" sampler = Sampler(seed=42) busy = sampler.generator("tasks.order.vars.busy") busy_customer = sampler.generator("tasks.order.payload.customer_id.then") quiet_customer = sampler.generator("tasks.order.payload.customer_id.else") orders_gap = DistributionConfig(dist="constant", value=1) # The random sequence the blueprint's draw uses orders_gap.stream = "arrival.orders" def orders_source(): number = 0 while True: yield env.timeout(sampler.sample(orders_gap)) number += 1 if busy.random() < 0.75: customer_id = int(busy_customer.integers(1, 5 + 1)) else: customer_id = int(quiet_customer.integers(6, 25 + 1)) env.publish_event( str(customer_id), # the record key, as the task's key_field gives it {"order_id": number, "customer_id": customer_id}, task="order", instance=number - 1, ) env.process(orders_source()) def run() -> None: """Runs the model unpaced into the console.""" env = DynamicRealtimeEnvironment(factor=0, **ENVIRONMENT) env.setup_egress([ConsoleEgress()]) build(env) try: env.run(until=UNTIL) finally: env.teardown() if __name__ == "__main__": logging.basicConfig(level=logging.INFO, format="%(levelname)s %(message)s") run() ``` # Change State Over Time Write a state machine as tasks: three packing stations that move between running, slow and stopped, each state lasting a set time, and each record telling which state a station was in. ______________________________________________________________________ ## Before You Start - The commands run from the root of a clone of the repository, where the files are in `docs/snippets/generate-data/`. The Full Files block of this page holds the same files, for a reader who saves them by hand. ```bash git clone https://github.com/jaehyeon-kim/desflow.git cd desflow ``` - [First Simulation](https://jaehyeon.me/desflow/latest/learn/first-model/first-simulation/index.md) explains arrivals, tasks and the records a run writes. - [Task Flow](https://jaehyeon.me/desflow/latest/user-guide/model-parts/task-flow/index.md) explains `next` and its `weights`. ______________________________________________________________________ ## Steps ### Start the Stations `initial: 3` creates three stations when the run is built, and `spawn: running` starts each one in the task `running`. The `key` generator names them `station-1` to `station-3`. ```yaml arrivals: stations: initial: 3 spawn: running key: {gen: sequence, start: 1, format: "station-{}"} ``` ```python app.add_initial_arrival( "stations", 3, spawn="running", key=lambda n: f"station-{n}" ) ``` ```python sampler = Sampler(seed=42) routers = { state: Router(rule, rng=sampler.generator(f"route.{state}")) for state, rule in NEXT.items() if isinstance(rule, dict) } counts = {state: 0 for state in DWELL} ``` ### Write a Task for Each State Each state is a task. `service_time` is how long a station stays in the state, the payload names the station and the state, and `next` chooses the state that follows. After running or slow the choice is by `weights`, and after stopped it is always slow, so a station never goes from stopped to running. A task writes its record when its time ends. ```yaml tasks: running: service_time: 300 payload: station: {gen: entity} state: running next: weights: {running: 85, slow: 15} slow: service_time: 120 payload: station: {gen: entity} state: slow next: weights: {running: 55, slow: 25, stopped: 20} stopped: service_time: 240 payload: station: {gen: entity} state: stopped next: slow ``` ```python def state(name): return Template( {"station": {"gen": "entity"}, "state": name}, name=f"tasks.{name}" ) running, slow, stopped = state("running"), state("slow"), state("stopped") @app.task( name="running", service_time=300, next={"weights": {"running": 85, "slow": 15}}, ) def running_task(task_id): """The station is running.""" return running @app.task( name="slow", service_time=120, next={"weights": {"running": 55, "slow": 25, "stopped": 20}}, ) def slow_task(task_id): """The station is slow.""" return slow @app.task(name="stopped", service_time=240, next="slow") def stopped_task(task_id): """The station is stopped.""" return stopped ``` ```python DWELL = {"running": 300, "slow": 120, "stopped": 240} # seconds in each state NEXT = { "running": {"weights": {"running": 85, "slow": 15}}, "slow": {"weights": {"running": 55, "slow": 25, "stopped": 20}}, "stopped": "slow", } ``` ```python def station(number): key = f"station-{number}" state = "running" while True: instance = counts[state] counts[state] += 1 env.publish_event(key, {"status": "started"}, task=state, instance=instance) yield env.timeout(DWELL[state]) env.publish_event( key, {"station": key, "state": state}, task=state, instance=instance ) if state in routers: state = routers[state].choose( Upstream(task_id=0, key=key, attributes={}) ) else: state = NEXT[state] for number in range(1, 4): env.process(station(number)) ``` The Low-level file keeps the dwell times and the rules in two dictionaries. A `Router` draws the next state from the rule of the current one, from its own random sequence, `route.`. ______________________________________________________________________ ## Check the Result Run the model for 2 simulated hours and print its first 8 records. Each station publishes a `started` record when it enters a state, and a record with its `station` and `state` when the state ends. The three stations start `running` at 0 seconds, and the first state ends at 300 seconds. ```bash desflow run docs/snippets/generate-data/change_state_over_time.yaml --sample 8 ``` ```bash python docs/snippets/generate-data/change_state_over_time_builder.py ``` This prints every record of the run as an `[EVT]` line with the same fields and values. ```bash python docs/snippets/generate-data/change_state_over_time_low_level.py ``` This prints every record of the run as an `[EVT]` line with the same fields and values. ```text {"stream_type":"event","sim_ts":0.0,"timestamp":"...","key":"station-1","task":"running","instance":0,"value":{"status":"started"}} {"stream_type":"event","sim_ts":0.0,"timestamp":"...","key":"station-2","task":"running","instance":1,"value":{"status":"started"}} {"stream_type":"event","sim_ts":0.0,"timestamp":"...","key":"station-3","task":"running","instance":2,"value":{"status":"started"}} {"stream_type":"event","sim_ts":300.0,"timestamp":"...","key":"station-1","task":"running","instance":0,"value":{"station":"station-1","state":"running"}} {"stream_type":"event","sim_ts":300.0,"timestamp":"...","key":"station-1","task":"slow","instance":0,"value":{"status":"started"}} {"stream_type":"event","sim_ts":300.0,"timestamp":"...","key":"station-2","task":"running","instance":1,"value":{"station":"station-2","state":"running"}} {"stream_type":"event","sim_ts":300.0,"timestamp":"...","key":"station-2","task":"running","instance":3,"value":{"status":"started"}} {"stream_type":"event","sim_ts":300.0,"timestamp":"...","key":"station-3","task":"running","instance":2,"value":{"station":"station-3","state":"running"}} ``` The time between two records of a station is the dwell time of the later state. The docs test follows every station through the run: each move is one of the allowed ones, and each state lasts its set time. ______________________________________________________________________ ## Full Files Full files ```yaml # Change state over time: packing stations move between running, slow and stopped. # # Each of 3 stations is a chain of tasks, one for each state. A task holds the station # in its state for a time, writes a record of the state when the time ends, and `next` # chooses the state that follows: by weights after running or slow, and always slow # after stopped, so a station never goes from stopped to running. The run lasts 2 hours. # # Needs: nothing. # Run it with: desflow run docs/snippets/generate-data/change_state_over_time.yaml simulation: sim_id: Shop factor: 0 random_seed: 42 logical_start_time: 2026-01-01T00:00:00 egress: - {type: Console} arrivals: stations: initial: 3 spawn: running key: {gen: sequence, start: 1, format: "station-{}"} tasks: running: service_time: 300 payload: station: {gen: entity} state: running next: weights: {running: 85, slow: 15} slow: service_time: 120 payload: station: {gen: entity} state: slow next: weights: {running: 55, slow: 25, stopped: 20} stopped: service_time: 240 payload: station: {gen: entity} state: stopped next: slow run: {until: 2 hours} ``` ```python """Change state over time: stations move between three states, builder API. The builder version of `change_state_over_time.yaml`: one task for each state, with a dwell time as `service_time` and the next state in `next`. Needs: nothing. Run it with: python docs/snippets/generate-data/change_state_over_time_builder.py """ import logging from datetime import datetime, timezone from desflow import ConsoleEgress, SimulationContext from desflow.values import Template UNTIL = 7200 def build() -> SimulationContext: """Builds the three stations.""" app = SimulationContext( sim_id="Shop", factor=0, random_seed=42, logical_start_time=datetime(2026, 1, 1, tzinfo=timezone.utc), ) app.add_egress(ConsoleEgress()) app.add_initial_arrival( "stations", 3, spawn="running", key=lambda n: f"station-{n}" ) def state(name): return Template( {"station": {"gen": "entity"}, "state": name}, name=f"tasks.{name}" ) running, slow, stopped = state("running"), state("slow"), state("stopped") @app.task( name="running", service_time=300, next={"weights": {"running": 85, "slow": 15}}, ) def running_task(task_id): """The station is running.""" return running @app.task( name="slow", service_time=120, next={"weights": {"running": 55, "slow": 25, "stopped": 20}}, ) def slow_task(task_id): """The station is slow.""" return slow @app.task(name="stopped", service_time=240, next="slow") def stopped_task(task_id): """The station is stopped.""" return stopped return app if __name__ == "__main__": logging.basicConfig(level=logging.INFO, format="%(levelname)s %(message)s") build().run(until=UNTIL) ``` ```python """Change state over time: stations move between three states, low-level API. The low-level version of `change_state_over_time.yaml`: plain SimPy on a `DynamicRealtimeEnvironment`. Each station is one process that holds a state for its dwell time, publishes the record of the state, and asks a `Router` for the next state. Needs: nothing. Run it with: python docs/snippets/generate-data/change_state_over_time_low_level.py """ import logging from datetime import datetime, timezone from desflow import ( ConsoleEgress, DynamicRealtimeEnvironment, Router, Sampler, Upstream, ) UNTIL = 7200 START = datetime(2026, 1, 1, tzinfo=timezone.utc) ENVIRONMENT: dict = {"logical_start_time": START, "timezone": "UTC"} DWELL = {"running": 300, "slow": 120, "stopped": 240} # seconds in each state NEXT = { "running": {"weights": {"running": 85, "slow": 15}}, "slow": {"weights": {"running": 55, "slow": 25, "stopped": 20}}, "stopped": "slow", } def build(env: DynamicRealtimeEnvironment) -> None: """Starts the three stations on `env`.""" sampler = Sampler(seed=42) routers = { state: Router(rule, rng=sampler.generator(f"route.{state}")) for state, rule in NEXT.items() if isinstance(rule, dict) } counts = {state: 0 for state in DWELL} def station(number): key = f"station-{number}" state = "running" while True: instance = counts[state] counts[state] += 1 env.publish_event(key, {"status": "started"}, task=state, instance=instance) yield env.timeout(DWELL[state]) env.publish_event( key, {"station": key, "state": state}, task=state, instance=instance ) if state in routers: state = routers[state].choose( Upstream(task_id=0, key=key, attributes={}) ) else: state = NEXT[state] for number in range(1, 4): env.process(station(number)) def run() -> None: """Runs the model unpaced into the console.""" env = DynamicRealtimeEnvironment(factor=0, **ENVIRONMENT) env.setup_egress([ConsoleEgress()]) build(env) try: env.run(until=UNTIL) finally: env.teardown() if __name__ == "__main__": logging.basicConfig(level=logging.INFO, format="%(levelname)s %(message)s") run() ``` # Look Up Other Records Join records as they are made: an order names a customer written earlier, a payment reads the order that led to it, and a report summarises the last 10 orders. ______________________________________________________________________ ## Before You Start - The commands run from the root of a clone of the repository, where the files are in `docs/snippets/generate-data/`. The Full Files block of this page holds the same files, for a reader who saves them by hand. ```bash git clone https://github.com/jaehyeon-kim/desflow.git cd desflow ``` - [First Simulation](https://jaehyeon.me/desflow/latest/learn/first-model/first-simulation/index.md) explains arrivals, tasks and the records a run writes. - [Task Flow](https://jaehyeon.me/desflow/latest/user-guide/model-parts/task-flow/index.md) explains `next`. [`lookup`](https://jaehyeon.me/desflow/latest/generators/related-records/lookup/index.md), [`upstream`](https://jaehyeon.me/desflow/latest/generators/related-records/upstream/index.md) and [`aggregate`](https://jaehyeon.me/desflow/latest/generators/related-records/aggregate/index.md) list the keys of the three generators. ______________________________________________________________________ ## Steps ### Describe the Arrivals Five customers are written when the run starts (`initial: 5`), and another about every 10 seconds. An order arrives about once a second, and a report every 10 seconds. ```yaml arrivals: customers: {initial: 5, dist: exponential, rate: 0.1, spawn: customer} orders: {dist: exponential, rate: 1, spawn: order} reports: {dist: constant, value: 10, spawn: report} ``` ```python app.add_arrival("customers", "exponential", rate=0.1, spawn="customer", initial=5) app.add_arrival("orders", "exponential", rate=1, spawn="order") app.add_arrival("reports", "constant", value=10, spawn="report") ``` ```python sampler = Sampler(seed=42) country = sampler.generator("tasks.customer.payload.country") pick = sampler.generator("tasks.order.payload.customer_id") total = sampler.generator("tasks.order.payload.total") customer_gap = DistributionConfig(dist="exponential", rate=0.1) # The random sequence the blueprint's draw uses customer_gap.stream = "arrival.customers" order_gap = DistributionConfig(dist="exponential", rate=1) order_gap.stream = "arrival.orders" report_gap = DistributionConfig(dist="constant", value=10) report_gap.stream = "arrival.reports" customer_rows: list = [] # the customers written so far, for the lookup order_rows: list = [] # the orders written so far, for the aggregate sent = {"customer": 0, "report": 0} ``` `Sampler(seed=42)` supplies every draw: a random generator for each payload field and for the gap. The `stream` line names the random sequence the blueprint uses for this arrival, so the three forms draw the same gaps. ### Read Other Records Three generators read the rows that other tasks have written: - `lookup` gives an order the `customer_id` of a customer already written. The five customers written at the start make sure that every order finds one. An order that starts before any customer has a row is dropped, so no record is written for it. - `upstream` gives the payment the `order_id` and `total` of the order that `next: payment` routed to it. - `aggregate` gives a report the mean and the largest total of the last 10 orders (`last: 10`). ```yaml tasks: customer: payload: customer_id: {gen: sequence, start: 1} country: {gen: one_of, choices: [AU, NZ, SG]} order: payload: order_id: {gen: sequence, start: 1} customer_id: {gen: lookup, task: customer, path: customer_id} total: {gen: uniform, low: 5, high: 200, decimals: 2} next: payment payment: payload: order_id: {gen: upstream, path: order_id} amount: {gen: upstream, path: total} report: payload: mean_total: {gen: aggregate, task: order, path: total, last: 10, function: mean} largest_total: {gen: aggregate, task: order, path: total, last: 10, function: max} ``` ```python customer_payload = Template( { "customer_id": {"gen": "sequence", "start": 1}, "country": {"gen": "one_of", "choices": ["AU", "NZ", "SG"]}, }, name="tasks.customer", ) order_payload = Template( { "order_id": {"gen": "sequence", "start": 1}, "customer_id": {"gen": "lookup", "task": "customer", "path": "customer_id"}, "total": {"gen": "uniform", "low": 5, "high": 200, "decimals": 2}, }, name="tasks.order", ) payment_payload = Template( { "order_id": {"gen": "upstream", "path": "order_id"}, "amount": {"gen": "upstream", "path": "total"}, }, name="tasks.payment", ) report_payload = Template( { "mean_total": { "gen": "aggregate", "task": "order", "path": "total", "last": 10, "function": "mean", }, "largest_total": { "gen": "aggregate", "task": "order", "path": "total", "last": 10, "function": "max", }, }, name="tasks.report", ) # A task that something looks up or aggregates keeps its rows: `history` is how # many. A builder task needs it because a `Template` payload is not searched for # them. @app.task(name="customer", history=1_000_000) def customer(task_id): """Gives one customer record.""" return customer_payload @app.task(name="order", next="payment", history=10) def order(task_id): """Gives one order record.""" return order_payload @app.task(name="payment") def payment(task_id): """Gives one payment record.""" return payment_payload @app.task(name="report") def report(task_id): """Gives one report record.""" return report_payload ``` A task that something looks up or aggregates keeps its rows, and `history=` says how many. A Builder task needs it, because a `Template` payload is not searched for them. A blueprint keeps 1,000,000 rows by default. ```python def write_customer(key): """Publishes the next customer and keeps its row.""" row = { "customer_id": len(customer_rows) + 1, "country": COUNTRIES[int(country.integers(len(COUNTRIES)))], } customer_rows.append(row) env.publish_event(key, row, task="customer", instance=sent["customer"]) sent["customer"] += 1 def customers(): for number in itertools.count(6): # 1 to 5 exist at the start yield env.timeout(sampler.sample(customer_gap)) write_customer(f"customers-{number}") def orders(): for number in itertools.count(1): yield env.timeout(sampler.sample(order_gap)) key, instance = f"orders-{number}", number - 1 # The lookup: one row of the customers written so far, chosen at random customer = customer_rows[int(pick.integers(len(customer_rows)))] order = { "order_id": number, "customer_id": customer["customer_id"], "total": round(float(total.uniform(5, 200)), 2), } order_rows.append(order) env.publish_event(key, order, task="order", instance=instance) # The upstream: the payment reads the order it follows payment = {"order_id": order["order_id"], "amount": order["total"]} env.publish_event(key, payment, task="payment", instance=instance) def reports(): while True: yield env.timeout(sampler.sample(report_gap)) # The aggregate: the last 10 orders, newest first, as the blueprint does recent = [row["total"] for row in reversed(order_rows[-10:])] report = { "mean_total": sum(recent) / len(recent), "largest_total": max(recent), } env.publish_event( f"reports-{sent['report'] + 1}", report, task="report", instance=sent["report"], ) sent["report"] += 1 def first(number): yield env.timeout(0) write_customer(f"customers-{number}") env.process(customers()) env.process(orders()) env.process(reports()) for number in range(1, 6): env.process(first(number)) ``` A Low-level script keeps the rows that a `lookup` or an `aggregate` reads in lists of its own, and picks a customer and takes the last 10 orders itself. ______________________________________________________________________ ## Check the Result Run the model for 60 simulated seconds and print its first 40 records. The block keeps three of them: the first order, the payment that follows it and the first report. The order names a customer that exists, the payment repeats the order's id and total as `amount`, and the report, at 10 seconds, gives the mean and the largest total of the 7 orders written by then, because fewer than 10 have arrived. ```bash desflow run docs/snippets/generate-data/look_up_other_records.yaml --sample 40 ``` ```bash python docs/snippets/generate-data/look_up_other_records_builder.py ``` This prints every record of the run as an `[EVT]` line with the same fields and values. ```bash python docs/snippets/generate-data/look_up_other_records_low_level.py ``` This prints every record of the run as an `[EVT]` line with the same fields and values. ```text {"stream_type":"event","sim_ts":0.3141556656469718,"timestamp":"...","key":"orders-1","task":"order","instance":0,"value":{"order_id":1,"customer_id":5,"total":161.55}} {"stream_type":"event","sim_ts":0.3141556656469718,"timestamp":"...","key":"orders-1","task":"payment","instance":0,"value":{"order_id":1,"amount":161.55}} {"stream_type":"event","sim_ts":10.0,"timestamp":"...","key":"reports-1","task":"report","instance":0,"value":{"mean_total":105.08285714285715,"largest_total":177.63}} ``` The docs test checks every order against the customers written by then, every payment against its order, and every report against the last 10 orders. ______________________________________________________________________ ## Full Files Full files ```yaml # Look up other records: an order names a customer, a payment reads its order, and a # report summarises the recent orders. # # Customers are written at the start and about every 10 seconds. `lookup` gives each # order the id of a customer already written. `next` routes each order to a payment, and # `upstream` gives the payment the order's id and total. A report every 10 seconds uses # `aggregate` to give the mean and the largest total of the last 10 orders. # # Needs: nothing. # Run it with: desflow run docs/snippets/generate-data/look_up_other_records.yaml simulation: sim_id: Shop factor: 0 random_seed: 42 logical_start_time: 2026-01-01T00:00:00 egress: - {type: Console} arrivals: customers: {initial: 5, dist: exponential, rate: 0.1, spawn: customer} orders: {dist: exponential, rate: 1, spawn: order} reports: {dist: constant, value: 10, spawn: report} tasks: customer: payload: customer_id: {gen: sequence, start: 1} country: {gen: one_of, choices: [AU, NZ, SG]} order: payload: order_id: {gen: sequence, start: 1} customer_id: {gen: lookup, task: customer, path: customer_id} total: {gen: uniform, low: 5, high: 200, decimals: 2} next: payment payment: payload: order_id: {gen: upstream, path: order_id} amount: {gen: upstream, path: total} report: payload: mean_total: {gen: aggregate, task: order, path: total, last: 10, function: mean} largest_total: {gen: aggregate, task: order, path: total, last: 10, function: max} run: {until: 60} ``` ```python """Look up other records: an order names a customer, a payment reads its order, and a report summarises the recent orders, builder API. The builder version of `look_up_other_records.yaml`: customers are written at the start and about every 10 seconds. `lookup` gives each order the id of a customer already written. `next` routes each order to a payment, and `upstream` gives the payment the order's id and total. A report every 10 seconds uses `aggregate` to give the mean and the largest total of the last 10 orders. Needs: nothing. Run it with: python docs/snippets/generate-data/look_up_other_records_builder.py """ import logging from datetime import datetime, timezone from desflow import ConsoleEgress, SimulationContext from desflow.values import Template UNTIL = 60 def build() -> SimulationContext: """Builds the shop.""" app = SimulationContext( sim_id="Shop", factor=0, random_seed=42, logical_start_time=datetime(2026, 1, 1, tzinfo=timezone.utc), ) app.add_egress(ConsoleEgress()) app.add_arrival("customers", "exponential", rate=0.1, spawn="customer", initial=5) app.add_arrival("orders", "exponential", rate=1, spawn="order") app.add_arrival("reports", "constant", value=10, spawn="report") customer_payload = Template( { "customer_id": {"gen": "sequence", "start": 1}, "country": {"gen": "one_of", "choices": ["AU", "NZ", "SG"]}, }, name="tasks.customer", ) order_payload = Template( { "order_id": {"gen": "sequence", "start": 1}, "customer_id": {"gen": "lookup", "task": "customer", "path": "customer_id"}, "total": {"gen": "uniform", "low": 5, "high": 200, "decimals": 2}, }, name="tasks.order", ) payment_payload = Template( { "order_id": {"gen": "upstream", "path": "order_id"}, "amount": {"gen": "upstream", "path": "total"}, }, name="tasks.payment", ) report_payload = Template( { "mean_total": { "gen": "aggregate", "task": "order", "path": "total", "last": 10, "function": "mean", }, "largest_total": { "gen": "aggregate", "task": "order", "path": "total", "last": 10, "function": "max", }, }, name="tasks.report", ) # A task that something looks up or aggregates keeps its rows: `history` is how # many. A builder task needs it because a `Template` payload is not searched for # them. @app.task(name="customer", history=1_000_000) def customer(task_id): """Gives one customer record.""" return customer_payload @app.task(name="order", next="payment", history=10) def order(task_id): """Gives one order record.""" return order_payload @app.task(name="payment") def payment(task_id): """Gives one payment record.""" return payment_payload @app.task(name="report") def report(task_id): """Gives one report record.""" return report_payload return app if __name__ == "__main__": logging.basicConfig(level=logging.INFO, format="%(levelname)s %(message)s") build().run(until=UNTIL) ``` ```python """Look up other records: an order names a customer, a payment reads its order, and a report summarises the recent orders, low-level API. The low-level version of `look_up_other_records.yaml`: plain SimPy on a `DynamicRealtimeEnvironment`, which publishes each record with `publish_event`. Each draw is made with `Sampler`, from the random sequence the blueprint's generator at that place uses, so the draws are the blueprint's. The script keeps the customers and the orders in lists. The lookup is one draw of a row of the customers, the upstream is the order the payment follows, and the aggregate is the mean and the largest total of the last 10 orders. Needs: nothing. Run it with: python docs/snippets/generate-data/look_up_other_records_low_level.py """ import itertools import logging from datetime import datetime, timezone from desflow import ( ConsoleEgress, DistributionConfig, DynamicRealtimeEnvironment, Sampler, ) UNTIL = 60 START = datetime(2026, 1, 1, tzinfo=timezone.utc) ENVIRONMENT: dict = {"logical_start_time": START, "timezone": "UTC"} COUNTRIES = ["AU", "NZ", "SG"] def build(env: DynamicRealtimeEnvironment) -> None: """Starts the customers, the orders and the reports on `env`.""" sampler = Sampler(seed=42) country = sampler.generator("tasks.customer.payload.country") pick = sampler.generator("tasks.order.payload.customer_id") total = sampler.generator("tasks.order.payload.total") customer_gap = DistributionConfig(dist="exponential", rate=0.1) # The random sequence the blueprint's draw uses customer_gap.stream = "arrival.customers" order_gap = DistributionConfig(dist="exponential", rate=1) order_gap.stream = "arrival.orders" report_gap = DistributionConfig(dist="constant", value=10) report_gap.stream = "arrival.reports" customer_rows: list = [] # the customers written so far, for the lookup order_rows: list = [] # the orders written so far, for the aggregate sent = {"customer": 0, "report": 0} def write_customer(key): """Publishes the next customer and keeps its row.""" row = { "customer_id": len(customer_rows) + 1, "country": COUNTRIES[int(country.integers(len(COUNTRIES)))], } customer_rows.append(row) env.publish_event(key, row, task="customer", instance=sent["customer"]) sent["customer"] += 1 def customers(): for number in itertools.count(6): # 1 to 5 exist at the start yield env.timeout(sampler.sample(customer_gap)) write_customer(f"customers-{number}") def orders(): for number in itertools.count(1): yield env.timeout(sampler.sample(order_gap)) key, instance = f"orders-{number}", number - 1 # The lookup: one row of the customers written so far, chosen at random customer = customer_rows[int(pick.integers(len(customer_rows)))] order = { "order_id": number, "customer_id": customer["customer_id"], "total": round(float(total.uniform(5, 200)), 2), } order_rows.append(order) env.publish_event(key, order, task="order", instance=instance) # The upstream: the payment reads the order it follows payment = {"order_id": order["order_id"], "amount": order["total"]} env.publish_event(key, payment, task="payment", instance=instance) def reports(): while True: yield env.timeout(sampler.sample(report_gap)) # The aggregate: the last 10 orders, newest first, as the blueprint does recent = [row["total"] for row in reversed(order_rows[-10:])] report = { "mean_total": sum(recent) / len(recent), "largest_total": max(recent), } env.publish_event( f"reports-{sent['report'] + 1}", report, task="report", instance=sent["report"], ) sent["report"] += 1 def first(number): yield env.timeout(0) write_customer(f"customers-{number}") env.process(customers()) env.process(orders()) env.process(reports()) for number in range(1, 6): env.process(first(number)) def run() -> None: """Runs the model unpaced into the console.""" env = DynamicRealtimeEnvironment(factor=0, **ENVIRONMENT) env.setup_egress([ConsoleEgress()]) build(env) try: env.run(until=UNTIL) finally: env.teardown() if __name__ == "__main__": logging.basicConfig(level=logging.INFO, format="%(levelname)s %(message)s") run() ``` # Join Across Sinks Write the ids of one kind of record to one sink and use them in another: customers go to one JSON Lines file, and the orders that name those customers go to a second file, so the two files join on `customer_id`. ______________________________________________________________________ ## Before You Start - The commands run from the root of a clone of the repository, where the files are in `docs/snippets/generate-data/`. The Full Files block of this page holds the same files, for a reader who saves them by hand. ```bash git clone https://github.com/jaehyeon-kim/desflow.git cd desflow ``` - [First Simulation](https://jaehyeon.me/desflow/latest/learn/first-model/first-simulation/index.md) explains arrivals, tasks and the records a run writes. - Install the file writers: `pip install "desflow[parquet]"`. - [Send Data to a Sink](https://jaehyeon.me/desflow/latest/how-to/generate-data/send-data-to-a-sink/index.md) shows the sinks, and [Look Up Other Records](https://jaehyeon.me/desflow/latest/how-to/generate-data/look-up-other-records/index.md) shows `lookup`. ______________________________________________________________________ ## Steps ### Write Customers and Orders Five customers are written at the start and another about every 10 seconds. An order arrives about once a second, and [`lookup`](https://jaehyeon.me/desflow/latest/generators/related-records/lookup/index.md) gives it the `customer_id` of a customer already written. ```yaml arrivals: customers: {initial: 5, dist: exponential, rate: 0.1, spawn: customer} orders: {dist: exponential, rate: 1, spawn: order} ``` ```yaml tasks: customer: payload: customer_id: {gen: sequence, start: 1} country: {gen: one_of, choices: [AU, NZ, SG]} order: payload: order_id: {gen: sequence, start: 1} customer_id: {gen: lookup, task: customer, path: customer_id} total: {gen: uniform, low: 5, high: 200, decimals: 2} ``` ```python app.add_arrival("customers", "exponential", rate=0.1, spawn="customer", initial=5) app.add_arrival("orders", "exponential", rate=1, spawn="order") ``` ```python customer_payload = Template( { "customer_id": {"gen": "sequence", "start": 1}, "country": {"gen": "one_of", "choices": ["AU", "NZ", "SG"]}, }, name="tasks.customer", ) order_payload = Template( { "order_id": {"gen": "sequence", "start": 1}, "customer_id": {"gen": "lookup", "task": "customer", "path": "customer_id"}, "total": {"gen": "uniform", "low": 5, "high": 200, "decimals": 2}, }, name="tasks.order", ) # A task that something looks up keeps its rows. `history` is the blueprint's # default, and a builder task needs it because a `Template` payload is not searched # for lookups. @app.task(name="customer", history=1_000_000) def customer(task_id): """Gives one customer record.""" return customer_payload @app.task(name="order") def order(task_id): """Gives one order record.""" return order_payload ``` A task that something looks up keeps its rows, and `history=` says how many. A Builder task needs it, because a `Template` payload is not searched for lookups. A blueprint keeps 1,000,000 rows by default. ```python sampler = Sampler(seed=42) country = sampler.generator("tasks.customer.payload.country") pick = sampler.generator("tasks.order.payload.customer_id") total = sampler.generator("tasks.order.payload.total") customer_gap = DistributionConfig(dist="exponential", rate=0.1) # The random sequence the blueprint's draw uses customer_gap.stream = "arrival.customers" order_gap = DistributionConfig(dist="exponential", rate=1) order_gap.stream = "arrival.orders" customer_rows: list = [] # the customers written so far, for a lookup sent = {"customer": 0, "order": 0} ``` `Sampler(seed=42)` supplies every draw: a random generator for each payload field and for the gap. The `stream` line names the random sequence the blueprint uses for this arrival, so the three forms draw the same gaps. ```python def write_customer(key): """Publishes the next customer and keeps its row.""" row = { "customer_id": len(customer_rows) + 1, "country": COUNTRIES[int(country.integers(len(COUNTRIES)))], } customer_rows.append(row) env.publish_event(key, row, task="customer", instance=sent["customer"]) sent["customer"] += 1 def customers(): for number in itertools.count(6): # 1 to 5 exist at the start yield env.timeout(sampler.sample(customer_gap)) write_customer(f"customers-{number}") def orders(): for number in itertools.count(1): yield env.timeout(sampler.sample(order_gap)) # The lookup: one row of the customers written so far, chosen at random customer = customer_rows[int(pick.integers(len(customer_rows)))] payload = { "order_id": number, "customer_id": customer["customer_id"], "total": round(float(total.uniform(5, 200)), 2), } env.publish_event( f"orders-{number}", payload, task="order", instance=sent["order"] ) sent["order"] += 1 def first(number): yield env.timeout(0) write_customer(f"customers-{number}") env.process(customers()) env.process(orders()) for number in range(1, 6): env.process(first(number)) ``` A Low-level script keeps the customers in a list and picks one at random for each order. ### Send Each Kind to Its File A `when` on each sink lets through the records of one task. The first file takes the records of the task `customer` and the second the records of the task `order`. ```yaml egress: - type: Jsonl when: {expr: "record.task == 'customer'"} config: default_path: ${DEST_PATH:-data}/customers.jsonl - type: Jsonl when: {expr: "record.task == 'order'"} config: default_path: ${DEST_PATH:-data}/orders.jsonl ``` ```python app.add_egress( JsonlStorageEgress(default_path=f"{folder}/customers.jsonl"), when=lambda record: record.get("task") == "customer", ) app.add_egress( JsonlStorageEgress(default_path=f"{folder}/orders.jsonl"), when=lambda record: record.get("task") == "order", ) ``` ```python env.setup_egress( [ JsonlStorageEgress(default_path=f"{folder}/customers.jsonl"), JsonlStorageEgress(default_path=f"{folder}/orders.jsonl"), ], predicates=[ lambda record: record.get("task") == "customer", lambda record: record.get("task") == "order", ], ) ``` `env.setup_egress` takes one predicate for each sink. ______________________________________________________________________ ## Check the Result Run the model for 60 simulated seconds into a folder of your own, and list the files: ```bash DEST_PATH=out desflow run docs/snippets/generate-data/join_across_sinks.yaml ls out ``` ```bash DEST_PATH=out python docs/snippets/generate-data/join_across_sinks_builder.py ls out ``` ```bash DEST_PATH=out python docs/snippets/generate-data/join_across_sinks_low_level.py ls out ``` `out` holds files named `customers_<8 hex digits>.jsonl` and `orders_<8 hex digits>.jsonl`, one flat row for each record. To see the records without writing files, print the first 8 of them: ```bash desflow run docs/snippets/generate-data/join_across_sinks.yaml --sample 8 ``` The block keeps the first customer and the first two orders. Each order names a customer written by then. ```text {"stream_type":"event","sim_ts":0.0,"timestamp":"...","key":"customers-1","task":"customer","instance":0,"value":{"customer_id":1,"country":"NZ"}} {"stream_type":"event","sim_ts":0.3141556656469718,"timestamp":"...","key":"orders-1","task":"order","instance":0,"value":{"order_id":1,"customer_id":5,"total":161.55}} {"stream_type":"event","sim_ts":2.4671694506095694,"timestamp":"...","key":"orders-2","task":"order","instance":1,"value":{"order_id":2,"customer_id":4,"total":177.63}} ``` The docs test runs all three forms into real files in a temporary folder. Each file holds the records of one task, every order in the orders file names a customer in the customers file, and the three forms write the same files. ______________________________________________________________________ ## Full Files Full files ```yaml # Join across sinks: customers go to one file, and the orders that name them to another. # # Customers are written to customers.jsonl. Each order takes its customer id from a # customer already written, with `lookup`, and goes to orders.jsonl. A `when` on each # sink sends it the records of one task, so the two files join on customer_id. # # Needs: the parquet extra, which holds the file writers. DEST_PATH sets the folder # (data by default). # Run it with: desflow run docs/snippets/generate-data/join_across_sinks.yaml simulation: sim_id: Shop factor: 0 random_seed: 42 logical_start_time: 2026-01-01T00:00:00 egress: - type: Jsonl when: {expr: "record.task == 'customer'"} config: default_path: ${DEST_PATH:-data}/customers.jsonl - type: Jsonl when: {expr: "record.task == 'order'"} config: default_path: ${DEST_PATH:-data}/orders.jsonl arrivals: customers: {initial: 5, dist: exponential, rate: 0.1, spawn: customer} orders: {dist: exponential, rate: 1, spawn: order} tasks: customer: payload: customer_id: {gen: sequence, start: 1} country: {gen: one_of, choices: [AU, NZ, SG]} order: payload: order_id: {gen: sequence, start: 1} customer_id: {gen: lookup, task: customer, path: customer_id} total: {gen: uniform, low: 5, high: 200, decimals: 2} run: {until: 60} ``` ```python """Join across sinks: customers to one file, and the orders that name them to another. The builder version of `join_across_sinks.yaml`: 5 customers at the start and one more about every 10 seconds, and an order about every second whose `lookup` takes the customer id from a customer already written. Each sink takes the records of one task, with `when`. Needs: the parquet extra, which holds the file writers. DEST_PATH sets the folder (data by default). Run it with: python docs/snippets/generate-data/join_across_sinks_builder.py """ import logging import os from datetime import datetime, timezone from desflow import JsonlStorageEgress, SimulationContext from desflow.values import Template UNTIL = 60 def build() -> SimulationContext: """Builds the shop, with a file for each kind of record.""" folder = os.environ.get("DEST_PATH", "data") app = SimulationContext( sim_id="Shop", factor=0, random_seed=42, logical_start_time=datetime(2026, 1, 1, tzinfo=timezone.utc), ) app.add_egress( JsonlStorageEgress(default_path=f"{folder}/customers.jsonl"), when=lambda record: record.get("task") == "customer", ) app.add_egress( JsonlStorageEgress(default_path=f"{folder}/orders.jsonl"), when=lambda record: record.get("task") == "order", ) app.add_arrival("customers", "exponential", rate=0.1, spawn="customer", initial=5) app.add_arrival("orders", "exponential", rate=1, spawn="order") customer_payload = Template( { "customer_id": {"gen": "sequence", "start": 1}, "country": {"gen": "one_of", "choices": ["AU", "NZ", "SG"]}, }, name="tasks.customer", ) order_payload = Template( { "order_id": {"gen": "sequence", "start": 1}, "customer_id": {"gen": "lookup", "task": "customer", "path": "customer_id"}, "total": {"gen": "uniform", "low": 5, "high": 200, "decimals": 2}, }, name="tasks.order", ) # A task that something looks up keeps its rows. `history` is the blueprint's # default, and a builder task needs it because a `Template` payload is not searched # for lookups. @app.task(name="customer", history=1_000_000) def customer(task_id): """Gives one customer record.""" return customer_payload @app.task(name="order") def order(task_id): """Gives one order record.""" return order_payload return app if __name__ == "__main__": logging.basicConfig(level=logging.INFO, format="%(levelname)s %(message)s") build().run(until=UNTIL) ``` ```python """Join across sinks: customers to one file, and the orders that name them to another. The low-level version of `join_across_sinks.yaml`: plain SimPy on a `DynamicRealtimeEnvironment`, which publishes each record with `publish_event`. Each draw is made with `Sampler`, from the random sequence the blueprint's generator at that place uses, so the draws are the blueprint's. The script keeps each customer row in a list, so that an order's lookup is one draw of a row of that list, and each sink takes the records of one task through a predicate. Needs: the parquet extra, which holds the file writers. DEST_PATH sets the folder (data by default). Run it with: python docs/snippets/generate-data/join_across_sinks_low_level.py """ import itertools import logging import os from datetime import datetime, timezone from desflow import ( DistributionConfig, DynamicRealtimeEnvironment, JsonlStorageEgress, Sampler, ) UNTIL = 60 START = datetime(2026, 1, 1, tzinfo=timezone.utc) ENVIRONMENT: dict = {"logical_start_time": START, "timezone": "UTC"} COUNTRIES = ["AU", "NZ", "SG"] def build(env: DynamicRealtimeEnvironment) -> None: """Starts the customers and the orders on `env`.""" sampler = Sampler(seed=42) country = sampler.generator("tasks.customer.payload.country") pick = sampler.generator("tasks.order.payload.customer_id") total = sampler.generator("tasks.order.payload.total") customer_gap = DistributionConfig(dist="exponential", rate=0.1) # The random sequence the blueprint's draw uses customer_gap.stream = "arrival.customers" order_gap = DistributionConfig(dist="exponential", rate=1) order_gap.stream = "arrival.orders" customer_rows: list = [] # the customers written so far, for a lookup sent = {"customer": 0, "order": 0} def write_customer(key): """Publishes the next customer and keeps its row.""" row = { "customer_id": len(customer_rows) + 1, "country": COUNTRIES[int(country.integers(len(COUNTRIES)))], } customer_rows.append(row) env.publish_event(key, row, task="customer", instance=sent["customer"]) sent["customer"] += 1 def customers(): for number in itertools.count(6): # 1 to 5 exist at the start yield env.timeout(sampler.sample(customer_gap)) write_customer(f"customers-{number}") def orders(): for number in itertools.count(1): yield env.timeout(sampler.sample(order_gap)) # The lookup: one row of the customers written so far, chosen at random customer = customer_rows[int(pick.integers(len(customer_rows)))] payload = { "order_id": number, "customer_id": customer["customer_id"], "total": round(float(total.uniform(5, 200)), 2), } env.publish_event( f"orders-{number}", payload, task="order", instance=sent["order"] ) sent["order"] += 1 def first(number): yield env.timeout(0) write_customer(f"customers-{number}") env.process(customers()) env.process(orders()) for number in range(1, 6): env.process(first(number)) def run() -> None: """Runs the model unpaced, with a file for each kind of record.""" env = DynamicRealtimeEnvironment(factor=0, **ENVIRONMENT) folder = os.environ.get("DEST_PATH", "data") env.setup_egress( [ JsonlStorageEgress(default_path=f"{folder}/customers.jsonl"), JsonlStorageEgress(default_path=f"{folder}/orders.jsonl"), ], predicates=[ lambda record: record.get("task") == "customer", lambda record: record.get("task") == "order", ], ) build(env) try: env.run(until=UNTIL) finally: env.teardown() if __name__ == "__main__": logging.basicConfig(level=logging.INFO, format="%(levelname)s %(message)s") run() ``` # Change the Schema During a Run Add, rename and retype a field at known times, and write a label record for each change: an order gains a `currency` field at 60 seconds, `total` becomes `amount` at 120 seconds, and the amount becomes text at 180 seconds. ______________________________________________________________________ ## Before You Start - The commands run from the root of a clone of the repository, where the files are in `docs/snippets/generate-data/`. The Full Files block of this page holds the same files, for a reader who saves them by hand. ```bash git clone https://github.com/jaehyeon-kim/desflow.git cd desflow ``` - [First Simulation](https://jaehyeon.me/desflow/latest/learn/first-model/first-simulation/index.md) explains arrivals, tasks and the records a run writes. - [Live Parameters](https://jaehyeon.me/desflow/latest/user-guide/live-runs-and-connectors/live-parameters/index.md) explains scenario steps and label records. ______________________________________________________________________ ## Steps ### Describe the Arrival An order arrives every 10 seconds. ```yaml arrivals: orders: {dist: constant, value: 10, spawn: order} ``` ```python app.add_arrival("orders", "constant", value=10, spawn="order") ``` ```python sampler = Sampler(seed=42) value = sampler.generator("tasks.order.vars.value") gap = DistributionConfig(dist="constant", value=10) # The random sequence the blueprint's draw uses gap.stream = "arrival.orders" ``` `Sampler(seed=42)` supplies every draw: a random generator for each payload field and for the gap. The `stream` line names the random sequence the blueprint uses for this arrival, so the three forms draw the same gaps. ### Change the Fields at Set Times `omit_when` leaves a field out of a record while its condition is true, and `t` is the simulation time. `currency` is left out before 60 seconds. `total` is left out from 120 seconds, when `amount` replaces it, and `amount` is left out before then. From 180 seconds [`when`](https://jaehyeon.me/desflow/latest/generators/conditions/when/index.md) writes the amount as text with [`format`](https://jaehyeon.me/desflow/latest/generators/text-and-ids/format/index.md). A `vars` entry draws the value once for each order, so `total` and `amount` hold the same number. ```yaml tasks: order: vars: value: {gen: uniform, low: 5, high: 200, decimals: 2} payload: order_id: {gen: sequence, start: 1} currency: {gen: literal, value: EUR, omit_when: "t < 60"} total: {gen: var, name: value, omit_when: "t >= 120"} amount: gen: when condition: "t >= 180" then: {gen: format, template: "{value}"} else: {gen: var, name: value} omit_when: "t < 120" ``` ```python order_payload = Template( { "order_id": {"gen": "sequence", "start": 1}, "currency": {"gen": "literal", "value": "EUR", "omit_when": "t < 60"}, "total": {"gen": "var", "name": "value", "omit_when": "t >= 120"}, "amount": { "gen": "when", "condition": "t >= 180", "then": {"gen": "format", "template": "{value}"}, "else": {"gen": "var", "name": "value"}, "omit_when": "t < 120", }, }, name="tasks.order", vars={"value": {"gen": "uniform", "low": 5, "high": 200, "decimals": 2}}, ) @app.task(name="order") def order(task_id): """Gives one order record.""" return order_payload ``` ```python def order(number): """The payload of one order, as it is at the time `t` it is written.""" t = env.now total = round(float(value.uniform(5, 200)), 2) payload = {"order_id": number} if t >= 60: payload["currency"] = "EUR" if t < 120: payload["total"] = total else: payload["amount"] = f"{total}" if t >= 180 else total return payload def source(): for number in itertools.count(1): yield env.timeout(sampler.sample(gap)) env.publish_event( f"orders-{number}", order(number), task="order", instance=number - 1, ) def changes(): for at, record in CHANGES: yield env.timeout(at - env.now) env.publish_label(record) env.process(source()) env.process(changes()) ``` ### Label Each Change A step of the `scenario` with a `record` writes a label record at its time. The second egress has `when: labels`, so it receives only the labels, and the first receives only the orders. The labels say what changed and when without mixing into the data. ```yaml scenario: - at: 60 record: {change: field_added, field: currency} - at: 120 record: {change: field_renamed, field: total, to: amount} - at: 180 record: {change: field_retyped, field: amount, to: text} ``` ```yaml egress: - {type: Console} - {type: Console, when: labels} ``` ```python app.add_scenario( [ {"at": 60, "record": {"change": "field_added", "field": "currency"}}, { "at": 120, "record": { "change": "field_renamed", "field": "total", "to": "amount", }, }, { "at": 180, "record": { "change": "field_retyped", "field": "amount", "to": "text", }, }, ] ) ``` ```python app.add_egress(ConsoleEgress()) app.add_egress(ConsoleEgress(), when="labels") ``` ```python CHANGES = [ # (time in seconds, the label record) (60, {"change": "field_added", "field": "currency"}), (120, {"change": "field_renamed", "field": "total", "to": "amount"}), (180, {"change": "field_retyped", "field": "amount", "to": "text"}), ] ``` ```python env.setup_egress([ConsoleEgress(), ConsoleEgress()], labels=[False, True]) ``` The Low-level file publishes each label with `env.publish_label` from a process of its own, and `labels=[False, True]` sends the second sink only the labels. ______________________________________________________________________ ## Check the Result Run the model for 240 simulated seconds and print its first 19 orders. The block keeps an order on each side of each change, and the three labels. ```bash desflow run docs/snippets/generate-data/change_the_schema_during_a_run.yaml --sample 19 ``` ```bash python docs/snippets/generate-data/change_the_schema_during_a_run_builder.py ``` This prints every record of the run as an `[EVT]` line with the same fields and values. ```bash python docs/snippets/generate-data/change_the_schema_during_a_run_low_level.py ``` This prints every record of the run as an `[EVT]` line with the same fields and values. ```text {"stream_type":"event","sim_ts":50.0,"timestamp":"...","key":"orders-5","task":"order","instance":4,"value":{"order_id":5,"total":11.08}} {"stream_type":"event","sim_ts":60.0,"timestamp":"...","key":"orders-6","task":"order","instance":5,"value":{"order_id":6,"currency":"EUR","total":48.48}} {"stream_type":"event","sim_ts":110.0,"timestamp":"...","key":"orders-11","task":"order","instance":10,"value":{"order_id":11,"currency":"EUR","total":26.51}} {"stream_type":"event","sim_ts":120.0,"timestamp":"...","key":"orders-12","task":"order","instance":11,"value":{"order_id":12,"currency":"EUR","amount":92.49}} {"stream_type":"event","sim_ts":170.0,"timestamp":"...","key":"orders-17","task":"order","instance":16,"value":{"order_id":17,"currency":"EUR","amount":197.02}} {"stream_type":"event","sim_ts":180.0,"timestamp":"...","key":"orders-18","task":"order","instance":17,"value":{"order_id":18,"currency":"EUR","amount":"68.52"}} {"stream_type":"label","sim_ts":60.0,"timestamp":"...","path":null,"old":null,"new":null,"label":{"change":"field_added","field":"currency"}} {"stream_type":"label","sim_ts":120.0,"timestamp":"...","path":null,"old":null,"new":null,"label":{"change":"field_renamed","field":"total","to":"amount"}} {"stream_type":"label","sim_ts":180.0,"timestamp":"...","path":null,"old":null,"new":null,"label":{"change":"field_retyped","field":"amount","to":"text"}} ``` Order 6, at 60 seconds, is the first with `currency`. Order 12, at 120 seconds, is the first with `amount` in place of `total`. Order 18, at 180 seconds, is the first with an amount that is text. Each label carries the `sim_ts` of its change. The docs test checks all three changes and that the labels reach only the labels sink. ______________________________________________________________________ ## Full Files Full files ```yaml # Change the schema during a run: a field is added, renamed and retyped at known times. # # An order arrives every 10 seconds. From 60 s the record has a `currency` field. From # 120 s `total` is written as `amount`, and from 180 s the amount is text, not a number. # A step of the scenario at each change writes a label record, which only the second # egress receives, so the labels say what changed and when without mixing into the data. # # Needs: nothing. # Run it with: desflow run # docs/snippets/generate-data/change_the_schema_during_a_run.yaml simulation: sim_id: Shop factor: 0 random_seed: 42 logical_start_time: 2026-01-01T00:00:00 egress: - {type: Console} - {type: Console, when: labels} arrivals: orders: {dist: constant, value: 10, spawn: order} tasks: order: vars: value: {gen: uniform, low: 5, high: 200, decimals: 2} payload: order_id: {gen: sequence, start: 1} currency: {gen: literal, value: EUR, omit_when: "t < 60"} total: {gen: var, name: value, omit_when: "t >= 120"} amount: gen: when condition: "t >= 180" then: {gen: format, template: "{value}"} else: {gen: var, name: value} omit_when: "t < 120" scenario: - at: 60 record: {change: field_added, field: currency} - at: 120 record: {change: field_renamed, field: total, to: amount} - at: 180 record: {change: field_retyped, field: amount, to: text} run: {until: 240} ``` ```python """Change the schema during a run, builder API. The builder version of `change_the_schema_during_a_run.yaml`: an order every 10 seconds for 4 minutes. A field is added at 60 s, renamed at 120 s and retyped at 180 s, and a scenario step at each change writes a label record to the labels sink. Needs: nothing. Run it with: python docs/snippets/generate-data/change_the_schema_during_a_run_builder.py """ import logging from datetime import datetime, timezone from desflow import ConsoleEgress, SimulationContext from desflow.values import Template UNTIL = 240 def build() -> SimulationContext: """Builds the shop.""" app = SimulationContext( sim_id="Shop", factor=0, random_seed=42, logical_start_time=datetime(2026, 1, 1, tzinfo=timezone.utc), ) app.add_egress(ConsoleEgress()) app.add_egress(ConsoleEgress(), when="labels") app.add_arrival("orders", "constant", value=10, spawn="order") app.add_scenario( [ {"at": 60, "record": {"change": "field_added", "field": "currency"}}, { "at": 120, "record": { "change": "field_renamed", "field": "total", "to": "amount", }, }, { "at": 180, "record": { "change": "field_retyped", "field": "amount", "to": "text", }, }, ] ) order_payload = Template( { "order_id": {"gen": "sequence", "start": 1}, "currency": {"gen": "literal", "value": "EUR", "omit_when": "t < 60"}, "total": {"gen": "var", "name": "value", "omit_when": "t >= 120"}, "amount": { "gen": "when", "condition": "t >= 180", "then": {"gen": "format", "template": "{value}"}, "else": {"gen": "var", "name": "value"}, "omit_when": "t < 120", }, }, name="tasks.order", vars={"value": {"gen": "uniform", "low": 5, "high": 200, "decimals": 2}}, ) @app.task(name="order") def order(task_id): """Gives one order record.""" return order_payload return app if __name__ == "__main__": logging.basicConfig(level=logging.INFO, format="%(levelname)s %(message)s") build().run(until=UNTIL) ``` ```python """Change the schema during a run, low-level API. The low-level version of `change_the_schema_during_a_run.yaml`: plain SimPy on a `DynamicRealtimeEnvironment`. A process publishes each label record with `publish_label` at the time of its change. The order is a dictionary. It gains `currency` from 60 s and writes `total` as `amount` from 120 s, and from 180 s the amount is text, as the blueprint's `omit_when` and `when` on `t` do. The value is drawn with `Sampler`, from the random sequence the blueprint's generator at that place uses. Needs: nothing. Run it with: python docs/snippets/generate-data/change_the_schema_during_a_run_low_level.py """ import itertools import logging from datetime import datetime, timezone from desflow import ( ConsoleEgress, DistributionConfig, DynamicRealtimeEnvironment, Sampler, ) UNTIL = 240 START = datetime(2026, 1, 1, tzinfo=timezone.utc) ENVIRONMENT: dict = {"logical_start_time": START, "timezone": "UTC"} CHANGES = [ # (time in seconds, the label record) (60, {"change": "field_added", "field": "currency"}), (120, {"change": "field_renamed", "field": "total", "to": "amount"}), (180, {"change": "field_retyped", "field": "amount", "to": "text"}), ] def build(env: DynamicRealtimeEnvironment) -> None: """Starts the orders and the changes on `env`.""" sampler = Sampler(seed=42) value = sampler.generator("tasks.order.vars.value") gap = DistributionConfig(dist="constant", value=10) # The random sequence the blueprint's draw uses gap.stream = "arrival.orders" def order(number): """The payload of one order, as it is at the time `t` it is written.""" t = env.now total = round(float(value.uniform(5, 200)), 2) payload = {"order_id": number} if t >= 60: payload["currency"] = "EUR" if t < 120: payload["total"] = total else: payload["amount"] = f"{total}" if t >= 180 else total return payload def source(): for number in itertools.count(1): yield env.timeout(sampler.sample(gap)) env.publish_event( f"orders-{number}", order(number), task="order", instance=number - 1, ) def changes(): for at, record in CHANGES: yield env.timeout(at - env.now) env.publish_label(record) env.process(source()) env.process(changes()) def run() -> None: """Runs the model unpaced: the orders to one sink, the labels to another.""" env = DynamicRealtimeEnvironment(factor=0, **ENVIRONMENT) env.setup_egress([ConsoleEgress(), ConsoleEgress()], labels=[False, True]) build(env) try: env.run(until=UNTIL) finally: env.teardown() if __name__ == "__main__": logging.basicConfig(level=logging.INFO, format="%(levelname)s %(message)s") run() ``` # Route Records to Topics Send each record of a simulation to the Kafka topic that suits it: failed orders to an alarm topic, telemetry to its own topic and every other event to the event topic. ______________________________________________________________________ ## Before You Start - [Egress](https://jaehyeon.me/desflow/latest/user-guide/live-runs-and-connectors/egress/#kafka) explains `KafkaEgress` and its two default topics. - Install the Kafka connectors: `pip install "desflow[kafka]"`. - The scripts publish to Kafka, so start a broker with `odctl up kafka-lite`. [Installation](https://jaehyeon.me/desflow/latest/installation/index.md) shows the one-time odctl install. Tear it down afterwards with `odctl down kafka-lite --volumes`. ______________________________________________________________________ ## Steps ### Name the Topic in the Payload A payload key `__topic__` names the topic of a record. The sink sends the record to that topic and removes the key from the message. An event without the key goes to the event topic, and telemetry always goes to the telemetry topic. This shop packs an order about every 2 seconds, and every tenth order fails. A failed order names `system-alarms`, and a packed order names `shop-events`: ```yaml resources: packers: {current_cap: 1, max_cap: 1} services: packing: {dist: constant, value: 1.5 s} arrivals: orders: {dist: exponential, rate: 0.5, spawn: pack_order} tasks: pack_order: service: packing resource: packers vars: failed: {gen: expr, expr: "process.instance % 10 == 9"} # every tenth order payload: status: {gen: when, condition: failed, then: packing_failed, else: packed} __topic__: {gen: when, condition: failed, then: system-alarms, else: shop-events} stats: {level: minimal, interval: 10} # readings for shop-telemetry ``` ```python app = SimulationContext(sim_id="Shop", factor=0, random_seed=42) app.add_egress(egress) app.add_resource("packers", current_cap=1, max_cap=1) app.add_arrival("orders", "exponential", rate=0.5, spawn="pack_order") app.add_service("packing", "constant", value=1.5) app.with_stats("minimal", interval=10) # readings for shop-telemetry payload = Template( { "status": { "gen": "when", "condition": "failed", "then": "packing_failed", "else": "packed", }, "__topic__": { "gen": "when", "condition": "failed", "then": "system-alarms", "else": "shop-events", }, }, name="tasks.pack_order", vars={"failed": {"gen": "expr", "expr": "process.instance % 10 == 9"}}, ) @app.task(name="pack_order", service_id="packing", resource_id="packers") def pack_order(task_id): """Gives one order record.""" return payload ``` ```python def pack_order(env, packers, sampler, key, task_id): path_id = "Shop.service.packing" stats = env.stats queued = {"path_id": path_id, "sim_id": "Shop", "service": "packing"} env.publish_event(key, {**queued, "status": "queued"}, "pack_order", task_id) stats.task_queued("pack_order", task_id) with packers.request() as unit: yield unit env.publish_event(key, {**queued, "status": "started"}, "pack_order", task_id) stats.task_started("pack_order", task_id) yield env.timeout(sampler.sample(env.registry.get_config(path_id))) failed = task_id % 10 == 9 # every tenth order payload = { "status": "packing_failed" if failed else "packed", "__topic__": "system-alarms" if failed else "shop-events", } env.publish_event(key, payload, "pack_order", task_id) stats.task_finished("pack_order", task_id) def orders(env, packers, sampler): gap = env.registry.get_config("Shop.arrival.orders") for number in itertools.count(1): yield env.timeout(sampler.sample(gap)) env.process(pack_order(env, packers, sampler, f"orders-{number}", number - 1)) ``` The `queued` and `started` records of an order name no topic, so they go to the event topic. ### Create the Topics The sink creates the event and telemetry topics when the run starts. A topic that only a payload names is unknown to the sink, so list it in `topics`. `topic_policy` says what the sink does with its topics: `create`, the default, makes a missing topic and leaves an existing one, `drop_and_create` deletes each topic and creates it again at the start of a run, and `manual` creates nothing. ```yaml egress: - type: Kafka config: bootstrap_servers: ${KAFKA_BOOTSTRAP_SERVERS:-127.0.0.1:9092} event_topic: shop-events telemetry_topic: shop-telemetry topic_policy: create topics: system-alarms: {} ``` ```python def payload_egress() -> KafkaEgress: """Sends each record to the topic its payload names, and creates the topics.""" return KafkaEgress( bootstrap_servers=BOOTSTRAP, event_topic="shop-events", telemetry_topic="shop-telemetry", topic_policy="create", topics={"system-alarms": {}}, ) ``` ```python def payload_egress() -> KafkaEgress: """Sends each record to the topic its payload names, and creates the topics.""" return KafkaEgress( bootstrap_servers=BOOTSTRAP, event_topic="shop-events", telemetry_topic="shop-telemetry", topic_policy="create", topics={"system-alarms": {}}, ) ``` ### Pick the Topic With a Function Use a function when the topic depends on more than a payload can say. A `topic_router` receives one record, as a dictionary with its `stream_type`, `key` or `path_id`, `task`, `instance` and `value`, and returns the topic name. It sees telemetry too, so it must always return a topic. It wins over `__topic__`, and the sink then creates only the topics in `topics`. To drop records, give the sink a `when` on its entry: it filters them before the router sees them. [Egress](https://jaehyeon.me/desflow/latest/user-guide/live-runs-and-connectors/egress/#choose-what-each-sink-gets) shows the forms of `when`. This router sends the shop's records to the same three topics. Every form uses it unchanged, from `complex_routing_logic.py`: ```python def custom_kafka_router(data: Dict[str, Any]) -> str: """Picks a topic for each record by its kind and its value.""" if data.get("stream_type") == "telemetry": return "shop-telemetry" value = data.get("value") if isinstance(value, dict) and ( value.get("status") == "packing_failed" or value.get("level") == "ERROR" ): return "system-alarms" # Every other event, including a payload that is not a dict. return "shop-events" ``` Then pass it to the sink: ```yaml egress: - type: Kafka config: bootstrap_servers: ${KAFKA_BOOTSTRAP_SERVERS:-127.0.0.1:9092} topic_router: !python complex_routing_logic.custom_kafka_router topics: # with a router, name the topics it uses shop-events: {} shop-telemetry: {} system-alarms: {} ``` ```python def router_egress() -> KafkaEgress: """Sends each record to the topic a function picks.""" return KafkaEgress( bootstrap_servers=BOOTSTRAP, topic_router=custom_kafka_router, topics={"shop-events": {}, "shop-telemetry": {}, "system-alarms": {}}, ) ``` ```python def router_egress() -> KafkaEgress: """Sends each record to the topic a function picks.""" return KafkaEgress( bootstrap_servers=BOOTSTRAP, topic_router=custom_kafka_router, topics={"shop-events": {}, "shop-telemetry": {}, "system-alarms": {}}, ) ``` Run the shop with the topic in the payload as `desflow run complex_routing.yaml`, `python complex_routing.py` or `python complex_routing_low_level.py`. Run it with the function as `desflow run complex_routing_router.yaml`, or set `ROUTING=router` in front of `python complex_routing.py` or `python complex_routing_low_level.py`. Each runs for one simulated minute and ends at once. ______________________________________________________________________ ## Check the Result While `kafka-lite` is up, the Kafka UI at http://127.0.0.1:8086 lists the topics `shop-events`, `shop-telemetry` and `system-alarms`. In one simulated minute `system-alarms` receives two messages, for `orders-10` and `orders-20`, the instances 9 and 19 of `pack_order`, and each has the value `{"status": "packing_failed"}`. No message holds `__topic__`. The three forms use seed 42, so they send the same messages, and the router sends each message to the same topic as the payload form. ______________________________________________________________________ ## Full Files Full files ```yaml # The Route Records to Topics guide: a shop whose failed orders go to their own Kafka # topic. Needs a broker on 127.0.0.1:9092 (odctl up kafka-lite). Run it with # desflow run complex_routing.yaml simulation: {sim_id: Shop, factor: 0, random_seed: 42} egress: - type: Kafka config: bootstrap_servers: ${KAFKA_BOOTSTRAP_SERVERS:-127.0.0.1:9092} event_topic: shop-events telemetry_topic: shop-telemetry topic_policy: create topics: system-alarms: {} resources: packers: {current_cap: 1, max_cap: 1} services: packing: {dist: constant, value: 1.5 s} arrivals: orders: {dist: exponential, rate: 0.5, spawn: pack_order} tasks: pack_order: service: packing resource: packers vars: failed: {gen: expr, expr: "process.instance % 10 == 9"} # every tenth order payload: status: {gen: when, condition: failed, then: packing_failed, else: packed} __topic__: {gen: when, condition: failed, then: system-alarms, else: shop-events} stats: {level: minimal, interval: 10} # readings for shop-telemetry run: {until: 1 min} ``` ```yaml # The Route Records to Topics guide: the same shop, with a function that picks the # topic. Needs a broker on 127.0.0.1:9092 (odctl up kafka-lite). Run it with # desflow run complex_routing_router.yaml, beside complex_routing_logic.py simulation: {sim_id: Shop, factor: 0, random_seed: 42} egress: - type: Kafka config: bootstrap_servers: ${KAFKA_BOOTSTRAP_SERVERS:-127.0.0.1:9092} topic_router: !python complex_routing_logic.custom_kafka_router topics: # with a router, name the topics it uses shop-events: {} shop-telemetry: {} system-alarms: {} resources: packers: {current_cap: 1, max_cap: 1} services: packing: {dist: constant, value: 1.5 s} arrivals: orders: {dist: exponential, rate: 0.5, spawn: pack_order} tasks: pack_order: service: packing resource: packers vars: failed: {gen: expr, expr: "process.instance % 10 == 9"} # every tenth order payload: status: {gen: when, condition: failed, then: packing_failed, else: packed} stats: {level: minimal, interval: 10} # readings for shop-telemetry run: {until: 1 min} ``` ```python """The Route Records to Topics guide: the function that picks a topic for each record.""" from typing import Any, Dict def custom_kafka_router(data: Dict[str, Any]) -> str: """Picks a topic for each record by its kind and its value.""" if data.get("stream_type") == "telemetry": return "shop-telemetry" value = data.get("value") if isinstance(value, dict) and ( value.get("status") == "packing_failed" or value.get("level") == "ERROR" ): return "system-alarms" # Every other event, including a payload that is not a dict. return "shop-events" ``` ```python """The Route Records to Topics guide: a shop whose failed orders go to their own topic. It needs a Kafka broker on 127.0.0.1:9092: start one with `odctl up kafka-lite`. Run it with `python complex_routing.py`, beside complex_routing_logic.py; it runs for one minute. With ROUTING=router in the environment, `python complex_routing.py` sends the records through a function instead, which wins over the topic in the payload. """ import logging import os from complex_routing_logic import custom_kafka_router from desflow import KafkaEgress, SimulationContext from desflow.values import Template BOOTSTRAP = os.environ.get("KAFKA_BOOTSTRAP_SERVERS", "127.0.0.1:9092") def payload_egress() -> KafkaEgress: """Sends each record to the topic its payload names, and creates the topics.""" return KafkaEgress( bootstrap_servers=BOOTSTRAP, event_topic="shop-events", telemetry_topic="shop-telemetry", topic_policy="create", topics={"system-alarms": {}}, ) def router_egress() -> KafkaEgress: """Sends each record to the topic a function picks.""" return KafkaEgress( bootstrap_servers=BOOTSTRAP, topic_router=custom_kafka_router, topics={"shop-events": {}, "shop-telemetry": {}, "system-alarms": {}}, ) def build(egress: KafkaEgress) -> SimulationContext: """Builds the shop, whose payload names a topic, with `egress` as its one sink.""" app = SimulationContext(sim_id="Shop", factor=0, random_seed=42) app.add_egress(egress) app.add_resource("packers", current_cap=1, max_cap=1) app.add_arrival("orders", "exponential", rate=0.5, spawn="pack_order") app.add_service("packing", "constant", value=1.5) app.with_stats("minimal", interval=10) # readings for shop-telemetry payload = Template( { "status": { "gen": "when", "condition": "failed", "then": "packing_failed", "else": "packed", }, "__topic__": { "gen": "when", "condition": "failed", "then": "system-alarms", "else": "shop-events", }, }, name="tasks.pack_order", vars={"failed": {"gen": "expr", "expr": "process.instance % 10 == 9"}}, ) @app.task(name="pack_order", service_id="packing", resource_id="packers") def pack_order(task_id): """Gives one order record.""" return payload return app if __name__ == "__main__": logging.basicConfig(level=logging.INFO, format="%(levelname)s %(message)s") chosen = ( router_egress() if os.environ.get("ROUTING") == "router" else payload_egress() ) build(chosen).run(until="1 min") ``` ```python """The Route Records to Topics guide, low-level API: a shop whose failed orders go to their own topic. It needs a Kafka broker on 127.0.0.1:9092: start one with `odctl up kafka-lite`. Run it with `python complex_routing_low_level.py`, beside complex_routing_logic.py; it runs for one minute. With ROUTING=router in the environment, it sends the records through a function instead, which wins over the topic in the payload. """ import itertools import logging import os from complex_routing_logic import custom_kafka_router from desflow import ( CapacityConfig, DistributionConfig, DynamicRealtimeEnvironment, DynamicResource, KafkaEgress, Sampler, SimParameter, ) BOOTSTRAP = os.environ.get("KAFKA_BOOTSTRAP_SERVERS", "127.0.0.1:9092") PARAMS = SimParameter( sim_id="Shop", arrival={"orders": DistributionConfig(dist="exponential", rate=0.5)}, service={"packing": DistributionConfig(dist="constant", value=1.5)}, resources={"packers": CapacityConfig(current_cap=1, max_cap=1)}, ) def payload_egress() -> KafkaEgress: """Sends each record to the topic its payload names, and creates the topics.""" return KafkaEgress( bootstrap_servers=BOOTSTRAP, event_topic="shop-events", telemetry_topic="shop-telemetry", topic_policy="create", topics={"system-alarms": {}}, ) def router_egress() -> KafkaEgress: """Sends each record to the topic a function picks.""" return KafkaEgress( bootstrap_servers=BOOTSTRAP, topic_router=custom_kafka_router, topics={"shop-events": {}, "shop-telemetry": {}, "system-alarms": {}}, ) def pack_order(env, packers, sampler, key, task_id): path_id = "Shop.service.packing" stats = env.stats queued = {"path_id": path_id, "sim_id": "Shop", "service": "packing"} env.publish_event(key, {**queued, "status": "queued"}, "pack_order", task_id) stats.task_queued("pack_order", task_id) with packers.request() as unit: yield unit env.publish_event(key, {**queued, "status": "started"}, "pack_order", task_id) stats.task_started("pack_order", task_id) yield env.timeout(sampler.sample(env.registry.get_config(path_id))) failed = task_id % 10 == 9 # every tenth order payload = { "status": "packing_failed" if failed else "packed", "__topic__": "system-alarms" if failed else "shop-events", } env.publish_event(key, payload, "pack_order", task_id) stats.task_finished("pack_order", task_id) def orders(env, packers, sampler): gap = env.registry.get_config("Shop.arrival.orders") for number in itertools.count(1): yield env.timeout(sampler.sample(gap)) env.process(pack_order(env, packers, sampler, f"orders-{number}", number - 1)) def run(until=60.0, egress=None): """Runs the shop unpaced into `egress`, which is `payload_egress()` unless given.""" env = DynamicRealtimeEnvironment(factor=0) env.registry.register_sim_parameter(PARAMS) env.setup_egress([egress or payload_egress()]) env.setup_stats("Shop", "minimal", interval=10) # readings for shop-telemetry packers = DynamicResource(env, "Shop", "packers") env.process(orders(env, packers, Sampler(seed=42))) try: env.run(until=until) finally: env.teardown() if __name__ == "__main__": logging.basicConfig(level=logging.INFO, format="%(levelname)s %(message)s") run(router_egress() if os.environ.get("ROUTING") == "router" else payload_egress()) ``` # Use Avro and Pydantic Send one Kafka topic as Avro, with the schema generated from a Pydantic model, while the other topics stay JSON. `KafkaEgress` writes every record as JSON by default. A consumer that needs a compact, schema-checked format, such as a machine learning service reading predictions, can read Avro instead. Each topic can have its own serializer, so JSON and Avro topics share one producer. ______________________________________________________________________ ## Before You Start - [Egress](https://jaehyeon.me/desflow/latest/user-guide/live-runs-and-connectors/egress/#kafka) explains `KafkaEgress`, and [Route Records to Topics](https://jaehyeon.me/desflow/latest/how-to/records-and-kafka/complex-routing/index.md) explains `__topic__`, which this page uses to pick the topic. - The code publishes to Kafka and to a schema registry, so start both with `odctl up kafka-lite`. See [Installation](https://jaehyeon.me/desflow/latest/installation/index.md) for the one-time odctl install. Stop it with `odctl down kafka-lite --volumes`. - The model needs `dataclasses-avroschema` with its Pydantic support: `pip install "dataclasses-avroschema[pydantic]"`. - The serializer needs its extra: `pip install "desflow[confluent]"` for the Confluent Schema Registry, or `pip install "desflow[glue]"` for the AWS Glue Schema Registry. Both include `kafka`. ______________________________________________________________________ ## Steps ### Generate the Schema from a Model A schema written by hand as a JSON string stops matching the data when someone changes the model and not the schema. `AvroBaseModel` of `dataclasses-avroschema` is a Pydantic model that also writes its Avro schema. `KafkaEgress` serializes the whole record, not only its `value`: `key`, `task`, `instance`, `sim_ts`, `timestamp` and `value`, without `stream_type`. `task` and `instance` are null on an event published without them, so the schema makes both nullable. `PredictionRecord` is that record, with the prediction `MLPrediction` as its `value`: ```python from typing import Optional from dataclasses_avroschema.pydantic import AvroBaseModel from pydantic import Field class MLPrediction(AvroBaseModel): """The prediction, published as the event value.""" event_type: str = "prediction" task_id: str = Field(...) confidence: float = Field(...) class PredictionRecord(AvroBaseModel): """The record KafkaEgress serializes for an event.""" key: str task: Optional[str] = None instance: Optional[int] = None sim_ts: float timestamp: str value: MLPrediction class Meta: namespace = "com.desflow.ml" schema_name = "PredictionEvent" schema_string = PredictionRecord.avro_schema() ``` A serializer takes the generated string as its schema. `ConfluentAvroSerializer` uses a Confluent Schema Registry, and `GlueAvroSerializer` uses an AWS Glue Schema Registry. A registry that needs a user name, a certificate or a proxy takes more arguments: see [Connect to a Secured Schema Registry](https://jaehyeon.me/desflow/latest/how-to/records-and-kafka/kafka-security/#connect-to-a-secured-schema-registry). ```python from desflow.connectors.egress.kafka import ConfluentAvroSerializer generated_serializer = ConfluentAvroSerializer( registry_url="http://127.0.0.1:8081", schema_str=PredictionRecord.avro_schema(), # follows the model ) ``` A blueprint reads the schema from a file, so write the generated schema beside it: ```bash python avro_and_pydantic_models.py > prediction_event.avsc ``` ### Serialize One Topic as Avro `topics` gives the settings of each topic, and its `serializer` names the serializer of that topic. A topic with no serializer uses the default, `JsonSerializer`. The mapping of a blueprint has a `type`, here `confluent_avro`, the registry address and the schema. For the Glue registry the type is `glue_avro` and the registry is named by `registry_name`. ```yaml egress: - type: Kafka config: bootstrap_servers: ${KAFKA_BOOTSTRAP_SERVERS:-127.0.0.1:9092} topics: ml-predictions: # Avro; sim-events and sim-telemetry stay JSON serializer: type: confluent_avro registry_url: ${SCHEMA_REGISTRY_URL:-http://127.0.0.1:8081} schema_file: prediction_event.avsc ``` ```python import logging import os from avro_and_pydantic_models import MLPrediction, generated_serializer from desflow import KafkaEgress, SimulationContext egress = KafkaEgress( bootstrap_servers=os.environ.get("KAFKA_BOOTSTRAP_SERVERS", "127.0.0.1:9092"), topics={"ml-predictions": {"serializer": generated_serializer}}, # Avro ) ``` ```python egress = KafkaEgress( bootstrap_servers=os.environ.get("KAFKA_BOOTSTRAP_SERVERS", "127.0.0.1:9092"), topics={"ml-predictions": {"serializer": generated_serializer}}, # Avro ) ``` ### Publish a Prediction to That Topic In this shop each packed order's finished event is a prediction, and it names the Avro topic with `__topic__`. The `queued` and `started` events name no topic, so they go to `sim-events` as JSON. A blueprint writes the fields of `MLPrediction` in its payload. In the code forms the model checks the fields and `model_dump()` gives the payload. ```yaml resources: packers: {current_cap: 1, max_cap: 1} services: packing: {dist: constant, value: 1.5} arrivals: orders: {dist: exponential, rate: 0.5, spawn: pack_order} tasks: pack_order: service: packing resource: packers # The finished event is a prediction for the order: the fields of MLPrediction payload: __topic__: ml-predictions event_type: prediction task_id: {gen: entity} confidence: 0.9 ``` ```python app = ( SimulationContext(sim_id="Shop", factor=0, random_seed=42) .add_resource("packers", current_cap=1, max_cap=1) .add_service("packing", dist="constant", value=1.5) .add_arrival("orders", dist="exponential", rate=0.5) .add_egress(egress) # predictions as Avro, the rest as JSON ) @app.task(service_id="packing", resource_id="packers") def pack_order(task_id: int, entity): # The finished event is a prediction for the order: the fields of MLPrediction prediction = MLPrediction(task_id=entity.key, confidence=0.9) return {**prediction.model_dump(), "__topic__": "ml-predictions"} @app.arrival_loop("orders") def orders(context: SimulationContext): while True: order = yield context.wait_for_arrival("orders") context.spawn(pack_order(context.next_instance("pack_order"), entity=order)) ``` ```python def pack_order(env, packers, sampler, key, task_id): path_id = "Shop.service.packing" env.publish_event( key, { "path_id": path_id, "sim_id": "Shop", "service": "packing", "status": "queued", }, "pack_order", task_id, ) with packers.request() as unit: yield unit env.publish_event( key, { "path_id": path_id, "sim_id": "Shop", "service": "packing", "status": "started", }, "pack_order", task_id, ) yield env.timeout(sampler.sample(env.registry.get_config(path_id))) # The finished event is a prediction for the order: the fields of MLPrediction prediction = MLPrediction(task_id=key, confidence=0.9) payload = {**prediction.model_dump(), "__topic__": "ml-predictions"} env.publish_event(key, payload, "pack_order", task_id) ``` The shop around it: ```python def orders(env, packers, sampler): gap = env.registry.get_config("Shop.arrival.orders") for number in itertools.count(1): yield env.timeout(sampler.sample(gap)) env.process(pack_order(env, packers, sampler, f"orders-{number}", number - 1)) def shop(sinks: list, factor: float = 0.0) -> DynamicRealtimeEnvironment: """The shop, publishing to the sinks given.""" env = DynamicRealtimeEnvironment(factor=factor) env.registry.register_sim_parameter(PARAMS) env.setup_egress(sinks) packers = DynamicResource(env, "Shop", "packers") env.process(orders(env, packers, Sampler(seed=42))) return env ``` A task can also return the model itself, and `publish_event` turns a Pydantic V2 model into a dictionary before any sink sees it. Pydantic V1 models, including `pydantic.v1`, are not supported and raise a `PydanticSerializationError`. A model cannot hold `__topic__`, so choose the topic of such a record with a `topic_router`, as [Route Records to Topics](https://jaehyeon.me/desflow/latest/how-to/records-and-kafka/complex-routing/#pick-the-topic-with-a-function) shows. ______________________________________________________________________ ## Check the Result Run `desflow run avro_and_pydantic.yaml`, `python avro_and_pydantic.py` or `python avro_and_pydantic_low_level.py` while `kafka-lite` is up. Each runs for one simulated minute and ends at once. The serializer registers the generated schema with the registry of `kafka-lite` on its first send, under the subject `ml-predictions-value`, which `curl http://127.0.0.1:8081/subjects` lists. The run sends 20 predictions to `ml-predictions`, and every one fits the generated schema. The `queued` and `started` events go to `sim-events` as JSON. To read a prediction back, run this script after a shop has run. It reads `ml-predictions` and decodes the first message with a `ConfluentAvroDeserializer`, which fetches the schema that the message names from the registry: ```python import asyncio from aiokafka import AIOKafkaConsumer from desflow.connectors.ingress.kafka import ConfluentAvroDeserializer async def show_first_prediction() -> None: """Prints the first message of ml-predictions, decoded with the schema it names.""" consumer = AIOKafkaConsumer( "ml-predictions", bootstrap_servers="127.0.0.1:9092", auto_offset_reset="earliest", ) await consumer.start() try: message = await asyncio.wait_for(consumer.getone(), timeout=10) reader = ConfluentAvroDeserializer(registry_url="http://127.0.0.1:8081") print(reader.deserialize("ml-predictions", message.value)) finally: await consumer.stop() if __name__ == "__main__": asyncio.run(show_first_prediction()) ``` ```bash python avro_and_pydantic_check.py ``` ```text {'key': 'orders-1', 'task': 'pack_order', 'instance': 0, 'sim_ts': 2.1283113312939435, 'timestamp': '2026-11-09T00:00:00.000+00:00', 'value': {'event_type': 'prediction', 'task_id': 'orders-1', 'confidence': 0.9}} ``` The `timestamp` is the clock time of your run. ______________________________________________________________________ ## Full Files Every code form imports the models and the serializer from `avro_and_pydantic_models.py`, which builds no shop, so keep the files in one folder. Full files ```python """The Pydantic models and the Avro serializer of the Use Avro and Pydantic page. Every code form of the shop imports the models and the serializer from this file: avro_and_pydantic.py (builder) and avro_and_pydantic_low_level.py. It builds no simulation. Install `dataclasses-avroschema[pydantic]` for the models. `python avro_and_pydantic_models.py` prints the Avro schema of the models, which is the file prediction_event.avsc of the blueprint. """ # Each section carries its own imports, as the page shows it. # ruff: noqa: E402 import json from typing import Optional from dataclasses_avroschema.pydantic import AvroBaseModel from pydantic import Field class MLPrediction(AvroBaseModel): """The prediction, published as the event value.""" event_type: str = "prediction" task_id: str = Field(...) confidence: float = Field(...) class PredictionRecord(AvroBaseModel): """The record KafkaEgress serializes for an event.""" key: str task: Optional[str] = None instance: Optional[int] = None sim_ts: float timestamp: str value: MLPrediction class Meta: namespace = "com.desflow.ml" schema_name = "PredictionEvent" schema_string = PredictionRecord.avro_schema() from desflow.connectors.egress.kafka import ConfluentAvroSerializer generated_serializer = ConfluentAvroSerializer( registry_url="http://127.0.0.1:8081", schema_str=PredictionRecord.avro_schema(), # follows the model ) if __name__ == "__main__": print(json.dumps(json.loads(schema_string), indent=2)) ``` ```yaml # The Use Avro and Pydantic guide: each packed order publishes a prediction, sent to # ml-predictions as Avro; every other record goes to its topic as JSON. Needs # prediction_event.avsc beside it, and a Kafka broker with a schema registry: # odctl up kafka-lite. Run it with: desflow run avro_and_pydantic.yaml simulation: {sim_id: Shop, factor: 0, random_seed: 42} egress: - type: Kafka config: bootstrap_servers: ${KAFKA_BOOTSTRAP_SERVERS:-127.0.0.1:9092} topics: ml-predictions: # Avro; sim-events and sim-telemetry stay JSON serializer: type: confluent_avro registry_url: ${SCHEMA_REGISTRY_URL:-http://127.0.0.1:8081} schema_file: prediction_event.avsc resources: packers: {current_cap: 1, max_cap: 1} services: packing: {dist: constant, value: 1.5} arrivals: orders: {dist: exponential, rate: 0.5, spawn: pack_order} tasks: pack_order: service: packing resource: packers # The finished event is a prediction for the order: the fields of MLPrediction payload: __topic__: ml-predictions event_type: prediction task_id: {gen: entity} confidence: 0.9 run: {until: 1 min} ``` ```json { "type": "record", "name": "PredictionEvent", "fields": [ { "name": "key", "type": "string" }, { "name": "task", "type": [ "null", "string" ], "default": null }, { "name": "instance", "type": [ "null", "long" ], "default": null }, { "name": "sim_ts", "type": "double" }, { "name": "timestamp", "type": "string" }, { "name": "value", "type": { "type": "record", "name": "MLPrediction", "fields": [ { "name": "event_type", "type": "string", "default": "prediction" }, { "name": "task_id", "type": "string" }, { "name": "confidence", "type": "double" } ], "doc": "The prediction, published as the event value." } } ], "doc": "The record KafkaEgress serializes for an event.", "namespace": "com.desflow.ml" } ``` ```python """The shop of the Use Avro and Pydantic page, built with the builder API. The shop publishes predictions as Avro and every other record as JSON. It needs a Kafka broker and a schema registry: start both with `odctl up kafka-lite`, then run `python avro_and_pydantic.py`. avro_and_pydantic.yaml and avro_and_pydantic_low_level.py are the same shop in YAML and the low-level API. The code forms import the models and the serializer of avro_and_pydantic_models.py, which must be beside them. """ # ruff: noqa: E402 import logging import os from avro_and_pydantic_models import MLPrediction, generated_serializer from desflow import KafkaEgress, SimulationContext egress = KafkaEgress( bootstrap_servers=os.environ.get("KAFKA_BOOTSTRAP_SERVERS", "127.0.0.1:9092"), topics={"ml-predictions": {"serializer": generated_serializer}}, # Avro ) app = ( SimulationContext(sim_id="Shop", factor=0, random_seed=42) .add_resource("packers", current_cap=1, max_cap=1) .add_service("packing", dist="constant", value=1.5) .add_arrival("orders", dist="exponential", rate=0.5) .add_egress(egress) # predictions as Avro, the rest as JSON ) @app.task(service_id="packing", resource_id="packers") def pack_order(task_id: int, entity): # The finished event is a prediction for the order: the fields of MLPrediction prediction = MLPrediction(task_id=entity.key, confidence=0.9) return {**prediction.model_dump(), "__topic__": "ml-predictions"} @app.arrival_loop("orders") def orders(context: SimulationContext): while True: order = yield context.wait_for_arrival("orders") context.spawn(pack_order(context.next_instance("pack_order"), entity=order)) if __name__ == "__main__": logging.basicConfig(level=logging.INFO, format="%(levelname)s %(message)s") app.run(until="1 min") ``` ```python """The Use Avro and Pydantic guide, low-level API: each packed order publishes a prediction, sent to ml-predictions as Avro, and every other record goes to its topic as JSON. The model and the serializer are those of avro_and_pydantic_models.py, which must be beside this script. It needs a Kafka broker and a schema registry: start both with `odctl up kafka-lite`, then run `python avro_and_pydantic_low_level.py`. """ import itertools import logging import os from avro_and_pydantic_models import MLPrediction, generated_serializer from desflow import ( CapacityConfig, DistributionConfig, DynamicRealtimeEnvironment, DynamicResource, KafkaEgress, Sampler, SimParameter, ) PARAMS = SimParameter( sim_id="Shop", arrival={"orders": DistributionConfig(dist="exponential", rate=0.5)}, service={"packing": DistributionConfig(dist="constant", value=1.5)}, resources={"packers": CapacityConfig(current_cap=1, max_cap=1)}, ) egress = KafkaEgress( bootstrap_servers=os.environ.get("KAFKA_BOOTSTRAP_SERVERS", "127.0.0.1:9092"), topics={"ml-predictions": {"serializer": generated_serializer}}, # Avro ) def pack_order(env, packers, sampler, key, task_id): path_id = "Shop.service.packing" env.publish_event( key, { "path_id": path_id, "sim_id": "Shop", "service": "packing", "status": "queued", }, "pack_order", task_id, ) with packers.request() as unit: yield unit env.publish_event( key, { "path_id": path_id, "sim_id": "Shop", "service": "packing", "status": "started", }, "pack_order", task_id, ) yield env.timeout(sampler.sample(env.registry.get_config(path_id))) # The finished event is a prediction for the order: the fields of MLPrediction prediction = MLPrediction(task_id=key, confidence=0.9) payload = {**prediction.model_dump(), "__topic__": "ml-predictions"} env.publish_event(key, payload, "pack_order", task_id) def orders(env, packers, sampler): gap = env.registry.get_config("Shop.arrival.orders") for number in itertools.count(1): yield env.timeout(sampler.sample(gap)) env.process(pack_order(env, packers, sampler, f"orders-{number}", number - 1)) def shop(sinks: list, factor: float = 0.0) -> DynamicRealtimeEnvironment: """The shop, publishing to the sinks given.""" env = DynamicRealtimeEnvironment(factor=factor) env.registry.register_sim_parameter(PARAMS) env.setup_egress(sinks) packers = DynamicResource(env, "Shop", "packers") env.process(orders(env, packers, Sampler(seed=42))) return env if __name__ == "__main__": logging.basicConfig( level=logging.INFO, format="%(levelname)s [%(asctime)s] %(message)s" ) env = shop([egress]) # predictions as Avro, the rest as JSON try: env.run(until=60) finally: env.teardown() ``` # Use Schema Serializers Send orders to two Kafka topics, one as JSON checked against a JSON Schema and one as Protobuf, and read each back with the matching deserializer. JSON Schema keeps a record as JSON and checks it against a schema before it is sent. Protobuf sends it as a compact binary message of a class generated from a `.proto` file. Either way, a consumer can rely on the shape of every record it reads. Both formats use the Confluent Schema Registry or the AWS Glue Schema Registry, and each topic can have its own serializer. ______________________________________________________________________ ## Before You Start - [Use Avro and Pydantic](https://jaehyeon.me/desflow/latest/how-to/records-and-kafka/avro-and-pydantic/index.md) shows the same steps for Avro, and [Route Records to Topics](https://jaehyeon.me/desflow/latest/how-to/records-and-kafka/complex-routing/index.md) explains `__topic__`, which this page uses to pick the topic. - The code publishes to Kafka and to a schema registry, so start both with `odctl up kafka-lite`. See [Installation](https://jaehyeon.me/desflow/latest/installation/index.md) for the one-time odctl install. Stop it with `odctl down kafka-lite --volumes`. - Each serializer needs its extra: `pip install "desflow[confluent]"` for the Confluent Schema Registry, or `pip install "desflow[glue]"` for the AWS Glue Schema Registry. Both include `kafka`. ______________________________________________________________________ ## Steps ### Describe the Record in JSON Schema As with [Avro](https://jaehyeon.me/desflow/latest/how-to/records-and-kafka/avro-and-pydantic/#generate-the-schema-from-a-model), the schema describes the whole record `KafkaEgress` sends, with your payload as `value`. The serializer raises `SerializationError` for a record that does not match, and a deserializer checks each record it reads in the same way. A blueprint reads the schema from a file, `order_record.schema.json`, which holds the same schema as this string: ```python from desflow.connectors.egress.kafka import ConfluentJsonSchemaSerializer # The schema describes the whole record KafkaEgress sends, with the order as its value. json_schema = """{ "type": "object", "properties": { "key": {"type": "string"}, "task": {"type": ["string", "null"]}, "instance": {"type": ["integer", "null"]}, "sim_ts": {"type": "number"}, "timestamp": {"type": "string"}, "value": { "type": "object", "properties": { "order_id": {"type": "integer"}, "amount": {"type": "number"} }, "required": ["order_id", "amount"] } }, "required": ["key", "sim_ts", "timestamp", "value"] }""" json_serializer = ConfluentJsonSchemaSerializer( registry_url="http://127.0.0.1:8081", schema_str=json_schema ) ``` `ConfluentJsonSchemaSerializer` registers the schema as you wrote it, under the subject `-value`, on the first record of each topic. It checks a schema with no `$schema` as Draft 2020-12. It registers no references, so the schema must hold every definition it uses, and a `$ref` points only inside the schema. `ConfluentJsonSchemaDeserializer` resolves a `$ref` to a schema that the writer registered as a reference. Neither fetches a schema from a web address. ### Describe the Record in Protobuf Protobuf sends each record as a message of a class that `protoc` generates from a `.proto` file. This file describes the same record as the JSON schema: ```proto // The record KafkaEgress sends for an order, as the JSON Schema and Protobuf // guide publishes it. Generate shop_record_pb2.py from it with the command on that page. syntax = "proto3"; package com.desflow.shop; message Order { int64 order_id = 1; double amount = 2; } // `optional` keeps a missing task or instance apart from 0 and "", as null is in JSON. message ShopRecord { string key = 1; optional string task = 2; optional int64 instance = 3; double sim_ts = 4; string timestamp = 5; Order value = 6; } ``` The code forms use the Python module that `protoc` generates. This command uses the `protoc` that grpcio-tools 1.85.0 bundles, which is protoc 35.1, in the folder that holds the file: ```bash uvx --from grpcio-tools==1.85.0 python -m grpc_tools.protoc -I. --python_out=. --pyi_out=. shop_record.proto ``` The module checks the protobuf runtime when it is imported and refuses a runtime older than the `protoc` that wrote it. The header of `shop_record_pb2.py` names the oldest runtime that imports it: `Protobuf Python Version: 7.35.1`. For your own file, use a `protoc` whose header shows a version no newer than the protobuf you have installed. A blueprint cannot import a Python module, so it reads a descriptor file that `protoc` writes from the same `.proto` file: ```bash uvx --from grpcio-tools==1.85.0 python -m grpc_tools.protoc -I. --descriptor_set_out=shop_record.desc --include_imports shop_record.proto ``` The serializer takes the generated class. It registers the file of the class under the subject `-value` on the first record of each topic, after the files that it imports. It builds the message from the record by field name and drops a key that the file does not have: ```python from shop_record_pb2 import ShopRecord from desflow.connectors.egress.kafka import ConfluentProtobufSerializer # message_type is the class that protoc generated. The serializer registers its file. protobuf_serializer = ConfluentProtobufSerializer( registry_url="http://127.0.0.1:8081", message_type=ShopRecord ) ``` ### Serialize Two Topics `topics` gives the settings of each topic, and its `serializer` names the serializer of that topic. A topic with no serializer uses the default, JSON. In a blueprint the serializer is a mapping with a `type`, here `confluent_json_schema` and `confluent_protobuf`, and the registry address. ```yaml egress: - type: Kafka config: bootstrap_servers: ${KAFKA_BOOTSTRAP_SERVERS:-127.0.0.1:9092} topics: orders-json: serializer: type: confluent_json_schema registry_url: ${SCHEMA_REGISTRY_URL:-http://127.0.0.1:8081} schema_file: order_record.schema.json orders-protobuf: serializer: type: confluent_protobuf registry_url: ${SCHEMA_REGISTRY_URL:-http://127.0.0.1:8081} descriptor_file: shop_record.desc message: com.desflow.shop.ShopRecord ``` ```python import logging import os from json_schema_and_protobuf_serializers import json_serializer, protobuf_serializer from desflow import KafkaEgress, SimulationContext egress = KafkaEgress( bootstrap_servers=os.environ.get("KAFKA_BOOTSTRAP_SERVERS", "127.0.0.1:9092"), topics={ "orders-json": {"serializer": json_serializer}, "orders-protobuf": {"serializer": protobuf_serializer}, }, ) ``` ```python egress = KafkaEgress( bootstrap_servers=os.environ.get("KAFKA_BOOTSTRAP_SERVERS", "127.0.0.1:9092"), topics={ "orders-json": {"serializer": json_serializer}, "orders-protobuf": {"serializer": protobuf_serializer}, }, ) ``` ### Publish Orders to Both Topics Each packed order's finished event is the order record, and it names its topic with `__topic__`. In this shop the orders alternate between the formats, so one run shows both. The `queued` and `started` events name no topic, so they go to `sim-events` as JSON. ```yaml resources: packers: {current_cap: 1, max_cap: 1} services: packing: {dist: constant, value: 1.5} arrivals: orders: {dist: exponential, rate: 0.5, spawn: pack_order} tasks: pack_order: service: packing resource: packers payload: # Orders alternate between the two formats, so one run shows both __topic__: gen: when condition: "process.instance % 2 == 1" then: orders-protobuf else: orders-json order_id: {gen: expr, expr: process.instance} amount: 19.99 ``` ```python app = ( SimulationContext(sim_id="Shop", factor=0, random_seed=42) .add_resource("packers", current_cap=1, max_cap=1) .add_service("packing", dist="constant", value=1.5) .add_arrival("orders", dist="exponential", rate=0.5) .add_egress(egress) # orders as JSON Schema or Protobuf, the rest as JSON ) @app.task(service_id="packing", resource_id="packers") def pack_order(task_id: int, entity): # Orders alternate between the two formats, so one run shows both topic = "orders-protobuf" if task_id % 2 else "orders-json" return {"__topic__": topic, "order_id": task_id, "amount": 19.99} @app.arrival_loop("orders") def orders(context: SimulationContext): while True: order = yield context.wait_for_arrival("orders") context.spawn(pack_order(context.next_instance("pack_order"), entity=order)) ``` `shop` takes the sinks as an argument, and the script passes it `[egress]`: ```python def pack_order(env, packers, sampler, key, task_id): path_id = "Shop.service.packing" env.publish_event( key, { "path_id": path_id, "sim_id": "Shop", "service": "packing", "status": "queued", }, "pack_order", task_id, ) with packers.request() as unit: yield unit env.publish_event( key, { "path_id": path_id, "sim_id": "Shop", "service": "packing", "status": "started", }, "pack_order", task_id, ) yield env.timeout(sampler.sample(env.registry.get_config(path_id))) # Orders alternate between the two formats, so one run shows both topic = "orders-protobuf" if task_id % 2 else "orders-json" order = {"__topic__": topic, "order_id": task_id, "amount": 19.99} env.publish_event(key, order, "pack_order", task_id) def orders(env, packers, sampler): gap = env.registry.get_config("Shop.arrival.orders") for number in itertools.count(1): yield env.timeout(sampler.sample(gap)) env.process(pack_order(env, packers, sampler, f"orders-{number}", number - 1)) def shop(sinks: list, factor: float = 0.0) -> DynamicRealtimeEnvironment: """The shop, publishing to the sinks given.""" env = DynamicRealtimeEnvironment(factor=factor) env.registry.register_sim_parameter(PARAMS) env.setup_egress(sinks) packers = DynamicResource(env, "Shop", "packers") env.process(orders(env, packers, Sampler(seed=42))) return env ``` ### Use the AWS Glue Schema Registry The same two formats work with an AWS Glue Schema Registry. The Glue classes need `desflow[glue]`; the rest of this page needs only `desflow[confluent]`, so this function builds the Glue serializers only when it is called. They replace the Confluent ones in `topics`. In a blueprint the types are `glue_json_schema` and `glue_protobuf`, with the key `registry_name` for the registry and the key `boto3` for the arguments of `boto3.client`, such as `region_name`. The classes take the same as keyword arguments (`region_name="us-east-1"`). Four rules differ from the Confluent classes: - `GlueProtobufSerializer` takes one more argument, `schema_str`: the text of the `.proto` file, because Glue stores the text and protobuf cannot print it from the generated class. The text must declare the same messages, in the same file, as `message_type`. In a blueprint it is the key `schema_file`. - `GlueJsonSchemaSerializer` compiles the schema with fastjsonschema when you build it, so a `$ref` to another document is fetched at that point. - `GlueJsonSchemaSerializer` fills in the `default` of a property that a record leaves out. - Glue checks a new version of a schema against the schema's compatibility mode before it is available. Both serializers wait for it: up to 10 checks, 3 seconds apart, which is about 30 seconds. If the version is still pending after that, the serializer raises an error that names the version. ```yaml egress: - type: Kafka config: bootstrap_servers: ${KAFKA_BOOTSTRAP_SERVERS} topics: orders-json: serializer: type: glue_json_schema registry_name: shop schema_file: order_record.schema.json boto3: {region_name: us-east-1} # passed to boto3.client orders-protobuf: serializer: type: glue_protobuf registry_name: shop descriptor_file: shop_record.desc message: com.desflow.shop.ShopRecord schema_file: shop_record.proto # the text of the .proto file boto3: {region_name: us-east-1} ``` ```python def glue_serializers(): """The same two formats for an AWS Glue Schema Registry; they need `desflow[glue]`.""" from pathlib import Path from desflow.connectors.egress.kafka import ( GlueJsonSchemaSerializer, GlueProtobufSerializer, ) glue_json = GlueJsonSchemaSerializer( registry_name="shop", schema_str=json_schema, region_name="us-east-1" ) # Glue stores the text of the .proto file, so the serializer takes it as schema_str. # It must declare the same messages as message_type. glue_protobuf = GlueProtobufSerializer( registry_name="shop", message_type=ShopRecord, schema_str=Path(__file__).with_name("shop_record.proto").read_text(), region_name="us-east-1", ) return glue_json, glue_protobuf def glue_egress(): """The egress of the shop, sending the two order topics through the Glue serializers.""" import os from desflow import KafkaEgress glue_json, glue_protobuf = glue_serializers() return KafkaEgress( bootstrap_servers=os.environ.get("KAFKA_BOOTSTRAP_SERVERS", "127.0.0.1:9092"), topics={ "orders-json": {"serializer": glue_json}, "orders-protobuf": {"serializer": glue_protobuf}, }, ) ``` Pass `glue_egress()` to `add_egress` in place of the `egress` above. ```python def glue_serializers(): """The same two formats for an AWS Glue Schema Registry; they need `desflow[glue]`.""" from pathlib import Path from desflow.connectors.egress.kafka import ( GlueJsonSchemaSerializer, GlueProtobufSerializer, ) glue_json = GlueJsonSchemaSerializer( registry_name="shop", schema_str=json_schema, region_name="us-east-1" ) # Glue stores the text of the .proto file, so the serializer takes it as schema_str. # It must declare the same messages as message_type. glue_protobuf = GlueProtobufSerializer( registry_name="shop", message_type=ShopRecord, schema_str=Path(__file__).with_name("shop_record.proto").read_text(), region_name="us-east-1", ) return glue_json, glue_protobuf def glue_egress(): """The egress of the shop, sending the two order topics through the Glue serializers.""" import os from desflow import KafkaEgress glue_json, glue_protobuf = glue_serializers() return KafkaEgress( bootstrap_servers=os.environ.get("KAFKA_BOOTSTRAP_SERVERS", "127.0.0.1:9092"), topics={ "orders-json": {"serializer": glue_json}, "orders-protobuf": {"serializer": glue_protobuf}, }, ) ``` Pass `glue_egress()` to the shop: `shop([glue_egress()])`. ### Read the Records Back A consumer reads each order topic with the deserializer of its format. `read_order` takes the topic and the value of one message, from any Kafka consumer, and returns the record that was sent. Each deserializer fetches the schema that a message names from the registry. `ConfluentJsonSchemaDeserializer` checks every record against it, and `ConfluentProtobufDeserializer` decodes the message as `message_type`. For a Glue registry, `GlueJsonSchemaDeserializer("shop", region_name="us-east-1")` and `GlueProtobufDeserializer("shop", ShopRecord, region_name="us-east-1")` take their place: the registry name, for Protobuf the message class, and the arguments of `boto3.client`. ```python from desflow.connectors.ingress.kafka import ( ConfluentJsonSchemaDeserializer, ConfluentProtobufDeserializer, MessageDeserializer, ) # A consumer of the order topics reads each one with the deserializer of its format. order_readers: dict[str, MessageDeserializer] = { "orders-json": ConfluentJsonSchemaDeserializer( registry_url="http://127.0.0.1:8081" ), "orders-protobuf": ConfluentProtobufDeserializer( registry_url="http://127.0.0.1:8081", message_type=ShopRecord ), } def read_order(topic: str, payload: bytes) -> dict: """Decodes one message of an order topic into the record that was sent.""" return order_readers[topic].deserialize(topic, payload) ``` ______________________________________________________________________ ## Check the Result Run `desflow run json_schema_and_protobuf.yaml`, `python json_schema_and_protobuf.py` or `python json_schema_and_protobuf_low_level.py` while `kafka-lite` is up, beside the files of the page. Each runs for one simulated minute and ends at once. Each form sends 10 orders to `orders-json` and 10 to `orders-protobuf`, and the other events to `sim-events` as JSON. To read the first order of each topic back, run the serializers file after a shop has run. It prints what `read_order` decodes: ```python import asyncio from aiokafka import AIOKafkaConsumer async def show_first_order(topic: str) -> None: """Prints the first order of a topic, decoded by the reader of its format.""" consumer = AIOKafkaConsumer( topic, bootstrap_servers="127.0.0.1:9092", auto_offset_reset="earliest" ) await consumer.start() try: message = await asyncio.wait_for(consumer.getone(), timeout=10) print(topic, read_order(topic, message.value)) finally: await consumer.stop() if __name__ == "__main__": for topic in order_readers: asyncio.run(show_first_order(topic)) ``` ```bash python json_schema_and_protobuf_serializers.py ``` ```text orders-json {'sim_ts': 2.1283113312939435, 'timestamp': '2026-11-09T00:00:00.000+00:00', 'key': 'orders-1', 'task': 'pack_order', 'instance': 0, 'value': {'order_id': 0, 'amount': 19.99}} orders-protobuf {'key': 'orders-2', 'task': 'pack_order', 'instance': '1', 'sim_ts': 6.434338901219139, 'timestamp': '2026-11-09T00:00:00.000+00:00', 'value': {'order_id': '1', 'amount': 19.99}} ``` The `timestamp` is the clock time of your run. A 64 bit integer field of Protobuf, such as `order_id` and `instance`, comes back from a deserializer as a string, so the Protobuf record shows `'1'` for `order_id` and `instance` where the JSON record shows numbers. ______________________________________________________________________ ## Full Files Every code form uses the serializers in `json_schema_and_protobuf_serializers.py`, which builds no shop, so keep the files in one folder. Full files ```python """The serializers and order readers of the Use Schema Serializers page. The code forms of the shop import the serializers from this file: json_schema_and_protobuf.py (builder) and json_schema_and_protobuf_low_level.py. It builds no simulation. shop_record.proto and shop_record_pb2.py, generated from it, must be beside this file. It needs a Kafka broker and a schema registry: start both with `odctl up kafka-lite`. After a shop has run, `python json_schema_and_protobuf_serializers.py` reads the first order of each order topic back. """ # Each section carries its own imports, as the page shows it. # ruff: noqa: E402 from desflow.connectors.egress.kafka import ConfluentJsonSchemaSerializer # The schema describes the whole record KafkaEgress sends, with the order as its value. json_schema = """{ "type": "object", "properties": { "key": {"type": "string"}, "task": {"type": ["string", "null"]}, "instance": {"type": ["integer", "null"]}, "sim_ts": {"type": "number"}, "timestamp": {"type": "string"}, "value": { "type": "object", "properties": { "order_id": {"type": "integer"}, "amount": {"type": "number"} }, "required": ["order_id", "amount"] } }, "required": ["key", "sim_ts", "timestamp", "value"] }""" json_serializer = ConfluentJsonSchemaSerializer( registry_url="http://127.0.0.1:8081", schema_str=json_schema ) from shop_record_pb2 import ShopRecord from desflow.connectors.egress.kafka import ConfluentProtobufSerializer # message_type is the class that protoc generated. The serializer registers its file. protobuf_serializer = ConfluentProtobufSerializer( registry_url="http://127.0.0.1:8081", message_type=ShopRecord ) def glue_serializers(): """The same two formats for an AWS Glue Schema Registry; they need `desflow[glue]`.""" from pathlib import Path from desflow.connectors.egress.kafka import ( GlueJsonSchemaSerializer, GlueProtobufSerializer, ) glue_json = GlueJsonSchemaSerializer( registry_name="shop", schema_str=json_schema, region_name="us-east-1" ) # Glue stores the text of the .proto file, so the serializer takes it as schema_str. # It must declare the same messages as message_type. glue_protobuf = GlueProtobufSerializer( registry_name="shop", message_type=ShopRecord, schema_str=Path(__file__).with_name("shop_record.proto").read_text(), region_name="us-east-1", ) return glue_json, glue_protobuf def glue_egress(): """The egress of the shop, sending the two order topics through the Glue serializers.""" import os from desflow import KafkaEgress glue_json, glue_protobuf = glue_serializers() return KafkaEgress( bootstrap_servers=os.environ.get("KAFKA_BOOTSTRAP_SERVERS", "127.0.0.1:9092"), topics={ "orders-json": {"serializer": glue_json}, "orders-protobuf": {"serializer": glue_protobuf}, }, ) from desflow.connectors.ingress.kafka import ( ConfluentJsonSchemaDeserializer, ConfluentProtobufDeserializer, MessageDeserializer, ) # A consumer of the order topics reads each one with the deserializer of its format. order_readers: dict[str, MessageDeserializer] = { "orders-json": ConfluentJsonSchemaDeserializer( registry_url="http://127.0.0.1:8081" ), "orders-protobuf": ConfluentProtobufDeserializer( registry_url="http://127.0.0.1:8081", message_type=ShopRecord ), } def read_order(topic: str, payload: bytes) -> dict: """Decodes one message of an order topic into the record that was sent.""" return order_readers[topic].deserialize(topic, payload) import asyncio from aiokafka import AIOKafkaConsumer async def show_first_order(topic: str) -> None: """Prints the first order of a topic, decoded by the reader of its format.""" consumer = AIOKafkaConsumer( topic, bootstrap_servers="127.0.0.1:9092", auto_offset_reset="earliest" ) await consumer.start() try: message = await asyncio.wait_for(consumer.getone(), timeout=10) print(topic, read_order(topic, message.value)) finally: await consumer.stop() if __name__ == "__main__": for topic in order_readers: asyncio.run(show_first_order(topic)) ``` ```yaml # The Use Schema Serializers guide: each packed order publishes an order record, sent # to orders-json as JSON Schema or to orders-protobuf as Protobuf; every other record # goes to sim-events as JSON. Needs order_record.schema.json and shop_record.desc beside # it, and a Kafka broker with a schema registry: odctl up kafka-lite. Run it with: # desflow run json_schema_and_protobuf.yaml simulation: {sim_id: Shop, factor: 0, random_seed: 42} egress: - type: Kafka config: bootstrap_servers: ${KAFKA_BOOTSTRAP_SERVERS:-127.0.0.1:9092} topics: orders-json: serializer: type: confluent_json_schema registry_url: ${SCHEMA_REGISTRY_URL:-http://127.0.0.1:8081} schema_file: order_record.schema.json orders-protobuf: serializer: type: confluent_protobuf registry_url: ${SCHEMA_REGISTRY_URL:-http://127.0.0.1:8081} descriptor_file: shop_record.desc message: com.desflow.shop.ShopRecord resources: packers: {current_cap: 1, max_cap: 1} services: packing: {dist: constant, value: 1.5} arrivals: orders: {dist: exponential, rate: 0.5, spawn: pack_order} tasks: pack_order: service: packing resource: packers payload: # Orders alternate between the two formats, so one run shows both __topic__: gen: when condition: "process.instance % 2 == 1" then: orders-protobuf else: orders-json order_id: {gen: expr, expr: process.instance} amount: 19.99 run: {until: 1 min} ``` ```yaml # The Use Schema Serializers guide: the shop of json_schema_and_protobuf.yaml with the # AWS Glue Schema Registry in place of the Confluent one. Needs # order_record.schema.json, shop_record.desc and shop_record.proto beside it, and the # package desflow[glue]. Set KAFKA_BOOTSTRAP_SERVERS and give AWS credentials, then run # it with: desflow run json_schema_and_protobuf_glue.yaml simulation: {sim_id: Shop, factor: 0, random_seed: 42} egress: - type: Kafka config: bootstrap_servers: ${KAFKA_BOOTSTRAP_SERVERS} topics: orders-json: serializer: type: glue_json_schema registry_name: shop schema_file: order_record.schema.json boto3: {region_name: us-east-1} # passed to boto3.client orders-protobuf: serializer: type: glue_protobuf registry_name: shop descriptor_file: shop_record.desc message: com.desflow.shop.ShopRecord schema_file: shop_record.proto # the text of the .proto file boto3: {region_name: us-east-1} resources: packers: {current_cap: 1, max_cap: 1} services: packing: {dist: constant, value: 1.5} arrivals: orders: {dist: exponential, rate: 0.5, spawn: pack_order} tasks: pack_order: service: packing resource: packers payload: # Orders alternate between the two formats, so one run shows both __topic__: gen: when condition: "process.instance % 2 == 1" then: orders-protobuf else: orders-json order_id: {gen: expr, expr: process.instance} amount: 19.99 run: {until: 1 min} ``` ```json { "type": "object", "properties": { "key": {"type": "string"}, "task": {"type": ["string", "null"]}, "instance": {"type": ["integer", "null"]}, "sim_ts": {"type": "number"}, "timestamp": {"type": "string"}, "value": { "type": "object", "properties": { "order_id": {"type": "integer"}, "amount": {"type": "number"} }, "required": ["order_id", "amount"] } }, "required": ["key", "sim_ts", "timestamp", "value"] } ``` ```python """The shop of the Use Schema Serializers page, built with the builder API. The shop publishes each packed order as JSON Schema or Protobuf and every other record as JSON. It needs a Kafka broker and a schema registry: start both with `odctl up kafka-lite`, then run `python json_schema_and_protobuf.py`. json_schema_and_protobuf.yaml and json_schema_and_protobuf_low_level.py are the same shop in YAML and the low-level API. The code forms import the serializers of json_schema_and_protobuf_serializers.py, which must be beside them. """ # ruff: noqa: E402 import logging import os from json_schema_and_protobuf_serializers import json_serializer, protobuf_serializer from desflow import KafkaEgress, SimulationContext egress = KafkaEgress( bootstrap_servers=os.environ.get("KAFKA_BOOTSTRAP_SERVERS", "127.0.0.1:9092"), topics={ "orders-json": {"serializer": json_serializer}, "orders-protobuf": {"serializer": protobuf_serializer}, }, ) app = ( SimulationContext(sim_id="Shop", factor=0, random_seed=42) .add_resource("packers", current_cap=1, max_cap=1) .add_service("packing", dist="constant", value=1.5) .add_arrival("orders", dist="exponential", rate=0.5) .add_egress(egress) # orders as JSON Schema or Protobuf, the rest as JSON ) @app.task(service_id="packing", resource_id="packers") def pack_order(task_id: int, entity): # Orders alternate between the two formats, so one run shows both topic = "orders-protobuf" if task_id % 2 else "orders-json" return {"__topic__": topic, "order_id": task_id, "amount": 19.99} @app.arrival_loop("orders") def orders(context: SimulationContext): while True: order = yield context.wait_for_arrival("orders") context.spawn(pack_order(context.next_instance("pack_order"), entity=order)) if __name__ == "__main__": logging.basicConfig(level=logging.INFO, format="%(levelname)s %(message)s") app.run(until="1 min") ``` ```python """The Use Schema Serializers guide, low-level API: each packed order publishes an order record, sent to orders-json as JSON Schema or to orders-protobuf as Protobuf, and every other record goes to its topic as JSON. The serializers are those of json_schema_and_protobuf_serializers.py, which must be beside this script, with shop_record.proto and shop_record_pb2.py. It needs a Kafka broker and a schema registry: start both with `odctl up kafka-lite`, then run `python json_schema_and_protobuf_low_level.py`. """ import itertools import logging import os from json_schema_and_protobuf_serializers import json_serializer, protobuf_serializer from desflow import ( CapacityConfig, DistributionConfig, DynamicRealtimeEnvironment, DynamicResource, KafkaEgress, Sampler, SimParameter, ) PARAMS = SimParameter( sim_id="Shop", arrival={"orders": DistributionConfig(dist="exponential", rate=0.5)}, service={"packing": DistributionConfig(dist="constant", value=1.5)}, resources={"packers": CapacityConfig(current_cap=1, max_cap=1)}, ) egress = KafkaEgress( bootstrap_servers=os.environ.get("KAFKA_BOOTSTRAP_SERVERS", "127.0.0.1:9092"), topics={ "orders-json": {"serializer": json_serializer}, "orders-protobuf": {"serializer": protobuf_serializer}, }, ) def pack_order(env, packers, sampler, key, task_id): path_id = "Shop.service.packing" env.publish_event( key, { "path_id": path_id, "sim_id": "Shop", "service": "packing", "status": "queued", }, "pack_order", task_id, ) with packers.request() as unit: yield unit env.publish_event( key, { "path_id": path_id, "sim_id": "Shop", "service": "packing", "status": "started", }, "pack_order", task_id, ) yield env.timeout(sampler.sample(env.registry.get_config(path_id))) # Orders alternate between the two formats, so one run shows both topic = "orders-protobuf" if task_id % 2 else "orders-json" order = {"__topic__": topic, "order_id": task_id, "amount": 19.99} env.publish_event(key, order, "pack_order", task_id) def orders(env, packers, sampler): gap = env.registry.get_config("Shop.arrival.orders") for number in itertools.count(1): yield env.timeout(sampler.sample(gap)) env.process(pack_order(env, packers, sampler, f"orders-{number}", number - 1)) def shop(sinks: list, factor: float = 0.0) -> DynamicRealtimeEnvironment: """The shop, publishing to the sinks given.""" env = DynamicRealtimeEnvironment(factor=factor) env.registry.register_sim_parameter(PARAMS) env.setup_egress(sinks) packers = DynamicResource(env, "Shop", "packers") env.process(orders(env, packers, Sampler(seed=42))) return env if __name__ == "__main__": logging.basicConfig( level=logging.INFO, format="%(levelname)s [%(asctime)s] %(message)s" ) env = shop([egress]) # orders as JSON Schema or Protobuf, the rest as JSON try: env.run(until=60) finally: env.teardown() ``` # Connect to Secure Kafka Publish a simulation's events to a Kafka cluster that needs SASL, mutual TLS or Amazon MSK IAM, by passing the security settings in the sink's `config`. The Kafka connectors pass any setting they do not use themselves to the Kafka client underneath, `aiokafka`, so SASL, mTLS, OAuth and AWS IAM work without code of your own. `KafkaAdminConnector` passes its settings to the `aiokafka` client of each method: the admin client for `create_topics`, the producer for `send_config` and the consumer for `collect_data`. Each setting must be one that client takes. ______________________________________________________________________ ## Before You Start - Install the Kafka connectors: `pip install "desflow[kafka]"`. - [Egress](https://jaehyeon.me/desflow/latest/user-guide/live-runs-and-connectors/egress/#kafka) and [Ingress](https://jaehyeon.me/desflow/latest/user-guide/live-runs-and-connectors/ingress/#kafka) explain the Kafka connectors without security. - Every example here connects to a managed or secured cluster. No odctl profile runs a secured broker, so the shop needs a cluster of your own, such as Confluent Cloud for SASL. To try the connectors locally without security, start a broker with `odctl up kafka-lite` and see [Installation](https://jaehyeon.me/desflow/latest/installation/index.md). ______________________________________________________________________ ## Steps ### Connect with SASL For Confluent Cloud, or any cluster that uses SASL PLAIN or SCRAM, pass `security_protocol`, `sasl_mechanism` and the credentials. The address and the credentials come from variables, so no secret is in the file. With no `topic_router`, `KafkaEgress` creates `sim-events` and `sim-telemetry` when it starts, and passes the security settings to the admin client that creates them. This simulation publishes its events through a SASL sink: ```yaml simulation: {sim_id: Shop, factor: 0, random_seed: 42} resources: packers: {current_cap: 1, max_cap: 1} services: packing: {dist: constant, value: 1.5} arrivals: orders: {dist: exponential, rate: 0.5, spawn: pack_order} tasks: pack_order: service: packing resource: packers payload: {event_type: order_packed} egress: - type: Kafka config: bootstrap_servers: ${KAFKA_BOOTSTRAP_SERVERS:-pkc-xxxx.us-east-1.aws.confluent.cloud:9092} # Passed as they are to the Kafka client security_protocol: SASL_SSL sasl_mechanism: PLAIN # or SCRAM-SHA-512 sasl_plain_username: ${KAFKA_API_KEY:-} sasl_plain_password: ${KAFKA_API_SECRET:-} run: {until: 1 min} ``` ```python import os from typing import Any, Dict from desflow import KafkaEgress def sasl_connection() -> Dict[str, Any]: """The settings of a cluster that uses SASL. The environment holds the credentials.""" return dict( bootstrap_servers=os.environ["KAFKA_BOOTSTRAP_SERVERS"], # Passed as they are to the Kafka client security_protocol="SASL_SSL", sasl_mechanism="PLAIN", # or SCRAM-SHA-512 sasl_plain_username=os.environ["KAFKA_API_KEY"], sasl_plain_password=os.environ["KAFKA_API_SECRET"], ) def sasl_egress() -> KafkaEgress: """The egress of a cluster that uses SASL.""" return KafkaEgress(**sasl_connection()) ``` ```python def build(egress: KafkaEgress) -> SimulationContext: """Builds the shop, with `egress` as its one sink.""" app = ( SimulationContext(sim_id="Shop", factor=0, random_seed=42) .add_resource("packers", current_cap=1, max_cap=1) .add_service("packing", dist="constant", value=1.5) .add_arrival("orders", dist="exponential", rate=0.5) .add_egress(egress) ) @app.task(service_id="packing", resource_id="packers") def pack_order(task_id: int): return {"event_type": "order_packed"} @app.arrival_loop("orders") def orders(context: SimulationContext): while True: order = yield context.wait_for_arrival("orders") context.spawn(pack_order(context.next_instance("pack_order"), entity=order)) return app if __name__ == "__main__": logging.basicConfig( level=logging.INFO, format="%(levelname)s [%(asctime)s] %(message)s" ) build(selected_egress()).run(until="1 min") ``` ```python def sasl_app() -> SimulationContext: """The shop with the egress of a cluster that uses SASL.""" return build(sasl_egress()) ``` ```python def pack_order(env, packers, sampler, key, task_id): path_id = "Shop.service.packing" env.publish_event( key, { "path_id": path_id, "sim_id": "Shop", "service": "packing", "status": "queued", }, "pack_order", task_id, ) with packers.request() as unit: yield unit env.publish_event( key, { "path_id": path_id, "sim_id": "Shop", "service": "packing", "status": "started", }, "pack_order", task_id, ) yield env.timeout(sampler.sample(env.registry.get_config(path_id))) env.publish_event(key, {"event_type": "order_packed"}, "pack_order", task_id) def orders(env, packers, sampler): gap = env.registry.get_config("Shop.arrival.orders") for number in itertools.count(1): yield env.timeout(sampler.sample(gap)) env.process(pack_order(env, packers, sampler, f"orders-{number}", number - 1)) def shop(sinks: list, factor: float = 0.0) -> DynamicRealtimeEnvironment: """The shop, publishing to the sinks given.""" env = DynamicRealtimeEnvironment(factor=factor) env.registry.register_sim_parameter(PARAMS) env.setup_egress(sinks) packers = DynamicResource(env, "Shop", "packers") env.process(orders(env, packers, Sampler(seed=42))) return env if __name__ == "__main__": logging.basicConfig( level=logging.INFO, format="%(levelname)s [%(asctime)s] %(message)s" ) env = shop([selected_egress()]) # KAFKA_CONNECTION picks the cluster try: env.run(until=60) finally: env.teardown() ``` ### Connect with mTLS For a cluster that requires mutual TLS, `ssl` takes the certificate files: `cafile`, `certfile`, `keyfile` and, for an encrypted key, `password`. The sink builds the SSL context from them with `aiokafka.helpers.create_ssl_context`, so one setting serves the sink and the other Kafka connectors. Set `security_protocol` to `SSL` as well. The Builder and Low-level forms run the same shop as the SASL step with this egress: `build(mtls_egress())` and `shop([mtls_egress()])`. ```yaml egress: - type: Kafka config: bootstrap_servers: ${KAFKA_BOOTSTRAP_SERVERS} security_protocol: SSL # The arguments of aiokafka.helpers.create_ssl_context ssl: cafile: ${KAFKA_CA_FILE} certfile: ${KAFKA_CERT_FILE} keyfile: ${KAFKA_KEY_FILE} ``` ```python import os def mtls_egress() -> KafkaEgress: """The egress of a cluster that requires mutual TLS.""" return KafkaEgress( bootstrap_servers=os.environ["KAFKA_BOOTSTRAP_SERVERS"], security_protocol="SSL", # The arguments of aiokafka.helpers.create_ssl_context ssl={ "cafile": os.environ["KAFKA_CA_FILE"], "certfile": os.environ["KAFKA_CERT_FILE"], "keyfile": os.environ["KAFKA_KEY_FILE"], }, ) ``` ```python def mtls_app() -> SimulationContext: """The shop with the egress of a cluster that requires mutual TLS.""" return build(mtls_egress()) ``` ```python def mtls_shop() -> DynamicRealtimeEnvironment: """The shop with the egress of a cluster that requires mutual TLS.""" return shop([mtls_egress()]) ``` ### Connect to AWS MSK Amazon MSK with IAM access control uses `sasl_mechanism` `OAUTHBEARER` with a token provider. `sasl_oauth_token_provider: {type: aws_msk_iam, region: }` builds one that signs a token with the AWS credentials of your environment, or the EC2 or EKS role. It needs the package `aws-msk-iam-sasl-signer-python`, which you install yourself. Set `security_protocol` to `SASL_SSL` as well. For Okta, Auth0 or another single sign-on provider, pass your own subclass of `aiokafka.abc.AbstractTokenProvider` with an `async` `token()` in the Builder and Low-level forms. The Builder and Low-level forms run the same shop as the SASL step with this egress: `build(msk_egress())` and `shop([msk_egress()])`. ```yaml egress: - type: Kafka config: bootstrap_servers: b-1.my-msk.amazonaws.com:9098 security_protocol: SASL_SSL sasl_mechanism: OAUTHBEARER # The token comes from the AWS credentials of your environment or role sasl_oauth_token_provider: {type: aws_msk_iam, region: us-east-1} ``` ```python def msk_egress() -> KafkaEgress: """The egress of an Amazon MSK cluster with IAM access control.""" return KafkaEgress( bootstrap_servers="b-1.my-msk.amazonaws.com:9098", security_protocol="SASL_SSL", sasl_mechanism="OAUTHBEARER", # The token comes from the AWS credentials of your environment or role sasl_oauth_token_provider={"type": "aws_msk_iam", "region": "us-east-1"}, ) ``` ```python def msk_app() -> SimulationContext: """The shop with the egress of an Amazon MSK cluster.""" return build(msk_egress()) ``` ```python def msk_shop() -> DynamicRealtimeEnvironment: """The shop with the egress of an Amazon MSK cluster.""" return shop([msk_egress()]) ``` ### Connect to a Secured Schema Registry A schema registry that needs a user name, a certificate or a proxy takes its own settings, apart from the Kafka ones. The Confluent serializers (`confluent_avro`, `confluent_json_schema` and `confluent_protobuf`) and the Confluent deserializers take these arguments: - `auth`: a user name and a password. - `verify`: `true`, `false`, the path of a CA file or directory, or in code an `ssl.SSLContext`. A YAML blueprint cannot write a context. - `cert`: a client certificate file, or a list of the certificate file, the key file and the key password. - `headers`: extra headers, such as a bearer token. - `proxy`: the URL of a proxy. - `timeout`: the seconds each step of a request (connecting, sending, reading) may take. The default is 10. `null` waits without a limit. - `max_retries`: how many times a request is repeated after a timeout or another transport error (3 by default). This shop sends its predictions to `ml-predictions` as Avro, as [Use Avro and Pydantic](https://jaehyeon.me/desflow/latest/how-to/records-and-kafka/avro-and-pydantic/index.md) does, through a registry with all of these settings. The Builder and Low-level forms need `avro_and_pydantic_models.py` of that page beside them. ```yaml egress: - type: Kafka config: bootstrap_servers: ${KAFKA_BOOTSTRAP_SERVERS} topics: ml-predictions: serializer: type: confluent_avro registry_url: ${SCHEMA_REGISTRY_URL} schema_file: prediction_event.avsc auth: # a user name and a password - ${REGISTRY_USER} - ${REGISTRY_PASSWORD} verify: ${REGISTRY_CA_FILE} # true, false or a CA file or directory cert: # a client certificate file and its key file - ${REGISTRY_CERT_FILE} - ${REGISTRY_KEY_FILE} headers: {X-Team: shop} # added to every request proxy: http://proxy.example.com:3128 timeout: 30 # seconds for each step of a request max_retries: 5 ``` ```python import os import ssl from avro_and_pydantic_models import PredictionRecord from desflow import KafkaEgress from desflow.connectors.egress.kafka import ConfluentAvroSerializer def registry_egress() -> KafkaEgress: """The egress of the Avro shop, with a serializer for a secured registry.""" serializer = ConfluentAvroSerializer( registry_url=os.environ["SCHEMA_REGISTRY_URL"], schema_str=PredictionRecord.avro_schema(), auth=(os.environ["REGISTRY_USER"], os.environ["REGISTRY_PASSWORD"]), # True, False, a CA file or directory, or an ssl.SSLContext verify=ssl.create_default_context(cafile=os.environ["REGISTRY_CA_FILE"]), # A client certificate file and its key file cert=(os.environ["REGISTRY_CERT_FILE"], os.environ["REGISTRY_KEY_FILE"]), headers={"X-Team": "shop"}, # added to every request proxy="http://proxy.example.com:3128", timeout=30, # seconds for each step of a request max_retries=5, ) return KafkaEgress( bootstrap_servers=os.environ["KAFKA_BOOTSTRAP_SERVERS"], topics={"ml-predictions": {"serializer": serializer}}, ) ``` ```python def build(egress: KafkaEgress) -> SimulationContext: """Builds the shop of Use Avro and Pydantic, with `egress` as its one sink.""" app = ( SimulationContext(sim_id="Shop", factor=0, random_seed=42) .add_resource("packers", current_cap=1, max_cap=1) .add_service("packing", dist="constant", value=1.5) .add_arrival("orders", dist="exponential", rate=0.5) .add_egress(egress) ) @app.task(service_id="packing", resource_id="packers") def pack_order(task_id: int, entity): prediction = MLPrediction(task_id=entity.key, confidence=0.9) return {**prediction.model_dump(), "__topic__": "ml-predictions"} @app.arrival_loop("orders") def orders(context: SimulationContext): while True: order = yield context.wait_for_arrival("orders") context.spawn(pack_order(context.next_instance("pack_order"), entity=order)) return app if __name__ == "__main__": logging.basicConfig(level=logging.INFO, format="%(levelname)s %(message)s") build(registry_egress()).run(until="1 min") ``` ```python import os import ssl from avro_and_pydantic_models import PredictionRecord from desflow import KafkaEgress from desflow.connectors.egress.kafka import ConfluentAvroSerializer def registry_egress() -> KafkaEgress: """The egress of the Avro shop, with a serializer for a secured registry.""" serializer = ConfluentAvroSerializer( registry_url=os.environ["SCHEMA_REGISTRY_URL"], schema_str=PredictionRecord.avro_schema(), auth=(os.environ["REGISTRY_USER"], os.environ["REGISTRY_PASSWORD"]), # True, False, a CA file or directory, or an ssl.SSLContext verify=ssl.create_default_context(cafile=os.environ["REGISTRY_CA_FILE"]), # A client certificate file and its key file cert=(os.environ["REGISTRY_CERT_FILE"], os.environ["REGISTRY_KEY_FILE"]), headers={"X-Team": "shop"}, # added to every request proxy="http://proxy.example.com:3128", timeout=30, # seconds for each step of a request max_retries=5, ) return KafkaEgress( bootstrap_servers=os.environ["KAFKA_BOOTSTRAP_SERVERS"], topics={"ml-predictions": {"serializer": serializer}}, ) ``` ```python if __name__ == "__main__": logging.basicConfig( level=logging.INFO, format="%(levelname)s [%(asctime)s] %(message)s" ) env = shop([registry_egress()]) # the shop of Use Avro and Pydantic try: env.run(until=60) finally: env.teardown() ``` A request to the registry that times out is retried up to `max_retries` times with a short random wait. With the defaults, `timeout: 10` and `max_retries: 3`, a request takes up to about 50 seconds for each registry URL. A larger `timeout` or `max_retries` makes it longer, and `timeout: null` sets no limit. The Kafka sink and the Kafka source wait for the registry in a worker thread, so the other sinks and sources of the run go on. When the registry fails for a time (a 5xx answer, a timeout or a lost connection) or throttles the call (a 408 or 429 answer, or the Glue error `ThrottlingException`), the Kafka sink keeps the batch and encodes it again after a wait that grows to one minute, with its connection to Kafka open. When the registry refuses the credentials or the access (a 401 or 403 answer, or the Glue error `AccessDeniedException`, or a Glue client that finds no credentials), it would refuse every record, so the Kafka sink or the Kafka source stops. The run logs a line at ERROR that starts with `Egress KafkaEgress stopped:` or `Ingress KafkaIngress stopped:` and gives the registry's error. When the registry refuses one record (any other 4xx answer, or a value the schema cannot encode), the sink skips that record with a warning that names its key and sends the rest of the batch. The Kafka source logs the error and skips that message, and the next message asks the registry again. The simulation goes on while each sink's queue has room. Once a queue stays full, the run stops with an error, as [Egress](https://jaehyeon.me/desflow/latest/user-guide/live-runs-and-connectors/egress/#how-it-works) describes. The JSON Schema and Protobuf serializers of [Use Schema Serializers](https://jaehyeon.me/desflow/latest/how-to/records-and-kafka/json-schema-and-protobuf/index.md) take the same arguments. The AWS Glue serializers do not: they take `registry_name` and `boto3`. ______________________________________________________________________ ## Check the Result Set `KAFKA_BOOTSTRAP_SERVERS`, `KAFKA_API_KEY` and `KAFKA_API_SECRET`, then run `desflow run kafka_security.yaml`, `python kafka_security.py` or `python kafka_security_low_level.py`. Each runs for one simulated minute, ends at once and publishes the same events to `sim-events`. The mTLS and MSK steps run the same shop. Run `desflow run kafka_security_mtls.yaml` or `desflow run kafka_security_msk.yaml`, or set `KAFKA_CONNECTION=mtls` or `KAFKA_CONNECTION=msk` (with the variables of the mTLS step, `KAFKA_CA_FILE`, `KAFKA_CERT_FILE` and `KAFKA_KEY_FILE`) before `python kafka_security.py` or `python kafka_security_low_level.py`. The secured registry runs with `desflow run kafka_security_registry.yaml`, `python kafka_security_registry.py` or `python kafka_security_registry_low_level.py`. The Kafka ingress and `KafkaAdminConnector` take the same security settings in their `config`: see [Ingress](https://jaehyeon.me/desflow/latest/user-guide/live-runs-and-connectors/ingress/#kafka). To read the events back, run the connections file with the SASL variables. Its last lines build a consumer from the same settings and print the first events of `sim-events`: ```python import asyncio from aiokafka import AIOKafkaConsumer async def show_events(count: int = 3) -> None: """Prints the first events of sim-events, read with the settings of the SASL egress.""" consumer = AIOKafkaConsumer( "sim-events", **sasl_connection(), auto_offset_reset="earliest" ) await consumer.start() try: for _ in range(count): message = await asyncio.wait_for(consumer.getone(), timeout=10) print(message.value.decode()) finally: await consumer.stop() if __name__ == "__main__": asyncio.run(show_events()) ``` ```bash python kafka_security_connections.py ``` ```text {"sim_ts":0.6283113312939436,"timestamp":"2026-11-09T00:00:00.628+00:00","key":"orders-1","task":"pack_order","instance":0,"value":{"path_id":"Shop.service.packing","sim_id":"Shop","service":"packing","status":"queued"}} {"sim_ts":0.6283113312939436,"timestamp":"2026-11-09T00:00:00.628+00:00","key":"orders-1","task":"pack_order","instance":0,"value":{"path_id":"Shop.service.packing","sim_id":"Shop","service":"packing","status":"started"}} {"sim_ts":2.1283113312939435,"timestamp":"2026-11-09T00:00:02.128+00:00","key":"orders-1","task":"pack_order","instance":0,"value":{"event_type":"order_packed"}} ``` Each line is one event as JSON. The `timestamp` is the clock time of your run. ______________________________________________________________________ ## Full Files The Builder and Low-level scripts import the egresses of `kafka_security_connections.py`, which builds no shop, so keep the files in one folder. Full files ```python """The secured Kafka connections of the Connect to Secure Kafka page. The Builder and Low-level forms of the shop import their egress from this file: kafka_security.py (builder) and kafka_security_low_level.py use it directly, and the YAML files set the same keys in the `config` of their sink. It builds no simulation. Each function builds the egress of one kind of cluster, and `selected_egress()` picks one by the variable KAFKA_CONNECTION: sasl (the default), mtls or msk. The SASL egress reads KAFKA_BOOTSTRAP_SERVERS, KAFKA_API_KEY and KAFKA_API_SECRET, the mTLS egress reads KAFKA_BOOTSTRAP_SERVERS, KAFKA_CA_FILE, KAFKA_CERT_FILE and KAFKA_KEY_FILE, and the MSK egress calls AWS when the sink starts. `registry_egress()` needs avro_and_pydantic_models.py of Use Avro and Pydantic beside this file, and the registry variables of kafka_security_registry.yaml. After a shop has run with the SASL egress, `python kafka_security_connections.py` prints the first events of sim-events. """ # Each section carries its own imports, as the page shows it. # ruff: noqa: E402, F811 import os from typing import Any, Dict from desflow import KafkaEgress def sasl_connection() -> Dict[str, Any]: """The settings of a cluster that uses SASL. The environment holds the credentials.""" return dict( bootstrap_servers=os.environ["KAFKA_BOOTSTRAP_SERVERS"], # Passed as they are to the Kafka client security_protocol="SASL_SSL", sasl_mechanism="PLAIN", # or SCRAM-SHA-512 sasl_plain_username=os.environ["KAFKA_API_KEY"], sasl_plain_password=os.environ["KAFKA_API_SECRET"], ) def sasl_egress() -> KafkaEgress: """The egress of a cluster that uses SASL.""" return KafkaEgress(**sasl_connection()) import os def mtls_egress() -> KafkaEgress: """The egress of a cluster that requires mutual TLS.""" return KafkaEgress( bootstrap_servers=os.environ["KAFKA_BOOTSTRAP_SERVERS"], security_protocol="SSL", # The arguments of aiokafka.helpers.create_ssl_context ssl={ "cafile": os.environ["KAFKA_CA_FILE"], "certfile": os.environ["KAFKA_CERT_FILE"], "keyfile": os.environ["KAFKA_KEY_FILE"], }, ) def msk_egress() -> KafkaEgress: """The egress of an Amazon MSK cluster with IAM access control.""" return KafkaEgress( bootstrap_servers="b-1.my-msk.amazonaws.com:9098", security_protocol="SASL_SSL", sasl_mechanism="OAUTHBEARER", # The token comes from the AWS credentials of your environment or role sasl_oauth_token_provider={"type": "aws_msk_iam", "region": "us-east-1"}, ) import os import ssl from avro_and_pydantic_models import PredictionRecord from desflow import KafkaEgress from desflow.connectors.egress.kafka import ConfluentAvroSerializer def registry_egress() -> KafkaEgress: """The egress of the Avro shop, with a serializer for a secured registry.""" serializer = ConfluentAvroSerializer( registry_url=os.environ["SCHEMA_REGISTRY_URL"], schema_str=PredictionRecord.avro_schema(), auth=(os.environ["REGISTRY_USER"], os.environ["REGISTRY_PASSWORD"]), # True, False, a CA file or directory, or an ssl.SSLContext verify=ssl.create_default_context(cafile=os.environ["REGISTRY_CA_FILE"]), # A client certificate file and its key file cert=(os.environ["REGISTRY_CERT_FILE"], os.environ["REGISTRY_KEY_FILE"]), headers={"X-Team": "shop"}, # added to every request proxy="http://proxy.example.com:3128", timeout=30, # seconds for each step of a request max_retries=5, ) return KafkaEgress( bootstrap_servers=os.environ["KAFKA_BOOTSTRAP_SERVERS"], topics={"ml-predictions": {"serializer": serializer}}, ) import os def selected_egress() -> KafkaEgress: """The egress that KAFKA_CONNECTION names: sasl (the default), mtls or msk.""" makers = {"sasl": sasl_egress, "mtls": mtls_egress, "msk": msk_egress} return makers[os.environ.get("KAFKA_CONNECTION", "sasl")]() import asyncio from aiokafka import AIOKafkaConsumer async def show_events(count: int = 3) -> None: """Prints the first events of sim-events, read with the settings of the SASL egress.""" consumer = AIOKafkaConsumer( "sim-events", **sasl_connection(), auto_offset_reset="earliest" ) await consumer.start() try: for _ in range(count): message = await asyncio.wait_for(consumer.getone(), timeout=10) print(message.value.decode()) finally: await consumer.stop() if __name__ == "__main__": asyncio.run(show_events()) ``` ```yaml # The Connect to Secure Kafka guide: a shop that publishes its events to a cluster # that uses SASL PLAIN, such as Confluent Cloud. Set KAFKA_BOOTSTRAP_SERVERS, # KAFKA_API_KEY and KAFKA_API_SECRET, then run it with: # desflow run kafka_security.yaml simulation: {sim_id: Shop, factor: 0, random_seed: 42} resources: packers: {current_cap: 1, max_cap: 1} services: packing: {dist: constant, value: 1.5} arrivals: orders: {dist: exponential, rate: 0.5, spawn: pack_order} tasks: pack_order: service: packing resource: packers payload: {event_type: order_packed} egress: - type: Kafka config: bootstrap_servers: ${KAFKA_BOOTSTRAP_SERVERS:-pkc-xxxx.us-east-1.aws.confluent.cloud:9092} # Passed as they are to the Kafka client security_protocol: SASL_SSL sasl_mechanism: PLAIN # or SCRAM-SHA-512 sasl_plain_username: ${KAFKA_API_KEY:-} sasl_plain_password: ${KAFKA_API_SECRET:-} run: {until: 1 min} ``` ```yaml # The Connect to Secure Kafka guide: a shop that publishes its events to a cluster that # requires mutual TLS. Set KAFKA_BOOTSTRAP_SERVERS, KAFKA_CA_FILE, KAFKA_CERT_FILE and # KAFKA_KEY_FILE, then run it with: desflow run kafka_security_mtls.yaml simulation: {sim_id: Shop, factor: 0, random_seed: 42} egress: - type: Kafka config: bootstrap_servers: ${KAFKA_BOOTSTRAP_SERVERS} security_protocol: SSL # The arguments of aiokafka.helpers.create_ssl_context ssl: cafile: ${KAFKA_CA_FILE} certfile: ${KAFKA_CERT_FILE} keyfile: ${KAFKA_KEY_FILE} resources: packers: {current_cap: 1, max_cap: 1} services: packing: {dist: constant, value: 1.5} arrivals: orders: {dist: exponential, rate: 0.5, spawn: pack_order} tasks: pack_order: service: packing resource: packers payload: {event_type: order_packed} run: {until: 1 min} ``` ```yaml # The Connect to Secure Kafka guide: a shop that publishes its events to Amazon MSK with # IAM access control. Needs the package aws-msk-iam-sasl-signer-python and AWS # credentials in the environment. Run it with: desflow run kafka_security_msk.yaml simulation: {sim_id: Shop, factor: 0, random_seed: 42} egress: - type: Kafka config: bootstrap_servers: b-1.my-msk.amazonaws.com:9098 security_protocol: SASL_SSL sasl_mechanism: OAUTHBEARER # The token comes from the AWS credentials of your environment or role sasl_oauth_token_provider: {type: aws_msk_iam, region: us-east-1} resources: packers: {current_cap: 1, max_cap: 1} services: packing: {dist: constant, value: 1.5} arrivals: orders: {dist: exponential, rate: 0.5, spawn: pack_order} tasks: pack_order: service: packing resource: packers payload: {event_type: order_packed} run: {until: 1 min} ``` ```yaml # The Connect to Secure Kafka guide: the shop of Use Avro and Pydantic, with its # predictions serialized through a schema registry that needs a user name, a client # certificate and more. Needs prediction_event.avsc from Use Avro and Pydantic beside # it. Set KAFKA_BOOTSTRAP_SERVERS, SCHEMA_REGISTRY_URL, REGISTRY_USER, # REGISTRY_PASSWORD, REGISTRY_CA_FILE, REGISTRY_CERT_FILE and REGISTRY_KEY_FILE, then # run it with: desflow run kafka_security_registry.yaml simulation: {sim_id: Shop, factor: 0, random_seed: 42} egress: - type: Kafka config: bootstrap_servers: ${KAFKA_BOOTSTRAP_SERVERS} topics: ml-predictions: serializer: type: confluent_avro registry_url: ${SCHEMA_REGISTRY_URL} schema_file: prediction_event.avsc auth: # a user name and a password - ${REGISTRY_USER} - ${REGISTRY_PASSWORD} verify: ${REGISTRY_CA_FILE} # true, false or a CA file or directory cert: # a client certificate file and its key file - ${REGISTRY_CERT_FILE} - ${REGISTRY_KEY_FILE} headers: {X-Team: shop} # added to every request proxy: http://proxy.example.com:3128 timeout: 30 # seconds for each step of a request max_retries: 5 resources: packers: {current_cap: 1, max_cap: 1} services: packing: {dist: constant, value: 1.5} arrivals: orders: {dist: exponential, rate: 0.5, spawn: pack_order} tasks: pack_order: service: packing resource: packers # The finished event is a prediction for the order: the fields of MLPrediction payload: __topic__: ml-predictions event_type: prediction task_id: {gen: entity} confidence: 0.9 run: {until: 1 min} ``` ```python """The shop of the Connect to Secure Kafka page, built with the builder API. `build(egress)` gives the shop with the egress it is given. Run `python kafka_security.py` to publish to a cluster that uses SASL PLAIN, such as Confluent Cloud: set KAFKA_BOOTSTRAP_SERVERS, KAFKA_API_KEY and KAFKA_API_SECRET. Set KAFKA_CONNECTION to mtls or msk to publish to a cluster of that kind instead, as kafka_security_connections.py sets out. That file, which holds the egresses, must be beside this one. """ # ruff: noqa: E402 import logging from kafka_security_connections import ( msk_egress, mtls_egress, sasl_egress, selected_egress, ) from desflow import KafkaEgress, SimulationContext def build(egress: KafkaEgress) -> SimulationContext: """Builds the shop, with `egress` as its one sink.""" app = ( SimulationContext(sim_id="Shop", factor=0, random_seed=42) .add_resource("packers", current_cap=1, max_cap=1) .add_service("packing", dist="constant", value=1.5) .add_arrival("orders", dist="exponential", rate=0.5) .add_egress(egress) ) @app.task(service_id="packing", resource_id="packers") def pack_order(task_id: int): return {"event_type": "order_packed"} @app.arrival_loop("orders") def orders(context: SimulationContext): while True: order = yield context.wait_for_arrival("orders") context.spawn(pack_order(context.next_instance("pack_order"), entity=order)) return app if __name__ == "__main__": logging.basicConfig( level=logging.INFO, format="%(levelname)s [%(asctime)s] %(message)s" ) build(selected_egress()).run(until="1 min") def sasl_app() -> SimulationContext: """The shop with the egress of a cluster that uses SASL.""" return build(sasl_egress()) def mtls_app() -> SimulationContext: """The shop with the egress of a cluster that requires mutual TLS.""" return build(mtls_egress()) def msk_app() -> SimulationContext: """The shop with the egress of an Amazon MSK cluster.""" return build(msk_egress()) ``` ```python """The shop of Use Avro and Pydantic, built with the builder API, with its predictions serialized through a secured schema registry. The egress is `registry_egress()` of kafka_security_connections.py, which needs avro_and_pydantic_models.py of Use Avro and Pydantic beside it. Set the variables of kafka_security_registry.yaml, then run `python kafka_security_registry.py`. It runs for one minute. """ import logging from avro_and_pydantic_models import MLPrediction from kafka_security_connections import registry_egress from desflow import KafkaEgress, SimulationContext def build(egress: KafkaEgress) -> SimulationContext: """Builds the shop of Use Avro and Pydantic, with `egress` as its one sink.""" app = ( SimulationContext(sim_id="Shop", factor=0, random_seed=42) .add_resource("packers", current_cap=1, max_cap=1) .add_service("packing", dist="constant", value=1.5) .add_arrival("orders", dist="exponential", rate=0.5) .add_egress(egress) ) @app.task(service_id="packing", resource_id="packers") def pack_order(task_id: int, entity): prediction = MLPrediction(task_id=entity.key, confidence=0.9) return {**prediction.model_dump(), "__topic__": "ml-predictions"} @app.arrival_loop("orders") def orders(context: SimulationContext): while True: order = yield context.wait_for_arrival("orders") context.spawn(pack_order(context.next_instance("pack_order"), entity=order)) return app if __name__ == "__main__": logging.basicConfig(level=logging.INFO, format="%(levelname)s %(message)s") build(registry_egress()).run(until="1 min") ``` ```python """The Connect to Secure Kafka guide, low-level API: a shop that publishes its events through the egress of kafka_security_connections.py, which must be beside this script. Set KAFKA_BOOTSTRAP_SERVERS, KAFKA_API_KEY and KAFKA_API_SECRET, then run `python kafka_security_low_level.py`. It runs for one minute and publishes to a cluster that uses SASL. Set KAFKA_CONNECTION to mtls or msk to publish to a cluster of that kind instead, as kafka_security_connections.py sets out. """ import itertools import logging from kafka_security_connections import msk_egress, mtls_egress, selected_egress from desflow import ( CapacityConfig, DistributionConfig, DynamicRealtimeEnvironment, DynamicResource, Sampler, SimParameter, ) PARAMS = SimParameter( sim_id="Shop", arrival={"orders": DistributionConfig(dist="exponential", rate=0.5)}, service={"packing": DistributionConfig(dist="constant", value=1.5)}, resources={"packers": CapacityConfig(current_cap=1, max_cap=1)}, ) def pack_order(env, packers, sampler, key, task_id): path_id = "Shop.service.packing" env.publish_event( key, { "path_id": path_id, "sim_id": "Shop", "service": "packing", "status": "queued", }, "pack_order", task_id, ) with packers.request() as unit: yield unit env.publish_event( key, { "path_id": path_id, "sim_id": "Shop", "service": "packing", "status": "started", }, "pack_order", task_id, ) yield env.timeout(sampler.sample(env.registry.get_config(path_id))) env.publish_event(key, {"event_type": "order_packed"}, "pack_order", task_id) def orders(env, packers, sampler): gap = env.registry.get_config("Shop.arrival.orders") for number in itertools.count(1): yield env.timeout(sampler.sample(gap)) env.process(pack_order(env, packers, sampler, f"orders-{number}", number - 1)) def shop(sinks: list, factor: float = 0.0) -> DynamicRealtimeEnvironment: """The shop, publishing to the sinks given.""" env = DynamicRealtimeEnvironment(factor=factor) env.registry.register_sim_parameter(PARAMS) env.setup_egress(sinks) packers = DynamicResource(env, "Shop", "packers") env.process(orders(env, packers, Sampler(seed=42))) return env if __name__ == "__main__": logging.basicConfig( level=logging.INFO, format="%(levelname)s [%(asctime)s] %(message)s" ) env = shop([selected_egress()]) # KAFKA_CONNECTION picks the cluster try: env.run(until=60) finally: env.teardown() def mtls_shop() -> DynamicRealtimeEnvironment: """The shop with the egress of a cluster that requires mutual TLS.""" return shop([mtls_egress()]) def msk_shop() -> DynamicRealtimeEnvironment: """The shop with the egress of an Amazon MSK cluster.""" return shop([msk_egress()]) ``` ```python """The shop of Use Avro and Pydantic, low-level API, with its predictions serialized through a secured schema registry. The egress is `registry_egress()` of kafka_security_connections.py, and the shop is that of avro_and_pydantic_low_level.py. Both files, and avro_and_pydantic_models.py, must be beside this script. Set the variables of kafka_security_registry.yaml, then run `python kafka_security_registry_low_level.py`. It runs for one minute. """ import logging from avro_and_pydantic_low_level import shop from kafka_security_connections import registry_egress if __name__ == "__main__": logging.basicConfig( level=logging.INFO, format="%(levelname)s [%(asctime)s] %(message)s" ) env = shop([registry_egress()]) # the shop of Use Avro and Pydantic try: env.run(until=60) finally: env.teardown() ``` # Write a Connector Write a connector of your own when a model must read changes from, or write records to, a system that desflow has no connector for. This page writes an egress that writes each event as a row of a CSV file, and an ingress that follows a JSON Lines file of changes. Neither needs a service. ______________________________________________________________________ ## Before You Start - [Ingress](https://jaehyeon.me/desflow/latest/user-guide/live-runs-and-connectors/ingress/index.md) and [Egress](https://jaehyeon.me/desflow/latest/user-guide/live-runs-and-connectors/egress/index.md) describe the connectors desflow has and the threads they run on. ______________________________________________________________________ ## Steps ### Write an Egress An egress subclasses `BaseEgress` and has one method, `async run(queue)`. desflow runs it on the egress thread's asyncio loop, apart from the simulation. The queue holds batches: each batch is a list of records, in the [record shape](https://jaehyeon.me/desflow/latest/reference/records-and-telemetry/#record-shape) every sink receives. `run` takes a batch with `get_nowait`, and sleeps when the queue is empty so the other connectors on the loop can run: ```python class CsvEgress(BaseEgress): """Writes one CSV row per record it is given: its time, key and task, then the payload fields that `columns` names. The sink's `when` keeps telemetry out.""" def __init__(self, path: str, columns: List[str]): self.path = Path(path) self.columns = list(columns) self.active_tasks = 0 # teardown waits while a write is in progress async def run(self, egress_queue: queue.Queue) -> None: with self.path.open("w", newline="") as file: writer = csv.writer(file) writer.writerow(["sim_ts", "key", "task", *self.columns]) while True: try: batch = egress_queue.get_nowait() except queue.Empty: await asyncio.sleep(0.1) # let the other connectors run continue self.active_tasks += 1 try: rows = [self._row(record) for record in batch] # A file write blocks, so it runs on a worker thread await asyncio.to_thread(self._write, file, writer, rows) finally: self.active_tasks -= 1 def _row(self, record: dict) -> list: value = record["value"] if isinstance(record.get("value"), dict) else {} fields = [value.get(column) for column in self.columns] return [record["sim_ts"], record.get("key"), record.get("task"), *fields] @staticmethod def _write(file, writer, rows: list) -> None: writer.writerows(rows) file.flush() ``` Three rules apply to every egress: - **Do not block the loop.** A write that blocks, such as a file write or a client without `async`, runs on a worker thread with `asyncio.to_thread`. - **Count the writes in progress.** At the end of the run, teardown waits for every queue to empty, then waits while the sink's `active_tasks` is above 0. A batch taken from the queue but not yet written is therefore not lost. - **Copy before you change a record.** Every sink receives the same dictionaries, so a sink that changes one in place changes what the others write. This sink builds new rows. An error that ends `run` is logged at ERROR with the connector's name. The sink then takes no more batches, so once its queue is full the simulation waits, and after `drain_stall_seconds` the run raises `RuntimeError`, as [Egress](https://jaehyeon.me/desflow/latest/user-guide/live-runs-and-connectors/egress/#how-it-works) describes. ### Write an Ingress An ingress subclasses `BaseIngress` and has one method too, `async run(queue)`, which desflow runs on the ingress thread. It puts each change on the queue as a `(path, value)` pair. `parse_change` turns a message such as `{"path": "Shop.resources.packers.current_cap", "value": 2}` into that pair, with the check the built-in connectors use. The ingress monitor applies what is queued every 0.1 simulation seconds, and the registry checks each value before it stores it ([Live Parameters](https://jaehyeon.me/desflow/latest/user-guide/live-runs-and-connectors/live-parameters/#how-it-works)): ```python class JsonlIngress(BaseIngress): """Follows a JSON Lines file and applies each line it adds, such as `{"path": "Shop.resources.packers.current_cap", "value": 2}`.""" def __init__(self, path: str, poll: float = 0.1): self.path = Path(path) self.poll = poll async def run(self, ingress_queue: queue.Queue) -> None: read = 0 # the lines already applied while True: if self.path.exists(): # A file read blocks, so it runs on a worker thread text = await asyncio.to_thread(self.path.read_text) # Only whole lines: a writer may be partway through the last one lines = text[: text.rfind("\n") + 1].splitlines() for line in lines[read:]: try: ingress_queue.put(parse_change(json.loads(line))) except ValueError as error: # also a line that is not JSON logger.warning("Skipped a line of %s: %s", self.path, error) read = len(lines) await asyncio.sleep(self.poll) ``` A line of the file that is not a change is logged as one WARNING and skipped, as the built-in connectors do, so one bad message does not stop the run. At the end of the run desflow cancels `run`, so it needs no way to stop. ### Use Them A connector of your own goes where a built-in one goes. Each `config` key is an argument of the class's constructor. An egress receives every event and telemetry record, and `when` limits it, as [Egress](https://jaehyeon.me/desflow/latest/user-guide/live-runs-and-connectors/egress/#choose-what-each-sink-gets) shows. This sink takes events only. ```yaml ingress: - type: !python write_a_connector_logic.JsonlIngress config: {path: changes.jsonl} egress: - type: !python write_a_connector_logic.CsvEgress when: events # events only; the readings of telemetry stay out of the file config: {path: events.csv, columns: [status, event_type]} ``` The classes are in `write_a_connector_logic.py`, beside the blueprint. `type: !python` names the class, and the loader builds it with `config` as its arguments. ```python app = ( SimulationContext(sim_id="Shop", factor=0.05, random_seed=42) .add_resource("packers", current_cap=1, max_cap=3) .add_service("packing", dist="constant", value=1.5) .add_arrival("orders", dist="constant", value=1.0) .add_ingress(JsonlIngress("changes.jsonl")) .add_egress( CsvEgress("events.csv", columns=["status", "event_type"]), when=lambda record: record["stream_type"] == "event", # no telemetry ) ) @app.task(service_id="packing", resource_id="packers") def pack_order(task_id: int): return {"event_type": "order_packed"} @app.arrival_loop("orders") def order_generator(context: SimulationContext): while True: order = yield context.wait_for_arrival("orders") context.spawn(pack_order(context.next_instance("pack_order"), entity=order)) app.run(until=20) ``` ```python env = DynamicRealtimeEnvironment(factor=0.05) env.registry.register_sim_parameter( SimParameter( sim_id="Shop", service={"packing": DistributionConfig(dist="constant", value=1.5)}, resources={"packers": CapacityConfig(current_cap=1, max_cap=3)}, ) ) env.setup_ingress([JsonlIngress("changes.jsonl")]) env.setup_egress( [CsvEgress("events.csv", columns=["status", "event_type"])], predicates=[lambda record: record["stream_type"] == "event"], # no telemetry ) packers = DynamicResource(env, "Shop", "packers") def order(env, number): key, path_id = f"orders-{number}", "Shop.service.packing" env.publish_event( key, { "path_id": path_id, "sim_id": "Shop", "service": "packing", "status": "queued", }, "pack_order", number - 1, ) with packers.request() as request: yield request env.publish_event( key, { "path_id": path_id, "sim_id": "Shop", "service": "packing", "status": "started", }, "pack_order", number - 1, ) yield env.timeout(1.5) env.publish_event(key, {"event_type": "order_packed"}, "pack_order", number - 1) def arrivals(env): number = 0 while True: yield env.timeout(1.0) number += 1 env.process(order(env, number)) env.process(arrivals(env)) try: env.run(until=20) finally: env.teardown() # writes what is still buffered and stops the threads ``` The low-level API attaches the same objects with `setup_ingress` and `setup_egress`, and `teardown` waits for the CSV sink to write what is still queued. The shop is paced at `factor: 0.05`, so 20 simulation seconds pass in each real second, and the run lasts one second of real time. An ingress reads its source while time passes, and a run at `factor: 0` can end before the source is read once. ______________________________________________________________________ ## Check the Result Before the run, `changes.jsonl` holds one line, which sets the packers to 2 units. An order arrives every second from 1 second, and each takes 1.5 seconds, so one packer would fall behind. The ingress applies the change in the first moments of the run, and from then on each order starts when it arrives. The first rows of `events.csv`: ```text sim_ts,key,task,status,event_type 1.0,orders-1,pack_order,queued, 1.0,orders-1,pack_order,started, 2.0,orders-2,pack_order,queued, 2.0,orders-2,pack_order,started, 2.5,orders-1,pack_order,,order_packed ``` `orders-2` starts at 2 seconds while `orders-1` is still being packed, so the second unit is there. By 20 seconds, 19 orders have arrived and started, and the 18 that arrived by 18 seconds are packed. That is 19 `queued`, 19 `started` and 18 `order_packed` events: 56 rows. All three forms write the same rows. Save the files that the tab of your form names from [Full Files](#full-files) in one folder, each under the last part of its title, and run the command of your form from that folder: Save `write_a_connector.yaml` and `write_a_connector_logic.py`. The first line writes the change that the ingress reads. The blueprint does not write it: ```bash echo '{"path": "Shop.resources.packers.current_cap", "value": 2}' > changes.jsonl desflow run write_a_connector.yaml head -n 6 events.csv wc -l events.csv ``` ```text sim_ts,key,task,status,event_type 1.0,orders-1,pack_order,queued, 1.0,orders-1,pack_order,started, 2.0,orders-2,pack_order,queued, 2.0,orders-2,pack_order,started, 2.5,orders-1,pack_order,,order_packed 57 events.csv ``` The 57 lines are the header and the 56 rows. The spaces before the count depend on your system. Save `write_a_connector.py`, `write_a_connector_logic.py` and the blueprint `write_a_connector.yaml`, because the script runs the YAML form first. `python write_a_connector.py` writes `changes.jsonl`, runs the YAML form and then the builder form, and prints the packers' units at the end and the number of rows in `events.csv` for each: ```text yaml_form packers: 2, rows in events.csv: 56 builder_form packers: 2, rows in events.csv: 56 ``` Save `write_a_connector_low_level.py` and `write_a_connector_logic.py`. `python write_a_connector_low_level.py` does the same for the low-level form: ```text low_level_form packers: 2, rows in events.csv: 56 ``` ______________________________________________________________________ ## Full Files Every form uses the two connectors in `write_a_connector_logic.py` unchanged. Put it, the blueprint and the scripts in one folder, and run the scripts from there. Full files ```python """Python for write_a_connector.yaml: an egress that writes events to a CSV file and an ingress that follows a JSON Lines file of changes, as the Write a Connector guide builds them.""" import asyncio import csv import json import logging import queue from pathlib import Path from typing import List from desflow.connectors.egress.base import BaseEgress from desflow.connectors.ingress.base import BaseIngress, parse_change logger = logging.getLogger(__name__) class CsvEgress(BaseEgress): """Writes one CSV row per record it is given: its time, key and task, then the payload fields that `columns` names. The sink's `when` keeps telemetry out.""" def __init__(self, path: str, columns: List[str]): self.path = Path(path) self.columns = list(columns) self.active_tasks = 0 # teardown waits while a write is in progress async def run(self, egress_queue: queue.Queue) -> None: with self.path.open("w", newline="") as file: writer = csv.writer(file) writer.writerow(["sim_ts", "key", "task", *self.columns]) while True: try: batch = egress_queue.get_nowait() except queue.Empty: await asyncio.sleep(0.1) # let the other connectors run continue self.active_tasks += 1 try: rows = [self._row(record) for record in batch] # A file write blocks, so it runs on a worker thread await asyncio.to_thread(self._write, file, writer, rows) finally: self.active_tasks -= 1 def _row(self, record: dict) -> list: value = record["value"] if isinstance(record.get("value"), dict) else {} fields = [value.get(column) for column in self.columns] return [record["sim_ts"], record.get("key"), record.get("task"), *fields] @staticmethod def _write(file, writer, rows: list) -> None: writer.writerows(rows) file.flush() class JsonlIngress(BaseIngress): """Follows a JSON Lines file and applies each line it adds, such as `{"path": "Shop.resources.packers.current_cap", "value": 2}`.""" def __init__(self, path: str, poll: float = 0.1): self.path = Path(path) self.poll = poll async def run(self, ingress_queue: queue.Queue) -> None: read = 0 # the lines already applied while True: if self.path.exists(): # A file read blocks, so it runs on a worker thread text = await asyncio.to_thread(self.path.read_text) # Only whole lines: a writer may be partway through the last one lines = text[: text.rfind("\n") + 1].splitlines() for line in lines[read:]: try: ingress_queue.put(parse_change(json.loads(line))) except ValueError as error: # also a line that is not JSON logger.warning("Skipped a line of %s: %s", self.path, error) read = len(lines) await asyncio.sleep(self.poll) ``` ```yaml # The Write a Connector guide: a shop whose packers follow a file of changes and # whose events go to a CSV file, through two connectors of its own. # Write changes.jsonl first (the line is in the Check the Result section of the page), # then run it with: desflow run write_a_connector.yaml # In a folder with no changes.jsonl, it keeps one packer. simulation: sim_id: Shop factor: 0.05 # 20 simulation seconds a second, so the file is read during the run random_seed: 42 resources: packers: {current_cap: 1, max_cap: 3} services: packing: {dist: constant, value: 1.5 s} arrivals: orders: {dist: constant, value: 1 s, spawn: pack_order} tasks: pack_order: service: packing resource: packers payload: {event_type: order_packed} ingress: - type: !python write_a_connector_logic.JsonlIngress config: {path: changes.jsonl} egress: - type: !python write_a_connector_logic.CsvEgress when: events # events only; the readings of telemetry stay out of the file config: {path: events.csv, columns: [status, event_type]} run: {until: 20 s} ``` ```python """Write a Connector: an egress that writes events to a CSV file and an ingress that follows a JSON Lines file of changes. An order arrives every second and each takes 1.5 seconds to pack, so one packer falls behind. Before the run, changes.jsonl holds one change that sets the packers to 2. The ingress applies it at the start, and the events go to events.csv. Each function runs the shop in the current folder, in YAML or in the builder, and returns the packers' capacity at the end and the rows of events.csv. write_a_connector_low_level.py is the low-level API. """ import csv import json import logging import sys from pathlib import Path from desflow import SimulationContext HERE = Path(__file__).resolve().parent sys.path.insert(0, str(HERE)) # write_a_connector_logic.py is beside the blueprint from write_a_connector_logic import CsvEgress, JsonlIngress # noqa: E402 logging.basicConfig( level=logging.WARNING, format="%(levelname)s [%(asctime)s] %(message)s" ) CHANGE = {"path": "Shop.resources.packers.current_cap", "value": 2} def _rows(): with open("events.csv", newline="") as file: return list(csv.DictReader(file)) def yaml_form(): """The blueprint beside the classes.""" Path("changes.jsonl").write_text(json.dumps(CHANGE) + "\n") app = SimulationContext.from_yaml(HERE / "write_a_connector.yaml") app.run() return app.get_resource("packers").capacity, _rows() def builder_form(): """The same shop with the builder.""" Path("changes.jsonl").write_text(json.dumps(CHANGE) + "\n") app = ( SimulationContext(sim_id="Shop", factor=0.05, random_seed=42) .add_resource("packers", current_cap=1, max_cap=3) .add_service("packing", dist="constant", value=1.5) .add_arrival("orders", dist="constant", value=1.0) .add_ingress(JsonlIngress("changes.jsonl")) .add_egress( CsvEgress("events.csv", columns=["status", "event_type"]), when=lambda record: record["stream_type"] == "event", # no telemetry ) ) @app.task(service_id="packing", resource_id="packers") def pack_order(task_id: int): return {"event_type": "order_packed"} @app.arrival_loop("orders") def order_generator(context: SimulationContext): while True: order = yield context.wait_for_arrival("orders") context.spawn(pack_order(context.next_instance("pack_order"), entity=order)) app.run(until=20) return app.get_resource("packers").capacity, _rows() if __name__ == "__main__": for form in (yaml_form, builder_form): capacity, rows = form() print( f"{form.__name__:15} packers: {capacity}, rows in events.csv: {len(rows)}" ) ``` ```python """Write a Connector, low-level API: the shop with the CSV egress and the JSON Lines ingress of write_a_connector_logic.py. The low-level version of write_a_connector.py. Before the run, changes.jsonl holds one change that sets the packers to 2. `low_level_form` runs the shop in the current folder and returns the packers' capacity at the end and the rows of events.csv. """ import csv import json import logging import sys from pathlib import Path from desflow import ( CapacityConfig, DistributionConfig, DynamicRealtimeEnvironment, DynamicResource, SimParameter, ) HERE = Path(__file__).resolve().parent sys.path.insert(0, str(HERE)) # write_a_connector_logic.py is beside the blueprint from write_a_connector_logic import CsvEgress, JsonlIngress # noqa: E402 logging.basicConfig( level=logging.WARNING, format="%(levelname)s [%(asctime)s] %(message)s" ) CHANGE = {"path": "Shop.resources.packers.current_cap", "value": 2} def _rows(): with open("events.csv", newline="") as file: return list(csv.DictReader(file)) def low_level_form(): """The same shop with the environment and the resource.""" Path("changes.jsonl").write_text(json.dumps(CHANGE) + "\n") env = DynamicRealtimeEnvironment(factor=0.05) env.registry.register_sim_parameter( SimParameter( sim_id="Shop", service={"packing": DistributionConfig(dist="constant", value=1.5)}, resources={"packers": CapacityConfig(current_cap=1, max_cap=3)}, ) ) env.setup_ingress([JsonlIngress("changes.jsonl")]) env.setup_egress( [CsvEgress("events.csv", columns=["status", "event_type"])], predicates=[lambda record: record["stream_type"] == "event"], # no telemetry ) packers = DynamicResource(env, "Shop", "packers") def order(env, number): key, path_id = f"orders-{number}", "Shop.service.packing" env.publish_event( key, { "path_id": path_id, "sim_id": "Shop", "service": "packing", "status": "queued", }, "pack_order", number - 1, ) with packers.request() as request: yield request env.publish_event( key, { "path_id": path_id, "sim_id": "Shop", "service": "packing", "status": "started", }, "pack_order", number - 1, ) yield env.timeout(1.5) env.publish_event(key, {"event_type": "order_packed"}, "pack_order", number - 1) def arrivals(env): number = 0 while True: yield env.timeout(1.0) number += 1 env.process(order(env, number)) env.process(arrivals(env)) try: env.run(until=20) finally: env.teardown() # writes what is still buffered and stops the threads return packers.capacity, _rows() if __name__ == "__main__": capacity, rows = low_level_form() print(f"low_level_form packers: {capacity}, rows in events.csv: {len(rows)}") ``` # Data at Scale Generate a dataset of the size you name, such as a month of orders for 1,000 customers, as one Parquet file for each day, and check that it is complete. The run needs no wall-clock time: it takes as long as the machine needs to compute the records. For the speed of one run, see [Tune Performance](https://jaehyeon.me/desflow/latest/how-to/tools/performance-tuning/index.md). This page is about the size of the data and how to split a job that is too large for one run. ______________________________________________________________________ ## Before You Start - [Write to Cloud Storage](https://jaehyeon.me/desflow/latest/how-to/storage-and-tables/cloud-storage/#write-a-file-for-each-day) explains `__path__` and how the sinks name their files. - [Time and Pacing](https://jaehyeon.me/desflow/latest/user-guide/time-and-pacing/index.md) explains `factor: 0` and `logical_start_time`. - Install the extra: `pip install "desflow[parquet]"`. - The code runs in a folder of your choice. The files go to `scale_output/`, or to the folder in `OUT`. `CUSTOMERS` and `DAYS` set the size, and a small value for each is the quickest way to try the page, such as `CUSTOMERS=20 DAYS=3`. ______________________________________________________________________ ## Steps ### Set the Span A run covers the period you want when it starts at the first day, runs without waiting, and stops at the last. `factor: 0` removes the wait, `logical_start_time` and `timezone` fix the calendar the file names are built from, and `run.until` is the length of the period: ```yaml simulation: sim_id: Shop factor: 0 random_seed: ${SEED:-42} timezone: UTC logical_start_time: "2026-01-01T00:00:00+00:00" run: {until: "${DAYS:-30} days"} ``` ```python def new_shop() -> SimulationContext: """A shop that runs without waiting and starts on 1 January 2026, UTC.""" return SimulationContext( sim_id="Shop", factor=0, random_seed=int(os.getenv("SEED", "42")), timezone="UTC", logical_start_time=datetime(2026, 1, 1, tzinfo=timezone.utc), ) ``` ```python def new_env() -> DynamicRealtimeEnvironment: """An environment that runs without waiting and starts on 1 January 2026, UTC.""" return DynamicRealtimeEnvironment( factor=0, logical_start_time=datetime(2026, 1, 1, tzinfo=timezone.utc), timezone="UTC", ) ``` The period is 30 days unless `DAYS` says otherwise. ### Set the Volume The number of records comes from how many entities there are and how often each one acts. This shop has 1,000 customers, and each orders after a gap of 12 to 36 hours, so a customer places about one order a day. `count` makes the customers, `key` gives each its name, and the gap is drawn again after every order. The month then holds about 30,000 orders. For a different volume, change `CUSTOMERS`, or the gap: ```yaml arrivals: # Each customer orders about once a day: a gap of 12 to 36 hours, drawn again after # each order customers: dist: uniform low: 43200 high: 129600 spawn: place_order count: ${CUSTOMERS:-1000} key: {gen: sequence, start: "${FIRST:-1}", format: "customer-{}"} ``` ```python def add_customers(app: SimulationContext) -> None: """One arrival for each customer, ordering about once a day (12 to 36 hours apart). A blueprint's `count` is one arrival here, each with its own key.""" for number in range(FIRST, FIRST + CUSTOMERS): app.add_arrival( f"customer-{number}", "uniform", low=43200, high=129600, spawn="place_order", key=lambda n, number=number: f"customer-{number}", ) ``` ```python def add_customers(env: DynamicRealtimeEnvironment) -> None: """One process for each customer, ordering about once a day (12 to 36 hours apart).""" sampler = Sampler(seed=int(os.getenv("SEED", "42"))) gap = DistributionConfig(dist="uniform", low=43200, high=129600) amounts = sampler.generator("tasks.place_order.payload.amount") sent = {"orders": 0} def customer(key): while True: yield env.timeout(sampler.sample(gap)) amount = round(float(amounts.normal(40, 10)), 2) order = order_row(env, key, sent["orders"], amount) env.publish_event(key, order, task="place_order", instance=sent["orders"]) sent["orders"] += 1 for number in range(FIRST, FIRST + CUSTOMERS): env.process(customer(f"customer-{number}")) ``` `keys` takes a list of names instead of `count` and `key`, for entities with names you choose. ### Write a File for Each Day `__path__` in the order sends it to the file of its day, as [Write to Cloud Storage](https://jaehyeon.me/desflow/latest/how-to/storage-and-tables/cloud-storage/#write-a-file-for-each-day) explains. A Parquet sink writes one file for each batch, so a `batch_size` of 10,000 makes a file of up to 10,000 rows instead of one for every 500 records, the default. A file name is the path with an eight-digit hexadecimal suffix, such as `2026-01-01_a28fed01.parquet`: ```yaml tasks: place_order: payload: # Numbered within the run, so the first customer of the run is part of the id order_id: {gen: sequence, format: "${FIRST:-1}-{}"} customer: {gen: entity} amount: {gen: normal, mean: 40, std: 10, decimals: 2} # The file of the order: the day it was placed, in the simulated calendar __path__: {gen: format_time, format: "${OUT:-scale_output}/%Y-%m-%d.parquet"} egress: - type: Parquet # One file for each batch, so a large batch gives few, large files batch_size: 10000 config: default_path: ${OUT:-scale_output}/other.parquet ``` ```python def add_files(app: SimulationContext) -> None: """A Parquet sink with a large batch, and an order that names the file of its day.""" # One file for each batch, so a large batch gives few, large files app.add_egress( ParquetStorageEgress(default_path=f"{OUT}/other.parquet"), batch_size=10000 ) order = Template( { # Numbered within the run, so the first customer of the run is part of the id "order_id": {"gen": "sequence", "format": f"{FIRST}-{{}}"}, "customer": {"gen": "entity"}, "amount": {"gen": "normal", "mean": 40, "std": 10, "decimals": 2}, # The file of the order: the day it was placed, in the simulated calendar "__path__": {"gen": "format_time", "format": f"{OUT}/%Y-%m-%d.parquet"}, }, name="tasks.place_order", ) @app.task(name="place_order") def place_order(task_id): return order ``` ```python def setup_files(env: DynamicRealtimeEnvironment) -> None: """A Parquet sink with a large batch. One file for each batch, so a large batch gives few, large files.""" env.setup_egress( [ParquetStorageEgress(default_path=f"{OUT}/other.parquet")], batch_size=10000 ) def order_row(env: DynamicRealtimeEnvironment, key: str, number: int, amount: float): """An order that names the file of its day.""" # The file of the order: the day it was placed, in the simulated calendar day = env.start_datetime + timedelta(seconds=env.now) return { # Numbered within the run, so the first customer of the run is part of the id "order_id": f"{FIRST}-{number}", "customer": key, "amount": amount, "__path__": day.strftime(f"{OUT}/%Y-%m-%d.parquet"), } ``` ### Split a Large Job One run keeps its entities and its records in one process. When a month for 1,000 customers is too much for one run, or too slow, run several shards, each as a separate process with its own part of the customers. Give each shard its own `FIRST`, `CUSTOMERS` and `SEED`, so that no two shards share a customer or a random sequence. They can write to the same folder, because every file name has its own suffix: ```bash desflow run data_at_scale.yaml --var FIRST=1 --var CUSTOMERS=500 --seed 1 & desflow run data_at_scale.yaml --var FIRST=501 --var CUSTOMERS=500 --seed 2 & wait ``` ```bash FIRST=1 CUSTOMERS=500 SEED=1 python data_at_scale.py & FIRST=501 CUSTOMERS=500 SEED=2 python data_at_scale.py & wait ``` ```bash FIRST=1 CUSTOMERS=500 SEED=1 python data_at_scale_low_level.py & FIRST=501 CUSTOMERS=500 SEED=2 python data_at_scale_low_level.py & wait ``` Each shard writes its own file for each day, so a day has one file for each shard. The order ids start with the number of the shard's first customer, so they stay unique across shards. To split by period instead, give each shard its own `logical_start_time` and `run.until`. `desflow run --replications` does not do this. A replication runs the model with no ingress and no egress, so it writes no files. It is for the spread of a result, not for data. ______________________________________________________________________ ## Check the Result Count the rows and the files of each day, and compare the total with the volume the model should give. Each customer orders about once a day, but the first order comes 12 to 36 hours in, so the total is about half a day short of customers times days. Save `data_at_scale_check.py` from [Full Files](#full-files) and run it from the folder of the files: ```python import sys from collections import Counter from pathlib import Path import pyarrow.parquet as pq def check(folder: str, customers: int, days: int) -> int: """Prints the files and rows of each day and returns the total rows.""" rows: Counter = Counter() files: Counter = Counter() for path in sorted(Path(folder).glob("*.parquet")): day = path.name[:10] # the day in the file name, such as 2026-01-01 files[day] += 1 rows[day] += pq.ParquetFile(path).metadata.num_rows for day in sorted(rows): print(f"{day} {files[day]} file {rows[day]:>7} rows") # Each customer orders once a day on average. Its first order comes 12 to 36 hours # in, so the total is about half a day short of customers * days. expected = customers * (days - 0.46) total = sum(rows.values()) print(f"total {total} rows, expected about {expected:.0f}") assert len(rows) == days, f"{len(rows)} days have a file, expected {days}" assert abs(total - expected) < 0.1 * expected, ( "the total is far from the expected volume" ) return total if __name__ == "__main__": folder = sys.argv[1] if len(sys.argv) > 1 else "scale_output" customers = int(sys.argv[2]) if len(sys.argv) > 2 else 1000 days = int(sys.argv[3]) if len(sys.argv) > 3 else 30 check(folder, customers, days) ``` ```bash python data_at_scale_check.py scale_output 20 3 ``` ```text 2026-01-01 1 file 9 rows 2026-01-02 1 file 20 rows 2026-01-03 1 file 18 rows total 47 rows, expected about 51 ``` The check stops with an error when a day has no file, or when the total is more than 10 percent from the expected volume. After a sharded run, it counts the files of every shard in the folder, so the days show one file for each shard. ______________________________________________________________________ ## Full Files Full files ```yaml # The Data at Scale guide: a month of orders for 1,000 customers, written as one Parquet # file for each day. CUSTOMERS, DAYS and OUT change the size and the folder, FIRST names # the number of the first customer and SEED the random seed, so that separate runs can # each cover some of the customers. Run it with: desflow run data_at_scale.yaml simulation: sim_id: Shop factor: 0 random_seed: ${SEED:-42} timezone: UTC logical_start_time: "2026-01-01T00:00:00+00:00" run: {until: "${DAYS:-30} days"} arrivals: # Each customer orders about once a day: a gap of 12 to 36 hours, drawn again after # each order customers: dist: uniform low: 43200 high: 129600 spawn: place_order count: ${CUSTOMERS:-1000} key: {gen: sequence, start: "${FIRST:-1}", format: "customer-{}"} tasks: place_order: payload: # Numbered within the run, so the first customer of the run is part of the id order_id: {gen: sequence, format: "${FIRST:-1}-{}"} customer: {gen: entity} amount: {gen: normal, mean: 40, std: 10, decimals: 2} # The file of the order: the day it was placed, in the simulated calendar __path__: {gen: format_time, format: "${OUT:-scale_output}/%Y-%m-%d.parquet"} egress: - type: Parquet # One file for each batch, so a large batch gives few, large files batch_size: 10000 config: default_path: ${OUT:-scale_output}/other.parquet ``` ```python """The Data at Scale guide, built with the builder API: a month of orders for 1,000 customers, written as Parquet files, one for each day. CUSTOMERS, DAYS, FIRST (the number of the first customer), SEED and OUT change the size, the customers, the random seed and the folder. Run it with `python data_at_scale.py`. """ import logging import os from datetime import datetime, timezone from desflow import ParquetStorageEgress, SimulationContext from desflow.values import Template CUSTOMERS = int(os.getenv("CUSTOMERS", "1000")) DAYS = int(os.getenv("DAYS", "30")) FIRST = int(os.getenv("FIRST", "1")) OUT = os.getenv("OUT", "scale_output") def new_shop() -> SimulationContext: """A shop that runs without waiting and starts on 1 January 2026, UTC.""" return SimulationContext( sim_id="Shop", factor=0, random_seed=int(os.getenv("SEED", "42")), timezone="UTC", logical_start_time=datetime(2026, 1, 1, tzinfo=timezone.utc), ) def add_customers(app: SimulationContext) -> None: """One arrival for each customer, ordering about once a day (12 to 36 hours apart). A blueprint's `count` is one arrival here, each with its own key.""" for number in range(FIRST, FIRST + CUSTOMERS): app.add_arrival( f"customer-{number}", "uniform", low=43200, high=129600, spawn="place_order", key=lambda n, number=number: f"customer-{number}", ) def add_files(app: SimulationContext) -> None: """A Parquet sink with a large batch, and an order that names the file of its day.""" # One file for each batch, so a large batch gives few, large files app.add_egress( ParquetStorageEgress(default_path=f"{OUT}/other.parquet"), batch_size=10000 ) order = Template( { # Numbered within the run, so the first customer of the run is part of the id "order_id": {"gen": "sequence", "format": f"{FIRST}-{{}}"}, "customer": {"gen": "entity"}, "amount": {"gen": "normal", "mean": 40, "std": 10, "decimals": 2}, # The file of the order: the day it was placed, in the simulated calendar "__path__": {"gen": "format_time", "format": f"{OUT}/%Y-%m-%d.parquet"}, }, name="tasks.place_order", ) @app.task(name="place_order") def place_order(task_id): return order def build_shop() -> SimulationContext: app = new_shop() add_customers(app) add_files(app) return app if __name__ == "__main__": logging.basicConfig(level=logging.INFO, format="%(levelname)s %(message)s") build_shop().run(until=f"{DAYS} days") ``` ```python """The Data at Scale guide, low-level API: a month of orders for 1,000 customers, written as Parquet files, one for each day. CUSTOMERS, DAYS, FIRST (the number of the first customer), SEED and OUT change the size, the customers, the random seed and the folder. Run it with `python data_at_scale_low_level.py`. """ import logging import os from datetime import datetime, timedelta, timezone from desflow import ( DistributionConfig, DynamicRealtimeEnvironment, ParquetStorageEgress, Sampler, ) CUSTOMERS = int(os.getenv("CUSTOMERS", "1000")) DAYS = int(os.getenv("DAYS", "30")) FIRST = int(os.getenv("FIRST", "1")) OUT = os.getenv("OUT", "scale_output") def new_env() -> DynamicRealtimeEnvironment: """An environment that runs without waiting and starts on 1 January 2026, UTC.""" return DynamicRealtimeEnvironment( factor=0, logical_start_time=datetime(2026, 1, 1, tzinfo=timezone.utc), timezone="UTC", ) def setup_files(env: DynamicRealtimeEnvironment) -> None: """A Parquet sink with a large batch. One file for each batch, so a large batch gives few, large files.""" env.setup_egress( [ParquetStorageEgress(default_path=f"{OUT}/other.parquet")], batch_size=10000 ) def order_row(env: DynamicRealtimeEnvironment, key: str, number: int, amount: float): """An order that names the file of its day.""" # The file of the order: the day it was placed, in the simulated calendar day = env.start_datetime + timedelta(seconds=env.now) return { # Numbered within the run, so the first customer of the run is part of the id "order_id": f"{FIRST}-{number}", "customer": key, "amount": amount, "__path__": day.strftime(f"{OUT}/%Y-%m-%d.parquet"), } def add_customers(env: DynamicRealtimeEnvironment) -> None: """One process for each customer, ordering about once a day (12 to 36 hours apart).""" sampler = Sampler(seed=int(os.getenv("SEED", "42"))) gap = DistributionConfig(dist="uniform", low=43200, high=129600) amounts = sampler.generator("tasks.place_order.payload.amount") sent = {"orders": 0} def customer(key): while True: yield env.timeout(sampler.sample(gap)) amount = round(float(amounts.normal(40, 10)), 2) order = order_row(env, key, sent["orders"], amount) env.publish_event(key, order, task="place_order", instance=sent["orders"]) sent["orders"] += 1 for number in range(FIRST, FIRST + CUSTOMERS): env.process(customer(f"customer-{number}")) def shop() -> DynamicRealtimeEnvironment: env = new_env() setup_files(env) add_customers(env) return env if __name__ == "__main__": logging.basicConfig(level=logging.INFO, format="%(levelname)s %(message)s") env = shop() try: env.run(until=DAYS * 24 * 3600) finally: env.teardown() ``` ```python """The check of the Data at Scale page: count the rows and the files of each day. Run it from the folder of the files with `python data_at_scale_check.py [folder] [customers] [days]`. It reads every Parquet file under the folder, prints the rows and the files of each day, and stops with an error when a day has no file or the total is far from the volume the model should give. """ import sys from collections import Counter from pathlib import Path import pyarrow.parquet as pq def check(folder: str, customers: int, days: int) -> int: """Prints the files and rows of each day and returns the total rows.""" rows: Counter = Counter() files: Counter = Counter() for path in sorted(Path(folder).glob("*.parquet")): day = path.name[:10] # the day in the file name, such as 2026-01-01 files[day] += 1 rows[day] += pq.ParquetFile(path).metadata.num_rows for day in sorted(rows): print(f"{day} {files[day]} file {rows[day]:>7} rows") # Each customer orders once a day on average. Its first order comes 12 to 36 hours # in, so the total is about half a day short of customers * days. expected = customers * (days - 0.46) total = sum(rows.values()) print(f"total {total} rows, expected about {expected:.0f}") assert len(rows) == days, f"{len(rows)} days have a file, expected {days}" assert abs(total - expected) < 0.1 * expected, ( "the total is far from the expected volume" ) return total if __name__ == "__main__": folder = sys.argv[1] if len(sys.argv) > 1 else "scale_output" customers = int(sys.argv[2]) if len(sys.argv) > 2 else 1000 days = int(sys.argv[3]) if len(sys.argv) > 3 else 30 check(folder, customers, days) ``` # Write to Cloud Storage `ParquetStorageEgress` and `JsonlStorageEgress` write each batch of records as a file. The same two sinks write to the local disk, Amazon S3, Google Cloud Storage or Azure Blob Storage: only their `filesystem` mapping changes. This page writes an hour of a shop's orders to a store you pick, then reads the files back as one table. ______________________________________________________________________ ## Before You Start - [Egress](https://jaehyeon.me/desflow/latest/user-guide/live-runs-and-connectors/egress/#parquet-and-json-lines) explains the two sinks, their file names and their columns. - Install the extra: `pip install "desflow[parquet]"`. - To write to a cloud, set up its credentials first, as [Choose the Store](#choose-the-store) describes, and create the bucket or container the files go to. ______________________________________________________________________ ## Steps ### Choose the Store A `filesystem` mapping names the store with `type`, and its other keys are the arguments of the PyArrow filesystem class of that store. Without credentials in the mapping, each cloud uses its standard settings: - `s3`: the AWS settings, from environment variables such as `AWS_ACCESS_KEY_ID` and `AWS_SECRET_ACCESS_KEY`, the files in `~/.aws`, or the role the machine runs as. - `gcs`: Google's default credentials, such as those `gcloud auth application-default login` saves. - `azure`: Azure's default credentials for the storage account that `account_name` names. The script takes the account name from the environment variable `AZURE_STORAGE_ACCOUNT`. The script keeps one mapping for each store. `STORAGE` picks one, and `STORAGE_BUCKET` names the bucket, the container or, for `local`, the folder: ```python import os # One filesystem mapping for each store; desflow builds it into a PyArrow filesystem STORES: dict[str, dict] = { # The local disk, for a first run "local": {"type": "local"}, # Amazon S3, with the standard AWS settings: environment variables, ~/.aws or a role "s3": {"type": "s3", "region": os.getenv("AWS_REGION", "us-east-1")}, # Google Cloud Storage, with Google's default credentials "gcs": {"type": "gcs"}, # Azure Blob Storage, with Azure's default credentials for the storage account "azure": {"type": "azure", "account_name": os.getenv("AZURE_STORAGE_ACCOUNT")}, } filesystem = STORES[os.getenv("STORAGE", "local")] bucket = os.getenv("STORAGE_BUCKET", "output") ``` The [Egress](https://jaehyeon.me/desflow/latest/user-guide/live-runs-and-connectors/egress/#parquet-and-json-lines) table lists the keys each store takes, such as `access_key` and `secret_key` for S3, `access_token` for GCS and `account_key` or `sas_token` for Azure. `endpoint_override` points `s3` or `gcs` at another service, such as SeaweedFS or MinIO. ### Write the Files Both sinks take the same mapping. Each writes into its own folder of the bucket, so a reader of one folder reads one format: ```python from desflow import JsonlStorageEgress, ParquetStorageEgress def storage_sinks(filesystem: dict, bucket: str) -> list: """Every event as Parquet and as JSON Lines, in two folders of the bucket.""" return [ ParquetStorageEgress( default_path=f"{bucket}/parquet/events.parquet", filesystem=filesystem ), JsonlStorageEgress( default_path=f"{bucket}/jsonl/events.jsonl", filesystem=filesystem ), ] sinks = storage_sinks(filesystem, bucket) ``` Each form runs the shop for an hour of simulated time at `factor=0.0`, so the run takes a few seconds: ```yaml egress: # Every event as Parquet and as JSON Lines, in two folders of the bucket - type: Parquet config: default_path: ${STORAGE_BUCKET:-output}/parquet/events.parquet filesystem: !include cloud_storage_stores/${STORAGE:-local}.yaml - type: Jsonl config: default_path: ${STORAGE_BUCKET:-output}/jsonl/events.jsonl filesystem: !include cloud_storage_stores/${STORAGE:-local}.yaml ``` The YAML form keeps the same four mappings in the files `local.yaml`, `s3.yaml`, `gcs.yaml` and `azure.yaml` of the folder `cloud_storage_stores`. `!include cloud_storage_stores/${STORAGE:-local}.yaml` reads the one that `STORAGE` names, so the variable picks the store in every form. `${STORAGE_BUCKET:-output}` reads the bucket from its variable in the same way. ```python import logging from cloud_storage_stores import sinks from desflow import SimulationContext def build_shop(sinks: list) -> SimulationContext: """The shop, writing to the sinks given, as fast as the machine allows.""" app = ( SimulationContext(sim_id="Shop", factor=0.0, random_seed=42) .add_resource("packers", current_cap=1, max_cap=1) .add_service("packing", dist="constant", value=1.5) .add_arrival("orders", dist="exponential", rate=0.5) ) for sink in sinks: app.add_egress(sink) @app.task(service_id="packing", resource_id="packers") def pack_order(task_id: int, entity): # The finished event is the order record return {"order_id": task_id, "amount": 19.99} @app.arrival_loop("orders") def orders(context: SimulationContext): while True: order = yield context.wait_for_arrival("orders") context.spawn(pack_order(context.next_instance("pack_order"), entity=order)) return app app = build_shop(sinks) if __name__ == "__main__": logging.basicConfig( level=logging.INFO, format="%(levelname)s [%(asctime)s] %(message)s" ) app.run(until="1 hour") ``` `shop` takes the sinks as an argument, and the script passes it `sinks` from `cloud_storage_stores.py`: ```python def pack_order(env, packers, sampler, key, task_id): path_id = "Shop.service.packing" env.publish_event( key, { "path_id": path_id, "sim_id": "Shop", "service": "packing", "status": "queued", }, "pack_order", task_id, ) with packers.request() as unit: yield unit env.publish_event( key, { "path_id": path_id, "sim_id": "Shop", "service": "packing", "status": "started", }, "pack_order", task_id, ) yield env.timeout(sampler.sample(env.registry.get_config(path_id))) # The finished event is the order record order = {"order_id": task_id, "amount": 19.99} env.publish_event(key, order, "pack_order", task_id) def orders(env, packers, sampler): gap = env.registry.get_config("Shop.arrival.orders") for number in itertools.count(1): yield env.timeout(sampler.sample(gap)) env.process(pack_order(env, packers, sampler, f"orders-{number}", number - 1)) def shop(sinks: list, factor: float = 0.0) -> DynamicRealtimeEnvironment: """The shop, writing to the sinks given, as fast as the machine allows.""" env = DynamicRealtimeEnvironment(factor=factor) env.registry.register_sim_parameter(PARAMS) env.setup_egress(sinks) packers = DynamicResource(env, "Shop", "packers") env.process(orders(env, packers, Sampler(seed=42))) return env ``` ### Write a File for Each Day A record whose `__path__` key holds a file path is written to that file, and the key is removed from the row. `{gen: format_time, format: ...}` builds the path from the simulated time, so each day goes to a file of its own. The shop below packs an order every hour for two days from 1 January 2026: ```yaml payload: order_id: {gen: sequence} amount: 19.99 # The file of the order: the day it was packed, in the simulated calendar __path__: gen: format_time format: "${STORAGE_BUCKET:-output}/daily/%Y-%m-%d.jsonl" ``` The same file gives the sink a `default_path` and `!include`s the store, as the first shop does. ```python import logging from datetime import datetime, timezone from cloud_storage_stores import bucket, filesystem from desflow import JsonlStorageEgress, SimulationContext from desflow.values import Template def build_shop() -> SimulationContext: """The shop, writing each order to the file of its day.""" app = SimulationContext( sim_id="Shop", factor=0.0, random_seed=42, timezone="UTC", logical_start_time=datetime(2026, 1, 1, tzinfo=timezone.utc), ) app.add_arrival("orders", dist="constant", value=3600, spawn="pack_order") app.add_egress( # The file of a record with no __path__ JsonlStorageEgress( default_path=f"{bucket}/daily/other.jsonl", filesystem=filesystem ) ) order = Template( { "order_id": {"gen": "sequence"}, "amount": 19.99, # The file of the order: the day it was packed, in the simulated calendar "__path__": { "gen": "format_time", "format": f"{bucket}/daily/%Y-%m-%d.jsonl", }, }, name="tasks.pack_order", ) @app.task(name="pack_order") def pack_order(task_id): return order return app app = build_shop() if __name__ == "__main__": logging.basicConfig(level=logging.INFO, format="%(levelname)s %(message)s") app.run(until="2 days") ``` ```python import itertools import logging from datetime import datetime, timedelta, timezone from cloud_storage_stores import bucket, filesystem from desflow import DynamicRealtimeEnvironment, JsonlStorageEgress START = datetime(2026, 1, 1, tzinfo=timezone.utc) def orders(env): for number in itertools.count(): yield env.timeout(3600) # The file of the order: the day it was packed, in the simulated calendar day = env.start_datetime + timedelta(seconds=env.now) order = { "order_id": number, "amount": 19.99, "__path__": day.strftime(f"{bucket}/daily/%Y-%m-%d.jsonl"), } env.publish_event(f"orders-{number + 1}", order, "pack_order", number) def shop() -> DynamicRealtimeEnvironment: """The shop, writing each order to the file of its day.""" env = DynamicRealtimeEnvironment( factor=0.0, logical_start_time=START, timezone="UTC" ) env.setup_egress( # The file of a record with no __path__ [ JsonlStorageEgress( default_path=f"{bucket}/daily/other.jsonl", filesystem=filesystem ) ] ) env.process(orders(env)) return env if __name__ == "__main__": logging.basicConfig(level=logging.INFO, format="%(levelname)s %(message)s") env = shop() try: env.run(until=2 * 24 * 3600) finally: env.teardown() ``` The sink writes one file for each flush and adds an identifier to its name: the orders of 1 January go to `output/daily/2026-01-01_.jsonl`. A record whose `__path__` is missing, null or empty goes to `default_path`. A `path_router` wins over `__path__`. A sink with neither `default_path` nor `path_router` writes only the records that carry a `__path__`, and each flush logs a warning with the number of records it skipped. `ParquetStorageEgress` takes `__path__` in the same way. ### Read the Files Back `read_events` reads every file in a folder as one table, through a PyArrow filesystem of the same store: ```python def read_events(store, folder: str, format: str = "parquet"): """Every file a sink wrote under `folder`, as one table. `store` is a PyArrow filesystem, such as pyarrow.fs.S3FileSystem(region="us-east-1"). """ import pyarrow.dataset as ds # format="json" reads the files of the JSON Lines sink return ds.dataset(folder, format=format, filesystem=store).to_table() ``` Give each run a folder of its own, or clear the folder before a run, because a second run adds its files beside the first run's. ______________________________________________________________________ ## Check the Result Run `python cloud_storage.py`, `python cloud_storage_low_level.py` or `desflow run cloud_storage.yaml`. With no variables set, the files go to the folder `output` on the local disk: ```bash STORAGE=s3 STORAGE_BUCKET=my-bucket python cloud_storage.py ``` writes them to the bucket `my-bucket` on S3 instead. In every form, `output/parquet` and `output/jsonl` hold one file for each batch, with the same events: the `queued` and `started` events of each order, with `path_id` and `status`, and its finished event, with `order_id` and `amount`. A seeded run writes the same events in every form. Only `timestamp` differs, because it is the clock time at the start of the run plus the simulation time. To count the rows, run the stores file with the same variables. Its last lines build the PyArrow filesystem of the store from the mapping, call `read_events` on each folder and print the rows: ```python if __name__ == "__main__": from pyarrow import fs # The PyArrow class of the store takes the keys of its mapping. It is looked up # by name, because some pyarrow builds lack the classes of the other clouds. classes = { "local": "LocalFileSystem", "s3": "S3FileSystem", "gcs": "GcsFileSystem", "azure": "AzureFileSystem", } options = { key: value for key, value in filesystem.items() if key != "type" and value } store = getattr(fs, classes[filesystem["type"]])(**options) for folder, format in (("parquet", "parquet"), ("jsonl", "json")): events = read_events(store, f"{bucket}/{folder}", format) print(f"{folder}: {events.num_rows} rows") ``` ```bash python cloud_storage_stores.py ``` ```text parquet: 5465 rows jsonl: 5465 rows ``` Both folders hold the same number of rows. For a cloud, run the script with the same `STORAGE` and `STORAGE_BUCKET` as the shop. The daily shop is run as `python cloud_storage_daily.py`, `python cloud_storage_daily_low_level.py` or `desflow run cloud_storage_daily.yaml`. Each form writes 47 orders to `output/daily`: 23 in the file of 1 January and 24 in the file of 2 January. The packing at midnight belongs to the new day. ______________________________________________________________________ ## Full Files The Builder and Low-level forms use the store and the sinks of `cloud_storage_stores.py`, which builds no shop. The YAML form uses the folder `cloud_storage_stores` instead. Keep the files of the form you run in one folder. Full files ```python """The stores, sinks and reader of the Write to Cloud Storage page. The builder and low-level forms of the shop import the store and the sinks from this file: cloud_storage.py and cloud_storage_low_level.py, and the daily shops. cloud_storage.yaml reads the same mappings from the folder cloud_storage_stores. It builds no simulation. STORAGE picks the store: local (the default), s3, gcs or azure. STORAGE_BUCKET names the bucket or container, or the folder on the local disk, with the credentials of that cloud set up as the page describes. """ # Each section carries its own imports, as the page shows it. # ruff: noqa: E402 import os # One filesystem mapping for each store; desflow builds it into a PyArrow filesystem STORES: dict[str, dict] = { # The local disk, for a first run "local": {"type": "local"}, # Amazon S3, with the standard AWS settings: environment variables, ~/.aws or a role "s3": {"type": "s3", "region": os.getenv("AWS_REGION", "us-east-1")}, # Google Cloud Storage, with Google's default credentials "gcs": {"type": "gcs"}, # Azure Blob Storage, with Azure's default credentials for the storage account "azure": {"type": "azure", "account_name": os.getenv("AZURE_STORAGE_ACCOUNT")}, } filesystem = STORES[os.getenv("STORAGE", "local")] bucket = os.getenv("STORAGE_BUCKET", "output") from desflow import JsonlStorageEgress, ParquetStorageEgress def storage_sinks(filesystem: dict, bucket: str) -> list: """Every event as Parquet and as JSON Lines, in two folders of the bucket.""" return [ ParquetStorageEgress( default_path=f"{bucket}/parquet/events.parquet", filesystem=filesystem ), JsonlStorageEgress( default_path=f"{bucket}/jsonl/events.jsonl", filesystem=filesystem ), ] sinks = storage_sinks(filesystem, bucket) def read_events(store, folder: str, format: str = "parquet"): """Every file a sink wrote under `folder`, as one table. `store` is a PyArrow filesystem, such as pyarrow.fs.S3FileSystem(region="us-east-1"). """ import pyarrow.dataset as ds # format="json" reads the files of the JSON Lines sink return ds.dataset(folder, format=format, filesystem=store).to_table() if __name__ == "__main__": from pyarrow import fs # The PyArrow class of the store takes the keys of its mapping. It is looked up # by name, because some pyarrow builds lack the classes of the other clouds. classes = { "local": "LocalFileSystem", "s3": "S3FileSystem", "gcs": "GcsFileSystem", "azure": "AzureFileSystem", } options = { key: value for key, value in filesystem.items() if key != "type" and value } store = getattr(fs, classes[filesystem["type"]])(**options) for folder, format in (("parquet", "parquet"), ("jsonl", "json")): events = read_events(store, f"{bucket}/{folder}", format) print(f"{folder}: {events.num_rows} rows") ``` ```yaml # The Write to Cloud Storage guide: the shop writes an hour of orders as Parquet and # JSON Lines files, as fast as the machine allows. STORAGE picks the store (local, the # default, s3, gcs or azure) and STORAGE_BUCKET the bucket, container or local folder. # Needs the folder cloud_storage_stores beside it. Run it with: # desflow run cloud_storage.yaml simulation: {sim_id: Shop, factor: 0.0, random_seed: 42} resources: packers: {current_cap: 1, max_cap: 1} services: packing: {dist: constant, value: 1.5} arrivals: orders: {dist: exponential, rate: 0.5, spawn: pack_order} tasks: pack_order: service: packing resource: packers # The finished event is the order record payload: order_id: {gen: sequence} amount: 19.99 egress: # Every event as Parquet and as JSON Lines, in two folders of the bucket - type: Parquet config: default_path: ${STORAGE_BUCKET:-output}/parquet/events.parquet filesystem: !include cloud_storage_stores/${STORAGE:-local}.yaml - type: Jsonl config: default_path: ${STORAGE_BUCKET:-output}/jsonl/events.jsonl filesystem: !include cloud_storage_stores/${STORAGE:-local}.yaml run: {until: 1 hour} ``` ```yaml # The local disk, for a first run type: local ``` ```yaml # Amazon S3, with the standard AWS settings: environment variables, ~/.aws or a role type: s3 region: ${AWS_REGION:-us-east-1} ``` ```yaml # Google Cloud Storage, with Google's default credentials type: gcs ``` ```yaml # Azure Blob Storage, with Azure's default credentials for the storage account type: azure account_name: ${AZURE_STORAGE_ACCOUNT} ``` ```yaml # The Write to Cloud Storage guide, "Write a File for Each Day": two days of orders, # each day in a file of its own. STORAGE picks the store and STORAGE_BUCKET the bucket, # as in cloud_storage.yaml. Needs the folder cloud_storage_stores beside it. Run it # with: desflow run cloud_storage_daily.yaml simulation: sim_id: Shop factor: 0.0 random_seed: 42 timezone: UTC logical_start_time: "2026-01-01T00:00:00+00:00" arrivals: orders: {dist: constant, value: 3600, spawn: pack_order} tasks: pack_order: payload: order_id: {gen: sequence} amount: 19.99 # The file of the order: the day it was packed, in the simulated calendar __path__: gen: format_time format: "${STORAGE_BUCKET:-output}/daily/%Y-%m-%d.jsonl" egress: - type: Jsonl config: # The file of a record with no __path__ default_path: ${STORAGE_BUCKET:-output}/daily/other.jsonl filesystem: !include cloud_storage_stores/${STORAGE:-local}.yaml run: {until: 2 days} ``` ```python """The shop of the Write to Cloud Storage page, built with the builder API. The shop writes an hour of orders as Parquet and JSON Lines files, as fast as the machine allows. Run it with `STORAGE=s3 STORAGE_BUCKET=my-bucket python cloud_storage.py`, with the credentials of that cloud set up as the page describes. cloud_storage.yaml and cloud_storage_low_level.py are the same shop in YAML and the low-level API. All three import the store and the sinks of cloud_storage_stores.py, which must be beside them. """ # ruff: noqa: E402 import logging from cloud_storage_stores import sinks from desflow import SimulationContext def build_shop(sinks: list) -> SimulationContext: """The shop, writing to the sinks given, as fast as the machine allows.""" app = ( SimulationContext(sim_id="Shop", factor=0.0, random_seed=42) .add_resource("packers", current_cap=1, max_cap=1) .add_service("packing", dist="constant", value=1.5) .add_arrival("orders", dist="exponential", rate=0.5) ) for sink in sinks: app.add_egress(sink) @app.task(service_id="packing", resource_id="packers") def pack_order(task_id: int, entity): # The finished event is the order record return {"order_id": task_id, "amount": 19.99} @app.arrival_loop("orders") def orders(context: SimulationContext): while True: order = yield context.wait_for_arrival("orders") context.spawn(pack_order(context.next_instance("pack_order"), entity=order)) return app app = build_shop(sinks) if __name__ == "__main__": logging.basicConfig( level=logging.INFO, format="%(levelname)s [%(asctime)s] %(message)s" ) app.run(until="1 hour") ``` ```python """The "Write a File for Each Day" step of the Write to Cloud Storage page, built with the builder API. The shop packs an order every hour for two days, and each order goes to the file of its day. STORAGE and STORAGE_BUCKET pick the store as in cloud_storage.py. Needs cloud_storage_stores.py beside it. Run it with `python cloud_storage_daily.py`. """ import logging from datetime import datetime, timezone from cloud_storage_stores import bucket, filesystem from desflow import JsonlStorageEgress, SimulationContext from desflow.values import Template def build_shop() -> SimulationContext: """The shop, writing each order to the file of its day.""" app = SimulationContext( sim_id="Shop", factor=0.0, random_seed=42, timezone="UTC", logical_start_time=datetime(2026, 1, 1, tzinfo=timezone.utc), ) app.add_arrival("orders", dist="constant", value=3600, spawn="pack_order") app.add_egress( # The file of a record with no __path__ JsonlStorageEgress( default_path=f"{bucket}/daily/other.jsonl", filesystem=filesystem ) ) order = Template( { "order_id": {"gen": "sequence"}, "amount": 19.99, # The file of the order: the day it was packed, in the simulated calendar "__path__": { "gen": "format_time", "format": f"{bucket}/daily/%Y-%m-%d.jsonl", }, }, name="tasks.pack_order", ) @app.task(name="pack_order") def pack_order(task_id): return order return app app = build_shop() if __name__ == "__main__": logging.basicConfig(level=logging.INFO, format="%(levelname)s %(message)s") app.run(until="2 days") ``` ```python """The Write to Cloud Storage guide, low-level API: the shop writes an hour of orders as Parquet and JSON Lines files, as fast as the machine allows. The store and the sinks are those of cloud_storage_stores.py, which must be beside this script. STORAGE picks the store (local, the default, s3, gcs or azure) and STORAGE_BUCKET the bucket, container or local folder. Run it with `python cloud_storage_low_level.py`. """ import itertools import logging from cloud_storage_stores import sinks from desflow import ( CapacityConfig, DistributionConfig, DynamicRealtimeEnvironment, DynamicResource, Sampler, SimParameter, ) PARAMS = SimParameter( sim_id="Shop", arrival={"orders": DistributionConfig(dist="exponential", rate=0.5)}, service={"packing": DistributionConfig(dist="constant", value=1.5)}, resources={"packers": CapacityConfig(current_cap=1, max_cap=1)}, ) def pack_order(env, packers, sampler, key, task_id): path_id = "Shop.service.packing" env.publish_event( key, { "path_id": path_id, "sim_id": "Shop", "service": "packing", "status": "queued", }, "pack_order", task_id, ) with packers.request() as unit: yield unit env.publish_event( key, { "path_id": path_id, "sim_id": "Shop", "service": "packing", "status": "started", }, "pack_order", task_id, ) yield env.timeout(sampler.sample(env.registry.get_config(path_id))) # The finished event is the order record order = {"order_id": task_id, "amount": 19.99} env.publish_event(key, order, "pack_order", task_id) def orders(env, packers, sampler): gap = env.registry.get_config("Shop.arrival.orders") for number in itertools.count(1): yield env.timeout(sampler.sample(gap)) env.process(pack_order(env, packers, sampler, f"orders-{number}", number - 1)) def shop(sinks: list, factor: float = 0.0) -> DynamicRealtimeEnvironment: """The shop, writing to the sinks given, as fast as the machine allows.""" env = DynamicRealtimeEnvironment(factor=factor) env.registry.register_sim_parameter(PARAMS) env.setup_egress(sinks) packers = DynamicResource(env, "Shop", "packers") env.process(orders(env, packers, Sampler(seed=42))) return env if __name__ == "__main__": logging.basicConfig( level=logging.INFO, format="%(levelname)s [%(asctime)s] %(message)s" ) env = shop(sinks) # Parquet and JSON Lines files in the store STORAGE names try: env.run(until=3600) finally: env.teardown() ``` ```python """The "Write a File for Each Day" step of the Write to Cloud Storage page, low-level API. The shop packs an order every hour for two days, and each order goes to the file of its day. The path is built from the start time of the environment plus the simulation time, as the blueprint's `format_time` builds it. Needs cloud_storage_stores.py beside it. Run it with `python cloud_storage_daily_low_level.py`. """ import itertools import logging from datetime import datetime, timedelta, timezone from cloud_storage_stores import bucket, filesystem from desflow import DynamicRealtimeEnvironment, JsonlStorageEgress START = datetime(2026, 1, 1, tzinfo=timezone.utc) def orders(env): for number in itertools.count(): yield env.timeout(3600) # The file of the order: the day it was packed, in the simulated calendar day = env.start_datetime + timedelta(seconds=env.now) order = { "order_id": number, "amount": 19.99, "__path__": day.strftime(f"{bucket}/daily/%Y-%m-%d.jsonl"), } env.publish_event(f"orders-{number + 1}", order, "pack_order", number) def shop() -> DynamicRealtimeEnvironment: """The shop, writing each order to the file of its day.""" env = DynamicRealtimeEnvironment( factor=0.0, logical_start_time=START, timezone="UTC" ) env.setup_egress( # The file of a record with no __path__ [ JsonlStorageEgress( default_path=f"{bucket}/daily/other.jsonl", filesystem=filesystem ) ] ) env.process(orders(env)) return env if __name__ == "__main__": logging.basicConfig(level=logging.INFO, format="%(levelname)s %(message)s") env = shop() try: env.run(until=2 * 24 * 3600) finally: env.teardown() ``` # Write to Iceberg Tables `IcebergStorageEgress` appends records to an Apache Iceberg table through a catalog, so any engine that reads Iceberg, such as Spark, Trino or DuckDB, can query them. This page appends an hour of a shop's orders to the table `shop.events` through a catalog you pick, then reads the table back. ______________________________________________________________________ ## Before You Start - [Egress](https://jaehyeon.me/desflow/latest/user-guide/live-runs-and-connectors/egress/#iceberg) explains the sink, the columns of a table it creates, and upserts. - Install the extra: `pip install "desflow[iceberg]"`. It covers every catalog on this page. - The SQLite catalog needs no service. The REST catalog needs `odctl up catalog`, and the PostgreSQL catalog `odctl up postgres`. See [Installation](https://jaehyeon.me/desflow/latest/installation/index.md) for the one-time odctl install. Stop a profile with `odctl down --volumes`. - The Glue catalog needs AWS credentials and an S3 bucket for the table files. ______________________________________________________________________ ## Steps ### Choose the Catalog `catalog` is a mapping of PyIceberg catalog properties, which desflow passes to PyIceberg's `load_catalog` on the first write. `type` picks the kind of catalog, and the optional `name` key names it. The script keeps one mapping for each catalog, and `ICEBERG_CATALOG` picks one: ```python import os from pathlib import Path # The SQLite database and the local table files go in the folder iceberg/ FOLDER = Path("iceberg").resolve() FOLDER.mkdir(exist_ok=True) # One mapping of PyIceberg catalog properties for each catalog CATALOGS = { # A SQL catalog on SQLite, with no service, for a first run "sqlite": { "type": "sql", "uri": f"sqlite:///{FOLDER}/catalog.db", "warehouse": f"file://{FOLDER}/warehouse", }, # The REST catalog of `odctl up catalog`, with the table files on its SeaweedFS "rest": { "type": "rest", "uri": "http://127.0.0.1:8181", "warehouse": "s3://warehouse/", "s3.endpoint": "http://127.0.0.1:8333", "s3.access-key-id": "user", "s3.secret-access-key": "password", "s3.region": "us-east-1", }, # A SQL catalog on the PostgreSQL of `odctl up postgres`, with local table files "postgres": { "type": "sql", "uri": "postgresql+psycopg2://user:password@127.0.0.1:5432/odctl", "warehouse": f"file://{FOLDER}/warehouse", }, # The AWS Glue Data Catalog, with the table files in S3 and the standard AWS settings "glue": { "type": "glue", "glue.region": "us-east-1", "s3.region": "us-east-1", "warehouse": os.getenv("ICEBERG_WAREHOUSE", "s3://my-bucket/warehouse"), }, } name = os.getenv("ICEBERG_CATALOG", "sqlite") catalog = {"name": name, **CATALOGS[name]} ``` The Glue mapping gives no credentials, so PyIceberg uses the standard AWS settings: environment variables such as `AWS_ACCESS_KEY_ID`, the files in `~/.aws`, or the role the machine runs as. `ICEBERG_WAREHOUSE` names the S3 folder of the table files. [PyIceberg's configuration](https://py.iceberg.apache.org/configuration/) lists the properties of each catalog. ### Write the Table The sink creates the table from the first batch, with a column for each key of the records. Each flush is one commit, and every commit writes new metadata, so the sink gets a large batch of its own: ```python from desflow import IcebergStorageEgress def iceberg_sink(catalog: dict, table: str = "shop.events") -> IcebergStorageEgress: """Every event as a row of `table`, which the sink creates from the first batch.""" return IcebergStorageEgress(catalog=catalog, default_table=table) sink = iceberg_sink(catalog) # One commit per flush, so the sink gets a large batch of its own BATCH_SIZE = 200_000 ``` A new table takes the type of each column from `schemas` when it is named there, and otherwise from the first batch. A table that exists keeps its own types. A column that a later batch adds is added to the table, with two exceptions. A table named in `schemas` never gains a column. A table with `upsert_keys` that is not named there refuses that batch. [Egress](https://jaehyeon.me/desflow/latest/user-guide/live-runs-and-connectors/egress/#iceberg) has the column and type rules. A table that has an integer column refuses a later batch with a fraction in it. The sink logs an error, such as `could not write 1 rows to shop.events: row 1 holds 2.5 for the int64 column 'amount', which would lose its fraction. Iceberg cannot change the type of a column that exists. Name the column double in schemas before the table is created (for a list or struct column, in a PyArrow schema), or create the table again: run once with table_policy: drop_and_create, then set it back to create`, and the rows of that batch are not written. A table that exists keeps its `long` column, so a `schemas` entry changes it only when the table is created again. To fix it, name every column the table needs in `schemas`, such as `schemas: {shop.events: {stream_type: string, sim_ts: double, timestamp: string, key: string, task: string, instance: long, path_id: string, sim_id: string, service: string, status: string, order_id: long, amount: double}}`. A table named there is created with exactly those columns and leaves any other field out. Then create the table again. Run once with `table_policy: drop_and_create`, which drops the table and deletes its rows. Then set `table_policy` back to `create`. The policy drops the table at the first write of every run, as [Egress](https://jaehyeon.me/desflow/latest/user-guide/live-runs-and-connectors/egress/#iceberg) says, so a later run left on it deletes the new rows too. A statistic (a number) and an event or a reading (a mapping) cannot share a table or a file, because the `value` column has one type. If a `table_router` or a `path_router` sends both to one place, the error names this cause. Send each kind to its own table. Each form runs the shop for an hour of simulated time at `factor=0.0`. The run flushes once, at its end, so the hour of orders is one commit: ```yaml egress: # Every event as a row of shop.events, which the sink creates from the first batch - type: Iceberg config: default_table: shop.events catalog: !include iceberg_tables_catalogs/${ICEBERG_CATALOG:-sqlite}.yaml # One commit per flush, so the sink gets a large batch of its own batch_size: 200000 ``` The YAML form keeps the same four mappings in the files `sqlite.yaml`, `rest.yaml`, `postgres.yaml` and `glue.yaml` of the folder `iceberg_tables_catalogs`. `!include iceberg_tables_catalogs/${ICEBERG_CATALOG:-sqlite}.yaml` reads the one that `ICEBERG_CATALOG` names, so the variable picks the catalog in every form. The Builder and Low-level scripts create the folder `iceberg` for the SQLite files. For the YAML form, run `mkdir iceberg` first, because SQLite does not create the folder of its database. ```python import logging from iceberg_tables_catalog import BATCH_SIZE, sink from desflow import IcebergStorageEgress, SimulationContext def build_shop(sink: IcebergStorageEgress) -> SimulationContext: """The shop, appending to the table of the sink given, as fast as it can.""" app = ( SimulationContext(sim_id="Shop", factor=0.0, random_seed=42) .add_resource("packers", current_cap=1, max_cap=1) .add_service("packing", dist="constant", value=1.5) .add_arrival("orders", dist="exponential", rate=0.5) .add_egress(sink, batch_size=BATCH_SIZE) ) @app.task(service_id="packing", resource_id="packers") def pack_order(task_id: int, entity): # The finished event is the order record return {"order_id": task_id, "amount": 19.99} @app.arrival_loop("orders") def orders(context: SimulationContext): while True: order = yield context.wait_for_arrival("orders") context.spawn(pack_order(context.next_instance("pack_order"), entity=order)) return app app = build_shop(sink) if __name__ == "__main__": logging.basicConfig( level=logging.INFO, format="%(levelname)s [%(asctime)s] %(message)s" ) app.run(until="1 hour") ``` `shop` takes the sink as an argument, and the script passes it `sink` from `iceberg_tables_catalog.py`. `shop` sets the batch size of the sink, `BATCH_SIZE` from the same file, in `batch_sizes`: ```python def pack_order(env, packers, sampler, key, task_id): path_id = "Shop.service.packing" env.publish_event( key, { "path_id": path_id, "sim_id": "Shop", "service": "packing", "status": "queued", }, "pack_order", task_id, ) with packers.request() as unit: yield unit env.publish_event( key, { "path_id": path_id, "sim_id": "Shop", "service": "packing", "status": "started", }, "pack_order", task_id, ) yield env.timeout(sampler.sample(env.registry.get_config(path_id))) # The finished event is the order record order = {"order_id": task_id, "amount": 19.99} env.publish_event(key, order, "pack_order", task_id) def orders(env, packers, sampler): gap = env.registry.get_config("Shop.arrival.orders") for number in itertools.count(1): yield env.timeout(sampler.sample(gap)) env.process(pack_order(env, packers, sampler, f"orders-{number}", number - 1)) def shop(sink, factor: float = 0.0) -> DynamicRealtimeEnvironment: """The shop, appending to the table of the sink given, as fast as it can.""" env = DynamicRealtimeEnvironment(factor=factor) env.registry.register_sim_parameter(PARAMS) # One commit per flush, so the sink gets a large batch of its own env.setup_egress([sink], batch_sizes=[BATCH_SIZE]) packers = DynamicResource(env, "Shop", "packers") env.process(orders(env, packers, Sampler(seed=42))) return env ``` ### Read the Table Back `read_events` loads the table through the same catalog and reads every row: ```python def read_events(catalog: dict, table: str = "shop.events"): """Every row of `table`, as one PyArrow table.""" from pyiceberg.catalog import load_catalog properties = {key: value for key, value in catalog.items() if key != "name"} return ( load_catalog(catalog["name"], **properties).load_table(table).scan().to_arrow() ) ``` A second run appends its rows to the same table. To replace the rows of an earlier run instead, give the sink `upsert_keys`, as [Egress](https://jaehyeon.me/desflow/latest/user-guide/live-runs-and-connectors/egress/#iceberg) shows. A table with `upsert_keys` that is not named in `schemas` refuses a batch that brings a column the table lacks. A table named there leaves such a field out without an error. So name every column in `schemas` before the table is created. For a table that exists, name them and create the table again. Run once with `table_policy: drop_and_create`, which deletes its rows. Then set `table_policy` back to `create`, or every later run drops the table again. [Egress](https://jaehyeon.me/desflow/latest/user-guide/live-runs-and-connectors/egress/#iceberg) has the rest of the column rules. A sink with `upsert_keys` skips a record that has no destination or that has a null or missing key column, and logs one warning at the end of each flush with the number skipped and the reason. An entry that names its tables in `schemas`, `locations` or `upsert_keys` needs no `default_table` or router: a record routes by its `__table__`. A record whose `__table__` is null or empty goes to `default_table`. A record whose `__table__` names no namespace, such as `events` in place of `shop.events`, is skipped, and the flush logs a warning with the number skipped. ______________________________________________________________________ ## Check the Result Run `python iceberg_tables.py`, `python iceberg_tables_low_level.py` or `desflow run iceberg_tables.yaml`. With no variables set, the catalog is SQLite, and its database and table files go in the folder `iceberg`. With the catalog profile up, ```bash ICEBERG_CATALOG=rest python iceberg_tables.py ``` writes through the REST catalog instead. In every form, `shop.events` gains one snapshot, with a row for each event: the `queued` and `started` events of each order, with `path_id` and `status`, and its finished event, with `order_id` and `amount`. A seeded run writes the same events in every form. Only `timestamp` differs, because it is the clock time at the start of the run plus the simulation time. To count the rows, run the catalog file with the same variables. Its last lines call `read_events` and print the count: ```python if __name__ == "__main__": events = read_events(catalog) print(f"{events.num_rows} rows in shop.events") ``` ```bash python iceberg_tables_catalog.py ``` ```text 5465 rows in shop.events ``` The count of one run is 5,465 rows. A second run appends its rows to the table, so the count is then the sum of both runs. ______________________________________________________________________ ## Full Files The Builder and Low-level forms use the catalog and the sink of `iceberg_tables_catalog.py`, which builds no shop. The YAML form uses the folder `iceberg_tables_catalogs` instead. Keep the files of the form you run in one folder. Full files ```python """The catalogs, sink and reader of the Write Iceberg Tables page. The builder and low-level forms of the shop import the catalog and the sink from this file: iceberg_tables.py and iceberg_tables_low_level.py. iceberg_tables.yaml reads the same mappings from the folder iceberg_tables_catalogs. It builds no simulation. ICEBERG_CATALOG picks the catalog: sqlite (the default), rest, postgres or glue. """ # Each section carries its own imports, as the page shows it. # ruff: noqa: E402 import os from pathlib import Path # The SQLite database and the local table files go in the folder iceberg/ FOLDER = Path("iceberg").resolve() FOLDER.mkdir(exist_ok=True) # One mapping of PyIceberg catalog properties for each catalog CATALOGS = { # A SQL catalog on SQLite, with no service, for a first run "sqlite": { "type": "sql", "uri": f"sqlite:///{FOLDER}/catalog.db", "warehouse": f"file://{FOLDER}/warehouse", }, # The REST catalog of `odctl up catalog`, with the table files on its SeaweedFS "rest": { "type": "rest", "uri": "http://127.0.0.1:8181", "warehouse": "s3://warehouse/", "s3.endpoint": "http://127.0.0.1:8333", "s3.access-key-id": "user", "s3.secret-access-key": "password", "s3.region": "us-east-1", }, # A SQL catalog on the PostgreSQL of `odctl up postgres`, with local table files "postgres": { "type": "sql", "uri": "postgresql+psycopg2://user:password@127.0.0.1:5432/odctl", "warehouse": f"file://{FOLDER}/warehouse", }, # The AWS Glue Data Catalog, with the table files in S3 and the standard AWS settings "glue": { "type": "glue", "glue.region": "us-east-1", "s3.region": "us-east-1", "warehouse": os.getenv("ICEBERG_WAREHOUSE", "s3://my-bucket/warehouse"), }, } name = os.getenv("ICEBERG_CATALOG", "sqlite") catalog = {"name": name, **CATALOGS[name]} from desflow import IcebergStorageEgress def iceberg_sink(catalog: dict, table: str = "shop.events") -> IcebergStorageEgress: """Every event as a row of `table`, which the sink creates from the first batch.""" return IcebergStorageEgress(catalog=catalog, default_table=table) sink = iceberg_sink(catalog) # One commit per flush, so the sink gets a large batch of its own BATCH_SIZE = 200_000 def read_events(catalog: dict, table: str = "shop.events"): """Every row of `table`, as one PyArrow table.""" from pyiceberg.catalog import load_catalog properties = {key: value for key, value in catalog.items() if key != "name"} return ( load_catalog(catalog["name"], **properties).load_table(table).scan().to_arrow() ) if __name__ == "__main__": events = read_events(catalog) print(f"{events.num_rows} rows in shop.events") ``` ```yaml # The Write to Iceberg Tables guide: the shop appends an hour of orders to the Iceberg # table shop.events, as fast as the machine allows. ICEBERG_CATALOG picks the catalog # (sqlite, the default, rest, postgres or glue). Needs the folder # iceberg_tables_catalogs beside it, and for sqlite an empty folder iceberg. Run it # with: desflow run iceberg_tables.yaml simulation: {sim_id: Shop, factor: 0.0, random_seed: 42} resources: packers: {current_cap: 1, max_cap: 1} services: packing: {dist: constant, value: 1.5} arrivals: orders: {dist: exponential, rate: 0.5, spawn: pack_order} tasks: pack_order: service: packing resource: packers # The finished event is the order record payload: order_id: {gen: sequence} amount: 19.99 egress: # Every event as a row of shop.events, which the sink creates from the first batch - type: Iceberg config: default_table: shop.events catalog: !include iceberg_tables_catalogs/${ICEBERG_CATALOG:-sqlite}.yaml # One commit per flush, so the sink gets a large batch of its own batch_size: 200000 run: {until: 1 hour} ``` ```yaml # A SQL catalog on SQLite, with no service, for a first run. The folder iceberg must # exist name: sqlite type: sql uri: sqlite:///iceberg/catalog.db warehouse: iceberg/warehouse ``` ```yaml # The REST catalog of `odctl up catalog`, with the table files on its SeaweedFS name: rest type: rest uri: http://127.0.0.1:8181 warehouse: s3://warehouse/ s3.endpoint: http://127.0.0.1:8333 s3.access-key-id: user s3.secret-access-key: password s3.region: us-east-1 ``` ```yaml # A SQL catalog on the PostgreSQL of `odctl up postgres`, with local table files name: postgres type: sql uri: postgresql+psycopg2://user:password@127.0.0.1:5432/odctl warehouse: iceberg/warehouse ``` ```yaml # The AWS Glue Data Catalog, with the table files in S3 and the standard AWS settings name: glue type: glue glue.region: us-east-1 s3.region: us-east-1 warehouse: ${ICEBERG_WAREHOUSE:-s3://my-bucket/warehouse} ``` ```python """The shop of the Write Iceberg Tables page, built with the builder API. The shop appends an hour of orders to the Iceberg table shop.events, as fast as the machine allows. Run it with `python iceberg_tables.py`; rest needs `odctl up catalog`, postgres needs `odctl up postgres`, and glue needs AWS credentials and ICEBERG_WAREHOUSE. iceberg_tables.yaml and iceberg_tables_low_level.py are the same shop in YAML and the low-level API. All three import the catalog and the sink of iceberg_tables_catalog.py, which must be beside them. """ # ruff: noqa: E402 import logging from iceberg_tables_catalog import BATCH_SIZE, sink from desflow import IcebergStorageEgress, SimulationContext def build_shop(sink: IcebergStorageEgress) -> SimulationContext: """The shop, appending to the table of the sink given, as fast as it can.""" app = ( SimulationContext(sim_id="Shop", factor=0.0, random_seed=42) .add_resource("packers", current_cap=1, max_cap=1) .add_service("packing", dist="constant", value=1.5) .add_arrival("orders", dist="exponential", rate=0.5) .add_egress(sink, batch_size=BATCH_SIZE) ) @app.task(service_id="packing", resource_id="packers") def pack_order(task_id: int, entity): # The finished event is the order record return {"order_id": task_id, "amount": 19.99} @app.arrival_loop("orders") def orders(context: SimulationContext): while True: order = yield context.wait_for_arrival("orders") context.spawn(pack_order(context.next_instance("pack_order"), entity=order)) return app app = build_shop(sink) if __name__ == "__main__": logging.basicConfig( level=logging.INFO, format="%(levelname)s [%(asctime)s] %(message)s" ) app.run(until="1 hour") ``` ```python """The Write to Iceberg Tables guide, low-level API: the shop appends an hour of orders to the Iceberg table shop.events, as fast as the machine allows. The catalog and the sink are those of iceberg_tables_catalog.py, which must be beside this script. ICEBERG_CATALOG picks the catalog: sqlite (the default), rest, postgres or glue. Run it with `python iceberg_tables_low_level.py`. """ import itertools import logging from iceberg_tables_catalog import BATCH_SIZE, sink from desflow import ( CapacityConfig, DistributionConfig, DynamicRealtimeEnvironment, DynamicResource, Sampler, SimParameter, ) PARAMS = SimParameter( sim_id="Shop", arrival={"orders": DistributionConfig(dist="exponential", rate=0.5)}, service={"packing": DistributionConfig(dist="constant", value=1.5)}, resources={"packers": CapacityConfig(current_cap=1, max_cap=1)}, ) def pack_order(env, packers, sampler, key, task_id): path_id = "Shop.service.packing" env.publish_event( key, { "path_id": path_id, "sim_id": "Shop", "service": "packing", "status": "queued", }, "pack_order", task_id, ) with packers.request() as unit: yield unit env.publish_event( key, { "path_id": path_id, "sim_id": "Shop", "service": "packing", "status": "started", }, "pack_order", task_id, ) yield env.timeout(sampler.sample(env.registry.get_config(path_id))) # The finished event is the order record order = {"order_id": task_id, "amount": 19.99} env.publish_event(key, order, "pack_order", task_id) def orders(env, packers, sampler): gap = env.registry.get_config("Shop.arrival.orders") for number in itertools.count(1): yield env.timeout(sampler.sample(gap)) env.process(pack_order(env, packers, sampler, f"orders-{number}", number - 1)) def shop(sink, factor: float = 0.0) -> DynamicRealtimeEnvironment: """The shop, appending to the table of the sink given, as fast as it can.""" env = DynamicRealtimeEnvironment(factor=factor) env.registry.register_sim_parameter(PARAMS) # One commit per flush, so the sink gets a large batch of its own env.setup_egress([sink], batch_sizes=[BATCH_SIZE]) packers = DynamicResource(env, "Shop", "packers") env.process(orders(env, packers, Sampler(seed=42))) return env if __name__ == "__main__": logging.basicConfig( level=logging.INFO, format="%(levelname)s [%(asctime)s] %(message)s" ) env = shop(sink) # rows of shop.events in the catalog ICEBERG_CATALOG names try: env.run(until=3600) finally: env.teardown() ``` # Keep Records in Memory `InMemoryEgress` keeps a run's records in the Python program that runs the model, and returns them as `pyarrow` tables after the run. A program can then use the records in the same process, for example to train or test a model, with no file and no service. This page runs a shop for two minutes, reads its events and telemetry as tables, and converts the events to pandas. ______________________________________________________________________ ## Before You Start - [Egress](https://jaehyeon.me/desflow/latest/user-guide/live-runs-and-connectors/egress/#in-memory) describes the sink, and [Records and Telemetry](https://jaehyeon.me/desflow/latest/reference/records-and-telemetry/index.md) the fields of a record. - Install the extra: `pip install "desflow[parquet]"`. The sink needs pyarrow, from the same extra as the Parquet sink. - The conversion to pandas needs pandas, which desflow does not install: `pip install pandas`. ______________________________________________________________________ ## Steps ### Add the Sink The sink is added in Python in every form. The program then runs the model and reads the sink after the run: The blueprint names no sink: ```yaml # The Keep Records in Memory guide: one packer, orders about every 2 seconds, and # readings every 30 seconds. It names no sink, because a blueprint cannot name # InMemoryEgress: keep_records_in_memory_yaml.py loads it and adds the sink. # Run it with: python keep_records_in_memory_yaml.py simulation: {sim_id: Shop, factor: 0, random_seed: 42} resources: packers: {current_cap: 1, max_cap: 1} services: packing: {dist: constant, value: 1.5} arrivals: orders: {dist: exponential, rate: 0.5, spawn: pack_order} tasks: pack_order: service: packing resource: packers # The finished event is the order record payload: order_id: {gen: sequence} amount: 19.99 # Readings every 30 seconds, as telemetry stats: {level: minimal, interval: 30} run: {until: 120} ``` A blueprint cannot name `InMemoryEgress`, because `desflow run` has no program to hand the tables to: an entry `type: InMemory` is refused with a message that points to the two calls below. `SimulationContext.from_yaml()` loads the blueprint, and `add_egress()` adds the sink to it: ```python from keep_records_in_memory import show from desflow import InMemoryEgress, SimulationContext sink = InMemoryEgress() app = SimulationContext.from_yaml("keep_records_in_memory.yaml") app.add_egress(sink) if __name__ == "__main__": app.run() # until 120, from the blueprint show(sink) ``` ```python from desflow import InMemoryEgress, SimulationContext def build_shop(sink: InMemoryEgress) -> SimulationContext: """One packer, orders about every 2 seconds, records kept in the sink.""" app = ( SimulationContext(sim_id="Shop", factor=0, random_seed=42) .add_resource("packers", current_cap=1, max_cap=1) .add_service("packing", dist="constant", value=1.5) .add_arrival("orders", dist="exponential", rate=0.5) # Readings every 30 seconds, as telemetry .with_stats("minimal", interval=30) .add_egress(sink) ) @app.task(service_id="packing", resource_id="packers") def pack_order(task_id: int, entity): # The finished event is the order record return {"order_id": task_id, "amount": 19.99} @app.arrival_loop("orders") def orders(context: SimulationContext): while True: order = yield context.wait_for_arrival("orders") context.spawn(pack_order(context.next_instance("pack_order"), entity=order)) return app sink = InMemoryEgress() app = build_shop(sink) if __name__ == "__main__": app.run(until=120) show(sink) ``` `setup_egress` takes the sink as it takes any other. `teardown()` hands the sink the records that are still in its buffer, so the script reads the sink after it: ```python from keep_records_in_memory import show from desflow import InMemoryEgress def build_shop(sink: InMemoryEgress) -> DynamicRealtimeEnvironment: """One packer, orders about every 2 seconds, records kept in the sink.""" env = DynamicRealtimeEnvironment(factor=0) env.registry.register_sim_parameter(PARAMS) env.setup_egress([sink]) # Readings every 30 seconds, as telemetry env.setup_stats("Shop", "minimal", interval=30) packers = DynamicResource(env, "Shop", "packers") env.process(orders(env, packers, Sampler(seed=42))) return env if __name__ == "__main__": sink = InMemoryEgress() env = build_shop(sink) try: env.run(until=120) finally: env.teardown() # hands the sink the last records show(sink) ``` In the YAML and Builder forms, the run and the reading sit under `if __name__ == "__main__":`. `desflow check`, `desflow run --sample` and `desflow test`, and the MCP server, import a builder file without running that block. So they check or sample the model without reading a table that no run has filled. `desflow run` without `--sample` takes only a blueprint. ### Read the Tables `sink.table(name)` returns the records of one destination, and `sink.tables()` returns every destination that holds records. The sink keeps each record in the destination of its stream type: - `events`: one flat row for each event, with its payload as columns, as the Parquet sink writes it. `order_id` and `amount` are columns of their own. - `telemetry`: one row for each telemetry record except the step and segment readings, with its `path_id` and its `value`. A statistic's `value` is a double, and here every row is a statistic. - `steps`: the readings of `run.steps` and `run.segments`, whose `value` is a mapping, kept apart from the other telemetry so that each table has one type of `value`. This shop has neither, so it has no `steps` table. - `labels` and `trace`: the records of a sink added with `when="labels"` or `when="trace"`. The columns come from every record, so a key that first appears in a later record still gets its column, and it holds null in the rows without it. `timestamp` is the record's ISO text, as in the files. A destination with no records gives an empty table. The sink empties its tables when a run starts, so a context run twice holds only the second run. `show` prints each table, then converts the events to pandas: ```python import pandas as pd from desflow import InMemoryEgress def show(sink: InMemoryEgress) -> None: """Prints each table the run filled, and the type of `order_id` in pandas.""" for name, table in sink.tables().items(): print(f"{name}: {table.num_rows} rows, {table.num_columns} columns") events = sink.table("events") # The queued and started events have no order_id, so the column holds nulls print("to_pandas():", events.to_pandas()["order_id"].dtype) arrow = events.to_pandas(types_mapper=pd.ArrowDtype) print("types_mapper=pd.ArrowDtype:", arrow["order_id"].dtype) ``` ### Convert to pandas `table.to_pandas()` gives a pandas DataFrame with NumPy types. An integer column that holds a null becomes `float64`, because a NumPy integer has no null. The queued and started events have no `order_id`, so `order_id` is `float64`. `table.to_pandas(types_mapper=pd.ArrowDtype)` keeps pyarrow's types in pandas, so `order_id` stays an integer, `int64[pyarrow]`, with the nulls as ``. ______________________________________________________________________ ## Check the Result Save the files of your form from [Full Files](#full-files) in a folder of their own, each under the last part of its title. Every form needs `keep_records_in_memory.py`, which holds `show`. Run from that folder, each prints the tables and the type of `order_id`: The files are `keep_records_in_memory.yaml`, `keep_records_in_memory_yaml.py` and `keep_records_in_memory.py`: ```bash python keep_records_in_memory_yaml.py ``` The file is `keep_records_in_memory.py`: ```bash python keep_records_in_memory.py ``` The files are `keep_records_in_memory_low_level.py` and `keep_records_in_memory.py`: ```bash python keep_records_in_memory_low_level.py ``` ```text events: 134 rows, 12 columns telemetry: 20 rows, 5 columns to_pandas(): float64 types_mapper=pd.ArrowDtype: int64[pyarrow] ``` The YAML and Builder forms print these lines. The 134 events are 45 queued, 45 started and 44 finished events, because one order is still being packed when the run ends. The 20 telemetry rows are five readings at each of 30, 60, 90 and 120 seconds: the packers' `capacity`, `in_use`, `queue_length` and `utilization`, and the task's `in_progress`. The low-level form prints the same lines with `telemetry: 16 rows`, because its `pack_order` is a plain generator, and only a task of the Builder and YAML forms publishes `in_progress`. ______________________________________________________________________ ## Full Files Full files ```yaml # The Keep Records in Memory guide: one packer, orders about every 2 seconds, and # readings every 30 seconds. It names no sink, because a blueprint cannot name # InMemoryEgress: keep_records_in_memory_yaml.py loads it and adds the sink. # Run it with: python keep_records_in_memory_yaml.py simulation: {sim_id: Shop, factor: 0, random_seed: 42} resources: packers: {current_cap: 1, max_cap: 1} services: packing: {dist: constant, value: 1.5} arrivals: orders: {dist: exponential, rate: 0.5, spawn: pack_order} tasks: pack_order: service: packing resource: packers # The finished event is the order record payload: order_id: {gen: sequence} amount: 19.99 # Readings every 30 seconds, as telemetry stats: {level: minimal, interval: 30} run: {until: 120} ``` ```python """The Keep Records in Memory guide, YAML: the blueprint run with an in-memory sink. A blueprint cannot name InMemoryEgress, so this script loads keep_records_in_memory.yaml with SimulationContext.from_yaml() and adds the sink with add_egress(). python keep_records_in_memory_yaml.py runs the blueprint and prints what keep_records_in_memory.py prints. Both files must be beside it. """ # ruff: noqa: E402 import logging logging.basicConfig(level=logging.WARNING) from keep_records_in_memory import show from desflow import InMemoryEgress, SimulationContext sink = InMemoryEgress() app = SimulationContext.from_yaml("keep_records_in_memory.yaml") app.add_egress(sink) if __name__ == "__main__": app.run() # until 120, from the blueprint show(sink) ``` `show` is in `keep_records_in_memory.py`, in the Builder tab. ```python """The Keep Records in Memory guide, builder API: a run's records as pyarrow tables. The shop runs for two minutes with one packer and keeps its records in an InMemoryEgress. After the run, the script reads the events and the telemetry as pyarrow tables and converts the events to pandas, which must be installed (pip install pandas). python keep_records_in_memory.py prints the tables and the column types. keep_records_in_memory_yaml.py and keep_records_in_memory_low_level.py are the same shop from the YAML blueprint and in the low-level API; each imports `show` from this file, which must be beside it. """ # ruff: noqa: E402 import logging logging.basicConfig(level=logging.WARNING) import pandas as pd from desflow import InMemoryEgress def show(sink: InMemoryEgress) -> None: """Prints each table the run filled, and the type of `order_id` in pandas.""" for name, table in sink.tables().items(): print(f"{name}: {table.num_rows} rows, {table.num_columns} columns") events = sink.table("events") # The queued and started events have no order_id, so the column holds nulls print("to_pandas():", events.to_pandas()["order_id"].dtype) arrow = events.to_pandas(types_mapper=pd.ArrowDtype) print("types_mapper=pd.ArrowDtype:", arrow["order_id"].dtype) from desflow import InMemoryEgress, SimulationContext def build_shop(sink: InMemoryEgress) -> SimulationContext: """One packer, orders about every 2 seconds, records kept in the sink.""" app = ( SimulationContext(sim_id="Shop", factor=0, random_seed=42) .add_resource("packers", current_cap=1, max_cap=1) .add_service("packing", dist="constant", value=1.5) .add_arrival("orders", dist="exponential", rate=0.5) # Readings every 30 seconds, as telemetry .with_stats("minimal", interval=30) .add_egress(sink) ) @app.task(service_id="packing", resource_id="packers") def pack_order(task_id: int, entity): # The finished event is the order record return {"order_id": task_id, "amount": 19.99} @app.arrival_loop("orders") def orders(context: SimulationContext): while True: order = yield context.wait_for_arrival("orders") context.spawn(pack_order(context.next_instance("pack_order"), entity=order)) return app sink = InMemoryEgress() app = build_shop(sink) if __name__ == "__main__": app.run(until=120) show(sink) ``` ```python """The Keep Records in Memory guide, low-level API: the shop with an in-memory sink. The low-level version of the shop in keep_records_in_memory.py: one packer, orders about every 2 seconds, and readings every 30 seconds, kept in an InMemoryEgress. python keep_records_in_memory_low_level.py prints what keep_records_in_memory.py prints, with its `show`, so that file must be beside it. """ # ruff: noqa: E402 import itertools import logging from desflow import ( CapacityConfig, DistributionConfig, DynamicRealtimeEnvironment, DynamicResource, Sampler, SimParameter, ) logging.basicConfig(level=logging.WARNING) PARAMS = SimParameter( sim_id="Shop", arrival={"orders": DistributionConfig(dist="exponential", rate=0.5)}, service={"packing": DistributionConfig(dist="constant", value=1.5)}, resources={"packers": CapacityConfig(current_cap=1, max_cap=1)}, ) def pack_order(env, packers, sampler, key, task_id): path_id = "Shop.service.packing" env.publish_event( key, { "path_id": path_id, "sim_id": "Shop", "service": "packing", "status": "queued", }, "pack_order", task_id, ) with packers.request() as unit: yield unit env.publish_event( key, { "path_id": path_id, "sim_id": "Shop", "service": "packing", "status": "started", }, "pack_order", task_id, ) yield env.timeout(sampler.sample(env.registry.get_config(path_id))) # The finished event is the order record order = {"order_id": task_id, "amount": 19.99} env.publish_event(key, order, "pack_order", task_id) def orders(env, packers, sampler): gap = env.registry.get_config("Shop.arrival.orders") for number in itertools.count(1): yield env.timeout(sampler.sample(gap)) env.process(pack_order(env, packers, sampler, f"orders-{number}", number - 1)) from keep_records_in_memory import show from desflow import InMemoryEgress def build_shop(sink: InMemoryEgress) -> DynamicRealtimeEnvironment: """One packer, orders about every 2 seconds, records kept in the sink.""" env = DynamicRealtimeEnvironment(factor=0) env.registry.register_sim_parameter(PARAMS) env.setup_egress([sink]) # Readings every 30 seconds, as telemetry env.setup_stats("Shop", "minimal", interval=30) packers = DynamicResource(env, "Shop", "packers") env.process(orders(env, packers, Sampler(seed=42))) return env if __name__ == "__main__": sink = InMemoryEgress() env = build_shop(sink) try: env.run(until=120) finally: env.teardown() # hands the sink the last records show(sink) ``` `show` is in `keep_records_in_memory.py`, in the Builder tab. # Fit a Distribution Fit a column of your own measured times, such as the gaps between orders in an order log, and load the result into a model. ______________________________________________________________________ ## Before You Start - [Fitting the Inputs](https://jaehyeon.me/desflow/latest/learn/inputs/fit-the-inputs/index.md) fits the shop's packing times and checks what the choice changes. - [Input Fitting](https://jaehyeon.me/desflow/latest/user-guide/model-parts/input-fitting/index.md) describes every option and outcome. - Fitting needs the `fit` extra: `pip install "desflow[fit]"`. ______________________________________________________________________ ## Steps ### Make the Column A service is fitted to its durations. An arrival is fitted to the gaps between arrivals, not to the times they happened, so turn an order log's times into gaps first: ```python with LOG.open(newline="", encoding="utf-8") as handle: placed = [ datetime.fromisoformat(row["placed_at"]) for row in csv.DictReader(handle) ] # An arrival is fitted to the gaps between orders, not to the times themselves return [ (later - earlier).total_seconds() for earlier, later in zip(placed, placed[1:]) ] ``` `order_log.csv` is an illustrative log of 300 orders placed one afternoon, with the time each was placed to a tenth of a second. Write the gaps to a CSV column with one header, `gap_seconds`, to fit them with `desflow fit` instead: ```python path = Path(folder) / "gaps.csv" path.write_text("gap_seconds\n" + "".join(f"{gap}\n" for gap in gaps())) ``` `python fit_a_distribution.py` writes this `gaps.csv` into the folder you run it in. ### Fit It State the unit and the bounds. The gaps are in seconds and none can be below 0: ```python result = fit_column(gaps(), unit="s", lower=0) print(result.text()) # every candidate, its status and diagnostics ``` On the command line, `desflow fit gaps.csv --column gap_seconds --unit s --lower 0 --out fitted/orders.yaml` does the same. The table for the 299 gaps: ```text 299 rows: 299 used, 0 missing, 0 invalid family status AIC KS stat KS p (approx.) parameters or reason exponential * fitted 1205 0.03517 0.8404 rate=0.36388 normal fitted 1487 0.1707 4.359e-08 mean=2.74816, std=2.88857 (can draw below the lower bound 0) lognormal skipped lognormal needs every value above 0; 5 are not truncated_normal did not fit RuntimeError: Maximum number of function evaluations has been exceeded. constant skipped the values are not all equal uniform rejected its mean is 12.75, the data's is 2.748: more than 25% apart triangular rejected out of the family's range: triangular low is a time and must be 0 or more, got -1.2701238878321361 gamma skipped gamma needs every value above 0; 5 are not weibull skipped weibull needs every value above 0; 5 are not empirical fitted values: 299 numbers * best: exponential ``` ### Read the Table - **Skipped** families were not fitted, and the reason says why. Here the log's times are given to a tenth of a second, so some orders share a time, and 5 gaps are 0. `gamma`, `weibull` and `lognormal` need every value above 0, so they are skipped. - **Did not fit** means scipy's fit failed. Its message is the reason. Here the truncated normal's search did not settle, because the gaps are far from a normal shape. - **Rejected** families were fitted, but their mean or standard deviation is more than 25% from the data's, or a parameter is out of range. Here `uniform` reaches far beyond most gaps, and the fitted `triangular` has a start below 0, which a time cannot have. - **Fitted** families have an [AIC](https://jaehyeon.me/desflow/latest/learn/concepts/a-simulation-study/#aic-and-the-ks-test), where lower is better, and a Kolmogorov-Smirnov p-value, which is approximate. The `exponential` has the lowest AIC and a p-value of 0.84. Its rate, `rate: 0.36388`, is one over the mean gap of 2.75 seconds: an order every 2.75 seconds on average. `normal` fits too, but it can draw below 0. When two families' AIC are too close to tell them apart, as [AIC and the KS Test](https://jaehyeon.me/desflow/latest/learn/concepts/a-simulation-study/#aic-and-the-ks-test) explains, run the model with each and see whether the answer changes, as [Fitting the Inputs](https://jaehyeon.me/desflow/latest/learn/inputs/fit-the-inputs/#does-the-choice-matter) does. Read `--plot fit.png`, or `result.plot("fit.png")`, as well as the table. ### Load It Write the best fit with `--out`, or from Python: ```python path = Path(folder) / "fitted" / "orders.yaml" path.parent.mkdir(parents=True, exist_ok=True) path.write_text(result.yaml(source="order_log.csv, gaps between placed_at")) ``` and include it. An arrival also needs the task it spawns, so the include names the file and adds `spawn`: ```yaml arrivals: # The fitted gaps, with the task each order starts added to them orders: !include {file: fitted/orders.yaml, spawn: pack_order} ``` The file: ```yaml # Fitted by desflow fit from order_log.csv, gaps between placed_at: exponential, from # 299 values in s, written in seconds. dist: exponential rate: 0.36388 ``` ```python # The best fit's settings, such as dist="exponential", rate=0.4 .add_arrival("orders", **result.settings()) ``` ```python def params(result) -> SimParameter: """One packer, with the fitted arrivals.""" return SimParameter( sim_id="Shop", # The best fit's settings, such as dist="exponential", rate=0.4 arrival={"orders": DistributionConfig(**result.settings())}, service={"packing": DistributionConfig(dist="gamma", shape=4, scale=0.375)}, resources={"packers": CapacityConfig(current_cap=1, max_cap=2)}, ) ``` `result.settings("normal")` takes another fitted family instead of the best. ### When Nothing Fits When every family is skipped, rejected or did not fit, the best is the `empirical` distribution: the data itself, which a run draws from at random. For many values, a histogram is shorter: ```python result = fit_column(gaps(), unit="s", candidates=["empirical"], bins=10) ``` On the command line, the same is `--candidates empirical --bins 10`. An empirical distribution never draws a value outside the data's range, so it cannot produce a gap longer than the longest one in the log. ______________________________________________________________________ ## Check the Result Each form fits the gaps and runs the shop for an hour with the fitted arrivals. In that one run, one packer packs 1,335 orders in every form, because each uses the same seed, 42. The scripts read `order_log.csv` from their own folder, so run them in a clone of the repository: ```bash # The scripts and the order log are in docs/snippets/guides/ of the repository git clone https://github.com/jaehyeon-kim/desflow.git cd desflow/docs/snippets/guides ``` The blueprint includes `fitted/orders.yaml`, which the repository holds beside it, in `docs/snippets/yaml/`. It is the file that `write` and `desflow fit --out` write. The run prints its records, so keep the last count of finished orders: ```bash cd ../yaml desflow run fit_a_distribution.yaml --stdout | grep flows.orders.finished | tail -n 1 ``` ```text {"stream_type":"telemetry","sim_ts":3600.0,"timestamp":"...","path_id":"Shop.stats.flows.orders.finished","value":1335} ``` The timestamp is the wall-clock time of the run. ```bash python fit_a_distribution.py ``` ```text orders packed in an hour: 1335 ``` The script prints the table of candidates before this line, and writes `gaps.csv` into the folder. ```bash python fit_a_distribution_low_level.py ``` ```text orders packed in an hour: 1335 ``` The script prints the table of candidates before this line. ______________________________________________________________________ ## Full Files Full files ```yaml # The Fit a Distribution guide: the shop with arrivals fitted to an order log. # The fitted/ folder beside it holds the best fit, orders.yaml. write() in # docs/snippets/guides/fit_a_distribution.py, or desflow fit on gaps.csv with # --out fitted/orders.yaml, writes it again. Run it with: desflow run # fit_a_distribution.yaml simulation: {sim_id: Shop, factor: 0, random_seed: 42} resources: packers: {current_cap: 1, max_cap: 2} services: packing: {dist: gamma, shape: 4, scale: 0.375} arrivals: # The fitted gaps, with the task each order starts added to them orders: !include {file: fitted/orders.yaml, spawn: pack_order} tasks: pack_order: service: packing resource: packers payload: {event_type: order_packed} stats: basic run: {until: 1 h} ``` ```yaml # Fitted by desflow fit from order_log.csv, gaps between placed_at: exponential, from # 299 values in s, written in seconds. dist: exponential rate: 0.36388 ``` ```python """Fit a Distribution: the gaps between orders in an order log, fitted and loaded. order_log.csv is an illustrative log of 300 orders placed one afternoon, with the time each was placed. The script turns the times into the gaps between orders, fits them, prints the table of candidates, and runs the shop for an hour with the fitted arrivals. `write_gaps` writes the gaps to gaps.csv, and `write` saves the settings for a blueprint's `!include`. """ import csv import logging from datetime import datetime from pathlib import Path from desflow import SimulationContext, fit_column logging.basicConfig( level=logging.WARNING, format="%(levelname)s [%(asctime)s] %(message)s" ) LOG = Path(__file__).resolve().parent / "order_log.csv" def gaps(): """The gaps between consecutive orders, in seconds.""" with LOG.open(newline="", encoding="utf-8") as handle: placed = [ datetime.fromisoformat(row["placed_at"]) for row in csv.DictReader(handle) ] # An arrival is fitted to the gaps between orders, not to the times themselves return [ (later - earlier).total_seconds() for earlier, later in zip(placed, placed[1:]) ] def write_gaps(folder): """Writes the gaps to a CSV column, for `desflow fit`.""" path = Path(folder) / "gaps.csv" path.write_text("gap_seconds\n" + "".join(f"{gap}\n" for gap in gaps())) return path def fit(): """Every family fitted to the gaps.""" result = fit_column(gaps(), unit="s", lower=0) print(result.text()) # every candidate, its status and diagnostics return result def histogram(): """The empirical alternative: the gaps as a histogram of 10 bins.""" result = fit_column(gaps(), unit="s", candidates=["empirical"], bins=10) return result def write(result, folder): """Writes the best fit where a blueprint includes it.""" path = Path(folder) / "fitted" / "orders.yaml" path.parent.mkdir(parents=True, exist_ok=True) path.write_text(result.yaml(source="order_log.csv, gaps between placed_at")) return path def shop(result) -> SimulationContext: """One packer, with the fitted arrivals.""" app = ( SimulationContext(sim_id="Shop", factor=0, random_seed=42) .add_resource("packers", current_cap=1, max_cap=2) .add_service("packing", dist="gamma", shape=4, scale=0.375) # The best fit's settings, such as dist="exponential", rate=0.4 .add_arrival("orders", **result.settings()) .with_stats("basic") ) @app.task(service_id="packing", resource_id="packers") def pack_order(task_id): return {"event_type": "order_packed"} @app.arrival_loop("orders") def order_loop(context): task_id = 0 while True: order = yield context.wait_for_arrival("orders") context.spawn(pack_order(task_id, entity=order)) task_id += 1 return app if __name__ == "__main__": write_gaps(".") # the column that `desflow fit` reads app = shop(fit()) app.run(until="1 h") finished = app.env.stats.readings()["Shop.stats.flows.orders.finished"] print(f"orders packed in an hour: {finished}") ``` ```python """The Fit a Distribution guide, low-level API: the shop with arrivals fitted to an order log. python fit_a_distribution_low_level.py fits the gaps between the orders in order_log.csv, as fit_a_distribution.py does, and runs the shop for an hour with the fitted arrivals. It prints the number of orders packed. """ import asyncio import itertools import queue from desflow import ( CapacityConfig, DistributionConfig, DynamicRealtimeEnvironment, DynamicResource, Sampler, SimParameter, ) from fit_a_distribution import fit class Count: """An egress that counts the orders packed.""" def __init__(self): self.packed = 0 async def run(self, egress_queue): try: while True: try: for record in egress_queue.get_nowait(): value = record["value"] self.packed += value.get("event_type") == "order_packed" except queue.Empty: await asyncio.sleep(0.01) except asyncio.CancelledError: pass def params(result) -> SimParameter: """One packer, with the fitted arrivals.""" return SimParameter( sim_id="Shop", # The best fit's settings, such as dist="exponential", rate=0.4 arrival={"orders": DistributionConfig(**result.settings())}, service={"packing": DistributionConfig(dist="gamma", shape=4, scale=0.375)}, resources={"packers": CapacityConfig(current_cap=1, max_cap=2)}, ) def pack_order(env, packers, sampler, key, task_id): path_id = "Shop.service.packing" env.publish_event( key, { "path_id": path_id, "sim_id": "Shop", "service": "packing", "status": "queued", }, "pack_order", task_id, ) with packers.request() as unit: yield unit env.publish_event( key, { "path_id": path_id, "sim_id": "Shop", "service": "packing", "status": "started", }, "pack_order", task_id, ) yield env.timeout(sampler.sample(env.registry.get_config(path_id))) env.publish_event(key, {"event_type": "order_packed"}, "pack_order", task_id) def orders(env, packers, sampler): gap = env.registry.get_config("Shop.arrival.orders") for number in itertools.count(1): yield env.timeout(sampler.sample(gap)) env.process(pack_order(env, packers, sampler, f"orders-{number}", number - 1)) def run(result, until: float = 3600) -> int: """Runs the shop for an hour and returns the number of orders packed.""" count = Count() env = DynamicRealtimeEnvironment(factor=0) env.registry.register_sim_parameter(params(result)) env.setup_egress([count]) packers = DynamicResource(env, "Shop", "packers") env.process(orders(env, packers, Sampler(seed=42))) env.run(until=until) env.teardown() # waits until the sink has taken every batch return count.packed if __name__ == "__main__": print(f"orders packed in an hour: {run(fit())}") ``` # Check Against Theory Check a model against the queueing formulas, on a queue the formulas describe. A model that agrees is computing what it should. A model that differs has a defect to find. ______________________________________________________________________ ## Before You Start - [Queues and Capacity](https://jaehyeon.me/desflow/latest/learn/first-model/queues-and-capacity/index.md) explains [utilisation](https://jaehyeon.me/desflow/latest/learn/concepts/queueing-basics/#utilisation) and the waits the formulas give. - [Checking a Model](https://jaehyeon.me/desflow/latest/learn/studies/checking-a-model/index.md) places this check among the others. - [Queueing Basics](https://jaehyeon.me/desflow/latest/learn/concepts/queueing-basics/index.md) gives the formulas. ______________________________________________________________________ ## Steps ### Build a Queue the Formulas Describe The [M/M/1](https://jaehyeon.me/desflow/latest/learn/concepts/queueing-basics/#kendalls-notation) and M/M/c formulas hold when the gaps between arrivals and the service times are exponential, every arrival joins one queue and waits until it is served, and nothing changes while the model runs. This shop has one packer, an order every 1.33 seconds on average (`rate: 0.75`) and a mean packing time of 1 second. Its utilisation is therefore 0.75 × 1 ÷ 1 = 0.75: ```yaml simulation: sim_id: Shop factor: 0 random_seed: 42 warmup: 2000 # seconds left out of every measure, while the queue fills arrivals: # An order every 1.33 s on average (rate 0.75) with one packer; RATE=1.5 with # PACKERS=2 orders: dist: exponential rate: ${RATE:-0.75} spawn: pack_order services: packing: {dist: exponential, rate: 1} # 1 second on average resources: packers: current_cap: ${PACKERS:-1} max_cap: 4 tasks: pack_order: service: packing resource: packers payload: {event_type: order_packed} run: {until: 20000} ``` ```python # An order every 1.33 s on average (rate 0.75) with one packer; RATE=1.5 with PACKERS=2 rate = float(os.environ.get("RATE", "0.75")) packers = int(os.environ.get("PACKERS", "1")) app = ( # warmup: seconds left out of every measure, while the queue fills SimulationContext(sim_id="Shop", factor=0, random_seed=42, warmup=2000) .add_arrival("orders", dist="exponential", rate=rate, spawn="pack_order") .add_service("packing", dist="exponential", rate=1) # 1 second on average .add_resource("packers", current_cap=packers, max_cap=4) ) @app.task(service_id="packing", resource_id="packers") def pack_order(task_id): return {"event_type": "order_packed"} ``` The low-level API has no analysis: `explain` and `analyze` read a blueprint or a builder file. Write the model as a [builder file](https://jaehyeon.me/desflow/latest/user-guide/writing-a-model/builder-api/index.md) to check it. The highlighted lines of the blueprint are the [warm-up](https://jaehyeon.me/desflow/latest/learn/concepts/output-analysis/#one-run-starts-empty) and the three numbers the formulas read: the arrival rate, the service rate and the number of packers. The warm-up leaves out the first 2,000 seconds, while the queue fills from empty. `RATE` and `PACKERS` set the second case below. Work out the mean wait by hand first. For one packer it is ρ ÷ (1 − ρ) × the mean service time, where ρ is the utilisation. For several packers it is the [Erlang C](https://jaehyeon.me/desflow/latest/learn/concepts/queueing-basics/#several-packers) chance that every packer is busy, divided by (c ÷ the mean service time − the arrival rate): ```python load = rate * service # packers' worth of work arriving each second utilisation = load / packers if packers == 1: return utilisation / (1 - utilisation) * service # M/M/1 # M/M/c: Erlang C, the chance that every packer is busy, over (c / service - rate) last = load**packers / math.factorial(packers) / (1 - utilisation) busy = last / (sum(load**k / math.factorial(k) for k in range(packers)) + last) return busy / (packers / service - rate) ``` With one packer at utilisation 0.75, the mean wait is 0.75 ÷ 0.25 × 1 = 3 seconds. With two packers and 1.5 orders a second, it is 1.286 seconds. ### Verify It `desflow explain` gives the same values from the blueprint, and `--verify` runs the model and compares. Each pair is a value from the formulas and the same measure from the runs. A pair differs by one of two rules: - With `--replications 10`, the model runs ten times. A pair differs when the formula's value lies outside the [95% interval](https://jaehyeon.me/desflow/latest/learn/concepts/output-analysis/#interval-and-half-width) of the runs and is more than 1 percent from their mean. - With one run, a pair differs when the two values are more than 10 percent apart. The 1 percent matters when every run gives the same value, as with constant times. The interval then has a width of 0, and the last order still being packed at the end would count as a difference. This command runs ten replications. A builder file has no `run.until`, so its command gives the end of each run: ```bash desflow explain check_against_theory.yaml --verify --replications 10 ``` ```bash desflow explain check_against_theory_shop.py --verify --replications 10 --until 20000 ``` The low-level API has no analysis: `explain` and `analyze` read a blueprint or a builder file. Write the model as a [builder file](https://jaehyeon.me/desflow/latest/user-guide/writing-a-model/builder-api/index.md) to check it. Both print the same tables, because they are the same model with the same seed: ```text Shop `-- orders (arrival, rate 0.75/s) `-- spawn -> pack_order (task, rate 0.75/s) +-- uses packers (resource) `-- next (share 1) -> exit Resources +--------------------------------------------------+ | resource | λ | μ | c | ρ | Wq | L | status | |----------+------+---+---+------+----+---+--------| | packers | 0.75 | 1 | 1 | 0.75 | 3 | 3 | OK | +--------------------------------------------------+ packers by units +---------------------+ | c | ρ | status | |---+--------+--------| | 1 | 0.75 | OK | | 2 | 0.375 | OK | | 3 | 0.25 | OK | | 4 | 0.1875 | OK | +---------------------+ Bottleneck: packers Hints for utilisation 0.85: packers with 1 unit: utilisation 0.75, at most 0.85 packers with 1 unit: utilisation 0.85 at a request every 1.18 seconds (51 a minute, 0.85 a second) Verify: 10 runs to 20000 s, seed 42 +---------------------------------------------------------------------+ | node | measure | analysis | measured | ± | result | |------------+--------------+----------+----------+----------+--------| | packers | utilization | 0.75 | 0.7502 | 0.007597 | agrees | | packers | queue_length | 2.25 | 2.267 | 0.1765 | agrees | | pack_order | wait | 3 | 3.02 | 0.2166 | agrees | | orders | throughput | 0.75 | 0.7501 | 0.005283 | agrees | +---------------------------------------------------------------------+ --verify checks the implementation against the queueing analysis where it applies; it does not show that the model is close enough to the real system ``` Every measure agrees: the utilisation, the queue length Lq = λ × Wq, the mean wait of 3 seconds and the throughput. With two packers at the same utilisation, the wait comes from Erlang C: ```bash PACKERS=2 RATE=1.5 desflow explain check_against_theory.yaml --verify --replications 10 ``` ```bash # Twice the orders and two packers, checked against the formulas PACKERS=2 RATE=1.5 desflow explain check_against_theory_shop.py --verify --replications 10 --until 20000 ``` The low-level API has no analysis: `explain` and `analyze` read a blueprint or a builder file. Write the model as a [builder file](https://jaehyeon.me/desflow/latest/user-guide/writing-a-model/builder-api/index.md) to check it. ```text Verify: 10 runs to 20000 s, seed 42 +---------------------------------------------------------------------+ | node | measure | analysis | measured | ± | result | |------------+--------------+----------+----------+----------+--------| | packers | utilization | 0.75 | 0.7488 | 0.005598 | agrees | | packers | queue_length | 1.929 | 1.912 | 0.1241 | agrees | | pack_order | wait | 1.286 | 1.274 | 0.0761 | agrees | | orders | throughput | 1.5 | 1.5 | 0.008894 | agrees | +---------------------------------------------------------------------+ --verify checks the implementation against the queueing analysis where it applies; it does not show that the model is close enough to the real system ``` From Python, `analyze(verify=True)` runs the same check and returns it as `explanation.verification`. This function prints each pair: ```python def show(explanation): """Prints each pair of the verification: the formula's value and the runs'.""" for c in explanation.verification.comparisons: result = "differs" if c.differs else "agrees" print( f"{c.node} {c.measure}: analysis {c.analytical:.3f}, " f"runs {c.measured:.3f} ± {c.half_width:.3f}, {result}" ) ``` Each form loads its model from its file and passes the result to `show`: ```python app = SimulationContext.from_yaml(BLUEPRINT) explanation = app.analyze(verify=True, replications=10) # until from run.until show(explanation) ``` ```python app = load_context(SHOP.parent, SHOP.name) # a new copy for each run needs a file explanation = app.analyze(verify=True, until=20000, replications=10) show(explanation) ``` The low-level API has no analysis: `explain` and `analyze` read a blueprint or a builder file. Write the model as a [builder file](https://jaehyeon.me/desflow/latest/user-guide/writing-a-model/builder-api/index.md) to check it. ```text packers utilization: analysis 0.750, runs 0.750 ± 0.008, agrees packers queue_length: analysis 2.250, runs 2.267 ± 0.177, agrees pack_order wait: analysis 3.000, runs 3.020 ± 0.217, agrees orders throughput: analysis 0.750, runs 0.750 ± 0.005, agrees ``` A context built in a script's own code refuses `verify=True`, because the runs need a new copy of the model, which only a file can give. `--json` prints the same result as JSON, for a script or a CI job outside Python. Each comparison has `node`, `measure`, `analytical`, `measured`, `half_width` and `differs`. With `jq -e`, this command prints `true` and exits 0 when no pair differs, and exits 1 when one does: ```bash # Exit with an error when any reading differs from its formula desflow explain check_against_theory.yaml --verify --replications 10 --json | jq -e '[.verification.comparisons[] | select(.differs)] | length == 0' ``` The JSON shape is experimental through 1.x, as the [Changelog](https://jaehyeon.me/desflow/latest/about/changelog/index.md) says. ______________________________________________________________________ ## Check the Result Every pair says `agrees` for the shop above. When one says `differs`, read it as follows. ### Read a Difference A pair that differs on a model the formulas describe points at the model: a wrong rate or unit, a task that holds its resource longer than its service, or a route that sends entities somewhere else. Chance can also make a pair differ. A short run varies from one run to the next. With replications, each pair's 95% interval misses a correct value about 1 time in 20, so among many pairs one difference is expected now and then. Before looking for a defect, run the check again with more [replications](https://jaehyeon.me/desflow/latest/learn/concepts/output-analysis/#replications), a longer `until` or another seed. Agreement shows the program computes what the model on paper says. It says nothing about whether the model is close enough to the real shop, which only a comparison with the shop's own records can show, as [Checking a Model](https://jaehyeon.me/desflow/latest/learn/studies/checking-a-model/index.md) does. ### When the Formulas Do Not Apply `explain` estimates a wait only where a formula holds, and gives the reason where none does. Two packers whose packing always takes 1 second have no closed formula: ```yaml simulation: {sim_id: Shop, factor: 0} arrivals: orders: {dist: exponential, rate: 1.5, spawn: pack_order} services: packing: {dist: constant, value: 1 s} resources: packers: {current_cap: 2, max_cap: 4} tasks: pack_order: service: packing resource: packers payload: {event_type: order_packed} ``` `desflow explain check_against_theory_constant.yaml` prints the same reason under `Not estimated`. ```python app = SimulationContext(sim_id="Shop", factor=0) app.add_arrival("orders", dist="exponential", rate=1.5, spawn="pack_order") app.add_service("packing", dist="constant", value=1) app.add_resource("packers", current_cap=2, max_cap=4) app.task("packing", "packers", name="pack_order")(lambda task_id: {}) packers = app.analyze().resources[0] print(f"utilisation {packers.utilization}, status {packers.status}") print(f"wait: {packers.wait_reason}") ``` The low-level API has no analysis: `explain` and `analyze` read a blueprint or a builder file. Write the model as a [builder file](https://jaehyeon.me/desflow/latest/user-guide/writing-a-model/builder-api/index.md) to check it. ```text utilisation 0.75, status OK wait: no closed formula for c > 1 with non-exponential times; run --verify to measure it ``` The utilisation is still known here, because it needs only the rates. The same rule applies to every model. The formulas hold in a plain network of queues: each task holds at most one resource, each queue serves first come, first served, and nothing blocks, removes, delays or reorders work. Anything else takes the formulas out of use, from the part of the model where it happens to the end of the flow: - a task's `patience`, `balk`, `fail`, `keep`, `get`, `put`, `signal`, `subscribe`, `interrupt` or `on` actions, preemption, or several resources held at once: that task and every task after it; - a task that an `interrupt` names (in the `interrupt` of a task, in an `on:` or `listen` entry of a task or a signal, or in a scenario step): that task and every task after it; - a `wait` other than a single `request`, such as a wait with two or more requests, or a request that a timeout of the same wait can end: that task and every task after it; - a spawn `count` other than 1, or a resource picked by `key` or `lowest`: that task and every task after it; - an arrival with a `group` other than 1 or with `active: false`: that arrival and every task after it; - a resource's `queue_limit`, custom type or breakdowns: the tasks that use it and every task after them; - an `on:` entry that sets a resource's capacity, or a resource family: the tasks that use the resource and every task after them; - an unstable resource: every task after its tasks, though the resource itself keeps its utilisation and status; - a priority queue whose tasks have different priorities: its wait, and every task after its tasks; - a scenario step that changes a parameter, an `on:` entry that sets an arrival or a service, live ingress, or an `add_process` function: every arrival and every task; - a replayed arrival, a hand-written arrival loop or a `next` function: every rate they could change; - a task started by a `spawn` entry of a task's `on:` or `listen` list, by a `task` branch of a `wait`, `open` or `subscribe`, by a `spawn` entry in the `on:` list of a signal a task fires, or by `on_interrupt_next` or `on_interrupt_run`: it has no rate, because how often it starts is known only in a run. A task outside what the formulas cover has no rate, so each resource it uses has no utilisation, status or wait. Such a resource is not ranked as the [bottleneck](https://jaehyeon.me/desflow/latest/learn/concepts/queueing-basics/#flow-balance-and-the-bottleneck). When no resource has a utilisation, `explain` says that no bottleneck can be named, and why. Each unknown value is printed under `Not estimated`, with the first reason found. One value is given but not compared. With one packer and gaps that are not exponential, such as constant or uniform gaps, [Kingman's formula](https://jaehyeon.me/desflow/latest/learn/concepts/queueing-basics/#variation-lengthens-waits) gives the wait only approximately, so `explain` shows it as an estimate. `--verify` marks that wait and the queue length `not compared`, because a correct model can differ from an approximation. `--verify` still runs such a model and prints what it measures. It compares only the values the analysis gives. Every other row says `not compared`, with the reason, and a row whose measure did not happen in the run says `no reading`. The interval from replications is then the check, as the experiments of [Checking a Model](https://jaehyeon.me/desflow/latest/learn/studies/checking-a-model/index.md) use it. ______________________________________________________________________ ## Full Files The script reads the blueprint and the builder file from the repository, so run it in a clone: ```bash # The script and the builder file are in docs/snippets/guides/, the blueprints in docs/snippets/yaml/ git clone https://github.com/jaehyeon-kim/desflow.git cd desflow/docs/snippets/guides python check_against_theory.py ``` Full files ```yaml # Check Against Theory: a shop the queueing formulas describe exactly. Gaps and # packing times are exponential, one queue, no limits, nothing changes during the run. # Check it with: desflow explain check_against_theory.yaml --verify --replications 10 simulation: sim_id: Shop factor: 0 random_seed: 42 warmup: 2000 # seconds left out of every measure, while the queue fills arrivals: # An order every 1.33 s on average (rate 0.75) with one packer; RATE=1.5 with # PACKERS=2 orders: dist: exponential rate: ${RATE:-0.75} spawn: pack_order services: packing: {dist: exponential, rate: 1} # 1 second on average resources: packers: current_cap: ${PACKERS:-1} max_cap: 4 tasks: pack_order: service: packing resource: packers payload: {event_type: order_packed} run: {until: 20000} egress: - {type: Console} ``` ```yaml # Check Against Theory: two packers whose packing always takes 1 second, which no # closed formula describes. # Check it with: desflow explain check_against_theory_constant.yaml simulation: {sim_id: Shop, factor: 0} arrivals: orders: {dist: exponential, rate: 1.5, spawn: pack_order} services: packing: {dist: constant, value: 1 s} resources: packers: {current_cap: 2, max_cap: 4} tasks: pack_order: service: packing resource: packers payload: {event_type: order_packed} ``` The script works out the waits by hand and verifies both the blueprint and the builder file: ```python """Check Against Theory: a shop the queueing formulas describe, checked against them. check_against_theory.yaml, and check_against_theory_shop.py in the builder, are one packer with exponential gaps and packing times. The script works out the wait by hand, verifies each form against `explain`'s analysis from Python, and shows a shop the formulas do not cover, with the reason. """ import math from pathlib import Path from desflow import SimulationContext, load_context BLUEPRINT = Path(__file__).resolve().parents[1] / "yaml" / "check_against_theory.yaml" SHOP = Path(__file__).resolve().parent / "check_against_theory_shop.py" def by_hand(packers: int, rate: float, service: float = 1.0) -> float: """The mean wait in the queue from the M/M/1 and M/M/c formulas.""" load = rate * service # packers' worth of work arriving each second utilisation = load / packers if packers == 1: return utilisation / (1 - utilisation) * service # M/M/1 # M/M/c: Erlang C, the chance that every packer is busy, over (c / service - rate) last = load**packers / math.factorial(packers) / (1 - utilisation) busy = last / (sum(load**k / math.factorial(k) for k in range(packers)) + last) return busy / (packers / service - rate) def show(explanation): """Prints each pair of the verification: the formula's value and the runs'.""" for c in explanation.verification.comparisons: result = "differs" if c.differs else "agrees" print( f"{c.node} {c.measure}: analysis {c.analytical:.3f}, " f"runs {c.measured:.3f} ± {c.half_width:.3f}, {result}" ) def verify(): """The blueprint's one packer, verified with 10 runs from Python.""" app = SimulationContext.from_yaml(BLUEPRINT) explanation = app.analyze(verify=True, replications=10) # until from run.until show(explanation) return explanation def verify_builder(): """The builder file's one packer, verified with 10 runs from Python.""" app = load_context(SHOP.parent, SHOP.name) # a new copy for each run needs a file explanation = app.analyze(verify=True, until=20000, replications=10) show(explanation) return explanation def unsupported(): """Two packers whose packing always takes 1 second: no formula for the wait.""" app = SimulationContext(sim_id="Shop", factor=0) app.add_arrival("orders", dist="exponential", rate=1.5, spawn="pack_order") app.add_service("packing", dist="constant", value=1) app.add_resource("packers", current_cap=2, max_cap=4) app.task("packing", "packers", name="pack_order")(lambda task_id: {}) packers = app.analyze().resources[0] print(f"utilisation {packers.utilization}, status {packers.status}") print(f"wait: {packers.wait_reason}") return packers if __name__ == "__main__": print(f"one packer, an order every 1.33 s (rate 0.75): {by_hand(1, 0.75):.3f} s") print(f"two packers at 1.5 orders a second: {by_hand(2, 1.5):.3f} s") verify() verify_builder() unsupported() ``` ```python """Check Against Theory: the shop of check_against_theory.yaml as a builder file. Check it with: desflow explain check_against_theory_shop.py --verify --replications 10 --until 20000 """ import os from desflow import SimulationContext # An order every 1.33 s on average (rate 0.75) with one packer; RATE=1.5 with PACKERS=2 rate = float(os.environ.get("RATE", "0.75")) packers = int(os.environ.get("PACKERS", "1")) app = ( # warmup: seconds left out of every measure, while the queue fills SimulationContext(sim_id="Shop", factor=0, random_seed=42, warmup=2000) .add_arrival("orders", dist="exponential", rate=rate, spawn="pack_order") .add_service("packing", dist="exponential", rate=1) # 1 second on average .add_resource("packers", current_cap=packers, max_cap=4) ) @app.task(service_id="packing", resource_id="packers") def pack_order(task_id): return {"event_type": "order_packed"} if __name__ == "__main__": app.run(until=20000) ``` `check_against_theory.py`, in the YAML tab, verifies this file too, with `verify_builder`. The low-level API has no analysis: `explain` and `analyze` read a blueprint or a builder file. Write the model as a [builder file](https://jaehyeon.me/desflow/latest/user-guide/writing-a-model/builder-api/index.md) to check it. # Test a Model Write tests for a model that fail when a change breaks it. This page writes four kinds: a functional test of what the model does when an input changes, a unit test of one component on its own, a test written in the blueprint that states the statistics of a seeded run, and a back test against results saved from an earlier run. ______________________________________________________________________ ## Before You Start - [Checking a Model](https://jaehyeon.me/desflow/latest/learn/studies/checking-a-model/index.md) checks the shop by hand, against observed values and against [Little's law](https://jaehyeon.me/desflow/latest/learn/concepts/queueing-basics/#littles-law). - [Checking and Validating](https://jaehyeon.me/desflow/latest/learn/concepts/checking-and-validating/index.md) says what each check proves. - The functional, unit and back tests follow the [Tests chapter](https://des.hsma.co.uk/tests.html) of the HSMA book on discrete event simulation. - You need pytest: `pip install pytest`. - To test a program that reads the model's records, such as a detector, see [Test a Pipeline](https://jaehyeon.me/desflow/latest/how-to/analysis/test-a-pipeline/index.md). ______________________________________________________________________ ## Steps ### Build a Model to Test A test changes one input and runs the model again, so write the model as a function of its inputs and return the numbers a test reads. This shop takes the number of packers, the order rate and the seed. `results` runs ten minutes of it. A blueprint reads its inputs from variables, so the YAML form sets them before it loads the blueprint: ```yaml simulation: sim_id: Shop factor: 0 random_seed: ${SEED:-42} resources: packers: {current_cap: "${PACKERS:-2}", max_cap: 10} arrivals: orders: {dist: exponential, rate: "${RATE:-0.5}", spawn: pack_order} services: packing: {dist: constant, value: 1.5} tasks: pack_order: service: packing resource: packers payload: {event_type: order_packed} stats: {level: typical, interval: 600} run: {until: 600} ``` `shop` sets the variables and loads the blueprint, and `results` runs it: ```python def shop(packers=2, rate=0.5, seed=42) -> SimulationContext: """The blueprint, with its inputs set through the variables it reads.""" inputs = {"PACKERS": str(packers), "RATE": str(rate), "SEED": str(seed)} with patch.dict(os.environ, inputs): # restored when the blueprint is loaded return SimulationContext.from_yaml(BLUEPRINT) def results(**inputs) -> dict: """Runs ten minutes of the shop and returns the orders packed and the mean wait.""" app = shop(**inputs) app.run() # until 600, from the blueprint readings = app.env.stats.readings() name = "Shop.stats.tasks.pack_order.{}".format return { "finished": readings[name("finished")], "wait_mean": round(readings[name("wait_mean")], 6), } ``` ```python def shop(packers=2, rate=0.5, seed=42) -> SimulationContext: """The shop with `packers` packers and orders at `rate` a second.""" app = ( SimulationContext(sim_id="Shop", factor=0, random_seed=seed) .add_resource("packers", current_cap=packers, max_cap=10) .add_arrival("orders", dist="exponential", rate=rate) .add_service("packing", dist="constant", value=1.5) .with_stats("typical", interval=600) ) @app.task(service_id="packing", resource_id="packers") def pack_order(task_id: int): return {"event_type": "order_packed"} @app.arrival_loop("orders") def order_generator(context: SimulationContext): task_id = 0 while True: order = yield context.wait_for_arrival("orders") context.spawn(pack_order(task_id, entity=order)) task_id += 1 return app def results(**inputs) -> dict: """Runs ten minutes of the shop and returns the orders packed and the mean wait.""" app = shop(**inputs) app.run(until=600) readings = app.env.stats.readings() name = "Shop.stats.tasks.pack_order.{}".format return { "finished": readings[name("finished")], "wait_mean": round(readings[name("wait_mean")], 6), } ``` ```python def pack_order(env, packers, task_id): key, stats = f"orders-{task_id + 1}", env.stats stats.task_queued("pack_order", task_id) with packers.request() as unit: yield unit stats.task_started("pack_order", task_id) yield env.timeout(1.5) env.publish_event(key, {"event_type": "order_packed"}, "pack_order", task_id) stats.task_finished("pack_order", task_id) def orders(env, packers, sampler): gap = env.registry.get_config("Shop.arrival.orders") for task_id in itertools.count(): yield env.timeout(sampler.sample(gap)) env.process(pack_order(env, packers, task_id)) def results(packers=2, rate=0.5, seed=42) -> dict: """Runs ten minutes of the shop and returns the orders packed and the mean wait.""" env = DynamicRealtimeEnvironment(factor=0) env.registry.register_sim_parameter( SimParameter( sim_id="Shop", arrival={"orders": DistributionConfig(dist="exponential", rate=rate)}, resources={"packers": CapacityConfig(current_cap=packers, max_cap=10)}, ) ) env.setup_stats("Shop", "typical", interval=600) unit = DynamicResource(env, "Shop", "packers") env.process(orders(env, unit, Sampler(seed=seed))) env.run(until=600) readings = env.stats.readings() env.teardown() name = "Shop.stats.tasks.pack_order.{}".format return { "finished": readings[name("finished")], "wait_mean": round(readings[name("wait_mean")], 6), } ``` ### Write a Functional Test The tests call only `results`, so they are the same in the file of every form. A functional test checks that the model behaves as expected when an input changes. Add packers and the mean wait must fall, so run one, two and three packers and compare the three waits: ```python def test_more_packers_shorten_the_wait(): """A functional test: change one input and check the output moves the right way.""" waits = [results(packers=packers)["wait_mean"] for packers in (1, 2, 3)] assert waits[0] > waits[1] > waits[2] ``` The test asserts the direction of the change, not the waits themselves. The waits are **2.142**, **0.158** and **0.016** seconds, from one 10-minute run each of this shop, not the busy hour of the tutorials. A test of the direction still passes when a change to the model moves them a little. ### Write a Unit Test A unit test checks one component alone. A distribution refuses a rate of 0, which would mean no orders ever. It also refuses a negative time to pack. `DistributionConfig` raises `ValueError` for each. `pytest.mark.parametrize` runs one test for each setting: ```python @pytest.mark.parametrize( "settings", [ {"dist": "exponential", "rate": 0}, # no orders ever {"dist": "constant", "value": -1}, # a negative time to pack ], ) def test_a_distribution_that_cannot_happen_is_refused(settings): """A unit test: one component, alone, refuses an input that means nothing.""" with pytest.raises(ValueError): DistributionConfig(**settings) ``` ### Write Tests in the Blueprint A blueprint carries tests of its own under `tests`. Each entry has these keys: - `name`: the name the test prints. - `seed`: the random seed of the run. Without it, the test uses the file's `random_seed`. - `until`: the end of the run. Without it, the test uses `run.until`. - `expect`: the statistics the run must give, each named as `measures` names it in an experiment file, such as `tasks.pack_order.finished`. A number must match exactly. `{value, within}` allows a difference of at most `within`. `desflow test` runs each entry once, unpaced, with no ingress and no egress, so a test contacts no service: ```yaml tests: # The statistics of one run of the file at its seed: 284 orders packed, 0.1576 s of # wait - name: two packers expect: tasks.pack_order.finished: 284 tasks.pack_order.wait_mean: {value: 0.1576, within: 0.001} # The same shop at another seed - name: another seed seed: 7 expect: {tasks.pack_order.finished: 306} ``` A builder file has no `tests` key, so its tests go in a file named `tests.yaml` in the same folder, and each names its `until`. The file `test_a_model.py` also needs one context at module level for `desflow test` to build: ```python # `desflow test test_a_model.py` builds this context and runs the tests of tests.yaml app = shop() ``` ```yaml tests: # A builder file has no run.until, so each test names its end - name: two packers until: 600 expect: tasks.pack_order.finished: 284 tasks.pack_order.wait_mean: {value: 0.1576, within: 0.001} # The same shop at another seed - name: another seed seed: 7 until: 600 expect: {tasks.pack_order.finished: 306} ``` `desflow test` reads a blueprint or a builder file. A model written with the low-level API is tested with pytest, as the other steps of this page do, or with a saved result, as [Write a Back Test](#write-a-back-test) shows. Run the tests of your form: ```bash desflow test test_a_model.yaml ``` ```bash desflow test test_a_model.py ``` `desflow test` has nothing to read in a low-level model. Run its tests with pytest, as the other steps of this page do, or write a back test, as [Write a Back Test](#write-a-back-test) shows. Each passing test prints `ok`: ```text ok test_a_model.yaml: two packers ok test_a_model.yaml: another seed ``` A test that differs prints each statistic with its expected and measured values, and the command exits with 1. With `finished: 300` in place of 284, the first test prints: ```text FAILED test_a_model.yaml: two packers tasks.pack_order.finished: expected 300, measured 284 ok test_a_model.yaml: another seed ``` `desflow test --fix` writes the measured values into the `expect` entries that differ, and into a test with no `expect`, instead of reporting them. Read the changes before you keep them. A test states the statistics at one seed of one version of desflow. A new release may draw its random numbers differently, so the same seed can give other values. After an upgrade, run `desflow test --fix` and read what changed. ### Write a Back Test A back test works for every form, including the low-level one. It checks that the code gives the results an earlier version of it gave, with the same inputs and the same seed. Save the results once, and the test compares every later run with the file: ```python def test_results_match_the_saved_run(): """A back test: the code reproduces what an earlier version of it produced.""" assert results() == json.loads(SAVED.read_text()) ``` The saved file holds **284** orders packed and a mean wait of **0.157602** seconds for two packers, written by `save_results`: ```python def save_results(): """Saves the results the back test compares with.""" SAVED.write_text(json.dumps(results(), indent=2) + "\n") ``` A back test fails on any change to the results, so a failure is either a fault or an intended change. Review the change. If it is intended, run `save_results` and commit the new file with the change that caused it. ______________________________________________________________________ ## Check the Result Save the files of your form from [Full Files](#full-files) in a folder of their own, each under the last part of its title, such as `test_a_model.yaml`. The back test needs the saved results, so write them once from that folder. pytest then collects the `test_` functions of a file whose name starts with `test_`. The three forms give the same results, so each passes the same four tests: The files are `test_a_model_yaml.py` and `test_a_model.yaml`: ```bash python -c "import test_a_model_yaml; test_a_model_yaml.save_results()" pytest test_a_model_yaml.py ``` ```text test_a_model_yaml.py .... [100%] ============================== 4 passed in 0.32s =============================== ``` The file is `test_a_model.py`: ```bash python -c "import test_a_model; test_a_model.save_results()" pytest test_a_model.py ``` ```text test_a_model.py .... [100%] ============================== 4 passed in 0.14s =============================== ``` The file is `test_a_model_low_level.py`: ```bash python -c "import test_a_model_low_level; test_a_model_low_level.save_results()" pytest test_a_model_low_level.py ``` ```text test_a_model_low_level.py .... [100%] ============================== 4 passed in 0.27s =============================== ``` The times differ from run to run. ______________________________________________________________________ ## Full Files Full files ```yaml # The Test a Model guide: the shop that test_a_model_yaml.py tests. Its inputs are # variables, so a test sets PACKERS, RATE and SEED and loads it again; each has the # value the tests use by default. `desflow test test_a_model.yaml` runs its `tests`. simulation: sim_id: Shop factor: 0 random_seed: ${SEED:-42} resources: packers: {current_cap: "${PACKERS:-2}", max_cap: 10} arrivals: orders: {dist: exponential, rate: "${RATE:-0.5}", spawn: pack_order} services: packing: {dist: constant, value: 1.5} tasks: pack_order: service: packing resource: packers payload: {event_type: order_packed} stats: {level: typical, interval: 600} run: {until: 600} tests: # The statistics of one run of the file at its seed: 284 orders packed, 0.1576 s of # wait - name: two packers expect: tasks.pack_order.finished: 284 tasks.pack_order.wait_mean: {value: 0.1576, within: 0.001} # The same shop at another seed - name: another seed seed: 7 expect: {tasks.pack_order.finished: 306} ``` ```python """Test a Model, YAML: the tests of test_a_model.py, run against the blueprint. test_a_model.yaml reads its inputs from the variables PACKERS, RATE and SEED, so `shop` sets them and loads the blueprint again. The tests and the saved results are those of test_a_model.py, so all three forms give the same numbers. Run them with: pytest test_a_model_yaml.py """ import json import logging import os from pathlib import Path from unittest.mock import patch import pytest from desflow import DistributionConfig, SimulationContext logging.getLogger("desflow").setLevel(logging.WARNING) HERE = Path(__file__).resolve().parent SAVED = HERE / "test_a_model_saved.json" BLUEPRINT = HERE / "test_a_model.yaml" def shop(packers=2, rate=0.5, seed=42) -> SimulationContext: """The blueprint, with its inputs set through the variables it reads.""" inputs = {"PACKERS": str(packers), "RATE": str(rate), "SEED": str(seed)} with patch.dict(os.environ, inputs): # restored when the blueprint is loaded return SimulationContext.from_yaml(BLUEPRINT) def results(**inputs) -> dict: """Runs ten minutes of the shop and returns the orders packed and the mean wait.""" app = shop(**inputs) app.run() # until 600, from the blueprint readings = app.env.stats.readings() name = "Shop.stats.tasks.pack_order.{}".format return { "finished": readings[name("finished")], "wait_mean": round(readings[name("wait_mean")], 6), } def test_more_packers_shorten_the_wait(): """A functional test: change one input and check the output moves the right way.""" waits = [results(packers=packers)["wait_mean"] for packers in (1, 2, 3)] assert waits[0] > waits[1] > waits[2] @pytest.mark.parametrize( "settings", [ {"dist": "exponential", "rate": 0}, # no orders ever {"dist": "constant", "value": -1}, # a negative time to pack ], ) def test_a_distribution_that_cannot_happen_is_refused(settings): """A unit test: one component, alone, refuses an input that means nothing.""" with pytest.raises(ValueError): DistributionConfig(**settings) def test_results_match_the_saved_run(): """A back test: the code reproduces what an earlier version of it produced.""" assert results() == json.loads(SAVED.read_text()) def save_results(): """Saves the results the back test compares with.""" SAVED.write_text(json.dumps(results(), indent=2) + "\n") ``` ```python """Test a Model: functional, unit and back tests of the shop, with pytest. The shop has packers, an order every 2 seconds on average (exponential, rate 0.5) and 1.5 seconds of packing. Write the saved results once with `save_results()`, then run the tests with: pytest test_a_model.py `save_results()` writes test_a_model_saved.json, the results the back test compares with. Run it again only when a change to the results is intended. """ import json import logging from pathlib import Path import pytest from desflow import DistributionConfig, SimulationContext logging.getLogger("desflow").setLevel(logging.WARNING) SAVED = Path(__file__).resolve().parent / "test_a_model_saved.json" def shop(packers=2, rate=0.5, seed=42) -> SimulationContext: """The shop with `packers` packers and orders at `rate` a second.""" app = ( SimulationContext(sim_id="Shop", factor=0, random_seed=seed) .add_resource("packers", current_cap=packers, max_cap=10) .add_arrival("orders", dist="exponential", rate=rate) .add_service("packing", dist="constant", value=1.5) .with_stats("typical", interval=600) ) @app.task(service_id="packing", resource_id="packers") def pack_order(task_id: int): return {"event_type": "order_packed"} @app.arrival_loop("orders") def order_generator(context: SimulationContext): task_id = 0 while True: order = yield context.wait_for_arrival("orders") context.spawn(pack_order(task_id, entity=order)) task_id += 1 return app def results(**inputs) -> dict: """Runs ten minutes of the shop and returns the orders packed and the mean wait.""" app = shop(**inputs) app.run(until=600) readings = app.env.stats.readings() name = "Shop.stats.tasks.pack_order.{}".format return { "finished": readings[name("finished")], "wait_mean": round(readings[name("wait_mean")], 6), } # `desflow test test_a_model.py` builds this context and runs the tests of tests.yaml app = shop() def test_more_packers_shorten_the_wait(): """A functional test: change one input and check the output moves the right way.""" waits = [results(packers=packers)["wait_mean"] for packers in (1, 2, 3)] assert waits[0] > waits[1] > waits[2] @pytest.mark.parametrize( "settings", [ {"dist": "exponential", "rate": 0}, # no orders ever {"dist": "constant", "value": -1}, # a negative time to pack ], ) def test_a_distribution_that_cannot_happen_is_refused(settings): """A unit test: one component, alone, refuses an input that means nothing.""" with pytest.raises(ValueError): DistributionConfig(**settings) def test_results_match_the_saved_run(): """A back test: the code reproduces what an earlier version of it produced.""" assert results() == json.loads(SAVED.read_text()) def save_results(): """Saves the results the back test compares with.""" SAVED.write_text(json.dumps(results(), indent=2) + "\n") ``` Save this file as `tests.yaml` in the same folder: ```yaml # The Test a Model guide, Builder tab: the tests of test_a_model.py. Save this file as # tests.yaml in the folder of test_a_model.py, and run: desflow test test_a_model.py tests: # A builder file has no run.until, so each test names its end - name: two packers until: 600 expect: tasks.pack_order.finished: 284 tasks.pack_order.wait_mean: {value: 0.1576, within: 0.001} # The same shop at another seed - name: another seed seed: 7 until: 600 expect: {tasks.pack_order.finished: 306} ``` ```python """Test a Model, low-level API: the tests of test_a_model.py, run against the shop written with the environment and the resource. The tests and the saved results are those of test_a_model.py, so all three forms give the same numbers. Run them with: pytest test_a_model_low_level.py """ import itertools import json import logging from pathlib import Path import pytest from desflow import ( CapacityConfig, DistributionConfig, DynamicRealtimeEnvironment, DynamicResource, Sampler, SimParameter, ) logging.getLogger("desflow").setLevel(logging.WARNING) SAVED = Path(__file__).resolve().parent / "test_a_model_saved.json" def pack_order(env, packers, task_id): key, stats = f"orders-{task_id + 1}", env.stats stats.task_queued("pack_order", task_id) with packers.request() as unit: yield unit stats.task_started("pack_order", task_id) yield env.timeout(1.5) env.publish_event(key, {"event_type": "order_packed"}, "pack_order", task_id) stats.task_finished("pack_order", task_id) def orders(env, packers, sampler): gap = env.registry.get_config("Shop.arrival.orders") for task_id in itertools.count(): yield env.timeout(sampler.sample(gap)) env.process(pack_order(env, packers, task_id)) def results(packers=2, rate=0.5, seed=42) -> dict: """Runs ten minutes of the shop and returns the orders packed and the mean wait.""" env = DynamicRealtimeEnvironment(factor=0) env.registry.register_sim_parameter( SimParameter( sim_id="Shop", arrival={"orders": DistributionConfig(dist="exponential", rate=rate)}, resources={"packers": CapacityConfig(current_cap=packers, max_cap=10)}, ) ) env.setup_stats("Shop", "typical", interval=600) unit = DynamicResource(env, "Shop", "packers") env.process(orders(env, unit, Sampler(seed=seed))) env.run(until=600) readings = env.stats.readings() env.teardown() name = "Shop.stats.tasks.pack_order.{}".format return { "finished": readings[name("finished")], "wait_mean": round(readings[name("wait_mean")], 6), } def test_more_packers_shorten_the_wait(): """A functional test: change one input and check the output moves the right way.""" waits = [results(packers=packers)["wait_mean"] for packers in (1, 2, 3)] assert waits[0] > waits[1] > waits[2] @pytest.mark.parametrize( "settings", [ {"dist": "exponential", "rate": 0}, # no orders ever {"dist": "constant", "value": -1}, # a negative time to pack ], ) def test_a_distribution_that_cannot_happen_is_refused(settings): """A unit test: one component, alone, refuses an input that means nothing.""" with pytest.raises(ValueError): DistributionConfig(**settings) def test_results_match_the_saved_run(): """A back test: the code reproduces what an earlier version of it produced.""" assert results() == json.loads(SAVED.read_text()) def save_results(): """Saves the results the back test compares with.""" SAVED.write_text(json.dumps(results(), indent=2) + "\n") ``` # Analyse the Event Log Write a run's events to Parquet, read them back with pyarrow and turn them into an event log: one row for each step an order took, with the entity, the event type, the event, the time and the run. Then find each order's wait and time in the shop, and the run's throughput. ______________________________________________________________________ ## Before You Start - [Streaming Out](https://jaehyeon.me/desflow/latest/learn/running-live/streaming-out/index.md) writes records to files. - [Egress](https://jaehyeon.me/desflow/latest/user-guide/live-runs-and-connectors/egress/index.md) describes the sink, and [Records and Telemetry](https://jaehyeon.me/desflow/latest/reference/records-and-telemetry/index.md) the fields of a record. - The analysis uses pyarrow only, with no pandas. Install it with `pip install "desflow[parquet]"`. ______________________________________________________________________ ## Steps ### Write the Events Add a Parquet sink, `ParquetStorageEgress`, to the shop. It writes one flat row for each event, in files named `events_<8 hex digits>.parquet`. The finished event carries a `status`, as the queued and started events do: ```yaml simulation: {sim_id: Shop, factor: 0, random_seed: 42} resources: packers: {current_cap: 1, max_cap: 1} services: packing: {dist: constant, value: 1.5} arrivals: orders: {dist: exponential, rate: 0.5, spawn: pack_order} tasks: pack_order: service: packing resource: packers # The finished event's value, so every event of a task has a status payload: {status: finished} egress: # One flat row per event, in files named events_<8 hex digits>.parquet - type: Parquet config: default_path: ${OUT:-analyse_output}/events.parquet run: {until: 120} ``` `run_yaml` loads it with the folder in `OUT`, and runs it: ```python def run_yaml( out: Path, blueprint: str = "analyse_the_event_log.yaml" ) -> SimulationContext: """Runs the blueprint for two minutes into an empty folder and returns it.""" shutil.rmtree(out, ignore_errors=True) # a run adds files; start empty with patch.dict(os.environ, {"OUT": str(out)}): # the folder the blueprint reads app = SimulationContext.from_yaml(blueprint) app.run() # until 120, from the blueprint return app ``` ```python def shop(out: Path) -> SimulationContext: """One packer, orders about every 2 seconds, events written to Parquet in out.""" app = ( SimulationContext(sim_id="Shop", factor=0, random_seed=42) .add_resource("packers", current_cap=1, max_cap=1) .add_service("packing", dist="constant", value=1.5) .add_arrival("orders", dist="exponential", rate=0.5) # One flat row per event, in files named events_<8 hex digits>.parquet .add_egress(ParquetStorageEgress(default_path=f"{out}/events.parquet")) ) @app.task(service_id="packing", resource_id="packers") def pack_order(task_id: int): # The finished event's value, so every event of a task has a status return {"status": "finished"} @app.arrival_loop("orders") def order_generator(context: SimulationContext): task_id = 0 while True: order = yield context.wait_for_arrival("orders") context.spawn(pack_order(task_id, entity=order)) task_id += 1 return app ``` ```python def pack_order(env, packers, sampler, key, task_id): path_id = "Shop.service.packing" env.publish_event( key, { "path_id": path_id, "sim_id": "Shop", "service": "packing", "status": "queued", }, "pack_order", task_id, ) with packers.request() as unit: yield unit env.publish_event( key, { "path_id": path_id, "sim_id": "Shop", "service": "packing", "status": "started", }, "pack_order", task_id, ) yield env.timeout(sampler.sample(env.registry.get_config(path_id))) # The finished event's value, so every event of a task has a status env.publish_event(key, {"status": "finished"}, "pack_order", task_id) def orders(env, packers, sampler): gap = env.registry.get_config("Shop.arrival.orders") for number in itertools.count(1): yield env.timeout(sampler.sample(gap)) env.process(pack_order(env, packers, sampler, f"orders-{number}", number - 1)) def shop(out: Path) -> DynamicRealtimeEnvironment: """One packer, orders about every 2 seconds, events written to Parquet in out.""" env = DynamicRealtimeEnvironment(factor=0) env.registry.register_sim_parameter(PARAMS) # One flat row per event, in files named events_<8 hex digits>.parquet env.setup_egress([ParquetStorageEgress(default_path=f"{out}/events.parquet")]) packers = DynamicResource(env, "Shop", "packers") env.process(orders(env, packers, Sampler(seed=42))) return env ``` A run adds files to the folder and never replaces them, so the script empties it before a run. ### Read Them Back From here on, the code is the same for every form. `pyarrow.dataset` reads every file under a folder as one table: ```python def read_events(out: Path) -> Table: """Every file the sink wrote under out, as one table of events.""" return ds.dataset(out, format="parquet").to_table() ``` One 2-minute run of the shop writes **134** rows in every form: 45 queued events, 45 started and 44 finished, because one order is still being packed when the run ends. ### Build the Event Log Each order's three events become the rows of an event log. A queued event is the order's arrival and its wait in the queue, a started event is the start of packing, and a finished event is the end of packing and the order leaving. The files are read in no fixed order, so the rows are sorted by time, and by the order of the statuses where times are equal: ```python # Each status of a task becomes these rows of the log, in this order ROWS = { "queued": [("arrival_departure", "arrival"), ("queue", "waiting_for_packer")], "started": [("resource_use", "packing_start")], "finished": [("resource_use_end", "packing_end"), ("arrival_departure", "depart")], } ORDER = list(ROWS) # queued, started, finished: the order of an order's events def event_log(events: Table, run: int = 1) -> Table: """The event log: one row for each step an order took, sorted by time. The files are read in no fixed order, so the rows are sorted by time and, at the same time, by the order of the statuses. """ packing = events.filter(pc.equal(events["task"], "pack_order")).to_pylist() packing.sort(key=lambda row: (row["sim_ts"], ORDER.index(row["status"]))) rows = [ { "entity_id": row["key"], "event_type": event_type, "event": event, "time": row["sim_ts"], "run": run, } for row in packing for event_type, event in ROWS[row["status"]] ] return Table.from_pylist(rows) ``` The log has **223** rows for **45** orders, and its columns are `entity_id`, `event_type`, `event`, `time` and `run`. This is the form [Animate a Run](https://jaehyeon.me/desflow/latest/how-to/analysis/animate-a-run/index.md) takes. ### Find Waits and Throughput An order's wait is the time from its arrival to the start of packing, and its time in the shop is the time from its arrival to its departure. Throughput is the number of orders that left in each minute of the run: ```python def times(log: Table, event: str) -> dict: """The time of `event` for each order that reached it.""" rows = log.filter(pc.equal(log["event"], event)) return dict(zip(rows["entity_id"].to_pylist(), rows["time"].to_pylist())) def waits_and_times(log: Table) -> dict: """Each order's wait, and its time in the shop if it left before the run ended.""" arrived = times(log, "arrival") started = times(log, "packing_start") left = times(log, "depart") return { order: { "wait": round(started[order] - arrived[order], 3), "in_shop": round(left[order] - arrived[order], 3) if order in left else None, } for order in started } def mean_wait(per_order: dict) -> float: """The mean wait of the orders that started packing, in seconds.""" return pc.mean(pa.array([row["wait"] for row in per_order.values()])).as_py() def throughput_per_minute(log: Table, seconds: float) -> float: """Orders that left the shop in each minute of the run.""" return len(times(log, "depart")) / (seconds / 60) ``` ______________________________________________________________________ ## Check the Result Save the files of your form from [Full Files](#full-files) in a folder of their own, each under the last part of its title. Every form needs `analyse_the_event_log.py`, which holds the analysis. Run from that folder, each writes the files to `analyse_output/` and prints the counts. The forms write the same events, so they print the same counts: The files are `analyse_the_event_log.yaml` and `analyse_the_event_log.py`. The argument `yaml` makes the script run the blueprint with `run_yaml`: ```bash python analyse_the_event_log.py yaml ``` The file is `analyse_the_event_log.py`: ```bash python analyse_the_event_log.py ``` The files are `analyse_the_event_log_low_level.py` and `analyse_the_event_log.py`: ```bash python analyse_the_event_log_low_level.py ``` ```text 223 rows in the log, for 45 orders mean wait 0.592 s throughput 22.0 orders a minute ``` The first order waits **0.0** seconds and is in the shop for **1.5** seconds. The mean wait is **0.592** seconds and the longest wait is **3.630** seconds. These come from one 2-minute run of a shop with one packer, not from the busy hour of the tutorials. **44** orders leave in two minutes, a throughput of **22.0** orders a minute. The 45th is still being packed, so it has a wait and no time in the shop. ______________________________________________________________________ ## Full Files Full files ```yaml # The Analyse the Event Log guide: one packer, orders about every 2 seconds, events # written to Parquet. The files go to analyse_output/, or to the folder in OUT, which # run_yaml() in analyse_the_event_log.py sets. Run it with: # desflow run analyse_the_event_log.yaml simulation: {sim_id: Shop, factor: 0, random_seed: 42} resources: packers: {current_cap: 1, max_cap: 1} services: packing: {dist: constant, value: 1.5} arrivals: orders: {dist: exponential, rate: 0.5, spawn: pack_order} tasks: pack_order: service: packing resource: packers # The finished event's value, so every event of a task has a status payload: {status: finished} egress: # One flat row per event, in files named events_<8 hex digits>.parquet - type: Parquet config: default_path: ${OUT:-analyse_output}/events.parquet run: {until: 120} ``` The analysis and `run_yaml` are in `analyse_the_event_log.py`, in the Builder tab. ```python """Analyse the Event Log: a run written to Parquet, read back as an event log. The shop runs for two minutes with one packer and writes its events to Parquet. The script reads the files with pyarrow, turns each order's three events into the rows of an event log (entity, event type, event, time, run), and computes each order's wait and time in the shop and the run's throughput. It uses pyarrow only, no pandas. python analyse_the_event_log.py writes the files to analyse_output/. With the argument yaml, `run_yaml` runs analyse_the_event_log.yaml (beside the script) instead, and analyse_the_event_log_low_level.py is the low-level API; each writes the same events. """ import logging import os import shutil import sys from pathlib import Path from unittest.mock import patch import pyarrow as pa import pyarrow.compute as pc import pyarrow.dataset as ds from pyarrow import Table from desflow import ParquetStorageEgress, SimulationContext logging.basicConfig(level=logging.WARNING) RUN_SECONDS = 120 def shop(out: Path) -> SimulationContext: """One packer, orders about every 2 seconds, events written to Parquet in out.""" app = ( SimulationContext(sim_id="Shop", factor=0, random_seed=42) .add_resource("packers", current_cap=1, max_cap=1) .add_service("packing", dist="constant", value=1.5) .add_arrival("orders", dist="exponential", rate=0.5) # One flat row per event, in files named events_<8 hex digits>.parquet .add_egress(ParquetStorageEgress(default_path=f"{out}/events.parquet")) ) @app.task(service_id="packing", resource_id="packers") def pack_order(task_id: int): # The finished event's value, so every event of a task has a status return {"status": "finished"} @app.arrival_loop("orders") def order_generator(context: SimulationContext): task_id = 0 while True: order = yield context.wait_for_arrival("orders") context.spawn(pack_order(task_id, entity=order)) task_id += 1 return app def run(out: Path) -> SimulationContext: """Runs the shop for two minutes into an empty folder and returns it.""" shutil.rmtree(out, ignore_errors=True) # a run adds files; start empty app = shop(out) app.run(until=RUN_SECONDS) return app def run_yaml( out: Path, blueprint: str = "analyse_the_event_log.yaml" ) -> SimulationContext: """Runs the blueprint for two minutes into an empty folder and returns it.""" shutil.rmtree(out, ignore_errors=True) # a run adds files; start empty with patch.dict(os.environ, {"OUT": str(out)}): # the folder the blueprint reads app = SimulationContext.from_yaml(blueprint) app.run() # until 120, from the blueprint return app def read_events(out: Path) -> Table: """Every file the sink wrote under out, as one table of events.""" return ds.dataset(out, format="parquet").to_table() # Each status of a task becomes these rows of the log, in this order ROWS = { "queued": [("arrival_departure", "arrival"), ("queue", "waiting_for_packer")], "started": [("resource_use", "packing_start")], "finished": [("resource_use_end", "packing_end"), ("arrival_departure", "depart")], } ORDER = list(ROWS) # queued, started, finished: the order of an order's events def event_log(events: Table, run: int = 1) -> Table: """The event log: one row for each step an order took, sorted by time. The files are read in no fixed order, so the rows are sorted by time and, at the same time, by the order of the statuses. """ packing = events.filter(pc.equal(events["task"], "pack_order")).to_pylist() packing.sort(key=lambda row: (row["sim_ts"], ORDER.index(row["status"]))) rows = [ { "entity_id": row["key"], "event_type": event_type, "event": event, "time": row["sim_ts"], "run": run, } for row in packing for event_type, event in ROWS[row["status"]] ] return Table.from_pylist(rows) def times(log: Table, event: str) -> dict: """The time of `event` for each order that reached it.""" rows = log.filter(pc.equal(log["event"], event)) return dict(zip(rows["entity_id"].to_pylist(), rows["time"].to_pylist())) def waits_and_times(log: Table) -> dict: """Each order's wait, and its time in the shop if it left before the run ended.""" arrived = times(log, "arrival") started = times(log, "packing_start") left = times(log, "depart") return { order: { "wait": round(started[order] - arrived[order], 3), "in_shop": round(left[order] - arrived[order], 3) if order in left else None, } for order in started } def mean_wait(per_order: dict) -> float: """The mean wait of the orders that started packing, in seconds.""" return pc.mean(pa.array([row["wait"] for row in per_order.values()])).as_py() def throughput_per_minute(log: Table, seconds: float) -> float: """Orders that left the shop in each minute of the run.""" return len(times(log, "depart")) / (seconds / 60) if __name__ == "__main__": folder = Path("analyse_output") run_yaml(folder) if sys.argv[1:] == ["yaml"] else run(folder) log = event_log(read_events(folder)) per_order = waits_and_times(log) print(f"{log.num_rows} rows in the log, for {len(per_order)} orders") print(f"mean wait {mean_wait(per_order):.3f} s") print(f"throughput {throughput_per_minute(log, RUN_SECONDS):.1f} orders a minute") ``` ```python """The Analyse the Event Log guide, low-level API: the shop written to Parquet. The low-level version of the shop in analyse_the_event_log.py: one packer, orders about every 2 seconds, each event written to Parquet with its status. python analyse_the_event_log_low_level.py writes the files to analyse_output/ and analyses them with the functions of analyse_the_event_log.py, which must be beside it. """ import itertools import logging import shutil from pathlib import Path from desflow import ( CapacityConfig, DistributionConfig, DynamicRealtimeEnvironment, DynamicResource, ParquetStorageEgress, Sampler, SimParameter, ) logging.basicConfig(level=logging.WARNING) RUN_SECONDS = 120 PARAMS = SimParameter( sim_id="Shop", arrival={"orders": DistributionConfig(dist="exponential", rate=0.5)}, service={"packing": DistributionConfig(dist="constant", value=1.5)}, resources={"packers": CapacityConfig(current_cap=1, max_cap=1)}, ) def pack_order(env, packers, sampler, key, task_id): path_id = "Shop.service.packing" env.publish_event( key, { "path_id": path_id, "sim_id": "Shop", "service": "packing", "status": "queued", }, "pack_order", task_id, ) with packers.request() as unit: yield unit env.publish_event( key, { "path_id": path_id, "sim_id": "Shop", "service": "packing", "status": "started", }, "pack_order", task_id, ) yield env.timeout(sampler.sample(env.registry.get_config(path_id))) # The finished event's value, so every event of a task has a status env.publish_event(key, {"status": "finished"}, "pack_order", task_id) def orders(env, packers, sampler): gap = env.registry.get_config("Shop.arrival.orders") for number in itertools.count(1): yield env.timeout(sampler.sample(gap)) env.process(pack_order(env, packers, sampler, f"orders-{number}", number - 1)) def shop(out: Path) -> DynamicRealtimeEnvironment: """One packer, orders about every 2 seconds, events written to Parquet in out.""" env = DynamicRealtimeEnvironment(factor=0) env.registry.register_sim_parameter(PARAMS) # One flat row per event, in files named events_<8 hex digits>.parquet env.setup_egress([ParquetStorageEgress(default_path=f"{out}/events.parquet")]) packers = DynamicResource(env, "Shop", "packers") env.process(orders(env, packers, Sampler(seed=42))) return env def run(out: Path) -> DynamicRealtimeEnvironment: """Runs the shop for two minutes into an empty folder and returns it.""" shutil.rmtree(out, ignore_errors=True) # a run adds files; start empty env = shop(out) env.run(until=RUN_SECONDS) env.teardown() # writes the last files return env if __name__ == "__main__": from analyse_the_event_log import ( event_log, mean_wait, read_events, throughput_per_minute, waits_and_times, ) folder = Path("analyse_output") run(folder) log = event_log(read_events(folder)) per_order = waits_and_times(log) print(f"{log.num_rows} rows in the log, for {len(per_order)} orders") print(f"mean wait {mean_wait(per_order):.3f} s") print(f"throughput {throughput_per_minute(log, RUN_SECONDS):.1f} orders a minute") ``` # Animate a Run Animate a run so each order is seen moving through the shop: arriving, waiting, being packed and leaving. ______________________________________________________________________ ## Before You Start - [Analyse the Event Log](https://jaehyeon.me/desflow/latest/how-to/analysis/analyse-the-event-log/index.md) writes the event log this page animates. - [vidigi](https://hsma-tools.github.io/vidigi/vidigi_docs/) is a separate package that animates a discrete event simulation from its event log. Install it with `pip install "vidigi==2.0.0"` and the `parquet` extra of desflow. ______________________________________________________________________ ## Steps ### Build the Log vidigi takes a pandas table with the columns `entity_id`, `event_type`, `event` and `time`, as the event log of Analyse the Event Log has them. It recognises the event types `arrival_departure`, `queue`, `resource_use` and `resource_use_end`. It draws a resource as numbered slots, so the rows of `resource_use` need a `resource_id` column. There is one packer, so the slot is 1: ```python def vidigi_log(out: Path) -> pd.DataFrame: """The run's event log as a pandas table, with the packer's slot on its use rows.""" log = event_log(read_events(out)).to_pandas() # vidigi draws the packers in numbered slots; there is one packer, so slot 1 log["resource_id"] = log["event_type"].eq("resource_use").map({True: 1}) return log ``` vidigi reads one run at a time, and refuses a log that holds more than one. ### Place the Events Each event is drawn at a position, with a label. The event that uses a resource names it, so vidigi draws the packers there: ```python # Where each event is drawn: the arrival, the queue, the packer and the exit POSITIONS = pd.DataFrame( [ {"event": "arrival", "x": 250, "y": 220, "label": "Arrival"}, {"event": "waiting_for_packer", "x": 250, "y": 160, "label": "Waiting"}, { "event": "packing_start", "x": 250, "y": 100, "label": "Packing", "resource": "packers", }, {"event": "depart", "x": 250, "y": 40, "label": "Shipped"}, ] ) ``` ### Animate `animate_activity_log` returns a Plotly figure. `scenario` gives the number of packers to draw, the times are in seconds, and `every_x_time_units` makes one frame for every 2 seconds: ```python def animation(log: pd.DataFrame) -> Figure: """The Plotly animation of the run, one frame for every 2 simulated seconds.""" figure = animate_activity_log( log, POSITIONS, scenario={"packers": 1}, # the number of packers drawn at the packing event simulation_time_unit="seconds", every_x_time_units=FRAME_SECONDS, limit_duration=RUN_SECONDS, plotly_height=480, override_x_max=400, stage_label_offset=30, # room for the order icon before each label override_y_max=260, text_size=14, entity_icon_size=16, gap_between_entities=32, # clear of the icon size at a phone width ) # Narrow side margins leave the plot wide enough for the labels on a phone figure.update_layout(margin={"l": 10, "r": 10}) return figure ``` ______________________________________________________________________ ## Check the Result `make` runs the shop into a folder and animates it. It takes the run of any form, because every form of the shop writes the same events: ```python def make(out: Path, run_shop=run) -> Figure: """Runs the shop into out and animates it. run_shop is the run of any form: run, run_yaml or the low-level script's run. """ run_shop(out) return animation(vidigi_log(out)) ``` The 2-minute run makes **61** frames, named 0, 2, 4 and on to 120, and the figure draws all **45** orders. Passing `run_yaml`, or the `run` of `analyse_the_event_log_low_level.py`, makes the same frames. `figure.write_html("animate_a_run.html", include_plotlyjs="cdn", config={"responsive": True})` saves the figure as a page that fits the width of its window. This is the animation of the script below. Press play, or drag the slider: ______________________________________________________________________ ## Full Files The script imports the functions of Analyse the Event Log, so keep it in one folder with the [files of that page](https://jaehyeon.me/desflow/latest/how-to/analysis/analyse-the-event-log/#full-files). Full files ```python """Animate a Run: the shop's event log, animated with vidigi. The script runs the shop of Analyse the Event Log for two minutes, reads its Parquet files back as an event log, adds the one column vidigi needs beyond it, and animates the run with vidigi 2.0.0's animate_activity_log: one frame for every 2 simulated seconds. python animate_a_run.py writes the animation to animate_a_run.html. Every form of the shop writes the same events, so `make` animates any of them. """ import tempfile from pathlib import Path import pandas as pd from analyse_the_event_log import RUN_SECONDS, event_log, read_events, run from plotly.graph_objects import Figure from vidigi.animation import animate_activity_log FRAME_SECONDS = 2 def vidigi_log(out: Path) -> pd.DataFrame: """The run's event log as a pandas table, with the packer's slot on its use rows.""" log = event_log(read_events(out)).to_pandas() # vidigi draws the packers in numbered slots; there is one packer, so slot 1 log["resource_id"] = log["event_type"].eq("resource_use").map({True: 1}) return log # Where each event is drawn: the arrival, the queue, the packer and the exit POSITIONS = pd.DataFrame( [ {"event": "arrival", "x": 250, "y": 220, "label": "Arrival"}, {"event": "waiting_for_packer", "x": 250, "y": 160, "label": "Waiting"}, { "event": "packing_start", "x": 250, "y": 100, "label": "Packing", "resource": "packers", }, {"event": "depart", "x": 250, "y": 40, "label": "Shipped"}, ] ) def animation(log: pd.DataFrame) -> Figure: """The Plotly animation of the run, one frame for every 2 simulated seconds.""" figure = animate_activity_log( log, POSITIONS, scenario={"packers": 1}, # the number of packers drawn at the packing event simulation_time_unit="seconds", every_x_time_units=FRAME_SECONDS, limit_duration=RUN_SECONDS, plotly_height=480, override_x_max=400, stage_label_offset=30, # room for the order icon before each label override_y_max=260, text_size=14, entity_icon_size=16, gap_between_entities=32, # clear of the icon size at a phone width ) # Narrow side margins leave the plot wide enough for the labels on a phone figure.update_layout(margin={"l": 10, "r": 10}) return figure def make(out: Path, run_shop=run) -> Figure: """Runs the shop into out and animates it. run_shop is the run of any form: run, run_yaml or the low-level script's run. """ run_shop(out) return animation(vidigi_log(out)) if __name__ == "__main__": with tempfile.TemporaryDirectory() as folder: figure = make(Path(folder)) figure.write_html( "animate_a_run.html", include_plotlyjs="cdn", config={"responsive": True} ) print(f"{len(figure.frames)} frames") ``` # Test a Pipeline Test a pipeline that reads a stream of records, such as a detector or an alert rule, against a fault that a seeded run plants and labels. The run is the same every time, so the test can say which fault the pipeline must find and where. ______________________________________________________________________ ## Before You Start - [Live Parameters](https://jaehyeon.me/desflow/latest/user-guide/live-runs-and-connectors/live-parameters/#record-what-a-change-was-for) explains the scenario step and the label record it publishes. - [Egress](https://jaehyeon.me/desflow/latest/user-guide/live-runs-and-connectors/egress/index.md) explains the `when` values of a sink. - [Test a Model](https://jaehyeon.me/desflow/latest/how-to/analysis/test-a-model/index.md) tests the model itself. This page tests a program that reads the model's records. - You need pytest: `pip install pytest`, and the JSON Lines sink, which needs the `parquet` extra: `pip install "desflow[parquet]"`. ______________________________________________________________________ ## Steps ### Plant a Fault and Label It The shop takes an order every 2 seconds on average. A scenario step at 300 seconds triples the rate, and its `record` publishes a ground-truth label of the fault. A second step at 360 seconds puts the rate back, with no label. Two sinks write what the run produces. The data sink gets the events only. The labels sink gets the labels only, so the pipeline under test never sees them. `OUT`, or the `folder` of the function, is where the two sinks write: ```yaml egress: # The data under test: events only, with no label - type: Jsonl config: {default_path: "${OUT:-output}/data/events.jsonl"} when: events # The labels only, for the scorer - type: Jsonl config: {default_path: "${OUT:-output}/labels/labels.jsonl"} when: labels ``` ```yaml scenario: # The fault: the order rate triples at 300 seconds, and the label says so - at: 300 path: Shop.arrival.orders.rate value: 1.5 record: {fault: order_surge} # The end of the fault, which needs no label - {at: 360, path: Shop.arrival.orders.rate, value: 0.5} ``` `run_shop` runs the blueprint, with `OUT` set to the folder: ```python def run_shop(folder: Path) -> None: """Runs the shop of the blueprint, writing its data and labels under `folder`.""" blueprint = Path(__file__).with_name("test_a_pipeline.yaml") SimulationContext.from_yaml(blueprint, variables={"OUT": str(folder)}).run() ``` ```python def run_shop(folder: Path) -> None: """Runs the shop, writing its data and labels under `folder`.""" app = ( SimulationContext(sim_id="Shop", factor=0, random_seed=7) .add_resource("packers", current_cap=3, max_cap=5) .add_service("packing", dist="constant", value=1.5) .add_arrival("orders", dist="exponential", rate=0.5, spawn="pack_order") # The data under test: events only, with no label .add_egress( JsonlStorageEgress(default_path=f"{folder}/data/events.jsonl"), when=lambda record: record["stream_type"] == "event", ) # The labels only, for the scorer .add_egress( JsonlStorageEgress(default_path=f"{folder}/labels/labels.jsonl"), when="labels", ) .add_scenario( [ # The fault: the order rate triples at 300 seconds, and the label says so { "at": 300, "path": "Shop.arrival.orders.rate", "value": 1.5, "record": {"fault": "order_surge"}, }, # The end of the fault, which needs no label {"at": 360, "path": "Shop.arrival.orders.rate", "value": 0.5}, ] ) ) @app.task(name="pack_order", service_id="packing", resource_id="packers") def pack_order(task_id): return {"event_type": "order_packed"} app.run(until="10 min") ``` ```python def run_shop(folder: Path) -> None: """Runs the shop, writing its data and labels under `folder`.""" env = DynamicRealtimeEnvironment(factor=0) env.registry.register_sim_parameter(PARAMS) env.setup_egress( [ # The data under test: events only, with no label JsonlStorageEgress(default_path=f"{folder}/data/events.jsonl"), # The labels only, for the scorer JsonlStorageEgress(default_path=f"{folder}/labels/labels.jsonl"), ], predicates=[lambda record: record["stream_type"] == "event", None], labels=[False, True], ) packers = DynamicResource(env, "Shop", "packers") env.process(run_scenario(env, STEPS, until=600)) env.process(orders(env, packers, Sampler(seed=7))) try: env.run(until=600) finally: env.teardown() ``` Each sink writes one file for each batch, named `events_<8 hex digits>.jsonl` and `labels_<8 hex digits>.jsonl`. The label file holds one line, with `sim_ts` 300 and the label `{"fault": "order_surge"}`. ### Write the Pipeline Under Test The pipeline counts the finished orders in each window of 10 seconds and flags a window when its count is more than 2.5 times the median count. A surge shows as flagged windows: ```python def count_orders(events: list[dict], window: int) -> list[int]: """Returns the number of finished orders in each window, from the first window.""" packed: Counter = Counter() for event in events: if "event_type" in event: packed[int(event["sim_ts"] // window)] += 1 return [packed[number] for number in range(max(packed) + 1)] def find_surges(events: list[dict], window: int = 10, factor: float = 2.5) -> list[int]: """Returns the start of each window with more than `factor` times the usual orders.""" counts = count_orders(events, window) limit = factor * statistics.median(counts) starts = [] for number, count in enumerate(counts): if count > limit: starts.append(number * window) return starts ``` ### Score It Against the Labels A fault is caught when a window is flagged within 60 seconds of its label. A flagged window with no fault before it is a false alarm: ```python def score(found: list[int], labels: list[dict], within: int = 60) -> dict: """Returns how many planted faults the flagged windows caught and missed, and how many flagged windows had no fault before them.""" faults = [label["sim_ts"] for label in labels] caught = 0 for fault in faults: if any(fault <= start < fault + within for start in found): caught += 1 false_alarms = 0 for start in found: if not any(fault <= start < fault + within for fault in faults): false_alarms += 1 return { "caught": caught, "missed": len(faults) - caught, "false": false_alarms, } ``` For this run the pipeline flags the windows that start at 320, 330 and 340 seconds. A window is flagged only when it holds more than 2.5 times the usual number of finished orders, so the first flagged window starts at 320 seconds, 20 seconds after the label. The score is one fault caught, none missed and no false alarm. ### Write the Tests The tests run the shop once, and check the labels, the data and the pipeline. The last test shows that the check can fail: a pipeline that flags only a window with ten times the usual orders misses the fault: ```python def test_the_labels_name_the_planted_fault(run): _, labels = run assert [label["label"] for label in labels] == [{"fault": "order_surge"}] assert [label["sim_ts"] for label in labels] == [300.0] def test_the_data_carries_no_label(run): events, _ = run assert {event["stream_type"] for event in events} == {"event"} def test_the_pipeline_catches_the_fault_without_a_false_alarm(run): events, labels = run assert score(find_surges(events), labels) == {"caught": 1, "missed": 0, "false": 0} def test_a_pipeline_that_is_too_strict_misses_the_fault(run): events, labels = run assert score(find_surges(events, factor=10), labels)["missed"] == 1 ``` ______________________________________________________________________ ## Check the Result Save the shop of your form as `pipeline_shop.py`, in a folder with `pipeline_under_test.py` and `test_a_pipeline.py`. For the YAML form, add `test_a_pipeline.yaml` to the folder. Then run: ```bash pytest test_a_pipeline.py ``` pytest reports 4 passed. The three forms flag the same windows and give the same score. A test of this kind states what a pipeline does on one seeded run. A new release of desflow may draw its random numbers differently, so after an upgrade, run the tests again and read any change before you keep it. ______________________________________________________________________ ## Full Files Full files ```python """The pipeline under test and its scorer, for the Test a Pipeline page. The pipeline reads the events of a run and flags the windows with unusually many orders. The scorer compares what it flagged with the labels of the faults the run planted. """ import glob import json import statistics from collections import Counter def read_lines(folder: str) -> list[dict]: """Every JSON line of every file under `folder`, in time order.""" lines = [] for path in glob.glob(f"{folder}/*.jsonl"): with open(path) as file: lines += [json.loads(line) for line in file] return sorted(lines, key=lambda line: line["sim_ts"]) def count_orders(events: list[dict], window: int) -> list[int]: """Returns the number of finished orders in each window, from the first window.""" packed: Counter = Counter() for event in events: if "event_type" in event: packed[int(event["sim_ts"] // window)] += 1 return [packed[number] for number in range(max(packed) + 1)] def find_surges(events: list[dict], window: int = 10, factor: float = 2.5) -> list[int]: """Returns the start of each window with more than `factor` times the usual orders.""" counts = count_orders(events, window) limit = factor * statistics.median(counts) starts = [] for number, count in enumerate(counts): if count > limit: starts.append(number * window) return starts def score(found: list[int], labels: list[dict], within: int = 60) -> dict: """Returns how many planted faults the flagged windows caught and missed, and how many flagged windows had no fault before them.""" faults = [label["sim_ts"] for label in labels] caught = 0 for fault in faults: if any(fault <= start < fault + within for start in found): caught += 1 false_alarms = 0 for start in found: if not any(fault <= start < fault + within for fault in faults): false_alarms += 1 return { "caught": caught, "missed": len(faults) - caught, "false": false_alarms, } ``` ```python """The Test a Pipeline page: tests of a pipeline against the labels of a planted fault. Save the shop of your form from the page as pipeline_shop.py in the folder of this file, with pipeline_under_test.py, and run: pytest test_a_pipeline.py """ import pytest from pipeline_shop import run_shop from pipeline_under_test import find_surges, read_lines, score @pytest.fixture(scope="module") def run(tmp_path_factory): """One run of the shop: its events and its labels.""" folder = tmp_path_factory.mktemp("run") run_shop(folder) return read_lines(f"{folder}/data"), read_lines(f"{folder}/labels") def test_the_labels_name_the_planted_fault(run): _, labels = run assert [label["label"] for label in labels] == [{"fault": "order_surge"}] assert [label["sim_ts"] for label in labels] == [300.0] def test_the_data_carries_no_label(run): events, _ = run assert {event["stream_type"] for event in events} == {"event"} def test_the_pipeline_catches_the_fault_without_a_false_alarm(run): events, labels = run assert score(find_surges(events), labels) == {"caught": 1, "missed": 0, "false": 0} def test_a_pipeline_that_is_too_strict_misses_the_fault(run): events, labels = run assert score(find_surges(events, factor=10), labels)["missed"] == 1 ``` ```yaml # The Test a Pipeline guide: a shop with a planted fault. Orders surge at 300 seconds # and the label of the fault goes only to the labels sink. OUT is the folder the two # sinks write under. Run it with: desflow run test_a_pipeline.yaml simulation: {sim_id: Shop, factor: 0, random_seed: 7} resources: packers: {current_cap: 3, max_cap: 5} services: packing: {dist: constant, value: 1.5} arrivals: orders: {dist: exponential, rate: 0.5, spawn: pack_order} tasks: pack_order: service: packing resource: packers payload: {event_type: order_packed} egress: # The data under test: events only, with no label - type: Jsonl config: {default_path: "${OUT:-output}/data/events.jsonl"} when: events # The labels only, for the scorer - type: Jsonl config: {default_path: "${OUT:-output}/labels/labels.jsonl"} when: labels scenario: # The fault: the order rate triples at 300 seconds, and the label says so - at: 300 path: Shop.arrival.orders.rate value: 1.5 record: {fault: order_surge} # The end of the fault, which needs no label - {at: 360, path: Shop.arrival.orders.rate, value: 0.5} run: {until: 10 min} ``` ```python """The Test a Pipeline page, YAML form: runs test_a_pipeline.yaml, beside this file, with its sinks under `folder`. Save it as pipeline_shop.py for the tests.""" from pathlib import Path from desflow import SimulationContext def run_shop(folder: Path) -> None: """Runs the shop of the blueprint, writing its data and labels under `folder`.""" blueprint = Path(__file__).with_name("test_a_pipeline.yaml") SimulationContext.from_yaml(blueprint, variables={"OUT": str(folder)}).run() ``` ```python """The Test a Pipeline page, builder form: the shop with a planted fault. Save it as pipeline_shop.py for the tests.""" from pathlib import Path from desflow import JsonlStorageEgress, SimulationContext def run_shop(folder: Path) -> None: """Runs the shop, writing its data and labels under `folder`.""" app = ( SimulationContext(sim_id="Shop", factor=0, random_seed=7) .add_resource("packers", current_cap=3, max_cap=5) .add_service("packing", dist="constant", value=1.5) .add_arrival("orders", dist="exponential", rate=0.5, spawn="pack_order") # The data under test: events only, with no label .add_egress( JsonlStorageEgress(default_path=f"{folder}/data/events.jsonl"), when=lambda record: record["stream_type"] == "event", ) # The labels only, for the scorer .add_egress( JsonlStorageEgress(default_path=f"{folder}/labels/labels.jsonl"), when="labels", ) .add_scenario( [ # The fault: the order rate triples at 300 seconds, and the label says so { "at": 300, "path": "Shop.arrival.orders.rate", "value": 1.5, "record": {"fault": "order_surge"}, }, # The end of the fault, which needs no label {"at": 360, "path": "Shop.arrival.orders.rate", "value": 0.5}, ] ) ) @app.task(name="pack_order", service_id="packing", resource_id="packers") def pack_order(task_id): return {"event_type": "order_packed"} app.run(until="10 min") ``` ```python """The Test a Pipeline page, low-level form: the shop with a planted fault. Save it as pipeline_shop.py for the tests.""" import itertools from pathlib import Path from desflow import ( CapacityConfig, DistributionConfig, DynamicRealtimeEnvironment, DynamicResource, JsonlStorageEgress, Sampler, SimParameter, run_scenario, ) PARAMS = SimParameter( sim_id="Shop", arrival={"orders": DistributionConfig(dist="exponential", rate=0.5)}, service={"packing": DistributionConfig(dist="constant", value=1.5)}, resources={"packers": CapacityConfig(current_cap=3, max_cap=5)}, ) # The fault: the order rate triples at 300 seconds, and the label says so STEPS = [ { "at": 300, "path": "Shop.arrival.orders.rate", "value": 1.5, "record": {"fault": "order_surge"}, }, # The end of the fault, which needs no label {"at": 360, "path": "Shop.arrival.orders.rate", "value": 0.5}, ] def pack_order(env, packers, sampler, key, task_id): with packers.request() as unit: yield unit yield env.timeout( sampler.sample(env.registry.get_config("Shop.service.packing")) ) env.publish_event(key, {"event_type": "order_packed"}, "pack_order", task_id) def orders(env, packers, sampler): gap = env.registry.get_config("Shop.arrival.orders") for number in itertools.count(1): yield env.timeout(sampler.sample(gap)) env.process(pack_order(env, packers, sampler, f"orders-{number}", number - 1)) def run_shop(folder: Path) -> None: """Runs the shop, writing its data and labels under `folder`.""" env = DynamicRealtimeEnvironment(factor=0) env.registry.register_sim_parameter(PARAMS) env.setup_egress( [ # The data under test: events only, with no label JsonlStorageEgress(default_path=f"{folder}/data/events.jsonl"), # The labels only, for the scorer JsonlStorageEgress(default_path=f"{folder}/labels/labels.jsonl"), ], predicates=[lambda record: record["stream_type"] == "event", None], labels=[False, True], ) packers = DynamicResource(env, "Shop", "packers") env.process(run_scenario(env, STEPS, until=600)) env.process(orders(env, packers, Sampler(seed=7))) try: env.run(until=600) finally: env.teardown() ``` # Call Python from YAML Read outside data during a run, or use a class of your own, from a blueprint. A reference of the form `!python module.attribute` takes the place of a value, and the blueprint uses the Python object it names. Most logic that once needed Python is a key of the blueprint now, so this page covers the two uses that stay. ______________________________________________________________________ ## Before You Start - [YAML Blueprints](https://jaehyeon.me/desflow/latest/user-guide/writing-a-model/blueprints/index.md) describes the blueprint file. - Install the Redis extra for the example: `pip install "desflow[redis]"`. Start the Valkey of odctl with `odctl up valkey`. See [Installation](https://jaehyeon.me/desflow/latest/installation/index.md) for the one-time odctl install. - Every file on this page is in the repository under [`docs/snippets/`](https://github.com/jaehyeon-kim/desflow/tree/v1.3.0/docs/snippets). ### When to Use It Use `!python` for one of these two things: - **Data that only an outside system holds during a run**, such as a model that another program keeps in a store. No key of the blueprint reads a store while the model runs. - **A class of your own**, such as a connector, a resource, a store or a container, which the blueprint builds from a `type`. Everything else is a key. Look there first: - Field values with logic, such as random or weighted choices, fields that depend on other fields and values that change from one event to the next, are the [generators](https://jaehyeon.me/desflow/latest/generators/index.md) and the expressions of [Task Flow](https://jaehyeon.me/desflow/latest/user-guide/model-parts/task-flow/index.md). - **Keys of a task** that SimPy programs wrote as functions and processes, which [YAML Keys](https://jaehyeon.me/desflow/latest/reference/yaml-keys/index.md) lists: - `service_time`, a time computed for each entity, such as `"attr.litres / 2"`, and `next: {weights: {fast: "attr.w", slow: "1 - attr.w"}}`, routing weights from an expression. - `seize` and `release`, a unit held across several steps. - `wait: {task: child, args: {...}}` and `set_args`, a sub-process with arguments. - `wait: {timeout: "attr.limit"}`, a timeout computed for each entity, `wait: {when: ..., of: {...}}`, a wait with its own rule, and `running: {task, whole_flow: true}`, a wait for a whole flow. - `open` with `{handle}`, a wait that goes on after an interrupt. - **Keys of an arrival**: `max_events`, a fixed number of arrivals, `gap: "1 + t / 4"`, a gap that depends on the time, `group`, `active`, `activate` and `off_mode`, `count` and `copy_attributes` of a spawn, and `initial`. - [Processes](https://jaehyeon.me/desflow/latest/user-guide/tasks-and-processes/processes/index.md) and [Signals and Waiting](https://jaehyeon.me/desflow/latest/user-guide/tasks-and-processes/signals-and-waiting/index.md) explain the flow these keys sit in. - Routing, priorities, preemption, breakdowns, several resources, stores and containers are keys too, as [Resources](https://jaehyeon.me/desflow/latest/user-guide/resources/index.md) and [Stores and Containers](https://jaehyeon.me/desflow/latest/user-guide/model-parts/stores-and-containers/index.md) show. - Readings other than the built-in statistics are described in [Built-in Statistics](https://jaehyeon.me/desflow/latest/user-guide/results/statistics/index.md). - Kafka topics, serializers, file and catalog settings and the setup of a connector are keys of the sink, as [Route Records to Topics](https://jaehyeon.me/desflow/latest/how-to/records-and-kafka/complex-routing/index.md), [Use Schema Serializers](https://jaehyeon.me/desflow/latest/how-to/records-and-kafka/json-schema-and-protobuf/index.md) and [Egress](https://jaehyeon.me/desflow/latest/user-guide/live-runs-and-connectors/egress/index.md) show. ### How a Reference Is Resolved [YAML Blueprints](https://jaehyeon.me/desflow/latest/user-guide/writing-a-model/blueprints/#how-it-works) describes how `!python module.attribute` is resolved, and [its Security section](https://jaehyeon.me/desflow/latest/user-guide/writing-a-model/blueprints/#security) says why a blueprint with a reference needs the trust of a Python script. ______________________________________________________________________ ## Steps ### Call Outside Code During a Run A `{gen: call}` field calls a function each time the record is made. The function is called as `function(context, **kwargs)`, and the values in `kwargs` are worked out first. Its result becomes the value of the field. The example is a product recommender. Each visit has three features, and the function ranks five products with the model of each, which another program keeps in Valkey under the key `linucb:`. It reads all five in one `MGET`, scores a product as the expected reaction plus a bonus for how uncertain the model is, and gives the three best. A product with no model yet gets the untrained one, so it can still be shown: ```python def top_products(context, x): """The three products with the highest LinUCB score for the features x.""" scores = {} for pid, stored in zip(PRODUCTS, CLIENT.mget([f"linucb:{p}" for p in PRODUCTS])): if stored: model = json.loads(stored) else: # A product with no model yet gets the identity matrix and a zero vector identity = [ [float(i == j) for j in range(FEATURES)] for i in range(FEATURES) ] model = {"A_inv": identity, "b": [0.0] * FEATURES} ax = [sum(a * v for a, v in zip(row, x)) for row in model["A_inv"]] expected = sum(a * b for a, b in zip(ax, model["b"])) uncertainty = math.sqrt(sum(a * v for a, v in zip(ax, x))) scores[pid] = expected + ALPHA * uncertainty return sorted(scores, key=scores.get, reverse=True)[:3] ``` The shop makes a visit every 0.1 seconds. The features are a var, so the record shows them and the function reads the same values: In YAML, the `gen: call` field of the task payload names the function: ```yaml tasks: recommend: vars: # The visitor's three features, each between 0 and 1 x: gen: repeat times: 3 value: {gen: uniform, low: 0, high: 1, decimals: 3} payload: features: {gen: var, name: x} # call_python_ranking.top_products(context, x=...) gives the three products shown: gen: call function: !python call_python_ranking.top_products kwargs: x: {gen: var, name: x} ``` In the Builder, the field takes the function itself: ```python def build_shop() -> SimulationContext: """The shop: each visit calls the ranking function with the visitor's features.""" app = SimulationContext(sim_id="Recommender", factor=0, random_seed=42) app.add_egress(ConsoleEgress(format="json")) app.add_arrival("visits", dist="constant", value=0.1, spawn="recommend") x = {"gen": "var", "name": "x"} visit = Template( { "features": x, # top_products(context, x=...) gives the three products "shown": {"gen": "call", "function": top_products, "kwargs": {"x": x}}, }, name="tasks.recommend", # The visitor's three features, each between 0 and 1 vars={ "x": { "gen": "repeat", "times": 3, "value": {"gen": "uniform", "low": 0, "high": 1, "decimals": 3}, } }, ) @app.task(name="recommend") def recommend(task_id): """Gives one visit record.""" return visit return app if __name__ == "__main__": logging.basicConfig(level=logging.INFO, format="%(levelname)s %(message)s") build_shop().run(until=1) ``` In the low-level API, which has no `gen`, the process draws the features with a `Sampler` and calls the function itself: ```python def visits(env, sampler): """A visit every 0.1 seconds, shown the products the ranking function picks.""" features = sampler.generator("tasks.recommend.vars.x.value") for number in itertools.count(1): yield env.timeout(0.1) # The visitor's three features, each between 0 and 1 x = [round(float(features.uniform(0, 1)), 3) for _ in range(3)] # top_products(context, x) gives the three products record = {"features": x, "shown": top_products(env, x)} env.publish_event(f"visits-{number}", record, "recommend", number - 1) def shop() -> DynamicRealtimeEnvironment: """The shop, with its visits started.""" env = DynamicRealtimeEnvironment(factor=0) env.setup_egress([ConsoleEgress(format="json")]) env.process(visits(env, Sampler(seed=42))) return env if __name__ == "__main__": logging.basicConfig(level=logging.INFO, format="%(levelname)s %(message)s") env = shop() try: env.run(until=1) finally: env.teardown() ``` The function runs inside the simulation, so a slow call holds the run. This one asks for five keys in one call. A function that waits for a network call at each visit sets the pace of the run. ### Use Your Own Class A `type: !python module.Class` entry builds your class from the `config` mapping. It works for `ingress`, `egress`, resources, stores and containers. The blueprint passes the keys of `config` to the class as keyword arguments: ```yaml ingress: - type: !python write_a_connector_logic.JsonlIngress config: {path: changes.jsonl} egress: - type: !python write_a_connector_logic.CsvEgress when: events # events only; the readings of telemetry stay out of the file config: {path: events.csv, columns: [status, event_type]} ``` [Write a Connector](https://jaehyeon.me/desflow/latest/how-to/records-and-kafka/write-a-connector/index.md) writes these two classes. [Custom Resource Types](https://jaehyeon.me/desflow/latest/user-guide/resources/custom-resource-types/index.md) and [Stores and Containers](https://jaehyeon.me/desflow/latest/user-guide/model-parts/stores-and-containers/index.md) show a resource, a store and a container. In the Builder and Low-level forms, pass the object itself, such as `app.add_egress(CsvEgress(path="events.csv"))`. ______________________________________________________________________ ## Check the Result Store the models, then run the shop from one folder that holds `call_python_ranking.py`, `call_python_seed.py` and the files of your form: ```bash python call_python_seed.py ``` Three products get a model and two do not. Then run your form. In YAML: ```bash desflow run call_python.yaml ``` In the Builder: ```bash python call_python.py ``` In the low-level API: ```bash python call_python_low_level.py ``` Each prints one JSON record for each visit, ten in all, and the three forms print the same `features` and `shown`. The first three are: ```text {"stream_type":"event","sim_ts":0.1,"timestamp":"2026-11-08T22:36:15.282+00:00","key":"visits-1","task":"recommend","instance":0,"value":{"features":[0.6,0.288,0.277],"shown":["p1","p2","p4"]}} {"stream_type":"event","sim_ts":0.2,"timestamp":"2026-11-08T22:36:15.382+00:00","key":"visits-2","task":"recommend","instance":1,"value":{"features":[0.107,0.018,0.831],"shown":["p3","p4","p5"]}} {"stream_type":"event","sim_ts":0.30000000000000004,"timestamp":"2026-11-08T22:36:15.482+00:00","key":"visits-3","task":"recommend","instance":2,"value":{"features":[0.722,0.727,0.319],"shown":["p2","p1","p4"]}} ``` The `timestamp` of a record is the clock time of the run, so it differs from run to run. In the first visit, `p4` ranks third although it has no model: its score is only the bonus for not being known. When the models change in Valkey, the next visit ranks with the new models. A reference that cannot be resolved stops the load with its line. [`python_error.yaml`](https://github.com/jaehyeon-kim/desflow/blob/v1.3.0/docs/snippets/yaml/python_error.yaml) names `shop_logic.missing` as the payload of its task, and `desflow run python_error.yaml` prints: ```text Error: python_error.yaml:15: !python shop_logic.missing: 'shop_logic' has no attribute 'missing' ``` A module that exists but fails on one of its own imports is reported with that error, rather than as a missing module. ______________________________________________________________________ ## Full Files Full files ```python """The ranking function of the Call Python from YAML page. It reads the LinUCB model of each product from Valkey, scores the products for one visitor and returns the best three. Every form of the shop calls it. It needs the redis package (`pip install "desflow[redis]"`) and the Valkey of `odctl up valkey`. """ import json import math import os import redis PRODUCTS = ["p1", "p2", "p3", "p4", "p5"] FEATURES = 3 ALPHA = 1.0 # The Valkey of `odctl up valkey`; VALKEY_URL points the function at another one CLIENT = redis.Redis.from_url( os.getenv("VALKEY_URL", "redis://user:password@127.0.0.1:6379/0"), decode_responses=True, ) def top_products(context, x): """The three products with the highest LinUCB score for the features x.""" scores = {} for pid, stored in zip(PRODUCTS, CLIENT.mget([f"linucb:{p}" for p in PRODUCTS])): if stored: model = json.loads(stored) else: # A product with no model yet gets the identity matrix and a zero vector identity = [ [float(i == j) for j in range(FEATURES)] for i in range(FEATURES) ] model = {"A_inv": identity, "b": [0.0] * FEATURES} ax = [sum(a * v for a, v in zip(row, x)) for row in model["A_inv"]] expected = sum(a * b for a, b in zip(ax, model["b"])) uncertainty = math.sqrt(sum(a * v for a, v in zip(ax, x))) scores[pid] = expected + ALPHA * uncertainty return sorted(scores, key=scores.get, reverse=True)[:3] ``` ```python """Writes the models the Call Python from YAML page ranks with into Valkey. Three products have a model and two have none yet. Run it once before the shop with `python call_python_seed.py`, beside call_python_ranking.py. """ import json from call_python_ranking import CLIENT MODELS = { "p1": {"A_inv": [[0.5, 0, 0], [0, 0.5, 0], [0, 0, 0.5]], "b": [2.0, 0.0, 0.0]}, "p2": {"A_inv": [[0.5, 0, 0], [0, 0.5, 0], [0, 0, 0.5]], "b": [0.0, 2.0, 0.0]}, "p3": {"A_inv": [[0.25, 0, 0], [0, 0.25, 0], [0, 0, 0.25]], "b": [0.0, 0.0, 3.0]}, } def seed(client) -> None: """Stores the models of p1, p2 and p3; p4 and p5 keep none.""" for pid, model in MODELS.items(): client.set(f"linucb:{pid}", json.dumps(model)) if __name__ == "__main__": seed(CLIENT) ``` In YAML: ```yaml # The Call Python from YAML guide: a visit every 0.1 seconds, each shown the three # products with the highest score from the models in Valkey. Needs # call_python_ranking.py beside it. Run it with: desflow run call_python.yaml simulation: {sim_id: Recommender, factor: 0, random_seed: 42} arrivals: visits: {dist: constant, value: 0.1, spawn: recommend} tasks: recommend: vars: # The visitor's three features, each between 0 and 1 x: gen: repeat times: 3 value: {gen: uniform, low: 0, high: 1, decimals: 3} payload: features: {gen: var, name: x} # call_python_ranking.top_products(context, x=...) gives the three products shown: gen: call function: !python call_python_ranking.top_products kwargs: x: {gen: var, name: x} egress: - type: Console config: {format: json} run: {until: 1 s} ``` In the Builder: ```python """The Call Python from YAML guide, built with the builder API. A visit every 0.1 seconds, each shown the three products with the highest score from the models in Valkey. call_python.yaml and call_python_low_level.py are the same shop in YAML and the low-level API. Needs call_python_ranking.py beside it. Run it with: python call_python.py """ import logging from call_python_ranking import top_products from desflow import ConsoleEgress, SimulationContext from desflow.values import Template def build_shop() -> SimulationContext: """The shop: each visit calls the ranking function with the visitor's features.""" app = SimulationContext(sim_id="Recommender", factor=0, random_seed=42) app.add_egress(ConsoleEgress(format="json")) app.add_arrival("visits", dist="constant", value=0.1, spawn="recommend") x = {"gen": "var", "name": "x"} visit = Template( { "features": x, # top_products(context, x=...) gives the three products "shown": {"gen": "call", "function": top_products, "kwargs": {"x": x}}, }, name="tasks.recommend", # The visitor's three features, each between 0 and 1 vars={ "x": { "gen": "repeat", "times": 3, "value": {"gen": "uniform", "low": 0, "high": 1, "decimals": 3}, } }, ) @app.task(name="recommend") def recommend(task_id): """Gives one visit record.""" return visit return app if __name__ == "__main__": logging.basicConfig(level=logging.INFO, format="%(levelname)s %(message)s") build_shop().run(until=1) ``` In the low-level API: ```python """The Call Python from YAML guide, low-level API. A visit every 0.1 seconds, each shown the three products with the highest score from the models in Valkey. The features come from `Sampler`, from the random sequence the blueprint's generator at that place uses, so the draws are the blueprint's. Needs call_python_ranking.py beside it. Run it with: python call_python_low_level.py """ import itertools import logging from call_python_ranking import top_products from desflow import ConsoleEgress, DynamicRealtimeEnvironment, Sampler def visits(env, sampler): """A visit every 0.1 seconds, shown the products the ranking function picks.""" features = sampler.generator("tasks.recommend.vars.x.value") for number in itertools.count(1): yield env.timeout(0.1) # The visitor's three features, each between 0 and 1 x = [round(float(features.uniform(0, 1)), 3) for _ in range(3)] # top_products(context, x) gives the three products record = {"features": x, "shown": top_products(env, x)} env.publish_event(f"visits-{number}", record, "recommend", number - 1) def shop() -> DynamicRealtimeEnvironment: """The shop, with its visits started.""" env = DynamicRealtimeEnvironment(factor=0) env.setup_egress([ConsoleEgress(format="json")]) env.process(visits(env, Sampler(seed=42))) return env if __name__ == "__main__": logging.basicConfig(level=logging.INFO, format="%(levelname)s %(message)s") env = shop() try: env.run(until=1) finally: env.teardown() ``` ______________________________________________________________________ ## Sources The recommender is cut down from [product-recommender](https://github.com/jaehyeon-kim/benchtop/tree/main/product-recommender), which keeps 200 products with about 15 features each. The 1.0 language has no key that reads a store during a run, which is why this call is written in Python. # Set Up Your Editor Get completion for the keys of a blueprint as you type, and a mark under a misspelt key or a value of the wrong kind. ______________________________________________________________________ ## Before You Start - [YAML Blueprints](https://jaehyeon.me/desflow/latest/user-guide/writing-a-model/blueprints/index.md) describes what a blueprint file is. - [YAML Keys](https://jaehyeon.me/desflow/latest/reference/yaml-keys/index.md) and the [Generators](https://jaehyeon.me/desflow/latest/generators/index.md) pages together list every key the editor will offer. - The editor checks the shape of the file against the blueprint JSON Schema. It does not run the model, so `desflow run` is still what proves a blueprint works. ______________________________________________________________________ ## Steps 1. Install Visual Studio Code and the Red Hat YAML extension (`redhat.vscode-yaml`) version 1.24.0 or later, which is the extension that reads a JSON Schema for a YAML file. 1. Put this line at the top of the blueprint, or use the setting in step 3 for every blueprint in a folder: ```yaml # yaml-language-server: $schema=https://jaehyeon.me/desflow/latest/schema/blueprint.schema.json ``` 1. To cover a folder of blueprints without a line in each file, add the schema to the workspace settings (`.vscode/settings.json`) with a glob of the files it applies to. The same object holds the tags of step 4: ```json { "yaml.schemas": { "https://jaehyeon.me/desflow/latest/schema/blueprint.schema.json": "blueprints/*.yaml" }, "yaml.customTags": [ "!python scalar:string", "!include scalar:object", "!include mapping:object" ] } ``` 1. The `yaml.customTags` entries tell the extension about the tags a blueprint uses. Without them, it marks `!python`, and an `!include` written as a mapping, as unknown tags, and it marks a file name given to `!include` as the wrong type. They go in the same `.vscode/settings.json`. Your user settings work too. 1. Open the file and write a key. The editor offers the keys of the section you are in, shows the section's description when you hover over it, and underlines a key it does not know or a value of the wrong kind. To work offline, or to pin the schema to the version you have installed, write the copy that comes with the package to a file and name that file instead of the address: ```bash desflow schema > blueprint.schema.json ``` Then use `# yaml-language-server: $schema=./blueprint.schema.json` as the line, or `"./blueprint.schema.json"` as the key in `yaml.schemas`. In the line the path is relative to the blueprint's folder. In `yaml.schemas` it is relative to the workspace folder, in a single-folder workspace. The address above always serves the latest release, so it can offer keys that an older install does not have. To pin a release, use its versioned address, `https://jaehyeon.me/desflow//schema/blueprint.schema.json`, with `` the release you installed, which `desflow --version` prints. ______________________________________________________________________ ## Check the Result Open the blueprint from [Full Files](#full-files) in the editor. Its highlighted line names the schema. Change `packers` to `packer` under `tasks`, and the editor underlines nothing. Resource names are checked by `desflow run`, as the list below says. Change `current_cap` to `capacity` instead, and the editor underlines it as a key it does not know. Run the blueprint with `desflow run editor_setup.yaml`. ### What the Editor Cannot Check The schema describes the shape of one file. `desflow run` checks the following instead, and reports each with the file and line: - The content of a file named by `!include`. - Whether the module and attribute of a `!python` reference exist. - The text of an expression, such as a `when` condition or an amount. - A name that refers to another section, such as a `spawn` that names a task that is not there, or a `resource` that is not declared. - The rules between the parameters of one distribution, such as a `low` below a `high`. A mapping `!include`, such as `!include {file: fitted/orders.yaml, spawn: pack_order}`, is checked as the entry it stands for, so the editor marks `file` as an unknown key. `desflow run` reads it correctly. Where a value is a number, a whole number, `true` or `false`, or one of a fixed set of names, a `${VAR}` or `${VAR:-default}` reference is also accepted. ______________________________________________________________________ ## Full Files Full files ```yaml # A small blueprint with the line that tells the Red Hat YAML extension which schema to # use. Run it with: desflow run editor_setup.yaml # yamllint disable rule:line-length # yaml-language-server: $schema=https://jaehyeon.me/desflow/latest/schema/blueprint.schema.json # yamllint enable rule:line-length simulation: {sim_id: Shop, factor: 0, random_seed: 42} resources: packers: {current_cap: 1, max_cap: 1} services: packing: {dist: constant, value: 1.5} arrivals: orders: {dist: exponential, rate: 0.5, spawn: pack_order} tasks: pack_order: service: packing resource: packers payload: {event_type: order_packed} egress: - {type: Console} run: {until: 20} ``` ______________________________________________________________________ ## Sources The modeline and the `yaml.schemas` and `yaml.customTags` settings belong to the [yaml-language-server](https://github.com/redhat-developer/yaml-language-server/tree/2.0.0) that the extension runs, as its README at version 2.0.0 describes. That README does not say how a tag with both a scalar and a mapping form is written. The source at 2.0.0 shows it: `src/languageservice/parser/custom-tag-provider.ts` adds one tag for each entry of `yaml.customTags`, and its own `!include` is a scalar only. The YAML library the server uses (version 2.8.3, `src/compose/compose-collection.ts`) then chooses a tag by its name and its kind of node. Without the `!include mapping:object` entry, a mapping `!include` is reported as `Unresolved tag: !include`. # Tune Performance Make a run that generates data go as fast as the machine allows, and measure how many records a second it publishes. To choose the size of a dataset and split a large job, see [Data at Scale](https://jaehyeon.me/desflow/latest/how-to/records-and-kafka/data-at-scale/index.md). ______________________________________________________________________ ## Before You Start - [Time and Pacing](https://jaehyeon.me/desflow/latest/user-guide/time-and-pacing/index.md) explains `factor`. - [Egress](https://jaehyeon.me/desflow/latest/user-guide/live-runs-and-connectors/egress/index.md) explains batches. ______________________________________________________________________ ## Steps 1. Run at `factor: 0`, without `go_live_at`. The run then waits for no wall clock, each event is processed by SimPy's own step, and no lag telemetry is published. A pending go-live keeps the real-time step until it is reached. 1. Ask only for the statistics you read: `minimal` reads a few values at each interval, while `typical` and `all` add work at every task step, as [Statistics](https://jaehyeon.me/desflow/latest/user-guide/results/statistics/#stability-and-limits) explains. 1. Use the console sink only to look at a run. It writes one line per record. A file or a stream sink costs less per record, and a counting sink almost nothing. 1. Give a lake sink a large `batch_size`, such as 10,000, because each batch becomes one file. A stream sink can keep a small one. 1. After building a large model, `gc.freeze()` leaves the objects built so far out of garbage collection. In the measurements below it saved about 9 percent. This shop takes ten orders a second with 25 packers, and has no sink of its own: ```yaml simulation: sim_id: Shop factor: 0 # no wall clock to wait for random_seed: 42 resources: packers: {current_cap: 25, max_cap: 25} services: packing: {dist: normal, mean: 2 s, std: 0.4 s} arrivals: orders: {dist: exponential, rate: 10, spawn: pack_order} tasks: pack_order: service: packing resource: packers payload: {event_type: order_packed} # minimal: readings every 10 s, not the costlier task statistics stats: {level: minimal, interval: 10} run: {until: 1 h} ``` ```python def shop() -> SimulationContext: """Ten orders a second and 25 packers, with no sink of its own.""" app = ( # factor 0: no wall clock to wait for SimulationContext(sim_id="Shop", factor=0, random_seed=42) .add_resource("packers", current_cap=25, max_cap=25) .add_service("packing", dist="normal", mean=2.0, std=0.4) .add_arrival("orders", dist="exponential", rate=10.0) # minimal: readings every 10 s, not the costlier task statistics .with_stats("minimal", interval=10) ) @app.task(service_id="packing", resource_id="packers") def pack_order(task_id: int): return {"event_type": "order_packed"} @app.arrival_loop("orders") def order_loop(context: SimulationContext): while True: order = yield context.wait_for_arrival("orders") context.spawn(pack_order(context.next_instance("pack_order"), entity=order)) return app ``` ```python def pack_order(env, packers, sampler, key, task_id): path_id, stats = "Shop.service.packing", env.stats env.publish_event( key, { "path_id": path_id, "sim_id": "Shop", "service": "packing", "status": "queued", }, "pack_order", task_id, ) stats.task_queued("pack_order", task_id) with packers.request() as unit: yield unit env.publish_event( key, { "path_id": path_id, "sim_id": "Shop", "service": "packing", "status": "started", }, "pack_order", task_id, ) stats.task_started("pack_order", task_id) yield env.timeout(sampler.sample(env.registry.get_config(path_id))) env.publish_event(key, {"event_type": "order_packed"}, "pack_order", task_id) stats.task_finished("pack_order", task_id) def orders(env, packers, sampler): gap = env.registry.get_config("Shop.arrival.orders") for number in itertools.count(1): yield env.timeout(sampler.sample(gap)) env.process(pack_order(env, packers, sampler, f"orders-{number}", number - 1)) def shop(egress: list) -> DynamicRealtimeEnvironment: """Ten orders a second and 25 packers, publishing to the sinks given.""" env = DynamicRealtimeEnvironment(factor=0) # no wall clock to wait for env.registry.register_sim_parameter(PARAMS) env.setup_egress(egress) # minimal: readings every 10 s, not the costlier task statistics env.setup_stats("Shop", "minimal", interval=10) packers = DynamicResource(env, "Shop", "packers") env.process(orders(env, packers, Sampler(seed=42))) return env ``` At `factor: 0` no `system.simulation.lag_seconds` is published, so the count holds only the shop's own records. With a lag reading every second it would be 3,600 more. ______________________________________________________________________ ## Check the Result Save the files of your form from [Full Files](#full-files) in a folder of their own, each under the last part of its title. The low-level file imports the counting sink from `performance_tuning.py`, so it needs that file beside it. The function below adds a counting sink to a model, runs it, and returns the number of records it published and the records published per second, counted from the start of `run()` to the end of its teardown. A blueprint loads as a context, so the YAML form uses the builder's function. The low-level form adds the sink to the environment and calls the teardown itself: ```python app = SimulationContext.from_yaml(path) # a context, as the builder makes one return throughput(app, until=3600) ``` The files are `performance_tuning.yaml` and `performance_tuning.py`. The argument `yaml` makes the script measure the blueprint beside it: ```bash python performance_tuning.py yaml ``` ```python def throughput(app: SimulationContext, until: float) -> dict: """Runs a model with a counting sink: the record count and the records per second.""" count = Count() app.add_egress(count) gc.collect() gc.freeze() # leave the objects built so far out of garbage collection started = time.perf_counter() app.run(until=until) seconds = time.perf_counter() - started gc.unfreeze() return {"records": count.records, "per_second": round(count.records / seconds)} ``` The file is `performance_tuning.py`: ```bash python performance_tuning.py ``` ```python def throughput(until: float) -> dict: """Runs the shop with a counting sink: the record count and the records per second.""" count = Count() env = shop([count]) gc.collect() gc.freeze() # leave the objects built so far out of garbage collection started = time.perf_counter() env.run(until=until) env.teardown() # waits until the sink has taken every batch seconds = time.perf_counter() - started gc.unfreeze() return {"records": count.records, "per_second": round(count.records / seconds)} ``` The files are `performance_tuning_low_level.py` and `performance_tuning.py`: ```bash python performance_tuning_low_level.py ``` For one simulated hour, each form prints **110,070** records, at about 100,000 records a second of wall-clock time on the machine below. The rate differs from run to run and between machines: ```text {'records': 110070, 'per_second': 98264} ``` ### Measurements `benchmarks/throughput.py` in the repository runs one low-level workload, 5,000 simulation seconds of 10 orders a second, at `factor: 0` with a fixed seed, and gives the median of seven runs. Each line changes one thing, so the effect of a change is the ratio of two lines. These are from an arm64 Mac (macOS 26) with Python 3.12.13. "Run" is `env.run()` alone, and "total" adds the teardown, which waits until every sink has taken every batch: | Configuration | Run, seconds | Total, seconds | Records | | ------------------------------------------ | ------------ | -------------- | ------- | | core only, nothing published | 0.248 | 0.248 | 0 | | as shipped, counting sink | 0.531 | 1.138 | 157,771 | | as shipped, with `gc.freeze()` after setup | 0.485 | 1.092 | 157,771 | | `ConsoleEgress`, to `/dev/null` | 0.648 | 1.251 | 157,771 | - **Console:** in the total, which covers the run and the teardown, logging a batch with one call takes 0.11 seconds more than a counting sink. A terminal is slower than `/dev/null`, so a run that prints to one costs more than this. - **Teardown:** about 0.6 seconds of every total is the teardown. Once the queues are empty, it waits half a second for a file sink to close its last file, so a short run spends most of its time there. The table below shows where the time of the run "as shipped" goes. It comes from a sampling profile: a thread reads the main thread's stack every 0.2 milliseconds, as py-spy does from outside the process (py-spy needs root on macOS): | Part | Share of the run | | ----------------------------------------------------------------------- | ---------------- | | SimPy's scheduler | 28 percent | | publishing a record: the value made JSON-safe | 18 percent | | publishing a record: building it, its timestamp, buffering and flushing | 21 percent | | resource request and release | 14 percent | | drawing samples | 9 percent | | SimPy events and processes | 8 percent | | the model's own generators and the rest | 3 percent | A draw through `Sampler.sample` costs about 360 nanoseconds, against 200 for numpy's `Generator.normal` alone. A request granted and released costs about 1,760 nanoseconds, and a timeout about 260. **Python versions.** The run "as shipped" takes 0.517 seconds on Python 3.11.15, 0.531 on 3.12.13, 0.492 on 3.13.14 and 0.556 on 3.14.6. No version is more than 13 percent faster than another. **PyPy.** desflow does not install on PyPy, because orjson, which it depends on, does not support PyPy. With the other dependencies installed by hand, the run "as shipped" took 0.851 seconds on PyPy 3.11.15, 1.6 times slower than CPython 3.12. Drawing samples, which goes through numpy, took 23 percent of a short profile (96 samples), against 9 percent on CPython. **Real sinks.** With the same workload, the total was 1.138 seconds with a counting sink, 1.262 with Parquet on the local disk, and 3.558 with Kafka. The Kafka run used the odctl `kafka-lite` profile on the same machine, with JSON values. A sink that sends over the network can take longer than the model. Run `uv run --all-extras python benchmarks/throughput.py configs` to measure your machine, and `micro`, `profile` or `sinks` for the other parts. ______________________________________________________________________ ## Full Files Full files ```yaml # The Tune Performance guide: ten orders a second and 25 packers, with no sink of its # own. performance_tuning.py measures it with a counting sink. simulation: sim_id: Shop factor: 0 # no wall clock to wait for random_seed: 42 resources: packers: {current_cap: 25, max_cap: 25} services: packing: {dist: normal, mean: 2 s, std: 0.4 s} arrivals: orders: {dist: exponential, rate: 10, spawn: pack_order} tasks: pack_order: service: packing resource: packers payload: {event_type: order_packed} # minimal: readings every 10 s, not the costlier task statistics stats: {level: minimal, interval: 10} run: {until: 1 h} ``` ```python """The Tune Performance guide: records per second of a model, without its sinks. python performance_tuning.py prints the records a one-hour run of the shop below published, and how many a second. With the argument yaml, `blueprint()` measures performance_tuning.yaml, which must be beside the script. """ import asyncio import gc import queue import sys import time from desflow import SimulationContext class Count: """An egress that counts the records it receives and keeps none.""" def __init__(self): self.records = 0 async def run(self, egress_queue): try: while True: try: self.records += len(egress_queue.get_nowait()) except queue.Empty: await asyncio.sleep(0.01) except asyncio.CancelledError: pass def shop() -> SimulationContext: """Ten orders a second and 25 packers, with no sink of its own.""" app = ( # factor 0: no wall clock to wait for SimulationContext(sim_id="Shop", factor=0, random_seed=42) .add_resource("packers", current_cap=25, max_cap=25) .add_service("packing", dist="normal", mean=2.0, std=0.4) .add_arrival("orders", dist="exponential", rate=10.0) # minimal: readings every 10 s, not the costlier task statistics .with_stats("minimal", interval=10) ) @app.task(service_id="packing", resource_id="packers") def pack_order(task_id: int): return {"event_type": "order_packed"} @app.arrival_loop("orders") def order_loop(context: SimulationContext): while True: order = yield context.wait_for_arrival("orders") context.spawn(pack_order(context.next_instance("pack_order"), entity=order)) return app def throughput(app: SimulationContext, until: float) -> dict: """Runs a model with a counting sink: the record count and the records per second.""" count = Count() app.add_egress(count) gc.collect() gc.freeze() # leave the objects built so far out of garbage collection started = time.perf_counter() app.run(until=until) seconds = time.perf_counter() - started gc.unfreeze() return {"records": count.records, "per_second": round(count.records / seconds)} def blueprint(path: str = "performance_tuning.yaml") -> dict: """The same measure of the blueprint, which loads as a context.""" app = SimulationContext.from_yaml(path) # a context, as the builder makes one return throughput(app, until=3600) if __name__ == "__main__": print(blueprint() if sys.argv[1:] == ["yaml"] else throughput(shop(), until=3600)) ``` ```python """The Tune Performance guide, low-level API: records per second of a model, without its sinks. python performance_tuning_low_level.py prints the records a one-hour run of the shop below published, and how many a second. """ import gc import itertools import time from desflow import ( CapacityConfig, DistributionConfig, DynamicRealtimeEnvironment, DynamicResource, Sampler, SimParameter, ) from performance_tuning import Count PARAMS = SimParameter( sim_id="Shop", arrival={"orders": DistributionConfig(dist="exponential", rate=10.0)}, service={"packing": DistributionConfig(dist="normal", mean=2.0, std=0.4)}, resources={"packers": CapacityConfig(current_cap=25, max_cap=25)}, ) def pack_order(env, packers, sampler, key, task_id): path_id, stats = "Shop.service.packing", env.stats env.publish_event( key, { "path_id": path_id, "sim_id": "Shop", "service": "packing", "status": "queued", }, "pack_order", task_id, ) stats.task_queued("pack_order", task_id) with packers.request() as unit: yield unit env.publish_event( key, { "path_id": path_id, "sim_id": "Shop", "service": "packing", "status": "started", }, "pack_order", task_id, ) stats.task_started("pack_order", task_id) yield env.timeout(sampler.sample(env.registry.get_config(path_id))) env.publish_event(key, {"event_type": "order_packed"}, "pack_order", task_id) stats.task_finished("pack_order", task_id) def orders(env, packers, sampler): gap = env.registry.get_config("Shop.arrival.orders") for number in itertools.count(1): yield env.timeout(sampler.sample(gap)) env.process(pack_order(env, packers, sampler, f"orders-{number}", number - 1)) def shop(egress: list) -> DynamicRealtimeEnvironment: """Ten orders a second and 25 packers, publishing to the sinks given.""" env = DynamicRealtimeEnvironment(factor=0) # no wall clock to wait for env.registry.register_sim_parameter(PARAMS) env.setup_egress(egress) # minimal: readings every 10 s, not the costlier task statistics env.setup_stats("Shop", "minimal", interval=10) packers = DynamicResource(env, "Shop", "packers") env.process(orders(env, packers, Sampler(seed=42))) return env def throughput(until: float) -> dict: """Runs the shop with a counting sink: the record count and the records per second.""" count = Count() env = shop([count]) gc.collect() gc.freeze() # leave the objects built so far out of garbage collection started = time.perf_counter() env.run(until=until) env.teardown() # waits until the sink has taken every batch seconds = time.perf_counter() - started gc.unfreeze() return {"records": count.records, "per_second": round(count.records / seconds)} if __name__ == "__main__": print(throughput(until=3600)) ``` # Generators # Generators A generator draws a value each time a blueprint makes a record. Generators are written in YAML blueprints; a Builder or Low-level model makes its values in Python. This section has one page for each kind, with its keys, an example blueprint, the records it prints, and its JSON Schema. ## What a Generator Is A place that takes a value, such as a field of a task's `payload` or of an arrival's `attributes`, takes a constant or a generator. A generator is a mapping with a `gen` key that names its kind, such as `{gen: integer, bounds: [1, 6]}`. The tables of this section call such a place `Value`. [YAML Keys](https://jaehyeon.me/desflow/latest/reference/yaml-keys/index.md) calls the generator part of such a place `Generator`: a key that takes a generator, an integer or text is written `Generator or integer or text`. Each generator draws from a random sequence of its own, named for the place it is written at. The same seed gives the same values. Adding a field to a mapping moves no other draw. Inserting an item into a list moves the draws of the items after it. The keys of every other part of a blueprint are on [YAML Keys](https://jaehyeon.me/desflow/latest/reference/yaml-keys/index.md). ## Choose a Kind The sidebar groups the kinds by the sort of value they give: - **Random Numbers:** Numbers and flags drawn from a range or a distribution. - **Choices:** A value picked from a list you write. - **Text and IDs:** Names, identifiers and text. - **Time:** The simulation clock as text or numbers. - **Maths:** Arithmetic on other values. - **Conditions:** A value that depends on a condition or a case, or that is kept as written. - **Structure:** Mappings and lists built from other generators. - **Model State:** Values the model already holds: the entity, the task's vars and the registry. - **Related Records:** Values from the records other tasks or earlier orders published, and from files. - **Python:** A value from your own Python function, the one kind that runs `!python`. | Group | Kind | Use it for | | --------------- | ----------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------- | | Random Numbers | [`integer`](https://jaehyeon.me/desflow/latest/generators/random-numbers/integer/index.md) | A count or a quantity in which every whole number in the range is as likely as any other. | | Random Numbers | [`uniform`](https://jaehyeon.me/desflow/latest/generators/random-numbers/uniform/index.md) | A price or a size in which every value in the range is as likely as any other. | | Random Numbers | [`normal`](https://jaehyeon.me/desflow/latest/generators/random-numbers/normal/index.md) | A measurement that clusters around a mean, such as a weight. | | Random Numbers | [`sample`](https://jaehyeon.me/desflow/latest/generators/random-numbers/sample/index.md) | A duration or a size whose shape you know, such as exponential gaps, or one that follows the live distribution of a service. | | Random Numbers | [`boolean`](https://jaehyeon.me/desflow/latest/generators/random-numbers/boolean/index.md) | A flag that is true for a share of the orders, such as a gift. | | Choices | [`one_of`](https://jaehyeon.me/desflow/latest/generators/choices/one-of/index.md) | One value out of a list, each equally likely, such as a colour. | | Choices | [`weighted`](https://jaehyeon.me/desflow/latest/generators/choices/weighted/index.md) | One value out of a list in which some values are more likely, such as a region. | | Choices | [`pick`](https://jaehyeon.me/desflow/latest/generators/choices/pick/index.md) | Several different values out of a list, such as optional extras. | | Text and IDs | [`fake`](https://jaehyeon.me/desflow/latest/generators/text-and-ids/fake/index.md) | Names, addresses and other realistic text, when invented values are enough. | | Text and IDs | [`uuid`](https://jaehyeon.me/desflow/latest/generators/text-and-ids/uuid/index.md) | A unique identifier, such as an order id. | | Text and IDs | [`sequence`](https://jaehyeon.me/desflow/latest/generators/text-and-ids/sequence/index.md) | An order number or a label that counts up. | | Text and IDs | [`format`](https://jaehyeon.me/desflow/latest/generators/text-and-ids/format/index.md) | Text built from parts, such as a label made of a region and a number. | | Text and IDs | [`lower`](https://jaehyeon.me/desflow/latest/generators/text-and-ids/lower/index.md) | A code or a label that must be in one standard case, whatever case it was drawn in. | | Text and IDs | [`upper`](https://jaehyeon.me/desflow/latest/generators/text-and-ids/upper/index.md) | A code or a label that must be in one standard case, whatever case it was drawn in. | | Time | [`now`](https://jaehyeon.me/desflow/latest/generators/time/now/index.md) | A time field of a record, with an offset when it is dated before or after the clock. | | Time | [`format_time`](https://jaehyeon.me/desflow/latest/generators/time/format-time/index.md) | A time in the form another system expects, such as epoch milliseconds or a local time zone. | | Maths | [`add`](https://jaehyeon.me/desflow/latest/generators/maths/add/index.md) | A total, or a time that falls some seconds after another time. | | Maths | [`subtract`](https://jaehyeon.me/desflow/latest/generators/maths/subtract/index.md) | A difference, or a time that falls some seconds before another time. | | Maths | [`multiply`](https://jaehyeon.me/desflow/latest/generators/maths/multiply/index.md) | A cost, such as a quantity times a price. | | Maths | [`divide`](https://jaehyeon.me/desflow/latest/generators/maths/divide/index.md) | A ratio, such as a total divided by a count. | | Maths | [`min`](https://jaehyeon.me/desflow/latest/generators/maths/min/index.md) | A cap: the smaller of a drawn value and a limit. | | Maths | [`max`](https://jaehyeon.me/desflow/latest/generators/maths/max/index.md) | A floor: the larger of a drawn value and a minimum. | | Conditions | [`when`](https://jaehyeon.me/desflow/latest/generators/conditions/when/index.md) | A value that changes with one condition, such as a discount for a large order. | | Conditions | [`switch`](https://jaehyeon.me/desflow/latest/generators/conditions/switch/index.md) | One value out of several, chosen by an exact match or by a range. | | Conditions | [`expr`](https://jaehyeon.me/desflow/latest/generators/conditions/expr/index.md) | A value computed from vars and numbers by an expression. | | Conditions | [`literal`](https://jaehyeon.me/desflow/latest/generators/conditions/literal/index.md) | A value that must be kept as written, even when it looks like a generator. | | Structure | [`object`](https://jaehyeon.me/desflow/latest/generators/structure/object/index.md) | A nested record that is sometimes null or left out as a whole. | | Structure | [`repeat`](https://jaehyeon.me/desflow/latest/generators/structure/repeat/index.md) | The items of an order: a list in which each item is drawn on its own. | | Model State | [`attr`](https://jaehyeon.me/desflow/latest/generators/model-state/attr/index.md) | A value the entity has carried since it started, such as a size the arrival gave it. | | Model State | [`var`](https://jaehyeon.me/desflow/latest/generators/model-state/var/index.md) | A value drawn once for the task and used in several places. | | Model State | [`param`](https://jaehyeon.me/desflow/latest/generators/model-state/param/index.md) | A live setting of the simulation, which a scenario step or an ingress update can change. | | Model State | [`entity`](https://jaehyeon.me/desflow/latest/generators/model-state/entity/index.md) | A payload field that names the entity the record belongs to. | | Related Records | [`lookup`](https://jaehyeon.me/desflow/latest/generators/related-records/lookup/index.md) | A value from a record that another task already published, such as an existing customer. | | Related Records | [`previous`](https://jaehyeon.me/desflow/latest/generators/related-records/previous/index.md) | A value from the last finished record of the same task, such as the previous reading. | | Related Records | [`upstream`](https://jaehyeon.me/desflow/latest/generators/related-records/upstream/index.md) | A value from the record of the task that routed to this one. | | Related Records | [`aggregate`](https://jaehyeon.me/desflow/latest/generators/related-records/aggregate/index.md) | A mean, sum, minimum, maximum or count over earlier records of another task. | | Related Records | [`row`](https://jaehyeon.me/desflow/latest/generators/related-records/row/index.md) | A whole row of a CSV or Parquet file, such as a product from a price list. | | Python | [`call`](https://jaehyeon.me/desflow/latest/generators/python/call/index.md) | A value that your own Python function computes. | ## Keys Every Kind Accepts These four keys go on any kind. | Key | Type | Default | What it does | | ----------- | ------- | ------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `null_rate` | number | none | The chance, from 0 to 1, that the value is `null` instead of a draw. | | `unique` | boolean | `false` | When true, a draw that repeats an earlier value of this generator is drawn again, up to 1000 times, and the run stops with an error if no new value is found. | | `omit_rate` | number | none | The chance, from 0 to 1, that the field of a mapping is left out. | | `omit_when` | text | none | An expression. The field of a mapping is left out when it holds. | `omit_rate` and `omit_when` apply to a field of a mapping, such as a field of a `payload`. A blueprint that writes them on any other value is refused when it loads. ## Run the Examples Every example is a model in which an order starts every 60 seconds and the run lasts 200 seconds, so three orders start. The seed is 42 and `factor` is 0, so a run takes no wall-clock time and prints the same records each time. No example needs a service. Each kind has one blueprint in `examples/generators/` of the repository, `.yaml`. Run it from the repository's root folder: ```bash desflow run examples/generators/integer.yaml ``` `fake` needs the `fake` extra, which `pip install "desflow[fake]"` adds. `row` reads `products.csv` and `call` imports `call_helpers.py`, both in the same folder. # integer `integer`: a whole number between `bounds[0]` and `bounds[1]`, both included. Use it for a count or a quantity in which every whole number in the range is as likely as any other. ## Keys | Key | Type | Default | | -------- | ------------- | -------- | | `gen` | `integer` | required | | `bounds` | list of Value | required | A `Value` is a constant or a generator, as [What a Generator Is](https://jaehyeon.me/desflow/latest/generators/#what-a-generator-is) explains. Every kind also accepts `null_rate`, `unique`, `omit_rate` and `omit_when`, which [Generators](https://jaehyeon.me/desflow/latest/generators/#keys-every-kind-accepts) describes. ## Example `quantity` is a whole number from 1 to 50, and 1 and 50 are both possible. An order starts every 60 seconds for 200 seconds, with the seed 42, so three orders start. ```yaml # Integer: a whole number between two bounds. # A task `order` starts every 60 seconds, and the run lasts 200 seconds, so three orders # start. # # Run it with: desflow run examples/generators/integer.yaml simulation: sim_id: Gen factor: 0 random_seed: 42 logical_start_time: 2026-01-01T00:00:00 egress: - {type: Console} arrivals: orders: {dist: constant, value: 60, spawn: order} tasks: order: payload: quantity: {gen: integer, bounds: [1, 50]} run: {until: 200} ``` It prints these records: ```text [EVT] {'sim_ts': 60.0, 'timestamp': '...', 'key': 'orders-1', 'task': 'order', 'instance': 0, 'value': {'quantity': 25}} [EVT] {'sim_ts': 120.0, 'timestamp': '...', 'key': 'orders-2', 'task': 'order', 'instance': 1, 'value': {'quantity': 43}} [EVT] {'sim_ts': 180.0, 'timestamp': '...', 'key': 'orders-3', 'task': 'order', 'instance': 2, 'value': {'quantity': 26}} ``` ## JSON Schema The schema of `Integer`, from `desflow schema`. ```json { "additionalProperties": false, "description": "`integer`: a whole number between `bounds[0]` and `bounds[1]`, both included.", "properties": { "null_rate": { "anyOf": [ { "maximum": 1, "minimum": 0, "type": "number" }, { "type": "null" }, { "$ref": "#/$defs/NonNegativeNumberText" }, { "$ref": "#/$defs/Placeholder" } ], "default": null }, "unique": { "default": false, "description": "Gives each value once. A value built only from a task's vars, such as a format or an expr with no generator that draws, draws the vars again and makes the whole payload again until the value is new.", "anyOf": [ { "type": "boolean" }, { "$ref": "#/$defs/Placeholder" } ] }, "omit_rate": { "anyOf": [ { "maximum": 1, "minimum": 0, "type": "number" }, { "type": "null" }, { "$ref": "#/$defs/NonNegativeNumberText" }, { "$ref": "#/$defs/Placeholder" } ], "default": null }, "omit_when": { "anyOf": [ { "type": "string" }, { "type": "null" } ], "default": null }, "gen": { "anyOf": [ { "const": "integer", "type": "string" }, { "$ref": "#/$defs/Placeholder" } ] }, "bounds": { "items": { "$ref": "#/$defs/Value" }, "maxItems": 2, "minItems": 2, "type": "array" } }, "required": [ "gen", "bounds" ], "title": "Integer", "type": "object" } ``` # uniform `uniform`: a float in \[low, high), from `low + (high - low) * random()`; `decimals` rounds it, and 0 gives an integer. Use it for a price or a size in which every value in the range is as likely as any other. ## Keys | Key | Type | Default | | ---------- | --------- | -------- | | `gen` | `uniform` | required | | `low` | Value | required | | `high` | Value | required | | `decimals` | integer | none | A `Value` is a constant or a generator, as [What a Generator Is](https://jaehyeon.me/desflow/latest/generators/#what-a-generator-is) explains. Every kind also accepts `null_rate`, `unique`, `omit_rate` and `omit_when`, which [Generators](https://jaehyeon.me/desflow/latest/generators/#keys-every-kind-accepts) describes. ## Example `price` is a number from 1 up to, but not including, 10, rounded to 2 decimals. An order starts every 60 seconds for 200 seconds, with the seed 42, so three orders start. ```yaml # Uniform: a decimal number between two limits. # A task `order` starts every 60 seconds, and the run lasts 200 seconds, so three orders # start. # # Run it with: desflow run examples/generators/uniform.yaml simulation: sim_id: Gen factor: 0 random_seed: 42 logical_start_time: 2026-01-01T00:00:00 egress: - {type: Console} arrivals: orders: {dist: constant, value: 60, spawn: order} tasks: order: payload: price: {gen: uniform, low: 1, high: 10, decimals: 2} run: {until: 200} ``` It prints these records: ```text [EVT] {'sim_ts': 60.0, 'timestamp': '...', 'key': 'orders-1', 'task': 'order', 'instance': 0, 'value': {'price': 8.27}} [EVT] {'sim_ts': 120.0, 'timestamp': '...', 'key': 'orders-2', 'task': 'order', 'instance': 1, 'value': {'price': 3.15}} [EVT] {'sim_ts': 180.0, 'timestamp': '...', 'key': 'orders-3', 'task': 'order', 'instance': 2, 'value': {'price': 5.57}} ``` ## JSON Schema The schema of `Uniform`, from `desflow schema`. ```json { "additionalProperties": false, "description": "`uniform`: a float in [low, high), from `low + (high - low) * random()`;\n`decimals` rounds it, and 0 gives an integer.", "properties": { "null_rate": { "anyOf": [ { "maximum": 1, "minimum": 0, "type": "number" }, { "type": "null" }, { "$ref": "#/$defs/NonNegativeNumberText" }, { "$ref": "#/$defs/Placeholder" } ], "default": null }, "unique": { "default": false, "description": "Gives each value once. A value built only from a task's vars, such as a format or an expr with no generator that draws, draws the vars again and makes the whole payload again until the value is new.", "anyOf": [ { "type": "boolean" }, { "$ref": "#/$defs/Placeholder" } ] }, "omit_rate": { "anyOf": [ { "maximum": 1, "minimum": 0, "type": "number" }, { "type": "null" }, { "$ref": "#/$defs/NonNegativeNumberText" }, { "$ref": "#/$defs/Placeholder" } ], "default": null }, "omit_when": { "anyOf": [ { "type": "string" }, { "type": "null" } ], "default": null }, "gen": { "anyOf": [ { "const": "uniform", "type": "string" }, { "$ref": "#/$defs/Placeholder" } ] }, "low": { "$ref": "#/$defs/Value" }, "high": { "$ref": "#/$defs/Value" }, "decimals": { "anyOf": [ { "minimum": 0, "type": "integer" }, { "type": "null" }, { "$ref": "#/$defs/NonNegativeIntegerText" }, { "$ref": "#/$defs/Placeholder" } ], "default": null } }, "required": [ "gen", "low", "high" ], "title": "Uniform", "type": "object" } ``` # normal `normal`: a float from a normal distribution with `mean` and `std`. Use it for a measurement that clusters around a mean, such as a weight. ## Keys | Key | Type | Default | | ---------- | -------- | -------- | | `gen` | `normal` | required | | `mean` | Value | required | | `std` | Value | required | | `decimals` | integer | none | A `Value` is a constant or a generator, as [What a Generator Is](https://jaehyeon.me/desflow/latest/generators/#what-a-generator-is) explains. Every kind also accepts `null_rate`, `unique`, `omit_rate` and `omit_when`, which [Generators](https://jaehyeon.me/desflow/latest/generators/#keys-every-kind-accepts) describes. ## Example `weight_g` has a mean of 500 and a standard deviation of 20, rounded to 1 decimal. An order starts every 60 seconds for 200 seconds, with the seed 42, so three orders start. ```yaml # Normal: a number from a bell curve. # A task `order` starts every 60 seconds, and the run lasts 200 seconds, so three orders # start. # # Run it with: desflow run examples/generators/normal.yaml simulation: sim_id: Gen factor: 0 random_seed: 42 logical_start_time: 2026-01-01T00:00:00 egress: - {type: Console} arrivals: orders: {dist: constant, value: 60, spawn: order} tasks: order: payload: weight_g: {gen: normal, mean: 500, std: 20, decimals: 1} run: {until: 200} ``` It prints these records: ```text [EVT] {'sim_ts': 60.0, 'timestamp': '...', 'key': 'orders-1', 'task': 'order', 'instance': 0, 'value': {'weight_g': 492.0}} [EVT] {'sim_ts': 120.0, 'timestamp': '...', 'key': 'orders-2', 'task': 'order', 'instance': 1, 'value': {'weight_g': 477.7}} [EVT] {'sim_ts': 180.0, 'timestamp': '...', 'key': 'orders-3', 'task': 'order', 'instance': 2, 'value': {'weight_g': 518.3}} ``` ## JSON Schema The schema of `Normal`, from `desflow schema`. ```json { "additionalProperties": false, "description": "`normal`: a float from a normal distribution with `mean` and `std`.", "properties": { "null_rate": { "anyOf": [ { "maximum": 1, "minimum": 0, "type": "number" }, { "type": "null" }, { "$ref": "#/$defs/NonNegativeNumberText" }, { "$ref": "#/$defs/Placeholder" } ], "default": null }, "unique": { "default": false, "description": "Gives each value once. A value built only from a task's vars, such as a format or an expr with no generator that draws, draws the vars again and makes the whole payload again until the value is new.", "anyOf": [ { "type": "boolean" }, { "$ref": "#/$defs/Placeholder" } ] }, "omit_rate": { "anyOf": [ { "maximum": 1, "minimum": 0, "type": "number" }, { "type": "null" }, { "$ref": "#/$defs/NonNegativeNumberText" }, { "$ref": "#/$defs/Placeholder" } ], "default": null }, "omit_when": { "anyOf": [ { "type": "string" }, { "type": "null" } ], "default": null }, "gen": { "anyOf": [ { "const": "normal", "type": "string" }, { "$ref": "#/$defs/Placeholder" } ] }, "mean": { "$ref": "#/$defs/Value" }, "std": { "$ref": "#/$defs/Value" }, "decimals": { "anyOf": [ { "minimum": 0, "type": "integer" }, { "type": "null" }, { "$ref": "#/$defs/NonNegativeIntegerText" }, { "$ref": "#/$defs/Placeholder" } ], "default": null } }, "required": [ "gen", "mean", "std" ], "title": "Normal", "type": "object" } ``` # sample `sample`: one draw from a distribution family with its parameters, or from the live distribution of a service. An `exponential` takes `mean`, the average gap, in place of `rate`. Use it for a duration or a size whose shape you know, such as exponential gaps, or one that follows the live distribution of a service. ## Keys | Key | Type | Default | | ---------- | --------------------------------- | -------- | | `gen` | `sample` | required | | `dist` | text | none | | `service` | text | none | | `rate` | Value | none | | `mean` | Value | none | | `std` | Value | none | | `low` | Value | none | | `value` | Value | none | | `high` | Value | none | | `mode` | Value | none | | `shape` | Value | none | | `scale` | Value | none | | `p` | Value | none | | `values` | list of integer or number or text | none | | `weights` | list of number | none | | `edges` | list of integer or number or text | none | | `counts` | list of number | none | | `decimals` | integer | none | A `Value` is a constant or a generator, as [What a Generator Is](https://jaehyeon.me/desflow/latest/generators/#what-a-generator-is) explains. Every kind also accepts `null_rate`, `unique`, `omit_rate` and `omit_when`, which [Generators](https://jaehyeon.me/desflow/latest/generators/#keys-every-kind-accepts) describes. ## Example `wait_s` is a draw from an exponential distribution with a rate of 0.5, so its mean is 2 seconds, rounded to 2 decimals. An order starts every 60 seconds for 200 seconds, with the seed 42, so three orders start. ```yaml # Sample: a draw from a distribution family. # A task `order` starts every 60 seconds, and the run lasts 200 seconds, so three orders # start. # # Run it with: desflow run examples/generators/sample.yaml simulation: sim_id: Gen factor: 0 random_seed: 42 logical_start_time: 2026-01-01T00:00:00 egress: - {type: Console} arrivals: orders: {dist: constant, value: 60, spawn: order} tasks: order: payload: wait_s: {gen: sample, dist: exponential, rate: 0.5, decimals: 2} run: {until: 200} ``` It prints these records: ```text [EVT] {'sim_ts': 60.0, 'timestamp': '...', 'key': 'orders-1', 'task': 'order', 'instance': 0, 'value': {'wait_s': 0.37}} [EVT] {'sim_ts': 120.0, 'timestamp': '...', 'key': 'orders-2', 'task': 'order', 'instance': 1, 'value': {'wait_s': 0.72}} [EVT] {'sim_ts': 180.0, 'timestamp': '...', 'key': 'orders-3', 'task': 'order', 'instance': 2, 'value': {'wait_s': 2.37}} ``` ## JSON Schema The schema of `Sample`, from `desflow schema`. ```json { "additionalProperties": false, "description": "`sample`: one draw from a distribution family with its parameters, or from\nthe live distribution of a service. An `exponential` takes `mean`, the average\ngap, in place of `rate`.", "properties": { "null_rate": { "anyOf": [ { "maximum": 1, "minimum": 0, "type": "number" }, { "type": "null" }, { "$ref": "#/$defs/NonNegativeNumberText" }, { "$ref": "#/$defs/Placeholder" } ], "default": null }, "unique": { "default": false, "description": "Gives each value once. A value built only from a task's vars, such as a format or an expr with no generator that draws, draws the vars again and makes the whole payload again until the value is new.", "anyOf": [ { "type": "boolean" }, { "$ref": "#/$defs/Placeholder" } ] }, "omit_rate": { "anyOf": [ { "maximum": 1, "minimum": 0, "type": "number" }, { "type": "null" }, { "$ref": "#/$defs/NonNegativeNumberText" }, { "$ref": "#/$defs/Placeholder" } ], "default": null }, "omit_when": { "anyOf": [ { "type": "string" }, { "type": "null" } ], "default": null }, "gen": { "anyOf": [ { "const": "sample", "type": "string" }, { "$ref": "#/$defs/Placeholder" } ] }, "dist": { "anyOf": [ { "type": "string" }, { "type": "null" } ], "default": null }, "service": { "anyOf": [ { "type": "string" }, { "type": "null" } ], "default": null }, "rate": { "$ref": "#/$defs/Value", "default": null }, "mean": { "$ref": "#/$defs/Value", "default": null }, "std": { "$ref": "#/$defs/Value", "default": null }, "low": { "$ref": "#/$defs/Value", "default": null }, "value": { "$ref": "#/$defs/Value", "default": null }, "high": { "$ref": "#/$defs/Value", "default": null }, "mode": { "$ref": "#/$defs/Value", "default": null }, "shape": { "$ref": "#/$defs/Value", "default": null }, "scale": { "$ref": "#/$defs/Value", "default": null }, "p": { "$ref": "#/$defs/Value", "default": null }, "values": { "anyOf": [ { "items": { "anyOf": [ { "type": "integer" }, { "type": "number" }, { "type": "string" }, { "$ref": "#/$defs/NumberText" }, { "$ref": "#/$defs/Placeholder" } ] }, "type": "array" }, { "type": "null" } ], "default": null }, "weights": { "anyOf": [ { "items": { "anyOf": [ { "type": "number" }, { "$ref": "#/$defs/NumberText" }, { "$ref": "#/$defs/Placeholder" } ] }, "type": "array" }, { "type": "null" } ], "default": null }, "edges": { "anyOf": [ { "items": { "anyOf": [ { "type": "integer" }, { "type": "number" }, { "type": "string" }, { "$ref": "#/$defs/NumberText" }, { "$ref": "#/$defs/Placeholder" } ] }, "type": "array" }, { "type": "null" } ], "default": null }, "counts": { "anyOf": [ { "items": { "anyOf": [ { "type": "number" }, { "$ref": "#/$defs/NumberText" }, { "$ref": "#/$defs/Placeholder" } ] }, "type": "array" }, { "type": "null" } ], "default": null }, "decimals": { "anyOf": [ { "minimum": 0, "type": "integer" }, { "type": "null" }, { "$ref": "#/$defs/NonNegativeIntegerText" }, { "$ref": "#/$defs/Placeholder" } ], "default": null } }, "required": [ "gen" ], "title": "Sample", "type": "object" } ``` # boolean `boolean`: true with probability `p` (0.5 when not given). Use it for a flag that is true for a share of the orders, such as a gift. ## Keys | Key | Type | Default | | ----- | --------- | -------- | | `gen` | `boolean` | required | | `p` | Value | `0.5` | A `Value` is a constant or a generator, as [What a Generator Is](https://jaehyeon.me/desflow/latest/generators/#what-a-generator-is) explains. Every kind also accepts `null_rate`, `unique`, `omit_rate` and `omit_when`, which [Generators](https://jaehyeon.me/desflow/latest/generators/#keys-every-kind-accepts) describes. ## Example `gift` is true for about half of the orders. An order starts every 60 seconds for 200 seconds, with the seed 42, so three orders start. ```yaml # Boolean: true or false, with a chance of true. # A task `order` starts every 60 seconds, and the run lasts 200 seconds, so three orders # start. # # Run it with: desflow run examples/generators/boolean.yaml simulation: sim_id: Gen factor: 0 random_seed: 42 logical_start_time: 2026-01-01T00:00:00 egress: - {type: Console} arrivals: orders: {dist: constant, value: 60, spawn: order} tasks: order: payload: gift: {gen: boolean, p: 0.5} run: {until: 200} ``` It prints these records: ```text [EVT] {'sim_ts': 60.0, 'timestamp': '...', 'key': 'orders-1', 'task': 'order', 'instance': 0, 'value': {'gift': False}} [EVT] {'sim_ts': 120.0, 'timestamp': '...', 'key': 'orders-2', 'task': 'order', 'instance': 1, 'value': {'gift': True}} [EVT] {'sim_ts': 180.0, 'timestamp': '...', 'key': 'orders-3', 'task': 'order', 'instance': 2, 'value': {'gift': False}} ``` ## JSON Schema The schema of `Boolean`, from `desflow schema`. ```json { "additionalProperties": false, "description": "`boolean`: true with probability `p` (0.5 when not given).", "properties": { "null_rate": { "anyOf": [ { "maximum": 1, "minimum": 0, "type": "number" }, { "type": "null" }, { "$ref": "#/$defs/NonNegativeNumberText" }, { "$ref": "#/$defs/Placeholder" } ], "default": null }, "unique": { "default": false, "description": "Gives each value once. A value built only from a task's vars, such as a format or an expr with no generator that draws, draws the vars again and makes the whole payload again until the value is new.", "anyOf": [ { "type": "boolean" }, { "$ref": "#/$defs/Placeholder" } ] }, "omit_rate": { "anyOf": [ { "maximum": 1, "minimum": 0, "type": "number" }, { "type": "null" }, { "$ref": "#/$defs/NonNegativeNumberText" }, { "$ref": "#/$defs/Placeholder" } ], "default": null }, "omit_when": { "anyOf": [ { "type": "string" }, { "type": "null" } ], "default": null }, "gen": { "anyOf": [ { "const": "boolean", "type": "string" }, { "$ref": "#/$defs/Placeholder" } ] }, "p": { "$ref": "#/$defs/Value", "default": 0.5 } }, "required": [ "gen" ], "title": "Boolean", "type": "object" } ``` # one_of `one_of`: one of `choices`, each equally likely. Only the choice picked is evaluated. Use it for one value out of a list, each equally likely, such as a colour. ## Keys | Key | Type | Default | | --------- | ------------- | -------- | | `gen` | `one_of` | required | | `choices` | list of Value | required | A `Value` is a constant or a generator, as [What a Generator Is](https://jaehyeon.me/desflow/latest/generators/#what-a-generator-is) explains. Every kind also accepts `null_rate`, `unique`, `omit_rate` and `omit_when`, which [Generators](https://jaehyeon.me/desflow/latest/generators/#keys-every-kind-accepts) describes. ## Example `colour` is red, green or blue, each with a chance of one in three. An order starts every 60 seconds for 200 seconds, with the seed 42, so three orders start. ```yaml # One Of: one choice out of a list, each equally likely. # A task `order` starts every 60 seconds, and the run lasts 200 seconds, so three orders # start. # # Run it with: desflow run examples/generators/one_of.yaml simulation: sim_id: Gen factor: 0 random_seed: 42 logical_start_time: 2026-01-01T00:00:00 egress: - {type: Console} arrivals: orders: {dist: constant, value: 60, spawn: order} tasks: order: payload: colour: {gen: one_of, choices: [red, green, blue]} run: {until: 200} ``` It prints these records: ```text [EVT] {'sim_ts': 60.0, 'timestamp': '...', 'key': 'orders-1', 'task': 'order', 'instance': 0, 'value': {'colour': 'blue'}} [EVT] {'sim_ts': 120.0, 'timestamp': '...', 'key': 'orders-2', 'task': 'order', 'instance': 1, 'value': {'colour': 'red'}} [EVT] {'sim_ts': 180.0, 'timestamp': '...', 'key': 'orders-3', 'task': 'order', 'instance': 2, 'value': {'colour': 'green'}} ``` ## JSON Schema The schema of `OneOf`, from `desflow schema`. ```json { "additionalProperties": false, "description": "`one_of`: one of `choices`, each equally likely. Only the choice picked is\nevaluated.", "properties": { "null_rate": { "anyOf": [ { "maximum": 1, "minimum": 0, "type": "number" }, { "type": "null" }, { "$ref": "#/$defs/NonNegativeNumberText" }, { "$ref": "#/$defs/Placeholder" } ], "default": null }, "unique": { "default": false, "description": "Gives each value once. A value built only from a task's vars, such as a format or an expr with no generator that draws, draws the vars again and makes the whole payload again until the value is new.", "anyOf": [ { "type": "boolean" }, { "$ref": "#/$defs/Placeholder" } ] }, "omit_rate": { "anyOf": [ { "maximum": 1, "minimum": 0, "type": "number" }, { "type": "null" }, { "$ref": "#/$defs/NonNegativeNumberText" }, { "$ref": "#/$defs/Placeholder" } ], "default": null }, "omit_when": { "anyOf": [ { "type": "string" }, { "type": "null" } ], "default": null }, "gen": { "anyOf": [ { "const": "one_of", "type": "string" }, { "$ref": "#/$defs/Placeholder" } ] }, "choices": { "items": { "$ref": "#/$defs/Value" }, "minItems": 1, "type": "array" } }, "required": [ "gen", "choices" ], "title": "OneOf", "type": "object" } ``` # weighted `weighted`: one choice, by weight. `options` maps each value to its weight, or `choices` lists `{value, weight}` for values that are mappings or generators. Each weight is 0 or more and at least one is above 0; weights are divided by their sum. Only the value picked is evaluated. In a blueprint, an option key written `yes`, `no`, `on` or `off` is that text, not a boolean. Use it for one value out of a list in which some values are more likely, such as a region. ## Keys | Key | Type | Default | | --------- | ----------------------------------------- | -------- | | `gen` | `weighted` | required | | `options` | mapping of names to Value | none | | `choices` | list of [WeightedChoice](#weightedchoice) | none | A `Value` is a constant or a generator, as [What a Generator Is](https://jaehyeon.me/desflow/latest/generators/#what-a-generator-is) explains. Every kind also accepts `null_rate`, `unique`, `omit_rate` and `omit_when`, which [Generators](https://jaehyeon.me/desflow/latest/generators/#keys-every-kind-accepts) describes. ### WeightedChoice One entry of `weighted` `choices`: a value and its weight. | Key | Type | Default | | -------- | ----- | -------- | | `value` | Value | required | | `weight` | Value | required | ## Example `region` is north with weight 3, south with weight 1 or east with weight 2, so north has a chance of one in two. An order starts every 60 seconds for 200 seconds, with the seed 42, so three orders start. ```yaml # Weighted: one choice by weight. # A task `order` starts every 60 seconds, and the run lasts 200 seconds, so three orders # start. # # Run it with: desflow run examples/generators/weighted.yaml simulation: sim_id: Gen factor: 0 random_seed: 42 logical_start_time: 2026-01-01T00:00:00 egress: - {type: Console} arrivals: orders: {dist: constant, value: 60, spawn: order} tasks: order: payload: region: gen: weighted options: {north: 3, south: 1, east: 2} run: {until: 200} ``` It prints these records: ```text [EVT] {'sim_ts': 60.0, 'timestamp': '...', 'key': 'orders-1', 'task': 'order', 'instance': 0, 'value': {'region': 'east'}} [EVT] {'sim_ts': 120.0, 'timestamp': '...', 'key': 'orders-2', 'task': 'order', 'instance': 1, 'value': {'region': 'north'}} [EVT] {'sim_ts': 180.0, 'timestamp': '...', 'key': 'orders-3', 'task': 'order', 'instance': 2, 'value': {'region': 'south'}} ``` ## JSON Schema The schema of `Weighted`, from `desflow schema`. ```json { "additionalProperties": false, "description": "`weighted`: one choice, by weight. `options` maps each value to its weight, or\n`choices` lists `{value, weight}` for values that are mappings or generators. Each\nweight is 0 or more and at least one is above 0; weights are divided by their\nsum. Only the value picked is evaluated. In a blueprint, an option key written\n`yes`, `no`, `on` or `off` is that text, not a boolean.", "properties": { "null_rate": { "anyOf": [ { "maximum": 1, "minimum": 0, "type": "number" }, { "type": "null" }, { "$ref": "#/$defs/NonNegativeNumberText" }, { "$ref": "#/$defs/Placeholder" } ], "default": null }, "unique": { "default": false, "description": "Gives each value once. A value built only from a task's vars, such as a format or an expr with no generator that draws, draws the vars again and makes the whole payload again until the value is new.", "anyOf": [ { "type": "boolean" }, { "$ref": "#/$defs/Placeholder" } ] }, "omit_rate": { "anyOf": [ { "maximum": 1, "minimum": 0, "type": "number" }, { "type": "null" }, { "$ref": "#/$defs/NonNegativeNumberText" }, { "$ref": "#/$defs/Placeholder" } ], "default": null }, "omit_when": { "anyOf": [ { "type": "string" }, { "type": "null" } ], "default": null }, "gen": { "anyOf": [ { "const": "weighted", "type": "string" }, { "$ref": "#/$defs/Placeholder" } ] }, "options": { "anyOf": [ { "additionalProperties": { "$ref": "#/$defs/Value" }, "type": "object" }, { "type": "null" } ], "default": null }, "choices": { "anyOf": [ { "items": { "$ref": "#/$defs/WeightedChoice" }, "minItems": 1, "type": "array" }, { "type": "null" } ], "default": null } }, "required": [ "gen" ], "title": "Weighted", "type": "object" } ``` # pick `pick`: a list of `count` different `choices`, drawn without replacement, in the order drawn. Only the choices picked are evaluated. Use it for several different values out of a list, such as optional extras. ## Keys | Key | Type | Default | | --------- | ------------- | -------- | | `gen` | `pick` | required | | `choices` | list of Value | required | | `count` | Value | `1` | A `Value` is a constant or a generator, as [What a Generator Is](https://jaehyeon.me/desflow/latest/generators/#what-a-generator-is) explains. Every kind also accepts `null_rate`, `unique`, `omit_rate` and `omit_when`, which [Generators](https://jaehyeon.me/desflow/latest/generators/#keys-every-kind-accepts) describes. ## Example `extras` is a list of 2 different extras out of 4, in the order drawn. An order starts every 60 seconds for 200 seconds, with the seed 42, so three orders start. ```yaml # Pick: several different choices out of a list. # A task `order` starts every 60 seconds, and the run lasts 200 seconds, so three orders # start. # # Run it with: desflow run examples/generators/pick.yaml simulation: sim_id: Gen factor: 0 random_seed: 42 logical_start_time: 2026-01-01T00:00:00 egress: - {type: Console} arrivals: orders: {dist: constant, value: 60, spawn: order} tasks: order: payload: extras: {gen: pick, choices: [card, ribbon, box, tag], count: 2} run: {until: 200} ``` It prints these records: ```text [EVT] {'sim_ts': 60.0, 'timestamp': '...', 'key': 'orders-1', 'task': 'order', 'instance': 0, 'value': {'extras': ['card', 'ribbon']}} [EVT] {'sim_ts': 120.0, 'timestamp': '...', 'key': 'orders-2', 'task': 'order', 'instance': 1, 'value': {'extras': ['tag', 'box']}} [EVT] {'sim_ts': 180.0, 'timestamp': '...', 'key': 'orders-3', 'task': 'order', 'instance': 2, 'value': {'extras': ['tag', 'box']}} ``` ## JSON Schema The schema of `Pick`, from `desflow schema`. ```json { "additionalProperties": false, "description": "`pick`: a list of `count` different `choices`, drawn without replacement, in\nthe order drawn. Only the choices picked are evaluated.", "properties": { "null_rate": { "anyOf": [ { "maximum": 1, "minimum": 0, "type": "number" }, { "type": "null" }, { "$ref": "#/$defs/NonNegativeNumberText" }, { "$ref": "#/$defs/Placeholder" } ], "default": null }, "unique": { "default": false, "description": "Gives each value once. A value built only from a task's vars, such as a format or an expr with no generator that draws, draws the vars again and makes the whole payload again until the value is new.", "anyOf": [ { "type": "boolean" }, { "$ref": "#/$defs/Placeholder" } ] }, "omit_rate": { "anyOf": [ { "maximum": 1, "minimum": 0, "type": "number" }, { "type": "null" }, { "$ref": "#/$defs/NonNegativeNumberText" }, { "$ref": "#/$defs/Placeholder" } ], "default": null }, "omit_when": { "anyOf": [ { "type": "string" }, { "type": "null" } ], "default": null }, "gen": { "anyOf": [ { "const": "pick", "type": "string" }, { "$ref": "#/$defs/Placeholder" } ] }, "choices": { "items": { "$ref": "#/$defs/Value" }, "minItems": 1, "type": "array" }, "count": { "$ref": "#/$defs/Value", "default": 1 } }, "required": [ "gen", "choices" ], "title": "Pick", "type": "object" } ``` # fake `fake`: a value from the Faker library. `method` names any method of Faker's providers, such as `name`, `email`, `isbn13` or `credit_card_number`, and `args` and `kwargs` are passed to it. `locale` picks the language and country, `en_US` by default. It needs the `fake` extra. Each `fake` generator has a Faker of its own, seeded from the run's seed and its place in the file, so the same seed gives the same values and adding a field changes no other. With no seed, the values change on every run. A date, a time or a decimal result is written as text or a float. Use it for names, addresses and other realistic text, when invented values are enough. ## Keys | Key | Type | Default | | -------- | ------------------------- | --------- | | `gen` | `fake` | required | | `method` | text | required | | `args` | list of Value | | | `kwargs` | mapping of names to Value | | | `locale` | text | `"en_US"` | A `Value` is a constant or a generator, as [What a Generator Is](https://jaehyeon.me/desflow/latest/generators/#what-a-generator-is) explains. Every kind also accepts `null_rate`, `unique`, `omit_rate` and `omit_when`, which [Generators](https://jaehyeon.me/desflow/latest/generators/#keys-every-kind-accepts) describes. ## Example `customer` is a made-up person's name. An order starts every 60 seconds for 200 seconds, with the seed 42, so three orders start. ```yaml # Fake: a made-up name from Faker. # A task `order` starts every 60 seconds, and the run lasts 200 seconds, so three orders # start. # # Run it with: desflow run examples/generators/fake.yaml simulation: sim_id: Gen factor: 0 random_seed: 42 logical_start_time: 2026-01-01T00:00:00 egress: - {type: Console} arrivals: orders: {dist: constant, value: 60, spawn: order} tasks: order: payload: customer: {gen: fake, method: name} run: {until: 200} ``` It prints these records: ```text [EVT] {'sim_ts': 60.0, 'timestamp': '...', 'key': 'orders-1', 'task': 'order', 'instance': 0, 'value': {'customer': 'Amanda Rose'}} [EVT] {'sim_ts': 120.0, 'timestamp': '...', 'key': 'orders-2', 'task': 'order', 'instance': 1, 'value': {'customer': 'Noah Boone'}} [EVT] {'sim_ts': 180.0, 'timestamp': '...', 'key': 'orders-3', 'task': 'order', 'instance': 2, 'value': {'customer': 'James Walker'}} ``` ## JSON Schema The schema of `Fake`, from `desflow schema`. ```json { "additionalProperties": false, "description": "`fake`: a value from the Faker library. `method` names any method of Faker's\nproviders, such as `name`, `email`, `isbn13` or `credit_card_number`, and `args`\nand `kwargs` are passed to it. `locale` picks the language and country, `en_US`\nby default. It needs the `fake` extra.\n\nEach `fake` generator has a Faker of its own, seeded from the run's seed and its\nplace in the file, so the same seed gives the same values and adding a field\nchanges no other. With no seed, the values change on every run. A date, a time\nor a decimal result is written as text or a float.", "properties": { "null_rate": { "anyOf": [ { "maximum": 1, "minimum": 0, "type": "number" }, { "type": "null" }, { "$ref": "#/$defs/NonNegativeNumberText" }, { "$ref": "#/$defs/Placeholder" } ], "default": null }, "unique": { "default": false, "description": "Gives each value once. A value built only from a task's vars, such as a format or an expr with no generator that draws, draws the vars again and makes the whole payload again until the value is new.", "anyOf": [ { "type": "boolean" }, { "$ref": "#/$defs/Placeholder" } ] }, "omit_rate": { "anyOf": [ { "maximum": 1, "minimum": 0, "type": "number" }, { "type": "null" }, { "$ref": "#/$defs/NonNegativeNumberText" }, { "$ref": "#/$defs/Placeholder" } ], "default": null }, "omit_when": { "anyOf": [ { "type": "string" }, { "type": "null" } ], "default": null }, "gen": { "anyOf": [ { "const": "fake", "type": "string" }, { "$ref": "#/$defs/Placeholder" } ] }, "method": { "type": "string" }, "args": { "items": { "$ref": "#/$defs/Value" }, "type": "array" }, "kwargs": { "additionalProperties": { "$ref": "#/$defs/Value" }, "type": "object" }, "locale": { "default": "en_US", "type": "string" } }, "required": [ "gen", "method" ], "title": "Fake", "type": "object" } ``` # uuid `uuid`: a version 4 UUID from the generator's random sequence, so it repeats with the seed, or a version 7 UUID whose 48-bit millisecond field comes from the logical time. Use it for a unique identifier, such as an order id. ## Keys | Key | Type | Default | | --------- | ---------- | -------- | | `gen` | `uuid` | required | | `version` | `4` or `7` | `4` | Every kind also accepts `null_rate`, `unique`, `omit_rate` and `omit_when`, which [Generators](https://jaehyeon.me/desflow/latest/generators/#keys-every-kind-accepts) describes. ## Example `order_id` is a version 4 UUID, and the same seed gives the same UUIDs. An order starts every 60 seconds for 200 seconds, with the seed 42, so three orders start. ```yaml # UUID: a version 4 UUID that repeats with the seed. # A task `order` starts every 60 seconds, and the run lasts 200 seconds, so three orders # start. # # Run it with: desflow run examples/generators/uuid.yaml simulation: sim_id: Gen factor: 0 random_seed: 42 logical_start_time: 2026-01-01T00:00:00 egress: - {type: Console} arrivals: orders: {dist: constant, value: 60, spawn: order} tasks: order: payload: order_id: {gen: uuid} run: {until: 200} ``` It prints these records: ```text [EVT] {'sim_ts': 60.0, 'timestamp': '...', 'key': 'orders-1', 'task': 'order', 'instance': 0, 'value': {'order_id': 'e770f19e-f419-4749-9cf9-9551739f102d'}} [EVT] {'sim_ts': 120.0, 'timestamp': '...', 'key': 'orders-2', 'task': 'order', 'instance': 1, 'value': {'order_id': 'a3b69289-469e-4be2-b8ec-41e32b1d0fed'}} [EVT] {'sim_ts': 180.0, 'timestamp': '...', 'key': 'orders-3', 'task': 'order', 'instance': 2, 'value': {'order_id': '97215c05-1e3e-4ff7-b54a-b0380a902655'}} ``` ## JSON Schema The schema of `Uuid`, from `desflow schema`. ```json { "additionalProperties": false, "description": "`uuid`: a version 4 UUID from the generator's random sequence, so it repeats\nwith the seed, or a version 7 UUID whose 48-bit millisecond field comes from the\nlogical time.", "properties": { "null_rate": { "anyOf": [ { "maximum": 1, "minimum": 0, "type": "number" }, { "type": "null" }, { "$ref": "#/$defs/NonNegativeNumberText" }, { "$ref": "#/$defs/Placeholder" } ], "default": null }, "unique": { "default": false, "description": "Gives each value once. A value built only from a task's vars, such as a format or an expr with no generator that draws, draws the vars again and makes the whole payload again until the value is new.", "anyOf": [ { "type": "boolean" }, { "$ref": "#/$defs/Placeholder" } ] }, "omit_rate": { "anyOf": [ { "maximum": 1, "minimum": 0, "type": "number" }, { "type": "null" }, { "$ref": "#/$defs/NonNegativeNumberText" }, { "$ref": "#/$defs/Placeholder" } ], "default": null }, "omit_when": { "anyOf": [ { "type": "string" }, { "type": "null" } ], "default": null }, "gen": { "anyOf": [ { "const": "uuid", "type": "string" }, { "$ref": "#/$defs/Placeholder" } ] }, "version": { "default": 4, "anyOf": [ { "enum": [ 4, 7 ], "type": "integer" }, { "$ref": "#/$defs/Placeholder" } ] } }, "required": [ "gen" ], "title": "Uuid", "type": "object" } ``` # sequence `sequence`: the next integer of a counter, `start` plus `step` times the count of calls so far, restarting after `loop_after` calls. With `format`, the text `format.format(n)`, such as `"sensor-{}"`. There is one counter for the run, shared by every entity, so ids stay unique. Use it for an order number or a label that counts up. ## Keys | Key | Type | Default | | ------------ | ---------- | -------- | | `gen` | `sequence` | required | | `start` | integer | `0` | | `step` | integer | `1` | | `loop_after` | integer | none | | `format` | text | none | Every kind also accepts `null_rate`, `unique`, `omit_rate` and `omit_when`, which [Generators](https://jaehyeon.me/desflow/latest/generators/#keys-every-kind-accepts) describes. ## Example `order_id` counts up from 1000 and is written as `ord-1000`, `ord-1001` and so on. An order starts every 60 seconds for 200 seconds, with the seed 42, so three orders start. ```yaml # Sequence: the next number of a counter, as text. # A task `order` starts every 60 seconds, and the run lasts 200 seconds, so three orders # start. # # Run it with: desflow run examples/generators/sequence.yaml simulation: sim_id: Gen factor: 0 random_seed: 42 logical_start_time: 2026-01-01T00:00:00 egress: - {type: Console} arrivals: orders: {dist: constant, value: 60, spawn: order} tasks: order: payload: order_id: {gen: sequence, start: 1000, format: "ord-{}"} run: {until: 200} ``` It prints these records: ```text [EVT] {'sim_ts': 60.0, 'timestamp': '...', 'key': 'orders-1', 'task': 'order', 'instance': 0, 'value': {'order_id': 'ord-1000'}} [EVT] {'sim_ts': 120.0, 'timestamp': '...', 'key': 'orders-2', 'task': 'order', 'instance': 1, 'value': {'order_id': 'ord-1001'}} [EVT] {'sim_ts': 180.0, 'timestamp': '...', 'key': 'orders-3', 'task': 'order', 'instance': 2, 'value': {'order_id': 'ord-1002'}} ``` ## JSON Schema The schema of `Sequence`, from `desflow schema`. ```json { "additionalProperties": false, "description": "`sequence`: the next integer of a counter, `start` plus `step` times the\ncount of calls so far, restarting after `loop_after` calls. With `format`, the\ntext `format.format(n)`, such as `\"sensor-{}\"`. There is one counter for the run,\nshared by every entity, so ids stay unique.", "properties": { "null_rate": { "anyOf": [ { "maximum": 1, "minimum": 0, "type": "number" }, { "type": "null" }, { "$ref": "#/$defs/NonNegativeNumberText" }, { "$ref": "#/$defs/Placeholder" } ], "default": null }, "unique": { "default": false, "description": "Gives each value once. A value built only from a task's vars, such as a format or an expr with no generator that draws, draws the vars again and makes the whole payload again until the value is new.", "anyOf": [ { "type": "boolean" }, { "$ref": "#/$defs/Placeholder" } ] }, "omit_rate": { "anyOf": [ { "maximum": 1, "minimum": 0, "type": "number" }, { "type": "null" }, { "$ref": "#/$defs/NonNegativeNumberText" }, { "$ref": "#/$defs/Placeholder" } ], "default": null }, "omit_when": { "anyOf": [ { "type": "string" }, { "type": "null" } ], "default": null }, "gen": { "anyOf": [ { "const": "sequence", "type": "string" }, { "$ref": "#/$defs/Placeholder" } ] }, "start": { "default": 0, "anyOf": [ { "type": "integer" }, { "$ref": "#/$defs/IntegerText" }, { "$ref": "#/$defs/Placeholder" } ] }, "step": { "default": 1, "anyOf": [ { "type": "integer" }, { "$ref": "#/$defs/IntegerText" }, { "$ref": "#/$defs/Placeholder" } ] }, "loop_after": { "anyOf": [ { "minimum": 1, "type": "integer" }, { "type": "null" }, { "$ref": "#/$defs/PositiveIntegerText" }, { "$ref": "#/$defs/Placeholder" } ], "default": null }, "format": { "anyOf": [ { "type": "string" }, { "type": "null" } ], "default": null } }, "required": [ "gen" ], "title": "Sequence", "type": "object" } ``` # format `format`: `template.format_map(...)` over `names`, then the vars of the task. A name in the template is a var, or an entry of `names`, which wins. `{attr.}` reads an attribute of the entity, as `attr.` does in an expression, and `{attr.pair[0]}` an item of one; a place that runs before the entity has attributes, such as an arrival's `vars`, `key` or `count`, refuses it. Use it for text built from parts, such as a label made of a region and a number. ## Keys | Key | Type | Default | | ---------- | ------------------------- | -------- | | `gen` | `format` | required | | `template` | text | required | | `names` | mapping of names to Value | | A `Value` is a constant or a generator, as [What a Generator Is](https://jaehyeon.me/desflow/latest/generators/#what-a-generator-is) explains. Every kind also accepts `null_rate`, `unique`, `omit_rate` and `omit_when`, which [Generators](https://jaehyeon.me/desflow/latest/generators/#keys-every-kind-accepts) describes. ## Example `label` joins a region and a number, each from its own generator, with a dash. An order starts every 60 seconds for 200 seconds, with the seed 42, so three orders start. ```yaml # Format: text built from a template and named parts. # A task `order` starts every 60 seconds, and the run lasts 200 seconds, so three orders # start. # # Run it with: desflow run examples/generators/format.yaml simulation: sim_id: Gen factor: 0 random_seed: 42 logical_start_time: 2026-01-01T00:00:00 egress: - {type: Console} arrivals: orders: {dist: constant, value: 60, spawn: order} tasks: order: payload: label: gen: format template: "{region}-{number}" names: region: {gen: one_of, choices: [north, south]} number: {gen: integer, bounds: [10, 99]} run: {until: 200} ``` It prints these records: ```text [EVT] {'sim_ts': 60.0, 'timestamp': '...', 'key': 'orders-1', 'task': 'order', 'instance': 0, 'value': {'label': 'north-28'}} [EVT] {'sim_ts': 120.0, 'timestamp': '...', 'key': 'orders-2', 'task': 'order', 'instance': 1, 'value': {'label': 'north-21'}} [EVT] {'sim_ts': 180.0, 'timestamp': '...', 'key': 'orders-3', 'task': 'order', 'instance': 2, 'value': {'label': 'north-14'}} ``` ## JSON Schema The schema of `Format`, from `desflow schema`. ```json { "additionalProperties": false, "description": "`format`: `template.format_map(...)` over `names`, then the vars of the task.\nA name in the template is a var, or an entry of `names`, which wins.\n`{attr.}` reads an attribute of the entity, as `attr.` does in an\nexpression, and `{attr.pair[0]}` an item of one; a place that runs before the\nentity has attributes, such as an arrival's `vars`, `key` or `count`, refuses\nit.", "properties": { "null_rate": { "anyOf": [ { "maximum": 1, "minimum": 0, "type": "number" }, { "type": "null" }, { "$ref": "#/$defs/NonNegativeNumberText" }, { "$ref": "#/$defs/Placeholder" } ], "default": null }, "unique": { "default": false, "description": "Gives each value once. A value built only from a task's vars, such as a format or an expr with no generator that draws, draws the vars again and makes the whole payload again until the value is new.", "anyOf": [ { "type": "boolean" }, { "$ref": "#/$defs/Placeholder" } ] }, "omit_rate": { "anyOf": [ { "maximum": 1, "minimum": 0, "type": "number" }, { "type": "null" }, { "$ref": "#/$defs/NonNegativeNumberText" }, { "$ref": "#/$defs/Placeholder" } ], "default": null }, "omit_when": { "anyOf": [ { "type": "string" }, { "type": "null" } ], "default": null }, "gen": { "anyOf": [ { "const": "format", "type": "string" }, { "$ref": "#/$defs/Placeholder" } ] }, "template": { "type": "string" }, "names": { "additionalProperties": { "$ref": "#/$defs/Value" }, "type": "object" } }, "required": [ "gen", "template" ], "title": "Format", "type": "object" } ``` # lower `lower`: the text of `value` in lower case. Use it for a code or a label that must be in one standard case, whatever case it was drawn in. ## Keys | Key | Type | Default | | ------- | ------- | -------- | | `gen` | `lower` | required | | `value` | Value | required | A `Value` is a constant or a generator, as [What a Generator Is](https://jaehyeon.me/desflow/latest/generators/#what-a-generator-is) explains. Every kind also accepts `null_rate`, `unique`, `omit_rate` and `omit_when`, which [Generators](https://jaehyeon.me/desflow/latest/generators/#keys-every-kind-accepts) describes. ## Example `code` is a code from a list, written in lower case. An order starts every 60 seconds for 200 seconds, with the seed 42, so three orders start. ```yaml # Lower: the lower case of a text. # A task `order` starts every 60 seconds, and the run lasts 200 seconds, so three orders # start. # # Run it with: desflow run examples/generators/lower.yaml simulation: sim_id: Gen factor: 0 random_seed: 42 logical_start_time: 2026-01-01T00:00:00 egress: - {type: Console} arrivals: orders: {dist: constant, value: 60, spawn: order} tasks: order: payload: code: gen: lower value: {gen: one_of, choices: [AB-1, CD-2]} run: {until: 200} ``` It prints these records: ```text [EVT] {'sim_ts': 60.0, 'timestamp': '...', 'key': 'orders-1', 'task': 'order', 'instance': 0, 'value': {'code': 'ab-1'}} [EVT] {'sim_ts': 120.0, 'timestamp': '...', 'key': 'orders-2', 'task': 'order', 'instance': 1, 'value': {'code': 'cd-2'}} [EVT] {'sim_ts': 180.0, 'timestamp': '...', 'key': 'orders-3', 'task': 'order', 'instance': 2, 'value': {'code': 'cd-2'}} ``` ## JSON Schema The schema of `Lower`, from `desflow schema`. ```json { "additionalProperties": false, "description": "`lower`: the text of `value` in lower case.", "properties": { "null_rate": { "anyOf": [ { "maximum": 1, "minimum": 0, "type": "number" }, { "type": "null" }, { "$ref": "#/$defs/NonNegativeNumberText" }, { "$ref": "#/$defs/Placeholder" } ], "default": null }, "unique": { "default": false, "description": "Gives each value once. A value built only from a task's vars, such as a format or an expr with no generator that draws, draws the vars again and makes the whole payload again until the value is new.", "anyOf": [ { "type": "boolean" }, { "$ref": "#/$defs/Placeholder" } ] }, "omit_rate": { "anyOf": [ { "maximum": 1, "minimum": 0, "type": "number" }, { "type": "null" }, { "$ref": "#/$defs/NonNegativeNumberText" }, { "$ref": "#/$defs/Placeholder" } ], "default": null }, "omit_when": { "anyOf": [ { "type": "string" }, { "type": "null" } ], "default": null }, "gen": { "anyOf": [ { "const": "lower", "type": "string" }, { "$ref": "#/$defs/Placeholder" } ] }, "value": { "$ref": "#/$defs/Value" } }, "required": [ "gen", "value" ], "title": "Lower", "type": "object" } ``` # upper `upper`: the text of `value` in upper case. Use it for a code or a label that must be in one standard case, whatever case it was drawn in. ## Keys | Key | Type | Default | | ------- | ------- | -------- | | `gen` | `upper` | required | | `value` | Value | required | A `Value` is a constant or a generator, as [What a Generator Is](https://jaehyeon.me/desflow/latest/generators/#what-a-generator-is) explains. Every kind also accepts `null_rate`, `unique`, `omit_rate` and `omit_when`, which [Generators](https://jaehyeon.me/desflow/latest/generators/#keys-every-kind-accepts) describes. ## Example `code` is a code from a list, written in upper case. An order starts every 60 seconds for 200 seconds, with the seed 42, so three orders start. ```yaml # Upper: the upper case of a text. # A task `order` starts every 60 seconds, and the run lasts 200 seconds, so three orders # start. # # Run it with: desflow run examples/generators/upper.yaml simulation: sim_id: Gen factor: 0 random_seed: 42 logical_start_time: 2026-01-01T00:00:00 egress: - {type: Console} arrivals: orders: {dist: constant, value: 60, spawn: order} tasks: order: payload: code: gen: upper value: {gen: one_of, choices: [ab-1, cd-2]} run: {until: 200} ``` It prints these records: ```text [EVT] {'sim_ts': 60.0, 'timestamp': '...', 'key': 'orders-1', 'task': 'order', 'instance': 0, 'value': {'code': 'AB-1'}} [EVT] {'sim_ts': 120.0, 'timestamp': '...', 'key': 'orders-2', 'task': 'order', 'instance': 1, 'value': {'code': 'CD-2'}} [EVT] {'sim_ts': 180.0, 'timestamp': '...', 'key': 'orders-3', 'task': 'order', 'instance': 2, 'value': {'code': 'CD-2'}} ``` ## JSON Schema The schema of `Upper`, from `desflow schema`. ```json { "additionalProperties": false, "description": "`upper`: the text of `value` in upper case.", "properties": { "null_rate": { "anyOf": [ { "maximum": 1, "minimum": 0, "type": "number" }, { "type": "null" }, { "$ref": "#/$defs/NonNegativeNumberText" }, { "$ref": "#/$defs/Placeholder" } ], "default": null }, "unique": { "default": false, "description": "Gives each value once. A value built only from a task's vars, such as a format or an expr with no generator that draws, draws the vars again and makes the whole payload again until the value is new.", "anyOf": [ { "type": "boolean" }, { "$ref": "#/$defs/Placeholder" } ] }, "omit_rate": { "anyOf": [ { "maximum": 1, "minimum": 0, "type": "number" }, { "type": "null" }, { "$ref": "#/$defs/NonNegativeNumberText" }, { "$ref": "#/$defs/Placeholder" } ], "default": null }, "omit_when": { "anyOf": [ { "type": "string" }, { "type": "null" } ], "default": null }, "gen": { "anyOf": [ { "const": "upper", "type": "string" }, { "$ref": "#/$defs/Placeholder" } ] }, "value": { "$ref": "#/$defs/Value" } }, "required": [ "gen", "value" ], "title": "Upper", "type": "object" } ``` # now `now`: the logical time plus `offset` (seconds or a duration, signed), as the ISO text a record's `timestamp` uses. It reads the simulation clock, never the wall clock. Use it for a time field of a record, with an offset when it is dated before or after the clock. ## Keys | Key | Type | Default | | -------- | ----- | -------- | | `gen` | `now` | required | | `offset` | Value | `0` | A `Value` is a constant or a generator, as [What a Generator Is](https://jaehyeon.me/desflow/latest/generators/#what-a-generator-is) explains. Every kind also accepts `null_rate`, `unique`, `omit_rate` and `omit_when`, which [Generators](https://jaehyeon.me/desflow/latest/generators/#keys-every-kind-accepts) describes. ## Example `placed_at` is the time of the order, and `due_at` is one hour later. An order starts every 60 seconds for 200 seconds, with the seed 42, so three orders start. ```yaml # Now: the simulation time, with an offset. # A task `order` starts every 60 seconds, and the run lasts 200 seconds, so three orders # start. # # Run it with: desflow run examples/generators/now.yaml simulation: sim_id: Gen factor: 0 random_seed: 42 logical_start_time: 2026-01-01T00:00:00 egress: - {type: Console} arrivals: orders: {dist: constant, value: 60, spawn: order} tasks: order: payload: placed_at: {gen: now} due_at: {gen: now, offset: 1 hour} run: {until: 200} ``` It prints these records: ```text [EVT] {'sim_ts': 60.0, 'timestamp': '...', 'key': 'orders-1', 'task': 'order', 'instance': 0, 'value': {'placed_at': '2026-01-01T00:01:00.000+00:00', 'due_at': '2026-01-01T01:01:00.000+00:00'}} [EVT] {'sim_ts': 120.0, 'timestamp': '...', 'key': 'orders-2', 'task': 'order', 'instance': 1, 'value': {'placed_at': '2026-01-01T00:02:00.000+00:00', 'due_at': '2026-01-01T01:02:00.000+00:00'}} [EVT] {'sim_ts': 180.0, 'timestamp': '...', 'key': 'orders-3', 'task': 'order', 'instance': 2, 'value': {'placed_at': '2026-01-01T00:03:00.000+00:00', 'due_at': '2026-01-01T01:03:00.000+00:00'}} ``` ## JSON Schema The schema of `Now`, from `desflow schema`. ```json { "additionalProperties": false, "description": "`now`: the logical time plus `offset` (seconds or a duration, signed), as the\nISO text a record's `timestamp` uses. It reads the simulation clock, never the\nwall clock.", "properties": { "null_rate": { "anyOf": [ { "maximum": 1, "minimum": 0, "type": "number" }, { "type": "null" }, { "$ref": "#/$defs/NonNegativeNumberText" }, { "$ref": "#/$defs/Placeholder" } ], "default": null }, "unique": { "default": false, "description": "Gives each value once. A value built only from a task's vars, such as a format or an expr with no generator that draws, draws the vars again and makes the whole payload again until the value is new.", "anyOf": [ { "type": "boolean" }, { "$ref": "#/$defs/Placeholder" } ] }, "omit_rate": { "anyOf": [ { "maximum": 1, "minimum": 0, "type": "number" }, { "type": "null" }, { "$ref": "#/$defs/NonNegativeNumberText" }, { "$ref": "#/$defs/Placeholder" } ], "default": null }, "omit_when": { "anyOf": [ { "type": "string" }, { "type": "null" } ], "default": null }, "gen": { "anyOf": [ { "const": "now", "type": "string" }, { "$ref": "#/$defs/Placeholder" } ] }, "offset": { "$ref": "#/$defs/Value", "default": 0 } }, "required": [ "gen" ], "title": "Now", "type": "object" } ``` # format_time `format_time`: a time as text or a number. `time` is the text `{gen: now}` gives, or seconds of simulation time (default: now). `format` is a `strftime` pattern, `iso`, `iso_utc` (milliseconds and a `Z`), `epoch_s` or `epoch_ms` (integers). `tz` is an IANA name and defaults to the run's time zone. Use it for a time in the form another system expects, such as epoch milliseconds or a local time zone. ## Keys | Key | Type | Default | | -------- | ------------- | -------- | | `gen` | `format_time` | required | | `time` | Value | none | | `format` | text | `"iso"` | | `tz` | text | none | A `Value` is a constant or a generator, as [What a Generator Is](https://jaehyeon.me/desflow/latest/generators/#what-a-generator-is) explains. Every kind also accepts `null_rate`, `unique`, `omit_rate` and `omit_when`, which [Generators](https://jaehyeon.me/desflow/latest/generators/#keys-every-kind-accepts) describes. ## Example `day` is the time of the order as year, month, day, hour and minute. `epoch_s` is the same time as seconds since 1 January 1970. An order starts every 60 seconds for 200 seconds, with the seed 42, so three orders start. ```yaml # Format Time: the simulation time in a chosen format. # A task `order` starts every 60 seconds, and the run lasts 200 seconds, so three orders # start. # # Run it with: desflow run examples/generators/format_time.yaml simulation: sim_id: Gen factor: 0 random_seed: 42 logical_start_time: 2026-01-01T00:00:00 egress: - {type: Console} arrivals: orders: {dist: constant, value: 60, spawn: order} tasks: order: payload: day: {gen: format_time, format: "%Y-%m-%d %H:%M"} epoch_s: {gen: format_time, format: epoch_s} run: {until: 200} ``` It prints these records: ```text [EVT] {'sim_ts': 60.0, 'timestamp': '...', 'key': 'orders-1', 'task': 'order', 'instance': 0, 'value': {'day': '2026-01-01 00:01', 'epoch_s': 1767225660}} [EVT] {'sim_ts': 120.0, 'timestamp': '...', 'key': 'orders-2', 'task': 'order', 'instance': 1, 'value': {'day': '2026-01-01 00:02', 'epoch_s': 1767225720}} [EVT] {'sim_ts': 180.0, 'timestamp': '...', 'key': 'orders-3', 'task': 'order', 'instance': 2, 'value': {'day': '2026-01-01 00:03', 'epoch_s': 1767225780}} ``` ## JSON Schema The schema of `FormatTime`, from `desflow schema`. ```json { "additionalProperties": false, "description": "`format_time`: a time as text or a number. `time` is the text `{gen: now}`\ngives, or seconds of simulation time (default: now). `format` is a `strftime`\npattern, `iso`, `iso_utc` (milliseconds and a `Z`), `epoch_s` or `epoch_ms`\n(integers). `tz` is an IANA name and defaults to the run's time zone.", "properties": { "null_rate": { "anyOf": [ { "maximum": 1, "minimum": 0, "type": "number" }, { "type": "null" }, { "$ref": "#/$defs/NonNegativeNumberText" }, { "$ref": "#/$defs/Placeholder" } ], "default": null }, "unique": { "default": false, "description": "Gives each value once. A value built only from a task's vars, such as a format or an expr with no generator that draws, draws the vars again and makes the whole payload again until the value is new.", "anyOf": [ { "type": "boolean" }, { "$ref": "#/$defs/Placeholder" } ] }, "omit_rate": { "anyOf": [ { "maximum": 1, "minimum": 0, "type": "number" }, { "type": "null" }, { "$ref": "#/$defs/NonNegativeNumberText" }, { "$ref": "#/$defs/Placeholder" } ], "default": null }, "omit_when": { "anyOf": [ { "type": "string" }, { "type": "null" } ], "default": null }, "gen": { "anyOf": [ { "const": "format_time", "type": "string" }, { "$ref": "#/$defs/Placeholder" } ] }, "time": { "$ref": "#/$defs/Value", "default": null }, "format": { "default": "iso", "type": "string" }, "tz": { "anyOf": [ { "type": "string" }, { "type": "null" } ], "default": null } }, "required": [ "gen" ], "title": "FormatTime", "type": "object" } ``` # add `add`: the sum of `args`. When the first is a time (the text `{gen: now}` gives), the rest are seconds and the result is a time. Use it for a total, or a time that falls some seconds after another time. ## Keys | Key | Type | Default | | ---------- | ------------- | -------- | | `args` | list of Value | required | | `decimals` | integer | none | | `gen` | `add` | required | A `Value` is a constant or a generator, as [What a Generator Is](https://jaehyeon.me/desflow/latest/generators/#what-a-generator-is) explains. Every kind also accepts `null_rate`, `unique`, `omit_rate` and `omit_when`, which [Generators](https://jaehyeon.me/desflow/latest/generators/#keys-every-kind-accepts) describes. ## Example `total` is 10 plus a whole number from 1 to 5. An order starts every 60 seconds for 200 seconds, with the seed 42, so three orders start. ```yaml # Add: the sum of values. # A task `order` starts every 60 seconds, and the run lasts 200 seconds, so three orders # start. # # Run it with: desflow run examples/generators/add.yaml simulation: sim_id: Gen factor: 0 random_seed: 42 logical_start_time: 2026-01-01T00:00:00 egress: - {type: Console} arrivals: orders: {dist: constant, value: 60, spawn: order} tasks: order: payload: total: gen: add args: [10, {gen: integer, bounds: [1, 5]}] run: {until: 200} ``` It prints these records: ```text [EVT] {'sim_ts': 60.0, 'timestamp': '...', 'key': 'orders-1', 'task': 'order', 'instance': 0, 'value': {'total': 13}} [EVT] {'sim_ts': 120.0, 'timestamp': '...', 'key': 'orders-2', 'task': 'order', 'instance': 1, 'value': {'total': 11}} [EVT] {'sim_ts': 180.0, 'timestamp': '...', 'key': 'orders-3', 'task': 'order', 'instance': 2, 'value': {'total': 13}} ``` ## JSON Schema The schema of `Add`, from `desflow schema`. ```json { "additionalProperties": false, "description": "`add`: the sum of `args`. When the first is a time (the text `{gen: now}`\ngives), the rest are seconds and the result is a time.", "properties": { "null_rate": { "anyOf": [ { "maximum": 1, "minimum": 0, "type": "number" }, { "type": "null" }, { "$ref": "#/$defs/NonNegativeNumberText" }, { "$ref": "#/$defs/Placeholder" } ], "default": null }, "unique": { "default": false, "description": "Gives each value once. A value built only from a task's vars, such as a format or an expr with no generator that draws, draws the vars again and makes the whole payload again until the value is new.", "anyOf": [ { "type": "boolean" }, { "$ref": "#/$defs/Placeholder" } ] }, "omit_rate": { "anyOf": [ { "maximum": 1, "minimum": 0, "type": "number" }, { "type": "null" }, { "$ref": "#/$defs/NonNegativeNumberText" }, { "$ref": "#/$defs/Placeholder" } ], "default": null }, "omit_when": { "anyOf": [ { "type": "string" }, { "type": "null" } ], "default": null }, "args": { "items": { "$ref": "#/$defs/Value" }, "minItems": 2, "type": "array" }, "decimals": { "anyOf": [ { "minimum": 0, "type": "integer" }, { "type": "null" }, { "$ref": "#/$defs/NonNegativeIntegerText" }, { "$ref": "#/$defs/Placeholder" } ], "default": null }, "gen": { "anyOf": [ { "const": "add", "type": "string" }, { "$ref": "#/$defs/Placeholder" } ] } }, "required": [ "args", "gen" ], "title": "Add", "type": "object" } ``` # subtract `subtract`: the first of `args` less the others. When the first is a time, the rest are seconds and the result is a time. Use it for a difference, or a time that falls some seconds before another time. ## Keys | Key | Type | Default | | ---------- | ------------- | -------- | | `args` | list of Value | required | | `decimals` | integer | none | | `gen` | `subtract` | required | A `Value` is a constant or a generator, as [What a Generator Is](https://jaehyeon.me/desflow/latest/generators/#what-a-generator-is) explains. Every kind also accepts `null_rate`, `unique`, `omit_rate` and `omit_when`, which [Generators](https://jaehyeon.me/desflow/latest/generators/#keys-every-kind-accepts) describes. ## Example `left` is 100 less a whole number from 1 to 20. An order starts every 60 seconds for 200 seconds, with the seed 42, so three orders start. ```yaml # Subtract: the first value less the others. # A task `order` starts every 60 seconds, and the run lasts 200 seconds, so three orders # start. # # Run it with: desflow run examples/generators/subtract.yaml simulation: sim_id: Gen factor: 0 random_seed: 42 logical_start_time: 2026-01-01T00:00:00 egress: - {type: Console} arrivals: orders: {dist: constant, value: 60, spawn: order} tasks: order: payload: left: gen: subtract args: [100, {gen: integer, bounds: [1, 20]}] run: {until: 200} ``` It prints these records: ```text [EVT] {'sim_ts': 60.0, 'timestamp': '...', 'key': 'orders-1', 'task': 'order', 'instance': 0, 'value': {'left': 97}} [EVT] {'sim_ts': 120.0, 'timestamp': '...', 'key': 'orders-2', 'task': 'order', 'instance': 1, 'value': {'left': 89}} [EVT] {'sim_ts': 180.0, 'timestamp': '...', 'key': 'orders-3', 'task': 'order', 'instance': 2, 'value': {'left': 83}} ``` ## JSON Schema The schema of `Subtract`, from `desflow schema`. ```json { "additionalProperties": false, "description": "`subtract`: the first of `args` less the others. When the first is a time,\nthe rest are seconds and the result is a time.", "properties": { "null_rate": { "anyOf": [ { "maximum": 1, "minimum": 0, "type": "number" }, { "type": "null" }, { "$ref": "#/$defs/NonNegativeNumberText" }, { "$ref": "#/$defs/Placeholder" } ], "default": null }, "unique": { "default": false, "description": "Gives each value once. A value built only from a task's vars, such as a format or an expr with no generator that draws, draws the vars again and makes the whole payload again until the value is new.", "anyOf": [ { "type": "boolean" }, { "$ref": "#/$defs/Placeholder" } ] }, "omit_rate": { "anyOf": [ { "maximum": 1, "minimum": 0, "type": "number" }, { "type": "null" }, { "$ref": "#/$defs/NonNegativeNumberText" }, { "$ref": "#/$defs/Placeholder" } ], "default": null }, "omit_when": { "anyOf": [ { "type": "string" }, { "type": "null" } ], "default": null }, "args": { "items": { "$ref": "#/$defs/Value" }, "minItems": 2, "type": "array" }, "decimals": { "anyOf": [ { "minimum": 0, "type": "integer" }, { "type": "null" }, { "$ref": "#/$defs/NonNegativeIntegerText" }, { "$ref": "#/$defs/Placeholder" } ], "default": null }, "gen": { "anyOf": [ { "const": "subtract", "type": "string" }, { "$ref": "#/$defs/Placeholder" } ] } }, "required": [ "args", "gen" ], "title": "Subtract", "type": "object" } ``` # multiply `multiply`: the product of `args`. Use it for a cost, such as a quantity times a price. ## Keys | Key | Type | Default | | ---------- | ------------- | -------- | | `args` | list of Value | required | | `decimals` | integer | none | | `gen` | `multiply` | required | A `Value` is a constant or a generator, as [What a Generator Is](https://jaehyeon.me/desflow/latest/generators/#what-a-generator-is) explains. Every kind also accepts `null_rate`, `unique`, `omit_rate` and `omit_when`, which [Generators](https://jaehyeon.me/desflow/latest/generators/#keys-every-kind-accepts) describes. ## Example `area` is a whole number from 1 to 9 times 2.5, rounded to 1 decimal. An order starts every 60 seconds for 200 seconds, with the seed 42, so three orders start. ```yaml # Multiply: the product of values. # A task `order` starts every 60 seconds, and the run lasts 200 seconds, so three orders # start. # # Run it with: desflow run examples/generators/multiply.yaml simulation: sim_id: Gen factor: 0 random_seed: 42 logical_start_time: 2026-01-01T00:00:00 egress: - {type: Console} arrivals: orders: {dist: constant, value: 60, spawn: order} tasks: order: payload: area: gen: multiply args: [{gen: integer, bounds: [1, 9]}, 2.5] decimals: 1 run: {until: 200} ``` It prints these records: ```text [EVT] {'sim_ts': 60.0, 'timestamp': '...', 'key': 'orders-1', 'task': 'order', 'instance': 0, 'value': {'area': 10.0}} [EVT] {'sim_ts': 120.0, 'timestamp': '...', 'key': 'orders-2', 'task': 'order', 'instance': 1, 'value': {'area': 22.5}} [EVT] {'sim_ts': 180.0, 'timestamp': '...', 'key': 'orders-3', 'task': 'order', 'instance': 2, 'value': {'area': 2.5}} ``` ## JSON Schema The schema of `Multiply`, from `desflow schema`. ```json { "additionalProperties": false, "description": "`multiply`: the product of `args`.", "properties": { "null_rate": { "anyOf": [ { "maximum": 1, "minimum": 0, "type": "number" }, { "type": "null" }, { "$ref": "#/$defs/NonNegativeNumberText" }, { "$ref": "#/$defs/Placeholder" } ], "default": null }, "unique": { "default": false, "description": "Gives each value once. A value built only from a task's vars, such as a format or an expr with no generator that draws, draws the vars again and makes the whole payload again until the value is new.", "anyOf": [ { "type": "boolean" }, { "$ref": "#/$defs/Placeholder" } ] }, "omit_rate": { "anyOf": [ { "maximum": 1, "minimum": 0, "type": "number" }, { "type": "null" }, { "$ref": "#/$defs/NonNegativeNumberText" }, { "$ref": "#/$defs/Placeholder" } ], "default": null }, "omit_when": { "anyOf": [ { "type": "string" }, { "type": "null" } ], "default": null }, "args": { "items": { "$ref": "#/$defs/Value" }, "minItems": 2, "type": "array" }, "decimals": { "anyOf": [ { "minimum": 0, "type": "integer" }, { "type": "null" }, { "$ref": "#/$defs/NonNegativeIntegerText" }, { "$ref": "#/$defs/Placeholder" } ], "default": null }, "gen": { "anyOf": [ { "const": "multiply", "type": "string" }, { "$ref": "#/$defs/Placeholder" } ] } }, "required": [ "args", "gen" ], "title": "Multiply", "type": "object" } ``` # divide `divide`: the first of `args` divided by each of the others in turn (`/`). Use it for a ratio, such as a total divided by a count. ## Keys | Key | Type | Default | | ---------- | ------------- | -------- | | `args` | list of Value | required | | `decimals` | integer | none | | `gen` | `divide` | required | A `Value` is a constant or a generator, as [What a Generator Is](https://jaehyeon.me/desflow/latest/generators/#what-a-generator-is) explains. Every kind also accepts `null_rate`, `unique`, `omit_rate` and `omit_when`, which [Generators](https://jaehyeon.me/desflow/latest/generators/#keys-every-kind-accepts) describes. ## Example `share` is a whole number from 1 to 9 divided by 4, rounded to 2 decimals. An order starts every 60 seconds for 200 seconds, with the seed 42, so three orders start. ```yaml # Divide: the first value divided by the others. # A task `order` starts every 60 seconds, and the run lasts 200 seconds, so three orders # start. # # Run it with: desflow run examples/generators/divide.yaml simulation: sim_id: Gen factor: 0 random_seed: 42 logical_start_time: 2026-01-01T00:00:00 egress: - {type: Console} arrivals: orders: {dist: constant, value: 60, spawn: order} tasks: order: payload: share: gen: divide args: [{gen: integer, bounds: [1, 9]}, 4] decimals: 2 run: {until: 200} ``` It prints these records: ```text [EVT] {'sim_ts': 60.0, 'timestamp': '...', 'key': 'orders-1', 'task': 'order', 'instance': 0, 'value': {'share': 0.5}} [EVT] {'sim_ts': 120.0, 'timestamp': '...', 'key': 'orders-2', 'task': 'order', 'instance': 1, 'value': {'share': 1.0}} [EVT] {'sim_ts': 180.0, 'timestamp': '...', 'key': 'orders-3', 'task': 'order', 'instance': 2, 'value': {'share': 2.25}} ``` ## JSON Schema The schema of `Divide`, from `desflow schema`. ```json { "additionalProperties": false, "description": "`divide`: the first of `args` divided by each of the others in turn (`/`).", "properties": { "null_rate": { "anyOf": [ { "maximum": 1, "minimum": 0, "type": "number" }, { "type": "null" }, { "$ref": "#/$defs/NonNegativeNumberText" }, { "$ref": "#/$defs/Placeholder" } ], "default": null }, "unique": { "default": false, "description": "Gives each value once. A value built only from a task's vars, such as a format or an expr with no generator that draws, draws the vars again and makes the whole payload again until the value is new.", "anyOf": [ { "type": "boolean" }, { "$ref": "#/$defs/Placeholder" } ] }, "omit_rate": { "anyOf": [ { "maximum": 1, "minimum": 0, "type": "number" }, { "type": "null" }, { "$ref": "#/$defs/NonNegativeNumberText" }, { "$ref": "#/$defs/Placeholder" } ], "default": null }, "omit_when": { "anyOf": [ { "type": "string" }, { "type": "null" } ], "default": null }, "args": { "items": { "$ref": "#/$defs/Value" }, "minItems": 2, "type": "array" }, "decimals": { "anyOf": [ { "minimum": 0, "type": "integer" }, { "type": "null" }, { "$ref": "#/$defs/NonNegativeIntegerText" }, { "$ref": "#/$defs/Placeholder" } ], "default": null }, "gen": { "anyOf": [ { "const": "divide", "type": "string" }, { "$ref": "#/$defs/Placeholder" } ] } }, "required": [ "args", "gen" ], "title": "Divide", "type": "object" } ``` # min `min`: the smallest of `args`. Use it for a cap: the smaller of a drawn value and a limit. ## Keys | Key | Type | Default | | ---------- | ------------- | -------- | | `args` | list of Value | required | | `decimals` | integer | none | | `gen` | `min` | required | A `Value` is a constant or a generator, as [What a Generator Is](https://jaehyeon.me/desflow/latest/generators/#what-a-generator-is) explains. Every kind also accepts `null_rate`, `unique`, `omit_rate` and `omit_when`, which [Generators](https://jaehyeon.me/desflow/latest/generators/#keys-every-kind-accepts) describes. ## Example `lowest` is the smallest of two whole numbers from 1 to 9 and the number 5. An order starts every 60 seconds for 200 seconds, with the seed 42, so three orders start. ```yaml # Min: the smallest of values. # A task `order` starts every 60 seconds, and the run lasts 200 seconds, so three orders # start. # # Run it with: desflow run examples/generators/min.yaml simulation: sim_id: Gen factor: 0 random_seed: 42 logical_start_time: 2026-01-01T00:00:00 egress: - {type: Console} arrivals: orders: {dist: constant, value: 60, spawn: order} tasks: order: payload: lowest: gen: min args: [{gen: integer, bounds: [1, 9]}, {gen: integer, bounds: [1, 9]}, 5] run: {until: 200} ``` It prints these records: ```text [EVT] {'sim_ts': 60.0, 'timestamp': '...', 'key': 'orders-1', 'task': 'order', 'instance': 0, 'value': {'lowest': 5}} [EVT] {'sim_ts': 120.0, 'timestamp': '...', 'key': 'orders-2', 'task': 'order', 'instance': 1, 'value': {'lowest': 2}} [EVT] {'sim_ts': 180.0, 'timestamp': '...', 'key': 'orders-3', 'task': 'order', 'instance': 2, 'value': {'lowest': 5}} ``` ## JSON Schema The schema of `Min`, from `desflow schema`. ```json { "additionalProperties": false, "description": "`min`: the smallest of `args`.", "properties": { "null_rate": { "anyOf": [ { "maximum": 1, "minimum": 0, "type": "number" }, { "type": "null" }, { "$ref": "#/$defs/NonNegativeNumberText" }, { "$ref": "#/$defs/Placeholder" } ], "default": null }, "unique": { "default": false, "description": "Gives each value once. A value built only from a task's vars, such as a format or an expr with no generator that draws, draws the vars again and makes the whole payload again until the value is new.", "anyOf": [ { "type": "boolean" }, { "$ref": "#/$defs/Placeholder" } ] }, "omit_rate": { "anyOf": [ { "maximum": 1, "minimum": 0, "type": "number" }, { "type": "null" }, { "$ref": "#/$defs/NonNegativeNumberText" }, { "$ref": "#/$defs/Placeholder" } ], "default": null }, "omit_when": { "anyOf": [ { "type": "string" }, { "type": "null" } ], "default": null }, "args": { "items": { "$ref": "#/$defs/Value" }, "minItems": 2, "type": "array" }, "decimals": { "anyOf": [ { "minimum": 0, "type": "integer" }, { "type": "null" }, { "$ref": "#/$defs/NonNegativeIntegerText" }, { "$ref": "#/$defs/Placeholder" } ], "default": null }, "gen": { "anyOf": [ { "const": "min", "type": "string" }, { "$ref": "#/$defs/Placeholder" } ] } }, "required": [ "args", "gen" ], "title": "Min", "type": "object" } ``` # max `max`: the largest of `args`. Use it for a floor: the larger of a drawn value and a minimum. ## Keys | Key | Type | Default | | ---------- | ------------- | -------- | | `args` | list of Value | required | | `decimals` | integer | none | | `gen` | `max` | required | A `Value` is a constant or a generator, as [What a Generator Is](https://jaehyeon.me/desflow/latest/generators/#what-a-generator-is) explains. Every kind also accepts `null_rate`, `unique`, `omit_rate` and `omit_when`, which [Generators](https://jaehyeon.me/desflow/latest/generators/#keys-every-kind-accepts) describes. ## Example `highest` is the largest of two whole numbers from 1 to 9 and the number 5. An order starts every 60 seconds for 200 seconds, with the seed 42, so three orders start. ```yaml # Max: the largest of values. # A task `order` starts every 60 seconds, and the run lasts 200 seconds, so three orders # start. # # Run it with: desflow run examples/generators/max.yaml simulation: sim_id: Gen factor: 0 random_seed: 42 logical_start_time: 2026-01-01T00:00:00 egress: - {type: Console} arrivals: orders: {dist: constant, value: 60, spawn: order} tasks: order: payload: highest: gen: max args: [{gen: integer, bounds: [1, 9]}, {gen: integer, bounds: [1, 9]}, 5] run: {until: 200} ``` It prints these records: ```text [EVT] {'sim_ts': 60.0, 'timestamp': '...', 'key': 'orders-1', 'task': 'order', 'instance': 0, 'value': {'highest': 9}} [EVT] {'sim_ts': 120.0, 'timestamp': '...', 'key': 'orders-2', 'task': 'order', 'instance': 1, 'value': {'highest': 7}} [EVT] {'sim_ts': 180.0, 'timestamp': '...', 'key': 'orders-3', 'task': 'order', 'instance': 2, 'value': {'highest': 5}} ``` ## JSON Schema The schema of `Max`, from `desflow schema`. ```json { "additionalProperties": false, "description": "`max`: the largest of `args`.", "properties": { "null_rate": { "anyOf": [ { "maximum": 1, "minimum": 0, "type": "number" }, { "type": "null" }, { "$ref": "#/$defs/NonNegativeNumberText" }, { "$ref": "#/$defs/Placeholder" } ], "default": null }, "unique": { "default": false, "description": "Gives each value once. A value built only from a task's vars, such as a format or an expr with no generator that draws, draws the vars again and makes the whole payload again until the value is new.", "anyOf": [ { "type": "boolean" }, { "$ref": "#/$defs/Placeholder" } ] }, "omit_rate": { "anyOf": [ { "maximum": 1, "minimum": 0, "type": "number" }, { "type": "null" }, { "$ref": "#/$defs/NonNegativeNumberText" }, { "$ref": "#/$defs/Placeholder" } ], "default": null }, "omit_when": { "anyOf": [ { "type": "string" }, { "type": "null" } ], "default": null }, "args": { "items": { "$ref": "#/$defs/Value" }, "minItems": 2, "type": "array" }, "decimals": { "anyOf": [ { "minimum": 0, "type": "integer" }, { "type": "null" }, { "$ref": "#/$defs/NonNegativeIntegerText" }, { "$ref": "#/$defs/Placeholder" } ], "default": null }, "gen": { "anyOf": [ { "const": "max", "type": "string" }, { "$ref": "#/$defs/Placeholder" } ] } }, "required": [ "args", "gen" ], "title": "Max", "type": "object" } ``` # when `when`: `then` when the `condition` (an expression) holds, else `else`. Only the branch taken is evaluated. Use it for a value that changes with one condition, such as a discount for a large order. ## Keys | Key | Type | Default | | ----------- | ------ | -------- | | `gen` | `when` | required | | `condition` | text | required | | `then` | Value | required | | `else` | Value | none | A `Value` is a constant or a generator, as [What a Generator Is](https://jaehyeon.me/desflow/latest/generators/#what-a-generator-is) explains. Every kind also accepts `null_rate`, `unique`, `omit_rate` and `omit_when`, which [Generators](https://jaehyeon.me/desflow/latest/generators/#keys-every-kind-accepts) describes. ## Example `quantity` is a var, a whole number from 1 to 6. `size` is large when `quantity` is above 3, and small otherwise. An order starts every 60 seconds for 200 seconds, with the seed 42, so three orders start. ```yaml # When: one of two values, by a condition. # A task `order` starts every 60 seconds, and the run lasts 200 seconds, so three orders # start. # # Run it with: desflow run examples/generators/when.yaml simulation: sim_id: Gen factor: 0 random_seed: 42 logical_start_time: 2026-01-01T00:00:00 egress: - {type: Console} arrivals: orders: {dist: constant, value: 60, spawn: order} tasks: order: vars: quantity: {gen: integer, bounds: [1, 6]} payload: quantity: {gen: var, name: quantity} size: {gen: when, condition: "quantity > 3", then: large, else: small} run: {until: 200} ``` It prints these records: ```text [EVT] {'sim_ts': 60.0, 'timestamp': '...', 'key': 'orders-1', 'task': 'order', 'instance': 0, 'value': {'quantity': 4, 'size': 'large'}} [EVT] {'sim_ts': 120.0, 'timestamp': '...', 'key': 'orders-2', 'task': 'order', 'instance': 1, 'value': {'quantity': 4, 'size': 'large'}} [EVT] {'sim_ts': 180.0, 'timestamp': '...', 'key': 'orders-3', 'task': 'order', 'instance': 2, 'value': {'quantity': 4, 'size': 'large'}} ``` ## JSON Schema The schema of `When`, from `desflow schema`. ```json { "additionalProperties": false, "description": "`when`: `then` when the `condition` (an expression) holds, else `else`.\nOnly the branch taken is evaluated.", "properties": { "null_rate": { "anyOf": [ { "maximum": 1, "minimum": 0, "type": "number" }, { "type": "null" }, { "$ref": "#/$defs/NonNegativeNumberText" }, { "$ref": "#/$defs/Placeholder" } ], "default": null }, "unique": { "default": false, "description": "Gives each value once. A value built only from a task's vars, such as a format or an expr with no generator that draws, draws the vars again and makes the whole payload again until the value is new.", "anyOf": [ { "type": "boolean" }, { "$ref": "#/$defs/Placeholder" } ] }, "omit_rate": { "anyOf": [ { "maximum": 1, "minimum": 0, "type": "number" }, { "type": "null" }, { "$ref": "#/$defs/NonNegativeNumberText" }, { "$ref": "#/$defs/Placeholder" } ], "default": null }, "omit_when": { "anyOf": [ { "type": "string" }, { "type": "null" } ], "default": null }, "gen": { "anyOf": [ { "const": "when", "type": "string" }, { "$ref": "#/$defs/Placeholder" } ] }, "condition": { "type": "string" }, "then": { "$ref": "#/$defs/Value" }, "else": { "$ref": "#/$defs/Value", "default": null } }, "required": [ "gen", "condition", "then" ], "title": "When", "type": "object" } ``` # switch `switch`: the value of the first case that matches `on`, evaluated only when picked. `cases` is a mapping from a value to its result, or a list of ranges; `default` is used when none matches (null when it is left out). In a blueprint, a key written `yes`, `no`, `on` or `off` is that text, not a boolean. Use it for one value out of several, chosen by an exact match or by a range. ## Keys | Key | Type | Default | | --------- | ---------------------------------------------------------------- | -------- | | `gen` | `switch` | required | | `on` | Value | required | | `cases` | mapping of names to Value or list of [SwitchRange](#switchrange) | required | | `default` | Value | none | A `Value` is a constant or a generator, as [What a Generator Is](https://jaehyeon.me/desflow/latest/generators/#what-a-generator-is) explains. Every kind also accepts `null_rate`, `unique`, `omit_rate` and `omit_when`, which [Generators](https://jaehyeon.me/desflow/latest/generators/#keys-every-kind-accepts) describes. ### SwitchRange One range case of `switch`: the first case whose `min` is at or below `on` and whose `max`, when given, is above it. | Key | Type | Default | | ------- | ----------------- | -------- | | `min` | integer or number | none | | `max` | integer or number | none | | `value` | Value | required | ## Example `band` is small below 3, medium from 3 up to, but not including, 5, and large otherwise. An order starts every 60 seconds for 200 seconds, with the seed 42, so three orders start. ```yaml # Switch: the value of the first case that matches. # A task `order` starts every 60 seconds, and the run lasts 200 seconds, so three orders # start. # # Run it with: desflow run examples/generators/switch.yaml simulation: sim_id: Gen factor: 0 random_seed: 42 logical_start_time: 2026-01-01T00:00:00 egress: - {type: Console} arrivals: orders: {dist: constant, value: 60, spawn: order} tasks: order: vars: quantity: {gen: integer, bounds: [1, 6]} payload: quantity: {gen: var, name: quantity} band: gen: switch on: {gen: var, name: quantity} cases: - {max: 3, value: small} - {min: 3, max: 5, value: medium} default: large run: {until: 200} ``` It prints these records: ```text [EVT] {'sim_ts': 60.0, 'timestamp': '...', 'key': 'orders-1', 'task': 'order', 'instance': 0, 'value': {'quantity': 4, 'band': 'medium'}} [EVT] {'sim_ts': 120.0, 'timestamp': '...', 'key': 'orders-2', 'task': 'order', 'instance': 1, 'value': {'quantity': 4, 'band': 'medium'}} [EVT] {'sim_ts': 180.0, 'timestamp': '...', 'key': 'orders-3', 'task': 'order', 'instance': 2, 'value': {'quantity': 4, 'band': 'medium'}} ``` ## JSON Schema The schema of `Switch`, from `desflow schema`. ```json { "additionalProperties": false, "description": "`switch`: the value of the first case that matches `on`, evaluated only when\npicked. `cases` is a mapping from a value to its result, or a list of ranges;\n`default` is used when none matches (null when it is left out). In a blueprint,\na key written `yes`, `no`, `on` or `off` is that text, not a boolean.", "properties": { "null_rate": { "anyOf": [ { "maximum": 1, "minimum": 0, "type": "number" }, { "type": "null" }, { "$ref": "#/$defs/NonNegativeNumberText" }, { "$ref": "#/$defs/Placeholder" } ], "default": null }, "unique": { "default": false, "description": "Gives each value once. A value built only from a task's vars, such as a format or an expr with no generator that draws, draws the vars again and makes the whole payload again until the value is new.", "anyOf": [ { "type": "boolean" }, { "$ref": "#/$defs/Placeholder" } ] }, "omit_rate": { "anyOf": [ { "maximum": 1, "minimum": 0, "type": "number" }, { "type": "null" }, { "$ref": "#/$defs/NonNegativeNumberText" }, { "$ref": "#/$defs/Placeholder" } ], "default": null }, "omit_when": { "anyOf": [ { "type": "string" }, { "type": "null" } ], "default": null }, "gen": { "anyOf": [ { "const": "switch", "type": "string" }, { "$ref": "#/$defs/Placeholder" } ] }, "on": { "$ref": "#/$defs/Value" }, "cases": { "anyOf": [ { "additionalProperties": { "$ref": "#/$defs/Value" }, "type": "object" }, { "items": { "$ref": "#/$defs/SwitchRange" }, "type": "array" } ] }, "default": { "$ref": "#/$defs/Value", "default": null } }, "required": [ "gen", "on", "cases" ], "title": "Switch", "type": "object" } ``` # expr `expr`: the value of an expression, with the names of the language, the vars of the task and the entries of `names` (evaluated first) as bare names, `t` for the simulation time, and `pi` and `e` where no var or name hides them. It can give any type; a number is rounded to `decimals`. Use it for a value computed from vars and numbers by an expression. ## Keys | Key | Type | Default | | ---------- | ------------------------- | -------- | | `gen` | `expr` | required | | `expr` | text | required | | `names` | mapping of names to Value | | | `decimals` | integer | none | A `Value` is a constant or a generator, as [What a Generator Is](https://jaehyeon.me/desflow/latest/generators/#what-a-generator-is) explains. Every kind also accepts `null_rate`, `unique`, `omit_rate` and `omit_when`, which [Generators](https://jaehyeon.me/desflow/latest/generators/#keys-every-kind-accepts) describes. ## Example `total` is the var `quantity` times a `price` of 2.5, rounded to 2 decimals. An order starts every 60 seconds for 200 seconds, with the seed 42, so three orders start. ```yaml # Expr: the value of an expression over the task's vars. # A task `order` starts every 60 seconds, and the run lasts 200 seconds, so three orders # start. # # Run it with: desflow run examples/generators/expr.yaml simulation: sim_id: Gen factor: 0 random_seed: 42 logical_start_time: 2026-01-01T00:00:00 egress: - {type: Console} arrivals: orders: {dist: constant, value: 60, spawn: order} tasks: order: vars: quantity: {gen: integer, bounds: [1, 6]} payload: quantity: {gen: var, name: quantity} total: gen: expr expr: "quantity * price" names: {price: 2.5} decimals: 2 run: {until: 200} ``` It prints these records: ```text [EVT] {'sim_ts': 60.0, 'timestamp': '...', 'key': 'orders-1', 'task': 'order', 'instance': 0, 'value': {'quantity': 4, 'total': 10.0}} [EVT] {'sim_ts': 120.0, 'timestamp': '...', 'key': 'orders-2', 'task': 'order', 'instance': 1, 'value': {'quantity': 4, 'total': 10.0}} [EVT] {'sim_ts': 180.0, 'timestamp': '...', 'key': 'orders-3', 'task': 'order', 'instance': 2, 'value': {'quantity': 4, 'total': 10.0}} ``` ## JSON Schema The schema of `Expr`, from `desflow schema`. ```json { "additionalProperties": false, "description": "`expr`: the value of an expression, with the names of the language, the vars of\nthe task and the entries of `names` (evaluated first) as bare names, `t` for the\nsimulation time, and `pi` and `e` where no var or name hides them. It can give any\ntype; a number is rounded to `decimals`.", "properties": { "null_rate": { "anyOf": [ { "maximum": 1, "minimum": 0, "type": "number" }, { "type": "null" }, { "$ref": "#/$defs/NonNegativeNumberText" }, { "$ref": "#/$defs/Placeholder" } ], "default": null }, "unique": { "default": false, "description": "Gives each value once. A value built only from a task's vars, such as a format or an expr with no generator that draws, draws the vars again and makes the whole payload again until the value is new.", "anyOf": [ { "type": "boolean" }, { "$ref": "#/$defs/Placeholder" } ] }, "omit_rate": { "anyOf": [ { "maximum": 1, "minimum": 0, "type": "number" }, { "type": "null" }, { "$ref": "#/$defs/NonNegativeNumberText" }, { "$ref": "#/$defs/Placeholder" } ], "default": null }, "omit_when": { "anyOf": [ { "type": "string" }, { "type": "null" } ], "default": null }, "gen": { "anyOf": [ { "const": "expr", "type": "string" }, { "$ref": "#/$defs/Placeholder" } ] }, "expr": { "type": "string" }, "names": { "additionalProperties": { "$ref": "#/$defs/Value" }, "type": "object" }, "decimals": { "anyOf": [ { "minimum": 0, "type": "integer" }, { "type": "null" }, { "$ref": "#/$defs/NonNegativeIntegerText" }, { "$ref": "#/$defs/Placeholder" } ], "default": null } }, "required": [ "gen", "expr" ], "title": "Expr", "type": "object" } ``` # literal `literal`: `value` as written, not evaluated, so a mapping that has a `gen` key can be a payload field. Use it for a value that must be kept as written, even when it looks like a generator. ## Keys | Key | Type | Default | | ------- | --------- | -------- | | `gen` | `literal` | required | | `value` | None | none | Every kind also accepts `null_rate`, `unique`, `omit_rate` and `omit_when`, which [Generators](https://jaehyeon.me/desflow/latest/generators/#keys-every-kind-accepts) describes. ## Example `template` is the mapping `{gen: not_evaluated}`, published as it is. An order starts every 60 seconds for 200 seconds, with the seed 42, so three orders start. ```yaml # Literal: a value kept as written, not evaluated. # A task `order` starts every 60 seconds, and the run lasts 200 seconds, so three orders # start. # # Run it with: desflow run examples/generators/literal.yaml simulation: sim_id: Gen factor: 0 random_seed: 42 logical_start_time: 2026-01-01T00:00:00 egress: - {type: Console} arrivals: orders: {dist: constant, value: 60, spawn: order} tasks: order: payload: template: gen: literal value: {gen: not_evaluated} run: {until: 200} ``` It prints these records: ```text [EVT] {'sim_ts': 60.0, 'timestamp': '...', 'key': 'orders-1', 'task': 'order', 'instance': 0, 'value': {'template': {'gen': 'not_evaluated'}}} [EVT] {'sim_ts': 120.0, 'timestamp': '...', 'key': 'orders-2', 'task': 'order', 'instance': 1, 'value': {'template': {'gen': 'not_evaluated'}}} [EVT] {'sim_ts': 180.0, 'timestamp': '...', 'key': 'orders-3', 'task': 'order', 'instance': 2, 'value': {'template': {'gen': 'not_evaluated'}}} ``` ## JSON Schema The schema of `Literal_`, from `desflow schema`. ```json { "additionalProperties": false, "description": "`literal`: `value` as written, not evaluated, so a mapping that has a `gen`\nkey can be a payload field.", "properties": { "null_rate": { "anyOf": [ { "maximum": 1, "minimum": 0, "type": "number" }, { "type": "null" }, { "$ref": "#/$defs/NonNegativeNumberText" }, { "$ref": "#/$defs/Placeholder" } ], "default": null }, "unique": { "default": false, "description": "Gives each value once. A value built only from a task's vars, such as a format or an expr with no generator that draws, draws the vars again and makes the whole payload again until the value is new.", "anyOf": [ { "type": "boolean" }, { "$ref": "#/$defs/Placeholder" } ] }, "omit_rate": { "anyOf": [ { "maximum": 1, "minimum": 0, "type": "number" }, { "type": "null" }, { "$ref": "#/$defs/NonNegativeNumberText" }, { "$ref": "#/$defs/Placeholder" } ], "default": null }, "omit_when": { "anyOf": [ { "type": "string" }, { "type": "null" } ], "default": null }, "gen": { "anyOf": [ { "const": "literal", "type": "string" }, { "$ref": "#/$defs/Placeholder" } ] }, "value": { "default": null } }, "required": [ "gen" ], "title": "Literal_", "type": "object" } ``` # object `object`: the mapping `fields`, each evaluated as a plain mapping is. It lets a modifier such as `null_rate` or `omit_rate` apply to the whole mapping. Use it for a nested record that is sometimes null or left out as a whole. ## Keys | Key | Type | Default | | -------- | ------------------------- | -------- | | `gen` | `object` | required | | `fields` | mapping of names to Value | required | A `Value` is a constant or a generator, as [What a Generator Is](https://jaehyeon.me/desflow/latest/generators/#what-a-generator-is) explains. Every kind also accepts `null_rate`, `unique`, `omit_rate` and `omit_when`, which [Generators](https://jaehyeon.me/desflow/latest/generators/#keys-every-kind-accepts) describes. ## Example `address` is a mapping of a city and a postcode. With `null_rate: 0.5`, about half of the orders have no address (`null`). An order starts every 60 seconds for 200 seconds, with the seed 42, so three orders start. ```yaml # Object: a mapping that a modifier can apply to as a whole. # A task `order` starts every 60 seconds, and the run lasts 200 seconds, so three orders # start. # # Run it with: desflow run examples/generators/object.yaml simulation: sim_id: Gen factor: 0 random_seed: 42 logical_start_time: 2026-01-01T00:00:00 egress: - {type: Console} arrivals: orders: {dist: constant, value: 60, spawn: order} tasks: order: payload: address: gen: object null_rate: 0.4 fields: city: {gen: one_of, choices: [Perth, Hobart]} postcode: {gen: integer, bounds: [1000, 9999]} run: {until: 200} ``` It prints these records: ```text [EVT] {'sim_ts': 60.0, 'timestamp': '...', 'key': 'orders-1', 'task': 'order', 'instance': 0, 'value': {'address': None}} [EVT] {'sim_ts': 120.0, 'timestamp': '...', 'key': 'orders-2', 'task': 'order', 'instance': 1, 'value': {'address': {'city': 'Perth', 'postcode': 6403}}} [EVT] {'sim_ts': 180.0, 'timestamp': '...', 'key': 'orders-3', 'task': 'order', 'instance': 2, 'value': {'address': None}} ``` ## JSON Schema The schema of `Object`, from `desflow schema`. ```json { "additionalProperties": false, "description": "`object`: the mapping `fields`, each evaluated as a plain mapping is. It lets\na modifier such as `null_rate` or `omit_rate` apply to the whole mapping.", "properties": { "null_rate": { "anyOf": [ { "maximum": 1, "minimum": 0, "type": "number" }, { "type": "null" }, { "$ref": "#/$defs/NonNegativeNumberText" }, { "$ref": "#/$defs/Placeholder" } ], "default": null }, "unique": { "default": false, "description": "Gives each value once. A value built only from a task's vars, such as a format or an expr with no generator that draws, draws the vars again and makes the whole payload again until the value is new.", "anyOf": [ { "type": "boolean" }, { "$ref": "#/$defs/Placeholder" } ] }, "omit_rate": { "anyOf": [ { "maximum": 1, "minimum": 0, "type": "number" }, { "type": "null" }, { "$ref": "#/$defs/NonNegativeNumberText" }, { "$ref": "#/$defs/Placeholder" } ], "default": null }, "omit_when": { "anyOf": [ { "type": "string" }, { "type": "null" } ], "default": null }, "gen": { "anyOf": [ { "const": "object", "type": "string" }, { "$ref": "#/$defs/Placeholder" } ] }, "fields": { "additionalProperties": { "$ref": "#/$defs/Value" }, "type": "object" } }, "required": [ "gen", "fields" ], "title": "Object", "type": "object" } ``` # repeat `repeat`: a list of `times` values, each evaluated on its own. Use it for the items of an order: a list in which each item is drawn on its own. ## Keys | Key | Type | Default | | ------- | -------- | -------- | | `gen` | `repeat` | required | | `times` | Value | required | | `value` | Value | required | A `Value` is a constant or a generator, as [What a Generator Is](https://jaehyeon.me/desflow/latest/generators/#what-a-generator-is) explains. Every kind also accepts `null_rate`, `unique`, `omit_rate` and `omit_when`, which [Generators](https://jaehyeon.me/desflow/latest/generators/#keys-every-kind-accepts) describes. ## Example `scores` is a list of 3 whole numbers from 1 to 5. An order starts every 60 seconds for 200 seconds, with the seed 42, so three orders start. ```yaml # Repeat: a list of values, each drawn on its own. # A task `order` starts every 60 seconds, and the run lasts 200 seconds, so three orders # start. # # Run it with: desflow run examples/generators/repeat.yaml simulation: sim_id: Gen factor: 0 random_seed: 42 logical_start_time: 2026-01-01T00:00:00 egress: - {type: Console} arrivals: orders: {dist: constant, value: 60, spawn: order} tasks: order: payload: scores: gen: repeat times: 3 value: {gen: integer, bounds: [1, 5]} run: {until: 200} ``` It prints these records: ```text [EVT] {'sim_ts': 60.0, 'timestamp': '...', 'key': 'orders-1', 'task': 'order', 'instance': 0, 'value': {'scores': [3, 2, 1]}} [EVT] {'sim_ts': 120.0, 'timestamp': '...', 'key': 'orders-2', 'task': 'order', 'instance': 1, 'value': {'scores': [1, 5, 5]}} [EVT] {'sim_ts': 180.0, 'timestamp': '...', 'key': 'orders-3', 'task': 'order', 'instance': 2, 'value': {'scores': [1, 1, 4]}} ``` ## JSON Schema The schema of `Repeat`, from `desflow schema`. ```json { "additionalProperties": false, "description": "`repeat`: a list of `times` values, each evaluated on its own.", "properties": { "null_rate": { "anyOf": [ { "maximum": 1, "minimum": 0, "type": "number" }, { "type": "null" }, { "$ref": "#/$defs/NonNegativeNumberText" }, { "$ref": "#/$defs/Placeholder" } ], "default": null }, "unique": { "default": false, "description": "Gives each value once. A value built only from a task's vars, such as a format or an expr with no generator that draws, draws the vars again and makes the whole payload again until the value is new.", "anyOf": [ { "type": "boolean" }, { "$ref": "#/$defs/Placeholder" } ] }, "omit_rate": { "anyOf": [ { "maximum": 1, "minimum": 0, "type": "number" }, { "type": "null" }, { "$ref": "#/$defs/NonNegativeNumberText" }, { "$ref": "#/$defs/Placeholder" } ], "default": null }, "omit_when": { "anyOf": [ { "type": "string" }, { "type": "null" } ], "default": null }, "gen": { "anyOf": [ { "const": "repeat", "type": "string" }, { "$ref": "#/$defs/Placeholder" } ] }, "times": { "$ref": "#/$defs/Value" }, "value": { "$ref": "#/$defs/Value" } }, "required": [ "gen", "times", "value" ], "title": "Repeat", "type": "object" } ``` # attr `attr`: the entity's attribute `name`, or the part of it at `path`. Use it for a value the entity has carried since it started, such as a size the arrival gave it. ## Keys | Key | Type | Default | | ------ | ------ | -------- | | `gen` | `attr` | required | | `name` | text | required | | `path` | text | none | Every kind also accepts `null_rate`, `unique`, `omit_rate` and `omit_when`, which [Generators](https://jaehyeon.me/desflow/latest/generators/#keys-every-kind-accepts) describes. ## Example Each order starts with a `size` attribute from its arrival, and the payload publishes it. An order starts every 60 seconds for 200 seconds, with the seed 42, so three orders start. ```yaml # Attr: an attribute of the entity. # An entity `orders-N` starts every 60 seconds with a `size`, and the run lasts 200 # seconds, so three orders start. # # Run it with: desflow run examples/generators/attr.yaml simulation: sim_id: Gen factor: 0 random_seed: 42 logical_start_time: 2026-01-01T00:00:00 egress: - {type: Console} arrivals: orders: dist: constant value: 60 spawn: order attributes: size: {gen: integer, bounds: [1, 50]} tasks: order: payload: size: {gen: attr, name: size} run: {until: 200} ``` It prints these records: ```text [EVT] {'sim_ts': 60.0, 'timestamp': '...', 'key': 'orders-1', 'task': 'order', 'instance': 0, 'value': {'size': 7}} [EVT] {'sim_ts': 120.0, 'timestamp': '...', 'key': 'orders-2', 'task': 'order', 'instance': 1, 'value': {'size': 21}} [EVT] {'sim_ts': 180.0, 'timestamp': '...', 'key': 'orders-3', 'task': 'order', 'instance': 2, 'value': {'size': 29}} ``` ## JSON Schema The schema of `Attr`, from `desflow schema`. ```json { "additionalProperties": false, "description": "`attr`: the entity's attribute `name`, or the part of it at `path`.", "properties": { "null_rate": { "anyOf": [ { "maximum": 1, "minimum": 0, "type": "number" }, { "type": "null" }, { "$ref": "#/$defs/NonNegativeNumberText" }, { "$ref": "#/$defs/Placeholder" } ], "default": null }, "unique": { "default": false, "description": "Gives each value once. A value built only from a task's vars, such as a format or an expr with no generator that draws, draws the vars again and makes the whole payload again until the value is new.", "anyOf": [ { "type": "boolean" }, { "$ref": "#/$defs/Placeholder" } ] }, "omit_rate": { "anyOf": [ { "maximum": 1, "minimum": 0, "type": "number" }, { "type": "null" }, { "$ref": "#/$defs/NonNegativeNumberText" }, { "$ref": "#/$defs/Placeholder" } ], "default": null }, "omit_when": { "anyOf": [ { "type": "string" }, { "type": "null" } ], "default": null }, "gen": { "anyOf": [ { "const": "attr", "type": "string" }, { "$ref": "#/$defs/Placeholder" } ] }, "name": { "type": "string" }, "path": { "anyOf": [ { "type": "string" }, { "type": "null" } ], "default": null } }, "required": [ "gen", "name" ], "title": "Attr", "type": "object" } ``` # var `var`: a var of the task, or the part of it at `path` (dotted; an integer part indexes a list). Every reference to a var in one event gives the same value. Use it for a value drawn once for the task and used in several places. ## Keys | Key | Type | Default | | ------ | ----- | -------- | | `gen` | `var` | required | | `name` | text | required | | `path` | text | none | Every kind also accepts `null_rate`, `unique`, `omit_rate` and `omit_when`, which [Generators](https://jaehyeon.me/desflow/latest/generators/#keys-every-kind-accepts) describes. ## Example `quantity` is drawn once for each order, so `first` and `second` are equal. An order starts every 60 seconds for 200 seconds, with the seed 42, so three orders start. ```yaml # Var: a var of the task, the same everywhere in one event. # A task `order` starts every 60 seconds, and the run lasts 200 seconds, so three orders # start. # # Run it with: desflow run examples/generators/var.yaml simulation: sim_id: Gen factor: 0 random_seed: 42 logical_start_time: 2026-01-01T00:00:00 egress: - {type: Console} arrivals: orders: {dist: constant, value: 60, spawn: order} tasks: order: vars: quantity: {gen: integer, bounds: [1, 6]} payload: first: {gen: var, name: quantity} second: {gen: var, name: quantity} run: {until: 200} ``` It prints these records: ```text [EVT] {'sim_ts': 60.0, 'timestamp': '...', 'key': 'orders-1', 'task': 'order', 'instance': 0, 'value': {'first': 4, 'second': 4}} [EVT] {'sim_ts': 120.0, 'timestamp': '...', 'key': 'orders-2', 'task': 'order', 'instance': 1, 'value': {'first': 4, 'second': 4}} [EVT] {'sim_ts': 180.0, 'timestamp': '...', 'key': 'orders-3', 'task': 'order', 'instance': 2, 'value': {'first': 4, 'second': 4}} ``` ## JSON Schema The schema of `Var`, from `desflow schema`. ```json { "additionalProperties": false, "description": "`var`: a var of the task, or the part of it at `path` (dotted; an integer part\nindexes a list). Every reference to a var in one event gives the same value.", "properties": { "null_rate": { "anyOf": [ { "maximum": 1, "minimum": 0, "type": "number" }, { "type": "null" }, { "$ref": "#/$defs/NonNegativeNumberText" }, { "$ref": "#/$defs/Placeholder" } ], "default": null }, "unique": { "default": false, "description": "Gives each value once. A value built only from a task's vars, such as a format or an expr with no generator that draws, draws the vars again and makes the whole payload again until the value is new.", "anyOf": [ { "type": "boolean" }, { "$ref": "#/$defs/Placeholder" } ] }, "omit_rate": { "anyOf": [ { "maximum": 1, "minimum": 0, "type": "number" }, { "type": "null" }, { "$ref": "#/$defs/NonNegativeNumberText" }, { "$ref": "#/$defs/Placeholder" } ], "default": null }, "omit_when": { "anyOf": [ { "type": "string" }, { "type": "null" } ], "default": null }, "gen": { "anyOf": [ { "const": "var", "type": "string" }, { "$ref": "#/$defs/Placeholder" } ] }, "name": { "type": "string" }, "path": { "anyOf": [ { "type": "string" }, { "type": "null" } ], "default": null } }, "required": [ "gen", "name" ], "title": "Var", "type": "object" } ``` # param `param`: the live registry value at `path` (a full registry path, such as `Shop.variables.error_rate`) at the moment of the call, or the `field` key of a mapping value. A scenario step or an ingress update shows in the next call. Use it for a live setting of the simulation, which a scenario step or an ingress update can change. ## Keys | Key | Type | Default | | ------- | ------- | -------- | | `gen` | `param` | required | | `path` | text | required | | `field` | Value | none | A `Value` is a constant or a generator, as [What a Generator Is](https://jaehyeon.me/desflow/latest/generators/#what-a-generator-is) explains. Every kind also accepts `null_rate`, `unique`, `omit_rate` and `omit_when`, which [Generators](https://jaehyeon.me/desflow/latest/generators/#keys-every-kind-accepts) describes. ## Example `tax_rate` is the variable `tax_rate` of the simulation `Gen`, read when each order is published. An order starts every 60 seconds for 200 seconds, with the seed 42, so three orders start. ```yaml # Param: the live value of a variable. # An order starts every 60 seconds, and the run lasts 200 seconds, so three orders # start. # # Run it with: desflow run examples/generators/param.yaml simulation: sim_id: Gen factor: 0 random_seed: 42 logical_start_time: 2026-01-01T00:00:00 egress: - {type: Console} variables: {tax_rate: 0.2} arrivals: orders: {dist: constant, value: 60, spawn: order} tasks: order: payload: tax_rate: {gen: param, path: Gen.variables.tax_rate} run: {until: 200} ``` It prints these records: ```text [EVT] {'sim_ts': 60.0, 'timestamp': '...', 'key': 'orders-1', 'task': 'order', 'instance': 0, 'value': {'tax_rate': 0.2}} [EVT] {'sim_ts': 120.0, 'timestamp': '...', 'key': 'orders-2', 'task': 'order', 'instance': 1, 'value': {'tax_rate': 0.2}} [EVT] {'sim_ts': 180.0, 'timestamp': '...', 'key': 'orders-3', 'task': 'order', 'instance': 2, 'value': {'tax_rate': 0.2}} ``` ## JSON Schema The schema of `Param`, from `desflow schema`. ```json { "additionalProperties": false, "description": "`param`: the live registry value at `path` (a full registry path, such as\n`Shop.variables.error_rate`) at the moment of the call, or the `field` key of a\nmapping value. A scenario step or an ingress update shows in the next call.", "properties": { "null_rate": { "anyOf": [ { "maximum": 1, "minimum": 0, "type": "number" }, { "type": "null" }, { "$ref": "#/$defs/NonNegativeNumberText" }, { "$ref": "#/$defs/Placeholder" } ], "default": null }, "unique": { "default": false, "description": "Gives each value once. A value built only from a task's vars, such as a format or an expr with no generator that draws, draws the vars again and makes the whole payload again until the value is new.", "anyOf": [ { "type": "boolean" }, { "$ref": "#/$defs/Placeholder" } ] }, "omit_rate": { "anyOf": [ { "maximum": 1, "minimum": 0, "type": "number" }, { "type": "null" }, { "$ref": "#/$defs/NonNegativeNumberText" }, { "$ref": "#/$defs/Placeholder" } ], "default": null }, "omit_when": { "anyOf": [ { "type": "string" }, { "type": "null" } ], "default": null }, "gen": { "anyOf": [ { "const": "param", "type": "string" }, { "$ref": "#/$defs/Placeholder" } ] }, "path": { "type": "string" }, "field": { "$ref": "#/$defs/Value", "default": null } }, "required": [ "gen", "path" ], "title": "Param", "type": "object" } ``` # entity `entity`: the key of the entity the task runs for, such as `sensor-1`. It is given only inside a task, so an arrival's `attributes`, `vars` and `key` refuse it. Use it for a payload field that names the entity the record belongs to. ## Keys | Key | Type | Default | | ----- | -------- | -------- | | `gen` | `entity` | required | Every kind also accepts `null_rate`, `unique`, `omit_rate` and `omit_when`, which [Generators](https://jaehyeon.me/desflow/latest/generators/#keys-every-kind-accepts) describes. ## Example `order_key` is the key of the order, such as `orders-1`. An order starts every 60 seconds for 200 seconds, with the seed 42, so three orders start. ```yaml # Entity: the key of the entity. # An entity `orders-N` starts every 60 seconds, and the run lasts 200 seconds, so three # orders start. # # Run it with: desflow run examples/generators/entity.yaml simulation: sim_id: Gen factor: 0 random_seed: 42 logical_start_time: 2026-01-01T00:00:00 egress: - {type: Console} arrivals: orders: {dist: constant, value: 60, spawn: order} tasks: order: payload: order_key: {gen: entity} run: {until: 200} ``` It prints these records: ```text [EVT] {'sim_ts': 60.0, 'timestamp': '...', 'key': 'orders-1', 'task': 'order', 'instance': 0, 'value': {'order_key': 'orders-1'}} [EVT] {'sim_ts': 120.0, 'timestamp': '...', 'key': 'orders-2', 'task': 'order', 'instance': 1, 'value': {'order_key': 'orders-2'}} [EVT] {'sim_ts': 180.0, 'timestamp': '...', 'key': 'orders-3', 'task': 'order', 'instance': 2, 'value': {'order_key': 'orders-3'}} ``` ## JSON Schema The schema of `Entity`, from `desflow schema`. ```json { "additionalProperties": false, "description": "`entity`: the key of the entity the task runs for, such as `sensor-1`. It is\ngiven only inside a task, so an arrival's `attributes`, `vars` and `key` refuse it.", "properties": { "null_rate": { "anyOf": [ { "maximum": 1, "minimum": 0, "type": "number" }, { "type": "null" }, { "$ref": "#/$defs/NonNegativeNumberText" }, { "$ref": "#/$defs/Placeholder" } ], "default": null }, "unique": { "default": false, "description": "Gives each value once. A value built only from a task's vars, such as a format or an expr with no generator that draws, draws the vars again and makes the whole payload again until the value is new.", "anyOf": [ { "type": "boolean" }, { "$ref": "#/$defs/Placeholder" } ] }, "omit_rate": { "anyOf": [ { "maximum": 1, "minimum": 0, "type": "number" }, { "type": "null" }, { "$ref": "#/$defs/NonNegativeNumberText" }, { "$ref": "#/$defs/Placeholder" } ], "default": null }, "omit_when": { "anyOf": [ { "type": "string" }, { "type": "null" } ], "default": null }, "gen": { "anyOf": [ { "const": "entity", "type": "string" }, { "$ref": "#/$defs/Placeholder" } ] } }, "required": [ "gen" ], "title": "Entity", "type": "object" } ``` # lookup `lookup`: a row of the finished payloads of the task `task`, or the part of it at `path` (dotted; an integer part indexes a list). A row is readable from the instant the task's finished record is published. The task keeps its last `history` rows (default 1,000,000). `strategy` is `random` (the default), `first` (the oldest row kept) or `last` (the newest). `histogram` splits the rows kept, in the order they were written, into bins of the stated shares; a draw picks a bin by its frequency and then a row of the bin at random, so it is for `random` only. A bin that holds no row yet is left out of the draw, and while no bin with a frequency above 0 holds a row (a few rows and a last bin of frequency 0), the draw is over all the rows. `latest_by` keeps only the newest row for each value of that field of the row, so a lookup sees a customer's latest address; `strategy` and `histogram` then choose among those rows, oldest first by the time each was written. `distinct` draws without replacement within one `repeat`, so the items of one order differ. Use it for a value from a record that another task already published, such as an existing customer. ## Keys | Key | Type | Default | | ----------- | ------------------------------------- | ---------- | | `gen` | `lookup` | required | | `task` | text | required | | `path` | text | none | | `strategy` | `random` or `first` or `last` | `"random"` | | `histogram` | list of [HistogramBin](#histogrambin) | none | | `latest_by` | text | none | | `distinct` | boolean | `false` | Every kind also accepts `null_rate`, `unique`, `omit_rate` and `omit_when`, which [Generators](https://jaehyeon.me/desflow/latest/generators/#keys-every-kind-accepts) describes. ### HistogramBin One bin of a `lookup` histogram: `bin` is the share of the rows it covers, in the order they were written, and `frequency` is the chance that a draw falls in it. Both are scaled to add up to 1, so `{bin: 2, frequency: 8}, {bin: 8, frequency: 2}` means the same as 0.2 with 0.8, and 0.8 with 0.2. | Key | Type | Default | | ----------- | ------ | -------- | | `bin` | number | required | | `frequency` | number | required | ## Example Three customers start at time 0. Each order picks one of them at random and publishes its `customer_id`. An order starts every 60 seconds for 200 seconds, with the seed 42, so three orders start. ```yaml # Lookup: a value from a finished record of another task. # Three customers start at time 0, and an order starts every 60 seconds. The run lasts # 200 seconds, so three orders start. # # Run it with: desflow run examples/generators/lookup.yaml simulation: sim_id: Gen factor: 0 random_seed: 42 logical_start_time: 2026-01-01T00:00:00 egress: - {type: Console} arrivals: customers: {initial: 3, dist: constant, value: 3600, spawn: customer} orders: {dist: constant, value: 60, spawn: order} tasks: customer: payload: customer_id: {gen: sequence, start: 100} order: payload: customer_id: {gen: lookup, task: customer, path: customer_id} run: {until: 200} ``` It prints these records: ```text [EVT] {'sim_ts': 0.0, 'timestamp': '...', 'key': 'customers-1', 'task': 'customer', 'instance': 0, 'value': {'customer_id': 100}} [EVT] {'sim_ts': 0.0, 'timestamp': '...', 'key': 'customers-2', 'task': 'customer', 'instance': 1, 'value': {'customer_id': 101}} [EVT] {'sim_ts': 0.0, 'timestamp': '...', 'key': 'customers-3', 'task': 'customer', 'instance': 2, 'value': {'customer_id': 102}} [EVT] {'sim_ts': 60.0, 'timestamp': '...', 'key': 'orders-1', 'task': 'order', 'instance': 0, 'value': {'customer_id': 102}} [EVT] {'sim_ts': 120.0, 'timestamp': '...', 'key': 'orders-2', 'task': 'order', 'instance': 1, 'value': {'customer_id': 102}} [EVT] {'sim_ts': 180.0, 'timestamp': '...', 'key': 'orders-3', 'task': 'order', 'instance': 2, 'value': {'customer_id': 100}} ``` ## JSON Schema The schema of `Lookup`, from `desflow schema`. ```json { "additionalProperties": false, "description": "`lookup`: a row of the finished payloads of the task `task`, or the part of it\nat `path` (dotted; an integer part indexes a list).\n\nA row is readable from the instant the task's finished record is published. The\ntask keeps its last `history` rows (default 1,000,000).\n\n`strategy` is `random` (the default), `first` (the oldest row kept) or `last` (the\nnewest). `histogram` splits the rows kept, in the order they were written, into\nbins of the stated shares; a draw picks a bin by its frequency and then a row of the\nbin at random, so it is for `random` only. A bin that holds no row yet is left out\nof the draw, and while no bin with a frequency above 0 holds a row (a few rows and\na last bin of frequency 0), the draw is over all the rows. `latest_by` keeps only\nthe newest row for each value of that field of the row, so a lookup sees a\ncustomer's latest address; `strategy` and `histogram` then choose among those rows,\noldest first by the time each was written. `distinct` draws without replacement\nwithin one `repeat`, so the items of one order differ.", "properties": { "null_rate": { "anyOf": [ { "maximum": 1, "minimum": 0, "type": "number" }, { "type": "null" }, { "$ref": "#/$defs/NonNegativeNumberText" }, { "$ref": "#/$defs/Placeholder" } ], "default": null }, "unique": { "default": false, "description": "Gives each value once. A value built only from a task's vars, such as a format or an expr with no generator that draws, draws the vars again and makes the whole payload again until the value is new.", "anyOf": [ { "type": "boolean" }, { "$ref": "#/$defs/Placeholder" } ] }, "omit_rate": { "anyOf": [ { "maximum": 1, "minimum": 0, "type": "number" }, { "type": "null" }, { "$ref": "#/$defs/NonNegativeNumberText" }, { "$ref": "#/$defs/Placeholder" } ], "default": null }, "omit_when": { "anyOf": [ { "type": "string" }, { "type": "null" } ], "default": null }, "gen": { "anyOf": [ { "const": "lookup", "type": "string" }, { "$ref": "#/$defs/Placeholder" } ] }, "task": { "type": "string" }, "path": { "anyOf": [ { "type": "string" }, { "type": "null" } ], "default": null }, "strategy": { "default": "random", "anyOf": [ { "enum": [ "random", "first", "last" ], "type": "string" }, { "$ref": "#/$defs/Placeholder" } ] }, "histogram": { "anyOf": [ { "items": { "$ref": "#/$defs/HistogramBin" }, "type": "array" }, { "type": "null" } ], "default": null }, "latest_by": { "anyOf": [ { "type": "string" }, { "type": "null" } ], "default": null }, "distinct": { "default": false, "anyOf": [ { "type": "boolean" }, { "$ref": "#/$defs/Placeholder" } ] } }, "required": [ "gen", "task" ], "title": "Lookup", "type": "object" } ``` # previous `previous`: the last finished payload of the same task for the same stream, or the part of it at `path`. The stream is the arrival, so all the entities it starts share one, except for an arrival with `count` or `keys`, where each entity has its own. `default` is evaluated only when the stream has no finished payload yet, and without one the first reading is null. Use it for a value from the last finished record of the same task, such as the previous reading. ## Keys | Key | Type | Default | | --------- | ---------- | -------- | | `gen` | `previous` | required | | `path` | text | none | | `default` | Value | none | A `Value` is a constant or a generator, as [What a Generator Is](https://jaehyeon.me/desflow/latest/generators/#what-a-generator-is) explains. Every kind also accepts `null_rate`, `unique`, `omit_rate` and `omit_when`, which [Generators](https://jaehyeon.me/desflow/latest/generators/#keys-every-kind-accepts) describes. ## Example `before` is the `reading` of the order before, and 0 for the first order. An order starts every 60 seconds for 200 seconds, with the seed 42, so three orders start. ```yaml # Previous: a value from the last finished record of the same task. # An order starts every 60 seconds, and the run lasts 200 seconds, so three orders # start. # # Run it with: desflow run examples/generators/previous.yaml simulation: sim_id: Gen factor: 0 random_seed: 42 logical_start_time: 2026-01-01T00:00:00 egress: - {type: Console} arrivals: orders: {dist: constant, value: 60, spawn: order} tasks: order: payload: reading: {gen: integer, bounds: [10, 20]} before: {gen: previous, path: reading, default: 0} run: {until: 200} ``` It prints these records: ```text [EVT] {'sim_ts': 60.0, 'timestamp': '...', 'key': 'orders-1', 'task': 'order', 'instance': 0, 'value': {'reading': 14, 'before': 0}} [EVT] {'sim_ts': 120.0, 'timestamp': '...', 'key': 'orders-2', 'task': 'order', 'instance': 1, 'value': {'reading': 17, 'before': 14}} [EVT] {'sim_ts': 180.0, 'timestamp': '...', 'key': 'orders-3', 'task': 'order', 'instance': 2, 'value': {'reading': 10, 'before': 17}} ``` ## JSON Schema The schema of `Previous`, from `desflow schema`. ```json { "additionalProperties": false, "description": "`previous`: the last finished payload of the same task for the same stream, or\nthe part of it at `path`. The stream is the arrival, so all the entities it starts\nshare one, except for an arrival with `count` or `keys`, where each entity has its\nown. `default` is evaluated only when the stream has no finished payload yet, and\nwithout one the first reading is null.", "properties": { "null_rate": { "anyOf": [ { "maximum": 1, "minimum": 0, "type": "number" }, { "type": "null" }, { "$ref": "#/$defs/NonNegativeNumberText" }, { "$ref": "#/$defs/Placeholder" } ], "default": null }, "unique": { "default": false, "description": "Gives each value once. A value built only from a task's vars, such as a format or an expr with no generator that draws, draws the vars again and makes the whole payload again until the value is new.", "anyOf": [ { "type": "boolean" }, { "$ref": "#/$defs/Placeholder" } ] }, "omit_rate": { "anyOf": [ { "maximum": 1, "minimum": 0, "type": "number" }, { "type": "null" }, { "$ref": "#/$defs/NonNegativeNumberText" }, { "$ref": "#/$defs/Placeholder" } ], "default": null }, "omit_when": { "anyOf": [ { "type": "string" }, { "type": "null" } ], "default": null }, "gen": { "anyOf": [ { "const": "previous", "type": "string" }, { "$ref": "#/$defs/Placeholder" } ] }, "path": { "anyOf": [ { "type": "string" }, { "type": "null" } ], "default": null }, "default": { "$ref": "#/$defs/Value", "default": null } }, "required": [ "gen" ], "title": "Previous", "type": "object" } ``` # upstream `upstream`: the finished payload of the task that routed to this one with `next`, or the part of it at `path`. A start by an arrival has no upstream, and a task that `on_fail` or `on_interrupt_next` reaches is handed a failure or an interrupted record, so a blueprint refuses `upstream` there. Use it for a value from the record of the task that routed to this one. ## Keys | Key | Type | Default | | ------ | ---------- | -------- | | `gen` | `upstream` | required | | `path` | text | none | Every kind also accepts `null_rate`, `unique`, `omit_rate` and `omit_when`, which [Generators](https://jaehyeon.me/desflow/latest/generators/#keys-every-kind-accepts) describes. ## Example The task `order` routes to the task `invoice`, which publishes the amount of the order. An order starts every 60 seconds for 200 seconds, with the seed 42, so three orders start. ```yaml # Upstream: a value from the record of the task that routed here. # An order starts every 60 seconds and routes to an invoice. The run lasts 200 seconds, # so three orders start. # # Run it with: desflow run examples/generators/upstream.yaml simulation: sim_id: Gen factor: 0 random_seed: 42 logical_start_time: 2026-01-01T00:00:00 egress: - {type: Console} arrivals: orders: {dist: constant, value: 60, spawn: order} tasks: order: payload: amount: {gen: integer, bounds: [10, 20]} next: invoice invoice: payload: amount: {gen: upstream, path: amount} run: {until: 200} ``` It prints these records: ```text [EVT] {'sim_ts': 60.0, 'timestamp': '...', 'key': 'orders-1', 'task': 'order', 'instance': 0, 'value': {'amount': 18}} [EVT] {'sim_ts': 60.0, 'timestamp': '...', 'key': 'orders-1', 'task': 'invoice', 'instance': 0, 'value': {'amount': 18}} [EVT] {'sim_ts': 120.0, 'timestamp': '...', 'key': 'orders-2', 'task': 'order', 'instance': 1, 'value': {'amount': 15}} [EVT] {'sim_ts': 120.0, 'timestamp': '...', 'key': 'orders-2', 'task': 'invoice', 'instance': 1, 'value': {'amount': 15}} [EVT] {'sim_ts': 180.0, 'timestamp': '...', 'key': 'orders-3', 'task': 'order', 'instance': 2, 'value': {'amount': 12}} [EVT] {'sim_ts': 180.0, 'timestamp': '...', 'key': 'orders-3', 'task': 'invoice', 'instance': 2, 'value': {'amount': 12}} ``` ## JSON Schema The schema of `Upstream`, from `desflow schema`. ```json { "additionalProperties": false, "description": "`upstream`: the finished payload of the task that routed to this one with\n`next`, or the part of it at `path`. A start by an arrival has no upstream, and a\ntask that `on_fail` or `on_interrupt_next` reaches is handed a failure or an\ninterrupted record, so a blueprint refuses `upstream` there.", "properties": { "null_rate": { "anyOf": [ { "maximum": 1, "minimum": 0, "type": "number" }, { "type": "null" }, { "$ref": "#/$defs/NonNegativeNumberText" }, { "$ref": "#/$defs/Placeholder" } ], "default": null }, "unique": { "default": false, "description": "Gives each value once. A value built only from a task's vars, such as a format or an expr with no generator that draws, draws the vars again and makes the whole payload again until the value is new.", "anyOf": [ { "type": "boolean" }, { "$ref": "#/$defs/Placeholder" } ] }, "omit_rate": { "anyOf": [ { "maximum": 1, "minimum": 0, "type": "number" }, { "type": "null" }, { "$ref": "#/$defs/NonNegativeNumberText" }, { "$ref": "#/$defs/Placeholder" } ], "default": null }, "omit_when": { "anyOf": [ { "type": "string" }, { "type": "null" } ], "default": null }, "gen": { "anyOf": [ { "const": "upstream", "type": "string" }, { "$ref": "#/$defs/Placeholder" } ] }, "path": { "anyOf": [ { "type": "string" }, { "type": "null" } ], "default": null } }, "required": [ "gen" ], "title": "Upstream", "type": "object" } ``` # aggregate `aggregate`: `mean`, `sum`, `min`, `max` or `count` over the last `last` rows of the task `task` that `where` keeps. `where` is an expression over the row's own fields, such as `lead_days == 3 and precipitation > 0`; without it every row counts. `count` counts rows and takes no `path`; the others read the number at `path`. A reading looks back through the rows the task keeps (its `history`) until `last` rows are kept, and takes the rows there are when `where` keeps fewer. Use it for a mean, sum, minimum, maximum or count over earlier records of another task. ## Keys | Key | Type | Default | | ---------- | -------------------------------------------- | -------- | | `gen` | `aggregate` | required | | `task` | text | required | | `path` | text | none | | `last` | integer | required | | `function` | `mean` or `sum` or `min` or `max` or `count` | required | | `where` | text | none | Every kind also accepts `null_rate`, `unique`, `omit_rate` and `omit_when`, which [Generators](https://jaehyeon.me/desflow/latest/generators/#keys-every-kind-accepts) describes. ## Example Three readings start at time 0. Each order publishes the mean of the last 3 levels. An order starts every 60 seconds for 200 seconds, with the seed 42, so three orders start. ```yaml # Aggregate: a mean, sum, minimum, maximum or count over the finished records of another # task. Three readings start at time 0, and an order starts every 60 seconds. The run # lasts 200 seconds, so three orders start. # # Run it with: desflow run examples/generators/aggregate.yaml simulation: sim_id: Gen factor: 0 random_seed: 42 logical_start_time: 2026-01-01T00:00:00 egress: - {type: Console} arrivals: readings: {initial: 3, dist: constant, value: 3600, spawn: reading} orders: {dist: constant, value: 60, spawn: order} tasks: reading: payload: level: {gen: integer, bounds: [10, 20]} order: payload: average: {gen: aggregate, task: reading, path: level, last: 3, function: mean} run: {until: 200} ``` It prints these records: ```text [EVT] {'sim_ts': 0.0, 'timestamp': '...', 'key': 'readings-1', 'task': 'reading', 'instance': 0, 'value': {'level': 15}} [EVT] {'sim_ts': 0.0, 'timestamp': '...', 'key': 'readings-2', 'task': 'reading', 'instance': 1, 'value': {'level': 18}} [EVT] {'sim_ts': 0.0, 'timestamp': '...', 'key': 'readings-3', 'task': 'reading', 'instance': 2, 'value': {'level': 13}} [EVT] {'sim_ts': 60.0, 'timestamp': '...', 'key': 'orders-1', 'task': 'order', 'instance': 0, 'value': {'average': 15.333333333333334}} [EVT] {'sim_ts': 120.0, 'timestamp': '...', 'key': 'orders-2', 'task': 'order', 'instance': 1, 'value': {'average': 15.333333333333334}} [EVT] {'sim_ts': 180.0, 'timestamp': '...', 'key': 'orders-3', 'task': 'order', 'instance': 2, 'value': {'average': 15.333333333333334}} ``` ## JSON Schema The schema of `Aggregate`, from `desflow schema`. ```json { "additionalProperties": false, "description": "`aggregate`: `mean`, `sum`, `min`, `max` or `count` over the last `last` rows of\nthe task `task` that `where` keeps. `where` is an expression over the row's own\nfields, such as `lead_days == 3 and precipitation > 0`; without it every row counts.\n`count` counts rows and takes no `path`; the others read the number at `path`. A\nreading looks back through the rows the task keeps (its `history`) until `last` rows\nare kept, and takes the rows there are when `where` keeps fewer.", "properties": { "null_rate": { "anyOf": [ { "maximum": 1, "minimum": 0, "type": "number" }, { "type": "null" }, { "$ref": "#/$defs/NonNegativeNumberText" }, { "$ref": "#/$defs/Placeholder" } ], "default": null }, "unique": { "default": false, "description": "Gives each value once. A value built only from a task's vars, such as a format or an expr with no generator that draws, draws the vars again and makes the whole payload again until the value is new.", "anyOf": [ { "type": "boolean" }, { "$ref": "#/$defs/Placeholder" } ] }, "omit_rate": { "anyOf": [ { "maximum": 1, "minimum": 0, "type": "number" }, { "type": "null" }, { "$ref": "#/$defs/NonNegativeNumberText" }, { "$ref": "#/$defs/Placeholder" } ], "default": null }, "omit_when": { "anyOf": [ { "type": "string" }, { "type": "null" } ], "default": null }, "gen": { "anyOf": [ { "const": "aggregate", "type": "string" }, { "$ref": "#/$defs/Placeholder" } ] }, "task": { "type": "string" }, "path": { "anyOf": [ { "type": "string" }, { "type": "null" } ], "default": null }, "last": { "anyOf": [ { "minimum": 1, "type": "integer" }, { "$ref": "#/$defs/Placeholder" } ] }, "function": { "anyOf": [ { "enum": [ "mean", "sum", "min", "max", "count" ], "type": "string" }, { "$ref": "#/$defs/Placeholder" } ] }, "where": { "anyOf": [ { "type": "string" }, { "type": "null" } ], "default": null } }, "required": [ "gen", "task", "last", "function" ], "title": "Aggregate", "type": "object" } ``` # row `row`: one row of a CSV or Parquet file as a mapping, read once at load. A cell of digits is read as a number, so a postal code with leading zeros loses them; write them with `{gen: format, template: "{n:05d}"}`. `where` is an expression over the row's columns that keeps some rows; `weight` names a column of weights; `order` is `random` (the default), `sequential`, `shuffle` (every row once, in a random order) or `circular` (in file order, again from the first); `on_end` says what a `sequential` or `shuffle` order does when the rows run out: `error` (the default), `loop` or `stop`, which ends the run. Use it for a whole row of a CSV or Parquet file, such as a product from a price list. ## Keys | Key | Type | Default | | -------- | --------------------------------------------------- | ---------- | | `gen` | `row` | required | | `file` | text | required | | `where` | text | none | | `weight` | text | none | | `order` | `random` or `sequential` or `shuffle` or `circular` | `"random"` | | `on_end` | `stop` or `loop` or `error` | `"error"` | Every kind also accepts `null_rate`, `unique`, `omit_rate` and `omit_when`, which [Generators](https://jaehyeon.me/desflow/latest/generators/#keys-every-kind-accepts) describes. ## Example `product` is one row of `products.csv`, and `shuffle` gives every row once, in a random order. An order starts every 60 seconds for 200 seconds, with the seed 42, so three orders start. ```yaml # Row: one row of a CSV file. # An order starts every 60 seconds, and the run lasts 200 seconds, so three orders # start. The file is `products.csv` in this folder. # # Run it with: desflow run examples/generators/row.yaml simulation: sim_id: Gen factor: 0 random_seed: 42 logical_start_time: 2026-01-01T00:00:00 egress: - {type: Console} arrivals: orders: {dist: constant, value: 60, spawn: order} tasks: order: payload: product: {gen: row, file: products.csv, order: shuffle} run: {until: 200} ``` It prints these records: ```text [EVT] {'sim_ts': 60.0, 'timestamp': '...', 'key': 'orders-1', 'task': 'order', 'instance': 0, 'value': {'product': {'sku': 'B-2', 'price': 4, 'weight': 3}}} [EVT] {'sim_ts': 120.0, 'timestamp': '...', 'key': 'orders-2', 'task': 'order', 'instance': 1, 'value': {'product': {'sku': 'A-1', 'price': 2.5, 'weight': 1}}} [EVT] {'sim_ts': 180.0, 'timestamp': '...', 'key': 'orders-3', 'task': 'order', 'instance': 2, 'value': {'product': {'sku': 'C-3', 'price': 6, 'weight': 6}}} ``` ## JSON Schema The schema of `Row`, from `desflow schema`. ```json { "additionalProperties": false, "description": "`row`: one row of a CSV or Parquet file as a mapping, read once at load. A cell\nof digits is read as a number, so a postal code with leading zeros loses them;\nwrite them with `{gen: format, template: \"{n:05d}\"}`. `where` is an expression over\nthe row's columns that keeps some rows; `weight` names a column of weights; `order`\nis `random` (the default), `sequential`, `shuffle` (every row once, in a random\norder) or `circular` (in file order, again from the first); `on_end` says what a\n`sequential` or `shuffle` order does when the rows run out: `error` (the default),\n`loop` or `stop`, which ends the run.", "properties": { "null_rate": { "anyOf": [ { "maximum": 1, "minimum": 0, "type": "number" }, { "type": "null" }, { "$ref": "#/$defs/NonNegativeNumberText" }, { "$ref": "#/$defs/Placeholder" } ], "default": null }, "unique": { "default": false, "description": "Gives each value once. A value built only from a task's vars, such as a format or an expr with no generator that draws, draws the vars again and makes the whole payload again until the value is new.", "anyOf": [ { "type": "boolean" }, { "$ref": "#/$defs/Placeholder" } ] }, "omit_rate": { "anyOf": [ { "maximum": 1, "minimum": 0, "type": "number" }, { "type": "null" }, { "$ref": "#/$defs/NonNegativeNumberText" }, { "$ref": "#/$defs/Placeholder" } ], "default": null }, "omit_when": { "anyOf": [ { "type": "string" }, { "type": "null" } ], "default": null }, "gen": { "anyOf": [ { "const": "row", "type": "string" }, { "$ref": "#/$defs/Placeholder" } ] }, "file": { "type": "string" }, "where": { "anyOf": [ { "type": "string" }, { "type": "null" } ], "default": null }, "weight": { "anyOf": [ { "type": "string" }, { "type": "null" } ], "default": null }, "order": { "default": "random", "anyOf": [ { "enum": [ "random", "sequential", "shuffle", "circular" ], "type": "string" }, { "$ref": "#/$defs/Placeholder" } ] }, "on_end": { "default": "error", "anyOf": [ { "enum": [ "stop", "loop", "error" ], "type": "string" }, { "$ref": "#/$defs/Placeholder" } ] } }, "required": [ "gen", "file" ], "title": "Row", "type": "object" } ``` # call `call`: what a `!python` function returns, called as `function(context, **kwargs)` with the kwargs evaluated first. Use it for a value that your own Python function computes. ## Keys | Key | Type | Default | | ---------- | ------------------------- | -------- | | `gen` | `call` | required | | `function` | !python reference | required | | `kwargs` | mapping of names to Value | | A `Value` is a constant or a generator, as [What a Generator Is](https://jaehyeon.me/desflow/latest/generators/#what-a-generator-is) explains. Every kind also accepts `null_rate`, `unique`, `omit_rate` and `omit_when`, which [Generators](https://jaehyeon.me/desflow/latest/generators/#keys-every-kind-accepts) describes. ## Example `total` is a price from 10 to 50 plus a tax of 10 per cent, added by `with_tax` in `call_helpers.py`. An order starts every 60 seconds for 200 seconds, with the seed 42, so three orders start. ```yaml # Call: what a Python function returns. # An order starts every 60 seconds, and the run lasts 200 seconds, so three orders # start. The function is in `call_helpers.py` in this folder. # # Run it with: desflow run examples/generators/call.yaml simulation: sim_id: Gen factor: 0 random_seed: 42 logical_start_time: 2026-01-01T00:00:00 egress: - {type: Console} arrivals: orders: {dist: constant, value: 60, spawn: order} tasks: order: payload: total: gen: call function: !python call_helpers.with_tax kwargs: price: {gen: integer, bounds: [10, 50]} run: {until: 200} ``` It prints these records: ```text [EVT] {'sim_ts': 60.0, 'timestamp': '...', 'key': 'orders-1', 'task': 'order', 'instance': 0, 'value': {'total': 41.8}} [EVT] {'sim_ts': 120.0, 'timestamp': '...', 'key': 'orders-2', 'task': 'order', 'instance': 1, 'value': {'total': 26.4}} [EVT] {'sim_ts': 180.0, 'timestamp': '...', 'key': 'orders-3', 'task': 'order', 'instance': 2, 'value': {'total': 53.9}} ``` ## JSON Schema The schema of `Call`, from `desflow schema`. ```json { "additionalProperties": false, "description": "`call`: what a `!python` function returns, called as `function(context,\n**kwargs)` with the kwargs evaluated first.", "properties": { "null_rate": { "anyOf": [ { "maximum": 1, "minimum": 0, "type": "number" }, { "type": "null" }, { "$ref": "#/$defs/NonNegativeNumberText" }, { "$ref": "#/$defs/Placeholder" } ], "default": null }, "unique": { "default": false, "description": "Gives each value once. A value built only from a task's vars, such as a format or an expr with no generator that draws, draws the vars again and makes the whole payload again until the value is new.", "anyOf": [ { "type": "boolean" }, { "$ref": "#/$defs/Placeholder" } ] }, "omit_rate": { "anyOf": [ { "maximum": 1, "minimum": 0, "type": "number" }, { "type": "null" }, { "$ref": "#/$defs/NonNegativeNumberText" }, { "$ref": "#/$defs/Placeholder" } ], "default": null }, "omit_when": { "anyOf": [ { "type": "string" }, { "type": "null" } ], "default": null }, "gen": { "anyOf": [ { "const": "call", "type": "string" }, { "$ref": "#/$defs/Placeholder" } ] }, "function": { "$ref": "#/$defs/PythonReference" }, "kwargs": { "additionalProperties": { "$ref": "#/$defs/Value" }, "type": "object" } }, "required": [ "gen", "function" ], "title": "Call", "type": "object" } ``` # Command Line # Command Line The `desflow` command runs a model without a line of Python, and also checks it, compares designs, fits measured times and converts a distribution's parameters. This page uses each command in the order a study uses it, on one shop, and says what each output tells you. ______________________________________________________________________ ## What It Is `desflow` is installed with the package: `uv tool install desflow`, or `pip install desflow`. Each task is a command of its own, such as `desflow run` or `desflow explain`. `desflow` on its own lists them by task, with examples. The `--help` of each command, such as `desflow run --help`, lists its options and ends with examples of that command. Each command below links to a page with its full help: | Command | What it does | | ---------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------- | | [`desflow run`](https://jaehyeon.me/desflow/latest/cli/run/index.md) | Build the simulation in FILE and run it, or run replications of it. | | [`desflow check`](https://jaehyeon.me/desflow/latest/cli/check/index.md) | Check that each blueprint or builder file in FILE... builds, without running it. | | [`desflow test`](https://jaehyeon.me/desflow/latest/cli/test/index.md) | Run the tests of each file in FILE... and report the statistics that differ. | | [`desflow explain`](https://jaehyeon.me/desflow/latest/cli/explain/index.md) | Show the model in SOURCE as a graph, with its utilisation, status, waits and tuning hints where the queueing formulas apply, and why where they do not. | | [`desflow experiment`](https://jaehyeon.me/desflow/latest/cli/experiment/index.md) | Run the experiment in FILE and write its artifacts and report. | | [`desflow report`](https://jaehyeon.me/desflow/latest/cli/report/index.md) | Build the report of an experiment again from the artifacts in FOLDER. | | [`desflow fit`](https://jaehyeon.me/desflow/latest/cli/fit/index.md) | Fit a column of FILE to the distribution families, and exit 1 if none is usable. | | [`desflow dist`](https://jaehyeon.me/desflow/latest/cli/dist/index.md) | List the distribution families, or convert parameters to a mean and std and back. | | [`desflow schema`](https://jaehyeon.me/desflow/latest/cli/schema/index.md) | Print the blueprint JSON Schema. | | [`desflow mcp`](https://jaehyeon.me/desflow/latest/cli/mcp/index.md) | Serve the desflow commands as MCP tools to an AI assistant on this machine. | | [`desflow examples`](https://jaehyeon.me/desflow/latest/cli/examples/index.md) | List the examples, or download one at the version you have installed. | | [`desflow examples list`](https://jaehyeon.me/desflow/latest/cli/examples-list/index.md) | List the examples, with what each shows and what it needs. | | [`desflow examples get`](https://jaehyeon.me/desflow/latest/cli/examples-get/index.md) | Download an example into ///, at the installed release. | The help of `desflow` ```text Usage: desflow [OPTIONS] COMMAND [ARGS]... Run, explain and analyse desflow simulations, fit their inputs, and download the examples. Options: --version Print the installed version and exit. --help Show this message and exit. Commands: run Build the simulation in FILE and run it, or run replications... check Check that each blueprint or builder file in FILE... test Run the tests of each file in FILE... explain Show the model in SOURCE as a graph, with its utilisation,... experiment Run the experiment in FILE and write its artifacts and report. report Build the report of an experiment again from the artifacts in... fit Fit a column of FILE to the distribution families, and exit 1... dist List the distribution families, or convert parameters to a... schema Print the blueprint JSON Schema. mcp Serve the desflow commands as MCP tools to an AI assistant on... examples List the examples, or download one at the version you have... Examples: # Run a blueprint, sending its records to its sinks $ desflow run shop.yaml # Print the first five events, with no services $ desflow run shop.yaml --sample 5 # Find the bottleneck before running $ desflow explain shop.yaml # List the examples, then download one $ desflow examples list $ desflow examples get local ``` The shop on this page is the model of the `experiment` example: two packers, an order every 2.5 seconds on average, and 4 seconds of packing on average. Every command runs in one folder and needs no Docker service. `desflow fit` needs the `fit` extra: `uv tool install "desflow[fit]"`, or `pip install "desflow[fit]"`. ______________________________________________________________________ ## How to Use It ### Get an Example `desflow --version` prints the release you installed. `desflow examples list`, or `desflow examples` alone, lists every example with the service it needs, such as `(no service)` or `(odctl up kafka-lite)`: ```bash desflow --version desflow examples list desflow examples ``` `desflow examples get` downloads one example at the release you installed, into a folder named after it: ```bash desflow examples get experiment --api yaml ``` ```text wrote experiment/yaml/experiment.yaml wrote experiment/yaml/experiment_shop.yaml wrote experiment/observed_waits.csv Find the bottleneck, with no run: cd experiment/yaml && desflow explain experiment_shop.yaml Run the yaml version: cd experiment/yaml && desflow experiment experiment.yaml ``` The model is `experiment_shop.yaml`, and `experiment.yaml` is the experiment that compares two designs of it. `observed_waits.csv` holds the mean wait measured in the real shop. The line before the last runs `desflow explain` on the model, and the last line is the command that runs the example from its own folder. `--api builder` or `--api low-level` downloads the same example in Python. `--dest` downloads into another folder, and `--ref` downloads from another tag or branch, such as `main` for an example added after your release: ```bash desflow examples get experiment --api builder --dest shop --ref main ``` ```text wrote shop/experiment/builder/experiment_example.py wrote shop/experiment/observed_waits.csv Run the builder version: cd shop/experiment/builder && python experiment_example.py ``` The builder version goes under `shop/experiment/builder`, and the last line runs it from there. A file that is already there stops the download before anything is written, and `--force` replaces it instead. This line downloads the YAML version again, over the files of the first download, and prints the same lines as the first download: ```bash desflow examples get experiment --api yaml --force ``` ### Check a File Before You Run It `desflow check` builds each blueprint or builder file you give it, and does not run it. It reports what `desflow run` reports before the clock starts: YAML errors, unknown keys, missing names, unset variables, `!python` references that cannot be imported, and connectors whose extra is missing or whose settings are refused. It does not call `run.before`, contact a broker, a database or a catalog, or run a `!python` function. Importing a `!python` module runs its top-level code, as `desflow run` does. It prints `ok FILE (sim_id ID)` for each valid file and every error of an invalid one, and exits 1 if any file is invalid. The commands below use a small shop in a file of its own. Its packers come from the variable `PACKERS`, 2 when it is not set, and it holds one test. Save it as `shop.yaml`: ```yaml # A small shop for the commands of the Command Line page that need a file with a # variable and a test. The packers come from PACKERS, 2 when it is not set. # Run it with: desflow run shop.yaml --sample 5 simulation: {sim_id: Shop, factor: 0, random_seed: 42} resources: packers: {current_cap: "${PACKERS:-2}", max_cap: 5} services: packing: {dist: gamma, shape: 4, scale: 1 s} arrivals: orders: {dist: exponential, rate: 0.4, spawn: pack} tasks: pack: service: packing resource: packers payload: {event_type: order_packed} stats: basic run: {until: 10 min} # desflow test runs the model once at the seed and compares these statistics tests: - name: two packers expect: tasks.pack.finished: 224 tasks.pack.wait_mean: {value: 2.299, within: 0.001} ``` A builder file has no `${PACKERS}` variable and no `test` section: its values are Python. `desflow check` and `desflow run` take a builder file too, and [Test a Model](https://jaehyeon.me/desflow/latest/how-to/analysis/test-a-model/index.md) shows how to test one with pytest. A low-level script is not a file the command reads. Run it with `python`, and test it with pytest as [Test a Model](https://jaehyeon.me/desflow/latest/how-to/analysis/test-a-model/index.md) shows. `desflow check` takes more than one file, and `--var NAME=VALUE` fills `${NAME}` in the files and in the files they include, before the environment does. Repeat `--var` for more variables: ```bash desflow check shop.yaml desflow check shop.yaml experiment/yaml/experiment_shop.yaml --var PACKERS=3 ``` It also warns about a run with no end: an arrival with a `dist` or a `gap` and no `max_events`, in a file with no `run.until`, `run.stop` or `run.segments`. The experiment's shop gives no `until`, because the experiment file gives it, so `check` warns about it and still prints `ok`. A `tests` entry with no seed, in a file with no seed of its own, is reported as `desflow test` reports it. desflow ships no pre-commit hook. A repository that keeps its blueprints in a folder can add its own to `.pre-commit-config.yaml`. pre-commit passes the changed files as the arguments, which `check` takes: ```text repos: - repo: local hooks: - id: desflow-check name: desflow check entry: desflow check language: system files: ^models/.*\.ya?ml$ ``` `desflow test` runs the tests that a file holds under `tests`. A test names a seed, an end time and the statistics its run must give. It runs the model once, unpaced, with no ingress and no egress, so a test contacts no service. It prints `ok` for each passing test and each difference of a failing one, and exits 1 if any test fails. A file with no tests prints `no tests`. A builder file reads its tests from a `tests.yaml` in its folder. `--fix` writes the measured statistics into the values that differ, and into a test with none, in place of reporting the differences. A statistic the run published as NaN cannot be written, so `--fix` reports that test as failed. Read the changes before you keep them, because a test states its numbers at one seed of one desflow version. [Test a Model](https://jaehyeon.me/desflow/latest/how-to/analysis/test-a-model/#write-tests-in-the-blueprint) writes tests step by step. ```bash desflow test shop.yaml desflow test shop.yaml --fix --var PACKERS=2 ``` ### Check It Before a Long Run `desflow explain` reads the model without running it. It draws the model as a graph and works out each resource's [utilisation](https://jaehyeon.me/desflow/latest/learn/concepts/queueing-basics/#utilisation), the share of its units that the arrivals keep busy. SOURCE is a blueprint, a builder Python file with a module-level `SimulationContext`, or a URI such as `s3://bucket/sims/shop.yaml`. A URI that ends in a folder is refused with its name, such as `Error: no file s3://bucket/models/`. ```bash desflow explain experiment/yaml/experiment_shop.yaml ``` The same output as text: ```text Shop `-- orders (arrival, rate 0.4/s) `-- spawn -> pack (task, rate 0.4/s) +-- uses packers (resource) `-- next (share 1) -> exit Resources +---------------------------------------------------+ | resource | λ | μ | c | ρ | Wq | L | status | |----------+-----+------+---+-----+----+---+--------| | packers | 0.4 | 0.25 | 2 | 0.8 | - | - | OK | +---------------------------------------------------+ packers by units +-----------------------+ | c | ρ | status | |---+--------+----------| | 1 | 1.6 | UNSTABLE | | 2 | 0.8 | OK | | 3 | 0.5333 | OK | | 4 | 0.4 | OK | +-----------------------+ Bottleneck: packers Not estimated: wait at packers: no closed formula for c > 1 with non-exponential times; run --verify to measure it Hints for utilisation 0.85: packers with 2 units: utilisation 0.8, at most 0.85 packers with 2 units: utilisation 0.85 at a request every 2.35 seconds (25.5 a minute, 0.425 a second) ``` The packers are at utilisation 0.8: they are busy 80% of the time. An order arrives every 2.5 seconds on average (24 a minute, `rate 0.4/s` in the graph). Each order needs 4 seconds of a packer, and 2 packers share the work. The resources table names its columns with the usual queueing symbols: - λ (lambda) is the arrival rate, 0.4 orders a second. - μ (mu) is the rate one packer serves, 0.25 orders a second (4 seconds each). - ρ (rho) is the utilisation. - Wq is the mean wait in the queue, and L the mean number of orders in the shop. Both show `-` when no formula applies. The line `Bottleneck: packers` names the resource with the highest utilisation. Relieving it makes the next busiest resource the bottleneck. The status is `OK` below 0.85, `CONGESTED` from 0.85 and `UNSTABLE` from 1, where the queue grows for as long as the run lasts. The table by units shows that one packer would be `UNSTABLE`. The hints give the units and the arrival rate that reach the target of 0.85. A hint of more units than the resource's `max_cap` also says to raise `max_cap`, because a `current_cap` above `max_cap` is lowered to it. To keep a resource stable, lower its utilisation or its variability: more units (a higher `current_cap`), a shorter service time, a lower arrival `rate`, or less variable gaps or service times. To test how a consumer of the records copes, do the opposite on purpose. From utilisation 0.85 a resource is congested, with long waits that come and go. Above 1 it is overloaded and its queue grows for as long as the overload lasts. `--target` sets the utilisation the hints aim for, 0.85 by default. At 1 or above the hints are for deliberate overload. This command uses the shop of [Queues and Capacity](https://jaehyeon.me/desflow/latest/learn/first-model/queues-and-capacity/index.md), saved as `queues_and_capacity.yaml`: ```bash desflow explain queues_and_capacity.yaml --target 1.2 ``` The end of the output is the hints: ```text Hints for utilisation 1.2: packers with 2 units: utilisation 1.35, at least 1.2, for deliberate overload packers with 1 unit: utilisation 1.2 at a request every 1.25 seconds (48 a minute, 0.8 a second) ``` With 2 packers the shop runs at utilisation 1.35, above the target of 1.2. With 1 packer, an arrival rate of 0.8 orders a second (an order every 1.25 seconds, 48 a minute) gives exactly 1.2. The formulas give no wait for two packers with gamma packing times, so the line under `Not estimated` says to measure it. [Queues and Capacity](https://jaehyeon.me/desflow/latest/learn/first-model/queues-and-capacity/#explain-the-load) works the same numbers out by hand. `--verify` measures it. It runs the model unpaced and compares each statistic with the analysis, as [Check Against Theory](https://jaehyeon.me/desflow/latest/how-to/analysis/check-against-theory/index.md) shows. With `--replications`, it runs the model that many times from `--seed`, each to `--until`, and compares with each measure's 95% interval. `--target` sets the utilisation the hints aim for: ```bash # Ten one-hour runs compared with the analysis, and hints for utilisation 0.9 desflow explain experiment/yaml/experiment_shop.yaml --verify --replications 10 --seed 42 --until 1h --target 0.9 ``` ```text Shop `-- orders (arrival, rate 0.4/s) `-- spawn -> pack (task, rate 0.4/s) +-- uses packers (resource) `-- next (share 1) -> exit Resources +---------------------------------------------------+ | resource | λ | μ | c | ρ | Wq | L | status | |----------+-----+------+---+-----+----+---+--------| | packers | 0.4 | 0.25 | 2 | 0.8 | - | - | OK | +---------------------------------------------------+ packers by units +-----------------------+ | c | ρ | status | |---+--------+----------| | 1 | 1.6 | UNSTABLE | | 2 | 0.8 | OK | | 3 | 0.5333 | OK | | 4 | 0.4 | OK | +-----------------------+ Bottleneck: packers Not estimated: wait at packers: no closed formula for c > 1 with non-exponential times Hints for utilisation 0.9: packers with 2 units: utilisation 0.8, at most 0.9 packers with 2 units: utilisation 0.9 at a request every 2.22 seconds (27 a minute, 0.45 a second) Verify: 10 runs to 3600 s, seed 42 +------------------------------------------------------------------------+ | node | measure | analysis | measured | ± | result | |---------+--------------+----------+----------+----------+--------------| | packers | utilization | 0.8 | 0.8017 | 0.01893 | agrees | | packers | queue_length | - | 1.753 | 0.2404 | not compared | | pack | wait | - | 4.354 | 0.5143 | not compared | | orders | throughput | 0.4 | 0.3992 | 0.009612 | agrees | +------------------------------------------------------------------------+ Not compared: packers queue_length: no closed formula for c > 1 with non-exponential times pack wait: no closed formula for c > 1 with non-exponential times --verify checks the implementation against the queueing analysis where it applies; it does not show that the model is close enough to the real system ``` The measured utilisation of 0.8017 and throughput of 0.3992 agree with the analysis, so the model does what the formulas say. The wait has no formula here, so the runs only measure it: 4.354 seconds. With a target of 0.9, the hints say that two packers reach it at an order every 2.22 seconds. `--json` prints the same explanation as one JSON object, for a script to read. Its `schema_version` names the shape, which the [`Explanation`](https://jaehyeon.me/desflow/latest/reference/api/#explaining-a-model) class describes: ```bash desflow explain experiment/yaml/experiment_shop.yaml --json > explain.json ``` ### Run It `desflow run --sample` prints the first events as JSON lines. It runs the model unpaced, with no ingress, and with no sinks of the file's own, so a model that writes to Kafka or a database needs no service: ```bash desflow run experiment/yaml/experiment_shop.yaml --sample 5 ``` ```text {"stream_type":"event","sim_ts":0.7853891641174294,"timestamp":"...","key":"orders-1","task":"pack","instance":0,"value":{"path_id":"Shop.service.packing","sim_id":"Shop","service":"packing","status":"queued"}} {"stream_type":"event","sim_ts":0.7853891641174294,"timestamp":"...","key":"orders-1","task":"pack","instance":0,"value":{"path_id":"Shop.service.packing","sim_id":"Shop","service":"packing","status":"started"}} {"stream_type":"event","sim_ts":4.186525464662821,"timestamp":"...","key":"orders-1","task":"pack","instance":0,"value":{"event_type":"order_packed"}} {"stream_type":"event","sim_ts":6.1679236265239235,"timestamp":"...","key":"orders-2","task":"pack","instance":1,"value":{"path_id":"Shop.service.packing","sim_id":"Shop","service":"packing","status":"queued"}} {"stream_type":"event","sim_ts":6.1679236265239235,"timestamp":"...","key":"orders-2","task":"pack","instance":1,"value":{"path_id":"Shop.service.packing","sim_id":"Shop","service":"packing","status":"started"}} ``` Each order publishes `queued` when it joins the packers' queue and `started` when a packer takes it. The first two orders find a packer free, so each starts at the moment it queues. Without `--sample`, `desflow run` runs the model with its own settings and sinks. A model that runs out of events before the sample is full ends with exit 0 and the records it made. `--var NAME=VALUE` fills `${NAME}` in the file and in the files it includes, before the environment does, and `check` and `test` take it too. `explain` and `experiment` do not take `--var`. `--watch` runs the file in a child process and runs it again whenever the file, or a `.py` file beside it, changes, so a change to a blueprint shows its first events at once. It needs the `watch` extra: `pip install "desflow[watch]"`. Press Ctrl+C to stop it: ```bash desflow run shop.yaml --var PACKERS=3 --sample 5 desflow run shop.yaml --sample 5 --watch ``` `--log-level` sets how much desflow logs for one run: `debug`, `info`, `warning` or `error`. It overrides `simulation.log_level` in the file, and without either `desflow run` logs at INFO. The other commands log at WARNING and do not take it, as [Log Level](https://jaehyeon.me/desflow/latest/user-guide/writing-a-model/blueprints/#log-level) describes. With `warning`, this sample prints its events with no INFO lines on stderr: ```bash desflow run shop.yaml --sample 5 --log-level warning ``` One run is one sample, so measure the wait with [replications](https://jaehyeon.me/desflow/latest/user-guide/results/replications/index.md): the same model with ten seeds, each run for one hour: ```bash desflow run experiment/yaml/experiment_shop.yaml --replications 10 --seed 42 --until 1h ``` ```text measure n mean half-width (95%) resources.packers.capacity 10 2 0 resources.packers.in_use 10 1.9 0.2262 resources.packers.queue_length 10 3.9 2.298 resources.packers.utilization 10 95 11.31 resources.packers.utilization_avg 10 80.17 1.893 resources.packers.queue_length_avg 10 1.753 0.2404 tasks.pack.in_progress 10 5.8 2.404 tasks.pack.finished 10 1437 34.6 tasks.pack.wait_mean 10 4.354 0.5143 tasks.pack.wait_max 10 28.17 3.833 tasks.pack.service_mean 10 4.013 0.03767 tasks.pack.service_max 10 15.15 1.292 flows.orders.finished 10 1437 34.6 flows.orders.started 10 1443 33.77 flows.orders.in_system 10 5.8 2.404 Seed 42; replication seeds: 2684470948, 4091952314, 233227757, 3276785861, 3644269654, 1206282609, 3543069911, 3479688010, 877132087, 1244265337 Repeat one replication with: desflow run experiment/yaml/experiment_shop.yaml --seed --until 1h ``` The mean wait is 4.354 seconds, and its [half-width](https://jaehyeon.me/desflow/latest/learn/concepts/output-analysis/#interval-and-half-width) of 0.5143 says that the true mean lies within about 0.51 seconds of it, with 95% confidence. The packers are busy 80.17% of the time, close to the 0.8 that `explain` worked out. The last line repeats any one replication, with its events. This shop has no sinks. A model with a sink, such as `type: Console`, also sends the result to it as telemetry: one reading for each replication and measure. A Console sink therefore prints those lines before the table, as [What the Sinks Receive](https://jaehyeon.me/desflow/latest/user-guide/results/replications/#what-the-sinks-receive) explains. `--measure` names a statistic to summarise, and repeats for more. `--level` sets the confidence level of the intervals. `--workers` runs that many replications at once, each in its own process, and gives the same results, because each replication keeps its seed. The three apply to `--replications`, and `desflow run` refuses them without it: ```bash # Two statistics at a 99% level, two replications at a time desflow run experiment/yaml/experiment_shop.yaml --replications 10 --seed 42 --until 1h --measure tasks.pack.wait_mean --measure resources.packers.utilization_avg --level 0.99 --workers 2 ``` ```text measure n mean half-width (99%) tasks.pack.wait_mean 10 4.354 0.7389 resources.packers.utilization_avg 10 80.17 2.72 Seed 42; replication seeds: 2684470948, 4091952314, 233227757, 3276785861, 3644269654, 1206282609, 3543069911, 3479688010, 877132087, 1244265337 Repeat one replication with: desflow run experiment/yaml/experiment_shop.yaml --seed --until 1h ``` The means are the same as before. At 99%, the half-width of the mean wait grows from 0.5143 to 0.7389 seconds, because more confidence needs a wider interval. `--summary` also writes the result to a JSON file, for a program that reads it, such as a task in a pipeline. A single run writes its own statistics the same way. [Write the Result to a File](https://jaehyeon.me/desflow/latest/user-guide/results/replications/#write-the-result-to-a-file) lists the keys: ```bash desflow run experiment/yaml/experiment_shop.yaml --replications 10 --seed 42 --until 1h --summary results/summary.json ``` In `results/summary.json`, the `summary` row of `tasks.pack.wait_mean` holds the same mean wait of 4.354 seconds, with its interval from 3.84 to 4.869 seconds as `low` and `high`. `--stdout` prints the run's records as JSON lines, instead of writing to the file's sinks. The run keeps its ingress connectors, so a `KafkaIngress` still applies its `topic_policy`: it creates the control topic, and with `drop_and_create` it deletes it and creates it again. `--drain` stops the arrivals at the end time and runs on until every order has left. This run stops the arrivals at 20 seconds, and its last record is the seventh order packed, at 20.502310430365075 seconds. A record keeps its time unrounded: ```bash # Every record of a 20-second run that drains, as JSON lines in a file desflow run experiment/yaml/experiment_shop.yaml --seed 42 --until 20 --drain --stdout > records.jsonl ``` ### Compare Designs `desflow experiment` runs an [experiment](https://jaehyeon.me/desflow/latest/user-guide/results/experiments/index.md): here two packers against three, 20 replications of each with the same seeds, with a check that three packers keep the mean wait under 2 seconds. `--output` names the folder for its files, here `results/packers` in the current folder. Without it, they go to the folder the file's `output` names, beside the file: ```bash desflow experiment experiment/yaml/experiment.yaml --output results/packers ``` ```text Wrote the artifacts and report.md to results/packers passed: three: tasks.pack.wait_mean max 2, checked 0.5816 ``` The check passed: the upper end of the interval of the mean wait with three packers is 0.5816 seconds, under the bound of 2. The command exits with status 1 when a check fails, so a CI job that runs it fails too. The six files in `results/packers` hold every value, and `report.md` compares the designs, as [Experiment Results](https://jaehyeon.me/desflow/latest/user-guide/results/experiment-results/index.md) describes. After editing `experiment.json` by hand, `desflow report` builds the report again from the files, without running anything: ```bash desflow report results/packers ``` ```text Wrote results/packers/report.md ``` ### Fit Measured Times A packing time in a model comes from measured times. The `fitting` example holds 40 packing times measured at a bench, for a shop of its own, and `desflow fit` fits every family of times to them: ```bash desflow examples get fitting --api yaml desflow fit fitting/packing_times.csv --column packing_seconds --lower 0 ``` ```text 40 rows: 40 used, 0 missing, 0 invalid family status AIC KS stat KS p (approx.) parameters or reason exponential rejected its std is 1.5, the data's is 0.4832: more than 25% apart normal fitted 59.33 0.157 0.2504 mean=1.5, std=0.483218 (can draw below the lower bound 0) lognormal fitted 57.33 0.09406 0.8385 mean=1.50251, std=0.511854 truncated_normal fitted 59.25 0.1558 0.2579 mean=1.49836, std=0.48579, low=0 constant skipped the values are not all equal uniform fitted 59.45 0.225 0.02923 low=0.7, high=2.7 triangular * fitted 56.68 0.1258 0.511 low=0.546332, mode=1.2, high=2.83766 gamma fitted 56.79 0.1157 0.6165 shape=9.55777, scale=0.15694 weibull fitted 58.99 0.1502 0.2972 shape=3.33522, scale=1.67203 empirical fitted values: 40 numbers * best: triangular ``` The first line counts the values. Each row is one family: `fitted` with its [AIC](https://jaehyeon.me/desflow/latest/learn/concepts/a-simulation-study/#aic-and-the-ks-test), where lower is better, or the reason it was not fitted. The `triangular` has the lowest AIC, 56.68, and the `gamma` is within 0.11 of it, so the data cannot tell the two apart. [Fitting the Inputs](https://jaehyeon.me/desflow/latest/learn/inputs/fit-the-inputs/#does-the-choice-matter) checks what the choice changes. The other options shape the fit, as [Input Fitting](https://jaehyeon.me/desflow/latest/user-guide/model-parts/input-fitting/index.md) describes: - `--unit` names the data's unit, `ms`, `s`, `min` or `h`, and the settings are written in seconds. - `--upper` is the highest plausible value, and a family that can draw above it is marked. - `--candidates` names the families to try. The default is every family that fits times, ten of them. `poisson` and `geometric` count whole numbers, so a fit does not try them, and named in `--candidates` they are skipped with the reason that they count whole numbers. - `--bins` offers the empirical distribution as a histogram with that many bins. - `--min-count` is the fewest values a family is fitted to. - `--tolerance` is how far a fitted mean and standard deviation may be from the data's, as a share of the data's. A tolerance that is negative or NaN, and a bound that is NaN, are refused, and so is a name in `--candidates` that is not a family, which the refusal quotes. - `--drop-invalid` leaves out values that are not numbers or lie outside the bounds, instead of stopping. - `--out` writes the best fit as YAML that a blueprint includes, and `--plot` draws the data against it as a PNG. ```bash # Three families, a histogram of 8 bins, and the best fit written for the blueprint desflow fit fitting/packing_times.csv --column packing_seconds --unit s --lower 0 --upper 10 --candidates triangular,gamma,empirical --bins 8 --min-count 30 --tolerance 0.2 --drop-invalid --out fitting/yaml/packing_fit.yaml --plot packing_fit.png ``` ```text 40 rows: 40 used, 0 missing, 0 invalid family status AIC KS stat KS p (approx.) parameters or reason triangular * fitted 56.68 0.1258 0.511 low=0.546332, mode=1.2, high=2.83766 gamma fitted 56.79 0.1157 0.6165 shape=9.55777, scale=0.15694 (can draw above the upper bound 10) empirical fitted edges: 9 numbers, counts: 8 numbers * best: triangular Wrote fitting/yaml/packing_fit.yaml Wrote packing_fit.png ``` The `empirical` row is now a histogram of 8 bins, and the `gamma` row is marked because a gamma can draw above 10 seconds. `fitting/yaml/packing_fit.yaml` is the file the fitting example's blueprint includes, so `fitting/yaml/fitting.yaml` now draws its packing times from this triangular. ### Convert Parameters A gamma takes a `shape` and a `scale`, not a mean and a standard deviation. `desflow dist` converts the measured times' mean of 1.5 seconds and standard deviation of 0.4832 seconds into them: ```bash desflow dist gamma --mean 1.5 --std 0.4832 ``` ```text parameters: shape 9.63671, scale 0.155655 mean 1.5, std 0.4832 variability: low (std / mean 0.322) with no random generator, every draw is 1.5 YAML: {dist: gamma, shape: 9.63671, scale: 0.155655} Python: dist="gamma", shape=9.63671, scale=0.155655 ``` The shape and scale are close to the gamma that `desflow fit` found from the 40 values. The last two lines are the service in a blueprint and in the builder. Given a family's own parameters, `desflow dist` converts the other way. Each of these lines prints the family's mean and standard deviation, as in the output above, for each kind of parameter: a rate, a constant's value, a low and a high, and a shape and a scale: ```bash desflow dist exponential --rate 0.4 desflow dist constant --value 4 desflow dist uniform --low 0.7 --high 2.7 desflow dist gamma --shape 9.63671 --scale 0.155655 ``` The shop's arrivals, `rate: 0.4`, are 2.5 seconds apart on average. A triangular also takes a mode, its most likely value. The one `desflow fit` found has a mean of 1.53 seconds, close to the measured 1.5: ```bash desflow dist triangular --low 0.55 --mode 1.2 --high 2.84 ``` ```text parameters: low 0.55, mode 1.2, high 2.84 mean 1.53, std 0.481785 variability: low (std / mean 0.315) with no random generator, every draw is 1.53 YAML: {dist: triangular, low: 0.55, mode: 1.2, high: 2.84} Python: dist="triangular", low=0.55, mode=1.2, high=2.84 ``` `poisson` takes `--mean`, and `geometric` takes `--p`, the chance of success on each try. Both give whole numbers: ```bash desflow dist geometric --p 0.25 ``` `desflow dist` alone prints a table of every family with its parameters and a one-line summary, and [Choosing Inputs](https://jaehyeon.me/desflow/latest/learn/inputs/choosing-inputs/#measured-times) explains the variability line: ```bash desflow dist ``` ### Set Up an Editor `desflow schema` prints the JSON Schema of a blueprint, for the release you installed. An editor that reads it offers the keys as you type and marks a misspelt one: ```bash desflow schema > blueprint.schema.json ``` [Set Up Your Editor](https://jaehyeon.me/desflow/latest/how-to/tools/set-up-your-editor/index.md) names the file in the editor's settings. ### Serve the Commands to an Assistant `desflow mcp` serves the desflow commands as tools to an AI assistant on the same machine, over MCP, the Model Context Protocol. The assistant's MCP client starts the command as a process and exchanges messages with it over the process's standard input and output. Each tool runs one desflow command, such as `check` for `desflow check` and `list_examples` for `desflow examples list`, and returns what the command prints, or its JSON document where the command writes one. It needs the `mcp` extra: `uv tool install "desflow[mcp]>=1.1"`, or `pip install "desflow[mcp]>=1.1"`. The tools `check`, `explain`, `test`, `fit`, `dist`, `schema` and `list_examples` write nothing, and the server always offers them. A Python builder file is the exception: loading it runs its own code, which can write files, so give these tools only builder files you trust. `--allow-changes` adds the tools that write: `run`, `experiment`, `report` and `get_example`, and the `fix` parameter of `test` and the `out` and `plot` parameters of `fit`. A run sends records to the blueprint's sinks, and the others write files. The `run` tool returns the document that `--summary` writes. The assistant's settings give the command and its options, so `--allow-changes` goes there: ```bash # An MCP client runs this; in a terminal it waits for messages until Ctrl+D desflow mcp --allow-changes ``` ______________________________________________________________________ ## How It Works Each command reads its file and calls the library function a Python script would call. `desflow run` loads the model with `load_context` and runs it once, or calls `replicate` when `--replications` is given. `desflow experiment` calls `run_experiment`, `desflow report` calls `write_report`, and `desflow fit` reads the column and calls `fit_column`. `desflow dist`, `desflow schema` and `desflow examples` read the distribution table, the blueprint schema and the list of examples. A command therefore gives the same result as the Python call with the same arguments. `desflow mcp` runs the command of each tool in the server's own process, through the same command line, so a tool checks and refuses its arguments as the command does. `desflow explain` takes the most steps. Look at them in order: **Graph.** `explain` builds the graph from what the model declares: its arrivals, tasks, resources, stores, containers and `next` shares. It builds and runs nothing. Code the model does not declare, such as a hand-written arrival loop or an `add_process` function, becomes an opaque node. The graph also has an edge with no share from a task to each task it starts by an `on:` or `listen` spawn, a `task` branch of `wait`, `open` or `subscribe`, a spawn in the `on:` of a signal it fires, and `on_interrupt_next` and `on_interrupt_run`. `next` weights, fixed or computed, end no flow. **Rates.** Each task's arrival rate comes from flow balance: the rate from its arrivals plus the share of each task that sends work to it. A `next` function or a hand-written arrival loop makes the rates unknown, because the graph cannot see where the work goes. A task reached by an edge with no share has no rate either, with the reason "how often starts it is not known before a run" or "the split after depends on the run". **Coverage.** The formulas hold for a plain network of queues: - Each task holds at most one resource. - Each queue serves in arrival order, `fifo` or `lifo`, which give the same mean wait. - Nothing blocks, removes, delays or reorders work by priority. Anything else marks tasks, and the rate of a marked task is unknown. These mark tasks: - A task feature, such as `put`, `patience`, `fail`, a `service_time` (`computed service time`) or an `interrupt` that names the task (`interruptions (an interrupt names it)`), marks that task and every task after it. - An arrival feature gives the arrival no rate, so the tasks it starts have none: a `gap` (`computed gaps`), a `count`, `keys`, a `key` that can repeat or `max_events` (`limited or repeated arrivals`), a `group` other than 1, and `active: false`. A spawn `count` other than 1 is a feature too. - A resource feature, such as `queue_limit`, breakdowns, a capacity that an `on:` entry sets, a resource family, or a resource picked by `key` or `lowest`, marks the tasks that use it and every task after them. - A router with a weight that is an expression ends no flow and has no shares. - A priority queue whose tasks have different priorities marks every task after its tasks. The resource keeps its utilisation but has no wait. - An unstable resource marks every task after its tasks. The resource keeps its status. - A scenario step, an `on:` entry that sets an arrival or a service, live ingress or an `add_process` function marks every arrival and every task. A resource used by a marked task has no supported utilisation, status or wait, and the output names the reason under `Not estimated`. **Waits.** The utilisation ρ is λ ÷ (c × μ): the arrival rate divided by the units times the rate one unit serves. The status follows from it. The wait depends on the units and the input: - With no unit limit, the wait is 0. - At one unit, the wait comes from Kingman's formula. It is exact when the input is Poisson, and an approximation when one arrival with other gaps feeds the resource's only task. - At more than one unit, the wait comes from Erlang C, which needs Poisson arrivals and one exponential service time shared by every task that uses the resource. - With any other input or times there is no wait, and the output says to run `--verify`. Little's law then gives the queue length and the number in the system. The bottleneck is the resource with the highest supported utilisation. The hints solve the utilisation alone for the units and the arrival rate that reach `--target`. **Verify.** `--verify` runs the model as one replication does: unpaced, with no ingress or egress, and with the `typical` statistics. It measures from the end of the warm-up to `--until`, or to the blueprint's `run.until` when `--until` is not given. It compares four measures with the analysis: each resource's utilisation and queue length, the wait of each task that holds one resource, and each arrival's throughput. A measure agrees with the analysis: - For one run, when it is within 10% of the analysis, or measures 0 where the analysis gives 0. - For replications, when it is within the 95% interval's half-width or 1%, whichever is larger. A measure is not compared in these cases: - The analysis has no value for it. - Its resource is unstable. - Its wait comes from Kingman's formula as an approximation. - For a throughput, the arrival starts no task the graph shows, its flow passes a marked task or an unstable resource, or the blueprint has a `run.stop` that can end a run before `until`. ______________________________________________________________________ ## Stability and Limits - **Inputs are files.** `run` reads a blueprint, or a builder file with `--sample` (not with `--stdout`, `--var` or `--watch`), `check` a blueprint or a builder file, `test` a blueprint or a builder file with a `tests.yaml`, `explain` a blueprint or a builder file with a module-level `SimulationContext`, `experiment` an experiment file, and `fit` a CSV file. For a Python model, use `replicate` and `run_experiment`, as [Replications](https://jaehyeon.me/desflow/latest/user-guide/results/replications/index.md) shows. - **Examples need the network.** `examples get` downloads from GitHub at the installed release's tag. `--ref` picks another tag or branch. - **`explain --json` is experimental.** Its shape can change in 1.x, and `schema_version` changes with it. - **Exit statuses:** 0 on success, 1 on a failure, 2 on a usage error. A `run` stopped by Ctrl+C or SIGTERM flushes its sinks, writes no `--summary` file and exits with 0. - **1:** `run`, `check`, `test` or `explain` cannot load the file, a `test` differs from the measured statistics, an `experiment` check fails (its files are still written), `fit` finds no usable family, or `dist` has no formula from a mean and a standard deviation for the family. - **2:** a missing file, an option value that is not valid such as `--until abc`, a value that is not a number in a `fit` column, or an experiment file that is not valid. # desflow run The help of `desflow run`, generated from the command's code. [Command Line](https://jaehyeon.me/desflow/latest/cli/#run-it) uses this one on the shop, and its [What It Is](https://jaehyeon.me/desflow/latest/cli/#what-it-is) lists every command. ```text Usage: desflow run [OPTIONS] {FILE} Build the simulation in FILE and run it, or run replications of it. FILE is a YAML blueprint. With --sample it may also be a builder file, a `.py` file with a module-level `SimulationContext`, which is imported as `desflow test` imports it, so its `if __name__ == "__main__":` block does not run. Arguments: FILE The blueprint file, or a builder file with --sample. [required] Options: --until TIME Simulation time to stop at, in seconds or as a duration such as '10 min'. Overrides run.until in the file. --seed N The random seed. Overrides simulation.random_seed in the file. A run without one logs the seed it drew, with the command that repeats it. --drain At the end time, stop the arrivals and keep running until every entity in the model has left. Sets run.drain in the file to true. --replications N Run N replications unpaced, with seeds spawned from the seed, and print the mean and confidence interval of each statistic. [x>=2] --level The confidence level of the replications' intervals, between 0 and 1. [default: 0.95] --measure NAME A statistic to summarise, such as tasks.pack.wait_mean; repeat it for more. Defaults to every statistic the run publishes, at least up to typical. --workers N Replications run at once, each in its own process. [default: 1; x>=1] --sample N Print the first N events as JSON lines, unpaced, with no ingress and no real sinks. [x>=1] --stdout Print every record except the system.simulation.lag_seconds readings as a JSON line, instead of writing to the file's sinks. The lag readings describe the wall clock, not the model. --summary PATH When the run ends, write its statistics to PATH as one JSON file, or with --replications the summary and every replication's values. A single run then keeps its statistics at the typical level or above, so a model with sinks also sends them its statistics telemetry. A file already at PATH is removed when the run starts, and a run that fails or is stopped writes none. --var NAME=VALUE Fill ${NAME} in the file and in the files it includes, before the environment does. Repeat it for more. --watch Run in a child process, and run again whenever the file or a .py file beside it changes. Needs the watch extra. --log-level LEVEL How much desflow logs: debug, info, warning or error. Overrides simulation.log_level in the file. Defaults to info. --help Show this message and exit. Examples: # Run a blueprint, sending its records to its sinks $ desflow run shop.yaml # Print the first five events, with no services $ desflow run shop.yaml --sample 5 # Print every record as a JSON line instead of sending it $ desflow run shop.yaml --stdout # Run 20 replications and print the mean and interval of each statistic $ desflow run shop.yaml --replications 20 --seed 7 # Write the statistics of the run to a JSON file $ desflow run shop.yaml --summary result.json # Print the first five events again whenever the file changes $ desflow run shop.yaml --sample 5 --watch ``` # desflow check The help of `desflow check`, generated from the command's code. [Command Line](https://jaehyeon.me/desflow/latest/cli/#check-it-before-a-long-run) uses this one on the shop, and its [What It Is](https://jaehyeon.me/desflow/latest/cli/#what-it-is) lists every command. ```text Usage: desflow check [OPTIONS] {FILE...}... Check that each blueprint or builder file in FILE... builds, without running it. It reports what `desflow run` reports before the clock starts: YAML errors, unknown keys, missing names, unset variables, `!python` references that cannot be imported, and connectors whose extra is missing or whose settings are refused. A Parquet, Jsonl or Iceberg connector, in a blueprint or a builder file, is refused when its extra is not installed. It also reports a `tests` entry with no seed in a file with none, as `desflow test` does. It warns about a run with no end: an arrival with a `dist` or a `gap` and no `max_events`, in a file with no `run.until`, `run.stop` or `run.segments`. It does not call `run.before`, contact a broker, a database or a catalog, or run a `!python` function. Importing a `!python` module runs its top-level code, as `desflow run` does. A builder file, a `.py` file with a module-level `SimulationContext`, is imported as `desflow test` imports it, so an import whose extra is missing is reported; its `if __name__ == "__main__":` block does not run. An error or a `sys.exit` of the file's code is one line, with the file, its line and the error's type. Prints `ok FILE (sim_id ID)` for each valid file and every error of an invalid one, and exits 1 if any file is invalid. Arguments: FILE... The blueprint files, or builder files. [required] Options: --var NAME=VALUE Fill ${NAME} in the files and in the files they include, before the environment does. Repeat it for more. --help Show this message and exit. Examples: # Check one blueprint without running it $ desflow check shop.yaml # Check every blueprint in a folder, as a pre-commit hook does $ desflow check examples/*.yaml # Check a builder file, which defines its model in Python $ desflow check shop.py ``` # desflow test The help of `desflow test`, generated from the command's code. [Command Line](https://jaehyeon.me/desflow/latest/cli/#check-it-before-a-long-run) uses this one on the shop, and its [What It Is](https://jaehyeon.me/desflow/latest/cli/#what-it-is) lists every command. ```text Usage: desflow test [OPTIONS] {FILE...}... Run the tests of each file in FILE... and report the statistics that differ. A test names a seed, an end time and the statistics its run must give, such as tasks.pack_order.finished. It runs the model once, unpaced, with no ingress and no egress, so a test contacts no service. A test states its measures at one seed in one version of desflow: a new release may draw its random numbers differently, so exact seeded values are not promised across versions. Run it with --fix after an upgrade or a deliberate change and read the changes. A builder file reads its tests from a tests.yaml in its folder. Prints ok for each passing test, and each difference of a failing one. Exits 1 if any test fails. Arguments: FILE... The blueprint files, or builder files with a tests.yaml beside them. [required] Options: --fix Write the statistics the runs gave into the expect values that differ, and into a test with none, instead of reporting differences. Read the changes before you keep them. --var NAME=VALUE Fill ${NAME} in a blueprint and in the files it includes, before the environment does. Repeat it for more. --help Show this message and exit. Examples: # Check the tests in a blueprint $ desflow test shop.yaml # Write the statistics the runs gave into the expect values, then read them $ desflow test shop.yaml --fix ``` # desflow explain The help of `desflow explain`, generated from the command's code. [Command Line](https://jaehyeon.me/desflow/latest/cli/#check-it-before-a-long-run) uses this one on the shop, and its [What It Is](https://jaehyeon.me/desflow/latest/cli/#what-it-is) lists every command. ```text Usage: desflow explain [OPTIONS] {SOURCE} Show the model in SOURCE as a graph, with its utilisation, status, waits and tuning hints where the queueing formulas apply, and why where they do not. Arguments: SOURCE A YAML blueprint, or a builder Python file with a module-level SimulationContext, local or a URI such as s3://bucket/sims/shop.yaml. [required] Options: --json Print the explanation as JSON (schema_version 0, experimental). --verify Also run the model unpaced and compare its statistics with the analysis. --until TIME With --verify: the end of the run, in seconds or as a duration such as '10 min'. Overrides run.until in the file. --seed N With --verify: the run's seed. Overrides the model's own. --replications N With --verify: run N times and compare with each measure's 95% interval, instead of one run within 10 percent. [x>=2] --target T The utilisation the hints aim for, above 0 and at most 10; at 1 or above the hints are for deliberate overload. [default: 0.85] --help Show this message and exit. Examples: # Show the graph, the utilisation and the bottleneck $ desflow explain shop.yaml # Size each resource for a utilisation of 0.7 $ desflow explain shop.yaml --target 0.7 # Compare the formulas with 10 replications of the model $ desflow explain shop.yaml --verify --replications 10[/bold cyan] # Print the result as JSON $ desflow explain shop.yaml --json ``` # desflow experiment The help of `desflow experiment`, generated from the command's code. [Command Line](https://jaehyeon.me/desflow/latest/cli/#compare-designs) uses this one on the shop, and its [What It Is](https://jaehyeon.me/desflow/latest/cli/#what-it-is) lists every command. ```text Usage: desflow experiment [OPTIONS] {FILE} Run the experiment in FILE and write its artifacts and report. Exits 1 if a check fails. Arguments: FILE The experiment file. [required] Options: --output FOLDER Where to write the artifacts. Overrides output in the file. --help Show this message and exit. Examples: # Run an experiment and write its results to a folder $ desflow experiment experiment.yaml --output results ``` # desflow report The help of `desflow report`, generated from the command's code. [Command Line](https://jaehyeon.me/desflow/latest/cli/#compare-designs) uses this one on the shop, and its [What It Is](https://jaehyeon.me/desflow/latest/cli/#what-it-is) lists every command. ```text Usage: desflow report [OPTIONS] {FOLDER} Build the report of an experiment again from the artifacts in FOLDER. Arguments: FOLDER An experiment's output folder, with its experiment.json. [required] Options: --help Show this message and exit. Examples: # Build the report again from an experiment's results $ desflow report results ``` # desflow fit The help of `desflow fit`, generated from the command's code. [Command Line](https://jaehyeon.me/desflow/latest/cli/#fit-measured-times) uses this one on the shop, and its [What It Is](https://jaehyeon.me/desflow/latest/cli/#what-it-is) lists every command. ```text Usage: desflow fit [OPTIONS] {FILE} Fit a column of FILE to the distribution families, and exit 1 if none is usable. Arguments: FILE A CSV file with a header row. [required] Options: --column NAME The column to fit. [required] --unit The data's unit: ms, s, min or h. Settings are in seconds. [default: s] --candidates NAMES The families to try, separated by commas. Defaults to every family. --lower The lowest plausible value, in the data's unit. --upper The highest plausible value, in the data's unit. --bins Offer the empirical distribution as a histogram with this many bins. [x>=1] --min-count The fewest values a family is fitted to. [default: 20; x>=1] --tolerance How far a fitted mean and standard deviation may be from the data's, as a share of the data's. [default: 0.25] --drop-invalid / --no-drop-invalid Leave out invalid values rather than stopping. [default: no-drop-invalid] --out FILE Write the best candidate's settings here, for !include in a blueprint. --plot FILE Draw the data against the best candidate, as a PNG. --help Show this message and exit. Examples: # Fit measured packing times, in seconds $ desflow fit times.csv --column packing_seconds # Write the best fit's settings for a blueprint to load $ desflow fit times.csv --column packing_seconds --lower 0 --out packing.yaml ``` # desflow dist The help of `desflow dist`, generated from the command's code. [Command Line](https://jaehyeon.me/desflow/latest/cli/#convert-parameters) uses this one on the shop, and its [What It Is](https://jaehyeon.me/desflow/latest/cli/#what-it-is) lists every command. ```text Usage: desflow dist [OPTIONS] [FAMILY] List the distribution families, or convert parameters to a mean and std and back. Exits 1 for a family with no formula from a mean and std. Arguments: FAMILY A family, such as gamma. Leave it out to list every family. Options: --rate X Events per second. --mean X The mean, a parameter or, with --std, the mean to convert from. --std X The std, a parameter or, with --mean, the std to convert from. --low X The lowest value. --value X A constant's time. --high X The highest value. --mode X The most likely value. --shape X The shape. --scale X The scale. --p X The chance of success on each try. --help Show this message and exit. Examples: # List the distribution families $ desflow dist # Show the parameters and rules of one family $ desflow dist gamma # Convert a mean and standard deviation to gamma parameters $ desflow dist gamma --mean 1.5 --std 0.4832 ``` # desflow schema The help of `desflow schema`, generated from the command's code. [Command Line](https://jaehyeon.me/desflow/latest/cli/#set-up-an-editor) uses this one on the shop, and its [What It Is](https://jaehyeon.me/desflow/latest/cli/#what-it-is) lists every command. ```text Usage: desflow schema [OPTIONS] Print the blueprint JSON Schema. Options: --help Show this message and exit. Examples: # Save the blueprint schema for an editor $ desflow schema > blueprint.schema.json ``` # desflow mcp The help of `desflow mcp`, generated from the command's code. [Command Line](https://jaehyeon.me/desflow/latest/cli/#serve-the-commands-to-an-assistant) uses this one on the shop, and its [What It Is](https://jaehyeon.me/desflow/latest/cli/#what-it-is) lists every command. ```text Usage: desflow mcp [OPTIONS] Serve the desflow commands as MCP tools to an AI assistant on this machine. An MCP client starts the server as a process and exchanges messages with it over its standard input and output. Each tool runs the command of the same name. The tools that write are served only with --allow-changes, an option that shows in the client's configuration. Needs the mcp extra. Options: --allow-changes Also serve the tools that write: run, experiment, report and get_example, test with fix, and fit with out and plot. A run sends records to the blueprint's sinks, and the others write files. --help Show this message and exit. Examples: # Serve the tools that write nothing, as an MCP client starts the server $ desflow mcp # Also serve the tools that run models and write files $ desflow mcp --allow-changes ``` # desflow examples The help of `desflow examples`, generated from the command's code. [Command Line](https://jaehyeon.me/desflow/latest/cli/#get-an-example) uses this one on the shop, and its [What It Is](https://jaehyeon.me/desflow/latest/cli/#what-it-is) lists every command. ```text Usage: desflow examples [OPTIONS] COMMAND [ARGS]... List the examples, or download one at the version you have installed. Options: --help Show this message and exit. Commands: list List the examples, with what each shows and what it needs. get Download an example into ///, at the installed... Examples: # List the examples $ desflow examples list # Download the YAML version of one $ desflow examples get local --api yaml ``` # desflow examples list The help of `desflow examples list`, generated from the command's code. [Command Line](https://jaehyeon.me/desflow/latest/cli/#get-an-example) uses this one on the shop, and its [What It Is](https://jaehyeon.me/desflow/latest/cli/#what-it-is) lists every command. ```text Usage: desflow examples list [OPTIONS] List the examples, with what each shows and what it needs. Options: --help Show this message and exit. Examples: # List the examples, with what each shows and the service it needs $ desflow examples list ``` # desflow examples get The help of `desflow examples get`, generated from the command's code. [Command Line](https://jaehyeon.me/desflow/latest/cli/#get-an-example) uses this one on the shop, and its [What It Is](https://jaehyeon.me/desflow/latest/cli/#what-it-is) lists every command. ```text Usage: desflow examples get [OPTIONS] {name} Download an example into ///, at the installed release. Arguments: name The example, as `desflow examples` lists it. [required] Options: --api Only this version: yaml, builder or low-level. --dest The folder to download into. [default: .] --ref A git tag or branch. Defaults to the installed release's tag. --force / --no-force Replace files that are already there. [default: no- force] --help Show this message and exit. Examples: # Download the three versions of an example into ./local/ $ desflow examples get local # Download only the YAML version into another folder $ desflow examples get local --api yaml --dest work # Download it from the main branch $ desflow examples get local --ref main ``` # Integrations # Integrations desflow runs from the tools people already use. An orchestrator such as Airflow runs a study as one task of a pipeline. An AI assistant gets the skill and the desflow commands from the plugin, which [AI Assistants](https://jaehyeon.me/desflow/latest/ai/index.md) describes. ______________________________________________________________________ ## Pages | Page | What it does | | --------------------------------------------------------------------------- | -------------------------------------------------------------------------- | | [Airflow](https://jaehyeon.me/desflow/latest/integrations/airflow/index.md) | a DAG whose task runs the shop in Python and returns its figures | | [Dagster](https://jaehyeon.me/desflow/latest/integrations/dagster/index.md) | an asset that runs the shop in Python and keeps its figures as metadata | | [Prefect](https://jaehyeon.me/desflow/latest/integrations/prefect/index.md) | a flow whose task runs the shop in Python and returns its figures | | [Kestra](https://jaehyeon.me/desflow/latest/integrations/kestra/index.md) | a flow whose Python task installs desflow in a container and runs the shop | ______________________________________________________________________ ## One Shop for Every Orchestrator The four orchestrator pages run one blueprint, `shop.yaml`. The shop takes an order every 2 seconds on average, and a packer takes 3 seconds on average to pack one. `factor: 0` runs the model as fast as it can, so an hour of simulated time ends in under a second: ```yaml # The shop that every page of the Integrations section runs from an orchestrator. An # order comes every 2 seconds on average, and the packers come from PACKERS, 2 when # it is not set. factor: 0 runs it as fast as it can, not at wall-clock speed. # Run it with: desflow run shop.yaml --var PACKERS=3 --until 3600 --seed 7 \ # --summary result.json simulation: {sim_id: Shop, factor: 0, random_seed: 42} resources: packers: {current_cap: "${PACKERS:-2}", max_cap: 5} services: packing: {dist: normal, mean: 3 s, std: 0.5 s} arrivals: orders: {dist: exponential, rate: 0.5, spawn: pack} tasks: pack: service: packing resource: packers payload: {event_type: order_packed} ``` Each page runs the shop with three packers for one simulated hour, at seed 7. In a terminal, this command does the same and writes the run's statistics to `result.json`: ```bash desflow run shop.yaml --var PACKERS=3 --until 3600 --seed 7 --summary result.json ``` ______________________________________________________________________ ## Figures Each Page Reads The Airflow, Dagster and Prefect pages call desflow in Python and read three of the run's statistics. The Kestra page runs the command and logs the whole file that `--summary` writes, whose keys [Write the Result to a File](https://jaehyeon.me/desflow/latest/user-guide/results/replications/#write-the-result-to-a-file) lists. The three statistics are: - `tasks.pack.finished`: the orders packed. - `tasks.pack.wait_mean`: the mean wait for a packer, in seconds. - `resources.packers.utilization_avg`: the packers' mean utilisation over the run, in percent. The fixed seed gives every orchestrator the same figures as the command run in a terminal. On the Airflow, Dagster and Prefect pages, an error in the run raises an exception, which fails the task. On the Kestra page, the command exits with 0 when the run finishes or is stopped by Ctrl+C or SIGTERM, 1 when the blueprint cannot be loaded, and 2 when a file is missing or an option is refused, and Kestra fails the task on any code other than 0. # Airflow Run a desflow study as a task of an Airflow DAG, and pass its figures to later tasks. The task calls desflow in Python and returns the figures. ______________________________________________________________________ ## Before You Start - [Integrations](https://jaehyeon.me/desflow/latest/integrations/#one-shop-for-every-orchestrator) shows the shop and the figures each page reads. - Install desflow 1.1 or later with a recent version of Airflow. Any version of Airflow that installs alongside desflow 1.1 or later works. On Airflow 2, import `dag` and `task` from `airflow.decorators` instead of `airflow.sdk`: ```bash pip install "desflow>=1.1" apache-airflow ``` - Put `shop.yaml` and `airflow_dag.py` in the DAGs folder, which is `~/airflow/dags` unless `AIRFLOW_HOME` names another folder for Airflow's files. ______________________________________________________________________ ## Steps ### Write the DAG The `run_shop` task loads `shop.yaml` from the DAG's folder with three packers, runs one simulated hour at seed 7, and returns the three figures. Airflow keeps the returned dictionary as the task's XCom value, so a later task can take it as an argument. `with_stats("typical")` switches on the statistics the figures come from, because the mean wait needs the `typical` level. desflow is imported inside the task, so the scheduler does not import it each time it parses the DAG file. An error in the run raises an exception, which fails the task: ```python """An Airflow DAG whose task runs the shop with desflow and returns its figures. Put this file and shop.yaml in the DAGs folder. `python airflow_dag.py` runs the DAG once, in this process, with no scheduler. """ from pathlib import Path from airflow.sdk import dag, task # The folder that holds this file and shop.yaml FOLDER = Path(__file__).resolve().parent # The figures the task returns FIGURES = ( "tasks.pack.finished", "tasks.pack.wait_mean", "resources.packers.utilization_avg", ) @dag(schedule=None, catchup=False) def shop_study(): @task def run_shop(packers: int = 3) -> dict: # Imported here, so parsing the DAG file does not import desflow from desflow import SimulationContext app = SimulationContext.from_yaml( FOLDER / "shop.yaml", variables={"PACKERS": str(packers)} ) app.random_seed = 7 app.with_stats("typical") # keeps the mean wait as well as the counts app.run(until=3600) readings = app.env.stats.readings() return {name: readings[f"Shop.stats.{name}"] for name in FIGURES} run_shop() study = shop_study() if __name__ == "__main__": run = study.test() print(run.get_task_instance("run_shop").xcom_pull(task_ids="run_shop")) ``` ### Run the DAG Once `dag.test()` runs every task of one DAG run in the current process, with no scheduler or API server. It needs Airflow's metadata database, which `airflow db migrate` creates as a SQLite file in Airflow's home folder. Run these from the DAGs folder: ```bash # From the DAGs folder, ~/airflow/dags unless AIRFLOW_HOME names another home airflow db migrate python airflow_dag.py ``` ______________________________________________________________________ ## Check the Result Airflow logs each task as it runs, with desflow's log lines inside `run_shop`'s output. The last line the script prints is the value of `run_shop`: ```text {'resources.packers.utilization_avg': 49.47475468873524, 'tasks.pack.finished': 1775, 'tasks.pack.wait_mean': 0.25614739363776756} ``` Three packers packed 1775 orders in the hour, and an order waited 0.26 seconds for a packer on average. These are the figures that `desflow run shop.yaml --var PACKERS=3 --until 3600 --seed 7 --summary result.json` writes to `result.json` in a terminal. In a deployed Airflow, the scheduler runs the DAG instead of `python airflow_dag.py`, and each worker that runs `run_shop` needs desflow installed and the two files in its DAGs folder. ______________________________________________________________________ ## Sources A task's return value as its XCom value is described in Airflow's [TaskFlow](https://airflow.apache.org/docs/apache-airflow/3.4.0/core-concepts/taskflow.html), and imports kept inside a task in [Best Practices](https://airflow.apache.org/docs/apache-airflow/3.4.0/best-practices.html#top-level-python-code). `dag.test()` and the metadata database it needs are described in [Debugging Airflow DAGs](https://airflow.apache.org/docs/apache-airflow/3.4.0/core-concepts/debug.html). # Dagster Run a desflow study as a Dagster asset, and keep its figures as the asset's metadata. The asset calls desflow in Python and returns the figures. ______________________________________________________________________ ## Before You Start - [Integrations](https://jaehyeon.me/desflow/latest/integrations/#one-shop-for-every-orchestrator) shows the shop and the figures each page reads. - Install desflow 1.1 or later with a recent version of Dagster. Any version of Dagster that installs alongside desflow 1.1 or later works: ```bash pip install "desflow>=1.1" dagster ``` - Put `shop.yaml` and `dagster_asset.py` in one folder. ______________________________________________________________________ ## Steps ### Write the Asset The asset loads `shop.yaml` from its folder with three packers, runs one simulated hour at seed 7, and returns the three figures as `MaterializeResult` metadata, one number each, which Dagster shows on the asset's page. `with_stats("typical")` switches on the statistics the figures come from, because the mean wait needs the `typical` level. An error in the run raises an exception, which fails the materialization: ```python """A Dagster asset that runs the shop with desflow and keeps its figures as metadata. Keep this file beside shop.yaml. `python dagster_asset.py` materializes the asset once, in this process, with no Dagster instance. """ from pathlib import Path from dagster import Definitions, MaterializeResult, asset, materialize from desflow import SimulationContext # The folder that holds this file and shop.yaml FOLDER = Path(__file__).resolve().parent # The figures the asset keeps as metadata FIGURES = ( "tasks.pack.finished", "tasks.pack.wait_mean", "resources.packers.utilization_avg", ) @asset def shop_result() -> MaterializeResult: app = SimulationContext.from_yaml(FOLDER / "shop.yaml", variables={"PACKERS": "3"}) app.random_seed = 7 app.with_stats("typical") # keeps the mean wait as well as the counts app.run(until=3600) readings = app.env.stats.readings() return MaterializeResult( metadata={name: readings[f"Shop.stats.{name}"] for name in FIGURES} ) defs = Definitions(assets=[shop_result]) if __name__ == "__main__": result = materialize([shop_result]) metadata = result.asset_materializations_for_node("shop_result")[0].metadata print({name: value.value for name, value in metadata.items()}) ``` `defs` holds the asset for Dagster's own tools: `dagster dev -f dagster_asset.py` starts Dagster's web server and daemon on your machine with the asset in them, once `pip install dagster-webserver` has added the web server, which `dagster` does not install. The `__main__` block materializes the asset once with `materialize()`, which runs in the current process and needs no `DAGSTER_HOME`, web server or daemon. ### Materialize It Once Run this from the folder that holds the two files: ```bash python dagster_asset.py ``` ______________________________________________________________________ ## Check the Result Dagster logs each step of the run, with desflow's log lines among them. The last line the script prints is the asset's metadata: ```text {'resources.packers.utilization_avg': 49.47475468873524, 'tasks.pack.finished': 1775, 'tasks.pack.wait_mean': 0.25614739363776756} ``` These are the figures that `desflow run shop.yaml --var PACKERS=3 --until 3600 --seed 7 --summary result.json` writes to `result.json` in a terminal. ______________________________________________________________________ ## Sources `MaterializeResult` and `materialize()` are described in their docstrings in Dagster 1.13.30, in `dagster/_core/definitions/result.py` and `dagster/_core/definitions/materialize.py`. # Prefect Run a desflow study as a task of a Prefect flow, and return its figures from the flow. The task calls desflow in Python and returns the figures. ______________________________________________________________________ ## Before You Start - [Integrations](https://jaehyeon.me/desflow/latest/integrations/#one-shop-for-every-orchestrator) shows the shop and the figures each page reads. - Install desflow 1.1 or later with a recent version of Prefect 3. Any version of Prefect 3 that installs alongside desflow 1.1 or later works: ```bash pip install "desflow>=1.1" "prefect>=3,<4" ``` - Put `shop.yaml` and `prefect_flow.py` in one folder. ______________________________________________________________________ ## Steps ### Write the Flow The `run_shop` task loads `shop.yaml` from the flow's folder with the packers the flow passes, three by default, runs one simulated hour at seed 7, and returns the three figures. `with_stats("typical")` switches on the statistics the figures come from, because the mean wait needs the `typical` level. An error in the run raises an exception, which fails the task and the flow. A task called inside a flow returns its value, so the flow returns the figures: ```python """A Prefect flow whose task runs the shop with desflow and returns its figures. Keep this file beside shop.yaml. `python prefect_flow.py` runs the flow once; with no Prefect server set, Prefect starts a temporary one for the run. """ from pathlib import Path from desflow import SimulationContext from prefect import flow, task # The folder that holds this file and shop.yaml FOLDER = Path(__file__).resolve().parent # The figures the task returns FIGURES = ( "tasks.pack.finished", "tasks.pack.wait_mean", "resources.packers.utilization_avg", ) @task def run_shop(packers: int) -> dict: app = SimulationContext.from_yaml( FOLDER / "shop.yaml", variables={"PACKERS": str(packers)} ) app.random_seed = 7 app.with_stats("typical") # keeps the mean wait as well as the counts app.run(until=3600) readings = app.env.stats.readings() return {name: readings[f"Shop.stats.{name}"] for name in FIGURES} @flow def shop_study(packers: int = 3) -> dict: return run_shop(packers) if __name__ == "__main__": print(shop_study()) ``` ### Run the Flow Once Run this from the folder that holds the two files: ```bash python prefect_flow.py ``` With no Prefect server set in `PREFECT_API_URL`, Prefect's default profile starts a temporary server for the run and stops it at the end. It keeps the run in a database under `~/.prefect`, or under `PREFECT_HOME` when that is set. ______________________________________________________________________ ## Check the Result Prefect logs the flow run and each task run, and the script prints the value the flow returns: ```text {'resources.packers.utilization_avg': 49.47475468873524, 'tasks.pack.finished': 1775, 'tasks.pack.wait_mean': 0.25614739363776756} ``` These are the figures that `desflow run shop.yaml --var PACKERS=3 --until 3600 --seed 7 --summary result.json` writes to `result.json` in a terminal. ______________________________________________________________________ ## Sources The default profile, `ephemeral`, is in `prefect/settings/profiles.toml` of Prefect 3.9.3, and the default home folder in `prefect/settings/models/_defaults.py`. Flows and tasks are described in Prefect's [Write and run workflows](https://www.prefect.io/docs/v3/how-to-guides/workflows/write-and-run). # Kestra Run a desflow study as a Kestra flow, and keep its result as an output file. The flow has two tasks: a Python script task that installs desflow in a container and runs the shop, and a task that logs the result. Kestra runs the flow on its own server, so this page starts one in Docker. ______________________________________________________________________ ## Before You Start - [Integrations](https://jaehyeon.me/desflow/latest/integrations/#one-shop-for-every-orchestrator) shows the shop, the command and the figures the result file holds. - You need Docker. Kestra installs desflow inside the task's container, so your machine needs no Python package. - Put `kestra_flow.yaml` in a folder and run the commands below from it. ______________________________________________________________________ ## Steps ### Write the Flow The `run_shop` task is an `io.kestra.plugin.scripts.python.Commands` task. Kestra runs it in a new `python:3.13-slim` container, with the folder Kestra prepares for the task as the working folder: - `beforeCommands` installs desflow with pip, which puts the `desflow` command on the container's `PATH`. The task's `dependencies` list is not used, because it installs packages for Python code and does not put their commands on the `PATH`. - `inputFiles` writes `shop.yaml` into the working folder. It holds the blueprint of the overview page, so the flow needs no other file. - `commands` runs the command, and a non-zero exit fails the task. - `outputFiles` keeps `result.json` in Kestra's storage after the container is removed. The `read_result` task reads that file with `read()` and logs it: ```yaml # A Kestra flow that runs the shop with desflow and logs the result. The first task # installs desflow in a python:3.13-slim container, writes shop.yaml into its working # folder and keeps result.json as an output file. The second task reads that file. # pip install puts the desflow command on the container's PATH; the task's # `dependencies` list installs packages for Python code, without their commands. id: shop_study namespace: desflow.examples tasks: - id: run_shop type: io.kestra.plugin.scripts.python.Commands containerImage: python:3.13-slim beforeCommands: - pip install --quiet "desflow>=1.1" inputFiles: shop.yaml: | simulation: {sim_id: Shop, factor: 0, random_seed: 42} resources: packers: {current_cap: "${PACKERS:-2}", max_cap: 5} services: packing: {dist: normal, mean: 3 s, std: 0.5 s} arrivals: orders: {dist: exponential, rate: 0.5, spawn: pack} tasks: pack: service: packing resource: packers payload: {event_type: order_packed} commands: - >- desflow run shop.yaml --var PACKERS=3 --until 3600 --seed 7 --summary result.json outputFiles: - result.json - id: read_result type: io.kestra.plugin.core.log.Log message: "{{ read(outputs.run_shop.outputFiles['result.json']) }}" ``` ### Start Kestra This starts Kestra in one container, with a login for its API and its web page: ```bash # Kestra 2.0.10 on http://localhost:8080, published on the loopback address, with # a login: the user name must be an email address, and the password at least 8 # characters with an upper-case letter, a lower-case letter and a digit. The # Docker socket and /tmp let it start task containers. docker run --pull=always --rm -d --name kestra -p 127.0.0.1:8080:8080 --user=root \ -e 'KESTRA_CONFIGURATION=kestra: server: basic-auth: username: admin@example.com password: Desflow-shop-1' \ -v /var/run/docker.sock:/var/run/docker.sock -v /tmp:/tmp \ kestra/kestra:v2.0.10-slim server local ``` `server local` keeps Kestra's data inside the container and installs the plugins a flow uses when it first needs them, so the first run of the flow downloads the Python script plugin. ### Run the Flow Once These commands create the flow through Kestra's API, then run it and wait until it ends: ```bash LOGIN=admin@example.com:Desflow-shop-1 # Create the flow, then run it and wait until it ends curl -sf -u "$LOGIN" -X POST -H "Content-Type: application/x-yaml" \ --data-binary @kestra_flow.yaml http://localhost:8080/api/v1/main/flows > /dev/null curl -sf -u "$LOGIN" -X POST \ "http://localhost:8080/api/v1/main/executions/desflow.examples/shop_study?wait=true" | python3 -c 'import json, sys; e = json.load(sys.stdin); print(e["id"], e["state"]["current"])' ``` ______________________________________________________________________ ## Check the Result The last command prints the execution's id and its state, which is `SUCCESS` when both tasks succeed. The id differs on each run: ```text 2wANPoP5mcql0TtBrQBXIq SUCCESS ``` Kestra's web page at http://localhost:8080 shows the execution, with the log of `read_result`, which holds `result.json`, and the file itself under the outputs of `run_shop`. The three figures in that file are the figures of the command run in a terminal. They are these three entries of its `statistics` list: ```json {"statistic": "resources.packers.utilization_avg", "unit": "percent", "population": "time average", "value": 49.47475468873524} {"statistic": "tasks.pack.finished", "unit": "count", "population": "count over the horizon", "value": 1775} {"statistic": "tasks.pack.wait_mean", "unit": "s", "population": "started instances", "value": 0.25614739363776756} ``` Stop Kestra when you are done. `--rm` removes the container, with the flow and its executions: ```bash docker stop kestra ``` ______________________________________________________________________ ## Sources The task's properties are those of `io.kestra.plugin.scripts.python.Commands` in `kestra-io/plugin-scripts` 1.18.9 (`Commands.java` and `AbstractPythonExecScript.java`). The API paths are those of `FlowController.java` and `ExecutionController.java` in Kestra 2.0.10. The Docker command and the login rules follow Kestra's [Docker](https://kestra.io/docs/installation/docker) installation page. # AI Assistants # AI Assistants An AI coding assistant can write, check and run desflow models when it has three things: the rules of the library, the desflow commands as tools it can call, and desflow's documentation as text. This section describes each and how to install them. The parts relate as follows: | Part | What it gives the assistant | Page | | --------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------- | | Agent skill | a folder, `skills/desflow/`, of rules in the Agent Skills format: how to write, check, test and run a model, and how to run a study | [Agent Skill](https://jaehyeon.me/desflow/latest/ai/agent-skill/index.md) | | MCP server | `desflow mcp`, which offers the desflow commands to an MCP client as tools; MCP, the Model Context Protocol, is the standard an assistant uses to call a tool | [MCP Server](https://jaehyeon.me/desflow/latest/ai/mcp-server/index.md) | | Plugin | one install for Claude Code, Codex or Antigravity that adds the skill and the MCP server together | [Plugin](https://jaehyeon.me/desflow/latest/ai/plugin/index.md) | | Schema and `llms.txt` | the blueprint's JSON Schema and the pages of this site as text | below | The plugin is a package of the other two parts. It starts the MCP server without `--allow-changes`, so the assistant gets the tools that write nothing. Install the skill without the plugin when your tool has no plugin support, and set up the MCP server by hand to allow the tools that write. The plugin does not install desflow, and its MCP server needs the `mcp` extra: see [Before You Install](https://jaehyeon.me/desflow/latest/ai/plugin/#before-you-install). ______________________________________________________________________ ## Other Ways to Teach an Assistant - **Schema.** Give the assistant `https://jaehyeon.me/desflow/latest/schema/blueprint.schema.json`, or the output of `desflow schema`, to validate what it writes. - **Documentation as text.** `https://jaehyeon.me/desflow/latest/llms.txt` is an index of the pages, and `https://jaehyeon.me/desflow/latest/llms-full.txt` holds all of them in one file. # Plugin The desflow plugin adds the [skill](https://jaehyeon.me/desflow/latest/ai/agent-skill/index.md) and the [MCP server](https://jaehyeon.me/desflow/latest/ai/mcp-server/index.md) to Claude Code, Codex or Antigravity with one install. The skill gives the assistant the rules of the library, and the server gives it the desflow commands as tools. The plugin starts the server as `desflow mcp`, without `--allow-changes`, so the assistant gets the tools that write nothing. The repository holds the plugin in `plugin/`: a manifest for each tool, the MCP entry, a logo and a copy of `skills/desflow/`. `.claude-plugin/marketplace.json` and `.agents/plugins/marketplace.json` at the repository root point at that folder. Each tool copies the plugin folder, about 780 KB, into its own plugin folder. Claude Code and Codex also keep a copy of the repository, from which they read the marketplace file. ______________________________________________________________________ ## Before You Install The plugin does not install desflow. The skill tells the assistant to run `desflow` commands, and the MCP server is the `desflow mcp` command, which needs the `mcp` extra. So install desflow with the extra first: ```bash uv tool install "desflow[mcp]>=1.1" ``` ```bash pip install "desflow[mcp]>=1.1" ``` Without the extra, `desflow mcp` exits with an error that names the `pip install` command, and the assistant shows the server as failed. If you copied the skill into `~/.claude/skills/desflow/` or `.claude/skills/desflow/` for desflow 1.0, delete that folder first. Claude Code loads that copy, not the plugin's, for a request that names desflow. ______________________________________________________________________ ## Install the Plugin Run the lines of your tool. Each installs the plugin from the repository's `main` branch: ```bash claude plugin marketplace add jaehyeon-kim/desflow claude plugin install desflow@desflow ``` ```bash codex plugin marketplace add jaehyeon-kim/desflow codex plugin add desflow@desflow ``` ```bash agy plugin install https://github.com/jaehyeon-kim/desflow ``` For Claude Code and Codex, `desflow@desflow` is the plugin's name, an `@`, and the marketplace's name, which are both `desflow`. Start a new session after the install, so the tool loads the skill and the server. ______________________________________________________________________ ## Check the Install The skill is named `desflow:desflow` in Claude Code and Codex, which join the plugin's name and the skill's name with a colon. Antigravity uses the skill's own name, `desflow`. `claude plugin list` shows `desflow@desflow` as enabled, and `claude plugin details desflow` lists the skill and the MCP server. `claude mcp list` shows the server as `plugin:desflow:desflow`, and each tool is named `mcp__plugin_desflow_desflow__` in permission settings and `--allowedTools`, such as `mcp__plugin_desflow_desflow__check`. `codex plugin list` shows `desflow@desflow` as installed and enabled. `agy plugin list` shows `desflow` as enabled, with 1 skill and 1 MCP server. Then ask the assistant for a model, such as "write a desflow blueprint for a shop with two packers and a lunch rush, and check it". It loads the skill when the request mentions desflow or a blueprint, and it can call the MCP tool `check`. ______________________________________________________________________ ## Update the Plugin A new desflow release changes the plugin's version. Upgrade desflow first, with `uv tool upgrade desflow` or `pip install --upgrade "desflow[mcp]"`, so the skill and the command are of one release. Then update the plugin with the same tool: `claude plugin update desflow@desflow`, then start a new session. `codex plugin marketplace upgrade desflow` fetches the repository again and reinstalls the plugin from it. Run `agy plugin install https://github.com/jaehyeon-kim/desflow` again. ______________________________________________________________________ ## Install Without the Plugin Another assistant that reads the Agent Skills format takes the skill as a folder, `skills/desflow/`, which holds the same files as the plugin's copy. Take it from the repository at the tag of the release you installed: `v` followed by what `desflow --version` prints. For Claude Code, `~/.claude/skills/desflow/` is for every project and `.claude/skills/desflow/` in a project is for that project. These lines copy it for every project: ```bash # The source of the installed release, which holds the skill src=$(mktemp -d) git clone --depth 1 --branch "v$(desflow --version)" https://github.com/jaehyeon-kim/desflow "$src" && mkdir -p ~/.claude/skills && rm -rf ~/.claude/skills/desflow && cp -R "$src/skills/desflow" ~/.claude/skills/desflow rm -rf "$src" ``` The lines clone into a new private folder, replace an earlier copy of the skill only when the clone succeeds, and remove the clone, so they also update the skill to a newer release. If `CLAUDE_CONFIG_DIR` is set, use that folder in place of `~/.claude`. With the GitHub CLI 2.90.0 or later, one command does the copy. `gh skill install` is a preview command of the GitHub CLI. The path `skills/desflow` names the folder, because the repository holds a second copy in the plugin, and `--pin` takes the release you installed: ```bash gh skill install jaehyeon-kim/desflow skills/desflow --pin "v$(desflow --version)" \ --agent claude-code --scope user ``` `--scope user` installs for every project, in your home folder. `--scope project`, the default, installs for the current project, inside its git repository. Another assistant takes its own `--agent` value, listed in `gh skill install --help`. Check that the folder holds `SKILL.md`: ```bash ls ~/.claude/skills/desflow/SKILL.md ``` In Claude Code, `/skills` lists the loaded skills, and `desflow` must be among them. After a project copy, check `.claude/skills/desflow/SKILL.md` in the project instead. [MCP Server](https://jaehyeon.me/desflow/latest/ai/mcp-server/#add-it-to-an-assistant) adds the server to an assistant without the plugin. ______________________________________________________________________ ## Sources The install, list and update commands are those of each tool's own help: `claude plugin --help` in Claude Code 2.1.326, `codex plugin --help` in codex-cli 0.166.0 and `agy plugin help` in Antigravity 1.5.12. The skill's name in each tool follows Claude Code's [plugins reference](https://code.claude.com/docs/en/plugins-reference) and Codex's source (`ext/skills/src/loader/namespace.rs`). The folder layout and the `SKILL.md` fields follow the [Agent Skills specification](https://agentskills.io/specification), and the `gh skill install` flags are those of `gh skill install --help` in GitHub CLI 2.95.0. # Agent Skill The desflow skill gives an AI coding assistant the rules of the library, so that it writes, checks, tests and runs desflow models instead of guessing them. It is one of the ways desflow makes a simulation quicker to build. A [YAML blueprint](https://jaehyeon.me/desflow/latest/user-guide/writing-a-model/blueprints/index.md) describes a whole model with no Python. The skill lets an assistant write that blueprint for you and check it. [Models from history](https://jaehyeon.me/desflow/latest/about/roadmap/#easier-to-create-simulations), planned after 1.0, start a model from an event log. The skill is a folder, `skills/desflow/`, in the Agent Skills format that Claude Code and other assistants read. An assistant that supports the format loads the skill when a request mentions desflow, a blueprint, a test of a simulation model, or a SimPy model that streams records. The folder is generated from the code, so it lists what the release has. [Plugin](https://jaehyeon.me/desflow/latest/ai/plugin/index.md) installs the skill in Claude Code, Codex or Antigravity, together with the [MCP server](https://jaehyeon.me/desflow/latest/ai/mcp-server/index.md), or copies the folder for another assistant. ______________________________________________________________________ ## Tasks Each page gives the request to type, what the skill tells the assistant to do, and the result on one example: the shop of the [Learn tutorial](https://jaehyeon.me/desflow/latest/learn/first-model/first-simulation/index.md), one packer and an order every 2 seconds, drafted from a description in words. | Task | What the assistant gives you | | ------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------- | | [Draft a Model](https://jaehyeon.me/desflow/latest/ai/draft-a-model/index.md) | a blueprint from a description of a process, with each assumed number marked, checked against queueing theory | | [Write Tests](https://jaehyeon.me/desflow/latest/ai/write-tests/index.md) | tests of the statistics with `desflow test`, with expected values taken from the request | | [Run a Study](https://jaehyeon.me/desflow/latest/ai/run-a-study/index.md) | replications with a confidence interval, and a comparison of designs with `desflow experiment` | | [Fit a Distribution](https://jaehyeon.me/desflow/latest/ai/fit-a-distribution/index.md) | a distribution fitted to measured times with `desflow fit`, loaded into the model | | [Write Another Form](https://jaehyeon.me/desflow/latest/ai/write-another-form/index.md) | the Builder and Low-level forms of a blueprint, which give the same records | | [Port a SimPy Program](https://jaehyeon.me/desflow/latest/ai/port-a-simpy-program/index.md) | a desflow model that does what a SimPy program does, compared with the program's output | ______________________________________________________________________ ## Sources The folder layout and the `SKILL.md` fields follow the [Agent Skills specification](https://agentskills.io/specification). # Draft a Model Describe a process in your own words, and an assistant with the skill turns it into a blueprint. It marks every number it had to assume, checks the load against queueing theory, and runs a study before it gives you an answer. The GIF follows one request, the packing shop of the [Learn tutorial](https://jaehyeon.me/desflow/latest/learn/first-model/first-simulation/index.md), through the steps the skill teaches: The sections below hold each step's text, so you can copy the request and check each answer. ______________________________________________________________________ ## Ask Paste the request into an assistant that has the skill: ```text A shop packs customer orders. An order arrives about every 2 seconds. One packer packs each order in about 1.5 seconds. How long does an order wait? ``` ______________________________________________________________________ ## Draft The skill tells the assistant to start from the nearest example (`desflow examples list`), and to build the model in stages, running the file after each one. It asks you for the numbers the description does not give. It also settles what the records are for, and asks when the description does not say. Records that feed a pipeline, a model or a dashboard come from one task that writes each record in its final form, with no service, wait or resource that no column needs. A question about waits, queues or how busy a resource is needs the steps that change them. When it has to assume a number, it marks it with a comment and lists the assumed numbers first in its reply, because you must confirm them. The description does not say whether orders arrive at random or how much the packing time varies. The draft assumes both: ```yaml simulation: sim_id: Shop factor: 0 # no pacing: the run ends as soon as it is done random_seed: 42 # a fixed date, so two runs give the same records logical_start_time: '2026-01-05T09:00:00Z' resources: packers: {current_cap: 1, max_cap: 1} # said: one packer services: # said: 1.5 seconds; assumed: every order takes the same time packing: {dist: constant, value: 1.5} arrivals: # said: an order every 2 seconds on average; assumed: orders arrive at random orders: {dist: exponential, rate: 0.5, spawn: pack_order} tasks: pack_order: service: packing resource: packers payload: {event_type: order_packed} ``` ```python app = ( SimulationContext( sim_id="Shop", factor=0, # no pacing: the run ends as soon as it is done random_seed=42, # a fixed date, so two runs give the same records logical_start_time=datetime(2026, 1, 5, 9, 0, tzinfo=timezone.utc), ) .add_resource("packers", current_cap=1, max_cap=1) # said: one packer # said: 1.5 seconds; assumed: every order takes the same time .add_service("packing", dist="constant", value=1.5) # said: an order every 2 seconds on average; assumed: orders arrive at random .add_arrival("orders", dist="exponential", rate=0.5) ) @app.task(service_id="packing", resource_id="packers") def pack_order(task_id: int): return {"event_type": "order_packed"} @app.arrival_loop("orders") def order_generator(context: SimulationContext): task_id = 0 while True: order = yield context.wait_for_arrival("orders") context.spawn(pack_order(task_id, entity=order)) task_id += 1 ``` ```python PARAMS = SimParameter( sim_id="Shop", # said: an order every 2 seconds on average; assumed: orders arrive at random arrival={"orders": DistributionConfig(dist="exponential", rate=0.5)}, # said: 1.5 seconds; assumed: every order takes the same time service={"packing": DistributionConfig(dist="constant", value=1.5)}, resources={"packers": CapacityConfig(current_cap=1, max_cap=1)}, # said: one packer ) SEED = 42 # a fixed date, so two runs give the same records START = datetime(2026, 1, 5, 9, 0, tzinfo=timezone.utc) def pack_order(env, sampler, packers, key, task_id): """One order: wait for a packer, pack it, release the packer.""" path_id = "Shop.service.packing" def publish(value): env.publish_event(key, value, task="pack_order", instance=task_id) publish( {"path_id": path_id, "sim_id": "Shop", "service": "packing", "status": "queued"} ) env.stats.task_queued("pack_order", task_id) with packers.request() as request: yield request publish( { "path_id": path_id, "sim_id": "Shop", "service": "packing", "status": "started", } ) env.stats.task_started("pack_order", task_id) yield env.timeout(sampler.sample(env.registry.get_config(path_id))) publish({"event_type": "order_packed"}) env.stats.task_finished("pack_order", task_id) def order_generator(env, sampler, packers): """Starts one pack_order for every arrival, keyed orders-1, orders-2, ...""" arrival = env.registry.get_config("Shop.arrival.orders") task_id = 0 while True: yield env.timeout(sampler.sample(arrival)) env.process(pack_order(env, sampler, packers, f"orders-{task_id + 1}", task_id)) task_id += 1 ``` ______________________________________________________________________ ## Check the Load Before it runs anything, the assistant checks that the packer can keep up. `desflow explain` gives the queueing formulas' answer: ```bash desflow explain drafted_shop.yaml ``` ```text Shop `-- orders (arrival, rate 0.5/s) `-- spawn -> pack_order (task, rate 0.5/s) +-- uses packers (resource) `-- next (share 1) -> exit Resources +------------------------------------------------------------+ | resource | λ | μ | c | ρ | Wq | L | status | |----------+-----+--------+---+------+------+-------+--------| | packers | 0.5 | 0.6667 | 1 | 0.75 | 2.25 | 1.875 | OK | +------------------------------------------------------------+ Bottleneck: packers Hints for utilisation 0.85: packers with 1 unit: utilisation 0.75, at most 0.85 packers with 1 unit: utilisation 0.85 at a request every 1.76 seconds (34 a minute, 0.5667 a second) ``` The packer is busy 75% of the time (`ρ`), so the queue does not grow without limit, and the formulas give a mean wait of 2.25 seconds (`Wq`). When a model routes on a variable or has scenario steps, `desflow explain` gives no estimate, and the skill tells the assistant to check the load by hand: the work of one case, times the arrival rate, must fit inside the capacity. [Command Line](https://jaehyeon.me/desflow/latest/cli/#check-it-before-a-long-run) shows more of `desflow explain`, and [Run a Study](https://jaehyeon.me/desflow/latest/ai/run-a-study/index.md) compares designs. ______________________________________________________________________ ## Answer From Replications One run is one sample, so the skill tells the assistant to answer from replications. 20 runs of an hour, each with its own seed spawned from 42: ```bash desflow run drafted_shop.yaml --replications 20 | grep -E "^measure|wait_mean" ``` ```text measure n mean half-width (95%) tasks.pack_order.wait_mean 20 2.175 0.1305 ``` The mean wait is 2.18 ± 0.13 seconds. The interval, 2.05 to 2.31, holds the 2.25 of the formulas, so the model and the theory agree. The run starts with an empty shop and has no warm-up, which [Trusting Results](https://jaehyeon.me/desflow/latest/learn/studies/trusting-results/index.md) explains how to choose. ______________________________________________________________________ ## Check the Reply The skill tells the assistant to copy a checklist into its reply and tick each line: every behaviour the request names, the key that makes it, the record that shows it, and a run of the skill's own check on the files. Read the assumed numbers first. Then check that the answer is an interval from replications, not the result of one run. ______________________________________________________________________ ## Full Files Full files ```yaml # Drafted from a description of the packing shop. Each value says where it came from: # "said" means the description gives it, and "assumed" means the user has not confirmed # it. # Run it with: desflow run drafted_shop.yaml simulation: sim_id: Shop factor: 0 # no pacing: the run ends as soon as it is done random_seed: 42 # a fixed date, so two runs give the same records logical_start_time: '2026-01-05T09:00:00Z' resources: packers: {current_cap: 1, max_cap: 1} # said: one packer services: # said: 1.5 seconds; assumed: every order takes the same time packing: {dist: constant, value: 1.5} arrivals: # said: an order every 2 seconds on average; assumed: orders arrive at random orders: {dist: exponential, rate: 0.5, spawn: pack_order} tasks: pack_order: service: packing resource: packers payload: {event_type: order_packed} egress: - {type: Console} run: {until: 1 hour} # assumed: one hour answers the question tests: # From the request: an order every 2 seconds is 18,000 orders in 10 hours. The # count varies by about 134 between seeds (the square root of 18,000), so 540 is # four standard deviations, and an arrival rate 10% higher, 19,800, fails - name: orders_packed_in_10_hours until: 10 hours # long enough that a 10% change is more than the spread expect: tasks.pack_order.finished: {value: 18000, within: 540} # From the request: 1.5 seconds of packing for every 2 seconds is 75% of the # packer's time. Over 10 hours it varies by about 0.5 between seeds, so 2 is four # standard deviations, and the same 10% higher rate, 82.5%, fails - name: packer_busy_three_quarters until: 10 hours expect: resources.packers.utilization_avg: {value: 75, within: 2} ``` ```python """The drafted packing shop with the SimulationContext builder. The Builder form of drafted_shop.yaml: it gives the same records at the same seed. Run it with: python drafted_shop_builder.py """ from datetime import datetime, timezone from desflow import ConsoleEgress, SimulationContext app = ( SimulationContext( sim_id="Shop", factor=0, # no pacing: the run ends as soon as it is done random_seed=42, # a fixed date, so two runs give the same records logical_start_time=datetime(2026, 1, 5, 9, 0, tzinfo=timezone.utc), ) .add_resource("packers", current_cap=1, max_cap=1) # said: one packer # said: 1.5 seconds; assumed: every order takes the same time .add_service("packing", dist="constant", value=1.5) # said: an order every 2 seconds on average; assumed: orders arrive at random .add_arrival("orders", dist="exponential", rate=0.5) ) @app.task(service_id="packing", resource_id="packers") def pack_order(task_id: int): return {"event_type": "order_packed"} @app.arrival_loop("orders") def order_generator(context: SimulationContext): task_id = 0 while True: order = yield context.wait_for_arrival("orders") context.spawn(pack_order(task_id, entity=order)) task_id += 1 app.add_egress(ConsoleEgress(format="json")) if __name__ == "__main__": app.run(until="1 hour") # assumed: one hour answers the question ``` ```python """The drafted packing shop on the low-level API. The Low-level form of drafted_shop.yaml: it gives the same records at the same seed. Times are in seconds. Run it with: python drafted_shop_low_level.py """ from datetime import datetime, timezone from desflow import ( CapacityConfig, ConsoleEgress, DistributionConfig, DynamicRealtimeEnvironment, DynamicResource, Sampler, SimParameter, ) PARAMS = SimParameter( sim_id="Shop", # said: an order every 2 seconds on average; assumed: orders arrive at random arrival={"orders": DistributionConfig(dist="exponential", rate=0.5)}, # said: 1.5 seconds; assumed: every order takes the same time service={"packing": DistributionConfig(dist="constant", value=1.5)}, resources={"packers": CapacityConfig(current_cap=1, max_cap=1)}, # said: one packer ) SEED = 42 # a fixed date, so two runs give the same records START = datetime(2026, 1, 5, 9, 0, tzinfo=timezone.utc) def pack_order(env, sampler, packers, key, task_id): """One order: wait for a packer, pack it, release the packer.""" path_id = "Shop.service.packing" def publish(value): env.publish_event(key, value, task="pack_order", instance=task_id) publish( {"path_id": path_id, "sim_id": "Shop", "service": "packing", "status": "queued"} ) env.stats.task_queued("pack_order", task_id) with packers.request() as request: yield request publish( { "path_id": path_id, "sim_id": "Shop", "service": "packing", "status": "started", } ) env.stats.task_started("pack_order", task_id) yield env.timeout(sampler.sample(env.registry.get_config(path_id))) publish({"event_type": "order_packed"}) env.stats.task_finished("pack_order", task_id) def order_generator(env, sampler, packers): """Starts one pack_order for every arrival, keyed orders-1, orders-2, ...""" arrival = env.registry.get_config("Shop.arrival.orders") task_id = 0 while True: yield env.timeout(sampler.sample(arrival)) env.process(pack_order(env, sampler, packers, f"orders-{task_id + 1}", task_id)) task_id += 1 def run(until=3600): # assumed: one hour answers the question env = DynamicRealtimeEnvironment(factor=0, logical_start_time=START) env.registry.register_sim_parameter(PARAMS) env.setup_egress([ConsoleEgress(format="json")]) packers = DynamicResource(env, "Shop", "packers") sampler = Sampler(seed=SEED) env.process(order_generator(env, sampler, packers)) try: env.run(until=until) finally: env.teardown() return env if __name__ == "__main__": run() ``` # Write Tests Ask for tests when a model will change, so that a change that breaks it is found. An assistant with the skill tests the statistics with `desflow test` and the records with pytest, and makes each test fail when the behaviour it covers changes. ______________________________________________________________________ ## Ask ```text Write tests for drafted_shop.yaml. Take the expected values from the request, not from a run of the model. ``` ______________________________________________________________________ ## What the Assistant Does The skill's testing guide gives the assistant these rules, each with a wrong and a right example: - Take each expected value from the request, a hand calculation or `desflow explain`, never from the model under test. - Set each tolerance from the spread between seeds: four standard deviations. - Change the number a test is about by a small amount and run the test again. It must fail. - Run every test unpaced, at a fixed seed and a fixed `logical_start_time`. - Keep each test independent of the others, so it passes alone and in any order. For the drafted shop, the request gives two values. An order every 2 seconds is 18,000 orders in 10 hours. 1.5 seconds of packing for every 2 seconds keeps the packer busy 75% of the time. A run of an hour varies too much between seeds for a 10% change to stand out, so the tests run for 10 hours: ```yaml tests: # From the request: an order every 2 seconds is 18,000 orders in 10 hours. The # count varies by about 134 between seeds (the square root of 18,000), so 540 is # four standard deviations, and an arrival rate 10% higher, 19,800, fails - name: orders_packed_in_10_hours until: 10 hours # long enough that a 10% change is more than the spread expect: tasks.pack_order.finished: {value: 18000, within: 540} # From the request: 1.5 seconds of packing for every 2 seconds is 75% of the # packer's time. Over 10 hours it varies by about 0.5 between seeds, so 2 is four # standard deviations, and the same 10% higher rate, 82.5%, fails - name: packer_busy_three_quarters until: 10 hours expect: resources.packers.utilization_avg: {value: 75, within: 2} ``` `desflow test` runs a Builder file with the same entries in a `tests.yaml` beside it. `desflow test` does not run a Low-level file. The skill's check in [Write Another Form](https://jaehyeon.me/desflow/latest/ai/write-another-form/index.md) compares its records with the YAML's. `desflow test` runs each entry once, unpaced, with no ingress and no egress: ```bash desflow test drafted_shop.yaml ``` ```text ok drafted_shop.yaml: orders_packed_in_10_hours ok drafted_shop.yaml: packer_busy_three_quarters ``` With the arrival rate 10% higher, both tests fail and name what they measured, 19,937 orders and 83% busy, so the tests check the rate they are about. For the records, the skill gives the assistant a pytest template that runs the model with the `desflow` command at three seeds and checks the records the request names. [Checking a Model](https://jaehyeon.me/desflow/latest/learn/studies/checking-a-model/index.md) shows the checks a model needs beyond tests. ______________________________________________________________________ ## Check the Reply Read where each expected value came from. A value copied from a run of the model passes whatever the model does. Ask the assistant to show a test failing on a small change to the number it covers. # Run a Study Ask for a study when you need an answer you can act on. One run is one sample, so an assistant with the skill answers from replications, with a confidence interval, and compares designs with the same seeds. ______________________________________________________________________ ## Ask ```text Does a second packer cut the mean wait of drafted_shop.yaml, and by how much? Run a study, and give the difference with its interval. ``` ______________________________________________________________________ ## What the Assistant Does The skill gives the assistant these steps: 1. Set a seed, so the study can be repeated. 1. Set a warm-up when the model needs time to reach its usual state. 1. Run replications. Each has its own seed, spawned from the study's seed. 1. Report each mean with its 95% confidence interval. 1. To compare designs, write an experiment file and run `desflow experiment`. It runs every design with the same seeds, compares them seed by seed, and writes `report.md`. For the drafted shop, the experiment runs one and two packers for an hour, 20 times each: ```yaml model: drafted_shop.yaml until: 1 h replications: 20 seed: 42 # Every design runs with the same 20 seeds, so they are compared seed by seed pairing: common measures: [tasks.pack_order.wait_mean, resources.packers.utilization_avg] variants: one: {} two: {Shop.resources.packers.max_cap: 2, Shop.resources.packers.current_cap: 2} compare: - {baseline: one, variant: two} ``` ```python "model": shop, "until": "1 h", "replications": 20, "seed": 42, # Every design runs with the same 20 seeds, so they are compared seed by seed "pairing": "common", "measures": ["tasks.pack_order.wait_mean", "resources.packers.utilization_avg"], "variants": { "one": {}, "two": { "Shop.resources.packers.max_cap": 2, "Shop.resources.packers.current_cap": 2, }, }, "compare": [{"baseline": "one", "variant": "two"}], ``` ```python "model": LowLevelModel(model, sim_id="Shop"), "until": 3600, "replications": 20, "seed": 42, # Every design runs with the same 20 seeds, so they are compared seed by seed "pairing": "common", "measures": ["tasks.pack_order.wait_mean", "resources.packers.utilization_avg"], "variants": { "one": {}, "two": { "Shop.resources.packers.max_cap": 2, "Shop.resources.packers.current_cap": 2, }, }, "compare": [{"baseline": "one", "variant": "two"}], ``` ```bash desflow experiment drafted_shop_experiment.yaml ``` The Comparisons table of `report.md` gives each difference, two packers minus one, seed by seed: ```text | Baseline | Variant | Measure | Difference | Half-width | Interval | Random streams | |---|---|---|---|---|---|---| | one | two | `tasks.pack_order.wait_mean` | -2.043 | 0.1261 | -2.169 to -1.917 | 1 shared | | one | two | `resources.packers.utilization_avg` | -37.26 | 0.4302 | -37.69 to -36.83 | 1 shared | ``` A second packer cuts the mean wait by 2.04 ± 0.13 seconds, from 2.18 to 0.13. The packers' utilisation halves, from 75% to 37%. The interval of the difference does not hold 0, so the cut is not chance. ______________________________________________________________________ ## Check the Reply Check that the answer is an interval, not one number, and that both designs ran with the same seeds. Read the report's Missing Inputs section: it names each input whose source the experiment does not state. [Trusting Results](https://jaehyeon.me/desflow/latest/learn/studies/trusting-results/index.md) explains how many replications and how long a warm-up a study needs, and [Experiments](https://jaehyeon.me/desflow/latest/user-guide/results/experiments/index.md) lists every file the experiment writes. ______________________________________________________________________ ## Full Files Full files ```yaml # Does a second packer cut the mean wait of the drafted shop, and by how much? # Run it with: desflow experiment drafted_shop_experiment.yaml experiment: second-packer question: Does a second packer cut the mean wait of an order, and by how much? model: drafted_shop.yaml until: 1 h replications: 20 seed: 42 # Every design runs with the same 20 seeds, so they are compared seed by seed pairing: common measures: [tasks.pack_order.wait_mean, resources.packers.utilization_avg] variants: one: {} two: {Shop.resources.packers.max_cap: 2, Shop.resources.packers.current_cap: 2} compare: - {baseline: one, variant: two} assumptions: - Orders arrive at random, at a steady one every 2 seconds. - Every order takes 1.5 seconds to pack. limits: [Each run starts with an empty shop and has no warm-up.] output: results/second-packer ``` ```python """Does a second packer cut the mean wait of the drafted shop, and by how much? The Builder form of drafted_shop_experiment.yaml: it gives the same comparison. Keep it beside drafted_shop_builder.py. Run it with: python drafted_shop_experiment_builder.py """ import logging from pathlib import Path from desflow import SimulationContext, load_context, run_experiment # The model logs at INFO; an experiment logs only its warnings logging.getLogger("desflow").setLevel(logging.WARNING) HERE = Path(__file__).resolve().parent def shop() -> SimulationContext: """A new drafted shop for each run, built from the builder file.""" return load_context(HERE, "drafted_shop_builder.py") EXPERIMENT = { "experiment": "second-packer", "question": "Does a second packer cut the mean wait of an order, and by how much?", "model": shop, "until": "1 h", "replications": 20, "seed": 42, # Every design runs with the same 20 seeds, so they are compared seed by seed "pairing": "common", "measures": ["tasks.pack_order.wait_mean", "resources.packers.utilization_avg"], "variants": { "one": {}, "two": { "Shop.resources.packers.max_cap": 2, "Shop.resources.packers.current_cap": 2, }, }, "compare": [{"baseline": "one", "variant": "two"}], "assumptions": [ "Orders arrive at random, at a steady one every 2 seconds.", "Every order takes 1.5 seconds to pack.", ], "limits": ["Each run starts with an empty shop and has no warm-up."], "output": "results/second-packer", } if __name__ == "__main__": result = run_experiment(EXPERIMENT) for row in result.comparisons: print(f"{row['measure']}: {row['difference']:.3f} ± {row['half_width']:.4f}") ``` ```python """Does a second packer cut the mean wait of the drafted shop, and by how much? The Low-level form of drafted_shop_experiment.yaml: it gives the same comparison. Keep it beside drafted_shop_low_level.py. Times are in seconds. Run it with: python drafted_shop_experiment_low_level.py """ import logging from drafted_shop_low_level import PARAMS, order_generator from desflow import DynamicResource, LowLevelModel, run_experiment # The model logs at INFO; an experiment logs only its warnings logging.getLogger("desflow").setLevel(logging.WARNING) def model(env, sampler): """The drafted shop in a given environment: the experiment sets the statistics.""" env.registry.register_sim_parameter(PARAMS) packers = DynamicResource(env, "Shop", "packers") env.process(order_generator(env, sampler, packers)) EXPERIMENT = { "experiment": "second-packer", "question": "Does a second packer cut the mean wait of an order, and by how much?", "model": LowLevelModel(model, sim_id="Shop"), "until": 3600, "replications": 20, "seed": 42, # Every design runs with the same 20 seeds, so they are compared seed by seed "pairing": "common", "measures": ["tasks.pack_order.wait_mean", "resources.packers.utilization_avg"], "variants": { "one": {}, "two": { "Shop.resources.packers.max_cap": 2, "Shop.resources.packers.current_cap": 2, }, }, "compare": [{"baseline": "one", "variant": "two"}], "assumptions": [ "Orders arrive at random, at a steady one every 2 seconds.", "Every order takes 1.5 seconds to pack.", ], "limits": ["Each run starts with an empty shop and has no warm-up."], "output": "results/second-packer", } if __name__ == "__main__": result = run_experiment(EXPERIMENT) for row in result.comparisons: print(f"{row['measure']}: {row['difference']:.3f} ± {row['half_width']:.4f}") ``` # Fit a Distribution Ask for a fit when you have measured times, such as packing times taken at the bench, and want the model to draw from a distribution that matches them. An assistant with the skill fits every family with `desflow fit` and loads the best fit into the model. ______________________________________________________________________ ## Ask ```text packing_times.csv holds 40 packing times measured at the bench, in seconds, in the column packing_seconds. Fit a distribution to them, and use it for packing in drafted_shop.yaml. ``` ______________________________________________________________________ ## What the Assistant Does The skill gives the assistant one command. It fits every family to the column, ranks the fits, and writes the best as YAML: ```bash desflow fit packing_times.csv --column packing_seconds --lower 0 --out fitted/packing.yaml ``` `--lower 0` says a time cannot be below 0. The command needs the `fit` extra, which adds scipy and matplotlib: `uv tool install "desflow[fit]"`. The assistant then puts the file where the service was, with `packing: !include fitted/packing.yaml` under `services`. ______________________________________________________________________ ## Example [Fitting the Inputs](https://jaehyeon.me/desflow/latest/learn/inputs/fit-the-inputs/index.md) fits the shop's 40 packing times with this command, and shows the table of families it ranks, a plot of the fit, and the file it writes. The best fit is not always the right choice. On that page the triangular has the lowest AIC, and the gamma is 0.11 behind, too close to tell apart. The two give different mean waits, and only the gamma keeps the data's mean. ______________________________________________________________________ ## Check the Reply Ask which families came close to the best fit, and whether the choice changes the answer. Look at the plot that `--plot` draws: the data and the fit should cover the same range. [Input Fitting](https://jaehyeon.me/desflow/latest/user-guide/model-parts/input-fitting/index.md) describes every option of `desflow fit`. # Write Another Form Ask for the Builder or Low-level form of a blueprint when the model needs Python, such as a payload function, or SimPy itself. An assistant with the skill writes a form that gives the same records as the blueprint, and checks that it does. ______________________________________________________________________ ## Ask ```text Write the Builder and Low-level forms of drafted_shop.yaml. They must give the same records as the YAML at the same seed. ``` ______________________________________________________________________ ## What the Assistant Does The skill gives the assistant the rules that keep the forms equal: - A time in YAML and in the Builder takes a unit. The Low-level `DistributionConfig` takes seconds only, so the unit goes in a comment. - The Low-level form draws each time through `sampler.sample(env.registry.get_config("."))`, as the YAML does, so it draws the same numbers at the same seed. - Builder and Low-level code use only the names `from desflow import ...` gives, never a private attribute. - A Python file runs with `python ` and prints its records with `ConsoleEgress(format="json")`. Then it runs the skill's check on the three files. The check runs each form at the model's seed and the two after it, and compares every record with the YAML's: ```bash python /scripts/check_model.py drafted_shop.yaml drafted_shop_builder.py drafted_shop_low_level.py ``` ```text ok desflow check ok imports ok runs of the Python files ok seed and start time ok records of the forms ok desflow test ``` Each line is a check that passed. A failed check names the file and line, and what to write instead. `seed and start time` fails on a model without a fixed `logical_start_time`, because the timestamps of two runs then differ, so the drafted shop sets one. ______________________________________________________________________ ## Check the Reply Check that every line of the check reads `ok`, and that the reply says it compared the forms at the model's seed and the two after it. ______________________________________________________________________ ## Full Files The three forms of the shop from [Draft a Model](https://jaehyeon.me/desflow/latest/ai/draft-a-model/index.md). [Writing a Model](https://jaehyeon.me/desflow/latest/user-guide/writing-a-model/index.md) explains how the three ways relate. Full files ```yaml # Drafted from a description of the packing shop. Each value says where it came from: # "said" means the description gives it, and "assumed" means the user has not confirmed # it. # Run it with: desflow run drafted_shop.yaml simulation: sim_id: Shop factor: 0 # no pacing: the run ends as soon as it is done random_seed: 42 # a fixed date, so two runs give the same records logical_start_time: '2026-01-05T09:00:00Z' resources: packers: {current_cap: 1, max_cap: 1} # said: one packer services: # said: 1.5 seconds; assumed: every order takes the same time packing: {dist: constant, value: 1.5} arrivals: # said: an order every 2 seconds on average; assumed: orders arrive at random orders: {dist: exponential, rate: 0.5, spawn: pack_order} tasks: pack_order: service: packing resource: packers payload: {event_type: order_packed} egress: - {type: Console} run: {until: 1 hour} # assumed: one hour answers the question tests: # From the request: an order every 2 seconds is 18,000 orders in 10 hours. The # count varies by about 134 between seeds (the square root of 18,000), so 540 is # four standard deviations, and an arrival rate 10% higher, 19,800, fails - name: orders_packed_in_10_hours until: 10 hours # long enough that a 10% change is more than the spread expect: tasks.pack_order.finished: {value: 18000, within: 540} # From the request: 1.5 seconds of packing for every 2 seconds is 75% of the # packer's time. Over 10 hours it varies by about 0.5 between seeds, so 2 is four # standard deviations, and the same 10% higher rate, 82.5%, fails - name: packer_busy_three_quarters until: 10 hours expect: resources.packers.utilization_avg: {value: 75, within: 2} ``` ```python """The drafted packing shop with the SimulationContext builder. The Builder form of drafted_shop.yaml: it gives the same records at the same seed. Run it with: python drafted_shop_builder.py """ from datetime import datetime, timezone from desflow import ConsoleEgress, SimulationContext app = ( SimulationContext( sim_id="Shop", factor=0, # no pacing: the run ends as soon as it is done random_seed=42, # a fixed date, so two runs give the same records logical_start_time=datetime(2026, 1, 5, 9, 0, tzinfo=timezone.utc), ) .add_resource("packers", current_cap=1, max_cap=1) # said: one packer # said: 1.5 seconds; assumed: every order takes the same time .add_service("packing", dist="constant", value=1.5) # said: an order every 2 seconds on average; assumed: orders arrive at random .add_arrival("orders", dist="exponential", rate=0.5) ) @app.task(service_id="packing", resource_id="packers") def pack_order(task_id: int): return {"event_type": "order_packed"} @app.arrival_loop("orders") def order_generator(context: SimulationContext): task_id = 0 while True: order = yield context.wait_for_arrival("orders") context.spawn(pack_order(task_id, entity=order)) task_id += 1 app.add_egress(ConsoleEgress(format="json")) if __name__ == "__main__": app.run(until="1 hour") # assumed: one hour answers the question ``` ```python """The drafted packing shop on the low-level API. The Low-level form of drafted_shop.yaml: it gives the same records at the same seed. Times are in seconds. Run it with: python drafted_shop_low_level.py """ from datetime import datetime, timezone from desflow import ( CapacityConfig, ConsoleEgress, DistributionConfig, DynamicRealtimeEnvironment, DynamicResource, Sampler, SimParameter, ) PARAMS = SimParameter( sim_id="Shop", # said: an order every 2 seconds on average; assumed: orders arrive at random arrival={"orders": DistributionConfig(dist="exponential", rate=0.5)}, # said: 1.5 seconds; assumed: every order takes the same time service={"packing": DistributionConfig(dist="constant", value=1.5)}, resources={"packers": CapacityConfig(current_cap=1, max_cap=1)}, # said: one packer ) SEED = 42 # a fixed date, so two runs give the same records START = datetime(2026, 1, 5, 9, 0, tzinfo=timezone.utc) def pack_order(env, sampler, packers, key, task_id): """One order: wait for a packer, pack it, release the packer.""" path_id = "Shop.service.packing" def publish(value): env.publish_event(key, value, task="pack_order", instance=task_id) publish( {"path_id": path_id, "sim_id": "Shop", "service": "packing", "status": "queued"} ) env.stats.task_queued("pack_order", task_id) with packers.request() as request: yield request publish( { "path_id": path_id, "sim_id": "Shop", "service": "packing", "status": "started", } ) env.stats.task_started("pack_order", task_id) yield env.timeout(sampler.sample(env.registry.get_config(path_id))) publish({"event_type": "order_packed"}) env.stats.task_finished("pack_order", task_id) def order_generator(env, sampler, packers): """Starts one pack_order for every arrival, keyed orders-1, orders-2, ...""" arrival = env.registry.get_config("Shop.arrival.orders") task_id = 0 while True: yield env.timeout(sampler.sample(arrival)) env.process(pack_order(env, sampler, packers, f"orders-{task_id + 1}", task_id)) task_id += 1 def run(until=3600): # assumed: one hour answers the question env = DynamicRealtimeEnvironment(factor=0, logical_start_time=START) env.registry.register_sim_parameter(PARAMS) env.setup_egress([ConsoleEgress(format="json")]) packers = DynamicResource(env, "Shop", "packers") sampler = Sampler(seed=SEED) env.process(order_generator(env, sampler, packers)) try: env.run(until=until) finally: env.teardown() return env if __name__ == "__main__": run() ``` # Port a SimPy Program Ask for a port when you have a SimPy program and want its records streamed, its parameters changed during a run, or its study run with desflow's tools. An assistant with the skill writes a desflow model that does what the program does, and compares the two outputs. ______________________________________________________________________ ## Ask ```text Port shop.py, a SimPy program, to desflow. Keep its behaviour, and compare its mean wait with the desflow model's. ``` ______________________________________________________________________ ## What the Assistant Does The skill gives the assistant a table of the places where desflow behaves differently from SimPy, each with what to write in the port. It checks each row against the program before it writes the model. Some of the rows: - A program that counts time in minutes has each time converted to its unit, such as `mean: 4 min`, because a bare number is seconds. - A signal fires once by default. One that the program fires more than once gets `once: false`. - A `put` with no `yield` in the program becomes a `put` with `wait: false`, which goes on at once. - A failure no task handles stops the run. A program that goes on after a child process fails gets `on_unhandled_failure: continue`. It picks the way to write the model as for any model: YAML when the program is resources, arrivals and tasks, and the Low-level API when it needs SimPy itself. Then it runs both and compares them: the records with `desflow run --sample`, or the statistics over replications, within their intervals. ______________________________________________________________________ ## Example [Coming from SimPy](https://jaehyeon.me/desflow/latest/simpy/coming-from-simpy/index.md) ports the shop, written as a plain SimPy program in the four classes most tutorials teach. Both versions run 10 times for an hour, and their mean waits agree within their intervals. [SimPy Examples](https://jaehyeon.me/desflow/latest/simpy/examples/index.md) ports the seven examples that ship with SimPy, each in YAML, the Builder and the Low-level API, and compares each with the program's output. ______________________________________________________________________ ## Check the Reply Check that the reply names each row of the table that applies to the program, and what the port writes for it. Then check the comparison: the same records at the same times, or statistics whose intervals overlap. [SimPy Compatibility](https://jaehyeon.me/desflow/latest/simpy/compatibility/index.md) lists every SimPy feature with its form in desflow. # MCP Server `desflow mcp` serves the desflow commands as tools to an AI assistant on the same machine. MCP, the Model Context Protocol, lets an assistant find the tools of a server and call them, each with named parameters. The assistant's MCP client starts `desflow mcp` as a process and exchanges messages with it over the process's standard input and output. Each tool runs one desflow command, named in the tables below, in the server's process, so it checks and refuses its arguments as the command does. The [plugin](https://jaehyeon.me/desflow/latest/ai/plugin/index.md) starts the server for Claude Code, Codex and Antigravity, with the [skill](https://jaehyeon.me/desflow/latest/ai/agent-skill/index.md). This page sets the server up for another assistant, or for one without the plugin, and calls its tools from a Python script. ______________________________________________________________________ ## Install The server needs the `mcp` extra: ```bash uv tool install "desflow[mcp]>=1.1" ``` ```bash pip install "desflow[mcp]>=1.1" ``` Without the extra, `desflow mcp` exits with an error that names the `pip install` command. The scripts on this page also import the `mcp` package, so run them where `pip install "desflow[mcp]>=1.1"` installed it, such as a virtual environment of their own. `uv tool install` keeps desflow in an environment that a script cannot import from. ______________________________________________________________________ ## Tools That Write Nothing The server always offers these seven tools. They write nothing themselves, but `check`, `explain` and `test` load a Python builder file by running its code, which can write files, so give them only builder files you trust. Each takes the arguments and options of its command as parameters, with the same names, and `variables` fills `${NAME}` in a blueprint as `--var` does: | Tool | Command | Returns | | --------------- | ------------------------------------------ | ----------------------------------------- | | `check` | `desflow check` | what the command prints | | `explain` | `desflow explain --json` | the JSON document that the command prints | | `test` | `desflow test` | what the command prints | | `fit` | `desflow fit`, which needs the `fit` extra | what the command prints | | `dist` | `desflow dist` | what the command prints | | `schema` | `desflow schema` | the blueprint JSON Schema | | `list_examples` | `desflow examples list` | what the command prints | A tool that returns a JSON document gives it as the result's structured content and as text. A tool that returns what the command prints gives its warnings first. A tool whose command fails returns an error with the command's message. The server runs one tool at a time. ______________________________________________________________________ ## Tools That Write `desflow mcp --allow-changes` also offers four tools, and three parameters of two tools above: | Tool | Command | Returns | | ------------- | ----------------------- | -------------------------------------------------------------------------------------------------------------------------------------------- | | `run` | `desflow run --summary` | the JSON document that `--summary` writes: the run's statistics, or with `replications` the seeds, the summary and each replication's values | | `experiment` | `desflow experiment` | what the command prints | | `report` | `desflow report` | what the command prints | | `get_example` | `desflow examples get` | what the command prints | `test` gains `fix`, which writes the statistics into the expected values that differ, and `fit` gains `out` and `plot`, which write the best fit and a picture of the fits. A run sends its records to the blueprint's sinks, such as a Kafka topic or a table, and the other tools write files. The server marks the four tools, and `test` and `fit` when it offers their writing parameters, as destructive, and the others as read-only, so a client can ask before it runs one. The plugin starts the server without the option. Add the option to an assistant's settings only for a project whose sinks it may write to. The option is part of the server's entry in the assistant's settings, so a project that shares that file shares the option. [Write the Result to a File](https://jaehyeon.me/desflow/latest/user-guide/results/replications/#write-the-result-to-a-file) lists the keys of the `run` tool's document. ______________________________________________________________________ ## Add It to an Assistant The server needs the command `desflow` and the argument `mcp`. It reads a relative path in a tool call from the folder the client starts it in, which the client chooses, so ask for absolute paths when a tool does not find a file. In Claude Code, run this in the project's folder, to add the server for that project: ```bash # Writes .mcp.json in this folder claude mcp add --scope project desflow -- desflow mcp ``` In Codex, this adds the server: ```bash codex mcp add desflow -- desflow mcp ``` Another assistant that reads MCP servers from a JSON file takes this entry, under the key its documentation names: ```json { "mcpServers": { "desflow": { "command": "desflow", "args": ["mcp"] } } } ``` ______________________________________________________________________ ## List the Tools This script starts the server command given in its arguments and prints the name and description of each tool. Save it as `mcp_client.py`: ```python import sys import anyio from mcp import Client, StdioServerParameters async def main(command): """Print the name and description of each tool the server offers. Args: command: The command that starts the server, as a list of words. """ server = StdioServerParameters(command=command[0], args=command[1:]) async with Client(server) as client: for tool in (await client.list_tools()).tools: print(f"{tool.name}: {tool.description}") anyio.run(main, sys.argv[1:]) ``` This lists the tools that write nothing: ```bash python mcp_client.py desflow mcp ``` ```text check: Check that each blueprint or builder file builds, without running it, as `desflow check` does. variables fill ${NAME} as --var does. explain: Explain a model as `desflow explain --json` does: its graph, each resource's utilisation, status and wait where the queueing formulas apply, the bottleneck and the tuning hints. With verify, also run it unpaced and compare. The shape can change with its schema_version. test: Run the tests of each blueprint, or of each builder file with a tests.yaml beside it, and report the statistics that differ, as `desflow test` does. Each test runs once, unpaced, with no ingress and no egress. fit: Fit a column of a CSV file to the distribution families and rank them, as `desflow fit` does. Needs the fit extra. dist: List the distribution families, or convert a family's parameters to its mean and standard deviation and back, as `desflow dist` does. schema: Return the blueprint JSON Schema, as `desflow schema` prints it. list_examples: List the examples, with what each shows and the service it needs, as `desflow examples list` does. ``` With `--allow-changes`, the four tools that write follow, and the descriptions of `test` and `fit` name their new parameters: ```bash python mcp_client.py desflow mcp --allow-changes ``` ```text check: Check that each blueprint or builder file builds, without running it, as `desflow check` does. variables fill ${NAME} as --var does. explain: Explain a model as `desflow explain --json` does: its graph, each resource's utilisation, status and wait where the queueing formulas apply, the bottleneck and the tuning hints. With verify, also run it unpaced and compare. The shape can change with its schema_version. test: Run the tests of each blueprint, or of each builder file with a tests.yaml beside it, and report the statistics that differ, as `desflow test` does. Each test runs once, unpaced, with no ingress and no egress. With fix, write the statistics the runs gave into the expect values that differ, as --fix does. fit: Fit a column of a CSV file to the distribution families and rank them, as `desflow fit` does. Needs the fit extra. out writes the best fit as YAML, and plot draws the fits as an image, as --out and --plot do. dist: List the distribution families, or convert a family's parameters to its mean and standard deviation and back, as `desflow dist` does. schema: Return the blueprint JSON Schema, as `desflow schema` prints it. list_examples: List the examples, with what each shows and the service it needs, as `desflow examples list` does. run: Run a blueprint once, or its replications, as `desflow run --summary` does, and return the summary it writes: the statistics of the run, or the seeds, the summary and every replication's values. A run sends its records to the blueprint's sinks. measures, level and workers apply only with replications, and a call that gives them without replications is refused. variables fill ${NAME} as --var does. experiment: Run an experiment file and write its artifacts and report.md, as `desflow experiment` does. output overrides the folder the file names. report: Build an experiment's report.md again from the artifacts in its output folder, as `desflow report` does. get_example: Download an example into /// at the installed release, as `desflow examples get` does. force replaces files that are already there. ``` ______________________________________________________________________ ## Run a Model Through the Tools This script checks the shop of [Integrations](https://jaehyeon.me/desflow/latest/integrations/#one-shop-for-every-orchestrator), reads the tuning hints from its explanation, and runs it with three packers for an hour. It starts the server with `--allow-changes`, because `run` writes. Save it as `mcp_example.py` beside `shop.yaml`: ```python import anyio from mcp import Client, StdioServerParameters # The rows of the run's statistics to print FIGURES = ( "tasks.pack.finished", "tasks.pack.wait_mean", "resources.packers.utilization_avg", ) async def call(client, name, arguments): """Call one tool and stop on an error. A tool that fails returns its error as the result, so the call checks for it. Args: client: The connected MCP client. name: The tool to call. arguments: The tool's parameters. Returns: The tool's result. Raises: RuntimeError: When the tool returns an error. """ result = await client.call_tool(name, arguments) if result.is_error: raise RuntimeError(f"{name}: {result.content[0].text}") return result async def main(): """Check the shop, explain it, then run it with three packers.""" server = StdioServerParameters(command="desflow", args=["mcp", "--allow-changes"]) async with Client(server) as client: checked = await call(client, "check", {"files": ["shop.yaml"]}) # check returns what the command prints, warnings first print("--- check") print(checked.content[0].text.splitlines()[-1]) explained = await call(client, "explain", {"source": "shop.yaml"}) # explain returns the document of desflow explain --json print("--- explain") for hint in explained.structured_content["hints"]: print(hint["text"]) ran = await call( client, "run", { "file": "shop.yaml", "until": "3600", "seed": 7, "variables": {"PACKERS": "3"}, }, ) # run returns the summary that desflow run --summary writes print("--- run") statistics = ran.structured_content["statistics"] print( { row["statistic"]: row["value"] for row in statistics if row["statistic"] in FIGURES } ) anyio.run(main) ``` ```bash python mcp_example.py ``` ```text --- check ok shop.yaml (sim_id Shop) --- explain packers with 2 units: utilisation 0.75, at most 0.85 packers with 2 units: utilisation 0.85 at a request every 1.76 seconds (34 a minute, 0.5667 a second) --- run {'resources.packers.utilization_avg': 49.47475468873524, 'tasks.pack.finished': 1775, 'tasks.pack.wait_mean': 0.25614739363776756} ``` The explanation holds two packers, the blueprint's default. The run's figures are those of the command on the overview page, because the tool runs the same command. ______________________________________________________________________ ## Sources The protocol and the client's `Client` and `StdioServerParameters` are those of the [MCP Python SDK](https://github.com/modelcontextprotocol/python-sdk) 2.3.0. The `claude mcp add` and `codex mcp add` lines follow `claude mcp add --help` in Claude Code 2.1.326 and `codex mcp add --help` in codex-cli 0.166.0, and Claude Code's [MCP documentation](https://code.claude.com/docs/en/mcp) for the `.mcp.json` file that project scope writes. # Gallery # Gallery The Gallery holds end-to-end examples. Each is a complete file that you can run, and each is written three ways: as a YAML blueprint, with the builder API and with the low-level API. Its page shows the three versions in tabs. [Ways to write a simulation](https://jaehyeon.me/desflow/latest/user-guide/writing-a-model/index.md) compares the three. ## Data Generation Blueprints that generate data for a table, a stream or a test. They run unpaced and need no service unless the page says so. | Page | What it covers | | ------------------------------------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | [Data Sets](https://jaehyeon.me/desflow/latest/gallery/data-generation/data-sets/index.md) | a retail set written to three sinks, a film rental store, auction streams, a group-by table, taxi rides, labelled text and a point-in-time training set | | [Event Streams](https://jaehyeon.me/desflow/latest/gallery/data-generation/event-streams/index.md) | orders that carry their customer's tier, a stolen card that makes three large payments, stock queries, traces of nested spans and customer deletes that become Kafka tombstones | | [Processes with Queues](https://jaehyeon.me/desflow/latest/gallery/data-generation/processes-with-queues/index.md) | busy packers, a machine that wears, a falling capacity, callers who hang up, urgent tickets, shopping carts, a sign-up funnel, bets and audits | ## Simulation Models Complete models that read from or write to a service, or that run unpaced to files. | Example | What it covers | | ------------------------------------------------------------------------------------------------------------------ | -------------------------------------------------------------------------- | | [Local Simulation](https://jaehyeon.me/desflow/latest/gallery/simulation-models/local/index.md) | prints events and telemetry, with no container | | [Kafka Digital Twin](https://jaehyeon.me/desflow/latest/gallery/simulation-models/kafka/index.md) | takes updates from Kafka and publishes events and telemetry to Kafka | | [Fast-Forward to Parquet](https://jaehyeon.me/desflow/latest/gallery/simulation-models/parquet/index.md) | data generated unpaced at `factor=0.0`: a week written to Parquet | | [Fast-Forward to Iceberg](https://jaehyeon.me/desflow/latest/gallery/simulation-models/iceberg/index.md) | data generated unpaced at `factor=0.0`: a day appended to an Iceberg table | | [PostgreSQL](https://jaehyeon.me/desflow/latest/gallery/simulation-models/postgres/index.md) | writes orders to PostgreSQL and takes updates from a table | | [Redis](https://jaehyeon.me/desflow/latest/gallery/simulation-models/redis/index.md) | writes to a Redis Stream and takes updates from Pub/Sub | | [Parquet History, Kafka Live](https://jaehyeon.me/desflow/latest/gallery/simulation-models/backfill-live/index.md) | backdated history to Parquet, then live to Kafka | | [Related Records](https://jaehyeon.me/desflow/latest/gallery/simulation-models/advanced-postgres-orders/index.md) | orders and their line items, in two PostgreSQL tables | ## More Examples [Projects Using desflow](https://jaehyeon.me/desflow/latest/gallery/projects/index.md) lists public projects that generate their data with desflow. The seven programs of SimPy's own documentation, each written in desflow, are in [SimPy Examples](https://jaehyeon.me/desflow/latest/simpy/examples/index.md). Each example page says how to download and run it, and which odctl profile from [Services for the Examples](#services-for-the-examples) it needs. `desflow examples get` prints the extra an example needs, and `pip install "desflow[all]"` installs every extra, so each example runs once its profile is up. `desflow examples list` prints every example in the terminal, with the odctl profile each one needs. The list also has the shop examples, such as `stock` and `breakdowns`, which are shown on the page that teaches their feature. `desflow examples get NAME` downloads the files of the release you installed into `NAME/yaml/`, `NAME/builder/` and `NAME/low-level/`. `--api` keeps one version, `--dest` downloads into another folder, `--ref` names another tag or branch, such as `main`, and `--force` replaces files that are already there: ```bash desflow examples list desflow examples get local --api yaml --dest work ``` The second command writes `work/local/yaml/local.yaml`. ______________________________________________________________________ ## Services for the Examples Every example that needs a broker, a database or an object store gets it from [odctl](https://github.com/jaehyeon-kim/odctl), a separate CLI that manages curated Docker Compose stacks. Install it once: ```bash # With uv uv tool install "odctl>=1.0,<2" # Or with pip pip install "odctl>=1.0,<2" ``` `odctl list -d` shows every profile and the ports it publishes. The examples here use five of them: `kafka-lite`, `postgres`, `valkey`, `storage` and `catalog`. ### Starting a Profile Each example needs at most one odctl profile. Start the profile before you run the example, and stop it afterwards: | Example | Start | Stop | | -------------------------------------------------------------------------------------------- | --------------------- | --------------------------------- | | every example that `desflow examples` marks `(no service)`, such as local, parquet and stock | nothing needed | | | kafka, backfill-live | `odctl up kafka-lite` | `odctl down kafka-lite --volumes` | | postgres, related-records | `odctl up postgres` | `odctl down postgres --volumes` | | redis | `odctl up valkey` | `odctl down valkey --volumes` | | parquet with `PARQUET_FILESYSTEM=s3` | `odctl up storage` | `odctl down storage --volumes` | | iceberg | `odctl up catalog` | `odctl down catalog --volumes` | An example's YAML version needs the same profile as its builder version: `desflow examples get ` prints the profile with the run command. The Kafka and Redis profiles are not named after their service. odctl's one-broker Kafka profile is `kafka-lite` and its three-broker Kafka profile is `kafka-full`. odctl runs Valkey in place of Redis, so its Redis profile is `valkey`. The Kafka examples run on either Kafka profile, because both publish a broker at `127.0.0.1:9092`. ### Endpoints These Profiles Publish These are the addresses the examples use. Every profile publishes on your machine only, on `127.0.0.1`. Use that address rather than `localhost`, which macOS resolves to the IPv6 address `::1` first, where nothing listens. | Profile | Service | Address the examples use | | ------------ | ---------------------------------------------------- | --------------------------------------------------------------------------------------- | | `kafka-lite` | Kafka, one broker, with the Karapace schema registry | `127.0.0.1:9092`; schema registry `http://127.0.0.1:8081` | | `kafka-full` | Kafka, three brokers, with the same schema registry | `127.0.0.1:9092,127.0.0.1:9093,127.0.0.1:9094`; schema registry `http://127.0.0.1:8081` | | `postgres` | PostgreSQL, database `odctl` | `postgresql://user:password@127.0.0.1:5432/odctl` | | `valkey` | Valkey (Redis protocol) | `redis://user:password@127.0.0.1:6379/0` | | `storage` | S3-compatible object store, bucket `odctl-dev` | `http://127.0.0.1:8333`, access key `user`, secret key `password` | | `catalog` | Iceberg REST catalog, warehouse `s3://warehouse/` | `http://127.0.0.1:8181` | `odctl list -d` shows every port a profile publishes. # Data Sets Seven data sets, each generated by one blueprint: a retail set written to three sinks, a film rental store, auction streams, a group-by table, taxi rides, labelled text and a point-in-time training set. Each entry is a complete file in three forms, so you can run it, read how it is built and change it. ______________________________________________________________________ ## Before You Start The commands run from the root of a clone of the repository, where the files are in `examples/gallery/`: ```bash git clone https://github.com/jaehyeon-kim/desflow.git cd desflow ``` An entry that needs a service or an extra says so. [Services for the Examples](https://jaehyeon.me/desflow/latest/gallery/#services-for-the-examples) shows how to start the services. A file with a fixed `random_seed` and `factor: 0` prints the same records on every run, and each output block below holds the first events of the YAML file. The Builder and Low-level files publish the same records. ______________________________________________________________________ ## Entries ### Retail records go to PostgreSQL, Kafka and Parquet A shop has 20 customers and 10 products at the start and takes about one order every two seconds. Each order picks a customer and a product at random and is followed by its invoice. The reference data goes to PostgreSQL tables, the orders to a Kafka topic and the invoices to a Parquet file, each sink taking the records of its own tasks (the `when` expression of the entry). It needs a broker and a database, started with `odctl up kafka-lite` and `odctl up postgres`, and the `kafka`, `postgres`, `parquet` and `fake` extras. `KAFKA_BOOTSTRAP_SERVERS` sets the broker address and `DEST_PATH` the folder of the Parquet file (`data` by default), so this entry shows no output block here. Run it with the sample option, which stops after the first events and prints them: ```bash desflow run examples/gallery/retail_records_to_three_sinks.yaml --sample 5 ``` ```yaml # Retail records go to PostgreSQL, Kafka and Parquet. # # A shop has 20 customers and 10 products at the start and takes about one order every # two seconds. Each order picks a customer and a product at random and is followed by # its invoice. The reference data goes to PostgreSQL tables, the orders to a Kafka # topic and the invoices to a Parquet file, each sink taking the records of its own # tasks (the `when` expression of the entry). # # Needs: a broker and a database, with odctl up kafka-lite and odctl up postgres, and # the kafka, postgres, parquet and fake extras. KAFKA_BOOTSTRAP_SERVERS sets the broker # address, and DEST_PATH the folder of the Parquet file (data by default). # Run it with: desflow run examples/gallery/retail_records_to_three_sinks.yaml simulation: sim_id: Retail factor: 0 random_seed: 42 logical_start_time: 2026-01-01T00:00:00 egress: - type: Postgres when: {expr: "record.task == 'customer'"} config: connection_dsn: postgresql://user:password@127.0.0.1:5432/odctl tables: customers: columns: {customer_id: INT, name: TEXT, country: TEXT} primary_key: customer_id - type: Postgres when: {expr: "record.task == 'product'"} config: connection_dsn: postgresql://user:password@127.0.0.1:5432/odctl tables: products: columns: {product_id: INT, title: TEXT, price: REAL} primary_key: product_id - type: Kafka when: {expr: "record.task == 'order'"} config: bootstrap_servers: ${KAFKA_BOOTSTRAP_SERVERS:-localhost:9092} event_topic: retail-orders - type: Parquet when: {expr: "record.task == 'invoice'"} config: {default_path: "${DEST_PATH:-data}/invoices.parquet"} arrivals: customers: {initial: 20, spawn: customer} products: {initial: 10, spawn: product} orders: {dist: exponential, rate: 0.5, spawn: order} tasks: customer: payload: customer_id: {gen: sequence, start: 1} name: {gen: fake, method: name} country: gen: weighted options: {AU: 5, US: 3, GB: 2} product: payload: product_id: {gen: sequence, start: 1} title: gen: one_of choices: [Desk lamp, Notebook, Water bottle, Backpack, Headphones, Keyboard] price: {gen: uniform, low: 2, high: 200, decimals: 2} order: vars: product: {gen: lookup, task: product} price: {gen: var, name: product, path: price} quantity: {gen: integer, bounds: [1, 5]} payload: order_id: {gen: sequence, start: 1} customer_id: {gen: lookup, task: customer, path: customer_id} product_id: {gen: var, name: product, path: product_id} quantity: {gen: var, name: quantity} total: {gen: expr, expr: "round(price * quantity, 2)"} next: invoice invoice: payload: order_id: {gen: upstream, path: order_id} amount: {gen: upstream, path: total} run: {until: 10 min} ``` The Builder file builds the same model with the builder API and prints every record of its run: ```bash python examples/gallery/retail_records_to_three_sinks_builder.py ``` ```python """Retail records go to PostgreSQL, Kafka and Parquet, builder API. The builder version of `retail_records_to_three_sinks.yaml`: 20 customers and 10 products at the start, an order about every two seconds and an invoice for each order. The customers and products go to PostgreSQL tables, the orders to a Kafka topic and the invoices to a Parquet file. Needs: a broker and a database, with odctl up kafka-lite and odctl up postgres, and the kafka, postgres, parquet and fake extras. KAFKA_BOOTSTRAP_SERVERS sets the broker address, and DEST_PATH the folder of the Parquet file (data by default). Run it with: python examples/gallery/retail_records_to_three_sinks_builder.py """ import logging import os from datetime import datetime, timezone from desflow import ( KafkaEgress, ParquetStorageEgress, PostgresEgress, SimulationContext, ) from desflow.values import Template UNTIL = 600 DSN = "postgresql://user:password@127.0.0.1:5432/odctl" def build() -> SimulationContext: """Builds the shop, with a sink for each kind of record.""" app = SimulationContext( sim_id="Retail", factor=0, random_seed=42, logical_start_time=datetime(2026, 1, 1, tzinfo=timezone.utc), ) app.add_egress( PostgresEgress( DSN, tables={ "customers": { "columns": { "customer_id": "INT", "name": "TEXT", "country": "TEXT", }, "primary_key": "customer_id", } }, ), when=lambda record: record.get("task") == "customer", ) app.add_egress( PostgresEgress( DSN, tables={ "products": { "columns": {"product_id": "INT", "title": "TEXT", "price": "REAL"}, "primary_key": "product_id", } }, ), when=lambda record: record.get("task") == "product", ) app.add_egress( KafkaEgress( bootstrap_servers=os.environ.get( "KAFKA_BOOTSTRAP_SERVERS", "localhost:9092" ), event_topic="retail-orders", ), when=lambda record: record.get("task") == "order", ) app.add_egress( ParquetStorageEgress( default_path=f"{os.environ.get('DEST_PATH', 'data')}/invoices.parquet" ), when=lambda record: record.get("task") == "invoice", ) app.add_initial_arrival("customers", 20, spawn="customer") app.add_initial_arrival("products", 10, spawn="product") app.add_arrival("orders", "exponential", rate=0.5, spawn="order") customer_payload = Template( { "customer_id": {"gen": "sequence", "start": 1}, "name": {"gen": "fake", "method": "name"}, "country": {"gen": "weighted", "options": {"AU": 5, "US": 3, "GB": 2}}, }, name="tasks.customer", ) product_payload = Template( { "product_id": {"gen": "sequence", "start": 1}, "title": { "gen": "one_of", "choices": [ "Desk lamp", "Notebook", "Water bottle", "Backpack", "Headphones", "Keyboard", ], }, "price": {"gen": "uniform", "low": 2, "high": 200, "decimals": 2}, }, name="tasks.product", ) order_payload = Template( { "order_id": {"gen": "sequence", "start": 1}, "customer_id": {"gen": "lookup", "task": "customer", "path": "customer_id"}, "product_id": {"gen": "var", "name": "product", "path": "product_id"}, "quantity": {"gen": "var", "name": "quantity"}, "total": {"gen": "expr", "expr": "round(price * quantity, 2)"}, }, name="tasks.order", vars={ "product": {"gen": "lookup", "task": "product"}, "price": {"gen": "var", "name": "product", "path": "price"}, "quantity": {"gen": "integer", "bounds": [1, 5]}, }, ) invoice_payload = Template( { "order_id": {"gen": "upstream", "path": "order_id"}, "amount": {"gen": "upstream", "path": "total"}, }, name="tasks.invoice", ) @app.task(name="customer", history=1_000_000) def customer(task_id): """Gives one customer.""" return customer_payload @app.task(name="product", history=1_000_000) def product(task_id): """Gives one product.""" return product_payload @app.task(name="order", next="invoice") def order(task_id): """Takes one order.""" return order_payload @app.task(name="invoice") def invoice(task_id): """Bills the order.""" return invoice_payload return app if __name__ == "__main__": logging.basicConfig(level=logging.INFO, format="%(levelname)s %(message)s") build().run(until=UNTIL) ``` The Low-level file builds the model on `DynamicRealtimeEnvironment`, with plain Python processes, and prints every record of its run: ```bash python examples/gallery/retail_records_to_three_sinks_low_level.py ``` The Low-level file draws each value with `Sampler.generator()`, where the place is the key path of the blueprint's generator that makes the same value, such as `tasks.customer.payload.name`, `tasks.customer.payload.country` and `tasks.product.payload.title` and 4 more. Each draw therefore comes from the random sequence the blueprint uses at the same place, so the draws are the blueprint's. The gaps between arrivals come from `Sampler.sample` on a `DistributionConfig` whose `stream` is `arrival.orders`, the sequence the blueprint uses for its arrivals. ```python """Retail records go to PostgreSQL, Kafka and Parquet, low-level API. The low-level version of `retail_records_to_three_sinks.yaml`: plain SimPy on a `DynamicRealtimeEnvironment`, which publishes each record with `publish_event`. Each draw is made with `Sampler.generator()`, from the random sequence the blueprint's generator at that place uses, so the draws are the blueprint's. A name is drawn with a Faker that is seeded from that sequence. Needs: a broker and a database, with odctl up kafka-lite and odctl up postgres, and the kafka, postgres, parquet and fake extras. KAFKA_BOOTSTRAP_SERVERS sets the broker address, and DEST_PATH the folder of the Parquet file (data by default). Run it with: python examples/gallery/retail_records_to_three_sinks_low_level.py """ import itertools import logging import os from datetime import datetime, timezone from faker import Faker from desflow import ( DistributionConfig, DynamicRealtimeEnvironment, KafkaEgress, ParquetStorageEgress, PostgresEgress, Sampler, ) UNTIL = 600 START = datetime(2026, 1, 1, tzinfo=timezone.utc) ENVIRONMENT = {"logical_start_time": START, "timezone": "UTC"} DSN = "postgresql://user:password@127.0.0.1:5432/odctl" COUNTRIES = {"AU": 5, "US": 3, "GB": 2} TITLES = ["Desk lamp", "Notebook", "Water bottle", "Backpack", "Headphones", "Keyboard"] def weighted(rng, options): """One key of `options`, chosen by its weight, as the `weighted` generator does.""" point = rng.random() * sum(options.values()) running = 0.0 for value, weight in options.items(): running += weight if point < running: return value return value def build(env: DynamicRealtimeEnvironment) -> None: """Starts the arrivals on `env`.""" sampler = Sampler(seed=42) faker = Faker("en_US") faker.seed_instance( int(sampler.generator("tasks.customer.payload.name#fake").integers(2**32)) ) country = sampler.generator("tasks.customer.payload.country") title = sampler.generator("tasks.product.payload.title") price = sampler.generator("tasks.product.payload.price") product_row = sampler.generator("tasks.order.vars.product") quantity = sampler.generator("tasks.order.vars.quantity") customer_row = sampler.generator("tasks.order.payload.customer_id") customers: list = [] # the ids of the customers so far, oldest first products: list = [] # the products so far, oldest first counts = {"customer": 0, "product": 0, "order": 0, "invoice": 0} def publish(key, task, payload): """Publishes a finished payload as the next instance of its task.""" env.publish_event(key, payload, task=task, instance=counts[task]) counts[task] += 1 def customer(): row = { "customer_id": len(customers) + 1, "name": faker.name(), "country": weighted(country, COUNTRIES), } customers.append(row["customer_id"]) return row def product(): row = { "product_id": len(products) + 1, "title": TITLES[int(title.integers(len(TITLES)))], "price": round(2 + (200 - 2) * price.random(), 2), } products.append(row) return row def order(number): """An order, and the invoice for it at once.""" key = f"orders-{number}" chosen = products[int(product_row.integers(len(products)))] count = int(quantity.integers(1, 6)) taken = { "order_id": number, "customer_id": customers[int(customer_row.integers(len(customers)))], "product_id": chosen["product_id"], "quantity": count, "total": round(chosen["price"] * count, 2), } publish(key, "order", taken) publish(key, "invoice", {"order_id": number, "amount": taken["total"]}) gap = DistributionConfig(dist="exponential", rate=0.5) gap.stream = "arrival.orders" def source(): for number in itertools.count(1): yield env.timeout(sampler.sample(gap)) order(number) def start(name, task, make, number): yield env.timeout(0) publish(f"{name}-{number}", task, make()) env.process(source()) for number in range(1, 21): env.process(start("customers", "customer", customer, number)) for number in range(1, 11): env.process(start("products", "product", product, number)) def run() -> None: """Runs the model unpaced, with a sink for each kind of record.""" env = DynamicRealtimeEnvironment(factor=0, **ENVIRONMENT) bootstrap = os.environ.get("KAFKA_BOOTSTRAP_SERVERS", "localhost:9092") sinks = [ ( PostgresEgress( DSN, tables={ "customers": { "columns": { "customer_id": "INT", "name": "TEXT", "country": "TEXT", }, "primary_key": "customer_id", } }, ), "customer", ), ( PostgresEgress( DSN, tables={ "products": { "columns": { "product_id": "INT", "title": "TEXT", "price": "REAL", }, "primary_key": "product_id", } }, ), "product", ), ( KafkaEgress(bootstrap_servers=bootstrap, event_topic="retail-orders"), "order", ), ( ParquetStorageEgress( default_path=f"{os.environ.get('DEST_PATH', 'data')}/invoices.parquet" ), "invoice", ), ] env.setup_egress( [sink for sink, _ in sinks], predicates=[ lambda record, task=task: record.get("task") == task for _, task in sinks ], ) build(env) try: env.run(until=UNTIL) finally: env.teardown() if __name__ == "__main__": logging.basicConfig(level=logging.INFO, format="%(levelname)s %(message)s") run() ``` ### A film rental store: films, customers, rentals, payments and returns The tables have the shape of the Sakila sample database. A store has 20 films and 15 customers at the start. About one rental starts every 8 minutes, for a week. A rental names a film and a customer that exist, is paid for at once at the film's rental rate, and is returned 1 to 7 days later. It needs the `fake` extra: `pip install "desflow[fake]"`. Run it with the sample option, which stops after the first events and prints them: ```bash desflow run examples/gallery/film_rental_store.yaml --sample 5 ``` ```yaml # A film rental store: films, customers, rentals, payments and returns. # # The tables have the shape of the Sakila sample database. A store has 20 films and 15 # customers at the start. About one rental starts every 8 minutes, for a week. A rental # names a film and a customer that exist, is paid for at once at the film's rental rate, # and is returned 1 to 7 days later. # # Needs: the fake extra. # Run it with: desflow run examples/gallery/film_rental_store.yaml simulation: sim_id: Store factor: 0 random_seed: 42 logical_start_time: 2026-01-01T00:00:00 egress: - {type: Console} arrivals: films: {initial: 20, spawn: film} customers: {initial: 15, spawn: customer} rentals: {dist: exponential, rate: 0.002, spawn: rental} tasks: film: payload: film_id: {gen: sequence, start: 1} title: gen: format template: "{adjective} {noun}" names: adjective: {gen: one_of, choices: [Silent, Broken, Golden, Hidden, Last]} noun: {gen: one_of, choices: [River, Garden, Highway, Letter, Harbour]} rating: gen: weighted options: {G: 2, PG: 3, PG-13: 3, R: 3, NC-17: 1} rental_rate: {gen: one_of, choices: [0.99, 2.99, 4.99]} length: {gen: integer, bounds: [60, 180]} customer: payload: customer_id: {gen: sequence, start: 1} first_name: {gen: fake, method: first_name} last_name: {gen: fake, method: last_name} active: {gen: boolean, p: 0.9} rental: vars: film: {gen: lookup, task: film} payload: rental_id: {gen: sequence, start: 1} rental_date: {gen: now} film_id: {gen: var, name: film, path: film_id} rental_rate: {gen: var, name: film, path: rental_rate} customer_id: {gen: lookup, task: customer, path: customer_id} next: payment payment: payload: rental_id: {gen: upstream, path: rental_id} customer_id: {gen: upstream, path: customer_id} amount: {gen: upstream, path: rental_rate} payment_date: {gen: now} next: return return: # 1 to 7 days, in seconds wait: timeout: {gen: uniform, low: 86400, high: 604800} payload: rental_id: {gen: upstream, path: rental_id} return_date: {gen: now} run: {until: 7 days} ``` ```text {"stream_type":"event","sim_ts":0.0,"timestamp":"...","key":"films-1","task":"film","instance":0,"value":{"film_id":1,"title":"Golden River","rating":"NC-17","rental_rate":2.99,"length":94}} {"stream_type":"event","sim_ts":0.0,"timestamp":"...","key":"films-2","task":"film","instance":1,"value":{"film_id":2,"title":"Last Letter","rating":"R","rental_rate":4.99,"length":62}} {"stream_type":"event","sim_ts":0.0,"timestamp":"...","key":"films-3","task":"film","instance":2,"value":{"film_id":3,"title":"Last Garden","rating":"PG","rental_rate":2.99,"length":164}} {"stream_type":"event","sim_ts":0.0,"timestamp":"...","key":"films-4","task":"film","instance":3,"value":{"film_id":4,"title":"Last Garden","rating":"PG-13","rental_rate":0.99,"length":60}} {"stream_type":"event","sim_ts":0.0,"timestamp":"...","key":"films-5","task":"film","instance":4,"value":{"film_id":5,"title":"Silent Garden","rating":"NC-17","rental_rate":2.99,"length":73}} ``` The Builder file builds the same model with the builder API and prints every record of its run: ```bash python examples/gallery/film_rental_store_builder.py ``` ```python """A film rental store: films, customers, rentals, payments and returns, builder API. The builder version of `film_rental_store.yaml`: 20 films and 15 customers at the start, a rental about every 8 minutes for a week, paid at once and returned 1 to 7 days later. Needs: the fake extra. Run it with: python examples/gallery/film_rental_store_builder.py """ import logging from datetime import datetime, timezone from desflow import ConsoleEgress, SimulationContext from desflow.values import Template, generator UNTIL = 7 * 86400 def build() -> SimulationContext: """Builds the store.""" app = SimulationContext( sim_id="Store", factor=0, random_seed=42, logical_start_time=datetime(2026, 1, 1, tzinfo=timezone.utc), ) app.add_egress(ConsoleEgress()) app.add_initial_arrival("films", 20, spawn="film") app.add_initial_arrival("customers", 15, spawn="customer") app.add_arrival("rentals", "exponential", rate=0.002, spawn="rental") film_payload = Template( { "film_id": {"gen": "sequence", "start": 1}, "title": { "gen": "format", "template": "{adjective} {noun}", "names": { "adjective": { "gen": "one_of", "choices": ["Silent", "Broken", "Golden", "Hidden", "Last"], }, "noun": { "gen": "one_of", "choices": ["River", "Garden", "Highway", "Letter", "Harbour"], }, }, }, "rating": { "gen": "weighted", "options": {"G": 2, "PG": 3, "PG-13": 3, "R": 3, "NC-17": 1}, }, "rental_rate": {"gen": "one_of", "choices": [0.99, 2.99, 4.99]}, "length": {"gen": "integer", "bounds": [60, 180]}, }, name="tasks.film", ) customer_payload = Template( { "customer_id": {"gen": "sequence", "start": 1}, "first_name": {"gen": "fake", "method": "first_name"}, "last_name": {"gen": "fake", "method": "last_name"}, "active": {"gen": "boolean", "p": 0.9}, }, name="tasks.customer", ) rental_payload = Template( { "rental_id": {"gen": "sequence", "start": 1}, "rental_date": {"gen": "now"}, "film_id": {"gen": "var", "name": "film", "path": "film_id"}, "rental_rate": {"gen": "var", "name": "film", "path": "rental_rate"}, "customer_id": {"gen": "lookup", "task": "customer", "path": "customer_id"}, }, name="tasks.rental", vars={"film": {"gen": "lookup", "task": "film"}}, ) payment_payload = Template( { "rental_id": {"gen": "upstream", "path": "rental_id"}, "customer_id": {"gen": "upstream", "path": "customer_id"}, "amount": {"gen": "upstream", "path": "rental_rate"}, "payment_date": {"gen": "now"}, }, name="tasks.payment", ) return_payload = Template( { "rental_id": {"gen": "upstream", "path": "rental_id"}, "return_date": {"gen": "now"}, }, name="tasks.return", ) @app.task(name="film", history=1_000_000) def film(task_id): """Gives one film.""" return film_payload @app.task(name="customer", history=1_000_000) def customer(task_id): """Gives one customer.""" return customer_payload @app.task(name="rental", next="payment") def rental(task_id): """Starts a rental of a film by a customer.""" return rental_payload @app.task(name="payment", next="return") def payment(task_id): """Pays for the rental at its rate.""" return payment_payload # 1 to 7 days, in seconds @app.task( name="return", wait={"timeout": generator({"gen": "uniform", "low": 86400, "high": 604800})}, ) def return_(task_id): """Returns the film.""" return return_payload return app if __name__ == "__main__": logging.basicConfig(level=logging.INFO, format="%(levelname)s %(message)s") build().run(until=UNTIL) ``` The Low-level file builds the model on `DynamicRealtimeEnvironment`, with plain Python processes, and prints every record of its run: ```bash python examples/gallery/film_rental_store_low_level.py ``` The Low-level file draws each value with `Sampler.generator()`, where the place is the key path of the blueprint's generator that makes the same value, such as `tasks.film.payload.title.names.adjective`, `tasks.film.payload.title.names.noun` and `tasks.film.payload.rating` and 6 more. Each draw therefore comes from the random sequence the blueprint uses at the same place, so the draws are the blueprint's. The gaps between arrivals come from `Sampler.sample` on a `DistributionConfig` whose `stream` is `arrival.rentals`, the sequence the blueprint uses for its arrivals. ```python """A film rental store: films, customers, rentals, payments and returns, low-level API. The low-level version of `film_rental_store.yaml`: plain SimPy on a `DynamicRealtimeEnvironment`, which publishes each record with `publish_event`. Each draw is made with `Sampler.generator()`, from the random sequence the blueprint's generator at that place uses, so the draws are the blueprint's. A name is drawn with a Faker that is seeded from that sequence. Needs: the fake extra. Run it with: python examples/gallery/film_rental_store_low_level.py """ import itertools import logging from datetime import datetime, timedelta, timezone from faker import Faker from desflow import ( ConsoleEgress, DistributionConfig, DynamicRealtimeEnvironment, Sampler, ) UNTIL = 7 * 86400 START = datetime(2026, 1, 1, tzinfo=timezone.utc) ENVIRONMENT = {"logical_start_time": START, "timezone": "UTC"} ADJECTIVES = ["Silent", "Broken", "Golden", "Hidden", "Last"] NOUNS = ["River", "Garden", "Highway", "Letter", "Harbour"] RATINGS = {"G": 2, "PG": 3, "PG-13": 3, "R": 3, "NC-17": 1} RATES = [0.99, 2.99, 4.99] def weighted(rng, options): """One key of `options`, chosen by its weight, as the `weighted` generator does.""" point = rng.random() * sum(options.values()) running = 0.0 for value, weight in options.items(): running += weight if point < running: return value return value def one_of(rng, choices): """One of `choices`, each equally likely, as the `one_of` generator does.""" return choices[int(rng.integers(len(choices)))] def build(env: DynamicRealtimeEnvironment) -> None: """Starts the arrivals on `env`.""" sampler = Sampler(seed=42) def faker_of(place): faker = Faker("en_US") faker.seed_instance(int(sampler.generator(f"{place}#fake").integers(2**32))) return faker first_names = faker_of("tasks.customer.payload.first_name") last_names = faker_of("tasks.customer.payload.last_name") adjective = sampler.generator("tasks.film.payload.title.names.adjective") noun = sampler.generator("tasks.film.payload.title.names.noun") rating = sampler.generator("tasks.film.payload.rating") rate = sampler.generator("tasks.film.payload.rental_rate") length = sampler.generator("tasks.film.payload.length") active = sampler.generator("tasks.customer.payload.active") film_row = sampler.generator("tasks.rental.vars.film") customer_row = sampler.generator("tasks.rental.payload.customer_id") stay = sampler.generator("tasks.return.wait.timeout") films: list = [] # the films so far, oldest first customers: list = [] # the ids of the customers so far, oldest first counts = {"film": 0, "customer": 0, "rental": 0, "payment": 0, "return": 0} def iso(): """The logical time now, as a timestamp text.""" moment = START + timedelta(seconds=env.now) return moment.isoformat(timespec="milliseconds") def publish(key, task, payload, instance=None): """Publishes a finished payload, as the next instance of its task unless the task has queued one.""" if instance is None: instance = counts[task] counts[task] += 1 env.publish_event(key, payload, task=task, instance=instance) def film(): row = { "film_id": len(films) + 1, "title": f"{one_of(adjective, ADJECTIVES)} {one_of(noun, NOUNS)}", "rating": weighted(rating, RATINGS), "rental_rate": one_of(rate, RATES), "length": int(length.integers(60, 181)), } films.append(row) return row def customer(): row = { "customer_id": len(customers) + 1, "first_name": first_names.first_name(), "last_name": last_names.last_name(), "active": bool(active.random() < 0.9), } customers.append(row["customer_id"]) return row def rental(number): """A rental, its payment at once, and its return after the stay.""" key = f"rentals-{number}" chosen = films[int(film_row.integers(len(films)))] rented = { "rental_id": number, "rental_date": iso(), "film_id": chosen["film_id"], "rental_rate": chosen["rental_rate"], "customer_id": customers[int(customer_row.integers(len(customers)))], } publish(key, "rental", rented) paid = { "rental_id": rented["rental_id"], "customer_id": rented["customer_id"], "amount": rented["rental_rate"], "payment_date": iso(), } publish(key, "payment", paid) instance = counts["return"] # the return waits, so it is queued first counts["return"] += 1 env.publish_event(key, {"status": "queued"}, task="return", instance=instance) yield env.timeout(86400 + (604800 - 86400) * stay.random()) # 1 to 7 days env.publish_event(key, {"status": "started"}, task="return", instance=instance) returned = {"rental_id": rented["rental_id"], "return_date": iso()} publish(key, "return", returned, instance) gap = DistributionConfig(dist="exponential", rate=0.002) gap.stream = "arrival.rentals" def source(): for number in itertools.count(1): yield env.timeout(sampler.sample(gap)) env.process(rental(number)) def start(name, task, make, number): yield env.timeout(0) publish(f"{name}-{number}", task, make()) env.process(source()) for number in range(1, 21): env.process(start("films", "film", film, number)) for number in range(1, 16): env.process(start("customers", "customer", customer, number)) def run() -> None: """Runs the model unpaced into the console.""" env = DynamicRealtimeEnvironment(factor=0, **ENVIRONMENT) env.setup_egress([ConsoleEgress()]) build(env) try: env.run(until=UNTIL) finally: env.teardown() if __name__ == "__main__": logging.basicConfig(level=logging.INFO, format="%(levelname)s %(message)s") run() ``` ### Auction streams: people, auctions and bids The three streams have the shape of the Nexmark benchmark, with about 1 new person for 3 new auctions and 46 bids. Each auction names a seller who exists and each bid names an auction and a bidder who exist. Ten people and five auctions exist at the start, so a bid always has something to name. The run lasts 10 minutes. It needs the `fake` extra: `pip install "desflow[fake]"`. Run it with the sample option, which stops after the first events and prints them: ```bash desflow run examples/gallery/auction_streams.yaml --sample 5 ``` ```yaml # Auction streams: people, auctions and bids. # # The three streams have the shape of the Nexmark benchmark, with about 1 new person # for 3 new auctions and 46 bids. Each auction names a seller who exists and each bid # names an auction and a bidder who exist. Ten people and five auctions exist at the # start, so a bid always has something to name. The run lasts 10 minutes. # # Needs: the fake extra. # Run it with: desflow run examples/gallery/auction_streams.yaml simulation: sim_id: Auction factor: 0 random_seed: 42 logical_start_time: 2026-01-01T00:00:00 egress: - {type: Console} arrivals: people: {initial: 10, dist: exponential, rate: 0.02, spawn: person} auctions: {initial: 5, dist: exponential, rate: 0.06, spawn: auction} bids: {dist: exponential, rate: 0.92, spawn: bid} tasks: person: payload: person_id: {gen: sequence, start: 1000} name: {gen: fake, method: name} city: {gen: one_of, choices: [Phoenix, Boise, Cheyenne, Portland, Kent]} state: gen: weighted options: {AZ: 3, ID: 2, WY: 1, OR: 3, WA: 3} auction: payload: auction_id: {gen: sequence, start: 1} seller: {gen: lookup, task: person, path: person_id} category: {gen: integer, bounds: [1, 10]} reserve: {gen: integer, bounds: [100, 1000]} expires: {gen: now, offset: 1 hour} bid: payload: auction: {gen: lookup, task: auction, path: auction_id} bidder: {gen: lookup, task: person, path: person_id} price: {gen: integer, bounds: [100, 2000]} bid_time: {gen: now} run: {until: 10 min} ``` ```text {"stream_type":"event","sim_ts":0.0,"timestamp":"...","key":"people-1","task":"person","instance":0,"value":{"person_id":1000,"name":"Gabriel Klein","city":"Boise","state":"OR"}} {"stream_type":"event","sim_ts":0.0,"timestamp":"...","key":"people-2","task":"person","instance":1,"value":{"person_id":1001,"name":"Paul Murphy","city":"Cheyenne","state":"OR"}} {"stream_type":"event","sim_ts":0.0,"timestamp":"...","key":"people-3","task":"person","instance":2,"value":{"person_id":1002,"name":"Stacey Adams","city":"Phoenix","state":"WY"}} {"stream_type":"event","sim_ts":0.0,"timestamp":"...","key":"people-4","task":"person","instance":3,"value":{"person_id":1003,"name":"Brandon Harmon","city":"Phoenix","state":"WA"}} {"stream_type":"event","sim_ts":0.0,"timestamp":"...","key":"people-5","task":"person","instance":4,"value":{"person_id":1004,"name":"Noah Russell","city":"Cheyenne","state":"AZ"}} ``` The Builder file builds the same model with the builder API and prints every record of its run: ```bash python examples/gallery/auction_streams_builder.py ``` ```python """Auction streams: people, auctions and bids, builder API. The builder version of `auction_streams.yaml`: about 1 new person for 3 new auctions and 46 bids, with ten people and five auctions at the start so that every lookup finds a row. Needs: the fake extra. Run it with: python examples/gallery/auction_streams_builder.py """ import logging from datetime import datetime, timezone from desflow import ConsoleEgress, SimulationContext from desflow.values import Template UNTIL = 600 def build() -> SimulationContext: """Builds the auction house.""" app = SimulationContext( sim_id="Auction", factor=0, random_seed=42, logical_start_time=datetime(2026, 1, 1, tzinfo=timezone.utc), ) app.add_egress(ConsoleEgress()) app.add_arrival("people", "exponential", rate=0.02, spawn="person", initial=10) app.add_arrival("auctions", "exponential", rate=0.06, spawn="auction", initial=5) app.add_arrival("bids", "exponential", rate=0.92, spawn="bid") person_payload = Template( { "person_id": {"gen": "sequence", "start": 1000}, "name": {"gen": "fake", "method": "name"}, "city": { "gen": "one_of", "choices": ["Phoenix", "Boise", "Cheyenne", "Portland", "Kent"], }, "state": { "gen": "weighted", "options": {"AZ": 3, "ID": 2, "WY": 1, "OR": 3, "WA": 3}, }, }, name="tasks.person", ) auction_payload = Template( { "auction_id": {"gen": "sequence", "start": 1}, "seller": {"gen": "lookup", "task": "person", "path": "person_id"}, "category": {"gen": "integer", "bounds": [1, 10]}, "reserve": {"gen": "integer", "bounds": [100, 1000]}, "expires": {"gen": "now", "offset": "1 hour"}, }, name="tasks.auction", ) bid_payload = Template( { "auction": {"gen": "lookup", "task": "auction", "path": "auction_id"}, "bidder": {"gen": "lookup", "task": "person", "path": "person_id"}, "price": {"gen": "integer", "bounds": [100, 2000]}, "bid_time": {"gen": "now"}, }, name="tasks.bid", ) # A task that something looks up keeps its finished rows @app.task(name="person", history=1_000_000) def person(task_id): """Gives one person.""" return person_payload @app.task(name="auction", history=1_000_000) def auction(task_id): """Gives one auction.""" return auction_payload @app.task(name="bid") def bid(task_id): """Gives one bid.""" return bid_payload return app if __name__ == "__main__": logging.basicConfig(level=logging.INFO, format="%(levelname)s %(message)s") build().run(until=UNTIL) ``` The Low-level file builds the model on `DynamicRealtimeEnvironment`, with plain Python processes, and prints every record of its run: ```bash python examples/gallery/auction_streams_low_level.py ``` The Low-level file draws each value with `Sampler.generator()`, where the place is the key path of the blueprint's generator that makes the same value, such as `tasks.person.payload.name`, `tasks.person.payload.city` and `tasks.person.payload.state` and 6 more. Each draw therefore comes from the random sequence the blueprint uses at the same place, so the draws are the blueprint's. The gaps between arrivals come from `Sampler.sample` on a `DistributionConfig` whose `stream` is `arrival.`, the sequence the blueprint uses for its arrivals. ```python """Auction streams: people, auctions and bids, low-level API. The low-level version of `auction_streams.yaml`: plain SimPy on a `DynamicRealtimeEnvironment`, which publishes each record with `publish_event`. Each draw is made with `Sampler.generator()`, from the random sequence the blueprint's generator at that place uses, so the draws are the blueprint's. A name is drawn with a Faker that is seeded from that sequence. Needs: the fake extra. Run it with: python examples/gallery/auction_streams_low_level.py """ import itertools import logging from datetime import datetime, timedelta, timezone from faker import Faker from desflow import ( ConsoleEgress, DistributionConfig, DynamicRealtimeEnvironment, Sampler, ) UNTIL = 600 START = datetime(2026, 1, 1, tzinfo=timezone.utc) ENVIRONMENT = {"logical_start_time": START, "timezone": "UTC"} CITIES = ["Phoenix", "Boise", "Cheyenne", "Portland", "Kent"] STATES = {"AZ": 3, "ID": 2, "WY": 1, "OR": 3, "WA": 3} def weighted(rng, options): """One key of `options`, chosen by its weight, as the `weighted` generator does.""" point = rng.random() * sum(options.values()) running = 0.0 for value, weight in options.items(): running += weight if point < running: return value return value def integer(rng, low, high): """A whole number from `low` to `high`, both included, as `integer` draws it.""" return int(rng.integers(low, high + 1)) def build(env: DynamicRealtimeEnvironment) -> None: """Starts the arrivals on `env`.""" sampler = Sampler(seed=42) faker = Faker("en_US") faker.seed_instance( int(sampler.generator("tasks.person.payload.name#fake").integers(2**32)) ) city = sampler.generator("tasks.person.payload.city") state = sampler.generator("tasks.person.payload.state") seller = sampler.generator("tasks.auction.payload.seller") category = sampler.generator("tasks.auction.payload.category") reserve = sampler.generator("tasks.auction.payload.reserve") auction = sampler.generator("tasks.bid.payload.auction") bidder = sampler.generator("tasks.bid.payload.bidder") price = sampler.generator("tasks.bid.payload.price") people: list = [] # the ids of the people so far, oldest first auctions: list = [] # the ids of the auctions so far, oldest first counts = {"person": 0, "auction": 0, "bid": 0} def iso(offset=0): """The logical time now plus `offset` seconds, as a timestamp text.""" moment = START + timedelta(seconds=env.now + offset) return moment.isoformat(timespec="milliseconds") def person(): counts["person"] += 1 row = { "person_id": 999 + counts["person"], "name": faker.name(), "city": CITIES[int(city.integers(len(CITIES)))], "state": weighted(state, STATES), } people.append(row["person_id"]) return row def new_auction(): counts["auction"] += 1 row = { "auction_id": counts["auction"], "seller": people[int(seller.integers(len(people)))], "category": integer(category, 1, 10), "reserve": integer(reserve, 100, 1000), "expires": iso(3600), } auctions.append(row["auction_id"]) return row def bid(): counts["bid"] += 1 return { "auction": auctions[int(auction.integers(len(auctions)))], "bidder": people[int(bidder.integers(len(people)))], "price": integer(price, 100, 2000), "bid_time": iso(), } def arrival(name, task, make, rate, initial=0): """Starts `initial` entities at time 0, then one after each gap.""" gap = DistributionConfig(dist="exponential", rate=rate) gap.stream = f"arrival.{name}" def start(number): key = f"{name}-{number}" payload = make() env.publish_event(key, payload, task=task, instance=counts[task] - 1) def source(): for number in itertools.count(initial + 1): yield env.timeout(sampler.sample(gap)) start(number) def first(number): yield env.timeout(0) start(number) env.process(source()) for number in range(1, initial + 1): env.process(first(number)) arrival("people", "person", person, 0.02, initial=10) arrival("auctions", "auction", new_auction, 0.06, initial=5) arrival("bids", "bid", bid, 0.92) def run() -> None: """Runs the model unpaced into the console.""" env = DynamicRealtimeEnvironment(factor=0, **ENVIRONMENT) env.setup_egress([ConsoleEgress()]) build(env) try: env.run(until=UNTIL) finally: env.teardown() if __name__ == "__main__": logging.basicConfig(level=logging.INFO, format="%(levelname)s %(message)s") run() ``` ### A table for group-by benchmarks Each row has three keys that are text (id1 to id3, with 100, 100 and 100,000 values), three that are whole numbers (id4 to id6) and three measures (v1, v2 and v3). A group-by on a key and a sum of a measure is the usual test of a data frame library. One row a second, 1,000 rows. Run it with the sample option, which stops after the first events and prints them: ```bash desflow run examples/gallery/group_by_table.yaml --sample 5 ``` ```yaml # A table for group-by benchmarks. # # Each row has three keys that are text (id1 to id3, with 100, 100 and 100,000 values), # three that are whole numbers (id4 to id6) and three measures (v1, v2 and v3). A # group-by on a key and a sum of a measure is the usual test of a data frame library. # One row a second, 1,000 rows. # # Needs: nothing # Run it with: desflow run examples/gallery/group_by_table.yaml simulation: sim_id: Table factor: 0 random_seed: 42 logical_start_time: 2026-01-01T00:00:00 egress: - {type: Console} arrivals: rows: {dist: constant, value: 1, spawn: row, max_events: 1000} tasks: row: payload: id1: gen: format template: "id{n:03d}" names: n: {gen: integer, bounds: [1, 100]} id2: gen: format template: "id{n:03d}" names: n: {gen: integer, bounds: [1, 100]} id3: gen: format template: "id{n:010d}" names: n: {gen: integer, bounds: [1, 100000]} id4: {gen: integer, bounds: [1, 100]} id5: {gen: integer, bounds: [1, 100]} id6: {gen: integer, bounds: [1, 100000]} v1: {gen: integer, bounds: [1, 5]} v2: {gen: integer, bounds: [1, 15]} v3: {gen: uniform, low: 0, high: 100, decimals: 6} run: # The 1,000th row is at 1,000 s, and a run stops before the events due at its end # time, so it ends 1 s later. until: 1001 ``` ```text {"stream_type":"event","sim_ts":1.0,"timestamp":"...","key":"rows-1","task":"row","instance":0,"value":{"id1":"id065","id2":"id052","id3":"id0000092102","id4":90,"id5":54,"id6":79667,"v1":3,"v2":8,"v3":98.973392}} {"stream_type":"event","sim_ts":2.0,"timestamp":"...","key":"rows-2","task":"row","instance":1,"value":{"id1":"id046","id2":"id037","id3":"id0000094548","id4":11,"id5":16,"id6":19271,"v1":1,"v2":2,"v3":25.314477}} {"stream_type":"event","sim_ts":3.0,"timestamp":"...","key":"rows-3","task":"row","instance":2,"value":{"id1":"id099","id2":"id045","id3":"id0000044421","id4":18,"id5":74,"id6":43698,"v1":2,"v2":4,"v3":51.069601}} {"stream_type":"event","sim_ts":4.0,"timestamp":"...","key":"rows-4","task":"row","instance":3,"value":{"id1":"id032","id2":"id014","id3":"id0000028409","id4":50,"id5":82,"id6":95333,"v1":2,"v2":9,"v3":39.159243}} {"stream_type":"event","sim_ts":5.0,"timestamp":"...","key":"rows-5","task":"row","instance":4,"value":{"id1":"id084","id2":"id019","id3":"id0000033540","id4":97,"id5":97,"id6":38451,"v1":1,"v2":1,"v3":51.161482}} ``` The Builder file builds the same model with the builder API and prints every record of its run: ```bash python examples/gallery/group_by_table_builder.py ``` ```python """A table for group-by benchmarks, builder API. The builder version of `group_by_table.yaml`: 1,000 rows, one a second, each with the keys id1 to id6 and the measures v1 to v3. Needs: nothing Run it with: python examples/gallery/group_by_table_builder.py """ import logging from datetime import datetime, timezone from desflow import ConsoleEgress, SimulationContext from desflow.values import Template # The 1,000th row is at 1,000 s, and a run stops before the events due at its end # time, so it ends 1 s later. UNTIL = 1001 def build() -> SimulationContext: """Builds the table.""" app = SimulationContext( sim_id="Table", factor=0, random_seed=42, logical_start_time=datetime(2026, 1, 1, tzinfo=timezone.utc), ) app.add_egress(ConsoleEgress()) app.add_arrival("rows", "constant", value=1, spawn="row", max_events=1000) row_payload = Template( { "id1": { "gen": "format", "template": "id{n:03d}", "names": {"n": {"gen": "integer", "bounds": [1, 100]}}, }, "id2": { "gen": "format", "template": "id{n:03d}", "names": {"n": {"gen": "integer", "bounds": [1, 100]}}, }, "id3": { "gen": "format", "template": "id{n:010d}", "names": {"n": {"gen": "integer", "bounds": [1, 100000]}}, }, "id4": {"gen": "integer", "bounds": [1, 100]}, "id5": {"gen": "integer", "bounds": [1, 100]}, "id6": {"gen": "integer", "bounds": [1, 100000]}, "v1": {"gen": "integer", "bounds": [1, 5]}, "v2": {"gen": "integer", "bounds": [1, 15]}, "v3": {"gen": "uniform", "low": 0, "high": 100, "decimals": 6}, }, name="tasks.row", ) @app.task(name="row") def row(task_id): """Gives one row.""" return row_payload return app if __name__ == "__main__": logging.basicConfig(level=logging.INFO, format="%(levelname)s %(message)s") build().run(until=UNTIL) ``` The Low-level file builds the model on `DynamicRealtimeEnvironment`, with plain Python processes, and prints every record of its run: ```bash python examples/gallery/group_by_table_low_level.py ``` The Low-level file draws each value with `Sampler.generator()`, where the place is the key path of the blueprint's generator that makes the same value, such as `.id1.names.n` with the place of the task filled in. Each draw therefore comes from the random sequence the blueprint uses at the same place, so the draws are the blueprint's. The file waits 1 simulation second between rows, as the blueprint's constant arrival does. ```python """A table for group-by benchmarks, low-level API. The low-level version of `group_by_table.yaml`: plain SimPy on a `DynamicRealtimeEnvironment`, which publishes each record with `publish_event`. Each draw is made with `Sampler.generator()`, from the random sequence the blueprint's generator at that place uses, so the draws are the blueprint's. Needs: nothing Run it with: python examples/gallery/group_by_table_low_level.py """ import logging from datetime import datetime, timezone from desflow import ConsoleEgress, DynamicRealtimeEnvironment, Sampler # The 1,000th row is at 1,000 s, and a run stops before the events due at its end # time, so it ends 1 s later. UNTIL = 1001 START = datetime(2026, 1, 1, tzinfo=timezone.utc) ENVIRONMENT = {"logical_start_time": START, "timezone": "UTC"} def integer(rng, low, high): """A whole number from `low` to `high`, both included, as `integer` draws it.""" return int(rng.integers(low, high + 1)) def build(env: DynamicRealtimeEnvironment) -> None: """Starts the arrivals on `env`.""" sampler = Sampler(seed=42) place = "tasks.row.payload" id1 = sampler.generator(f"{place}.id1.names.n") id2 = sampler.generator(f"{place}.id2.names.n") id3 = sampler.generator(f"{place}.id3.names.n") id4 = sampler.generator(f"{place}.id4") id5 = sampler.generator(f"{place}.id5") id6 = sampler.generator(f"{place}.id6") v1 = sampler.generator(f"{place}.v1") v2 = sampler.generator(f"{place}.v2") v3 = sampler.generator(f"{place}.v3") def source(): for number in range(1, 1001): yield env.timeout(1) row = { "id1": f"id{integer(id1, 1, 100):03d}", "id2": f"id{integer(id2, 1, 100):03d}", "id3": f"id{integer(id3, 1, 100000):010d}", "id4": integer(id4, 1, 100), "id5": integer(id5, 1, 100), "id6": integer(id6, 1, 100000), "v1": integer(v1, 1, 5), "v2": integer(v2, 1, 15), "v3": round(100 * v3.random(), 6), } env.publish_event(f"rows-{number}", row, task="row", instance=number - 1) env.process(source()) def run() -> None: """Runs the model unpaced into the console.""" env = DynamicRealtimeEnvironment(factor=0, **ENVIRONMENT) env.setup_egress([ConsoleEgress()]) build(env) try: env.run(until=UNTIL) finally: env.teardown() if __name__ == "__main__": logging.basicConfig(level=logging.INFO, format="%(levelname)s %(message)s") run() ``` ### Taxi rides with a pickup, a drop-off, a distance and a fare A ride starts about every 10 seconds. Its distance is 0.5 to 20 km, its duration is 3 to 40 minutes, and the fare is 3 plus 2.2 for each km and 0.4 for each minute. The pickup is in a box about 10 km across. Each ride is one record, written at the pickup with the drop-off time that follows from the duration. Run it with the sample option, which stops after the first events and prints them: ```bash desflow run examples/gallery/taxi_rides.yaml --sample 5 ``` ```yaml # Taxi rides with a pickup, a drop-off, a distance and a fare. # # A ride starts about every 10 seconds. Its distance is 0.5 to 20 km, its duration is # 3 to 40 minutes, and the fare is 3 plus 2.2 for each km and 0.4 for each minute. The # pickup is in a box about 10 km across. Each ride is one record, written at the pickup # with the drop-off time that follows from the duration. # # Needs: nothing # Run it with: desflow run examples/gallery/taxi_rides.yaml simulation: sim_id: Taxi factor: 0 random_seed: 42 logical_start_time: 2026-01-01T00:00:00 egress: - {type: Console} arrivals: rides: {dist: exponential, rate: 0.1, spawn: ride} tasks: ride: vars: distance: {gen: uniform, low: 0.5, high: 20, decimals: 2} minutes: {gen: uniform, low: 3, high: 40, decimals: 1} payload: ride_id: {gen: sequence, start: 1} pickup_time: {gen: now} dropoff_time: gen: add args: - {gen: now} - {gen: expr, expr: "minutes * 60"} passengers: gen: weighted options: {1: 70, 2: 15, 3: 5, 4: 5, 5: 5} pickup_latitude: {gen: uniform, low: 40.7, high: 40.8, decimals: 5} pickup_longitude: {gen: uniform, low: -74.02, high: -73.93, decimals: 5} distance_km: {gen: var, name: distance} fare: {gen: expr, expr: "round(3 + 2.2 * distance + 0.4 * minutes, 2)"} payment: gen: weighted options: {card: 65, cash: 33, dispute: 2} run: {until: 10 min} ``` ```text {"stream_type":"event","sim_ts":11.604677390791194,"timestamp":"...","key":"rides-1","task":"ride","instance":0,"value":{"ride_id":1,"pickup_time":"2026-01-01T00:00:11.604+00:00","dropoff_time":"2026-01-01T00:03:47.604+00:00","passengers":1,"pickup_latitude":40.75306,"pickup_longitude":-74.01146,"distance_km":8.02,"fare":22.08,"payment":"card"}} {"stream_type":"event","sim_ts":22.693542131865627,"timestamp":"...","key":"rides-2","task":"ride","instance":1,"value":{"ride_id":2,"pickup_time":"2026-01-01T00:00:22.693+00:00","dropoff_time":"2026-01-01T00:37:10.693+00:00","passengers":1,"pickup_latitude":40.74255,"pickup_longitude":-73.97564,"distance_km":8.66,"fare":36.77,"payment":"card"}} {"stream_type":"event","sim_ts":23.65052438981398,"timestamp":"...","key":"rides-3","task":"ride","instance":2,"value":{"ride_id":3,"pickup_time":"2026-01-01T00:00:23.650+00:00","dropoff_time":"2026-01-01T00:26:29.650+00:00","passengers":2,"pickup_latitude":40.77585,"pickup_longitude":-73.94231,"distance_km":4.55,"fare":23.45,"payment":"card"}} {"stream_type":"event","sim_ts":55.511066162645236,"timestamp":"...","key":"rides-4","task":"ride","instance":3,"value":{"ride_id":4,"pickup_time":"2026-01-01T00:00:55.511+00:00","dropoff_time":"2026-01-01T00:23:43.511+00:00","passengers":1,"pickup_latitude":40.78844,"pickup_longitude":-73.99307,"distance_km":12.18,"fare":38.92,"payment":"cash"}} {"stream_type":"event","sim_ts":87.27070653875613,"timestamp":"...","key":"rides-5","task":"ride","instance":4,"value":{"ride_id":5,"pickup_time":"2026-01-01T00:01:27.270+00:00","dropoff_time":"2026-01-01T00:27:03.270+00:00","passengers":1,"pickup_latitude":40.74953,"pickup_longitude":-73.95768,"distance_km":1.44,"fare":16.41,"payment":"card"}} ``` The Builder file builds the same model with the builder API and prints every record of its run: ```bash python examples/gallery/taxi_rides_builder.py ``` ```python """Taxi rides with a pickup, a drop-off, a distance and a fare, builder API. The builder version of `taxi_rides.yaml`: a ride about every 10 seconds, for 10 minutes. Needs: nothing Run it with: python examples/gallery/taxi_rides_builder.py """ import logging from datetime import datetime, timezone from desflow import ConsoleEgress, SimulationContext from desflow.values import Template UNTIL = 600 def build() -> SimulationContext: """Builds the taxi company.""" app = SimulationContext( sim_id="Taxi", factor=0, random_seed=42, logical_start_time=datetime(2026, 1, 1, tzinfo=timezone.utc), ) app.add_egress(ConsoleEgress()) app.add_arrival("rides", "exponential", rate=0.1, spawn="ride") ride_payload = Template( { "ride_id": {"gen": "sequence", "start": 1}, "pickup_time": {"gen": "now"}, "dropoff_time": { "gen": "add", "args": [{"gen": "now"}, {"gen": "expr", "expr": "minutes * 60"}], }, "passengers": { "gen": "weighted", "options": {1: 70, 2: 15, 3: 5, 4: 5, 5: 5}, }, "pickup_latitude": { "gen": "uniform", "low": 40.7, "high": 40.8, "decimals": 5, }, "pickup_longitude": { "gen": "uniform", "low": -74.02, "high": -73.93, "decimals": 5, }, "distance_km": {"gen": "var", "name": "distance"}, "fare": { "gen": "expr", "expr": "round(3 + 2.2 * distance + 0.4 * minutes, 2)", }, "payment": { "gen": "weighted", "options": {"card": 65, "cash": 33, "dispute": 2}, }, }, name="tasks.ride", vars={ "distance": {"gen": "uniform", "low": 0.5, "high": 20, "decimals": 2}, "minutes": {"gen": "uniform", "low": 3, "high": 40, "decimals": 1}, }, ) @app.task(name="ride") def ride(task_id): """Gives one ride.""" return ride_payload return app if __name__ == "__main__": logging.basicConfig(level=logging.INFO, format="%(levelname)s %(message)s") build().run(until=UNTIL) ``` The Low-level file builds the model on `DynamicRealtimeEnvironment`, with plain Python processes, and prints every record of its run: ```bash python examples/gallery/taxi_rides_low_level.py ``` The Low-level file draws each value with `Sampler.generator()`, where the place is the key path of the blueprint's generator that makes the same value, such as `.payload.passengers` with the place of the task filled in. Each draw therefore comes from the random sequence the blueprint uses at the same place, so the draws are the blueprint's. The gaps between arrivals come from `Sampler.sample` on a `DistributionConfig` whose `stream` is `arrival.rides`, the sequence the blueprint uses for its arrivals. ```python """Taxi rides with a pickup, a drop-off, a distance and a fare, low-level API. The low-level version of `taxi_rides.yaml`: plain SimPy on a `DynamicRealtimeEnvironment`, which publishes each record with `publish_event`. Each draw is made with `Sampler.generator()`, from the random sequence the blueprint's generator at that place uses, so the draws are the blueprint's. Needs: nothing Run it with: python examples/gallery/taxi_rides_low_level.py """ import itertools import logging from datetime import datetime, timedelta, timezone from desflow import ( ConsoleEgress, DistributionConfig, DynamicRealtimeEnvironment, Sampler, ) UNTIL = 600 START = datetime(2026, 1, 1, tzinfo=timezone.utc) ENVIRONMENT = {"logical_start_time": START, "timezone": "UTC"} PASSENGERS = {1: 70, 2: 15, 3: 5, 4: 5, 5: 5} PAYMENT = {"card": 65, "cash": 33, "dispute": 2} def weighted(rng, options): """One key of `options`, chosen by its weight, as the `weighted` generator does.""" point = rng.random() * sum(options.values()) running = 0.0 for value, weight in options.items(): running += weight if point < running: return value return value def uniform(rng, low, high, decimals): """A number in [low, high), as the `uniform` generator draws it.""" return round(low + (high - low) * rng.random(), decimals) def build(env: DynamicRealtimeEnvironment) -> None: """Starts the arrivals on `env`.""" sampler = Sampler(seed=42) place = "tasks.ride" passengers = sampler.generator(f"{place}.payload.passengers") latitude = sampler.generator(f"{place}.payload.pickup_latitude") longitude = sampler.generator(f"{place}.payload.pickup_longitude") payment = sampler.generator(f"{place}.payload.payment") distance = sampler.generator(f"{place}.vars.distance") minutes = sampler.generator(f"{place}.vars.minutes") gap = DistributionConfig(dist="exponential", rate=0.1) gap.stream = "arrival.rides" def source(): for number in itertools.count(1): yield env.timeout(sampler.sample(gap)) km = uniform(distance, 0.5, 20, 2) length = uniform(minutes, 3, 40, 1) pickup = START + timedelta(seconds=env.now) dropoff = datetime.fromisoformat( pickup.isoformat(timespec="milliseconds") ) + timedelta(seconds=length * 60) ride = { "ride_id": number, "pickup_time": pickup.isoformat(timespec="milliseconds"), "dropoff_time": dropoff.isoformat(timespec="milliseconds"), "passengers": weighted(passengers, PASSENGERS), "pickup_latitude": uniform(latitude, 40.7, 40.8, 5), "pickup_longitude": uniform(longitude, -74.02, -73.93, 5), "distance_km": km, "fare": round(3 + 2.2 * km + 0.4 * length, 2), "payment": weighted(payment, PAYMENT), } env.publish_event(f"rides-{number}", ride, task="ride", instance=number - 1) env.process(source()) def run() -> None: """Runs the model unpaced into the console.""" env = DynamicRealtimeEnvironment(factor=0, **ENVIRONMENT) env.setup_egress([ConsoleEgress()]) build(env) try: env.run(until=UNTIL) finally: env.teardown() if __name__ == "__main__": logging.basicConfig(level=logging.INFO, format="%(levelname)s %(message)s") run() ``` ### Messages and reviews with a known intent or sentiment Each message has an intent and each review a sentiment, drawn first by weight. The text is then written from one of the templates for that label, so the label is known for every record, and can be used to check a classifier, a retrieval system or a language model against what it should find. Run it with the sample option, which stops after the first events and prints them: ```bash desflow run examples/gallery/labelled_text.yaml --sample 5 ``` ```yaml # Messages and reviews with a known intent or sentiment. # # Each message has an intent and each review a sentiment, drawn first by weight. The # text is then written from one of the templates for that label, so the label is known # for every record, and can be used to check a classifier, a retrieval system or a # language model against what it should find. # # Needs: nothing # Run it with: desflow run examples/gallery/labelled_text.yaml simulation: sim_id: Text factor: 0 random_seed: 42 logical_start_time: 2026-01-01T00:00:00 egress: - {type: Console} arrivals: messages: {dist: exponential, rate: 0.5, spawn: message} reviews: {dist: exponential, rate: 0.2, spawn: review} tasks: message: vars: intent: gen: weighted options: {order_status: 4, refund: 2, cancel: 1, hello: 3} payload: message_id: {gen: sequence, start: 1} intent: {gen: var, name: intent} text: gen: switch on: {gen: var, name: intent} cases: order_status: gen: weighted choices: - value: gen: format template: "Where is my order {n}?" names: n: {gen: integer, bounds: [1000, 9999]} weight: 2 - {value: "Has my parcel been sent yet?", weight: 1} refund: gen: weighted choices: - {value: "I want my money back for this order.", weight: 2} - value: gen: format template: "Please refund order {n}." names: n: {gen: integer, bounds: [1000, 9999]} weight: 1 cancel: gen: weighted choices: - {value: "Cancel my order, I changed my mind.", weight: 1} - {value: "Please stop my subscription.", weight: 1} hello: gen: weighted choices: - {value: "Hi, I have a question.", weight: 1} - {value: "Hello, is anyone there?", weight: 1} review: vars: sentiment: gen: weighted options: {positive: 6, neutral: 2, negative: 2} product: {gen: one_of, choices: [lamp, notebook, backpack, headphones]} payload: review_id: {gen: sequence, start: 1} sentiment: {gen: var, name: sentiment} text: gen: switch on: {gen: var, name: sentiment} cases: positive: gen: weighted choices: - value: gen: format template: "The {product} is great and arrived early." weight: 1 - value: gen: format template: "I love this {product}, I would buy it again." weight: 1 neutral: {gen: format, template: "The {product} is fine, nothing special."} negative: gen: weighted choices: - value: {gen: format, template: "The {product} broke after a week."} weight: 1 - value: {gen: format, template: "I would not recommend this {product}."} weight: 1 run: {until: 10 min} ``` ```text {"stream_type":"event","sim_ts":0.501883476100159,"timestamp":"...","key":"reviews-1","task":"review","instance":0,"value":{"review_id":1,"sentiment":"neutral","text":"The lamp is fine, nothing special."}} {"stream_type":"event","sim_ts":5.9294365045675255,"timestamp":"...","key":"reviews-2","task":"review","instance":1,"value":{"review_id":2,"sentiment":"neutral","text":"The notebook is fine, nothing special."}} {"stream_type":"event","sim_ts":6.9507388220227355,"timestamp":"...","key":"messages-1","task":"message","instance":0,"value":{"message_id":1,"intent":"hello","text":"Hello, is anyone there?"}} {"stream_type":"event","sim_ts":7.1569152417580275,"timestamp":"...","key":"reviews-3","task":"review","instance":2,"value":{"review_id":3,"sentiment":"negative","text":"The notebook broke after a week."}} {"stream_type":"event","sim_ts":7.847108166885388,"timestamp":"...","key":"messages-2","task":"message","instance":1,"value":{"message_id":2,"intent":"order_status","text":"Where is my order 8831?"}} ``` The Builder file builds the same model with the builder API and prints every record of its run: ```bash python examples/gallery/labelled_text_builder.py ``` ```python """Messages and reviews with a known intent or sentiment, builder API. The builder version of `labelled_text.yaml`: a label is drawn first by weight, and the text is written from a template for that label. Needs: nothing Run it with: python examples/gallery/labelled_text_builder.py """ import logging from datetime import datetime, timezone from desflow import ConsoleEgress, SimulationContext from desflow.values import Template UNTIL = 600 def _number(low: int, high: int) -> dict: return {"gen": "integer", "bounds": [low, high]} def build() -> SimulationContext: """Builds the support desk and the shop.""" app = SimulationContext( sim_id="Text", factor=0, random_seed=42, logical_start_time=datetime(2026, 1, 1, tzinfo=timezone.utc), ) app.add_egress(ConsoleEgress()) app.add_arrival("messages", "exponential", rate=0.5, spawn="message") app.add_arrival("reviews", "exponential", rate=0.2, spawn="review") def says(template: str, **names: dict) -> dict: return {"gen": "format", "template": template, "names": names} message_payload = Template( { "message_id": {"gen": "sequence", "start": 1}, "intent": {"gen": "var", "name": "intent"}, "text": { "gen": "switch", "on": {"gen": "var", "name": "intent"}, "cases": { "order_status": { "gen": "weighted", "choices": [ { "value": says( "Where is my order {n}?", n=_number(1000, 9999) ), "weight": 2, }, {"value": "Has my parcel been sent yet?", "weight": 1}, ], }, "refund": { "gen": "weighted", "choices": [ { "value": "I want my money back for this order.", "weight": 2, }, { "value": says( "Please refund order {n}.", n=_number(1000, 9999) ), "weight": 1, }, ], }, "cancel": { "gen": "weighted", "choices": [ { "value": "Cancel my order, I changed my mind.", "weight": 1, }, {"value": "Please stop my subscription.", "weight": 1}, ], }, "hello": { "gen": "weighted", "choices": [ {"value": "Hi, I have a question.", "weight": 1}, {"value": "Hello, is anyone there?", "weight": 1}, ], }, }, }, }, name="tasks.message", vars={ "intent": { "gen": "weighted", "options": {"order_status": 4, "refund": 2, "cancel": 1, "hello": 3}, } }, ) review_payload = Template( { "review_id": {"gen": "sequence", "start": 1}, "sentiment": {"gen": "var", "name": "sentiment"}, "text": { "gen": "switch", "on": {"gen": "var", "name": "sentiment"}, "cases": { "positive": { "gen": "weighted", "choices": [ { "value": says( "The {product} is great and arrived early." ), "weight": 1, }, { "value": says( "I love this {product}, I would buy it again." ), "weight": 1, }, ], }, "neutral": says("The {product} is fine, nothing special."), "negative": { "gen": "weighted", "choices": [ { "value": says("The {product} broke after a week."), "weight": 1, }, { "value": says("I would not recommend this {product}."), "weight": 1, }, ], }, }, }, }, name="tasks.review", vars={ "sentiment": { "gen": "weighted", "options": {"positive": 6, "neutral": 2, "negative": 2}, }, "product": { "gen": "one_of", "choices": ["lamp", "notebook", "backpack", "headphones"], }, }, ) @app.task(name="message") def message(task_id): """Gives one message with its intent.""" return message_payload @app.task(name="review") def review(task_id): """Gives one review with its sentiment.""" return review_payload return app if __name__ == "__main__": logging.basicConfig(level=logging.INFO, format="%(levelname)s %(message)s") build().run(until=UNTIL) ``` The Low-level file builds the model on `DynamicRealtimeEnvironment`, with plain Python processes, and prints every record of its run: ```bash python examples/gallery/labelled_text_low_level.py ``` The Low-level file draws each value with `Sampler.generator()`, where the place is the key path of the blueprint's generator that makes the same value, such as `tasks.message.vars.intent`, `tasks.review.vars.sentiment` and `tasks.review.vars.product`. Each draw therefore comes from the random sequence the blueprint uses at the same place, so the draws are the blueprint's. The gaps between arrivals come from `Sampler.sample` on a `DistributionConfig` whose `stream` is `arrival.`, the sequence the blueprint uses for its arrivals. ```python """Messages and reviews with a known intent or sentiment, low-level API. The low-level version of `labelled_text.yaml`: plain SimPy on a `DynamicRealtimeEnvironment`, which publishes each record with `publish_event`. Each draw is made with `Sampler.generator()`, from the random sequence the blueprint's generator at that place uses, so the draws are the blueprint's. Needs: nothing Run it with: python examples/gallery/labelled_text_low_level.py """ import itertools import logging from datetime import datetime, timezone from desflow import ( ConsoleEgress, DistributionConfig, DynamicRealtimeEnvironment, Sampler, ) UNTIL = 600 START = datetime(2026, 1, 1, tzinfo=timezone.utc) ENVIRONMENT = {"logical_start_time": START, "timezone": "UTC"} INTENTS = {"order_status": 4, "refund": 2, "cancel": 1, "hello": 3} SENTIMENTS = {"positive": 6, "neutral": 2, "negative": 2} PRODUCTS = ["lamp", "notebook", "backpack", "headphones"] # The texts of a message, by intent. A text with {n} takes an order number MESSAGES = { "order_status": [ ("Where is my order {n}?", 2), ("Has my parcel been sent yet?", 1), ], "refund": [ ("I want my money back for this order.", 2), ("Please refund order {n}.", 1), ], "cancel": [ ("Cancel my order, I changed my mind.", 1), ("Please stop my subscription.", 1), ], "hello": [("Hi, I have a question.", 1), ("Hello, is anyone there?", 1)], } # The texts of a review, by sentiment. A text takes the product REVIEWS = { "positive": [ ("The {product} is great and arrived early.", 1), ("I love this {product}, I would buy it again.", 1), ], "neutral": [("The {product} is fine, nothing special.", 1)], "negative": [ ("The {product} broke after a week.", 1), ("I would not recommend this {product}.", 1), ], } def position(rng, weights): """The position of one weight, chosen by its size, as the `weighted` generator does.""" point = rng.random() * sum(weights) running = 0.0 for index, weight in enumerate(weights): running += weight if point < running: return index return len(weights) - 1 def build(env: DynamicRealtimeEnvironment) -> None: """Starts the arrivals on `env`.""" sampler = Sampler(seed=42) intent = sampler.generator("tasks.message.vars.intent") sentiment = sampler.generator("tasks.review.vars.sentiment") product = sampler.generator("tasks.review.vars.product") counts = {"message": 0, "review": 0} def message_text(label): """The text of a message: a template chosen by weight, with an order number.""" place = f"tasks.message.payload.text.cases.{label}" templates = MESSAGES[label] chosen = position(sampler.generator(place), [w for _, w in templates]) template = templates[chosen][0] number = sampler.generator(f"{place}.choices.{chosen}.value.names.n") return template.format(n=int(number.integers(1000, 10000))) def review_text(label, name): """The text of a review: a template chosen by weight, for the product.""" templates = REVIEWS[label] weights = [w for _, w in templates] place = f"tasks.review.payload.text.cases.{label}" chosen = 0 if len(weights) == 1 else position(sampler.generator(place), weights) return templates[chosen][0].format(product=name) def message(): counts["message"] += 1 label = list(INTENTS)[position(intent, list(INTENTS.values()))] return { "message_id": counts["message"], "intent": label, "text": message_text(label), } def review(): counts["review"] += 1 label = list(SENTIMENTS)[position(sentiment, list(SENTIMENTS.values()))] name = PRODUCTS[int(product.integers(len(PRODUCTS)))] return { "review_id": counts["review"], "sentiment": label, "text": review_text(label, name), } def arrival(name, task, make, rate): gap = DistributionConfig(dist="exponential", rate=rate) gap.stream = f"arrival.{name}" def source(): for number in itertools.count(1): yield env.timeout(sampler.sample(gap)) env.publish_event( f"{name}-{number}", make(), task=task, instance=number - 1 ) env.process(source()) arrival("messages", "message", message, 0.5) arrival("reviews", "review", review, 0.2) def run() -> None: """Runs the model unpaced into the console.""" env = DynamicRealtimeEnvironment(factor=0, **ENVIRONMENT) env.setup_egress([ConsoleEgress()]) build(env) try: env.run(until=UNTIL) finally: env.teardown() if __name__ == "__main__": logging.basicConfig(level=logging.INFO, format="%(levelname)s %(message)s") run() ``` ### A point-in-time training set: feature records and the label that follows each Five customers each get a feature record every day (sessions and spend over the last 30 days). Seven days after each one a label record says whether the customer left, with a high chance when the sessions were few. The label carries `as_of`, the time of the feature record it follows. To build the training set, join each label to the newest feature record of the same customer whose `sim_ts` is at or before the label's `sim_ts` less 7 days, so no feature that came after the start of the label's window reaches it. Run it with the sample option, which stops after the first events and prints them: ```bash desflow run examples/gallery/point_in_time_training_set.yaml --sample 5 ``` ```yaml # A point-in-time training set: feature records and the label that follows each. # # Five customers each get a feature record every day (sessions and spend over the last # 30 days). Seven days after each one a label record says whether the customer left, # with a high chance when the sessions were few. The label carries `as_of`, the time of # the feature record it follows. To build the training set, join each label to the # newest feature record of the same customer whose `sim_ts` is at or before the label's # `sim_ts` less 7 days, so no feature that came after the start of the label's window # reaches it. # # Needs: nothing # Run it with: desflow run examples/gallery/point_in_time_training_set.yaml simulation: sim_id: Churn factor: 0 random_seed: 42 logical_start_time: 2026-01-01T00:00:00 egress: - {type: Console} arrivals: customers: count: 5 key: {gen: sequence, format: "customer-{}", start: 1} dist: constant value: 1 day spawn: features tasks: features: payload: customer_id: {gen: entity} as_of: {gen: now} sessions_30d: {gen: integer, bounds: [0, 30]} spend_30d: {gen: uniform, low: 0, high: 500, decimals: 2} next: label label: wait: {timeout: 7 days} payload: customer_id: {gen: entity} as_of: {gen: upstream, path: as_of} churned: gen: when condition: upstream.sessions_30d < 5 then: {gen: boolean, p: 0.6} else: {gen: boolean, p: 0.05} run: {until: 40 days} ``` ```text {"stream_type":"event","sim_ts":86400.0,"timestamp":"...","key":"customer-1","task":"features","instance":0,"value":{"customer_id":"customer-1","as_of":"2026-01-02T00:00:00.000+00:00","sessions_30d":12,"spend_30d":408.84}} {"stream_type":"event","sim_ts":86400.0,"timestamp":"...","key":"customer-1","task":"label","instance":0,"value":{"status":"queued"}} {"stream_type":"event","sim_ts":86400.0,"timestamp":"...","key":"customer-2","task":"features","instance":1,"value":{"customer_id":"customer-2","as_of":"2026-01-02T00:00:00.000+00:00","sessions_30d":23,"spend_30d":240.3}} {"stream_type":"event","sim_ts":86400.0,"timestamp":"...","key":"customer-2","task":"label","instance":1,"value":{"status":"queued"}} {"stream_type":"event","sim_ts":86400.0,"timestamp":"...","key":"customer-3","task":"features","instance":2,"value":{"customer_id":"customer-3","as_of":"2026-01-02T00:00:00.000+00:00","sessions_30d":24,"spend_30d":178.15}} ``` The Builder file builds the same model with the builder API and prints every record of its run: ```bash python examples/gallery/point_in_time_training_set_builder.py ``` ```python """A point-in-time training set: feature records and the label that follows each, builder API. The builder version of `point_in_time_training_set.yaml`: five customers, each with a feature record every day and, 7 days after each, a label record. Needs: nothing Run it with: python examples/gallery/point_in_time_training_set_builder.py """ import logging from datetime import datetime, timezone from desflow import ConsoleEgress, SimulationContext from desflow.values import Template UNTIL = 40 * 86400 CUSTOMERS = 5 def build() -> SimulationContext: """Builds the customers. A blueprint's `count: 5` is five arrivals here, each with the key of its customer.""" app = SimulationContext( sim_id="Churn", factor=0, random_seed=42, logical_start_time=datetime(2026, 1, 1, tzinfo=timezone.utc), ) app.add_egress(ConsoleEgress()) for number in range(1, CUSTOMERS + 1): app.add_arrival( f"customers{number}", "constant", value=86400, # 1 day spawn="features", key=lambda n, number=number: f"customer-{number}", ) features_payload = Template( { "customer_id": {"gen": "entity"}, "as_of": {"gen": "now"}, "sessions_30d": {"gen": "integer", "bounds": [0, 30]}, "spend_30d": {"gen": "uniform", "low": 0, "high": 500, "decimals": 2}, }, name="tasks.features", ) label_payload = Template( { "customer_id": {"gen": "entity"}, "as_of": {"gen": "upstream", "path": "as_of"}, "churned": { "gen": "when", "condition": "upstream.sessions_30d < 5", "then": {"gen": "boolean", "p": 0.6}, "else": {"gen": "boolean", "p": 0.05}, }, }, name="tasks.label", ) @app.task(name="features", next="label") def features(task_id): """Gives the features of a customer.""" return features_payload @app.task(name="label", wait={"timeout": "7 days"}) def label(task_id): """Says, 7 days later, whether the customer left.""" return label_payload return app if __name__ == "__main__": logging.basicConfig(level=logging.INFO, format="%(levelname)s %(message)s") build().run(until=UNTIL) ``` The Low-level file builds the model on `DynamicRealtimeEnvironment`, with plain Python processes, and prints every record of its run: ```bash python examples/gallery/point_in_time_training_set_low_level.py ``` The Low-level file draws each value with `Sampler.generator()`, where the place is the key path of the blueprint's generator that makes the same value, such as `tasks.features.payload.sessions_30d`, `tasks.features.payload.spend_30d` and `tasks.label.payload.churned.then` and 1 more. Each draw therefore comes from the random sequence the blueprint uses at the same place, so the draws are the blueprint's. The file waits one day between the feature records and seven days before each label, as the blueprint's constant arrival and `wait` do. ```python """A point-in-time training set: feature records and the label that follows each, low-level API. The low-level version of `point_in_time_training_set.yaml`: plain SimPy on a `DynamicRealtimeEnvironment`, which publishes each record with `publish_event`. Each draw is made with `Sampler.generator()`, from the random sequence the blueprint's generator at that place uses, so the draws are the blueprint's. Needs: nothing Run it with: python examples/gallery/point_in_time_training_set_low_level.py """ import itertools import logging from datetime import datetime, timedelta, timezone from desflow import ConsoleEgress, DynamicRealtimeEnvironment, Sampler UNTIL = 40 * 86400 START = datetime(2026, 1, 1, tzinfo=timezone.utc) ENVIRONMENT = {"logical_start_time": START, "timezone": "UTC"} def build(env: DynamicRealtimeEnvironment) -> None: """Starts the customers on `env`.""" sampler = Sampler(seed=42) sessions = sampler.generator("tasks.features.payload.sessions_30d") spend = sampler.generator("tasks.features.payload.spend_30d") few = sampler.generator("tasks.label.payload.churned.then") many = sampler.generator("tasks.label.payload.churned.else") counts = {"features": 0, "label": 0} def customer(key): for _ in itertools.count(): yield env.timeout(86400) env.process(flow(key)) def flow(key): """The features of a customer now, then the label 7 days later.""" moment = START + timedelta(seconds=env.now) features = { "customer_id": key, "as_of": moment.isoformat(timespec="milliseconds"), "sessions_30d": int(sessions.integers(0, 31)), "spend_30d": round(500 * spend.random(), 2), } env.publish_event(key, features, task="features", instance=counts["features"]) counts["features"] += 1 instance = counts["label"] # the label waits, so it is queued first counts["label"] += 1 env.publish_event(key, {"status": "queued"}, task="label", instance=instance) yield env.timeout(7 * 86400) env.publish_event(key, {"status": "started"}, task="label", instance=instance) # A customer with few sessions leaves with a high chance chance, rng = (0.6, few) if features["sessions_30d"] < 5 else (0.05, many) label = { "customer_id": key, "as_of": features["as_of"], "churned": bool(rng.random() < chance), } env.publish_event(key, label, task="label", instance=instance) for number in range(1, 6): env.process(customer(f"customer-{number}")) def run() -> None: """Runs the model unpaced into the console.""" env = DynamicRealtimeEnvironment(factor=0, **ENVIRONMENT) env.setup_egress([ConsoleEgress()]) build(env) try: env.run(until=UNTIL) finally: env.teardown() if __name__ == "__main__": logging.basicConfig(level=logging.INFO, format="%(levelname)s %(message)s") run() ``` # Event Streams Five streams whose records depend on each other: orders that carry their customer's tier, a stolen card that makes three large payments, stock queries that read the latest level, requests that become traces of nested spans, and customer changes that end in Kafka tombstones. Each entry is a complete file in three forms. ______________________________________________________________________ ## Before You Start The commands run from the root of a clone of the repository, where the files are in `examples/gallery/`: ```bash git clone https://github.com/jaehyeon-kim/desflow.git cd desflow ``` An entry that needs a service or an extra says so. [Services for the Examples](https://jaehyeon.me/desflow/latest/gallery/#services-for-the-examples) shows how to start the services. A file with a fixed `random_seed` and `factor: 0` prints the same records on every run, and each output block below holds the first events of the YAML file. The Builder and Low-level files publish the same records. ______________________________________________________________________ ## Entries ### Each order carries the tier of the customer who placed it Customers sign up with a tier, and each order reads one sign-up row, so its customer id and tier agree. An order placed before any customer has signed up is dropped. Run it with the sample option, which stops after the first events and prints them: ```bash desflow run examples/gallery/orders_carry_the_customers_tier.yaml --sample 5 ``` ```yaml # Each order carries the tier of the customer who placed it. # # Customers sign up with a tier, and each order reads one sign-up row, so its customer # id and tier agree. An order placed before any customer has signed up is dropped. # # Needs: nothing # Run it with: desflow run examples/gallery/orders_carry_the_customers_tier.yaml simulation: sim_id: Shop factor: 0 random_seed: 42 logical_start_time: 2026-01-01T00:00:00 egress: - {type: Console} arrivals: signups: {dist: exponential, rate: 0.1, spawn: sign_up} orders: {dist: exponential, rate: 1, spawn: place_order} tasks: sign_up: payload: customer_id: {gen: sequence} tier: gen: weighted options: {basic: 70, plus: 25, pro: 5} place_order: vars: customer: {gen: lookup, task: sign_up} payload: order_id: {gen: sequence} customer_id: {gen: var, name: customer, path: customer_id} tier: {gen: var, name: customer, path: tier} amount: {gen: uniform, low: 5, high: 200, decimals: 2} run: {until: 300} ``` ```text {"stream_type":"event","sim_ts":42.95160161372071,"timestamp":"...","key":"signups-1","task":"sign_up","instance":0,"value":{"customer_id":0,"tier":"plus"}} {"stream_type":"event","sim_ts":44.816407163479376,"timestamp":"...","key":"orders-33","task":"place_order","instance":32,"value":{"order_id":0,"customer_id":0,"tier":"plus","amount":48.5}} {"stream_type":"event","sim_ts":45.43549590251013,"timestamp":"...","key":"orders-34","task":"place_order","instance":33,"value":{"order_id":1,"customer_id":0,"tier":"plus","amount":121.18}} {"stream_type":"event","sim_ts":45.58801673322658,"timestamp":"...","key":"orders-35","task":"place_order","instance":34,"value":{"order_id":2,"customer_id":0,"tier":"plus","amount":192.09}} {"stream_type":"event","sim_ts":45.75519547391547,"timestamp":"...","key":"orders-36","task":"place_order","instance":35,"value":{"order_id":3,"customer_id":0,"tier":"plus","amount":154.2}} ``` The Builder file builds the same model with the builder API and prints every record of its run: ```bash python examples/gallery/orders_carry_the_customers_tier_builder.py ``` ```python """Each order carries the tier of the customer who placed it. The Builder form of orders_carry_the_customers_tier.yaml, with the same records. Customers sign up with a tier, and each order reads one sign-up row, so its customer id and tier agree. An order placed before any customer has signed up is dropped. Needs: nothing Run it with: python examples/gallery/orders_carry_the_customers_tier_builder.py """ import logging from datetime import datetime from desflow import ConsoleEgress, SimulationContext from desflow.values import Template UNTIL = 300 def build() -> SimulationContext: """Builds the model.""" app = ( SimulationContext( sim_id="Shop", factor=0, random_seed=42, logical_start_time=datetime(2026, 1, 1), ) .add_egress(ConsoleEgress()) .add_arrival("signups", "exponential", rate=0.1, spawn="sign_up") .add_arrival("orders", "exponential", rate=1, spawn="place_order") ) sign_up_payload = Template( { "customer_id": {"gen": "sequence"}, "tier": { "gen": "weighted", "options": {"basic": 70, "plus": 25, "pro": 5}, }, }, name="tasks.sign_up", ) place_order_payload = Template( { "order_id": {"gen": "sequence"}, "customer_id": {"gen": "var", "name": "customer", "path": "customer_id"}, "tier": {"gen": "var", "name": "customer", "path": "tier"}, "amount": {"gen": "uniform", "low": 5, "high": 200, "decimals": 2}, }, name="tasks.place_order", vars={"customer": {"gen": "lookup", "task": "sign_up"}}, ) # history is the number of rows a blueprint keeps (1_000_000 here, as in the YAML); # place_order looks up the sign-up rows @app.task(name="sign_up", history=1_000_000) def sign_up(task_id): return sign_up_payload @app.task(name="place_order") def place_order(task_id): return place_order_payload return app if __name__ == "__main__": logging.basicConfig(level=logging.INFO, format="%(levelname)s %(message)s") build().run(until=UNTIL) ``` The Low-level file builds the model on `DynamicRealtimeEnvironment`, with plain Python processes, and prints every record of its run: ```bash python examples/gallery/orders_carry_the_customers_tier_low_level.py ``` The Low-level file draws each value with `Sampler.generator()`, where the place is the key path of the blueprint's generator that makes the same value, such as `tasks.sign_up.payload.tier`, `tasks.place_order.vars.customer` and `tasks.place_order.payload.amount`. Each draw therefore comes from the random sequence the blueprint uses at the same place, so the draws are the blueprint's. The gaps between arrivals come from `Sampler.sample` on a `DistributionConfig` whose `stream` is `arrival.signups` and `arrival.orders`, the sequences the blueprint uses for its arrivals. ```python """Each order carries the tier of the customer who placed it. The Low-level form of orders_carry_the_customers_tier.yaml, with the same records, built on `DynamicRealtimeEnvironment`. Customers sign up with a tier, and each order reads one sign-up row, so its customer id and tier agree. An order placed before any customer has signed up is dropped. Needs: nothing Run it with: python examples/gallery/orders_carry_the_customers_tier_low_level.py """ import itertools import logging from datetime import datetime from desflow import ( ConsoleEgress, DistributionConfig, DynamicRealtimeEnvironment, Sampler, ) SEED = 42 UNTIL = 300 TIERS = {"basic": 70, "plus": 25, "pro": 5} def weighted(rng, options): """One key of `options`, chosen by its weight, as the `weighted` generator does.""" point = rng.random() * sum(options.values()) running = 0.0 for value, weight in options.items(): running += weight if point < running: return value return value def build(env): """Starts the sign-up and order sources on `env`.""" sampler = Sampler(seed=SEED) tier = sampler.generator("tasks.sign_up.payload.tier") pick = sampler.generator("tasks.place_order.vars.customer") amount = sampler.generator("tasks.place_order.payload.amount") signup_gap = DistributionConfig(dist="exponential", rate=0.1) signup_gap.stream = "arrival.signups" order_gap = DistributionConfig(dist="exponential", rate=1) order_gap.stream = "arrival.orders" customers = [] # the sign-ups so far, oldest first order_ids = itertools.count() # the `sequence` of the published orders def signups(): for number in itertools.count(1): yield env.timeout(sampler.sample(signup_gap)) customer = {"customer_id": number - 1, "tier": weighted(tier, TIERS)} customers.append(customer) env.publish_event( f"signups-{number}", customer, task="sign_up", instance=number - 1 ) def orders(): for number in itertools.count(1): yield env.timeout(sampler.sample(order_gap)) # The blueprint drops an order that arrives before the first sign-up, and # the dropped order keeps its number if not customers: continue customer = customers[int(pick.integers(len(customers)))] payload = { "order_id": next(order_ids), "customer_id": customer["customer_id"], "tier": customer["tier"], "amount": round(5 + (200 - 5) * amount.random(), 2), } env.publish_event( f"orders-{number}", payload, task="place_order", instance=number - 1 ) env.process(signups()) env.process(orders()) def run(): """Runs the model for 300 simulation seconds.""" env = DynamicRealtimeEnvironment(factor=0, logical_start_time=datetime(2026, 1, 1)) env.setup_egress([ConsoleEgress()]) build(env) try: env.run(until=UNTIL) finally: env.teardown() if __name__ == "__main__": logging.basicConfig(level=logging.INFO, format="%(levelname)s %(message)s") run() ``` ### A stolen card makes three large payments seconds after a normal one Payments arrive from twenty cards, and 3 percent of them come from a card that has just been stolen. Two seconds later the same card makes three large payments, and every record is keyed by its card. Run it with the sample option, which stops after the first events and prints them: ```bash desflow run examples/gallery/stolen_card_makes_three_large_payments.yaml --sample 5 ``` ```yaml # A stolen card makes three large payments seconds after a normal one. # # Payments arrive from twenty cards, and 3 percent of them come from a card that has # just been stolen. Two seconds later the same card makes three large payments, and # every record is keyed by its card. # # Needs: nothing # Run it with: desflow run examples/gallery/stolen_card_makes_three_large_payments.yaml simulation: sim_id: Bank factor: 0 random_seed: 42 logical_start_time: 2026-01-01T00:00:00 egress: - {type: Console} arrivals: payments: dist: exponential rate: 1 vars: card: {gen: integer, bounds: [1, 20]} key: {gen: format, template: "card-{card}"} spawn: payment tasks: payment: payload: card: {gen: expr, expr: process.key} amount: {gen: uniform, low: 5, high: 120, decimals: 2} stolen: {gen: boolean, p: 0.03} next: when: - {condition: payload.stolen, task: burst} burst: payload: null spawn: task: large_payment count: 3 after: 2 args: card: {gen: upstream, path: card} large_payment: key: {gen: expr, expr: arg.card} payload: card: {gen: expr, expr: arg.card} amount: {gen: uniform, low: 500, high: 2000, decimals: 2} fraud: true run: {until: 600} ``` ```text {"stream_type":"event","sim_ts":2.081546583669206,"timestamp":"...","key":"card-4","task":"payment","instance":0,"value":{"card":"card-4","amount":46.73,"stolen":false}} {"stream_type":"event","sim_ts":2.859436022312404,"timestamp":"...","key":"card-3","task":"payment","instance":1,"value":{"card":"card-3","amount":9.54,"stolen":false}} {"stream_type":"event","sim_ts":2.9829212161369547,"timestamp":"...","key":"card-7","task":"payment","instance":2,"value":{"card":"card-7","amount":22.7,"stolen":false}} {"stream_type":"event","sim_ts":3.93943343963651,"timestamp":"...","key":"card-20","task":"payment","instance":3,"value":{"card":"card-20","amount":36.17,"stolen":false}} {"stream_type":"event","sim_ts":4.129047924723884,"timestamp":"...","key":"card-20","task":"payment","instance":4,"value":{"card":"card-20","amount":28.54,"stolen":false}} ``` The Builder file builds the same model with the builder API and prints every record of its run: ```bash python examples/gallery/stolen_card_makes_three_large_payments_builder.py ``` ```python """A stolen card makes three large payments seconds after a normal one. The Builder form of stolen_card_makes_three_large_payments.yaml, with the same records. Payments arrive from twenty cards, and 3 percent of them come from a card that has just been stolen. Two seconds later the same card makes three large payments. Needs: nothing Run it with: python examples/gallery/stolen_card_makes_three_large_payments_builder.py """ import logging from datetime import datetime from desflow import NO_RECORD, ConsoleEgress, SimulationContext from desflow.values import Template, generator UNTIL = 600 def build() -> SimulationContext: """Builds the model.""" app = ( SimulationContext( sim_id="Bank", factor=0, random_seed=42, logical_start_time=datetime(2026, 1, 1), ) .add_egress(ConsoleEgress()) .add_arrival( "payments", "exponential", rate=1, vars={"card": generator({"gen": "integer", "bounds": [1, 20]})}, key=generator({"gen": "format", "template": "card-{card}"}), spawn="payment", ) ) payment_payload = Template( { "card": {"gen": "expr", "expr": "process.key"}, "amount": {"gen": "uniform", "low": 5, "high": 120, "decimals": 2}, "stolen": {"gen": "boolean", "p": 0.03}, }, name="tasks.payment", ) large_payment_payload = Template( { "card": {"gen": "expr", "expr": "arg.card"}, "amount": {"gen": "uniform", "low": 500, "high": 2000, "decimals": 2}, "fraud": True, }, name="tasks.large_payment", ) @app.task( name="payment", next={"when": [{"condition": "payload.stolen", "task": "burst"}]}, ) def payment(task_id): return payment_payload @app.task( name="burst", spawn={ "task": "large_payment", "count": 3, "after": 2, "args": {"card": generator({"gen": "upstream", "path": "card"})}, }, ) def burst(task_id): return NO_RECORD @app.task(name="large_payment", key=generator({"gen": "expr", "expr": "arg.card"})) def large_payment(task_id): return large_payment_payload return app if __name__ == "__main__": logging.basicConfig(level=logging.INFO, format="%(levelname)s %(message)s") build().run(until=UNTIL) ``` The Low-level file builds the model on `DynamicRealtimeEnvironment`, with plain Python processes, and prints every record of its run: ```bash python examples/gallery/stolen_card_makes_three_large_payments_low_level.py ``` The Low-level file draws each value with `Sampler.generator()`, where the place is the key path of the blueprint's generator that makes the same value, such as `arrivals.payments.vars.card`, `tasks.payment.payload.amount` and `tasks.payment.payload.stolen` and 1 more. Each draw therefore comes from the random sequence the blueprint uses at the same place, so the draws are the blueprint's. The gaps between arrivals come from `Sampler.sample` on a `DistributionConfig` whose `stream` is `arrival.payments`, the sequence the blueprint uses for its arrivals. ```python """A stolen card makes three large payments seconds after a normal one. The Low-level form of stolen_card_makes_three_large_payments.yaml, with the same records, built on `DynamicRealtimeEnvironment`. Payments arrive from twenty cards, and 3 percent of them come from a card that has just been stolen. Two seconds later the same card makes three large payments. Needs: nothing Run it with: python examples/gallery/stolen_card_makes_three_large_payments_low_level.py """ import itertools import logging from datetime import datetime from desflow import ( ConsoleEgress, DistributionConfig, DynamicRealtimeEnvironment, Sampler, ) SEED = 42 UNTIL = 600 def build(env): """Starts the payment source on `env`.""" sampler = Sampler(seed=SEED) gap = DistributionConfig(dist="exponential", rate=1) gap.stream = "arrival.payments" pick_card = sampler.generator("arrivals.payments.vars.card") amount = sampler.generator("tasks.payment.payload.amount") stolen = sampler.generator("tasks.payment.payload.stolen") large_amount = sampler.generator("tasks.large_payment.payload.amount") instances = {"payment": itertools.count(), "large_payment": itertools.count()} def stolen_card(card): """Three large payments on the card, two seconds after the normal one.""" yield env.timeout(2) for _ in range(3): payload = { "card": card, "amount": round(500 + (2000 - 500) * large_amount.random(), 2), "fraud": True, } env.publish_event( card, payload, task="large_payment", instance=next(instances["large_payment"]), ) def payments(): for _ in itertools.count(): yield env.timeout(sampler.sample(gap)) card = f"card-{int(pick_card.integers(1, 21))}" payload = { "card": card, "amount": round(5 + (120 - 5) * amount.random(), 2), "stolen": bool(stolen.random() < 0.03), } env.publish_event( card, payload, task="payment", instance=next(instances["payment"]) ) if payload["stolen"]: env.process(stolen_card(card)) env.process(payments()) def run(): """Runs the model for 600 simulation seconds.""" env = DynamicRealtimeEnvironment(factor=0, logical_start_time=datetime(2026, 1, 1)) env.setup_egress([ConsoleEgress()]) build(env) try: env.run(until=UNTIL) finally: env.teardown() if __name__ == "__main__": logging.basicConfig(level=logging.INFO, format="%(levelname)s %(message)s") run() ``` ### Stock queries read the latest level of each product Five products change their stock level by a few units every 5 seconds, each from its own last level, and the first change is at the start. Queries ask for the level of one product and get the level its latest update gave. Run it with the sample option, which stops after the first events and prints them: ```bash desflow run examples/gallery/stock_queries_read_the_latest_level.yaml --sample 5 ``` ```yaml # Stock queries read the latest level of each product. # # Five products change their stock level by a few units every 5 seconds, each from its # own last level, and the first change is at the start. Queries ask for the level of # one product and get the level its latest update gave. # # Needs: nothing # Run it with: desflow run examples/gallery/stock_queries_read_the_latest_level.yaml simulation: sim_id: Warehouse factor: 0 random_seed: 42 logical_start_time: 2026-01-01T00:00:00 egress: - {type: Console} arrivals: updates: count: 5 key: {gen: sequence, start: 1, format: "sku-{}"} dist: constant value: 5 first_at: 0 spawn: update_stock queries: {dist: exponential, rate: 0.5, spawn: read_stock} tasks: update_stock: payload: sku: {gen: entity} level: gen: max args: - 0 - gen: add args: - {gen: previous, path: level, default: 100} - {gen: integer, bounds: [-12, 10]} read_stock: vars: row: {gen: lookup, task: update_stock, latest_by: sku} payload: sku: {gen: var, name: row, path: sku} level: {gen: var, name: row, path: level} run: {until: 200} ``` ```text {"stream_type":"event","sim_ts":0.0,"timestamp":"...","key":"sku-1","task":"update_stock","instance":0,"value":{"sku":"sku-1","level":96}} {"stream_type":"event","sim_ts":0.0,"timestamp":"...","key":"sku-2","task":"update_stock","instance":1,"value":{"sku":"sku-2","level":103}} {"stream_type":"event","sim_ts":0.0,"timestamp":"...","key":"sku-3","task":"update_stock","instance":2,"value":{"sku":"sku-3","level":103}} {"stream_type":"event","sim_ts":0.0,"timestamp":"...","key":"sku-4","task":"update_stock","instance":3,"value":{"sku":"sku-4","level":94}} {"stream_type":"event","sim_ts":0.0,"timestamp":"...","key":"sku-5","task":"update_stock","instance":4,"value":{"sku":"sku-5","level":93}} ``` The Builder file builds the same model with the builder API and prints every record of its run: ```bash python examples/gallery/stock_queries_read_the_latest_level_builder.py ``` ```python """Stock queries read the latest level of each product. The Builder form of stock_queries_read_the_latest_level.yaml, with the same records. A blueprint's `count: 5` is five arrivals here, one for each product, each with the key of its product. Queries look up the latest update of one product. Needs: nothing Run it with: python examples/gallery/stock_queries_read_the_latest_level_builder.py """ import logging from datetime import datetime from desflow import ConsoleEgress, SimulationContext from desflow.values import Template UNTIL = 200 def build() -> SimulationContext: """Builds the model.""" app = SimulationContext( sim_id="Warehouse", factor=0, random_seed=42, logical_start_time=datetime(2026, 1, 1), ).add_egress(ConsoleEgress()) for number in range(1, 6): app.add_arrival( f"updates{number}", "constant", value=5, first_at=0, spawn="update_stock", key=lambda n, number=number: f"sku-{number}", ) app.add_arrival("queries", "exponential", rate=0.5, spawn="read_stock") update_payload = Template( { "sku": {"gen": "entity"}, "level": { "gen": "max", "args": [ 0, { "gen": "add", "args": [ {"gen": "previous", "path": "level", "default": 100}, {"gen": "integer", "bounds": [-12, 10]}, ], }, ], }, }, name="tasks.update_stock", ) read_payload = Template( { "sku": {"gen": "var", "name": "row", "path": "sku"}, "level": {"gen": "var", "name": "row", "path": "level"}, }, name="tasks.read_stock", vars={"row": {"gen": "lookup", "task": "update_stock", "latest_by": "sku"}}, ) # history is the number of rows a blueprint keeps (1_000_000 here, as in the YAML); # read_stock looks up the update rows @app.task(name="update_stock", history=1_000_000) def update_stock(task_id): return update_payload @app.task(name="read_stock") def read_stock(task_id): return read_payload return app if __name__ == "__main__": logging.basicConfig(level=logging.INFO, format="%(levelname)s %(message)s") build().run(until=UNTIL) ``` The Low-level file builds the model on `DynamicRealtimeEnvironment`, with plain Python processes, and prints every record of its run: ```bash python examples/gallery/stock_queries_read_the_latest_level_low_level.py ``` The Low-level file draws each value with `Sampler.generator()`, where the place is the key path of the blueprint's generator that makes the same value, such as `tasks.update_stock.payload.level.args.1.args.1` and `tasks.read_stock.vars.row`. Each draw therefore comes from the random sequence the blueprint uses at the same place, so the draws are the blueprint's. The gaps between arrivals come from `Sampler.sample` on a `DistributionConfig` whose `stream` is `arrival.queries`, the sequence the blueprint uses for its arrivals. ```python """Stock queries read the latest level of each product. The Low-level form of stock_queries_read_the_latest_level.yaml, with the same records, built on `DynamicRealtimeEnvironment`. Each draw is made with `Sampler`, from the random sequence the blueprint's generator at that place uses, so the draws are the blueprint's. A product's new level is its last level plus the change. A query draws one of the products, which is what `lookup` with `latest_by` does, and reads its last level. Needs: nothing Run it with: python examples/gallery/stock_queries_read_the_latest_level_low_level.py """ import itertools import logging from datetime import datetime from desflow import ( ConsoleEgress, DistributionConfig, DynamicRealtimeEnvironment, Sampler, ) SEED = 42 UNTIL = 200 def build(env): """Starts the five product loops and the query source on `env`.""" sampler = Sampler(seed=SEED) change = sampler.generator("tasks.update_stock.payload.level.args.1.args.1") pick = sampler.generator("tasks.read_stock.vars.row") gap = DistributionConfig(dist="exponential", rate=0.5) gap.stream = "arrival.queries" instances = itertools.count() levels = {} # the last level of each product def product(number): sku = f"sku-{number}" for _ in itertools.count(): level = max(0, levels.get(sku, 100) + int(change.integers(-12, 11))) levels[sku] = level env.publish_event( sku, {"sku": sku, "level": level}, task="update_stock", instance=next(instances), ) yield env.timeout(5) def queries(): for number in itertools.count(1): yield env.timeout(sampler.sample(gap)) # The products first appear in the order 1 to 5, and each has a latest level sku = f"sku-{int(pick.integers(len(levels))) + 1}" env.publish_event( f"queries-{number}", {"sku": sku, "level": levels[sku]}, task="read_stock", instance=number - 1, ) for number in range(1, 6): env.process(product(number)) env.process(queries()) def run(): """Runs the model for 200 simulation seconds.""" env = DynamicRealtimeEnvironment(factor=0, logical_start_time=datetime(2026, 1, 1)) env.setup_egress([ConsoleEgress()]) build(env) try: env.run(until=UNTIL) finally: env.teardown() if __name__ == "__main__": logging.basicConfig(level=logging.INFO, format="%(levelname)s %(message)s") run() ``` ### Each request becomes a trace of nested spans, and each child span names its parent The gateway span covers an auth check and a database call that run inside it, so each child starts and ends within its parent's time. Every span has the trace id of its request, an id of its own, its parent's id (null for the gateway span), its start in seconds from the start of the run and its duration in milliseconds. Run it with the sample option, which stops after the first events and prints them: ```bash desflow run examples/gallery/requests_become_traces_of_nested_spans.yaml --sample 5 ``` ```yaml # Each request becomes a trace of nested spans, and each child span names its parent. # # The gateway span covers an auth check and a database call that run inside it, so each # child starts and ends within its parent's time. Every span has the trace id of its # request, an id of its own, its parent's id (null for the gateway span), its start in # seconds from the start of the run and its duration in milliseconds. # # Needs: nothing # Run it with: desflow run examples/gallery/requests_become_traces_of_nested_spans.yaml simulation: sim_id: Api factor: 0 random_seed: 42 logical_start_time: 2026-01-01T00:00:00 egress: - {type: Console} arrivals: requests: dist: exponential rate: 0.5 attributes: trace_id: {gen: uuid} gateway_span: {gen: uuid} began: {gen: expr, expr: t} spawn: auth # A span's record is published when it ends, so the children come before the gateway tasks: auth: vars: duration: {gen: integer, bounds: [5, 15]} service_time: duration / 1000 payload: trace_id: {gen: attr, name: trace_id} span_id: {gen: uuid} parent_span_id: {gen: attr, name: gateway_span} name: check token start: {gen: expr, expr: "t - duration / 1000"} duration_ms: {gen: var, name: duration} next: orders_db orders_db: vars: duration: {gen: integer, bounds: [10, 120]} service_time: duration / 1000 payload: trace_id: {gen: attr, name: trace_id} span_id: {gen: uuid} parent_span_id: {gen: attr, name: gateway_span} name: SELECT orders start: {gen: expr, expr: "t - duration / 1000"} duration_ms: {gen: var, name: duration} next: gateway gateway: vars: duration: {gen: integer, bounds: [20, 60]} service_time: duration / 1000 payload: trace_id: {gen: attr, name: trace_id} span_id: {gen: attr, name: gateway_span} parent_span_id: null name: GET /orders start: {gen: attr, name: began} duration_ms: {gen: expr, expr: "round((t - attr.began) * 1000, 3)"} run: {until: 120} ``` ```text {"stream_type":"event","sim_ts":0.9203554340231125,"timestamp":"...","key":"requests-1","task":"auth","instance":0,"value":{"status":"started"}} {"stream_type":"event","sim_ts":0.9263554340231125,"timestamp":"...","key":"requests-1","task":"auth","instance":0,"value":{"trace_id":"fbf20686-5abf-4ade-9510-ae446054562c","span_id":"5f760756-dd54-4de5-aabd-4788a813c817","parent_span_id":"218acc9a-37ea-463c-b078-b0bdd04140aa","name":"check token","start":0.9203554340231125,"duration_ms":6}} {"stream_type":"event","sim_ts":0.9263554340231125,"timestamp":"...","key":"requests-1","task":"orders_db","instance":0,"value":{"status":"started"}} {"stream_type":"event","sim_ts":1.0103554340231125,"timestamp":"...","key":"requests-1","task":"orders_db","instance":0,"value":{"trace_id":"fbf20686-5abf-4ade-9510-ae446054562c","span_id":"3eb6d72c-3be1-4f2f-b392-061e4d0579ab","parent_span_id":"218acc9a-37ea-463c-b078-b0bdd04140aa","name":"SELECT orders","start":0.9263554340231125,"duration_ms":84}} {"stream_type":"event","sim_ts":1.0103554340231125,"timestamp":"...","key":"requests-1","task":"gateway","instance":0,"value":{"status":"started"}} ``` The Builder file builds the same model with the builder API and prints every record of its run: ```bash python examples/gallery/requests_become_traces_of_nested_spans_builder.py ``` ```python """Each request becomes a trace of nested spans, and each child span names its parent. The Builder form of requests_become_traces_of_nested_spans.yaml, with the same records. The gateway span covers an auth check and a database call that run inside it, so each child starts and ends within its parent's time. Needs: nothing Run it with: python examples/gallery/requests_become_traces_of_nested_spans_builder.py """ import logging from datetime import datetime from desflow import ConsoleEgress, SimulationContext from desflow.values import Template, generator UNTIL = 120 def duration(low, high): """The task's `duration` var, drawn once for each span, in milliseconds.""" return {"duration": generator({"gen": "integer", "bounds": [low, high]})} def child_span(task, name): """The payload of a span inside the gateway span, whose id is its parent's id.""" return Template( { "trace_id": {"gen": "attr", "name": "trace_id"}, "span_id": {"gen": "uuid"}, "parent_span_id": {"gen": "attr", "name": "gateway_span"}, "name": name, "start": {"gen": "expr", "expr": "t - duration / 1000"}, "duration_ms": {"gen": "var", "name": "duration"}, }, name=f"tasks.{task}", ) gateway_payload = Template( { "trace_id": {"gen": "attr", "name": "trace_id"}, "span_id": {"gen": "attr", "name": "gateway_span"}, "parent_span_id": None, "name": "GET /orders", "start": {"gen": "attr", "name": "began"}, "duration_ms": {"gen": "expr", "expr": "round((t - attr.began) * 1000, 3)"}, }, name="tasks.gateway", ) def build() -> SimulationContext: """Builds the model.""" app = ( SimulationContext( sim_id="Api", factor=0, random_seed=42, logical_start_time=datetime(2026, 1, 1), ) .add_egress(ConsoleEgress()) .add_arrival( "requests", "exponential", rate=0.5, attributes={ "trace_id": generator({"gen": "uuid"}), "gateway_span": generator({"gen": "uuid"}), "began": generator({"gen": "expr", "expr": "t"}), }, spawn="auth", ) ) # A span's record is published when it ends, so the children come before the gateway auth_payload = child_span("auth", "check token") orders_db_payload = child_span("orders_db", "SELECT orders") @app.task( name="auth", vars=duration(5, 15), service_time="duration / 1000", next="orders_db", ) def auth(task_id): return auth_payload @app.task( name="orders_db", vars=duration(10, 120), service_time="duration / 1000", next="gateway", ) def orders_db(task_id): return orders_db_payload @app.task(name="gateway", vars=duration(20, 60), service_time="duration / 1000") def gateway(task_id): return gateway_payload return app if __name__ == "__main__": logging.basicConfig(level=logging.INFO, format="%(levelname)s %(message)s") build().run(until=UNTIL) ``` The Low-level file builds the model on `DynamicRealtimeEnvironment`, with plain Python processes, and prints every record of its run: ```bash python examples/gallery/requests_become_traces_of_nested_spans_low_level.py ``` The Low-level file draws each value with `Sampler.generator()`, where the place is the key path of the blueprint's generator that makes the same value, such as `arrivals.requests.attributes.trace_id` and `arrivals.requests.attributes.gateway_span`. Each draw therefore comes from the random sequence the blueprint uses at the same place, so the draws are the blueprint's. The gaps between arrivals come from `Sampler.sample` on a `DistributionConfig` whose `stream` is `arrival.requests`, the sequence the blueprint uses for its arrivals. ```python """Each request becomes a trace of nested spans, and each child span names its parent. The Low-level form of requests_become_traces_of_nested_spans.yaml, with the same records, built on `DynamicRealtimeEnvironment`. The gateway span covers an auth check and a database call that run inside it, so each child starts and ends within its parent's time. Needs: nothing Run it with: python examples/gallery/requests_become_traces_of_nested_spans_low_level.py """ import itertools import logging import uuid from datetime import datetime from desflow import ( ConsoleEgress, DistributionConfig, DynamicRealtimeEnvironment, Sampler, ) SEED = 42 UNTIL = 120 # The tasks of a request in order: the task, the span's name and its duration range in ms SPANS = [ ("auth", "check token", 5, 15), ("orders_db", "SELECT orders", 10, 120), ("gateway", "GET /orders", 20, 60), ] def build(env): """Starts the request source on `env`.""" sampler = Sampler(seed=SEED) gap = DistributionConfig(dist="exponential", rate=0.5) gap.stream = "arrival.requests" duration = { task: sampler.generator(f"tasks.{task}.vars.duration") for task, *_ in SPANS } trace_id = sampler.generator("arrivals.requests.attributes.trace_id") gateway_span = sampler.generator("arrivals.requests.attributes.gateway_span") span_id = { task: sampler.generator(f"tasks.{task}.payload.span_id") for task, *_ in SPANS if task != "gateway" } # Each task numbers its own instances instances = {task: itertools.count() for task, *_ in SPANS} def uuid_of(rng): return str(uuid.UUID(bytes=rng.bytes(16), version=4)) def request(key): # The trace and the gateway span are the request's own, and the children name them trace, gateway, began = uuid_of(trace_id), uuid_of(gateway_span), env.now for task, name, low, high in SPANS: instance = next(instances[task]) milliseconds = int(duration[task].integers(low, high + 1)) env.publish_event(key, {"status": "started"}, task=task, instance=instance) yield env.timeout(milliseconds / 1000) span = { "trace_id": trace, "span_id": gateway if task == "gateway" else uuid_of(span_id[task]), "parent_span_id": None if task == "gateway" else gateway, "name": name, "start": began if task == "gateway" else env.now - milliseconds / 1000, "duration_ms": ( round((env.now - began) * 1000, 3) if task == "gateway" else milliseconds ), } env.publish_event(key, span, task=task, instance=instance) def requests(): for number in itertools.count(1): yield env.timeout(sampler.sample(gap)) env.process(request(f"requests-{number}")) env.process(requests()) def run(): """Runs the model for 120 simulation seconds.""" env = DynamicRealtimeEnvironment(factor=0, logical_start_time=datetime(2026, 1, 1)) env.setup_egress([ConsoleEgress()]) build(env) try: env.run(until=UNTIL) finally: env.teardown() if __name__ == "__main__": logging.basicConfig(level=logging.INFO, format="%(levelname)s %(message)s") run() ``` ### A customer table's changes are written to Kafka, and each delete is a tombstone Ten customers exist at the start, then inserts, updates and deletes arrive in the shares 40, 45 and 15 percent, each keyed by its customer id. A delete has no value, which is how Kafka marks a deleted key (a tombstone), and the oldest customer is deleted first. It needs a broker, started with `odctl up kafka-lite`, and the `kafka` extra. A delete is published as a Kafka tombstone, a record with a key and no value, so this entry shows no output block here. Run it with the sample option, which stops after the first events and prints them: ```bash desflow run examples/gallery/customer_deletes_become_kafka_tombstones.yaml --sample 5 ``` ```yaml # A customer table's changes are written to Kafka, and each delete is a tombstone. # # Ten customers exist at the start, then inserts, updates and deletes arrive in the # shares 40, 45 and 15 percent, each keyed by its customer id. A delete has no value, # which is how Kafka marks a deleted key (a tombstone), and the oldest customer is # deleted first. # # Needs: odctl up kafka-lite and the kafka extra # Run it with: desflow run # examples/gallery/customer_deletes_become_kafka_tombstones.yaml simulation: sim_id: Customers factor: 0 random_seed: 42 logical_start_time: 2026-01-01T00:00:00 egress: - type: Kafka envelope: false config: bootstrap_servers: ${KAFKA_BOOTSTRAP_SERVERS:-127.0.0.1:9092} event_topic: customers-cdc arrivals: existing: {initial: 10, spawn: insert_customer} changes: {dist: exponential, rate: 1, spawn: change} tasks: change: payload: null next: weights: {insert_customer: 40, update_customer: 45, delete_customer: 15} insert_customer: key_field: customer_id payload: op: insert customer_id: {gen: sequence} plan: gen: weighted options: {free: 60, pro: 40} # An update changes the newest customer, so no record names a customer that is gone update_customer: key_field: customer_id payload: op: update customer_id: gen: lookup task: insert_customer path: customer_id strategy: last plan: gen: weighted options: {free: 40, pro: 60} delete_customer: key: {gen: sequence} payload: {gen: literal, value: null} run: {until: 120} ``` The Builder file builds the same model with the builder API and prints every record of its run: ```bash python examples/gallery/customer_deletes_become_kafka_tombstones_builder.py ``` ```python """A customer table's changes are written to Kafka, and each delete is a tombstone. The Builder form of customer_deletes_become_kafka_tombstones.yaml, with the same records. Every message is keyed by its customer id, and a delete has no value, so with `envelope=False` the Kafka sink sends it as a tombstone. Needs: odctl up kafka-lite and the kafka extra Run it with: python examples/gallery/customer_deletes_become_kafka_tombstones_builder.py """ import os from datetime import datetime from desflow import NO_RECORD, KafkaEgress, SimulationContext from desflow.values import Template, generator BOOTSTRAP_SERVERS = os.getenv("KAFKA_BOOTSTRAP_SERVERS", "127.0.0.1:9092") UNTIL = 120 def build() -> SimulationContext: """Builds the model.""" app = ( SimulationContext( sim_id="Customers", factor=0, random_seed=42, logical_start_time=datetime(2026, 1, 1), ) # envelope=False sends each event's value alone, and a null value as a tombstone .add_egress( KafkaEgress( bootstrap_servers=BOOTSTRAP_SERVERS, event_topic="customers-cdc" ), envelope=False, ) .add_initial_arrival("existing", 10, spawn="insert_customer") .add_arrival("changes", "exponential", rate=1, spawn="change") ) insert_payload = Template( { "op": "insert", "customer_id": {"gen": "sequence"}, "plan": {"gen": "weighted", "options": {"free": 60, "pro": 40}}, }, name="tasks.insert_customer", ) update_payload = Template( { "op": "update", "customer_id": { "gen": "lookup", "task": "insert_customer", "path": "customer_id", "strategy": "last", }, "plan": {"gen": "weighted", "options": {"free": 40, "pro": 60}}, }, name="tasks.update_customer", ) # One generator that gives null: the task publishes a record whose value is null delete_payload = Template( {"gen": "literal", "value": None}, name="tasks.delete_customer" ) @app.task( name="change", next={ "weights": { "insert_customer": 40, "update_customer": 45, "delete_customer": 15, } }, ) def change(task_id): return NO_RECORD # history is the number of rows a blueprint keeps (1_000_000 here, as in the YAML); # update_customer looks up the insert rows @app.task(name="insert_customer", key_field="customer_id", history=1_000_000) def insert_customer(task_id): return insert_payload @app.task(name="update_customer", key_field="customer_id") def update_customer(task_id): return update_payload @app.task(name="delete_customer", key=generator({"gen": "sequence"})) def delete_customer(task_id): return delete_payload return app if __name__ == "__main__": build().run(until=UNTIL) ``` The Low-level file builds the model on `DynamicRealtimeEnvironment`, with plain Python processes, and prints every record of its run: ```bash python examples/gallery/customer_deletes_become_kafka_tombstones_low_level.py ``` The Low-level file draws each value with `Sampler.generator()`, where the place is the key path of the blueprint's generator that makes the same value, such as `tasks.insert_customer.payload.plan` and `tasks.update_customer.payload.plan`. Each draw therefore comes from the random sequence the blueprint uses at the same place, so the draws are the blueprint's. The branch of each step is chosen by a `Router` whose random sequence is `Sampler.generator("route.change")`, the sequence of the blueprint's `next`. The gaps between arrivals come from `Sampler.sample` on a `DistributionConfig` whose `stream` is `arrival.changes`, the sequence the blueprint uses for its arrivals. ```python """A customer table's changes are written to Kafka, and each delete is a tombstone. The Low-level form of customer_deletes_become_kafka_tombstones.yaml, with the same records, built on `DynamicRealtimeEnvironment`. `publish_event(key, None)` publishes a delete, and a Kafka sink set up with `envelopes=[False]` sends it as a tombstone. Needs: odctl up kafka-lite and the kafka extra Run it with: python examples/gallery/customer_deletes_become_kafka_tombstones_low_level.py """ import itertools import os from datetime import datetime from desflow import ( DistributionConfig, DynamicRealtimeEnvironment, KafkaEgress, Router, Sampler, ) SEED = 42 UNTIL = 120 BOOTSTRAP_SERVERS = os.getenv("KAFKA_BOOTSTRAP_SERVERS", "127.0.0.1:9092") def weighted(rng, options): """One key of `options`, chosen by its weight, as the `weighted` generator does.""" point = rng.random() * sum(options.values()) running = 0.0 for value, weight in options.items(): running += weight if point < running: return value return value def build(env): """Starts the ten customers and the source of changes on `env`.""" sampler = Sampler(seed=SEED) insert_plan = sampler.generator("tasks.insert_customer.payload.plan") update_plan = sampler.generator("tasks.update_customer.payload.plan") router = Router( { "weights": { "insert_customer": 40, "update_customer": 45, "delete_customer": 15, } }, rng=sampler.generator("route.change"), ) gap = DistributionConfig(dist="exponential", rate=1) gap.stream = "arrival.changes" instances = { task: itertools.count() for task in ("insert_customer", "update_customer", "delete_customer") } customers = itertools.count() # the customer ids, as `sequence` counts deleted = itertools.count() # the oldest customer goes first inserted = [] # the customer ids of the inserts so far, oldest first def insert_customer(): payload = { "op": "insert", "customer_id": next(customers), "plan": weighted(insert_plan, {"free": 60, "pro": 40}), } inserted.append(payload["customer_id"]) env.publish_event( str(payload["customer_id"]), payload, task="insert_customer", instance=next(instances["insert_customer"]), ) def update_customer(): # An update changes the newest customer, as `lookup` with `strategy: last` does payload = { "op": "update", "customer_id": inserted[-1], "plan": weighted(update_plan, {"free": 40, "pro": 60}), } env.publish_event( str(payload["customer_id"]), payload, task="update_customer", instance=next(instances["update_customer"]), ) def delete_customer(): # A value of None is a tombstone for a Kafka sink with the envelope off env.publish_event( str(next(deleted)), None, task="delete_customer", instance=next(instances["delete_customer"]), ) def changes(): for _ in itertools.count(): yield env.timeout(sampler.sample(gap)) task = router.choose(None, env=env) { "insert_customer": insert_customer, "update_customer": update_customer, "delete_customer": delete_customer, }[task]() for _ in range(10): insert_customer() env.process(changes()) def run(): """Runs the model for 120 simulation seconds.""" env = DynamicRealtimeEnvironment(factor=0, logical_start_time=datetime(2026, 1, 1)) env.setup_egress( [KafkaEgress(bootstrap_servers=BOOTSTRAP_SERVERS, event_topic="customers-cdc")], envelopes=[False], ) build(env) try: env.run(until=UNTIL) finally: env.teardown() if __name__ == "__main__": run() ``` # Processes with Queues Nine processes in which entities wait for a resource or move through steps: orders that wait for busy packers, a machine that slows as it wears, a capacity that drops while the queue grows, callers who hang up, urgent tickets served first, shoppers who pay or abandon, visitors who drop out at each sign-up step, bets that are settled, and audits that need a follow-up. Each entry is a complete file in three forms. ______________________________________________________________________ ## Before You Start The commands run from the root of a clone of the repository, where the files are in `examples/gallery/`: ```bash git clone https://github.com/jaehyeon-kim/desflow.git cd desflow ``` An entry that needs a service or an extra says so. [Services for the Examples](https://jaehyeon.me/desflow/latest/gallery/#services-for-the-examples) shows how to start the services. A file with a fixed `random_seed` and `factor: 0` prints the same records on every run, and each output block below holds the first events of the YAML file. The Builder and Low-level files publish the same records. ______________________________________________________________________ ## Entries ### Orders wait in a queue when all packers are busy A shop has 3 packers. Orders arrive about once a minute, and packing takes a normal time with a mean of 240 s and a standard deviation of 60 s. The run lasts 2 hours. When all three packers are busy an order waits, and the minimal statistics publish the queue length and the units in use. Run it with the sample option, which stops after the first events and prints them: ```bash desflow run examples/gallery/orders_wait_for_busy_packers.yaml --sample 5 ``` ```yaml # Orders wait in a queue when all packers are busy. # # A shop has 3 packers. Orders arrive about once a minute, and packing takes a normal # time with a mean of 240 s and a standard deviation of 60 s. The run lasts 2 hours. # When all three packers are busy an order waits, and the minimal statistics publish # the queue length and the units in use. # # Needs: nothing # Run it with: desflow run examples/gallery/orders_wait_for_busy_packers.yaml simulation: sim_id: Shop factor: 0 random_seed: 42 logical_start_time: 2026-01-01T00:00:00 egress: - {type: Console} stats: {level: minimal} resources: packers: {current_cap: 3} services: pack: {dist: normal, mean: 240, std: 60} arrivals: orders: {dist: exponential, rate: 0.015, spawn: order} tasks: order: resource: packers service: pack id_field: order_id payload: {event_type: packed} run: {until: 2 hours} ``` ```text {"stream_type":"telemetry","sim_ts":10.0,"timestamp":"...","path_id":"Shop.stats.resources.packers.capacity","value":3} {"stream_type":"telemetry","sim_ts":10.0,"timestamp":"...","path_id":"Shop.stats.resources.packers.in_use","value":0} {"stream_type":"telemetry","sim_ts":10.0,"timestamp":"...","path_id":"Shop.stats.resources.packers.queue_length","value":0} {"stream_type":"telemetry","sim_ts":10.0,"timestamp":"...","path_id":"Shop.stats.resources.packers.utilization","value":0.0} {"stream_type":"telemetry","sim_ts":20.0,"timestamp":"...","path_id":"Shop.stats.resources.packers.capacity","value":3} {"stream_type":"telemetry","sim_ts":20.0,"timestamp":"...","path_id":"Shop.stats.resources.packers.in_use","value":0} {"stream_type":"telemetry","sim_ts":20.0,"timestamp":"...","path_id":"Shop.stats.resources.packers.queue_length","value":0} {"stream_type":"telemetry","sim_ts":20.0,"timestamp":"...","path_id":"Shop.stats.resources.packers.utilization","value":0.0} {"stream_type":"event","sim_ts":20.943711043131454,"timestamp":"...","key":"orders-1","task":"order","instance":0,"value":{"path_id":"Shop.service.pack","sim_id":"Shop","service":"pack","status":"queued"}} {"stream_type":"event","sim_ts":20.943711043131454,"timestamp":"...","key":"orders-1","task":"order","instance":0,"value":{"path_id":"Shop.service.pack","sim_id":"Shop","service":"pack","status":"started"}} {"stream_type":"telemetry","sim_ts":30.0,"timestamp":"...","path_id":"Shop.stats.resources.packers.capacity","value":3} {"stream_type":"telemetry","sim_ts":30.0,"timestamp":"...","path_id":"Shop.stats.resources.packers.in_use","value":1} {"stream_type":"telemetry","sim_ts":30.0,"timestamp":"...","path_id":"Shop.stats.resources.packers.queue_length","value":0} {"stream_type":"telemetry","sim_ts":30.0,"timestamp":"...","path_id":"Shop.stats.resources.packers.utilization","value":33.33333333333333} {"stream_type":"telemetry","sim_ts":30.0,"timestamp":"...","path_id":"Shop.stats.tasks.order.in_progress","value":1} {"stream_type":"telemetry","sim_ts":40.0,"timestamp":"...","path_id":"Shop.stats.resources.packers.capacity","value":3} {"stream_type":"telemetry","sim_ts":40.0,"timestamp":"...","path_id":"Shop.stats.resources.packers.in_use","value":1} {"stream_type":"telemetry","sim_ts":40.0,"timestamp":"...","path_id":"Shop.stats.resources.packers.queue_length","value":0} {"stream_type":"telemetry","sim_ts":40.0,"timestamp":"...","path_id":"Shop.stats.resources.packers.utilization","value":33.33333333333333} {"stream_type":"telemetry","sim_ts":40.0,"timestamp":"...","path_id":"Shop.stats.tasks.order.in_progress","value":1} {"stream_type":"telemetry","sim_ts":50.0,"timestamp":"...","path_id":"Shop.stats.resources.packers.capacity","value":3} {"stream_type":"telemetry","sim_ts":50.0,"timestamp":"...","path_id":"Shop.stats.resources.packers.in_use","value":1} {"stream_type":"telemetry","sim_ts":50.0,"timestamp":"...","path_id":"Shop.stats.resources.packers.queue_length","value":0} {"stream_type":"telemetry","sim_ts":50.0,"timestamp":"...","path_id":"Shop.stats.resources.packers.utilization","value":33.33333333333333} {"stream_type":"telemetry","sim_ts":50.0,"timestamp":"...","path_id":"Shop.stats.tasks.order.in_progress","value":1} {"stream_type":"telemetry","sim_ts":60.0,"timestamp":"...","path_id":"Shop.stats.resources.packers.capacity","value":3} {"stream_type":"telemetry","sim_ts":60.0,"timestamp":"...","path_id":"Shop.stats.resources.packers.in_use","value":1} {"stream_type":"telemetry","sim_ts":60.0,"timestamp":"...","path_id":"Shop.stats.resources.packers.queue_length","value":0} {"stream_type":"telemetry","sim_ts":60.0,"timestamp":"...","path_id":"Shop.stats.resources.packers.utilization","value":33.33333333333333} {"stream_type":"telemetry","sim_ts":60.0,"timestamp":"...","path_id":"Shop.stats.tasks.order.in_progress","value":1} {"stream_type":"telemetry","sim_ts":70.0,"timestamp":"...","path_id":"Shop.stats.resources.packers.capacity","value":3} {"stream_type":"telemetry","sim_ts":70.0,"timestamp":"...","path_id":"Shop.stats.resources.packers.in_use","value":1} {"stream_type":"telemetry","sim_ts":70.0,"timestamp":"...","path_id":"Shop.stats.resources.packers.queue_length","value":0} {"stream_type":"telemetry","sim_ts":70.0,"timestamp":"...","path_id":"Shop.stats.resources.packers.utilization","value":33.33333333333333} {"stream_type":"telemetry","sim_ts":70.0,"timestamp":"...","path_id":"Shop.stats.tasks.order.in_progress","value":1} {"stream_type":"telemetry","sim_ts":80.0,"timestamp":"...","path_id":"Shop.stats.resources.packers.capacity","value":3} {"stream_type":"telemetry","sim_ts":80.0,"timestamp":"...","path_id":"Shop.stats.resources.packers.in_use","value":1} {"stream_type":"telemetry","sim_ts":80.0,"timestamp":"...","path_id":"Shop.stats.resources.packers.queue_length","value":0} {"stream_type":"telemetry","sim_ts":80.0,"timestamp":"...","path_id":"Shop.stats.resources.packers.utilization","value":33.33333333333333} {"stream_type":"telemetry","sim_ts":80.0,"timestamp":"...","path_id":"Shop.stats.tasks.order.in_progress","value":1} {"stream_type":"telemetry","sim_ts":90.0,"timestamp":"...","path_id":"Shop.stats.resources.packers.capacity","value":3} {"stream_type":"telemetry","sim_ts":90.0,"timestamp":"...","path_id":"Shop.stats.resources.packers.in_use","value":1} {"stream_type":"telemetry","sim_ts":90.0,"timestamp":"...","path_id":"Shop.stats.resources.packers.queue_length","value":0} {"stream_type":"telemetry","sim_ts":90.0,"timestamp":"...","path_id":"Shop.stats.resources.packers.utilization","value":33.33333333333333} {"stream_type":"telemetry","sim_ts":90.0,"timestamp":"...","path_id":"Shop.stats.tasks.order.in_progress","value":1} {"stream_type":"telemetry","sim_ts":100.0,"timestamp":"...","path_id":"Shop.stats.resources.packers.capacity","value":3} {"stream_type":"telemetry","sim_ts":100.0,"timestamp":"...","path_id":"Shop.stats.resources.packers.in_use","value":1} {"stream_type":"telemetry","sim_ts":100.0,"timestamp":"...","path_id":"Shop.stats.resources.packers.queue_length","value":0} {"stream_type":"telemetry","sim_ts":100.0,"timestamp":"...","path_id":"Shop.stats.resources.packers.utilization","value":33.33333333333333} {"stream_type":"telemetry","sim_ts":100.0,"timestamp":"...","path_id":"Shop.stats.tasks.order.in_progress","value":1} {"stream_type":"telemetry","sim_ts":110.0,"timestamp":"...","path_id":"Shop.stats.resources.packers.capacity","value":3} {"stream_type":"telemetry","sim_ts":110.0,"timestamp":"...","path_id":"Shop.stats.resources.packers.in_use","value":1} {"stream_type":"telemetry","sim_ts":110.0,"timestamp":"...","path_id":"Shop.stats.resources.packers.queue_length","value":0} {"stream_type":"telemetry","sim_ts":110.0,"timestamp":"...","path_id":"Shop.stats.resources.packers.utilization","value":33.33333333333333} {"stream_type":"telemetry","sim_ts":110.0,"timestamp":"...","path_id":"Shop.stats.tasks.order.in_progress","value":1} {"stream_type":"telemetry","sim_ts":120.0,"timestamp":"...","path_id":"Shop.stats.resources.packers.capacity","value":3} {"stream_type":"telemetry","sim_ts":120.0,"timestamp":"...","path_id":"Shop.stats.resources.packers.in_use","value":1} {"stream_type":"telemetry","sim_ts":120.0,"timestamp":"...","path_id":"Shop.stats.resources.packers.queue_length","value":0} {"stream_type":"telemetry","sim_ts":120.0,"timestamp":"...","path_id":"Shop.stats.resources.packers.utilization","value":33.33333333333333} {"stream_type":"telemetry","sim_ts":120.0,"timestamp":"...","path_id":"Shop.stats.tasks.order.in_progress","value":1} {"stream_type":"telemetry","sim_ts":130.0,"timestamp":"...","path_id":"Shop.stats.resources.packers.capacity","value":3} {"stream_type":"telemetry","sim_ts":130.0,"timestamp":"...","path_id":"Shop.stats.resources.packers.in_use","value":1} {"stream_type":"telemetry","sim_ts":130.0,"timestamp":"...","path_id":"Shop.stats.resources.packers.queue_length","value":0} {"stream_type":"telemetry","sim_ts":130.0,"timestamp":"...","path_id":"Shop.stats.resources.packers.utilization","value":33.33333333333333} {"stream_type":"telemetry","sim_ts":130.0,"timestamp":"...","path_id":"Shop.stats.tasks.order.in_progress","value":1} {"stream_type":"telemetry","sim_ts":140.0,"timestamp":"...","path_id":"Shop.stats.resources.packers.capacity","value":3} {"stream_type":"telemetry","sim_ts":140.0,"timestamp":"...","path_id":"Shop.stats.resources.packers.in_use","value":1} {"stream_type":"telemetry","sim_ts":140.0,"timestamp":"...","path_id":"Shop.stats.resources.packers.queue_length","value":0} {"stream_type":"telemetry","sim_ts":140.0,"timestamp":"...","path_id":"Shop.stats.resources.packers.utilization","value":33.33333333333333} {"stream_type":"telemetry","sim_ts":140.0,"timestamp":"...","path_id":"Shop.stats.tasks.order.in_progress","value":1} {"stream_type":"telemetry","sim_ts":150.0,"timestamp":"...","path_id":"Shop.stats.resources.packers.capacity","value":3} {"stream_type":"telemetry","sim_ts":150.0,"timestamp":"...","path_id":"Shop.stats.resources.packers.in_use","value":1} {"stream_type":"telemetry","sim_ts":150.0,"timestamp":"...","path_id":"Shop.stats.resources.packers.queue_length","value":0} {"stream_type":"telemetry","sim_ts":150.0,"timestamp":"...","path_id":"Shop.stats.resources.packers.utilization","value":33.33333333333333} {"stream_type":"telemetry","sim_ts":150.0,"timestamp":"...","path_id":"Shop.stats.tasks.order.in_progress","value":1} {"stream_type":"telemetry","sim_ts":160.0,"timestamp":"...","path_id":"Shop.stats.resources.packers.capacity","value":3} {"stream_type":"telemetry","sim_ts":160.0,"timestamp":"...","path_id":"Shop.stats.resources.packers.in_use","value":1} {"stream_type":"telemetry","sim_ts":160.0,"timestamp":"...","path_id":"Shop.stats.resources.packers.queue_length","value":0} {"stream_type":"telemetry","sim_ts":160.0,"timestamp":"...","path_id":"Shop.stats.resources.packers.utilization","value":33.33333333333333} {"stream_type":"telemetry","sim_ts":160.0,"timestamp":"...","path_id":"Shop.stats.tasks.order.in_progress","value":1} {"stream_type":"event","sim_ts":164.4779633739713,"timestamp":"...","key":"orders-2","task":"order","instance":1,"value":{"path_id":"Shop.service.pack","sim_id":"Shop","service":"pack","status":"queued"}} {"stream_type":"event","sim_ts":164.4779633739713,"timestamp":"...","key":"orders-2","task":"order","instance":1,"value":{"path_id":"Shop.service.pack","sim_id":"Shop","service":"pack","status":"started"}} {"stream_type":"event","sim_ts":167.48162062711958,"timestamp":"...","key":"orders-3","task":"order","instance":2,"value":{"path_id":"Shop.service.pack","sim_id":"Shop","service":"pack","status":"queued"}} ``` The Builder file builds the same model with the builder API and prints every record of its run: ```bash python examples/gallery/orders_wait_for_busy_packers_builder.py ``` ```python """Orders wait in a queue when all packers are busy, builder API. The builder version of `orders_wait_for_busy_packers.yaml`: a shop with 3 packers, orders about once a minute, and a packing time that is normal with a mean of 240 s. Needs: nothing Run it with: python examples/gallery/orders_wait_for_busy_packers_builder.py """ import logging from datetime import datetime, timezone from desflow import ConsoleEgress, SimulationContext UNTIL = 7200 def build() -> SimulationContext: """Builds the shop.""" app = SimulationContext( sim_id="Shop", factor=0, random_seed=42, logical_start_time=datetime(2026, 1, 1, tzinfo=timezone.utc), ) app.add_egress(ConsoleEgress()) app.with_stats(level="minimal") app.add_resource("packers", current_cap=3) app.add_service("pack", dist="normal", mean=240, std=60) app.add_arrival("orders", "exponential", rate=0.015, spawn="order") @app.task(name="order", resource_id="packers", service_id="pack") def order(task_id): """Packs one order.""" return {"event_type": "packed", "order_id": task_id} return app if __name__ == "__main__": logging.basicConfig(level=logging.INFO, format="%(levelname)s %(message)s") build().run(until=UNTIL) ``` The Low-level file builds the model on `DynamicRealtimeEnvironment`, with plain Python processes, and prints every record of its run: ```bash python examples/gallery/orders_wait_for_busy_packers_low_level.py ``` The gaps and the service times come from `Sampler.sample` on a `DistributionConfig` whose `stream` is `arrival.orders` and `service.pack`, the sequences the blueprint uses for its arrivals and services. ```python """Orders wait in a queue when all packers are busy, low-level API. The low-level version of `orders_wait_for_busy_packers.yaml`: plain SimPy on a `DynamicRealtimeEnvironment`, which publishes each record with `publish_event` and each reading with `env.stats`. Each order is one process that queues for a packer, packs and publishes. Needs: nothing Run it with: python examples/gallery/orders_wait_for_busy_packers_low_level.py """ import itertools import logging from datetime import datetime, timezone from desflow import ( CapacityConfig, ConsoleEgress, DistributionConfig, DynamicRealtimeEnvironment, DynamicResource, Sampler, SimParameter, ) UNTIL = 7200 START = datetime(2026, 1, 1, tzinfo=timezone.utc) ENVIRONMENT = {"logical_start_time": START, "timezone": "UTC"} PARAMS = SimParameter( sim_id="Shop", arrival={"orders": DistributionConfig(dist="exponential", rate=0.015)}, service={"pack": DistributionConfig(dist="normal", mean=240, std=60)}, resources={"packers": CapacityConfig(current_cap=3)}, ) STATS = "minimal" def build(env: DynamicRealtimeEnvironment) -> None: """Starts the arrivals and the orders on `env`.""" sampler = Sampler(seed=42) packers = DynamicResource(env, "Shop", "packers") gap = env.registry.get_config("Shop.arrival.orders") gap.stream = "arrival.orders" # the random sequence the blueprint's draw uses service = env.registry.get_config("Shop.service.pack") service.stream = "service.pack" def order(key, task_id): path_id = "Shop.service.pack" env.stats.flow_started("orders") env.publish_event( key, { "path_id": path_id, "sim_id": "Shop", "service": "pack", "status": "queued", }, task="order", instance=task_id, ) env.stats.task_queued("order", task_id) with packers.request() as request: yield request env.publish_event( key, { "path_id": path_id, "sim_id": "Shop", "service": "pack", "status": "started", }, task="order", instance=task_id, ) env.stats.task_started("order", task_id) yield env.timeout(sampler.sample(service)) env.publish_event( key, {"event_type": "packed", "order_id": task_id}, task="order", instance=task_id, ) env.stats.task_finished("order", task_id) env.stats.flow_finished("orders") def source(): for number in itertools.count(1): yield env.timeout(sampler.sample(gap)) env.process(order(f"orders-{number}", number - 1)) env.process(source()) def run() -> None: """Runs the model unpaced into the console.""" env = DynamicRealtimeEnvironment(factor=0, **ENVIRONMENT) env.registry.register_sim_parameter(PARAMS) env.setup_egress([ConsoleEgress()]) env.setup_stats("Shop", "minimal") build(env) try: env.run(until=UNTIL) finally: env.teardown() if __name__ == "__main__": logging.basicConfig(level=logging.INFO, format="%(levelname)s %(message)s") run() ``` ### A machine slows down as it wears, then is repaired A press stamps one blank at a time. Stamping takes a normal time with a mean of 10 s. Wear raises the mean to 12, 14 and 16 s at 1, 2 and 3 hours, and a repair at 4 hours sets it back to 10 s. The wear is written as steps of a scenario. Run it with the sample option, which stops after the first events and prints them: ```bash desflow run examples/gallery/machine_slows_as_it_wears.yaml --sample 5 ``` ```yaml # A machine slows down as it wears, then is repaired. # # A press stamps one blank at a time. Stamping takes a normal time with a mean of 10 s. # Wear raises the mean to 12, 14 and 16 s at 1, 2 and 3 hours, and a repair at 4 hours # sets it back to 10 s. The wear is written as steps of a scenario. # # Needs: nothing # Run it with: desflow run examples/gallery/machine_slows_as_it_wears.yaml simulation: sim_id: Press factor: 0 random_seed: 42 logical_start_time: 2026-01-01T00:00:00 egress: - {type: Console} resources: station: {current_cap: 1} services: stamp: {dist: normal, mean: 10, std: 1} arrivals: blanks: {dist: exponential, rate: 0.05, spawn: blank} tasks: blank: resource: station service: stamp payload: {event_type: stamped} scenario: - {at: 1 hour, path: Press.service.stamp.mean, value: 12} - {at: 2 hours, path: Press.service.stamp.mean, value: 14} - {at: 3 hours, path: Press.service.stamp.mean, value: 16} - {at: 4 hours, path: Press.service.stamp.mean, value: 10} run: {until: 5 hours} ``` ```text {"stream_type":"event","sim_ts":21.79090305473576,"timestamp":"...","key":"blanks-1","task":"blank","instance":0,"value":{"path_id":"Press.service.stamp","sim_id":"Press","service":"stamp","status":"queued"}} {"stream_type":"event","sim_ts":21.79090305473576,"timestamp":"...","key":"blanks-1","task":"blank","instance":0,"value":{"path_id":"Press.service.stamp","sim_id":"Press","service":"stamp","status":"started"}} {"stream_type":"event","sim_ts":31.148971588708257,"timestamp":"...","key":"blanks-1","task":"blank","instance":0,"value":{"event_type":"stamped"}} {"stream_type":"event","sim_ts":41.95644863411036,"timestamp":"...","key":"blanks-2","task":"blank","instance":1,"value":{"path_id":"Press.service.stamp","sim_id":"Press","service":"stamp","status":"queued"}} {"stream_type":"event","sim_ts":41.95644863411036,"timestamp":"...","key":"blanks-2","task":"blank","instance":1,"value":{"path_id":"Press.service.stamp","sim_id":"Press","service":"stamp","status":"started"}} ``` The Builder file builds the same model with the builder API and prints every record of its run: ```bash python examples/gallery/machine_slows_as_it_wears_builder.py ``` ```python """A machine slows down as it wears, then is repaired, builder API. The builder version of `machine_slows_as_it_wears.yaml`: a press with one station, whose mean stamping time rises in steps at 1, 2 and 3 hours and returns to 10 s at 4. Needs: nothing Run it with: python examples/gallery/machine_slows_as_it_wears_builder.py """ import logging from datetime import datetime, timezone from desflow import ConsoleEgress, SimulationContext UNTIL = 18000 def build() -> SimulationContext: """Builds the press, with the wear and the repair as scenario steps.""" app = SimulationContext( sim_id="Press", factor=0, random_seed=42, logical_start_time=datetime(2026, 1, 1, tzinfo=timezone.utc), ) app.add_egress(ConsoleEgress()) app.add_resource("station", current_cap=1) app.add_service("stamp", dist="normal", mean=10, std=1) app.add_arrival("blanks", "exponential", rate=0.05, spawn="blank") app.add_scenario( [ {"at": "1 hour", "path": "Press.service.stamp.mean", "value": 12}, {"at": "2 hours", "path": "Press.service.stamp.mean", "value": 14}, {"at": "3 hours", "path": "Press.service.stamp.mean", "value": 16}, {"at": "4 hours", "path": "Press.service.stamp.mean", "value": 10}, ] ) @app.task(name="blank", resource_id="station", service_id="stamp") def blank(task_id): """Stamps one blank.""" return {"event_type": "stamped"} return app if __name__ == "__main__": logging.basicConfig(level=logging.INFO, format="%(levelname)s %(message)s") build().run(until=UNTIL) ``` The Low-level file builds the model on `DynamicRealtimeEnvironment`, with plain Python processes, and prints every record of its run: ```bash python examples/gallery/machine_slows_as_it_wears_low_level.py ``` The gaps and the service times come from `Sampler.sample` on a `DistributionConfig` whose `stream` is `arrival.blanks` and `service.stamp`, the sequences the blueprint uses for its arrivals and services. ```python """A machine slows down as it wears, then is repaired, low-level API. The low-level version of `machine_slows_as_it_wears.yaml`: plain SimPy on a `DynamicRealtimeEnvironment`, which publishes each record with `publish_event`. The wear is a process that sets the mean at the times of the steps. Needs: nothing Run it with: python examples/gallery/machine_slows_as_it_wears_low_level.py """ import itertools import logging from datetime import datetime, timezone from desflow import ( CapacityConfig, ConsoleEgress, DistributionConfig, DynamicRealtimeEnvironment, DynamicResource, Sampler, SimParameter, run_scenario, ) UNTIL = 18000 START = datetime(2026, 1, 1, tzinfo=timezone.utc) ENVIRONMENT = {"logical_start_time": START, "timezone": "UTC"} PARAMS = SimParameter( sim_id="Press", arrival={"blanks": DistributionConfig(dist="exponential", rate=0.05)}, service={"stamp": DistributionConfig(dist="normal", mean=10, std=1)}, resources={"station": CapacityConfig(current_cap=1)}, ) SCHEDULE = [ {"at": 3600, "path": "Press.service.stamp.mean", "value": 12}, {"at": 7200, "path": "Press.service.stamp.mean", "value": 14}, {"at": 10800, "path": "Press.service.stamp.mean", "value": 16}, {"at": 14400, "path": "Press.service.stamp.mean", "value": 10}, ] def build(env: DynamicRealtimeEnvironment) -> None: """Starts the arrivals and the scenario on `env`.""" sampler = Sampler(seed=42) station = DynamicResource(env, "Press", "station") gap = env.registry.get_config("Press.arrival.blanks") gap.stream = "arrival.blanks" # the random sequence the blueprint's draw uses service = env.registry.get_config("Press.service.stamp") service.stream = "service.stamp" def blank(key, task_id): path_id = "Press.service.stamp" env.publish_event( key, { "path_id": path_id, "sim_id": "Press", "service": "stamp", "status": "queued", }, task="blank", instance=task_id, ) with station.request() as request: yield request env.publish_event( key, { "path_id": path_id, "sim_id": "Press", "service": "stamp", "status": "started", }, task="blank", instance=task_id, ) yield env.timeout(sampler.sample(service)) env.publish_event( key, {"event_type": "stamped"}, task="blank", instance=task_id, ) def source(): for number in itertools.count(1): yield env.timeout(sampler.sample(gap)) env.process(blank(f"blanks-{number}", number - 1)) env.process(source()) env.process(run_scenario(env, SCHEDULE, until=UNTIL)) def run() -> None: """Runs the model unpaced into the console.""" env = DynamicRealtimeEnvironment(factor=0, **ENVIRONMENT) env.registry.register_sim_parameter(PARAMS) env.setup_egress([ConsoleEgress()]) build(env) try: env.run(until=UNTIL) finally: env.teardown() if __name__ == "__main__": logging.basicConfig(level=logging.INFO, format="%(levelname)s %(message)s") run() ``` ### Capacity drops to one at 20 seconds, and the queue grows A shop has 3 packers. An order arrives about every second, and packing takes a normal time with a mean of 2.5 s. A scenario step at 20 s sets the capacity to 1, so the orders queue. The statistics publish the capacity and the queue length every second. Run it with the sample option, which stops after the first events and prints them: ```bash desflow run examples/gallery/capacity_drops_and_queue_grows.yaml --sample 5 ``` ```yaml # Capacity drops to one at 20 seconds, and the queue grows. # # A shop has 3 packers. An order arrives about every second, and packing takes a # normal time with a mean of 2.5 s. A scenario step at 20 s sets the capacity to 1, so # the orders queue. The statistics publish the capacity and the queue length every # second. # # Needs: nothing # Run it with: desflow run examples/gallery/capacity_drops_and_queue_grows.yaml simulation: sim_id: Shop factor: 0 random_seed: 42 logical_start_time: 2026-01-01T00:00:00 egress: - {type: Console} stats: {level: minimal, interval: 1} resources: packers: {current_cap: 3} services: pack: {dist: normal, mean: 2.5, std: 0.3} arrivals: orders: {dist: exponential, rate: 1, spawn: order} tasks: order: resource: packers service: pack payload: {event_type: packed} scenario: - {at: 20, path: Shop.resources.packers.current_cap, value: 1} run: {until: 60} ``` ```text {"stream_type":"event","sim_ts":0.3141556656469718,"timestamp":"...","key":"orders-1","task":"order","instance":0,"value":{"path_id":"Shop.service.pack","sim_id":"Shop","service":"pack","status":"queued"}} {"stream_type":"event","sim_ts":0.3141556656469718,"timestamp":"...","key":"orders-1","task":"order","instance":0,"value":{"path_id":"Shop.service.pack","sim_id":"Shop","service":"pack","status":"started"}} {"stream_type":"telemetry","sim_ts":1.0,"timestamp":"...","path_id":"Shop.stats.resources.packers.capacity","value":3} {"stream_type":"telemetry","sim_ts":1.0,"timestamp":"...","path_id":"Shop.stats.resources.packers.in_use","value":1} {"stream_type":"telemetry","sim_ts":1.0,"timestamp":"...","path_id":"Shop.stats.resources.packers.queue_length","value":0} {"stream_type":"telemetry","sim_ts":1.0,"timestamp":"...","path_id":"Shop.stats.resources.packers.utilization","value":33.33333333333333} {"stream_type":"telemetry","sim_ts":1.0,"timestamp":"...","path_id":"Shop.stats.tasks.order.in_progress","value":1} {"stream_type":"telemetry","sim_ts":2.0,"timestamp":"...","path_id":"Shop.stats.resources.packers.capacity","value":3} {"stream_type":"telemetry","sim_ts":2.0,"timestamp":"...","path_id":"Shop.stats.resources.packers.in_use","value":1} {"stream_type":"telemetry","sim_ts":2.0,"timestamp":"...","path_id":"Shop.stats.resources.packers.queue_length","value":0} {"stream_type":"telemetry","sim_ts":2.0,"timestamp":"...","path_id":"Shop.stats.resources.packers.utilization","value":33.33333333333333} {"stream_type":"telemetry","sim_ts":2.0,"timestamp":"...","path_id":"Shop.stats.tasks.order.in_progress","value":1} {"stream_type":"event","sim_ts":2.4671694506095694,"timestamp":"...","key":"orders-2","task":"order","instance":1,"value":{"path_id":"Shop.service.pack","sim_id":"Shop","service":"pack","status":"queued"}} {"stream_type":"event","sim_ts":2.4671694506095694,"timestamp":"...","key":"orders-2","task":"order","instance":1,"value":{"path_id":"Shop.service.pack","sim_id":"Shop","service":"pack","status":"started"}} {"stream_type":"event","sim_ts":2.5122243094067938,"timestamp":"...","key":"orders-3","task":"order","instance":2,"value":{"path_id":"Shop.service.pack","sim_id":"Shop","service":"pack","status":"queued"}} ``` The Builder file builds the same model with the builder API and prints every record of its run: ```bash python examples/gallery/capacity_drops_and_queue_grows_builder.py ``` ```python """Capacity drops to one at 20 seconds, and the queue grows, builder API. The builder version of `capacity_drops_and_queue_grows.yaml`: 3 packers, an order a second, and a scenario step at 20 s that sets the capacity to 1. Needs: nothing Run it with: python examples/gallery/capacity_drops_and_queue_grows_builder.py """ import logging from datetime import datetime, timezone from desflow import ConsoleEgress, SimulationContext UNTIL = 60 def build() -> SimulationContext: """Builds the shop.""" app = SimulationContext( sim_id="Shop", factor=0, random_seed=42, logical_start_time=datetime(2026, 1, 1, tzinfo=timezone.utc), ) app.add_egress(ConsoleEgress()) app.with_stats(level="minimal", interval=1) app.add_resource("packers", current_cap=3) app.add_service("pack", dist="normal", mean=2.5, std=0.3) app.add_arrival("orders", "exponential", rate=1, spawn="order") app.add_scenario( [{"at": 20, "path": "Shop.resources.packers.current_cap", "value": 1}] ) @app.task(name="order", resource_id="packers", service_id="pack") def order(task_id): """Packs one order.""" return {"event_type": "packed"} return app if __name__ == "__main__": logging.basicConfig(level=logging.INFO, format="%(levelname)s %(message)s") build().run(until=UNTIL) ``` The Low-level file builds the model on `DynamicRealtimeEnvironment`, with plain Python processes, and prints every record of its run: ```bash python examples/gallery/capacity_drops_and_queue_grows_low_level.py ``` The gaps and the service times come from `Sampler.sample` on a `DistributionConfig` whose `stream` is `arrival.orders` and `service.pack`, the sequences the blueprint uses for its arrivals and services. ```python """Capacity drops to one at 20 seconds, and the queue grows, low-level API. The low-level version of `capacity_drops_and_queue_grows.yaml`: plain SimPy on a `DynamicRealtimeEnvironment`, which publishes each record with `publish_event` and each reading with `env.stats`. A process sets the capacity to 1 at 20 s. Needs: nothing Run it with: python examples/gallery/capacity_drops_and_queue_grows_low_level.py """ import itertools import logging from datetime import datetime, timezone from desflow import ( CapacityConfig, ConsoleEgress, DistributionConfig, DynamicRealtimeEnvironment, DynamicResource, Sampler, SimParameter, run_scenario, ) UNTIL = 60 START = datetime(2026, 1, 1, tzinfo=timezone.utc) ENVIRONMENT = {"logical_start_time": START, "timezone": "UTC"} PARAMS = SimParameter( sim_id="Shop", arrival={"orders": DistributionConfig(dist="exponential", rate=1)}, service={"pack": DistributionConfig(dist="normal", mean=2.5, std=0.3)}, resources={"packers": CapacityConfig(current_cap=3)}, ) STATS = ("minimal", 1) # the level and the interval of the readings SCHEDULE = [{"at": 20, "path": "Shop.resources.packers.current_cap", "value": 1}] def build(env: DynamicRealtimeEnvironment) -> None: """Starts the arrivals and the scenario on `env`.""" sampler = Sampler(seed=42) packers = DynamicResource(env, "Shop", "packers") gap = env.registry.get_config("Shop.arrival.orders") gap.stream = "arrival.orders" # the random sequence the blueprint's draw uses service = env.registry.get_config("Shop.service.pack") service.stream = "service.pack" def order(key, task_id): path_id = "Shop.service.pack" env.stats.flow_started("orders") env.publish_event( key, { "path_id": path_id, "sim_id": "Shop", "service": "pack", "status": "queued", }, task="order", instance=task_id, ) env.stats.task_queued("order", task_id) with packers.request() as request: yield request env.publish_event( key, { "path_id": path_id, "sim_id": "Shop", "service": "pack", "status": "started", }, task="order", instance=task_id, ) env.stats.task_started("order", task_id) yield env.timeout(sampler.sample(service)) env.publish_event( key, {"event_type": "packed"}, task="order", instance=task_id, ) env.stats.task_finished("order", task_id) env.stats.flow_finished("orders") def source(): for number in itertools.count(1): yield env.timeout(sampler.sample(gap)) env.process(order(f"orders-{number}", number - 1)) env.process(source()) env.process(run_scenario(env, SCHEDULE, until=UNTIL)) def run() -> None: """Runs the model unpaced into the console.""" env = DynamicRealtimeEnvironment(factor=0, **ENVIRONMENT) env.registry.register_sim_parameter(PARAMS) env.setup_egress([ConsoleEgress()]) env.setup_stats("Shop", "minimal", 1) build(env) try: env.run(until=UNTIL) finally: env.teardown() if __name__ == "__main__": logging.basicConfig(level=logging.INFO, format="%(levelname)s %(message)s") run() ``` ### Callers hang up when they wait for an agent for longer than they will tolerate Calls arrive at 54 an hour and two agents answer about 30 an hour, so a queue builds. A caller who waits longer than their patience, 1 to 5 minutes, hangs up. A scenario step adds two agents after half an hour, so calls wait less and fewer callers hang up. Run it with the sample option, which stops after the first events and prints them: ```bash desflow run examples/gallery/callers_hang_up_after_waiting_too_long.yaml --sample 5 ``` ```yaml # Callers hang up when they wait for an agent for longer than they will tolerate. # # Calls arrive at 54 an hour and two agents answer about 30 an hour, so a queue # builds. A caller who waits longer than their patience, 1 to 5 minutes, hangs up. A # scenario step adds two agents after half an hour, so calls wait less and fewer # callers hang up. # # Needs: nothing # Run it with: desflow run examples/gallery/callers_hang_up_after_waiting_too_long.yaml simulation: sim_id: Centre factor: 0 random_seed: 42 logical_start_time: 2026-01-01T00:00:00 egress: - {type: Console} resources: agents: {current_cap: 2, max_cap: 4} services: talk: {dist: normal, mean: 4 min, std: 1 min} arrivals: calls: {dist: exponential, rate: 0.015, spawn: answer_call} tasks: answer_call: service: talk resource: agents patience: {gen: uniform, low: 60, high: 300} on_renege: hang_up id_field: call_id payload: {event_type: answered} hang_up: payload: {event_type: hung_up} scenario: - {at: 30 min, path: Centre.resources.agents.current_cap, value: 4} run: {until: 1 hour} ``` ```text {"stream_type":"event","sim_ts":15.924314308737758,"timestamp":"...","key":"calls-1","task":"answer_call","instance":0,"value":{"path_id":"Centre.service.talk","sim_id":"Centre","service":"talk","status":"queued"}} {"stream_type":"event","sim_ts":15.924314308737758,"timestamp":"...","key":"calls-1","task":"answer_call","instance":0,"value":{"path_id":"Centre.service.talk","sim_id":"Centre","service":"talk","status":"started"}} {"stream_type":"event","sim_ts":250.72846807640823,"timestamp":"...","key":"calls-2","task":"answer_call","instance":1,"value":{"path_id":"Centre.service.talk","sim_id":"Centre","service":"talk","status":"queued"}} {"stream_type":"event","sim_ts":250.72846807640823,"timestamp":"...","key":"calls-2","task":"answer_call","instance":1,"value":{"path_id":"Centre.service.talk","sim_id":"Centre","service":"talk","status":"started"}} {"stream_type":"event","sim_ts":312.58292688735503,"timestamp":"...","key":"calls-3","task":"answer_call","instance":2,"value":{"path_id":"Centre.service.talk","sim_id":"Centre","service":"talk","status":"queued"}} ``` The Builder file builds the same model with the builder API and prints every record of its run: ```bash python examples/gallery/callers_hang_up_after_waiting_too_long_builder.py ``` ```python """Callers hang up when they wait for an agent for longer than they will tolerate. The Builder form of callers_hang_up_after_waiting_too_long.yaml, with the same records. Calls arrive at 54 an hour and two agents answer about 30 an hour, so a queue builds. A caller who waits longer than their patience, 1 to 5 minutes, hangs up. A scenario step adds two agents after half an hour, so calls wait less and fewer callers hang up. Needs: nothing Run it with: python examples/gallery/callers_hang_up_after_waiting_too_long_builder.py """ import logging from datetime import datetime from desflow import ConsoleEgress, SimulationContext from desflow.values import generator UNTIL = 3600 def build() -> SimulationContext: """Builds the model.""" app = ( SimulationContext( sim_id="Centre", factor=0, random_seed=42, logical_start_time=datetime(2026, 1, 1), ) .add_egress(ConsoleEgress()) .add_resource("agents", current_cap=2, max_cap=4) .add_service("talk", dist="normal", mean="4 min", std="1 min") .add_arrival("calls", "exponential", rate=0.015, spawn="answer_call") .add_scenario( [ { "at": "30 min", "path": "Centre.resources.agents.current_cap", "value": 4, } ] ) ) @app.task( name="answer_call", service_id="talk", resource_id="agents", patience=generator({"gen": "uniform", "low": 60, "high": 300}), on_renege="hang_up", ) def answer_call(task_id): return {"event_type": "answered", "call_id": task_id} @app.task(name="hang_up") def hang_up(task_id): return {"event_type": "hung_up"} return app if __name__ == "__main__": logging.basicConfig(level=logging.INFO, format="%(levelname)s %(message)s") build().run(until=UNTIL) ``` The Low-level file builds the model on `DynamicRealtimeEnvironment`, with plain Python processes, and prints every record of its run: ```bash python examples/gallery/callers_hang_up_after_waiting_too_long_low_level.py ``` The Low-level file draws each value with `Sampler.generator()`, where the place is the key path of the blueprint's generator that makes the same value, such as `tasks.answer_call.patience`. Each draw therefore comes from the random sequence the blueprint uses at the same place, so the draws are the blueprint's. ```python """Callers hang up when they wait for an agent for longer than they will tolerate. The Low-level form of callers_hang_up_after_waiting_too_long.yaml, with the same records, built on `DynamicRealtimeEnvironment`. Calls arrive at 54 an hour and two agents answer about 30 an hour, so a queue builds. A caller who waits longer than their patience, 1 to 5 minutes, hangs up. A scenario step adds two agents after half an hour, so calls wait less and fewer callers hang up. A process adds them at 30 minutes, through the registry. Needs: nothing Run it with: python examples/gallery/callers_hang_up_after_waiting_too_long_low_level.py """ import itertools import logging from datetime import datetime from desflow import ( CapacityConfig, ConsoleEgress, DistributionConfig, DynamicRealtimeEnvironment, DynamicResource, Sampler, SimParameter, ) SEED = 42 UNTIL = 3600 PARAMS = SimParameter( sim_id="Centre", arrival={"calls": DistributionConfig(dist="exponential", rate=0.015)}, # DistributionConfig takes seconds: 4 min (std 1 min) for a call service={"talk": DistributionConfig(dist="normal", mean=240, std=60)}, resources={"agents": CapacityConfig(current_cap=2, max_cap=4)}, ) def build(env): """Starts the call source and the shift change on `env`.""" env.registry.register_sim_parameter(PARAMS) sampler = Sampler(seed=SEED) patience = sampler.generator("tasks.answer_call.patience") agents = DynamicResource(env, "Centre", "agents") path_id = "Centre.service.talk" instances = {"answer_call": itertools.count(), "hang_up": itertools.count()} def call(key): instance = next(instances["answer_call"]) def publish(value): env.publish_event(key, value, task="answer_call", instance=instance) waits = 60 + (300 - 60) * patience.random() publish( { "path_id": path_id, "sim_id": "Centre", "service": "talk", "status": "queued", } ) with agents.request() as request: got = yield request | env.timeout(waits) if request not in got: publish( { "path_id": path_id, "sim_id": "Centre", "service": "talk", "status": "reneged", } ) env.publish_event( key, {"event_type": "hung_up"}, task="hang_up", instance=next(instances["hang_up"]), ) return publish( { "path_id": path_id, "sim_id": "Centre", "service": "talk", "status": "started", } ) yield env.timeout(sampler.sample(env.registry.get_config(path_id))) publish({"event_type": "answered", "call_id": instance}) def calls(): gap = env.registry.get_config("Centre.arrival.calls") for number in itertools.count(1): yield env.timeout(sampler.sample(gap)) env.process(call(f"calls-{number}")) def shift_change(): yield env.timeout(1800) env.registry.update("Centre.resources.agents.current_cap", 4) env.process(calls()) env.process(shift_change()) def run(): """Runs the model for one simulation hour.""" env = DynamicRealtimeEnvironment(factor=0, logical_start_time=datetime(2026, 1, 1)) env.setup_egress([ConsoleEgress()]) build(env) try: env.run(until=UNTIL) finally: env.teardown() if __name__ == "__main__": logging.basicConfig(level=logging.INFO, format="%(levelname)s %(message)s") run() ``` ### Urgent support tickets are served before older tickets of lower priority One agent solves a ticket in about 50 seconds, and a ticket arrives about every 55 seconds, so tickets wait. The agent's queue is ordered by priority, so a ticket of priority 1 (10 percent of them) waits less than one of priority 3 (60 percent). Run it with the sample option, which stops after the first events and prints them: ```bash desflow run examples/gallery/urgent_tickets_are_served_first.yaml --sample 5 ``` ```yaml # Urgent support tickets are served before older tickets of lower priority. # # One agent solves a ticket in about 50 seconds, and a ticket arrives about every 55 # seconds, so tickets wait. The agent's queue is ordered by priority, so a ticket of # priority 1 (10 percent of them) waits less than one of priority 3 (60 percent). # # Needs: nothing # Run it with: desflow run examples/gallery/urgent_tickets_are_served_first.yaml simulation: sim_id: Support factor: 0 random_seed: 42 logical_start_time: 2026-01-01T00:00:00 egress: - {type: Console} resources: agents: {current_cap: 1, max_cap: 1, queue: priority} services: solve: {dist: normal, mean: 50, std: 10} arrivals: tickets: dist: exponential rate: 0.018 attributes: priority: gen: weighted options: {1: 10, 2: 30, 3: 60} spawn: solve_ticket tasks: solve_ticket: service: solve resource: agents priority: attr.priority payload: event_type: solved priority: {gen: attr, name: priority} run: {until: 4 hours} ``` ```text {"stream_type":"event","sim_ts":15.04613672339676,"timestamp":"...","key":"tickets-1","task":"solve_ticket","instance":0,"value":{"path_id":"Support.service.solve","sim_id":"Support","service":"solve","status":"queued"}} {"stream_type":"event","sim_ts":15.04613672339676,"timestamp":"...","key":"tickets-1","task":"solve_ticket","instance":0,"value":{"path_id":"Support.service.solve","sim_id":"Support","service":"solve","status":"started"}} {"stream_type":"event","sim_ts":78.19013668146923,"timestamp":"...","key":"tickets-1","task":"solve_ticket","instance":0,"value":{"event_type":"solved","priority":3}} {"stream_type":"event","sim_ts":87.67926599645057,"timestamp":"...","key":"tickets-2","task":"solve_ticket","instance":1,"value":{"path_id":"Support.service.solve","sim_id":"Support","service":"solve","status":"queued"}} {"stream_type":"event","sim_ts":87.67926599645057,"timestamp":"...","key":"tickets-2","task":"solve_ticket","instance":1,"value":{"path_id":"Support.service.solve","sim_id":"Support","service":"solve","status":"started"}} ``` The Builder file builds the same model with the builder API and prints every record of its run: ```bash python examples/gallery/urgent_tickets_are_served_first_builder.py ``` ```python """Urgent support tickets are served before older tickets of lower priority. The Builder form of urgent_tickets_are_served_first.yaml, with the same records. One agent solves a ticket in about 50 seconds, and the agent's queue is ordered by the priority each ticket arrives with, so a ticket of priority 1 waits less than one of priority 3. Needs: nothing Run it with: python examples/gallery/urgent_tickets_are_served_first_builder.py """ import logging from datetime import datetime from desflow import ConsoleEgress, SimulationContext from desflow.values import Template, generator UNTIL = 14400 def build() -> SimulationContext: """Builds the model.""" app = ( SimulationContext( sim_id="Support", factor=0, random_seed=42, logical_start_time=datetime(2026, 1, 1), ) .add_egress(ConsoleEgress()) .add_resource("agents", current_cap=1, max_cap=1, queue="priority") .add_service("solve", dist="normal", mean=50, std=10) .add_arrival( "tickets", "exponential", rate=0.018, attributes={ "priority": generator( {"gen": "weighted", "options": {1: 10, 2: 30, 3: 60}} ) }, spawn="solve_ticket", ) ) solved_payload = Template( {"event_type": "solved", "priority": {"gen": "attr", "name": "priority"}}, name="tasks.solve_ticket", ) @app.task( name="solve_ticket", service_id="solve", resource_id="agents", priority="attr.priority", ) def solve_ticket(task_id): return solved_payload return app if __name__ == "__main__": logging.basicConfig(level=logging.INFO, format="%(levelname)s %(message)s") build().run(until=UNTIL) ``` The Low-level file builds the model on `DynamicRealtimeEnvironment`, with plain Python processes, and prints every record of its run: ```bash python examples/gallery/urgent_tickets_are_served_first_low_level.py ``` The Low-level file draws each value with `Sampler.generator()`, where the place is the key path of the blueprint's generator that makes the same value, such as `arrivals.tickets.attributes.priority`. Each draw therefore comes from the random sequence the blueprint uses at the same place, so the draws are the blueprint's. ```python """Urgent support tickets are served before older tickets of lower priority. The Low-level form of urgent_tickets_are_served_first.yaml, with the same records, built on `DynamicRealtimeEnvironment`. The agent is a `DynamicResource` whose queue order is `priority`, and each ticket asks for it with its own priority. The priority is drawn with `Sampler`, from the random sequence the blueprint's generator uses. Needs: nothing Run it with: python examples/gallery/urgent_tickets_are_served_first_low_level.py """ import itertools import logging from datetime import datetime from desflow import ( CapacityConfig, ConsoleEgress, DistributionConfig, DynamicRealtimeEnvironment, DynamicResource, Sampler, SimParameter, ) SEED = 42 UNTIL = 14400 PARAMS = SimParameter( sim_id="Support", arrival={"tickets": DistributionConfig(dist="exponential", rate=0.018)}, service={"solve": DistributionConfig(dist="normal", mean=50, std=10)}, resources={"agents": CapacityConfig(current_cap=1, max_cap=1)}, ) def weighted(rng, options): """One key of `options`, chosen by its weight, as the `weighted` generator does.""" point = rng.random() * sum(options.values()) running = 0.0 for value, weight in options.items(): running += weight if point < running: return value return value def build(env): """Starts the ticket source on `env`.""" env.registry.register_sim_parameter(PARAMS) sampler = Sampler(seed=SEED) pick = sampler.generator("arrivals.tickets.attributes.priority") agents = DynamicResource(env, "Support", "agents", queue="priority") path_id = "Support.service.solve" def ticket(key, priority, instance): def publish(value): env.publish_event(key, value, task="solve_ticket", instance=instance) publish( { "path_id": path_id, "sim_id": "Support", "service": "solve", "status": "queued", } ) # The lowest priority number is served first with agents.request(priority=priority) as request: yield request publish( { "path_id": path_id, "sim_id": "Support", "service": "solve", "status": "started", } ) yield env.timeout(sampler.sample(env.registry.get_config(path_id))) publish({"event_type": "solved", "priority": priority}) def tickets(): gap = env.registry.get_config("Support.arrival.tickets") for number in itertools.count(1): yield env.timeout(sampler.sample(gap)) priority = weighted(pick, {1: 10, 2: 30, 3: 60}) env.process(ticket(f"tickets-{number}", priority, number - 1)) env.process(tickets()) def run(): """Runs the model for four simulation hours.""" env = DynamicRealtimeEnvironment(factor=0, logical_start_time=datetime(2026, 1, 1)) env.setup_egress([ConsoleEgress()]) build(env) try: env.run(until=UNTIL) finally: env.teardown() if __name__ == "__main__": logging.basicConfig(level=logging.INFO, format="%(levelname)s %(message)s") run() ``` ### A shopper keeps adding items to a cart, then pays or abandons it A shopper adds an item every 5 to 30 seconds, and after each item 60 percent add another, 25 percent pay and 15 percent leave. Two tills serve the payments, each for about 25 seconds, so shoppers queue to pay when both are busy. Run it with the sample option, which stops after the first events and prints them: ```bash desflow run examples/gallery/shoppers_add_items_then_pay_or_abandon.yaml --sample 5 ``` ```yaml # A shopper keeps adding items to a cart, then pays or abandons it. # # A shopper adds an item every 5 to 30 seconds, and after each item 60 percent add # another, 25 percent pay and 15 percent leave. Two tills serve the payments, each for # about 25 seconds, so shoppers queue to pay when both are busy. # # Needs: nothing # Run it with: desflow run examples/gallery/shoppers_add_items_then_pay_or_abandon.yaml simulation: sim_id: Shop factor: 0 random_seed: 42 logical_start_time: 2026-01-01T00:00:00 egress: - {type: Console} resources: tills: {current_cap: 2, max_cap: 2} services: checkout: {dist: normal, mean: 25, std: 5} arrivals: shoppers: dist: exponential rate: 0.1 attributes: {items: 0} spawn: add_item tasks: add_item: service_time: {gen: uniform, low: 5, high: 30} set: items: {gen: expr, expr: attr.items + 1} payload: event_type: item_added items: {gen: expr, expr: attr.items + 1} next: weights: {add_item: 60, pay: 25, abandon: 15} pay: service: checkout resource: tills payload: event_type: paid items: {gen: attr, name: items} abandon: payload: event_type: abandoned items: {gen: attr, name: items} run: {until: 1 hour} ``` ```text {"stream_type":"event","sim_ts":10.467584677592853,"timestamp":"...","key":"shoppers-1","task":"add_item","instance":0,"value":{"status":"started"}} {"stream_type":"event","sim_ts":11.299271630799119,"timestamp":"...","key":"shoppers-2","task":"add_item","instance":1,"value":{"status":"started"}} {"stream_type":"event","sim_ts":11.629322773869537,"timestamp":"...","key":"shoppers-3","task":"add_item","instance":2,"value":{"status":"started"}} {"stream_type":"event","sim_ts":20.121210214963746,"timestamp":"...","key":"shoppers-4","task":"add_item","instance":3,"value":{"status":"started"}} {"stream_type":"event","sim_ts":22.33567323143638,"timestamp":"...","key":"shoppers-5","task":"add_item","instance":4,"value":{"status":"started"}} ``` The Builder file builds the same model with the builder API and prints every record of its run: ```bash python examples/gallery/shoppers_add_items_then_pay_or_abandon_builder.py ``` ```python """A shopper keeps adding items to a cart, then pays or abandons it. The Builder form of shoppers_add_items_then_pay_or_abandon.yaml, with the same records. A shopper adds an item every 5 to 30 seconds, and after each item 60 percent add another, 25 percent pay and 15 percent leave. Two tills serve the payments, each for about 25 seconds. Needs: nothing Run it with: python examples/gallery/shoppers_add_items_then_pay_or_abandon_builder.py """ import logging from datetime import datetime from desflow import ConsoleEgress, SimulationContext from desflow.values import Template, generator UNTIL = 3600 def build() -> SimulationContext: """Builds the model.""" app = ( SimulationContext( sim_id="Shop", factor=0, random_seed=42, logical_start_time=datetime(2026, 1, 1), ) .add_egress(ConsoleEgress()) .add_resource("tills", current_cap=2, max_cap=2) .add_service("checkout", dist="normal", mean=25, std=5) .add_arrival( "shoppers", "exponential", rate=0.1, attributes={"items": 0}, spawn="add_item", ) ) item_added_payload = Template( { "event_type": "item_added", "items": {"gen": "expr", "expr": "attr.items + 1"}, }, name="tasks.add_item", ) paid_payload = Template( {"event_type": "paid", "items": {"gen": "attr", "name": "items"}}, name="tasks.pay", ) abandoned_payload = Template( {"event_type": "abandoned", "items": {"gen": "attr", "name": "items"}}, name="tasks.abandon", ) @app.task( name="add_item", service_time=generator({"gen": "uniform", "low": 5, "high": 30}), set={"items": generator({"gen": "expr", "expr": "attr.items + 1"})}, next={"weights": {"add_item": 60, "pay": 25, "abandon": 15}}, ) def add_item(task_id): return item_added_payload @app.task(name="pay", resource_id="tills", service_id="checkout") def pay(task_id): return paid_payload @app.task(name="abandon") def abandon(task_id): return abandoned_payload return app if __name__ == "__main__": logging.basicConfig(level=logging.INFO, format="%(levelname)s %(message)s") build().run(until=UNTIL) ``` The Low-level file builds the model on `DynamicRealtimeEnvironment`, with plain Python processes, and prints every record of its run: ```bash python examples/gallery/shoppers_add_items_then_pay_or_abandon_low_level.py ``` The Low-level file draws each value with `Sampler.generator()`, where the place is the key path of the blueprint's generator that makes the same value, such as `tasks.add_item.service_time`. Each draw therefore comes from the random sequence the blueprint uses at the same place, so the draws are the blueprint's. The branch of each step is chosen by a `Router` whose random sequence is `Sampler.generator("route.add_item")`, the sequence of the blueprint's `next`. ```python """A shopper keeps adding items to a cart, then pays or abandons it. The Low-level form of shoppers_add_items_then_pay_or_abandon.yaml, with the same records, built on `DynamicRealtimeEnvironment`. A shopper adds an item every 5 to 30 seconds, and after each item 60 percent add another, 25 percent pay and 15 percent leave. Two tills serve the payments, each for about 25 seconds. Needs: nothing Run it with: python examples/gallery/shoppers_add_items_then_pay_or_abandon_low_level.py """ import itertools import logging from datetime import datetime from desflow import ( CapacityConfig, ConsoleEgress, DistributionConfig, DynamicRealtimeEnvironment, DynamicResource, Router, Sampler, SimParameter, ) SEED = 42 UNTIL = 3600 PARAMS = SimParameter( sim_id="Shop", arrival={"shoppers": DistributionConfig(dist="exponential", rate=0.1)}, service={"checkout": DistributionConfig(dist="normal", mean=25, std=5)}, resources={"tills": CapacityConfig(current_cap=2, max_cap=2)}, ) def build(env): """Starts the shopper source on `env`.""" env.registry.register_sim_parameter(PARAMS) sampler = Sampler(seed=SEED) browse = sampler.generator("tasks.add_item.service_time") router = Router( {"weights": {"add_item": 60, "pay": 25, "abandon": 15}}, rng=sampler.generator("route.add_item"), ) tills = DynamicResource(env, "Shop", "tills") path_id = "Shop.service.checkout" instances = {task: itertools.count() for task in ("add_item", "pay", "abandon")} def shopper(key): cart = {"items": 0} while True: instance = next(instances["add_item"]) env.publish_event( key, {"status": "started"}, task="add_item", instance=instance ) yield env.timeout(5 + (30 - 5) * browse.random()) env.publish_event( key, {"event_type": "item_added", "items": cart["items"] + 1}, task="add_item", instance=instance, ) cart["items"] += 1 # the blueprint's `set`, applied after the record task = router.choose(None, env=env) if task != "add_item": break instance = next(instances[task]) if task == "pay": env.publish_event( key, { "path_id": path_id, "sim_id": "Shop", "service": "checkout", "status": "queued", }, task="pay", instance=instance, ) with tills.request() as request: yield request env.publish_event( key, { "path_id": path_id, "sim_id": "Shop", "service": "checkout", "status": "started", }, task="pay", instance=instance, ) yield env.timeout(sampler.sample(env.registry.get_config(path_id))) env.publish_event( key, {"event_type": "paid", "items": cart["items"]}, task="pay", instance=instance, ) else: env.publish_event( key, {"event_type": "abandoned", "items": cart["items"]}, task="abandon", instance=instance, ) def shoppers(): gap = env.registry.get_config("Shop.arrival.shoppers") for number in itertools.count(1): yield env.timeout(sampler.sample(gap)) env.process(shopper(f"shoppers-{number}")) env.process(shoppers()) def run(): """Runs the model for one simulation hour.""" env = DynamicRealtimeEnvironment(factor=0, logical_start_time=datetime(2026, 1, 1)) env.setup_egress([ConsoleEgress()]) build(env) try: env.run(until=UNTIL) finally: env.teardown() if __name__ == "__main__": logging.basicConfig(level=logging.INFO, format="%(levelname)s %(message)s") run() ``` ### Visitors drop out at each step of a signup funnel Of every 100 visitors, 40 sign up, 20 of those start a trial, and 5 of those pay. A visitor who drops out ends in one `left` task, whose record names the step the visitor left after. Run it with the sample option, which stops after the first events and prints them: ```bash desflow run examples/gallery/visitors_drop_out_at_each_signup_step.yaml --sample 5 ``` ```yaml # Visitors drop out at each step of a signup funnel. # # Of every 100 visitors, 40 sign up, 20 of those start a trial, and 5 of those pay. A # visitor who drops out ends in one `left` task, whose record names the step the # visitor left after. # # Needs: nothing # Run it with: desflow run examples/gallery/visitors_drop_out_at_each_signup_step.yaml simulation: sim_id: Funnel factor: 0 random_seed: 42 logical_start_time: 2026-01-01T00:00:00 egress: - {type: Console} arrivals: visitors: {dist: exponential, rate: 0.5, spawn: visited} tasks: visited: payload: {stage: visited} next: weights: {signed_up: 40, left: 60} signed_up: service_time: {gen: uniform, low: 5, high: 30} payload: {stage: signed_up} next: weights: {trial_started: 50, left: 50} trial_started: service_time: {gen: uniform, low: 10, high: 60} payload: {stage: trial_started} next: weights: {paid: 25, left: 75} paid: payload: {stage: paid} left: payload: stage: left after: {gen: upstream, path: stage} run: {until: 20 min} ``` ```text {"stream_type":"event","sim_ts":5.685646145804752,"timestamp":"...","key":"visitors-1","task":"visited","instance":0,"value":{"stage":"visited"}} {"stream_type":"event","sim_ts":5.685646145804752,"timestamp":"...","key":"visitors-1","task":"left","instance":0,"value":{"stage":"left","after":"visited"}} {"stream_type":"event","sim_ts":6.716550977533494,"timestamp":"...","key":"visitors-2","task":"visited","instance":1,"value":{"stage":"visited"}} {"stream_type":"event","sim_ts":6.716550977533494,"timestamp":"...","key":"visitors-2","task":"left","instance":1,"value":{"stage":"left","after":"visited"}} {"stream_type":"event","sim_ts":8.101630035966295,"timestamp":"...","key":"visitors-3","task":"visited","instance":2,"value":{"stage":"visited"}} ``` The Builder file builds the same model with the builder API and prints every record of its run: ```bash python examples/gallery/visitors_drop_out_at_each_signup_step_builder.py ``` ```python """Visitors drop out at each step of a signup funnel. The Builder form of visitors_drop_out_at_each_signup_step.yaml, with the same records. Of every 100 visitors, 40 sign up, 20 of those start a trial, and 5 of those pay. A visitor who drops out ends in one `left` task, whose record names the step the visitor left after. Needs: nothing Run it with: python examples/gallery/visitors_drop_out_at_each_signup_step_builder.py """ import logging from datetime import datetime from desflow import ConsoleEgress, SimulationContext from desflow.values import Template, generator UNTIL = 1200 def build() -> SimulationContext: """Builds the model.""" app = ( SimulationContext( sim_id="Funnel", factor=0, random_seed=42, logical_start_time=datetime(2026, 1, 1), ) .add_egress(ConsoleEgress()) .add_arrival("visitors", "exponential", rate=0.5, spawn="visited") ) left_payload = Template( {"stage": "left", "after": {"gen": "upstream", "path": "stage"}}, name="tasks.left", ) @app.task(name="visited", next={"weights": {"signed_up": 40, "left": 60}}) def visited(task_id): return {"stage": "visited"} @app.task( name="signed_up", service_time=generator({"gen": "uniform", "low": 5, "high": 30}), next={"weights": {"trial_started": 50, "left": 50}}, ) def signed_up(task_id): return {"stage": "signed_up"} @app.task( name="trial_started", service_time=generator({"gen": "uniform", "low": 10, "high": 60}), next={"weights": {"paid": 25, "left": 75}}, ) def trial_started(task_id): return {"stage": "trial_started"} @app.task(name="paid") def paid(task_id): return {"stage": "paid"} @app.task(name="left") def left(task_id): return left_payload return app if __name__ == "__main__": logging.basicConfig(level=logging.INFO, format="%(levelname)s %(message)s") build().run(until=UNTIL) ``` The Low-level file builds the model on `DynamicRealtimeEnvironment`, with plain Python processes, and prints every record of its run: ```bash python examples/gallery/visitors_drop_out_at_each_signup_step_low_level.py ``` The Low-level file draws each value with `Sampler.generator()`, where the place is the key path of the blueprint's generator that makes the same value, such as `tasks..service_time` with the name of the step filled in. Each draw therefore comes from the random sequence the blueprint uses at the same place, so the draws are the blueprint's. The branch of each step is chosen by a `Router` whose random sequence is `Sampler.generator("route.")`, and one more for each step, the sequence of the blueprint's `next`. The gaps between arrivals come from `Sampler.sample` on a `DistributionConfig` whose `stream` is `arrival.visitors`, the sequence the blueprint uses for its arrivals. ```python """Visitors drop out at each step of a signup funnel. The Low-level form of visitors_drop_out_at_each_signup_step.yaml, with the same records, built on `DynamicRealtimeEnvironment`. Each visitor is one process that goes through the steps. A `Router` for each step makes the choice as the blueprint's `next` does, and the time a step takes is drawn with `Sampler`, from the random sequence the blueprint's generator uses. Needs: nothing Run it with: python examples/gallery/visitors_drop_out_at_each_signup_step_low_level.py """ import itertools import logging from datetime import datetime from desflow import ( ConsoleEgress, DistributionConfig, DynamicRealtimeEnvironment, Router, Sampler, ) SEED = 42 UNTIL = 1200 # Each step: its name, the least and the most seconds it takes (none for the first), # and the weights of the choice that follows it STEPS = [ ("visited", None, {"signed_up": 40, "left": 60}), ("signed_up", (5, 30), {"trial_started": 50, "left": 50}), ("trial_started", (10, 60), {"paid": 25, "left": 75}), ] def build(env): """Starts the visitor source on `env`.""" sampler = Sampler(seed=SEED) times, routers = {}, {} bounds_of = {step: bounds for step, bounds, _ in STEPS} for step, bounds, weights in STEPS: routers[step] = Router( {"weights": weights}, rng=sampler.generator(f"route.{step}") ) if bounds is not None: times[step] = sampler.generator(f"tasks.{step}.service_time") gap = DistributionConfig(dist="exponential", rate=0.5) gap.stream = "arrival.visitors" instances = { task: itertools.count() for task in ("visited", "signed_up", "trial_started", "paid", "left") } def visitor(key): step = "visited" while step in routers: instance = next(instances[step]) if step in times: env.publish_event( key, {"status": "started"}, task=step, instance=instance ) low, high = bounds_of[step] yield env.timeout(low + (high - low) * times[step].random()) env.publish_event(key, {"stage": step}, task=step, instance=instance) came_from, step = step, routers[step].choose(None, env=env) # `paid` and `left` end the visit. `left` names the step the visitor left after. payload = {"stage": step} if step == "left": payload["after"] = came_from env.publish_event(key, payload, task=step, instance=next(instances[step])) def visitors(): for number in itertools.count(1): yield env.timeout(sampler.sample(gap)) env.process(visitor(f"visitors-{number}")) env.process(visitors()) def run(): """Runs the model for 20 simulation minutes.""" env = DynamicRealtimeEnvironment(factor=0, logical_start_time=datetime(2026, 1, 1)) env.setup_egress([ConsoleEgress()]) build(env) try: env.run(until=UNTIL) finally: env.teardown() if __name__ == "__main__": logging.basicConfig(level=logging.INFO, format="%(levelname)s %(message)s") run() ``` ### Each bet is settled after the match, and a winner is paid the stake times the odds A bet is placed with a stake and odds. One to two minutes later it is settled: 45 percent win and are paid the stake times the odds, the rest lose and are paid nothing, and the settled record repeats the bet id. Run it with the sample option, which stops after the first events and prints them: ```bash desflow run examples/gallery/bets_are_settled_and_winners_paid.yaml --sample 5 ``` ```yaml # Each bet is settled after the match, and a winner is paid the stake times the odds. # # A bet is placed with a stake and odds. One to two minutes later it is settled: 45 # percent win and are paid the stake times the odds, the rest lose and are paid # nothing, and the settled record repeats the bet id. # # Needs: nothing # Run it with: desflow run examples/gallery/bets_are_settled_and_winners_paid.yaml simulation: sim_id: Book factor: 0 random_seed: 42 logical_start_time: 2026-01-01T00:00:00 egress: - {type: Console} arrivals: bets: {dist: exponential, rate: 0.2, spawn: place_bet} tasks: place_bet: payload: bet_id: {gen: sequence, start: 1} stake: gen: weighted options: {5: 50, 10: 30, 50: 15, 100: 5} odds: {gen: uniform, low: 1.5, high: 4, decimals: 2} next: settle_bet settle_bet: vars: won: {gen: boolean, p: 0.45} service_time: {gen: uniform, low: 60, high: 120} payload: bet_id: {gen: upstream, path: bet_id} result: {gen: when, condition: won, then: won, else: lost} payout: gen: when condition: won then: gen: multiply args: - {gen: upstream, path: stake} - {gen: upstream, path: odds} decimals: 2 else: 0 run: {until: 20 min} ``` ```text {"stream_type":"event","sim_ts":5.905507390799418,"timestamp":"...","key":"bets-1","task":"place_bet","instance":0,"value":{"bet_id":1,"stake":10,"odds":3.83}} {"stream_type":"event","sim_ts":5.905507390799418,"timestamp":"...","key":"bets-1","task":"settle_bet","instance":0,"value":{"status":"started"}} {"stream_type":"event","sim_ts":7.5806398141048446,"timestamp":"...","key":"bets-2","task":"place_bet","instance":1,"value":{"bet_id":2,"stake":10,"odds":2.74}} {"stream_type":"event","sim_ts":7.5806398141048446,"timestamp":"...","key":"bets-2","task":"settle_bet","instance":1,"value":{"status":"started"}} {"stream_type":"event","sim_ts":12.491926619839258,"timestamp":"...","key":"bets-3","task":"place_bet","instance":2,"value":{"bet_id":3,"stake":5,"odds":1.5}} ``` The Builder file builds the same model with the builder API and prints every record of its run: ```bash python examples/gallery/bets_are_settled_and_winners_paid_builder.py ``` ```python """Each bet is settled after the match, and a winner is paid the stake times the odds. The Builder form of bets_are_settled_and_winners_paid.yaml, with the same records. A bet is placed with a stake and odds. One to two minutes later it is settled: 45 percent win and are paid the stake times the odds, and the rest lose and are paid nothing. Needs: nothing Run it with: python examples/gallery/bets_are_settled_and_winners_paid_builder.py """ import logging from datetime import datetime from desflow import ConsoleEgress, SimulationContext from desflow.values import Template, generator UNTIL = 1200 def build() -> SimulationContext: """Builds the model.""" app = ( SimulationContext( sim_id="Book", factor=0, random_seed=42, logical_start_time=datetime(2026, 1, 1), ) .add_egress(ConsoleEgress()) .add_arrival("bets", "exponential", rate=0.2, spawn="place_bet") ) place_payload = Template( { "bet_id": {"gen": "sequence", "start": 1}, "stake": { "gen": "weighted", "options": {5: 50, 10: 30, 50: 15, 100: 5}, }, "odds": {"gen": "uniform", "low": 1.5, "high": 4, "decimals": 2}, }, name="tasks.place_bet", ) settle_payload = Template( { "bet_id": {"gen": "upstream", "path": "bet_id"}, "result": { "gen": "when", "condition": "won", "then": "won", "else": "lost", }, "payout": { "gen": "when", "condition": "won", "then": { "gen": "multiply", "args": [ {"gen": "upstream", "path": "stake"}, {"gen": "upstream", "path": "odds"}, ], "decimals": 2, }, "else": 0, }, }, name="tasks.settle_bet", ) @app.task(name="place_bet", next="settle_bet") def place_bet(task_id): return place_payload @app.task( name="settle_bet", vars={"won": generator({"gen": "boolean", "p": 0.45})}, service_time=generator({"gen": "uniform", "low": 60, "high": 120}), ) def settle_bet(task_id): return settle_payload return app if __name__ == "__main__": logging.basicConfig(level=logging.INFO, format="%(levelname)s %(message)s") build().run(until=UNTIL) ``` The Low-level file builds the model on `DynamicRealtimeEnvironment`, with plain Python processes, and prints every record of its run: ```bash python examples/gallery/bets_are_settled_and_winners_paid_low_level.py ``` The Low-level file draws each value with `Sampler.generator()`, where the place is the key path of the blueprint's generator that makes the same value, such as `tasks.place_bet.payload.stake`, `tasks.place_bet.payload.odds` and `tasks.settle_bet.vars.won` and 1 more. Each draw therefore comes from the random sequence the blueprint uses at the same place, so the draws are the blueprint's. The gaps between arrivals come from `Sampler.sample` on a `DistributionConfig` whose `stream` is `arrival.bets`, the sequence the blueprint uses for its arrivals. ```python """Each bet is settled after the match, and a winner is paid the stake times the odds. The Low-level form of bets_are_settled_and_winners_paid.yaml, with the same records, built on `DynamicRealtimeEnvironment`. A bet is placed with a stake and odds. One to two minutes later it is settled: 45 percent win and are paid the stake times the odds, and the rest lose and are paid nothing. Needs: nothing Run it with: python examples/gallery/bets_are_settled_and_winners_paid_low_level.py """ import itertools import logging from datetime import datetime from desflow import ( ConsoleEgress, DistributionConfig, DynamicRealtimeEnvironment, Sampler, ) SEED = 42 UNTIL = 1200 STAKES = {5: 50, 10: 30, 50: 15, 100: 5} def weighted(rng, options): """One key of `options`, chosen by its weight, as the `weighted` generator does.""" point = rng.random() * sum(options.values()) running = 0.0 for value, weight in options.items(): running += weight if point < running: return value return value def build(env): """Starts the bet source on `env`.""" sampler = Sampler(seed=SEED) stake = sampler.generator("tasks.place_bet.payload.stake") odds = sampler.generator("tasks.place_bet.payload.odds") wins = sampler.generator("tasks.settle_bet.vars.won") until_settled = sampler.generator("tasks.settle_bet.service_time") gap = DistributionConfig(dist="exponential", rate=0.2) gap.stream = "arrival.bets" bet_ids = itertools.count(1) def bet(key, instance): placed = { "bet_id": next(bet_ids), "stake": weighted(stake, STAKES), "odds": round(1.5 + (4 - 1.5) * odds.random(), 2), } env.publish_event(key, placed, task="place_bet", instance=instance) env.publish_event( key, {"status": "started"}, task="settle_bet", instance=instance ) yield env.timeout(60 + (120 - 60) * until_settled.random()) # The blueprint's `won` var is first read when the settled record is made won = bool(wins.random() < 0.45) payout = round(placed["stake"] * placed["odds"], 2) if won else 0 env.publish_event( key, { "bet_id": placed["bet_id"], "result": "won" if won else "lost", "payout": payout, }, task="settle_bet", instance=instance, ) def bets(): for number in itertools.count(1): yield env.timeout(sampler.sample(gap)) env.process(bet(f"bets-{number}", number - 1)) env.process(bets()) def run(): """Runs the model for 20 simulation minutes.""" env = DynamicRealtimeEnvironment(factor=0, logical_start_time=datetime(2026, 1, 1)) env.setup_egress([ConsoleEgress()]) build(env) try: env.run(until=UNTIL) finally: env.teardown() if __name__ == "__main__": logging.basicConfig(level=logging.INFO, format="%(levelname)s %(message)s") run() ``` ### An audit that finds an issue needs a follow-up, which waits for the same two auditors An audit of one of 150 merchants is due about every 3 hours and takes an auditor about 4 hours, and 15 percent find an issue. A follow-up takes about an hour and goes to the back of the same queue, so audits and follow-ups compete for the two auditors. Run it with the sample option, which stops after the first events and prints them: ```bash desflow run examples/gallery/audits_with_findings_need_a_follow_up.yaml --sample 5 ``` ```yaml # An audit that finds an issue needs a follow-up, which waits for the same two auditors. # # An audit of one of 150 merchants is due about every 3 hours and takes an auditor # about 4 hours, and 15 percent find an issue. A follow-up takes about an hour and # goes to the back of the same queue, so audits and follow-ups compete for the two # auditors. # # Needs: nothing # Run it with: desflow run examples/gallery/audits_with_findings_need_a_follow_up.yaml simulation: sim_id: Compliance factor: 0 random_seed: 42 logical_start_time: 2026-01-01T00:00:00 egress: - {type: Console} resources: auditors: {current_cap: 2, max_cap: 2} services: audit: {dist: normal, mean: 4 hours, std: 1 hour} follow_up: {dist: normal, mean: 1 hour, std: 15 min} arrivals: audits_due: {dist: exponential, rate: 0.0001, spawn: audit} tasks: audit: service: audit resource: auditors payload: merchant: {gen: integer, bounds: [1, 150]} finding: gen: weighted options: {clean: 85, issue: 15} next: when: - {condition: "payload.finding == 'issue'", task: follow_up} follow_up: service: follow_up resource: auditors payload: merchant: {gen: upstream, path: merchant} event_type: follow_up_done run: {until: 14 days} ``` ```text {"stream_type":"event","sim_ts":1105.7526406613883,"timestamp":"...","key":"audits_due-1","task":"audit","instance":0,"value":{"path_id":"Compliance.service.audit","sim_id":"Compliance","service":"audit","status":"queued"}} {"stream_type":"event","sim_ts":1105.7526406613883,"timestamp":"...","key":"audits_due-1","task":"audit","instance":0,"value":{"path_id":"Compliance.service.audit","sim_id":"Compliance","service":"audit","status":"started"}} {"stream_type":"event","sim_ts":19750.84009484635,"timestamp":"...","key":"audits_due-1","task":"audit","instance":0,"value":{"merchant":33,"finding":"clean"}} {"stream_type":"event","sim_ts":21228.07052368513,"timestamp":"...","key":"audits_due-2","task":"audit","instance":1,"value":{"path_id":"Compliance.service.audit","sim_id":"Compliance","service":"audit","status":"queued"}} {"stream_type":"event","sim_ts":21228.07052368513,"timestamp":"...","key":"audits_due-2","task":"audit","instance":1,"value":{"path_id":"Compliance.service.audit","sim_id":"Compliance","service":"audit","status":"started"}} ``` The Builder file builds the same model with the builder API and prints every record of its run: ```bash python examples/gallery/audits_with_findings_need_a_follow_up_builder.py ``` ```python """An audit that finds an issue needs a follow-up, which waits for the same auditors. The Builder form of audits_with_findings_need_a_follow_up.yaml, with the same records. An audit of one of 150 merchants is due about every 3 hours and takes an auditor about 4 hours, and 15 percent find an issue. A follow-up of about an hour goes to the back of the same queue. Needs: nothing Run it with: python examples/gallery/audits_with_findings_need_a_follow_up_builder.py """ import logging from datetime import datetime from desflow import ConsoleEgress, SimulationContext from desflow.values import Template UNTIL = 14 * 24 * 3600 def build() -> SimulationContext: """Builds the model.""" app = ( SimulationContext( sim_id="Compliance", factor=0, random_seed=42, logical_start_time=datetime(2026, 1, 1), ) .add_egress(ConsoleEgress()) .add_resource("auditors", current_cap=2, max_cap=2) .add_service("audit", dist="normal", mean="4 hours", std="1 hour") .add_service("follow_up", dist="normal", mean="1 hour", std="15 min") .add_arrival("audits_due", "exponential", rate=0.0001, spawn="audit") ) audit_payload = Template( { "merchant": {"gen": "integer", "bounds": [1, 150]}, "finding": {"gen": "weighted", "options": {"clean": 85, "issue": 15}}, }, name="tasks.audit", ) follow_up_payload = Template( { "merchant": {"gen": "upstream", "path": "merchant"}, "event_type": "follow_up_done", }, name="tasks.follow_up", ) @app.task( name="audit", service_id="audit", resource_id="auditors", next={ "when": [{"condition": "payload.finding == 'issue'", "task": "follow_up"}] }, ) def audit(task_id): return audit_payload @app.task(name="follow_up", service_id="follow_up", resource_id="auditors") def follow_up(task_id): return follow_up_payload return app if __name__ == "__main__": logging.basicConfig(level=logging.INFO, format="%(levelname)s %(message)s") build().run(until=UNTIL) ``` The Low-level file builds the model on `DynamicRealtimeEnvironment`, with plain Python processes, and prints every record of its run: ```bash python examples/gallery/audits_with_findings_need_a_follow_up_low_level.py ``` The Low-level file draws each value with `Sampler.generator()`, where the place is the key path of the blueprint's generator that makes the same value, such as `tasks.audit.payload.merchant` and `tasks.audit.payload.finding`. Each draw therefore comes from the random sequence the blueprint uses at the same place, so the draws are the blueprint's. ```python """An audit that finds an issue needs a follow-up, which waits for the same auditors. The Low-level form of audits_with_findings_need_a_follow_up.yaml, with the same records, built on `DynamicRealtimeEnvironment`. An audit of one of 150 merchants is due about every 3 hours and takes an auditor about 4 hours, and 15 percent find an issue. A follow-up of about an hour goes to the back of the same queue. Needs: nothing Run it with: python examples/gallery/audits_with_findings_need_a_follow_up_low_level.py """ import itertools import logging from datetime import datetime from desflow import ( CapacityConfig, ConsoleEgress, DistributionConfig, DynamicRealtimeEnvironment, DynamicResource, Sampler, SimParameter, ) SEED = 42 UNTIL = 14 * 24 * 3600 PARAMS = SimParameter( sim_id="Compliance", arrival={"audits_due": DistributionConfig(dist="exponential", rate=0.0001)}, # DistributionConfig takes seconds: 4 hours (std 1 hour) for an audit, # 1 hour (std 15 min) for a follow-up service={ "audit": DistributionConfig(dist="normal", mean=14400, std=3600), "follow_up": DistributionConfig(dist="normal", mean=3600, std=900), }, resources={"auditors": CapacityConfig(current_cap=2, max_cap=2)}, ) def weighted(rng, options): """One key of `options`, chosen by its weight, as the `weighted` generator does.""" point = rng.random() * sum(options.values()) running = 0.0 for value, weight in options.items(): running += weight if point < running: return value return value def build(env): """Starts the audit source on `env`.""" env.registry.register_sim_parameter(PARAMS) sampler = Sampler(seed=SEED) merchant = sampler.generator("tasks.audit.payload.merchant") finding = sampler.generator("tasks.audit.payload.finding") auditors = DynamicResource(env, "Compliance", "auditors") instances = {"audit": itertools.count(), "follow_up": itertools.count()} def step(key, task, payload): """Queues for an auditor, works for the task's service time, then publishes what `payload()` gives.""" path_id = f"Compliance.service.{task}" instance = next(instances[task]) def publish(value): env.publish_event(key, value, task=task, instance=instance) publish( { "path_id": path_id, "sim_id": "Compliance", "service": task, "status": "queued", } ) with auditors.request() as request: yield request publish( { "path_id": path_id, "sim_id": "Compliance", "service": task, "status": "started", } ) yield env.timeout(sampler.sample(env.registry.get_config(path_id))) made = payload() publish(made) return made def audit_payload(): return { "merchant": int(merchant.integers(1, 151)), "finding": weighted(finding, {"clean": 85, "issue": 15}), } def audit(key): made = yield from step(key, "audit", audit_payload) if made["finding"] == "issue": yield from step( key, "follow_up", lambda: {"merchant": made["merchant"], "event_type": "follow_up_done"}, ) def audits_due(): gap = env.registry.get_config("Compliance.arrival.audits_due") for number in itertools.count(1): yield env.timeout(sampler.sample(gap)) env.process(audit(f"audits_due-{number}")) env.process(audits_due()) def run(): """Runs the model for 14 simulation days.""" env = DynamicRealtimeEnvironment(factor=0, logical_start_time=datetime(2026, 1, 1)) env.setup_egress([ConsoleEgress()]) build(env) try: env.run(until=UNTIL) finally: env.teardown() if __name__ == "__main__": logging.basicConfig(level=logging.INFO, format="%(levelname)s %(message)s") run() ``` # Local Simulation This example models a shop packing orders. The simulation prints events and telemetry to the terminal. It needs no container, so it is the place to start. Each tab shows the example written one way: as a YAML blueprint, with the builder API, or with the low-level API. [Ways to write a simulation](https://jaehyeon.me/desflow/latest/user-guide/writing-a-model/index.md) compares the three. In the output, look for each order's `queued`, `started` and finished events, and for the packers' readings every 2 simulation seconds. The capacity reading changes when the scenario adds packers at 10 seconds and removes one at 20 seconds. ______________________________________________________________________ ## Before You Start The example needs only desflow, which each Quick Start below installs, and no other service. [Services for the Examples](https://jaehyeon.me/desflow/latest/gallery/#services-for-the-examples) lists the services the other examples need. ______________________________________________________________________ ## Steps ### Run It This example builds the same simulation as the builder example in the Builder tab, from a YAML blueprint and nothing else. No Python is written: the arrival loop, the task and the statistics are all declared in the file. It writes to `ConsoleEgress` and needs no container, so it is the place to start. **Quick Start** `desflow examples get` downloads the example at the release you install, into a folder of its own. Pick uv or pip: ```bash # 1. Install uv tool install desflow # 2. Download the example desflow examples get local --api yaml cd local/yaml # 3. Run it desflow run local.yaml ``` ```bash # 1. Install pip install desflow # 2. Download the example desflow examples get local --api yaml cd local/yaml # 3. Run it desflow run local.yaml ``` **What It Does** The run prints every record to the terminal and stops after 30 simulation seconds, which at `factor: 1.0` is 30 real seconds. Add `--until 10` to stop after 10 simulation seconds instead. [Check the Result](#check-the-result) shows what it prints. This version builds the simulation with the builder API (`SimulationContext`). It adds `ConsoleEgress` and no ingress. `add_process` starts `capacity_changes`, which waits on the simulation clock and changes the number of packers at 10 and 20 seconds, as the YAML `scenario` does. **Quick Start** `desflow examples get` downloads the example at the release you install, into a folder of its own. Pick uv or pip: ```bash # 1. Install uv tool install desflow # 2. Download the example desflow examples get local --api builder cd local/builder # 3. Run it uv run --no-project --with desflow local_example.py ``` ```bash # 1. Install pip install desflow # 2. Download the example desflow examples get local --api builder cd local/builder # 3. Run it python local_example.py ``` This version wires the simulation by hand on `DynamicRealtimeEnvironment`, the low-level API. **Quick Start** `desflow examples get` downloads the example at the release you install, into a folder of its own. Pick uv or pip: ```bash # 1. Install uv tool install desflow # 2. Download the example desflow examples get local --api low-level cd local/low-level # 3. Run it uv run --no-project --with desflow local_example.py ``` ```bash # 1. Install pip install desflow # 2. Download the example desflow examples get local --api low-level cd local/low-level # 3. Run it python local_example.py ``` ______________________________________________________________________ ## Check the Result The three tabs print the same records, which [a test](https://github.com/jaehyeon-kim/desflow/blob/v1.3.0/tests/docs/test_example_twins.py) checks by running each version unpaced. Telemetry lines carry `[TEL]` and events carry `[EVT]`. These are the events of the first order, and the packers' capacity reading before and after the first change: ```text [EVT] {'sim_ts': 0.3141556656469718, 'timestamp': '...', 'key': 'orders-1', 'task': 'pack_order', 'instance': 0, 'value': {'path_id': 'Shop.service.packing', 'sim_id': 'Shop', 'service': 'packing', 'status': 'queued'}} [EVT] {'sim_ts': 0.3141556656469718, 'timestamp': '...', 'key': 'orders-1', 'task': 'pack_order', 'instance': 0, 'value': {'path_id': 'Shop.service.packing', 'sim_id': 'Shop', 'service': 'packing', 'status': 'started'}} [TEL] {'sim_ts': 2.0, 'timestamp': '...', 'path_id': 'Shop.stats.resources.packers.capacity', 'value': 1} [EVT] {'sim_ts': 3.2430768707631574, 'timestamp': '...', 'key': 'orders-1', 'task': 'pack_order', 'instance': 0, 'value': {'event_type': 'order_packed', 'shipping': 'standard', 'order_id': 0}} [TEL] {'sim_ts': 12.0, 'timestamp': '...', 'path_id': 'Shop.stats.resources.packers.capacity', 'value': 3} ``` Each order produces a `queued`, a `started` and a finished event. Every event carries the order's key, such as `orders-1`, with the task's name and instance. The finished event is the task's `payload`, with the task id added as `order_id` because of `id_field`. The capacity reading shows the scenario: one packer, three from 10 seconds, then two from 20 seconds. ______________________________________________________________________ ## Full Files Full files The blueprint declares one resource, one service and one arrival. `spawn` names the task each arrival starts. `stats: minimal` publishes the packers' four readings and the task's `in_progress` every 2 simulation seconds. The `scenario` changes the number of packers at 10 and 20 seconds. Files live in the [`examples/yaml/` folder](https://github.com/jaehyeon-kim/desflow/tree/v1.3.0/examples/yaml) of the repository, and the label on each block below is its path there. ```yaml # Local simulation in YAML, with no Python and no containers. # # The YAML version of local_example.py, which --api builder downloads. This simulation # models a shop packing orders. ConsoleEgress prints events and telemetry to the # terminal. A scenario adds packers at 10 seconds and removes one at 20 seconds. # The run ends on its own after 30 simulation seconds. # # Run it from its folder with: desflow run local.yaml simulation: {sim_id: Shop, factor: 1.0, random_seed: 42} egress: - {type: Console} resources: packers: {current_cap: 1, max_cap: 5} services: packing: {dist: normal, mean: 3.0, std: 0.5} arrivals: # Each order spawns one pack_order task. orders: {dist: exponential, rate: 1.0, spawn: pack_order} tasks: pack_order: service: packing resource: packers # The value of the task's finished event. id_field adds the task id as order_id. payload: {event_type: order_packed, shipping: standard} id_field: order_id # Publishes the packers' capacity, in_use, queue_length and utilization every 2 # simulation seconds, as Shop.stats.resources.packers.. stats: {level: minimal, interval: 2} scenario: # Three packers from 10 seconds, then two from 20 seconds. - {at: 10, path: Shop.resources.packers.current_cap, value: 3} - {at: 20, path: Shop.resources.packers.current_cap, value: 2} run: {until: 30} ``` This script builds the model, runs it for 30 simulation seconds, and streams events and telemetry directly to your terminal. Scripts live in the [`examples/` folder](https://github.com/jaehyeon-kim/desflow/tree/v1.3.0/examples) of the repository, and the label on the block below is this one's path there. ```python """Local simulation, builder API, no containers. This example models a shop packing orders with `SimulationContext`. `ConsoleEgress` prints events and telemetry to the terminal, so nothing external is involved. A scenario adds packers at 10 seconds and removes one at 20 seconds. The built-in statistics show the effect. Start here. It needs no broker, no database and no object store, and it ends on its own after 30 simulation seconds. """ import logging from desflow import ConsoleEgress, SimulationContext # Logging is configured here rather than in a wrapper, because this script is run # directly. Without it the run prints no records, and a ConsoleEgress in the log # format prints one warning on stderr that says so and names the fix. logging.basicConfig( level=logging.INFO, format="%(asctime)s [%(levelname)s] %(name)s: %(message)s", datefmt="%H:%M:%S", ) logger = logging.getLogger(__name__) # ========================================== # 1. Infrastructure Builder # ========================================== app = ( SimulationContext(sim_id="Shop", factor=1.0, random_seed=42) .add_egress(ConsoleEgress()) .add_resource("packers", current_cap=1, max_cap=5) .add_service("packing", dist="normal", mean=3.0, std=0.5) .add_arrival("orders", dist="exponential", rate=1.0) # The packers' readings every 2 simulation seconds .with_stats("minimal", interval=2.0) ) # ========================================== # 2. Simulation Logic (Decorators) # ========================================== @app.task(service_id="packing", resource_id="packers") def pack_order(task_id: int, context): """Packs one order and returns the payload of its finished event.""" return {"event_type": "order_packed", "shipping": "standard", "order_id": task_id} @app.arrival_loop("orders") def arrival_generator(context): """Spawns a pack_order task for every order the 'orders' distribution draws.""" task_id = 0 while True: # Each arrival is a new order, whose key (orders-1, orders-2) is on its events entity = yield context.wait_for_arrival("orders") context.spawn(pack_order(task_id, context, entity=entity)) task_id += 1 def capacity_changes(context): """Three packers from 10 seconds, then two from 20 seconds, on simulation time.""" path = "Shop.resources.packers.current_cap" yield context.env.timeout(10) context.env.registry.update(path, 3) yield context.env.timeout(10) context.env.registry.update(path, 2) app.add_process(capacity_changes) # ========================================== # 3. Execution # ========================================== def run(): """Starts the local simulation for a fixed duration.""" logger.info("Starting Builder Local Example. Running for 30 seconds...") app.run(until=30) if __name__ == "__main__": run() ``` This script builds the model and runs it for 30 simulation seconds. The `capacity_changes` process changes the number of packers from 1 to 3 at 10 seconds, then down to 2 at 20 seconds. Events and telemetry stream directly to your terminal, driven by plain SimPy generators. Scripts live in the [`examples/` folder](https://github.com/jaehyeon-kim/desflow/tree/v1.3.0/examples) of the repository, and the label on the block below is this one's path there. ```python """Local simulation, low-level API, no containers. The low-level version of `builder/local_example.py`, built on `DynamicRealtimeEnvironment` directly. It models a shop packing orders and uses `ConsoleEgress` to print events and telemetry. A scenario process adds packers at 10 seconds and removes one at 20 seconds. The built-in statistics show the effect. Needs no containers. Ends on its own after 30 simulation seconds. """ import logging import numpy as np from desflow import ( CapacityConfig, ConsoleEgress, DistributionConfig, DynamicRealtimeEnvironment, DynamicResource, Sampler, SimParameter, ) logging.basicConfig( level=logging.INFO, format="%(levelname)s [%(asctime)s] %(message)s" ) logger = logging.getLogger("local_example") # The shop starts with 1 packer and has room for 5. PARAMS = SimParameter( sim_id="Shop", arrival={"orders": DistributionConfig(dist="exponential", rate=1.0)}, service={"packing": DistributionConfig(dist="normal", mean=3.0, std=0.5)}, resources={"packers": CapacityConfig(current_cap=1, max_cap=5)}, ) def pack_order(env, sampler, packers, key, task_id): """Models the task lifecycle: queued, started, then finished with its payload. Every event carries the order's key, and the task's name and instance id. """ path_id = "Shop.service.packing" def publish(value): env.publish_event(key, value, task="pack_order", instance=task_id) publish( {"path_id": path_id, "sim_id": "Shop", "service": "packing", "status": "queued"} ) env.stats.task_queued("pack_order", task_id) # counted as in progress with packers.request() as req: yield req publish( { "path_id": path_id, "sim_id": "Shop", "service": "packing", "status": "started", } ) env.stats.task_started("pack_order", task_id) # Late binding: the service time is read when the work starts yield env.timeout(sampler.sample(env.registry.get_config(path_id))) publish( {"event_type": "order_packed", "shipping": "standard", "order_id": task_id} ) env.stats.task_finished("pack_order", task_id) def arrival_generator(env, sampler, packers): """Spawns a pack_order task for every order the arrival distribution draws.""" # A reference: the config follows the registry when the rate changes gap = env.registry.get_config("Shop.arrival.orders") task_id = 0 while True: yield env.timeout(sampler.sample(gap)) # Each arrival is a new order, keyed orders-1, orders-2 and so on env.process(pack_order(env, sampler, packers, f"orders-{task_id + 1}", task_id)) task_id += 1 def capacity_changes(env): """Three packers from 10 seconds, then two from 20 seconds, on simulation time.""" path = "Shop.resources.packers.current_cap" yield env.timeout(10) env.registry.update(path, 3) yield env.timeout(10) env.registry.update(path, 2) def run(): env = DynamicRealtimeEnvironment(factor=1.0, strict=False) env.registry.register_sim_parameter(PARAMS) env.setup_egress([ConsoleEgress()]) # The packers' readings every 2 simulation seconds env.setup_stats("Shop", "minimal", interval=2.0) packers = DynamicResource(env, "Shop", "packers") sampler = Sampler(rng=np.random.default_rng(42)) env.process(arrival_generator(env, sampler, packers)) env.process(capacity_changes(env)) logger.info("Simulation started. Watch the capacity change at 10 s and 20 s...") try: env.run(until=30) finally: env.teardown() if __name__ == "__main__": run() ``` # Kafka Digital Twin This example models a shop packing orders. The simulation reads parameter updates from a Kafka topic and publishes events and telemetry to Kafka topics. Each tab shows the example written one way: as a YAML blueprint, with the builder API, or with the low-level API. [Ways to write a simulation](https://jaehyeon.me/desflow/latest/user-guide/writing-a-model/index.md) compares the three. With `KafkaIngress` and `KafkaEgress` in place of the local connectors, the simulation runs as a separate service. Look for the lifecycle events on `sim-events` and the packers' readings on `sim-telemetry`, published every 2 simulation seconds. A JSON parameter update sent to `sim-config` changes the running simulation, and the readings show the change. ______________________________________________________________________ ## Before You Start The example needs Docker and the odctl profile `kafka-lite`. Each Quick Start below starts the profile, and the Check the Result section stops it. [Services for the Examples](https://jaehyeon.me/desflow/latest/gallery/#services-for-the-examples) shows how to install odctl. ______________________________________________________________________ ## Steps ### Run It This example builds the simulation of the builder example in the Builder tab from a YAML blueprint, with no Python. The connectors, the parameters, the task and the telemetry are all declared in the file. **Quick Start** `desflow examples get` downloads the example at the release you install, into a folder of its own. Pick uv or pip: ```bash # 1. Install uv tool install "desflow[kafka]" --with-executables-from "odctl>=1.0,<2" # 2. Download the example desflow examples get kafka --api yaml cd kafka/yaml # 3. Start its service odctl up kafka-lite # 4. Run it (Ctrl + C to stop) desflow run kafka.yaml # 5. In a second terminal, in the same folder, watch and steer it at http://localhost:8080 uv run --no-project --with "desflow[kafka]" --with nicegui ../kafka_dashboard.py ``` ```bash # 1. Install pip install "desflow[kafka]" "odctl>=1.0,<2" nicegui # 2. Download the example desflow examples get kafka --api yaml cd kafka/yaml # 3. Start its service odctl up kafka-lite # 4. Run it (Ctrl + C to stop) desflow run kafka.yaml # 5. In a second terminal, in the same folder, watch and steer it at http://localhost:8080 python ../kafka_dashboard.py ``` **What It Does** The run keeps going until you stop it. When it starts, `KafkaEgress` creates `sim-events` and `sim-telemetry` if they do not exist, and `KafkaIngress` creates `sim-config` if it does not exist. The run then publishes task lifecycle events to `sim-events`, and the packers' four readings (`capacity`, `in_use`, `queue_length` and `utilization`) and the task's `in_progress` to `sim-telemetry`. It applies parameter updates sent to `sim-config`. The dashboard in the Quick Start works with this run unchanged, because it reads the same topics and the same four packer readings. The blueprint reads the broker address with `${KAFKA_BOOTSTRAP_SERVERS:-127.0.0.1:9092}`, so the environment variable `KAFKA_BOOTSTRAP_SERVERS` overrides it. This version builds the simulation with the builder API (`SimulationContext`). **Quick Start** `desflow examples get` downloads the example at the release you install, into a folder of its own. Pick uv or pip: ```bash # 1. Install uv tool install "desflow[kafka]" --with-executables-from "odctl>=1.0,<2" # 2. Download the example desflow examples get kafka --api builder cd kafka/builder # 3. Start its service odctl up kafka-lite # 4. Run it (Ctrl + C to stop) uv run --no-project --with "desflow[kafka]" kafka_example.py # 5. In a second terminal, in the same folder, watch and steer it at http://localhost:8080 uv run --no-project --with "desflow[kafka]" --with nicegui ../kafka_dashboard.py ``` ```bash # 1. Install pip install "desflow[kafka]" "odctl>=1.0,<2" nicegui # 2. Download the example desflow examples get kafka --api builder cd kafka/builder # 3. Start its service odctl up kafka-lite # 4. Run it (Ctrl + C to stop) python kafka_example.py # 5. In a second terminal, in the same folder, watch and steer it at http://localhost:8080 python ../kafka_dashboard.py ``` The run keeps going until you stop it. It logs one line per order when a packer starts on it. It publishes task lifecycle events to `sim-events`, and the packers' four readings (`capacity`, `in_use`, `queue_length` and `utilization`) and the task's `in_progress` to `sim-telemetry`. This version wires the simulation by hand on `DynamicRealtimeEnvironment`, the low-level API. **Quick Start** `desflow examples get` downloads the example at the release you install, into a folder of its own. Pick uv or pip: ```bash # 1. Install uv tool install "desflow[kafka]" --with-executables-from "odctl>=1.0,<2" # 2. Download the example desflow examples get kafka --api low-level cd kafka/low-level # 3. Start its service odctl up kafka-lite # 4. Run it (Ctrl + C to stop) uv run --no-project --with "desflow[kafka]" kafka_example.py # 5. In a second terminal, in the same folder, watch and steer it at http://localhost:8080 uv run --no-project --with "desflow[kafka]" --with nicegui ../kafka_dashboard.py ``` ```bash # 1. Install pip install "desflow[kafka]" "odctl>=1.0,<2" nicegui # 2. Download the example desflow examples get kafka --api low-level cd kafka/low-level # 3. Start its service odctl up kafka-lite # 4. Run it (Ctrl + C to stop) python kafka_example.py # 5. In a second terminal, in the same folder, watch and steer it at http://localhost:8080 python ../kafka_dashboard.py ``` The run keeps going until you stop it. It logs one line per order when a packer starts on it. It publishes task lifecycle events to `sim-events`, and the packers' four readings (`capacity`, `in_use`, `queue_length` and `utilization`) and the task's `in_progress` to `sim-telemetry`. ### Change a Parameter Live Step 5 of each Quick Start starts a dashboard at http://localhost:8080. It reads `sim-telemetry`, and its capacity control sends a new `current_cap` for the packers to `sim-config`. `KafkaIngress` applies the update while the run goes, and the packers' `capacity` reading on `sim-telemetry` shows the change. Any producer can send the same update: a JSON message such as `{"path": "Shop.resources.packers.current_cap", "value": 3}` on `sim-config`. ______________________________________________________________________ ## Check the Result The three tabs publish the same records, which [a test](https://github.com/jaehyeon-kim/desflow/blob/v1.3.0/tests/docs/test_example_twins.py) checks by running each version unpaced. A real run sends the events to `sim-events` and the telemetry to `sim-telemetry`. Stop the run and the dashboard with Ctrl + C, and leave the service up. This command reads the first three events back from the broker: ```bash docker exec kafka /opt/kafka/bin/kafka-console-consumer.sh \ --bootstrap-server localhost:9092 --topic sim-events --from-beginning --max-messages 3 ``` It prints three JSON lines, then `Processed a total of 3 messages`. The first two are `orders-1` queued and started, both at `sim_ts` 0.3141556656469718, and the third is `orders-2` queued. Each `timestamp` is the wall-clock time of your run: ```text {"sim_ts":0.3141556656469718,"timestamp":"...","key":"orders-1","task":"pack_order","instance":0,"value":{"path_id":"Shop.service.packing","sim_id":"Shop","service":"packing","status":"queued"}} {"sim_ts":0.3141556656469718,"timestamp":"...","key":"orders-1","task":"pack_order","instance":0,"value":{"path_id":"Shop.service.packing","sim_id":"Shop","service":"packing","status":"started"}} {"sim_ts":2.4671694506095694,"timestamp":"...","key":"orders-2","task":"pack_order","instance":1,"value":{"path_id":"Shop.service.packing","sim_id":"Shop","service":"packing","status":"queued"}} ``` Use `--topic sim-telemetry` to read the packers' readings, or open the Kafka UI at http://127.0.0.1:8086. A second run appends to the same topics, so start again with an empty broker when you want only one run in them. When you have checked the result, stop the service: ```bash odctl down kafka-lite --volumes ``` In `kafka/yaml`, which `desflow examples get kafka --api yaml` creates, `desflow run kafka.yaml --sample 5 --stdout` needs no broker. It prints the first five events, and the telemetry published between them, as JSON lines, unpaced: ```text {"stream_type":"event","sim_ts":0.3141556656469718,"timestamp":"...","key":"orders-1","task":"pack_order","instance":0,"value":{"path_id":"Shop.service.packing","sim_id":"Shop","service":"packing","status":"queued"}} {"stream_type":"event","sim_ts":0.3141556656469718,"timestamp":"...","key":"orders-1","task":"pack_order","instance":0,"value":{"path_id":"Shop.service.packing","sim_id":"Shop","service":"packing","status":"started"}} {"stream_type":"telemetry","sim_ts":2.0,"timestamp":"...","path_id":"Shop.stats.resources.packers.capacity","value":1} {"stream_type":"telemetry","sim_ts":2.0,"timestamp":"...","path_id":"Shop.stats.resources.packers.in_use","value":1} {"stream_type":"telemetry","sim_ts":2.0,"timestamp":"...","path_id":"Shop.stats.resources.packers.queue_length","value":0} {"stream_type":"telemetry","sim_ts":2.0,"timestamp":"...","path_id":"Shop.stats.resources.packers.utilization","value":100.0} {"stream_type":"telemetry","sim_ts":2.0,"timestamp":"...","path_id":"Shop.stats.tasks.pack_order.in_progress","value":1} {"stream_type":"event","sim_ts":2.4671694506095694,"timestamp":"...","key":"orders-2","task":"pack_order","instance":1,"value":{"path_id":"Shop.service.packing","sim_id":"Shop","service":"packing","status":"queued"}} {"stream_type":"event","sim_ts":2.5122243094067938,"timestamp":"...","key":"orders-3","task":"pack_order","instance":2,"value":{"path_id":"Shop.service.packing","sim_id":"Shop","service":"packing","status":"queued"}} {"stream_type":"event","sim_ts":3.124962891934927,"timestamp":"...","key":"orders-4","task":"pack_order","instance":3,"value":{"path_id":"Shop.service.packing","sim_id":"Shop","service":"packing","status":"queued"}} ``` With one packer, `orders-1` starts at once. At 2 simulation seconds the readings show 1 packer in use, an empty queue and 1 task in progress, and `orders-2` arrives after them. ______________________________________________________________________ ## Full Files Full files The blueprint wires both Kafka connectors and declares the packers, the packing service, the order arrival and the task. The finished event of each task is the fixed `payload`. `stats: minimal` publishes the packers' four built-in readings and the task's `in_progress` every 2 simulation seconds. `with_stats("minimal", interval=2.0)` does the same in the builder version, and `env.setup_stats` in the low-level version. Files live in the [`examples/yaml/` folder](https://github.com/jaehyeon-kim/desflow/tree/v1.3.0/examples/yaml) of the repository, and the label on each block below is its path there. ```yaml # Kafka digital twin in YAML. # # The YAML version of kafka_example.py, which --api builder downloads: a shop packing # orders. KafkaIngress reads parameter updates from sim-config, and KafkaEgress # publishes lifecycle events to sim-events and packer metrics to sim-telemetry. # KafkaEgress creates its two topics when the run starts. # # Needs a broker: odctl up kafka-lite. Runs until interrupted with Ctrl + C. # KAFKA_BOOTSTRAP_SERVERS overrides the broker address. # Run it from its folder with: desflow run kafka.yaml simulation: {sim_id: Shop, factor: 1.0, random_seed: 42} ingress: - type: Kafka config: topic: sim-config bootstrap_servers: ${KAFKA_BOOTSTRAP_SERVERS:-127.0.0.1:9092} egress: - type: Kafka config: event_topic: sim-events telemetry_topic: sim-telemetry bootstrap_servers: ${KAFKA_BOOTSTRAP_SERVERS:-127.0.0.1:9092} resources: packers: {current_cap: 1, max_cap: 10} services: packing: {dist: normal, mean: 3.0, std: 0.5} arrivals: orders: {dist: exponential, rate: 1.0, spawn: pack_order} tasks: pack_order: service: packing resource: packers payload: path_id: Shop.service.packing sim_id: Shop service: packing status: finished # The packers' readings every 2 seconds, which kafka_dashboard.py shows. stats: {level: minimal, interval: 2} ``` This script connects the simulation to Kafka topics and uses Pydantic models to fix the fields and types of the events. Scripts live in the [`examples/` folder](https://github.com/jaehyeon-kim/desflow/tree/v1.3.0/examples) of the repository, and the label on the block below is this one's path there. ```python """Kafka Digital Twin, builder API. Models a shop packing orders with `SimulationContext` and connects the simulation to Kafka for input and output. `KafkaIngress` reads parameter updates from `sim-config`, so the running simulation can be steered without restarting it. `KafkaEgress` publishes lifecycle events to `sim-events` and metrics to `sim-telemetry`, with Pydantic models that fix the fields and types of the events. Needs a broker: `odctl up kafka-lite`. Runs until interrupted with Ctrl + C. Set EXAMPLE_UNTIL to a number of simulation seconds to end the run at that time instead. """ import logging import os import time from pydantic import BaseModel from desflow import ( KafkaAdminConnector, KafkaEgress, KafkaIngress, SimulationContext, ) logging.basicConfig( level=logging.INFO, format="%(levelname)s [%(asctime)s] %(name)s: %(message)s" ) logger = logging.getLogger("kafka_example") # ========================================== # 1. Event Payload Model # ========================================== class TaskEvent(BaseModel): """The fields and types of the finished event. Pydantic checks them when the model is built, before the event is sent to Kafka. """ path_id: str sim_id: str service: str status: str BOOTSTRAP_SERVERS = os.getenv("KAFKA_BOOTSTRAP_SERVERS", "127.0.0.1:9092") # The simulation time, in seconds, at which the run ends. # When EXAMPLE_UNTIL is not set, the run goes on until Ctrl + C. EXAMPLE_UNTIL = float(os.getenv("EXAMPLE_UNTIL") or 0) or None # ========================================== # 2. Infrastructure Builder # ========================================== app = ( SimulationContext(sim_id="Shop", factor=1.0, random_seed=42) .add_ingress(KafkaIngress(topic="sim-config", bootstrap_servers=BOOTSTRAP_SERVERS)) .add_egress( KafkaEgress( event_topic="sim-events", telemetry_topic="sim-telemetry", bootstrap_servers=BOOTSTRAP_SERVERS, ) ) .add_resource("packers", current_cap=1, max_cap=10) .add_service("packing", dist="normal", mean=3.0, std=0.5) .add_arrival("orders", dist="exponential", rate=1.0) # The packers' readings every 2 seconds, which kafka_dashboard.py shows .with_stats("minimal", interval=2.0) ) # ========================================== # 3. Simulation Logic # ========================================== @app.task(service_id="packing", resource_id="packers") def pack_order(task_id: int, context): """ The @task decorator requests the resource and publishes the 'queued' and 'started' events. The function adds its own logic and returns the finished payload. """ logger.info(f"Task {task_id} started at sim time: {context.env.now:.2f}s") # The payload of the finished event, from the Pydantic model return TaskEvent( path_id="Shop.service.packing", sim_id="Shop", service="packing", status="finished", ).model_dump(mode="json") @app.arrival_loop("orders") def arrival_generator(context): task_id = 0 while True: entity = yield context.wait_for_arrival("orders") context.spawn(pack_order(task_id, context, entity=entity)) task_id += 1 # ========================================== # 4. Execution # ========================================== def run(): TOPICS_CONFIG = [ {"name": "sim-config", "partitions": 1}, {"name": "sim-telemetry", "partitions": 1}, {"name": "sim-events", "partitions": 1}, ] logger.info(f"Connecting to Kafka at {BOOTSTRAP_SERVERS}...") try: admin = KafkaAdminConnector(bootstrap_servers=BOOTSTRAP_SERVERS, max_tasks=100) admin.create_topics(topics_config=TOPICS_CONFIG) time.sleep(2) except Exception as e: logger.warning(f"Could not explicitly create topics: {e}") print("Simulation started.") print(" - Listen to 'sim-telemetry' for system vitals.") print(" - Listen to 'sim-events' for task lifecycles.") print(" - Send to 'sim-config' to update parameters.") app.run(until=EXAMPLE_UNTIL) # Starts the clock and orchestrates all connectors if __name__ == "__main__": run() ``` This script connects the simulation to Kafka topics and uses Pydantic models to fix the fields and types of the events. Scripts live in the [`examples/` folder](https://github.com/jaehyeon-kim/desflow/tree/v1.3.0/examples) of the repository, and the label on the block below is this one's path there. ```python """Kafka Digital Twin, low-level API. The low-level version of `builder/kafka_example.py`, a shop packing orders, with the environment, registry and connectors wired by hand. Like the builder version, it creates its topics first with `KafkaAdminConnector`. Needs a broker: `odctl up kafka-lite`. Runs until interrupted with Ctrl + C. Set EXAMPLE_UNTIL to a number of simulation seconds to end the run at that time instead. """ import logging import os import time import numpy as np from pydantic import BaseModel from desflow import ( CapacityConfig, DistributionConfig, DynamicRealtimeEnvironment, DynamicResource, KafkaAdminConnector, KafkaEgress, KafkaIngress, Sampler, SimParameter, ) logging.basicConfig( level=logging.INFO, format="%(levelname)s [%(asctime)s] %(name)s: %(message)s" ) logger = logging.getLogger("kafka_example") BOOTSTRAP_SERVERS = os.getenv("KAFKA_BOOTSTRAP_SERVERS", "127.0.0.1:9092") # The simulation time, in seconds, at which the run ends. # When EXAMPLE_UNTIL is not set, the run goes on until Ctrl + C. EXAMPLE_UNTIL = float(os.getenv("EXAMPLE_UNTIL") or 0) or None # ========================================== # 1. Event Payload Model # ========================================== class TaskEvent(BaseModel): """The fields and types of each lifecycle event. env.publish_event() takes this Pydantic model in place of a dict, and turns it into a dict. KafkaEgress serializes that dict, to JSON or to Avro. """ path_id: str sim_id: str service: str status: str # ========================================== # 2. Initial System State # ========================================== PARAMS = SimParameter( sim_id="Shop", arrival={"orders": DistributionConfig(dist="exponential", rate=1.0)}, # 1 a second service={"packing": DistributionConfig(dist="normal", mean=3.0, std=0.5)}, resources={"packers": CapacityConfig(current_cap=1, max_cap=10)}, ) # ========================================== # 3. Simulation Logic # ========================================== def pack_order(env, sampler, packers, key, task_id): """Publishes a Pydantic model instead of a dict for each lifecycle event.""" path_id = "Shop.service.packing" env.publish_event( key, TaskEvent(path_id=path_id, sim_id="Shop", service="packing", status="queued"), task="pack_order", instance=task_id, ) env.stats.task_queued("pack_order", task_id) # counted as in progress with packers.request() as req: yield req logger.info(f"Task {task_id} started at sim time: {env.now:.2f}s") env.publish_event( key, TaskEvent( path_id=path_id, sim_id="Shop", service="packing", status="started" ), task="pack_order", instance=task_id, ) env.stats.task_started("pack_order", task_id) # Use the latest service config from the registry yield env.timeout(sampler.sample(env.registry.get_config(path_id))) env.publish_event( key, TaskEvent( path_id=path_id, sim_id="Shop", service="packing", status="finished" ), task="pack_order", instance=task_id, ) env.stats.task_finished("pack_order", task_id) def arrival_generator(env, sampler, packers): gap = env.registry.get_config("Shop.arrival.orders") task_id = 0 while True: yield env.timeout(sampler.sample(gap)) env.process(pack_order(env, sampler, packers, f"orders-{task_id + 1}", task_id)) task_id += 1 # ========================================== # 4. Execution # ========================================== def run(): TOPICS_CONFIG = [ {"name": "sim-config", "partitions": 1}, {"name": "sim-telemetry", "partitions": 1}, {"name": "sim-events", "partitions": 1}, ] logger.info(f"Connecting to Kafka at {BOOTSTRAP_SERVERS}...") admin_connector = KafkaAdminConnector( bootstrap_servers=BOOTSTRAP_SERVERS, max_tasks=100 ) admin_connector.create_topics(topics_config=TOPICS_CONFIG) time.sleep(2) # A secured cluster needs more keyword arguments, such as security_protocol="SASL_SSL" ingress = KafkaIngress(topic="sim-config", bootstrap_servers=BOOTSTRAP_SERVERS) # KafkaEgress uses JsonSerializer by default. To write Avro instead: # from desflow.connectors.egress.kafka import ConfluentAvroSerializer # avro_serializer = ConfluentAvroSerializer( # registry_url="http://127.0.0.1:8081", schema_str=AVRO_SCHEMA # ) # Then pass: topic_serializers={"sim-events": avro_serializer} # Generate AVRO_SCHEMA from AvroBaseModel rather than a plain Pydantic model; # see Use Avro and Pydantic. TaskEvent above has no .avro_schema(). egress = KafkaEgress( telemetry_topic="sim-telemetry", event_topic="sim-events", bootstrap_servers=BOOTSTRAP_SERVERS, ) env = DynamicRealtimeEnvironment(factor=1.0, strict=False) env.registry.register_sim_parameter(PARAMS) env.setup_ingress([ingress]) env.setup_egress([egress]) # The packers' readings every 2 seconds, which kafka_dashboard.py shows env.setup_stats("Shop", "minimal", interval=2.0) packers = DynamicResource(env, "Shop", "packers") sampler = Sampler(rng=np.random.default_rng(42)) env.process(arrival_generator(env, sampler, packers)) print("Simulation started.") print(" - Listen to 'sim-telemetry' for system vitals.") print(" - Listen to 'sim-events' for task lifecycles.") print(" - Send to 'sim-config' to update parameters.") try: env.run(until=EXAMPLE_UNTIL) except KeyboardInterrupt: logger.info("Simulation interrupted by user.") finally: env.teardown() if __name__ == "__main__": run() ``` # Fast-Forward to Parquet This example generates a week of a shop's orders at `factor=0.0` and writes them to Parquet files, on the local disk or in S3-compatible storage. [Write to Cloud Storage](https://jaehyeon.me/desflow/latest/how-to/storage-and-tables/cloud-storage/index.md) shows Amazon S3, Google Cloud Storage and Azure Blob Storage. Each tab shows the example written one way: as a YAML blueprint, with the builder API, or with the low-level API. [Ways to write a simulation](https://jaehyeon.me/desflow/latest/user-guide/writing-a-model/index.md) compares the three. desflow is built for real-time digital twins, but the same model can also run faster than real time. With `factor` set to 0 the clock does not wait for the wall clock, and `logical_start_time` puts the week before now, so the records are stamped as history. Look for the Parquet files the run writes, one per batch, with one row for each lifecycle event. ______________________________________________________________________ ## Before You Start The example needs only desflow, which each Quick Start below installs, and no other service. With `PARQUET_FILESYSTEM=s3` it writes to an object store instead, which needs Docker and the odctl profile `storage`. [Services for the Examples](https://jaehyeon.me/desflow/latest/gallery/#services-for-the-examples) lists the services the other examples need. ______________________________________________________________________ ## Steps ### Run It This example builds the simulation of the builder example in the Builder tab from a YAML blueprint, with no Python. With `factor: 0.0` the clock is detached from the wall clock, so a week of shop orders is written to Parquet as fast as the machine allows. **Quick Start** `desflow examples get` downloads the example at the release you install, into a folder of its own. Pick uv or pip: ```bash # 1. Install uv tool install "desflow[parquet]" # 2. Download the example desflow examples get parquet --api yaml cd parquet/yaml # 3. Find the bottleneck, with no run desflow explain parquet.yaml # 4. Run it desflow run parquet.yaml ``` ```bash # 1. Install pip install "desflow[parquet]" # 2. Download the example desflow examples get parquet --api yaml cd parquet/yaml # 3. Find the bottleneck, with no run desflow explain parquet.yaml # 4. Run it desflow run parquet.yaml ``` **What It Does** The run writes each batch as a Parquet file of its own, such as `data/events_1a2b3c4d.parquet`, and ends on its own. `default_path` is a file name prefix, not a folder. [Egress](https://jaehyeon.me/desflow/latest/user-guide/live-runs-and-connectors/egress/#parquet-and-json-lines) explains the file names and how to read the files back as one table. A second run adds its files beside the first run's, so delete `data/` before running again, or set `DEST_PATH` to a new folder. On a laptop, one run of a week of simulated time takes about 20 seconds. It writes 726 files with 3.6 million rows in all, one row per lifecycle event. Without a router, the egress drops telemetry and writes each event as one flat row, so the columns are `stream_type`, `sim_ts`, `timestamp`, `key`, `task`, `instance`, `path_id` and `status`. `logical_start_time: -7d` stamps the week as history that ends now. To write to S3 instead, install `odctl` (`uv tool install "odctl>=1.0,<2"` or `pip install "odctl>=1.0,<2"`), start the object store, and set these variables before the run command. All three versions read the same ones. The files are written under the `odctl-dev/history/` prefix, which you can browse at . ```bash odctl up storage # Write the Parquet files to the S3 store that odctl started export PARQUET_FILESYSTEM=s3 DEST_PATH=odctl-dev/history S3_ENDPOINT=http://127.0.0.1:8333 \ S3_ACCESS_KEY=user S3_SECRET_KEY=password ``` This version builds the simulation with the builder API (`SimulationContext`) and writes with `ParquetStorageEgress`. **Quick Start** `desflow examples get` downloads the example at the release you install, into a folder of its own. Pick uv or pip: ```bash # 1. Install uv tool install "desflow[parquet]" # 2. Download the example desflow examples get parquet --api builder cd parquet/builder # 3. Run it uv run --no-project --with "desflow[parquet]" parquet_example.py ``` ```bash # 1. Install pip install "desflow[parquet]" # 2. Download the example desflow examples get parquet --api builder cd parquet/builder # 3. Run it python parquet_example.py ``` To write to S3 instead, install `odctl` (`uv tool install "odctl>=1.0,<2"` or `pip install "odctl>=1.0,<2"`), start the object store, and set these variables before the run command. All three versions read the same ones. The files are written under the `odctl-dev/history/` prefix, which you can browse at . ```bash odctl up storage # Write the Parquet files to the S3 store that odctl started export PARQUET_FILESYSTEM=s3 DEST_PATH=odctl-dev/history S3_ENDPOINT=http://127.0.0.1:8333 \ S3_ACCESS_KEY=user S3_SECRET_KEY=password ``` This version wires the simulation by hand on `DynamicRealtimeEnvironment`, the low-level API, and writes with `ParquetStorageEgress`. **Quick Start** `desflow examples get` downloads the example at the release you install, into a folder of its own. Pick uv or pip: ```bash # 1. Install uv tool install "desflow[parquet]" # 2. Download the example desflow examples get parquet --api low-level cd parquet/low-level # 3. Run it uv run --no-project --with "desflow[parquet]" parquet_example.py ``` ```bash # 1. Install pip install "desflow[parquet]" # 2. Download the example desflow examples get parquet --api low-level cd parquet/low-level # 3. Run it python parquet_example.py ``` To write to S3 instead, install `odctl` (`uv tool install "odctl>=1.0,<2"` or `pip install "odctl>=1.0,<2"`), start the object store, and set these variables before the run command. All three versions read the same ones. The files are written under the `odctl-dev/history/` prefix, which you can browse at . ```bash odctl up storage # Write the Parquet files to the S3 store that odctl started export PARQUET_FILESYSTEM=s3 DEST_PATH=odctl-dev/history S3_ENDPOINT=http://127.0.0.1:8333 \ S3_ACCESS_KEY=user S3_SECRET_KEY=password ``` ______________________________________________________________________ ## Check the Result The three tabs write the same records, which [a test](https://github.com/jaehyeon-kim/desflow/blob/v1.3.0/tests/docs/test_example_twins.py) checks by running each version unpaced. A real run writes them as rows of Parquet files under `data/`. From the folder the Quick Start used, count the rows in those files: ```bash uv run --no-project --with "desflow[parquet]" python -c "import pyarrow.dataset as ds; print(ds.dataset('data', format='parquet').count_rows())" ``` ```bash python -c "import pyarrow.dataset as ds; print(ds.dataset('data', format='parquet').count_rows())" ``` It prints `3627756`, one row per lifecycle event of the week, and `ls data | wc -l` prints `726`, the number of files. With the S3 variables set, the files are under `odctl-dev/history/` in the object store instead. Count them there with this command, which uses the same credentials as the variables, and expect the same `3627756`. With uv, start the command with the same `uv run --no-project --with "desflow[parquet]"` prefix: ```bash python -c "import pyarrow.dataset as ds; from pyarrow import fs; s3 = fs.S3FileSystem(endpoint_override='127.0.0.1:8333', scheme='http', access_key='user', secret_key='password'); print(ds.dataset('odctl-dev/history', filesystem=s3, format='parquet').count_rows())" ``` When you have checked the result, delete `data/`. If you started the object store, stop it: ```bash odctl down storage --volumes ``` In `parquet/yaml`, which `desflow examples get parquet --api yaml` creates, `desflow run parquet.yaml --sample 4 --stdout` prints the first four events as JSON lines instead, and writes no file: ```text {"stream_type":"event","sim_ts":0.1570778328234859,"timestamp":"...","key":"orders-1","task":"pack_order","instance":0,"value":{"path_id":"Shop.service.packing","sim_id":"Shop","service":"packing","status":"queued"}} {"stream_type":"event","sim_ts":0.1570778328234859,"timestamp":"...","key":"orders-1","task":"pack_order","instance":0,"value":{"path_id":"Shop.service.packing","sim_id":"Shop","service":"packing","status":"started"}} {"stream_type":"event","sim_ts":1.2335847253047847,"timestamp":"...","key":"orders-2","task":"pack_order","instance":1,"value":{"path_id":"Shop.service.packing","sim_id":"Shop","service":"packing","status":"queued"}} {"stream_type":"event","sim_ts":1.2335847253047847,"timestamp":"...","key":"orders-2","task":"pack_order","instance":1,"value":{"path_id":"Shop.service.packing","sim_id":"Shop","service":"packing","status":"started"}} ``` Each event becomes one row of a file, and the two fields of `value`, `path_id` and `status`, become columns of their own. ______________________________________________________________________ ## Full Files Full files `filesystem` is a mapping. `type` picks the local disk or S3, and the other keys are passed to PyArrow's `S3FileSystem`. A key whose value is empty is left out, so with no variables set the mapping is the local disk. Files live in the [`examples/yaml/` folder](https://github.com/jaehyeon-kim/desflow/tree/v1.3.0/examples/yaml) of the repository, and the label on each block below is its path there. ```yaml # Historical data generation in YAML. # # The YAML version of parquet_example.py, which --api builder downloads. With factor 0 # the clock is detached from the wall clock, so a week of shop orders is written to # Parquet as fast as the machine allows. Without a router, each event is written as # one flat row and telemetry is left out. Each batch is a file of its own, # data/events_<8 hex digits>.parquet. # # Writes to ./data by default. To write to the odctl storage profile instead (odctl # up storage), set PARQUET_FILESYSTEM=s3, DEST_PATH=odctl-dev/history, # S3_ENDPOINT=http://127.0.0.1:8333, S3_ACCESS_KEY=user and S3_SECRET_KEY=password. # Run it from its folder with: desflow run parquet.yaml simulation: sim_id: Shop factor: 0.0 random_seed: 42 # A week before now, so the records are stamped as history. logical_start_time: -7d egress: - type: Parquet config: default_path: ${DEST_PATH:-data}/events.parquet # Empty values are left out, so with no variables set this is the local disk. filesystem: type: ${PARQUET_FILESYSTEM:-local} endpoint_override: ${S3_ENDPOINT:-} access_key: ${S3_ACCESS_KEY:-} secret_key: ${S3_SECRET_KEY:-} batching: {batch_size: 5000, flush_interval: 86400} resources: packers: {current_cap: 4, max_cap: 10} services: packing: {dist: normal, mean: 2.0, std: 0.2} arrivals: orders: {dist: exponential, rate: 2.0, spawn: pack_order} tasks: pack_order: service: packing resource: packers payload: {path_id: Shop.service.packing, status: finished} run: {until: 1 week} ``` This script simulates 7 days of the shop. It flattens the lifecycle events into rows, routes them to one Parquet dataset and writes them as fast as the machine allows. Scripts live in the [`examples/` folder](https://github.com/jaehyeon-kim/desflow/tree/v1.3.0/examples) of the repository, and the label on the block below is this one's path there. ```python """ Historical Data Generation Example. Uses SimulationContext to generate data faster than real time. With `factor=0.0` the SimPy clock is detached from the wall clock, so the shop model generates a week of historical orders as fast as the machine allows, for example as training data for machine learning models. The orders are written to Parquet on disk or S3. """ import logging import os from datetime import datetime, timedelta, timezone from desflow import ParquetStorageEgress, SimulationContext # Logging is configured here rather than in a wrapper, because this script is run # directly. Without it the run prints no INFO log lines, such as its progress # messages. logging.basicConfig( level=logging.INFO, format="%(asctime)s [%(levelname)s] %(name)s: %(message)s", datefmt="%H:%M:%S", ) logger = logging.getLogger(__name__) def create_history_router(base_path: str): """ Router Factory: Generates a router function injected with the correct base path, and flattens nested event payloads for Parquet. """ def history_router(data: dict) -> str | None: if data.get("path_id") == "system.simulation.lag_seconds": return None stream_type = data.get("stream_type") if stream_type == "telemetry": return None # FLATTEN EVENT FOR PARQUET if ( stream_type == "event" and "value" in data and isinstance(data["value"], dict) ): nested_value = data.pop("value") data.update(nested_value) return f"{base_path}/events.parquet" return history_router # ========================================== # 1. DUAL-MODE STORAGE CONFIGURATION # ========================================== # The same variables as yaml/parquet.yaml. Unset, the run writes to data/ on the local # disk. PARQUET_FILESYSTEM=s3 with the S3_* variables writes to S3-compatible storage, # such as SeaweedFS from `odctl up storage`. The egress builds the filesystem from this # mapping and creates the destination folder on its first write; an empty value is # left out, so the PyArrow default applies. base_path = os.getenv("DEST_PATH", "data") filesystem = { "type": os.getenv("PARQUET_FILESYSTEM", "local"), "endpoint_override": os.getenv("S3_ENDPOINT", ""), "access_key": os.getenv("S3_ACCESS_KEY", ""), "secret_key": os.getenv("S3_SECRET_KEY", ""), } router = create_history_router(base_path) # The week of backdating this example exists to demonstrate. It sits at module scope # because the builder below needs it, and the builder has to stay at module scope for # the decorators further down to attach to it. The low-level version computes the same # value inside run(), where it has no such constraint. LOGICAL_START_TIME = datetime.now(timezone.utc) - timedelta(days=7) # ========================================== # 2. Infrastructure Builder # ========================================== app = ( SimulationContext( sim_id="Shop", factor=0.0, random_seed=42, # Without this, the example would log that it backdates a week but stamp every # record from the current clock. logical_start_time=LOGICAL_START_TIME, ) .add_egress(ParquetStorageEgress(path_router=router, filesystem=filesystem)) .with_batching(batch_size=5000, flush_interval=86400) .add_resource("packers", current_cap=4, max_cap=10) .add_service("packing", dist="normal", mean=2.0, std=0.2) .add_arrival("orders", dist="exponential", rate=2.0) ) # ========================================== # 3. Simulation Logic # ========================================== @app.task(service_id="packing", resource_id="packers") def pack_order(task_id: int, context): """ Returns the exact flat dictionary expected by the parquet router to represent the 'finished' state of the lifecycle. """ return {"path_id": "Shop.service.packing", "status": "finished"} @app.arrival_loop("orders") def arrival_generator(context): task_id = 0 while True: entity = yield context.wait_for_arrival("orders") context.spawn(pack_order(task_id, context, entity=entity)) task_id += 1 # ========================================== # 4. Execution # ========================================== def run(): """Generates 1 week of shop orders instantly.""" logger.info( "Generating historical data mimicking start from " f"{LOGICAL_START_TIME.strftime('%Y-%m-%d %H:%M:%S')}" ) logger.info("Fast-forwarding (factor=0.0)...") # The clock detaches and executes 1 week of operations instantaneously app.run(until="1 week") logger.info(f"Data generation complete. Check '{base_path}/' for chunks.") if __name__ == "__main__": run() ``` This script simulates 7 days of the shop. It flattens the lifecycle events into rows, routes them to one Parquet dataset and writes them as fast as the machine allows. Scripts live in the [`examples/` folder](https://github.com/jaehyeon-kim/desflow/tree/v1.3.0/examples) of the repository, and the label on the block below is this one's path there. ```python """Historical data generation, low-level API. The low-level version of `builder/parquet_example.py`. It wires `DynamicRealtimeEnvironment`, the registry and the connectors by hand rather than through the builder, which shows what `SimulationContext` does for you. `factor=0.0` detaches the clock from real time, so seven days of shop orders are generated as fast as the machine allows and written to Parquet. A router keeps the lifecycle events and flattens them into rows. Writes to `data/`, or to S3 with the variables `yaml/parquet.yaml` reads: `PARQUET_FILESYSTEM=s3` and `S3_ENDPOINT`, `S3_ACCESS_KEY`, `S3_SECRET_KEY`. """ import logging import os from datetime import datetime, timedelta, timezone import numpy as np from desflow import ( CapacityConfig, DistributionConfig, DynamicRealtimeEnvironment, DynamicResource, ParquetStorageEgress, Sampler, SimParameter, time_to_seconds, ) logging.basicConfig( level=logging.INFO, format="%(levelname)s [%(asctime)s] %(message)s" ) logger = logging.getLogger("parquet_example") def create_history_router(base_path: str): """ Router Factory: Generates a router function injected with the correct base path, and flattens nested event payloads for Parquet. """ def history_router(data: dict) -> str | None: if data.get("path_id") == "system.simulation.lag_seconds": return None stream_type = data.get("stream_type") if stream_type == "telemetry": return None # FLATTEN EVENT FOR PARQUET # If it's an event and has a nested 'value' dictionary, flatten it if ( stream_type == "event" and "value" in data and isinstance(data["value"], dict) ): # Extract and remove the nested 'value' object nested_value = data.pop("value") # Merge the nested keys (path_id, status) directly into the root dict data.update(nested_value) return f"{base_path}/events.parquet" return history_router # The shop starts with 4 packers and has room for 10. PARAMS = SimParameter( sim_id="Shop", arrival={"orders": DistributionConfig(dist="exponential", rate=2.0)}, service={"packing": DistributionConfig(dist="normal", mean=2.0, std=0.2)}, resources={"packers": CapacityConfig(current_cap=4, max_cap=10)}, ) def pack_order(env, sampler, packers, key, task_id): """What @app.task does: queued, started, the service time, then finished.""" path_id = "Shop.service.packing" env.publish_event( key, { "path_id": path_id, "sim_id": "Shop", "service": "packing", "status": "queued", }, task="pack_order", instance=task_id, ) with packers.request() as req: yield req env.publish_event( key, { "path_id": path_id, "sim_id": "Shop", "service": "packing", "status": "started", }, task="pack_order", instance=task_id, ) yield env.timeout(sampler.sample(env.registry.get_config(path_id))) env.publish_event( key, { "path_id": path_id, "status": "finished", }, task="pack_order", instance=task_id, ) def arrival_generator(env, sampler, packers): gap = env.registry.get_config("Shop.arrival.orders") task_id = 0 while True: yield env.timeout(sampler.sample(gap)) env.process(pack_order(env, sampler, packers, f"orders-{task_id + 1}", task_id)) task_id += 1 def run(): # --------------------------------------------------------- # 1. DUAL-MODE STORAGE CONFIGURATION # --------------------------------------------------------- # The same variables as yaml/parquet.yaml. Unset, the run writes to data/ on the local # disk. PARQUET_FILESYSTEM=s3 with the S3_* variables writes to S3-compatible storage, # such as SeaweedFS from `odctl up storage`. The egress builds the filesystem from this # mapping and creates the destination folder on its first write; an empty value is # left out, so the PyArrow default applies. base_path = os.getenv("DEST_PATH", "data") filesystem = { "type": os.getenv("PARQUET_FILESYSTEM", "local"), "endpoint_override": os.getenv("S3_ENDPOINT", ""), "access_key": os.getenv("S3_ACCESS_KEY", ""), "secret_key": os.getenv("S3_SECRET_KEY", ""), } # --------------------------------------------------------- # 2. SIMULATION SETUP # --------------------------------------------------------- start_time = datetime.now(timezone.utc) - timedelta(days=7) env = DynamicRealtimeEnvironment(factor=0.0, logical_start_time=start_time) env.registry.register_sim_parameter(PARAMS) # Initialize Egress with the dynamic router and conditional filesystem router = create_history_router(base_path) egress = ParquetStorageEgress(path_router=router, filesystem=filesystem) # batch_size=5000 for compression, flush_interval=86400 (1 day in sim time) env.setup_egress([egress], batch_size=5000, flush_interval=86400) packers = DynamicResource(env, "Shop", "packers") sampler = Sampler(rng=np.random.default_rng(42)) env.process(arrival_generator(env, sampler, packers)) run_duration_str = "1 week" run_duration_sec = time_to_seconds(run_duration_str) logger.info( f"Generating historical data from {start_time.strftime('%Y-%m-%d %H:%M:%S')}" ) logger.info("Fast-forwarding (factor=0.0)...") try: env.run(until=run_duration_sec) finally: env.teardown() logger.info(f"Data generation complete. Check '{base_path}/' for chunks.") if __name__ == "__main__": run() ``` # Fast-Forward to Iceberg This example generates a day of a shop's orders at `factor=0.0` and appends them to an Apache Iceberg table through an Iceberg REST catalog. [Write to Iceberg Tables](https://jaehyeon.me/desflow/latest/how-to/storage-and-tables/iceberg-tables/index.md) shows the other catalogs. Each tab shows the example written one way: as a YAML blueprint, with the builder API, or with the low-level API. [Ways to write a simulation](https://jaehyeon.me/desflow/latest/user-guide/writing-a-model/index.md) compares the three. `ParquetStorageEgress` writes files and leaves registering them as a table to you. `IcebergStorageEgress` appends into an Iceberg table instead, so one run ends with a table another engine can query. Look for the day's events as rows of `simulation.events`, and for the few snapshots that hold them. Each flush of the buffer is one Iceberg commit. Every commit writes a manifest, a manifest list and a new `metadata.json`, so query planning slows down as snapshots build up. This example therefore gives the Iceberg egress a large `batch_size` of its own. At `factor=0.0` the buffer is flushed each time it holds 200,000 records, and once more at the end of the run. Each flush adds one snapshot to the table. ______________________________________________________________________ ## Before You Start The example needs Docker and the odctl profile `catalog`. Each Quick Start below starts the profile, and the Check the Result section stops it. [Services for the Examples](https://jaehyeon.me/desflow/latest/gallery/#services-for-the-examples) shows how to install odctl. ______________________________________________________________________ ## Steps ### Run It This example builds the simulation of the builder example in the Builder tab from a YAML blueprint, with no Python. A day of shop orders is generated at `factor: 0.0`, and each flush of the buffer becomes one Iceberg commit. **Quick Start** `desflow examples get` downloads the example at the release you install, into a folder of its own. Pick uv or pip: ```bash # 1. Install uv tool install "desflow[iceberg]" --with-executables-from "odctl>=1.0,<2" # 2. Download the example desflow examples get iceberg --api yaml cd iceberg/yaml # 3. Find the bottleneck, with no run desflow explain iceberg.yaml # 4. Start its service odctl up catalog # 5. Run it desflow run iceberg.yaml ``` ```bash # 1. Install pip install "desflow[iceberg]" "odctl>=1.0,<2" # 2. Download the example desflow examples get iceberg --api yaml cd iceberg/yaml # 3. Find the bottleneck, with no run desflow explain iceberg.yaml # 4. Start its service odctl up catalog # 5. Run it desflow run iceberg.yaml ``` **What It Does** The run appends a day of lifecycle events to the `simulation.events` table and ends on its own. With `batch_size: 200000` on the egress, the buffer is flushed once per 200,000 records, and each flush is one commit. The day therefore lands in a few snapshots. Without a router, each event is written to `default_table` as one flat row, and telemetry is left out. The catalog is contacted on the first write, not when the blueprint is loaded, so a blueprint with a wrong catalog address still loads and fails when the first batch is written. `ICEBERG_URI`, `ICEBERG_WAREHOUSE`, `S3_ENDPOINT`, `S3_ACCESS_KEY`, `S3_SECRET_KEY` and `S3_REGION` override the catalog and credentials. This version builds the simulation with the builder API (`SimulationContext`) and writes with `IcebergStorageEgress`. **Quick Start** `desflow examples get` downloads the example at the release you install, into a folder of its own. Pick uv or pip: ```bash # 1. Install uv tool install "desflow[iceberg]" --with-executables-from "odctl>=1.0,<2" # 2. Download the example desflow examples get iceberg --api builder cd iceberg/builder # 3. Start its service odctl up catalog # 4. Run it uv run --no-project --with "desflow[iceberg]" iceberg_example.py ``` ```bash # 1. Install pip install "desflow[iceberg]" "odctl>=1.0,<2" # 2. Download the example desflow examples get iceberg --api builder cd iceberg/builder # 3. Start its service odctl up catalog # 4. Run it python iceberg_example.py ``` `ICEBERG_URI`, `ICEBERG_WAREHOUSE`, `ICEBERG_NAMESPACE`, `S3_ENDPOINT`, `S3_ACCESS_KEY`, `S3_SECRET_KEY` and `S3_REGION` override the catalog and credentials. A second run appends to the same table rather than replacing it, because `IcebergStorageEgress` appends every record by default. To start again with an empty catalog, stop the service as Check the Result shows and start it again. This version wires the simulation by hand on `DynamicRealtimeEnvironment`, the low-level API, and writes with `IcebergStorageEgress`. **Quick Start** `desflow examples get` downloads the example at the release you install, into a folder of its own. Pick uv or pip: ```bash # 1. Install uv tool install "desflow[iceberg]" --with-executables-from "odctl>=1.0,<2" # 2. Download the example desflow examples get iceberg --api low-level cd iceberg/low-level # 3. Start its service odctl up catalog # 4. Run it uv run --no-project --with "desflow[iceberg]" iceberg_example.py ``` ```bash # 1. Install pip install "desflow[iceberg]" "odctl>=1.0,<2" # 2. Download the example desflow examples get iceberg --api low-level cd iceberg/low-level # 3. Start its service odctl up catalog # 4. Run it python iceberg_example.py ``` `ICEBERG_URI`, `ICEBERG_WAREHOUSE`, `ICEBERG_NAMESPACE`, `S3_ENDPOINT`, `S3_ACCESS_KEY`, `S3_SECRET_KEY` and `S3_REGION` override the catalog and credentials. A second run appends to the same table rather than replacing it, because `IcebergStorageEgress` appends every record by default. To start again with an empty catalog, stop the service as Check the Result shows and start it again. ______________________________________________________________________ ## Check the Result The three tabs write the same records, which [a test](https://github.com/jaehyeon-kim/desflow/blob/v1.3.0/tests/docs/test_example_twins.py) checks by running each version unpaced. A real run appends them as rows of the `simulation.events` table. When the run has ended, leave the service up and read the table back from the catalog, with the same endpoints and credentials as the blueprint: ```bash uv run --no-project --with "desflow[iceberg]" \ python -c " from pyiceberg.catalog import load_catalog catalog = load_catalog( 'odctl', type='rest', uri='http://127.0.0.1:8181', **{'s3.endpoint': 'http://127.0.0.1:8333', 's3.access-key-id': 'user', 's3.secret-access-key': 'password', 's3.region': 'us-east-1'}, ) table = catalog.load_table('simulation.events') print(table.scan().to_arrow().num_rows, len(table.snapshots())) " ``` ```bash python -c " from pyiceberg.catalog import load_catalog catalog = load_catalog( 'odctl', type='rest', uri='http://127.0.0.1:8181', **{'s3.endpoint': 'http://127.0.0.1:8333', 's3.access-key-id': 'user', 's3.secret-access-key': 'password', 's3.region': 'us-east-1'}, ) table = catalog.load_table('simulation.events') print(table.scan().to_arrow().num_rows, len(table.snapshots())) " ``` It prints the number of rows and the number of snapshots. After one run with the seed in the file these are `518773 3`: one row for each lifecycle event of the day, in three snapshots (two flushes of 200,000 records and the final flush). After a second run both numbers grow, because each run appends. When you have checked the result, stop the service: ```bash odctl down catalog --volumes ``` In `iceberg/yaml`, which `desflow examples get iceberg --api yaml` creates, `desflow run iceberg.yaml --sample 4 --stdout` needs no catalog. It prints the first four events as JSON lines instead: ```text {"stream_type":"event","sim_ts":0.1570778328234859,"timestamp":"...","key":"orders-1","task":"pack_order","instance":0,"value":{"path_id":"Shop.service.packing","sim_id":"Shop","service":"packing","status":"queued"}} {"stream_type":"event","sim_ts":0.1570778328234859,"timestamp":"...","key":"orders-1","task":"pack_order","instance":0,"value":{"path_id":"Shop.service.packing","sim_id":"Shop","service":"packing","status":"started"}} {"stream_type":"event","sim_ts":1.2335847253047847,"timestamp":"...","key":"orders-2","task":"pack_order","instance":1,"value":{"path_id":"Shop.service.packing","sim_id":"Shop","service":"packing","status":"queued"}} {"stream_type":"event","sim_ts":1.2335847253047847,"timestamp":"...","key":"orders-2","task":"pack_order","instance":1,"value":{"path_id":"Shop.service.packing","sim_id":"Shop","service":"packing","status":"started"}} ``` Each event becomes one row of the table, and the two fields of `value`, `path_id` and `status`, become columns of their own. ______________________________________________________________________ ## Full Files Full files `catalog` is a mapping of PyIceberg catalog properties, passed to PyIceberg's `load_catalog`. `schemas` names a type for each column, so `timestamp` is created as a timestamp rather than inferred as a string. The ISO time each record carries is converted to a timestamp before the write. Files live in the [`examples/yaml/` folder](https://github.com/jaehyeon-kim/desflow/tree/v1.3.0/examples/yaml) of the repository, and the label on each block below is its path there. ```yaml # Lakehouse data generation in YAML. # # The YAML version of iceberg_example.py, which --api builder downloads. A day of shop # orders is generated at factor 0, and each flush of the buffer becomes one Iceberg # commit. Without a router, each event is written to default_table as one flat row # and telemetry is left out. The catalog is contacted on the first write. # # Needs the odctl catalog profile: odctl up catalog. ICEBERG_URI, ICEBERG_WAREHOUSE, # S3_ENDPOINT, S3_ACCESS_KEY and S3_SECRET_KEY override the catalog and credentials. # Run it from its folder with: desflow run iceberg.yaml simulation: sim_id: Shop factor: 0.0 random_seed: 42 # A day before now, so the records are stamped as history. logical_start_time: -1d egress: - type: Iceberg config: # PyIceberg catalog properties, passed to load_catalog. catalog: name: odctl type: rest uri: ${ICEBERG_URI:-http://127.0.0.1:8181} warehouse: ${ICEBERG_WAREHOUSE:-s3://warehouse/} s3.endpoint: ${S3_ENDPOINT:-http://127.0.0.1:8333} s3.access-key-id: ${S3_ACCESS_KEY:-user} s3.secret-access-key: ${S3_SECRET_KEY:-password} s3.region: ${S3_REGION:-us-east-1} default_table: simulation.events # Pinned rather than inferred, so timestamp is a timestamp, not a string. schemas: simulation.events: sim_ts: double timestamp: timestamp key: string path_id: string status: string # One commit per flush, sized so a day of events lands in a few snapshots. batch_size: 200000 resources: packers: {current_cap: 4, max_cap: 10} services: packing: {dist: normal, mean: 2.0, std: 0.2} arrivals: orders: {dist: exponential, rate: 2.0, spawn: pack_order} tasks: pack_order: service: packing resource: packers payload: {path_id: Shop.service.packing, status: finished} run: {until: 1 day} ``` This script simulates the shop over a 1-day period. It routes lifecycle events into one Iceberg table. It pins the schema, so the event time is stored as a timestamp. Without the schema, the column would be inferred as a string. Scripts live in the [`examples/` folder](https://github.com/jaehyeon-kim/desflow/tree/v1.3.0/examples) of the repository, and the label on the block below is this one's path there. ```python """ Lakehouse Data Generation Example. The Iceberg version of `builder/parquet_example.py`. The same fast-forward engine, but each flush of the buffer becomes one Iceberg commit rather than one Parquet file, so the run ends with a table another engine can query instead of a folder someone still has to register. Every commit writes a manifest, a manifest list and a new `metadata.json`. `batch_size` on `add_egress` sizes the buffer, so the run produces a handful of snapshots rather than hundreds. Requires the odctl `catalog` profile: `odctl up catalog`. """ import logging import os from datetime import datetime, timedelta, timezone import pyarrow as pa from desflow import IcebergStorageEgress, SimulationContext # Logging is configured here rather than in a wrapper, because this script is run # directly. Without it the run prints no INFO log lines, such as its progress # messages. logging.basicConfig( level=logging.INFO, format="%(asctime)s [%(levelname)s] %(name)s: %(message)s", datefmt="%H:%M:%S", ) logger = logging.getLogger(__name__) NAMESPACE = os.getenv("ICEBERG_NAMESPACE", "simulation") EVENTS_TABLE = f"{NAMESPACE}.events" # Pinned rather than inferred. Inference reads the ISO timestamp the environment # writes as a string, which is not what a consumer of an event table expects. EVENTS_SCHEMA = pa.schema( [ ("sim_ts", pa.float64()), ("timestamp", pa.timestamp("us")), ("key", pa.string()), ("path_id", pa.string()), ("status", pa.string()), ] ) def create_table_router(events_table: str): """ Router Factory: Generates a router returning `namespace.table`, and reshapes each event into the pinned schema. """ def table_router(data: dict) -> str | None: if data.get("path_id") == "system.simulation.lag_seconds": return None if data.get("stream_type") != "event": return None # FLATTEN EVENT INTO THE PINNED COLUMNS nested_value = data.pop("value", None) if isinstance(nested_value, dict): data.update(nested_value) # A pinned timestamp column takes a datetime. PyArrow rejects the ISO string # the environment writes, so the conversion belongs here. data["timestamp"] = datetime.fromisoformat(data["timestamp"]) return events_table return table_router # ========================================== # 1. CATALOG CONFIGURATION # ========================================== # RestCatalog fetches the catalog configuration as it is constructed, so building # the client below contacts the catalog when this module is imported. Creating the # namespace waits longer: the connector does that on its first batch, inside the run. def build_catalog(): """Connects to the Iceberg REST catalog from the odctl `catalog` profile.""" from pyiceberg.catalog.rest import RestCatalog return RestCatalog( "odctl", **{ "uri": os.getenv("ICEBERG_URI", "http://127.0.0.1:8181"), "warehouse": os.getenv("ICEBERG_WAREHOUSE", "s3://warehouse/"), "s3.endpoint": os.getenv("S3_ENDPOINT", "http://127.0.0.1:8333"), "s3.access-key-id": os.getenv("S3_ACCESS_KEY", "user"), "s3.secret-access-key": os.getenv("S3_SECRET_KEY", "password"), "s3.region": os.getenv("S3_REGION", "us-east-1"), }, ) router = create_table_router(EVENTS_TABLE) # The day of backdating this example exists to demonstrate. It sits at module scope # because the builder below needs it, and the builder has to stay at module scope for # the decorators further down to attach to it. LOGICAL_START_TIME = datetime.now(timezone.utc) - timedelta(days=1) # ========================================== # 2. Infrastructure Builder # ========================================== app = ( SimulationContext( sim_id="Shop", factor=0.0, random_seed=42, logical_start_time=LOGICAL_START_TIME, ) .add_egress( IcebergStorageEgress( catalog=build_catalog(), table_router=router, schemas={EVENTS_TABLE: EVENTS_SCHEMA}, ), # One commit per flush. Sized so a day of events lands in a few snapshots. batch_size=200_000, ) .add_resource("packers", current_cap=4, max_cap=10) .add_service("packing", dist="normal", mean=2.0, std=0.2) .add_arrival("orders", dist="exponential", rate=2.0) ) # ========================================== # 3. Simulation Logic # ========================================== @app.task(service_id="packing", resource_id="packers") def pack_order(task_id: int, context): """ Returns the exact flat dictionary expected by the table router to represent the 'finished' state of the lifecycle. """ return {"path_id": "Shop.service.packing", "status": "finished"} @app.arrival_loop("orders") def arrival_generator(context): task_id = 0 while True: entity = yield context.wait_for_arrival("orders") context.spawn(pack_order(task_id, context, entity=entity)) task_id += 1 # ========================================== # 4. Execution # ========================================== def run(): """Generates 1 day of shop orders instantly, into an Iceberg table.""" logger.info( "Generating historical data mimicking start from " f"{LOGICAL_START_TIME.strftime('%Y-%m-%d %H:%M:%S')}" ) logger.info("Fast-forwarding (factor=0.0)...") # The clock detaches and executes 1 day of operations instantaneously app.run(until="1 day") table = build_catalog().load_table(EVENTS_TABLE) logger.info( f"Wrote {table.scan().to_arrow().num_rows} rows to '{EVENTS_TABLE}' " f"in {len(table.metadata.snapshots)} snapshots at {table.location()}" ) if __name__ == "__main__": run() ``` This script simulates the shop over a 1-day period. It routes lifecycle events into one Iceberg table. It pins the schema, so the event time is stored as a timestamp. Without the schema, the column would be inferred as a string. Scripts live in the [`examples/` folder](https://github.com/jaehyeon-kim/desflow/tree/v1.3.0/examples) of the repository, and the label on the block below is this one's path there. ```python """Lakehouse data generation, low-level API. The low-level version of `builder/iceberg_example.py`. It wires `DynamicRealtimeEnvironment`, the registry and the connectors by hand rather than through the builder, which shows what `SimulationContext` does for you. `factor=0.0` detaches the clock from real time, so a day of shop orders is generated as fast as the machine allows and committed into an Iceberg table. Each flush of the buffer is one commit, so `batch_sizes` is what keeps the snapshot count down. Requires the odctl `catalog` profile: `odctl up catalog`. """ import logging import os from datetime import datetime, timedelta, timezone import numpy as np import pyarrow as pa from desflow import ( CapacityConfig, DistributionConfig, DynamicRealtimeEnvironment, DynamicResource, IcebergStorageEgress, Sampler, SimParameter, time_to_seconds, ) logging.basicConfig( level=logging.INFO, format="%(levelname)s [%(asctime)s] %(message)s" ) logger = logging.getLogger("iceberg_example") NAMESPACE = os.getenv("ICEBERG_NAMESPACE", "simulation") EVENTS_TABLE = f"{NAMESPACE}.events" # Pinned rather than inferred. Inference reads the ISO timestamp the environment # writes as a string, which is not what a consumer of an event table expects. EVENTS_SCHEMA = pa.schema( [ ("sim_ts", pa.float64()), ("timestamp", pa.timestamp("us")), ("key", pa.string()), ("path_id", pa.string()), ("status", pa.string()), ] ) def build_catalog(): """Connects to the Iceberg REST catalog from the odctl `catalog` profile.""" from pyiceberg.catalog.rest import RestCatalog return RestCatalog( "odctl", **{ "uri": os.getenv("ICEBERG_URI", "http://127.0.0.1:8181"), "warehouse": os.getenv("ICEBERG_WAREHOUSE", "s3://warehouse/"), "s3.endpoint": os.getenv("S3_ENDPOINT", "http://127.0.0.1:8333"), "s3.access-key-id": os.getenv("S3_ACCESS_KEY", "user"), "s3.secret-access-key": os.getenv("S3_SECRET_KEY", "password"), "s3.region": os.getenv("S3_REGION", "us-east-1"), }, ) def create_table_router(events_table: str): """ Router Factory: Generates a router returning `namespace.table`, and reshapes each event into the pinned schema. """ def table_router(data: dict) -> str | None: if data.get("path_id") == "system.simulation.lag_seconds": return None if data.get("stream_type") != "event": return None # FLATTEN EVENT INTO THE PINNED COLUMNS nested_value = data.pop("value", None) if isinstance(nested_value, dict): data.update(nested_value) # A pinned timestamp column takes a datetime. PyArrow rejects the ISO string # the environment writes, so the conversion belongs here. data["timestamp"] = datetime.fromisoformat(data["timestamp"]) return events_table return table_router # The shop starts with 4 packers and has room for 10. PARAMS = SimParameter( sim_id="Shop", arrival={"orders": DistributionConfig(dist="exponential", rate=2.0)}, service={"packing": DistributionConfig(dist="normal", mean=2.0, std=0.2)}, resources={"packers": CapacityConfig(current_cap=4, max_cap=10)}, ) def pack_order(env, sampler, packers, key, task_id): """What @app.task does: queued, started, the service time, then finished.""" path_id = "Shop.service.packing" env.publish_event( key, { "path_id": path_id, "sim_id": "Shop", "service": "packing", "status": "queued", }, task="pack_order", instance=task_id, ) with packers.request() as req: yield req env.publish_event( key, { "path_id": path_id, "sim_id": "Shop", "service": "packing", "status": "started", }, task="pack_order", instance=task_id, ) yield env.timeout(sampler.sample(env.registry.get_config(path_id))) env.publish_event( key, { "path_id": path_id, "status": "finished", }, task="pack_order", instance=task_id, ) def arrival_generator(env, sampler, packers): gap = env.registry.get_config("Shop.arrival.orders") task_id = 0 while True: yield env.timeout(sampler.sample(gap)) env.process(pack_order(env, sampler, packers, f"orders-{task_id + 1}", task_id)) task_id += 1 def run(): # --------------------------------------------------------- # 1. SIMULATION SETUP # --------------------------------------------------------- start_time = datetime.now(timezone.utc) - timedelta(days=1) env = DynamicRealtimeEnvironment(factor=0.0, logical_start_time=start_time) env.registry.register_sim_parameter(PARAMS) egress = IcebergStorageEgress( catalog=build_catalog(), table_router=create_table_router(EVENTS_TABLE), schemas={EVENTS_TABLE: EVENTS_SCHEMA}, ) # One commit per flush, so a day of events lands in a handful of snapshots. env.setup_egress([egress], batch_sizes=[200_000], flush_interval=86400) packers = DynamicResource(env, "Shop", "packers") sampler = Sampler(rng=np.random.default_rng(42)) env.process(arrival_generator(env, sampler, packers)) run_duration_str = "1 day" run_duration_sec = time_to_seconds(run_duration_str) logger.info( f"Generating historical data from {start_time.strftime('%Y-%m-%d %H:%M:%S')}" ) logger.info("Fast-forwarding (factor=0.0)...") try: env.run(until=run_duration_sec) finally: env.teardown() table = build_catalog().load_table(EVENTS_TABLE) logger.info( f"Wrote {table.scan().to_arrow().num_rows} rows to '{EVENTS_TABLE}' " f"in {len(table.metadata.snapshots)} snapshots at {table.location()}" ) if __name__ == "__main__": run() ``` # PostgreSQL This example models a shop receiving orders. The simulation writes order records to PostgreSQL and reads parameter updates from a PostgreSQL table. Each tab shows the example written one way: as a YAML blueprint, with the builder API, or with the low-level API. [Ways to write a simulation](https://jaehyeon.me/desflow/latest/user-guide/writing-a-model/index.md) compares the three. With `PostgresEgress` in place of the console egress, the simulation runs as a separate data generator. Look for one row in `orders` for each order, and for orders arriving faster after you insert a new rate into `simulation_params`. The egress writes rows into PostgreSQL with asynchronous bulk inserts through `asyncpg`. The connection string names `odctl`, the database that the odctl `postgres` profile creates, with the user `user` and the password `password`. ______________________________________________________________________ ## Before You Start The example needs Docker and the odctl profile `postgres`. Each Quick Start below starts the profile, and the Check the Result section stops it. [Services for the Examples](https://jaehyeon.me/desflow/latest/gallery/#services-for-the-examples) shows how to install odctl. ______________________________________________________________________ ## Steps ### Run It This example builds the simulation of the builder example in the Builder tab from a YAML blueprint, with no Python. Each order is written to `orders`, and `PostgresIngress` polls `simulation_params` for updates. The [Related Records](https://jaehyeon.me/desflow/latest/gallery/simulation-models/advanced-postgres-orders/index.md) example adds random line items in a second table, and keeps its order generator in Python. **Quick Start** `desflow examples get` downloads the example at the release you install, into a folder of its own. Pick uv or pip: ```bash # 1. Install uv tool install "desflow[postgres]" --with-executables-from "odctl>=1.0,<2" # 2. Download the example desflow examples get postgres --api yaml cd postgres/yaml # 3. Start its service odctl up postgres # 4. Run it (Ctrl + C to stop) desflow run postgres.yaml ``` ```bash # 1. Install pip install "desflow[postgres]" "odctl>=1.0,<2" # 2. Download the example desflow examples get postgres --api yaml cd postgres/yaml # 3. Start its service odctl up postgres # 4. Run it (Ctrl + C to stop) desflow run postgres.yaml ``` **What It Does** When the run starts, `PostgresEgress` creates the `orders` table and `PostgresIngress` creates `simulation_params`, if they do not exist. The run then writes one order per arrival until you stop it. The order id is the task id, and the primary key of `orders`. A second run numbers its orders from 0 again. `PostgresEgress` skips each order whose `order_id` is already in the table, so drop the table to write those orders again. This version builds the simulation with the builder API (`SimulationContext`). **Quick Start** `desflow examples get` downloads the example at the release you install, into a folder of its own. Pick uv or pip: ```bash # 1. Install uv tool install "desflow[postgres]" --with-executables-from "odctl>=1.0,<2" # 2. Download the example desflow examples get postgres --api builder cd postgres/builder # 3. Start its service odctl up postgres # 4. Run it (Ctrl + C to stop) uv run --no-project --with "desflow[postgres]" postgres_example.py ``` ```bash # 1. Install pip install "desflow[postgres]" "odctl>=1.0,<2" # 2. Download the example desflow examples get postgres --api builder cd postgres/builder # 3. Start its service odctl up postgres # 4. Run it (Ctrl + C to stop) python postgres_example.py ``` **Writing Rows** `PostgresEgress` creates each table in `tables` when it does not exist, and writes each record as one row. Record fields the table has no column for, such as `sim_ts`, are left out. ```python app = ( SimulationContext(sim_id="Shop", factor=1.0, random_seed=42) .add_ingress(PostgresIngress(DSN, table_name="simulation_params")) .add_egress(PostgresEgress(DSN, tables={"orders": ORDERS})) .add_arrival("orders", dist="exponential", rate=1.0) ) ``` **Generating Orders** `place_order` has no service or resource, so it publishes its payload as soon as the arrival loop spawns it. The task id is the order id: ```python @app.task() def place_order(task_id: int, context): """A task with no service or resource: its payload is published at once.""" return { "order_id": task_id, "customer_id": 42, "total_amount": 59.97, "status": "pending", } @app.arrival_loop("orders") def order_generator(context): task_id = 0 while True: entity = yield context.wait_for_arrival("orders") context.spawn(place_order(task_id, context, entity=entity)) task_id += 1 ``` **Dynamic Parameter Updates (Ingress)** This example also attaches a `PostgresIngress` listening to a `simulation_params` table. While the simulation runs, inserting a row with `path` and `value` into that table changes the parameter, such as the order arrival rate. The simulation reads the new value within its poll interval, which is 2 seconds by default. This version wires the simulation by hand on `DynamicRealtimeEnvironment`, the low-level API. **Quick Start** `desflow examples get` downloads the example at the release you install, into a folder of its own. Pick uv or pip: ```bash # 1. Install uv tool install "desflow[postgres]" --with-executables-from "odctl>=1.0,<2" # 2. Download the example desflow examples get postgres --api low-level cd postgres/low-level # 3. Start its service odctl up postgres # 4. Run it (Ctrl + C to stop) uv run --no-project --with "desflow[postgres]" postgres_example.py ``` ```bash # 1. Install pip install "desflow[postgres]" "odctl>=1.0,<2" # 2. Download the example desflow examples get postgres --api low-level cd postgres/low-level # 3. Start its service odctl up postgres # 4. Run it (Ctrl + C to stop) python postgres_example.py ``` **Writing Rows** `PostgresEgress` creates each table in `tables` when it does not exist, and writes each record as one row. `PostgresIngress` creates the `simulation_params` table it polls: ```python # PostgresEgress creates the orders table, and PostgresIngress creates the # simulation_params table it polls for parameter updates. env.setup_egress([PostgresEgress(DSN, tables={"orders": ORDERS})]) env.setup_ingress([PostgresIngress(DSN, table_name="simulation_params")]) ``` **Generating Orders** For each arriving order, the SimPy process publishes one record under the key the builder's task would use. The task id is the order id: ```python order = { "order_id": task_id, "customer_id": 42, "total_amount": 59.97, "status": "pending", } # The order key, and the task name and instance id the builder adds env.publish_event( f"orders-{task_id + 1}", order, task="place_order", instance=task_id ) ``` **Dynamic Parameter Updates (Ingress)** This example also attaches a `PostgresIngress` listening to a `simulation_params` table. While the simulation runs, inserting a row with `path` and `value` into that table changes the parameter, such as the order arrival rate. The simulation reads the new value within its poll interval, which is 2 seconds by default. ### Change a Parameter Live While the run goes, insert a new arrival rate into `simulation_params` from a second terminal. The command is the same for every form: ```bash # Insert the new arrival rate into simulation_params docker exec -it postgres psql -U user -d odctl -c "INSERT INTO simulation_params (path, value) VALUES ('Shop.arrival.orders.rate', '5.0');" ``` Within the poll interval, 2 seconds by default, the run logs `Ingested parameter update: Shop.arrival.orders.rate = 5.0`, and orders then arrive five times faster. ______________________________________________________________________ ## Check the Result The three tabs write the same records, which [a test](https://github.com/jaehyeon-kim/desflow/blob/v1.3.0/tests/docs/test_example_twins.py) checks by running each version unpaced. A real run writes each order as one row of the `orders` table. Stop the run with Ctrl + C, leave the service up, and read the first three rows back: ```bash docker exec postgres psql -U user -d odctl -c "SELECT order_id, customer_id, total_amount, status, timestamp FROM orders ORDER BY order_id LIMIT 3;" ``` It prints `(3 rows)` with `order_id` 0, 1 and 2, and `customer_id` 42, `total_amount` 59.97 and `status` `pending` in every row. The `timestamp` values are the wall-clock times of your run, the first gap 2.15 seconds and the second 0.05 seconds, because the first two orders are 2.153 simulation seconds apart and the next 0.045. `SELECT count(*) FROM orders` prints the number of orders the run wrote. When you have checked the result, stop the service: ```bash odctl down postgres --volumes ``` In `postgres/yaml`, which `desflow examples get postgres --api yaml` creates, `desflow run postgres.yaml --sample 3 --stdout` needs no database. It prints the first three orders as JSON lines instead: ```text {"stream_type":"event","sim_ts":0.3141556656469718,"timestamp":"...","key":"orders-1","task":"place_order","instance":0,"value":{"customer_id":42,"total_amount":59.97,"status":"pending","order_id":0}} {"stream_type":"event","sim_ts":2.4671694506095694,"timestamp":"...","key":"orders-2","task":"place_order","instance":1,"value":{"customer_id":42,"total_amount":59.97,"status":"pending","order_id":1}} {"stream_type":"event","sim_ts":2.5122243094067938,"timestamp":"...","key":"orders-3","task":"place_order","instance":2,"value":{"customer_id":42,"total_amount":59.97,"status":"pending","order_id":2}} ``` The fields of `value` and the `timestamp` fill the columns of `orders`. The task id is `order_id`, the table's primary key. ______________________________________________________________________ ## Full Files Full files `place_order` has no service or resource, so it publishes its fixed `payload` as soon as an arrival spawns it, with the task id added as `order_id`. `tables` gives the columns and the primary key of each table to create. The `timestamp` column is filled from the time the record carries. Files live in the [`examples/yaml/` folder](https://github.com/jaehyeon-kim/desflow/tree/v1.3.0/examples/yaml) of the repository, and the label on each block below is its path there. ```yaml # Relational output in YAML. # # The YAML version of postgres_example.py, which --api builder downloads: a simulation # that writes order records to one table. Each order spawns place_order, a task with no # service or resource, which publishes its payload at once. PostgresEgress creates # the orders table at start and writes one row per order. PostgresIngress creates # simulation_params and polls it for parameter updates. # # Needs a database: odctl up postgres. Runs until interrupted with Ctrl + C. # Run it from its folder with: desflow run postgres.yaml simulation: {sim_id: Shop, factor: 1.0, random_seed: 42} ingress: - type: Postgres config: connection_dsn: postgresql://user:password@127.0.0.1:5432/odctl table_name: simulation_params egress: - type: Postgres config: connection_dsn: postgresql://user:password@127.0.0.1:5432/odctl tables: orders: columns: order_id: INT customer_id: INT total_amount: REAL status: TEXT timestamp: TIMESTAMP primary_key: order_id arrivals: orders: {dist: exponential, rate: 1.0, spawn: place_order} tasks: place_order: # id_field adds the task id as order_id. timestamp comes from the record. payload: {customer_id: 42, total_amount: 59.97, status: pending} id_field: order_id ``` This script connects the simulation to PostgreSQL, creates the `orders` table and writes a continuous stream of orders. Scripts live in the [`examples/` folder](https://github.com/jaehyeon-kim/desflow/tree/v1.3.0/examples) of the repository, and the label on the block below is this one's path there. ```python """Relational output, builder API. The simulation writes order records to the PostgreSQL table `orders`. `PostgresEgress` creates the table at start and writes one row per order, and `PostgresIngress` creates `simulation_params` and polls it for parameter updates, so inserting a row there changes the arrival rate of a running simulation. Needs a database: `odctl up postgres`. Runs until interrupted with Ctrl + C. Set EXAMPLE_UNTIL to a number of simulation seconds to end the run at that time instead. """ import logging import os from desflow import PostgresEgress, PostgresIngress, SimulationContext logger = logging.getLogger(__name__) # Connection string matching the odctl `postgres` profile DSN = "postgresql://user:password@127.0.0.1:5432/odctl" # The table PostgresEgress creates when it does not exist. timestamp comes from the # record, and the egress converts its ISO string for the TIMESTAMP column. ORDERS = { "columns": { "order_id": "INT", "customer_id": "INT", "total_amount": "REAL", "status": "TEXT", "timestamp": "TIMESTAMP", }, "primary_key": "order_id", } app = ( SimulationContext(sim_id="Shop", factor=1.0, random_seed=42) .add_ingress(PostgresIngress(DSN, table_name="simulation_params")) .add_egress(PostgresEgress(DSN, tables={"orders": ORDERS})) .add_arrival("orders", dist="exponential", rate=1.0) ) @app.task() def place_order(task_id: int, context): """A task with no service or resource: its payload is published at once.""" return { "order_id": task_id, "customer_id": 42, "total_amount": 59.97, "status": "pending", } @app.arrival_loop("orders") def order_generator(context): task_id = 0 while True: entity = yield context.wait_for_arrival("orders") context.spawn(place_order(task_id, context, entity=entity)) task_id += 1 # The simulation time, in seconds, at which the run ends. # When EXAMPLE_UNTIL is not set, the run goes on until Ctrl + C. EXAMPLE_UNTIL = float(os.getenv("EXAMPLE_UNTIL") or 0) or None def run(): logger.info("Starting Builder Postgres Demo. Press Ctrl+C to stop...") logger.info( "Test Ingress by running: INSERT INTO simulation_params (path, " "value) VALUES ('Shop.arrival.orders.rate', '5.0');" ) try: app.run(until=EXAMPLE_UNTIL) except KeyboardInterrupt: logger.info("Simulation interrupted by user.") if __name__ == "__main__": logging.basicConfig(level=logging.INFO) run() ``` This script connects the simulation to PostgreSQL, creates the `orders` table and writes a continuous stream of orders. Scripts live in the [`examples/` folder](https://github.com/jaehyeon-kim/desflow/tree/v1.3.0/examples) of the repository, and the label on the block below is this one's path there. ```python """Relational output, low-level API. The low-level version of `builder/postgres_example.py`. The simulation writes order records to the PostgreSQL table `orders`. `PostgresEgress` creates the table at start, and `PostgresIngress` creates `simulation_params` and polls it for parameter updates. Needs a database: `odctl up postgres`. Runs until interrupted with Ctrl + C. Set EXAMPLE_UNTIL to a number of simulation seconds to end the run at that time instead. """ import logging import os import numpy as np from desflow import ( DistributionConfig, DynamicRealtimeEnvironment, PostgresEgress, PostgresIngress, Sampler, SimParameter, ) logger = logging.getLogger("postgres_example") # Connection string matching the odctl `postgres` profile DSN = "postgresql://user:password@127.0.0.1:5432/odctl" # The table PostgresEgress creates when it does not exist. timestamp comes from the # record, and the egress converts its ISO string for the TIMESTAMP column. ORDERS = { "columns": { "order_id": "INT", "customer_id": "INT", "total_amount": "REAL", "status": "TEXT", "timestamp": "TIMESTAMP", }, "primary_key": "order_id", } PARAMS = SimParameter( sim_id="Shop", arrival={"orders": DistributionConfig(dist="exponential", rate=1.0)}, ) def order_generator(env, sampler): """Publishes one order per arrival, as the builder's task with no service does.""" gap = env.registry.get_config("Shop.arrival.orders") task_id = 0 while True: yield env.timeout(sampler.sample(gap)) order = { "order_id": task_id, "customer_id": 42, "total_amount": 59.97, "status": "pending", } # The order key, and the task name and instance id the builder adds env.publish_event( f"orders-{task_id + 1}", order, task="place_order", instance=task_id ) task_id += 1 # The simulation time, in seconds, at which the run ends. # When EXAMPLE_UNTIL is not set, the run goes on until Ctrl + C. EXAMPLE_UNTIL = float(os.getenv("EXAMPLE_UNTIL") or 0) or None def run(): env = DynamicRealtimeEnvironment(factor=1.0, strict=False) env.registry.register_sim_parameter(PARAMS) # PostgresEgress creates the orders table, and PostgresIngress creates the # simulation_params table it polls for parameter updates. env.setup_egress([PostgresEgress(DSN, tables={"orders": ORDERS})]) env.setup_ingress([PostgresIngress(DSN, table_name="simulation_params")]) sampler = Sampler(rng=np.random.default_rng(42)) env.process(order_generator(env, sampler)) logger.info("Starting Low-level Postgres Demo. Press Ctrl+C to stop...") logger.info( "Test Ingress by running: INSERT INTO simulation_params (path, " "value) VALUES ('Shop.arrival.orders.rate', '5.0');" ) try: env.run(until=EXAMPLE_UNTIL) except KeyboardInterrupt: logger.info("Simulation interrupted by user.") finally: env.teardown() if __name__ == "__main__": logging.basicConfig(level=logging.INFO) run() ``` # Redis This example models a shop receiving orders. The simulation writes each order to a Redis Stream as it is placed and reads parameter updates from a Redis Pub/Sub channel. Each tab shows the example written one way: as a YAML blueprint, with the builder API, or with the low-level API. [Ways to write a simulation](https://jaehyeon.me/desflow/latest/user-guide/writing-a-model/index.md) compares the three. Look for one entry in the `order_events` stream for each order. After you publish a new arrival rate to `simulation_params`, the stream grows faster. ______________________________________________________________________ ## Before You Start The example needs Docker and the odctl profile `valkey`. Each Quick Start below starts the profile, and the Check the Result section stops it. [Services for the Examples](https://jaehyeon.me/desflow/latest/gallery/#services-for-the-examples) shows how to install odctl. ______________________________________________________________________ ## Steps ### Run It This example builds the simulation of the builder example in the Builder tab from a YAML blueprint, with no Python. `RedisEgress` writes order records to the `order_events` stream, named by each record's `__stream__` key. `RedisIngress` subscribes to the `simulation_params` channel. **Quick Start** `desflow examples get` downloads the example at the release you install, into a folder of its own. Pick uv or pip: ```bash # 1. Install uv tool install "desflow[redis]" --with-executables-from "odctl>=1.0,<2" # 2. Download the example desflow examples get redis --api yaml cd redis/yaml # 3. Start its service odctl up valkey # 4. Run it (Ctrl + C to stop) desflow run redis.yaml ``` ```bash # 1. Install pip install "desflow[redis]" "odctl>=1.0,<2" # 2. Download the example desflow examples get redis --api yaml cd redis/yaml # 3. Start its service odctl up valkey # 4. Run it (Ctrl + C to stop) desflow run redis.yaml ``` **What It Does** The run writes order records to the `order_events` stream, and the lag telemetry to `events`, until you stop it. This version builds the simulation with the builder API (`SimulationContext`). With `RedisIngress` and `RedisEgress`, the simulation reads parameter updates through Pub/Sub and writes events and telemetry to Redis Streams. **Streaming to Redis** `RedisEgress` writes each record to a Redis Stream with `XADD`. Its default stream is the one named in the constructor, `events` in this example. A `__stream__` key in a record picks another. ```python app = ( SimulationContext(sim_id="Shop", factor=1.0, random_seed=42) .add_ingress(RedisIngress(REDIS_URL, channel_name="simulation_params")) .add_egress(RedisEgress(REDIS_URL, stream_name="events")) .add_arrival("orders", dist="exponential", rate=2.0) ) ``` `record_order` has no service or resource, so its record is published as soon as the arrival loop spawns it, one per order: ```python @app.task() def record_order(task_id: int, context): """A task with no service or resource: its payload is published at once.""" return { "__stream__": "order_events", "order_id": task_id, "channel": "web", "status": "placed", } @app.arrival_loop("orders") def order_generator(context): task_id = 0 while True: entity = yield context.wait_for_arrival("orders") context.spawn(record_order(task_id, context, entity=entity)) task_id += 1 ``` Each entry holds one field, `payload`, containing the JSON of the published record. `RedisEgress` reads `__stream__` from inside `value`, where both `context.publish` and `publish_event` put the dictionary you pass them. Order records name `order_events`, so they go there. Every other record goes to `events`, the stream named in the constructor. The key itself is removed before writing, so it does not appear in the stored payload. **Dynamic Parameter Updates (Ingress)** The `RedisIngress` in the builder above listens to the Pub/Sub channel `simulation_params`. While the simulation runs, publishing a JSON message with `path` and `value` to that channel changes the parameter, such as `{"path": "Shop.arrival.orders.rate", "value": 10.0}` to raise the arrival rate. The example logs a `valkey-cli` command that sends it. **Quick Start** `desflow examples get` downloads the example at the release you install, into a folder of its own. Pick uv or pip: ```bash # 1. Install uv tool install "desflow[redis]" --with-executables-from "odctl>=1.0,<2" # 2. Download the example desflow examples get redis --api builder cd redis/builder # 3. Start its service odctl up valkey # 4. Run it (Ctrl + C to stop) uv run --no-project --with "desflow[redis]" redis_example.py ``` ```bash # 1. Install pip install "desflow[redis]" "odctl>=1.0,<2" # 2. Download the example desflow examples get redis --api builder cd redis/builder # 3. Start its service odctl up valkey # 4. Run it (Ctrl + C to stop) python redis_example.py ``` This version wires the simulation by hand on `DynamicRealtimeEnvironment`, the low-level API. This is useful if you are migrating existing SimPy generators and prefer to handle `env.process()` and component registration manually rather than through the builder. **Quick Start** `desflow examples get` downloads the example at the release you install, into a folder of its own. Pick uv or pip: ```bash # 1. Install uv tool install "desflow[redis]" --with-executables-from "odctl>=1.0,<2" # 2. Download the example desflow examples get redis --api low-level cd redis/low-level # 3. Start its service odctl up valkey # 4. Run it (Ctrl + C to stop) uv run --no-project --with "desflow[redis]" redis_example.py ``` ```bash # 1. Install pip install "desflow[redis]" "odctl>=1.0,<2" # 2. Download the example desflow examples get redis --api low-level cd redis/low-level # 3. Start its service odctl up valkey # 4. Run it (Ctrl + C to stop) python redis_example.py ``` ### Change a Parameter Live While the run goes, publish a new arrival rate to `simulation_params` from a second terminal. The command is the same for every form: ```bash # Connect to the Valkey container and publish the parameter update docker exec -it valkey valkey-cli --user user --pass password PUBLISH simulation_params '{"path": "Shop.arrival.orders.rate", "value": 10.0}' ``` `RedisIngress` does not log the message it receives. To see that the update took effect, watch `XLEN order_events`. The arrival rate goes from 2.0 to 10.0 orders a second, so the stream grows about five times faster than before. ______________________________________________________________________ ## Check the Result The three tabs write the same records, which [a test](https://github.com/jaehyeon-kim/desflow/blob/v1.3.0/tests/docs/test_example_twins.py) checks by running each version unpaced. A real run writes each order record to the `order_events` stream. Stop the run with Ctrl + C, leave the service up, and read the stream back: ```bash docker exec valkey valkey-cli --no-auth-warning --user user --pass password XLEN order_events docker exec valkey valkey-cli --no-auth-warning --user user --pass password XRANGE order_events - + COUNT 2 ``` `XLEN` prints one integer, the number of orders the run placed, about two for each second it ran at the starting rate. `XRANGE` prints two entries. Each has an id such as `1793407450263-0`, the field name `payload` and one JSON line, which holds the first two records below: `orders-1` with `order_id` 0 and `orders-2` with `order_id` 1. A second run appends to the same stream. When you have checked the result, stop the service: ```bash odctl down valkey --volumes ``` In `redis/yaml`, which `desflow examples get redis --api yaml` creates, `desflow run redis.yaml --sample 3 --stdout` needs no Valkey. It prints the first three records as JSON lines instead: ```text {"stream_type":"event","sim_ts":0.1570778328234859,"timestamp":"...","key":"orders-1","task":"record_order","instance":0,"value":{"channel":"web","status":"placed","order_id":0}} {"stream_type":"event","sim_ts":1.2335847253047847,"timestamp":"...","key":"orders-2","task":"record_order","instance":1,"value":{"channel":"web","status":"placed","order_id":1}} {"stream_type":"event","sim_ts":1.2561121547033969,"timestamp":"...","key":"orders-3","task":"record_order","instance":2,"value":{"channel":"web","status":"placed","order_id":2}} ``` This command leaves out the `__stream__` key that names the stream, because only a Redis sink uses it. It logs a warning that says so. `RedisEgress` also removes the key before it writes, so the stored records have the same fields. ______________________________________________________________________ ## Full Files Full files `record_order` has no service or resource, so it publishes its fixed `payload` as soon as an arrival spawns it, with the task id added as `order_id`. A mapping payload is a constant, so every order record here has the same `channel` field, `web`. Files live in the [`examples/yaml/` folder](https://github.com/jaehyeon-kim/desflow/tree/v1.3.0/examples/yaml) of the repository, and the label on each block below is its path there. ```yaml # Redis Streams output with live parameter updates, in YAML. # # The YAML version of redis_example.py, which --api builder downloads: a simulation that # records each order as it is placed. Each order spawns record_order, a task with no # service or resource, which publishes its payload at once. RedisEgress writes it to the # order_events stream that the __stream__ key names, while RedisIngress subscribes to # the simulation_params channel. # # Needs Valkey: odctl up valkey. Runs until interrupted with Ctrl + C. # Run it from its folder with: desflow run redis.yaml simulation: {sim_id: Shop, factor: 1.0, random_seed: 42} ingress: - type: Redis config: # The odctl valkey profile disables the unauthenticated default user, so the # URL carries credentials. url: redis://user:password@127.0.0.1:6379/0 channel_name: simulation_params egress: - type: Redis config: {url: redis://user:password@127.0.0.1:6379/0, stream_name: events} arrivals: orders: {dist: exponential, rate: 2.0, spawn: record_order} tasks: record_order: # id_field adds the task id as order_id. payload: {__stream__: order_events, channel: web, status: placed} id_field: order_id ``` Scripts live in the [`examples/` folder](https://github.com/jaehyeon-kim/desflow/tree/v1.3.0/examples) of the repository, and the label on the block below is this one's path there. ```python """Redis Streams output with live parameter updates, builder API. The simulation records each order as it is placed. `RedisEgress` writes the records to the `order_events` Redis Stream, named by each record's `__stream__` key, while `RedisIngress` subscribes to the `simulation_params` channel, so publishing a message to that channel changes the arrival rate of a running simulation. Needs Valkey: `odctl up valkey`. Runs until interrupted with Ctrl + C. Set EXAMPLE_UNTIL to a number of simulation seconds to end the run at that time instead. """ import logging import os from desflow import RedisEgress, RedisIngress, SimulationContext logger = logging.getLogger(__name__) # The odctl `valkey` profile disables the unauthenticated default user, so the # URL carries credentials. A plain Redis without auth takes redis://127.0.0.1:6379/0. REDIS_URL = "redis://user:password@127.0.0.1:6379/0" app = ( SimulationContext(sim_id="Shop", factor=1.0, random_seed=42) .add_ingress(RedisIngress(REDIS_URL, channel_name="simulation_params")) .add_egress(RedisEgress(REDIS_URL, stream_name="events")) .add_arrival("orders", dist="exponential", rate=2.0) ) @app.task() def record_order(task_id: int, context): """A task with no service or resource: its payload is published at once.""" return { "__stream__": "order_events", "order_id": task_id, "channel": "web", "status": "placed", } @app.arrival_loop("orders") def order_generator(context): task_id = 0 while True: entity = yield context.wait_for_arrival("orders") context.spawn(record_order(task_id, context, entity=entity)) task_id += 1 # The simulation time, in seconds, at which the run ends. # When EXAMPLE_UNTIL is not set, the run goes on until Ctrl + C. EXAMPLE_UNTIL = float(os.getenv("EXAMPLE_UNTIL") or 0) or None def run(): logger.info("Starting Builder Redis Demo. Press Ctrl+C to stop...") logger.info( "Test Ingress by running: docker exec -it valkey valkey-cli --user user " "--pass password PUBLISH simulation_params " '\'{"path": "Shop.arrival.orders.rate", "value": 10.0}\'' ) try: app.run(until=EXAMPLE_UNTIL) except KeyboardInterrupt: logger.info("Simulation interrupted by user.") if __name__ == "__main__": logging.basicConfig(level=logging.INFO) run() ``` Scripts live in the [`examples/` folder](https://github.com/jaehyeon-kim/desflow/tree/v1.3.0/examples) of the repository, and the label on the block below is this one's path there. ```python """Redis Streams output with live parameter updates, low-level API. The low-level version of `builder/redis_example.py`. The simulation records each order as it is placed. `RedisEgress` writes the records to the `order_events` stream, named by each record's `__stream__` key, and `RedisIngress` subscribes to the `simulation_params` channel. Needs Valkey: `odctl up valkey`. Runs until interrupted with Ctrl + C. Set EXAMPLE_UNTIL to a number of simulation seconds to end the run at that time instead. """ import logging import os import numpy as np from desflow import ( DistributionConfig, DynamicRealtimeEnvironment, RedisEgress, RedisIngress, Sampler, SimParameter, ) logger = logging.getLogger("redis_example") # The odctl `valkey` profile disables the unauthenticated default user, so the # URL carries credentials. A plain Redis without auth takes redis://127.0.0.1:6379/0. REDIS_URL = "redis://user:password@127.0.0.1:6379/0" PARAMS = SimParameter( sim_id="Shop", arrival={"orders": DistributionConfig(dist="exponential", rate=2.0)}, ) def order_generator(env, sampler): """Publishes one record per order, as the builder's task with no service does.""" gap = env.registry.get_config("Shop.arrival.orders") task_id = 0 while True: yield env.timeout(sampler.sample(gap)) order_event = { "__stream__": "order_events", "order_id": task_id, "channel": "web", "status": "placed", } # The order key, and the task name and instance id the builder adds env.publish_event( f"orders-{task_id + 1}", order_event, task="record_order", instance=task_id ) task_id += 1 # The simulation time, in seconds, at which the run ends. # When EXAMPLE_UNTIL is not set, the run goes on until Ctrl + C. EXAMPLE_UNTIL = float(os.getenv("EXAMPLE_UNTIL") or 0) or None def run(): env = DynamicRealtimeEnvironment(factor=1.0, strict=False) env.registry.register_sim_parameter(PARAMS) env.setup_egress([RedisEgress(REDIS_URL, stream_name="events")]) env.setup_ingress([RedisIngress(REDIS_URL, channel_name="simulation_params")]) sampler = Sampler(rng=np.random.default_rng(42)) env.process(order_generator(env, sampler)) logger.info("Starting Low-level Redis Demo. Press Ctrl+C to stop...") logger.info( "Test Ingress by running: docker exec -it valkey valkey-cli --user user " "--pass password PUBLISH simulation_params " '\'{"path": "Shop.arrival.orders.rate", "value": 10.0}\'' ) try: env.run(until=EXAMPLE_UNTIL) except KeyboardInterrupt: logger.info("Simulation interrupted by user.") finally: env.teardown() if __name__ == "__main__": logging.basicConfig(level=logging.INFO) run() ``` # Parquet History, Kafka Live One run writes ten minutes of backdated history to Parquet. It then publishes to Kafka in real time, and this second part is the live tail. Look for the `Logical clock reached go-live` line in the log, after which records reach Kafka at the pace of the wall clock, and about 10 seconds later for the history's Parquet files in `data/backfill/`. Each tab shows the example written one way. The sections after the tabs show the records, and explain why one run is better than two, how the settings fit together and what to get right. ______________________________________________________________________ ## Before You Start The example needs Docker and the odctl profile `kafka-lite`. Each Quick Start below starts the profile, and the Check the Result section stops it. [Services for the Examples](https://jaehyeon.me/desflow/latest/gallery/#services-for-the-examples) shows how to install odctl. ______________________________________________________________________ ## Steps ### Run It This example builds the simulation of the Builder tab from a YAML blueprint, with no Python. Until `go_live_at` the run is unpaced and writes backdated history to Parquet. From `go_live_at` it is paced in real time and publishes to Kafka. **Quick Start** `desflow examples get` downloads the example at the release you install, into a folder of its own. Pick uv or pip: ```bash # 1. Install uv tool install "desflow[kafka,parquet]" --with-executables-from "odctl>=1.0,<2" # 2. Download the example desflow examples get backfill-live --api yaml cd backfill-live/yaml # 3. Find the bottleneck, with no run desflow explain backfill_live.yaml # 4. Start its service odctl up kafka-lite # 5. Run it desflow run backfill_live.yaml ``` ```bash # 1. Install pip install "desflow[kafka,parquet]" "odctl>=1.0,<2" # 2. Download the example desflow examples get backfill-live --api yaml cd backfill-live/yaml # 3. Find the bottleneck, with no run desflow explain backfill_live.yaml # 4. Start its service odctl up kafka-lite # 5. Run it desflow run backfill_live.yaml ``` **What It Does** Ten minutes of history are generated within the first second. The records stay in the buffer, because they do not reach `batch_size`, and the first interval flush writes them to `data/backfill/` about 10 seconds after go-live. The run publishes to `sim-events` and `sim-telemetry` in real time for 60 seconds and ends. The history folder is created on the first write, and `KafkaEgress` creates the two topics when it starts. `logical_start_time: -10m` and `go_live_at: now` are both read against one moment, the time the file is loaded, so they are exactly ten minutes apart. `until: 11m` then adds one minute of live tail. `when: history` sends the records stamped before `go_live_at` to Parquet, and `when: live` sends the rest to Kafka. [`examples/builder/backfill_live_example.py`](https://github.com/jaehyeon-kim/desflow/blob/v1.3.0/examples/builder/backfill_live_example.py) backdates the clock by ten minutes, generates those ten minutes in the first second, then publishes to Kafka in real time for sixty seconds. The first interval flush writes the history to Parquet about 10 seconds after go-live. `HISTORY_MINUTES` and `LIVE_SECONDS` set the length of the two halves. A day of history (`HISTORY_MINUTES=1440`) is about 128,000 events. **Quick Start** `desflow examples get` downloads the example at the release you install, into a folder of its own. Pick uv or pip: ```bash # 1. Install uv tool install "desflow[kafka,parquet]" --with-executables-from "odctl>=1.0,<2" # 2. Download the example desflow examples get backfill-live --api builder cd backfill-live/builder # 3. Start its service odctl up kafka-lite # 4. Run it uv run --no-project --with "desflow[kafka,parquet]" backfill_live_example.py ``` ```bash # 1. Install pip install "desflow[kafka,parquet]" "odctl>=1.0,<2" # 2. Download the example desflow examples get backfill-live --api builder cd backfill-live/builder # 3. Start its service odctl up kafka-lite # 4. Run it python backfill_live_example.py ``` [`examples/low-level/backfill_live_example.py`](https://github.com/jaehyeon-kim/desflow/blob/v1.3.0/examples/low-level/backfill_live_example.py) wires the same run by hand on `DynamicRealtimeEnvironment`: it backdates the clock by ten minutes, generates those ten minutes in the first second, then publishes to Kafka in real time for sixty seconds. The first interval flush writes the history to Parquet about 10 seconds after go-live. `HISTORY_MINUTES` and `LIVE_SECONDS` set the two halves. **Quick Start** `desflow examples get` downloads the example at the release you install, into a folder of its own. Pick uv or pip: ```bash # 1. Install uv tool install "desflow[kafka,parquet]" --with-executables-from "odctl>=1.0,<2" # 2. Download the example desflow examples get backfill-live --api low-level cd backfill-live/low-level # 3. Start its service odctl up kafka-lite # 4. Run it uv run --no-project --with "desflow[kafka,parquet]" backfill_live_example.py ``` ```bash # 1. Install pip install "desflow[kafka,parquet]" "odctl>=1.0,<2" # 2. Download the example desflow examples get backfill-live --api low-level cd backfill-live/low-level # 3. Start its service odctl up kafka-lite # 4. Run it python backfill_live_example.py ``` ### Get Two Details Right **Predicates compare times read from the timestamp.** A record carries its logical time as an ISO string with its zone offset, such as `+00:00`. `GO_LIVE_AT` is a datetime, and Python cannot compare a string with a datetime, so `record["timestamp"] >= GO_LIVE_AT` raises a `TypeError`. Read the string with `datetime.fromisoformat` and compare the two instants. The comparison is correct whatever zone each side is written in. Cut the go-live instant to milliseconds, as timestamps are, so a record stamped in the go-live millisecond counts as live. Take the instant with `datetime.now(timezone.utc)`: a datetime without an offset is read in the run's `timezone`, else in the zone of `logical_start_time`, else in UTC, not in the machine's local time. ```yaml logical_start_time: -10m # From here the same run is paced at one simulated second per real second. go_live_at: now ``` ```yaml egress: - type: Parquet config: {default_path: data/backfill/events.parquet} # Records stamped before go_live_at. when: history - type: Kafka config: event_topic: sim-events telemetry_topic: sim-telemetry bootstrap_servers: ${KAFKA_BOOTSTRAP_SERVERS:-127.0.0.1:9092} # Records stamped at or after go_live_at. when: live ``` A blueprint needs no predicate. `when: history` and `when: live` compare each record's timestamp with `go_live_at`. ```python GO_LIVE_AT = datetime.now(timezone.utc) # Cut to milliseconds, as timestamps are, so a record stamped in the go-live # millisecond is live GO_LIVE_AT = GO_LIVE_AT.replace(microsecond=GO_LIVE_AT.microsecond // 1000 * 1000) LOGICAL_START_TIME = GO_LIVE_AT - HISTORY # Records carry their logical time as an ISO string with its zone offset, so the # predicates that split the two sinks read it as a time and compare instants. ``` ```python GO_LIVE_AT = datetime.now(timezone.utc) # Cut to milliseconds, as timestamps are, so a record stamped in the go-live # millisecond is live GO_LIVE_AT = GO_LIVE_AT.replace(microsecond=GO_LIVE_AT.microsecond // 1000 * 1000) LOGICAL_START_TIME = GO_LIVE_AT - HISTORY ``` **Before `go_live_at`, only `batch_size` decides when the history is flushed.** `flush_interval` has no effect yet. The interval flush is a simulation process. It starts only if `factor` is non-zero when the egress is set up. This run starts at `factor=0.0`, so before go-live, records leave the buffer only when it fills to `batch_size`. `batch_size` therefore sets the number of Parquet files. The interval flush starts at go-live, so the live tail also flushes every `flush_interval`. `flush_interval` therefore decides how often Kafka receives records. Give each sink its own `batch_size` and `flush_interval` to separate those two jobs: ```yaml - type: Parquet config: {default_path: data/backfill/events.parquet} when: history batch_size: 200000 - type: Kafka config: {bootstrap_servers: 127.0.0.1:9092} when: live batch_size: 500 flush_interval: 1.0 ``` ```python app.add_egress(parquet, when=is_history, batch_size=200_000) app.add_egress(kafka, when=is_live, batch_size=500, flush_interval=1.0) ``` ```python env.setup_egress( [parquet, kafka], predicates=[is_history, is_live], batch_sizes=[200_000, 500], flush_intervals=[None, 1.0], # None: the flush_interval of setup_egress ) ``` ______________________________________________________________________ ## Check the Result The three tabs publish the same records, which [a test](https://github.com/jaehyeon-kim/desflow/blob/v1.3.0/tests/docs/test_example_twins.py) checks by running each version unpaced. A real run writes the records stamped before `go_live_at` to Parquet files under `data/backfill/`, and the rest to `sim-events` and `sim-telemetry`. When the run has ended, leave the service up and count the history rows from the folder the Quick Start used: ```bash uv run --no-project --with "desflow[kafka,parquet]" python -c "import pyarrow.parquet as pq; print(pq.read_table('data/backfill').num_rows)" ``` ```bash python -c "import pyarrow.parquet as pq; print(pq.read_table('data/backfill').num_rows)" ``` It prints `854`, the records of the first ten simulated minutes with the seed in the file. Then read the first live event back from Kafka: ```bash docker exec kafka /opt/kafka/bin/kafka-console-consumer.sh \ --bootstrap-server localhost:9092 --topic sim-events --from-beginning --max-messages 1 ``` It prints one JSON line and `Processed a total of 1 messages`. Its `sim_ts` is a little over 600, the length of the history in simulation seconds, because the live tail starts where the history ends (`orders-285` finished, at `sim_ts` 601.9874667777033). A second run appends to both sinks. When you have checked the result, stop the service: ```bash odctl down kafka-lite --volumes ``` In `backfill-live/yaml`, which `desflow examples get backfill-live --api yaml` creates, `desflow run backfill_live.yaml --sample 4 --stdout` needs no broker. It prints the first four events as JSON lines, unpaced: ```text {"stream_type":"event","sim_ts":0.6283113312939436,"timestamp":"...","key":"orders-1","task":"pack_order","instance":0,"value":{"path_id":"Shop.service.packing","sim_id":"Shop","service":"packing","status":"queued"}} {"stream_type":"event","sim_ts":0.6283113312939436,"timestamp":"...","key":"orders-1","task":"pack_order","instance":0,"value":{"path_id":"Shop.service.packing","sim_id":"Shop","service":"packing","status":"started"}} {"stream_type":"event","sim_ts":2.5998798133404177,"timestamp":"...","key":"orders-1","task":"pack_order","instance":0,"value":{"path_id":"Shop.service.packing","status":"finished"}} {"stream_type":"event","sim_ts":4.934338901219139,"timestamp":"...","key":"orders-2","task":"pack_order","instance":1,"value":{"path_id":"Shop.service.packing","sim_id":"Shop","service":"packing","status":"queued"}} ``` Each `timestamp` is shown as `...`, because it changes with every run. It is the start of the history plus `sim_ts`, so these records are stamped before `go_live_at` and belong to the history. During the live tail the run can look as if it has stopped responding. History is generated within the first second of the run, and its files appear about 10 seconds after go-live. After the `Logical clock reached go-live` line, the run logs at most one more line, the Kafka producer's connection line, until it shuts down. From `go_live_at` the run waits on the wall clock, as any live run does. The `Logical clock reached go-live` line confirms the switch. [Go Live](https://jaehyeon.me/desflow/latest/user-guide/time-and-pacing/clocks-and-pacing/#go-live) explains why one run replaces two and how `logical_start_time`, `go_live_at` and `when` work together. ______________________________________________________________________ ## Full Files Full files Files live in the [`examples/yaml/` folder](https://github.com/jaehyeon-kim/desflow/tree/v1.3.0/examples/yaml) of the repository, and the label on each block below is its path there. ```yaml # Backfill then go live in one run, in YAML. # # The YAML version of backfill_live_example.py, which --api builder downloads. Until # go_live_at the clock is detached from the wall clock, so ten minutes of backdated # shop orders are written to Parquet as fast as the machine allows. From go_live_at # the run is paced at one simulated second per real second, and the same events go # to Kafka for one minute. # # Needs a broker: odctl up kafka-lite. # Run it from its folder with: desflow run backfill_live.yaml simulation: sim_id: Shop # Unpaced to begin with, so the history costs no real time. factor: 0.0 random_seed: 42 logical_start_time: -10m # From here the same run is paced at one simulated second per real second. go_live_at: now egress: - type: Parquet config: {default_path: data/backfill/events.parquet} # Records stamped before go_live_at. when: history - type: Kafka config: event_topic: sim-events telemetry_topic: sim-telemetry bootstrap_servers: ${KAFKA_BOOTSTRAP_SERVERS:-127.0.0.1:9092} # Records stamped at or after go_live_at. when: live # batch_size flushes the history only when 2000 records are waiting. The interval # flush starts at go-live, so it writes what is left about 10 seconds later, and the # live tail also flushes every 10 seconds. batching: {batch_size: 2000, flush_interval: 10.0} resources: packers: {current_cap: 4, max_cap: 10} services: packing: {dist: normal, mean: 2.0, std: 0.2} arrivals: # An order every 2 s on average (rate 0.5) orders: {dist: exponential, rate: 0.5, spawn: pack_order} tasks: pack_order: service: packing resource: packers payload: {path_id: Shop.service.packing, status: finished} # The packers' readings every 30 simulation seconds. stats: {level: minimal, interval: 30} run: # Ten minutes of history, then one minute of live tail. until: 11m ``` Scripts live in the [`examples/` folder](https://github.com/jaehyeon-kim/desflow/tree/v1.3.0/examples) of the repository, and the label on the block below is this one's path there. ```python """ Backfill-then-live Example. One run produces both halves of a tiered dataset. Until `go_live_at` the clock is detached from the wall clock, so ten minutes of backdated shop orders are written to Parquet as fast as the machine allows. From `go_live_at` the same run is paced at one simulated second per real second, and the same events are published to Kafka as they happen. Doing this in two processes would mean repeating the seed and the start instant in both, and keeping them in step by hand. """ import logging import os import time from datetime import datetime, timedelta, timezone from desflow import ( KafkaAdminConnector, KafkaEgress, ParquetStorageEgress, SimulationContext, ) # Logging is configured here rather than in a wrapper, because this script is run # directly. Without it the run prints no INFO log lines, such as its progress # messages. logging.basicConfig( level=logging.INFO, format="%(asctime)s [%(levelname)s] %(name)s: %(message)s", datefmt="%H:%M:%S", ) logger = logging.getLogger(__name__) BOOTSTRAP_SERVERS = os.getenv("KAFKA_BOOTSTRAP_SERVERS", "127.0.0.1:9092") EVENT_TOPIC = "sim-events" TELEMETRY_TOPIC = "sim-telemetry" # How much history to generate, and how long to keep tailing once live. The live half # costs real time, second for second, so it is short by default. HISTORY = timedelta(minutes=float(os.getenv("HISTORY_MINUTES", "10"))) LIVE_SECONDS = float(os.getenv("LIVE_SECONDS", "60")) base_path = os.getenv("DEST_PATH", "data/backfill") # The go-live instant is now, so everything before it is history and everything after # it is the live tail. These sit at module scope because the builder below needs them, # and the builder has to stay at module scope for the decorators to attach to it. GO_LIVE_AT = datetime.now(timezone.utc) # Cut to milliseconds, as timestamps are, so a record stamped in the go-live # millisecond is live GO_LIVE_AT = GO_LIVE_AT.replace(microsecond=GO_LIVE_AT.microsecond // 1000 * 1000) LOGICAL_START_TIME = GO_LIVE_AT - HISTORY # Records carry their logical time as an ISO string with its zone offset, so the # predicates that split the two sinks read it as a time and compare instants. def is_history(record: dict) -> bool: """True for records stamped before the go-live instant.""" return datetime.fromisoformat(record["timestamp"]) < GO_LIVE_AT def is_live(record: dict) -> bool: """True for records stamped at or after the go-live instant.""" return datetime.fromisoformat(record["timestamp"]) >= GO_LIVE_AT def history_router(data: dict) -> str | None: """Drops telemetry and flattens the event payload, as Parquet needs flat rows.""" if data.get("stream_type") != "event": return None if isinstance(data.get("value"), dict): data.update(data.pop("value")) return f"{base_path}/events.parquet" # ========================================== # 1. Infrastructure Builder # ========================================== app = ( SimulationContext( sim_id="Shop", # Unpaced to begin with, so the history costs no real time. factor=0.0, random_seed=42, logical_start_time=LOGICAL_START_TIME, # From here the same run is paced at one simulated second per real second. go_live_at=GO_LIVE_AT, ) .add_egress(ParquetStorageEgress(path_router=history_router), when=is_history) .add_egress( KafkaEgress( event_topic=EVENT_TOPIC, telemetry_topic=TELEMETRY_TOPIC, bootstrap_servers=BOOTSTRAP_SERVERS, ), when=is_live, ) # batch_size flushes the history only when 2000 records are waiting. The interval # flush is a simulation process, started only when factor is non-zero as the egress # is set up, and this run starts at 0.0. The interval flush starts at go-live, so it # writes what is left about 10 seconds later, and the live tail also flushes every # 10 seconds. .with_batching(batch_size=2000, flush_interval=10.0) .add_resource("packers", current_cap=4, max_cap=10) .add_service("packing", dist="normal", mean=2.0, std=0.2) # An order every 2 s on average (rate 0.5) .add_arrival("orders", dist="exponential", rate=0.5) # The packers' readings every 30 simulation seconds .with_stats("minimal", interval=30.0) ) # ========================================== # 2. Simulation Logic # ========================================== @app.task(service_id="packing", resource_id="packers") def pack_order(task_id: int, context): """Returns the flat payload that both sinks receive for a finished task.""" return {"path_id": "Shop.service.packing", "status": "finished"} @app.arrival_loop("orders") def arrival_generator(context): task_id = 0 while True: entity = yield context.wait_for_arrival("orders") context.spawn(pack_order(task_id, context, entity=entity)) task_id += 1 # ========================================== # 3. Execution # ========================================== def run(): """Generates the history instantly, then tails live for LIVE_SECONDS.""" os.makedirs(base_path, exist_ok=True) try: admin = KafkaAdminConnector(bootstrap_servers=BOOTSTRAP_SERVERS, max_tasks=100) admin.create_topics( topics_config=[ {"name": EVENT_TOPIC, "partitions": 1}, {"name": TELEMETRY_TOPIC, "partitions": 1}, ] ) time.sleep(2) except Exception as e: logger.warning(f"Could not explicitly create topics: {e}") logger.info( "Backfilling from %s to %s into '%s/', then tailing live to Kafka for %.0fs.", LOGICAL_START_TIME.strftime("%Y-%m-%d %H:%M:%S"), GO_LIVE_AT.strftime("%Y-%m-%d %H:%M:%S"), base_path, LIVE_SECONDS, ) app.run(until=HISTORY.total_seconds() + LIVE_SECONDS) logger.info("Run complete. History is in '%s/', the tail is in Kafka.", base_path) if __name__ == "__main__": run() ``` Scripts live in the [`examples/` folder](https://github.com/jaehyeon-kim/desflow/tree/v1.3.0/examples) of the repository, and the label on the block below is this one's path there. ```python """ Backfill-then-live Example, low-level API. The low-level version of `builder/backfill_live_example.py`. One run produces both halves of a tiered dataset. Until `go_live_at` the clock is detached from the wall clock, so ten minutes of backdated shop orders are written to Parquet as fast as the machine allows. From `go_live_at` the same run is paced at one simulated second per real second, and the same events are published to Kafka as they happen. """ import logging import os import time from datetime import datetime, timedelta, timezone import numpy as np from desflow import ( CapacityConfig, DistributionConfig, DynamicRealtimeEnvironment, DynamicResource, KafkaAdminConnector, KafkaEgress, ParquetStorageEgress, Sampler, SimParameter, ) logging.basicConfig( level=logging.INFO, format="%(asctime)s [%(levelname)s] %(name)s: %(message)s", datefmt="%H:%M:%S", ) logger = logging.getLogger(__name__) BOOTSTRAP_SERVERS = os.getenv("KAFKA_BOOTSTRAP_SERVERS", "127.0.0.1:9092") EVENT_TOPIC = "sim-events" TELEMETRY_TOPIC = "sim-telemetry" HISTORY = timedelta(minutes=float(os.getenv("HISTORY_MINUTES", "10"))) LIVE_SECONDS = float(os.getenv("LIVE_SECONDS", "60")) base_path = os.getenv("DEST_PATH", "data/backfill") GO_LIVE_AT = datetime.now(timezone.utc) # Cut to milliseconds, as timestamps are, so a record stamped in the go-live # millisecond is live GO_LIVE_AT = GO_LIVE_AT.replace(microsecond=GO_LIVE_AT.microsecond // 1000 * 1000) LOGICAL_START_TIME = GO_LIVE_AT - HISTORY PARAMS = SimParameter( sim_id="Shop", # An order every 2 s on average (rate 0.5) arrival={"orders": DistributionConfig(dist="exponential", rate=0.5)}, service={"packing": DistributionConfig(dist="normal", mean=2.0, std=0.2)}, resources={"packers": CapacityConfig(current_cap=4, max_cap=10)}, ) def is_history(record: dict) -> bool: """True for records stamped before the go-live instant.""" return datetime.fromisoformat(record["timestamp"]) < GO_LIVE_AT def is_live(record: dict) -> bool: """True for records stamped at or after the go-live instant.""" return datetime.fromisoformat(record["timestamp"]) >= GO_LIVE_AT def history_router(data: dict) -> str | None: """Drops telemetry and flattens the event payload, as Parquet needs flat rows.""" if data.get("stream_type") != "event": return None if isinstance(data.get("value"), dict): data.update(data.pop("value")) return f"{base_path}/events.parquet" def pack_order(env, sampler, packers, key, task_id): """What @app.task does: queued, started, the service time, then finished.""" path_id = "Shop.service.packing" env.publish_event( key, { "path_id": path_id, "sim_id": "Shop", "service": "packing", "status": "queued", }, task="pack_order", instance=task_id, ) env.stats.task_queued("pack_order", task_id) # counted as in progress with packers.request() as request: yield request env.publish_event( key, { "path_id": path_id, "sim_id": "Shop", "service": "packing", "status": "started", }, task="pack_order", instance=task_id, ) env.stats.task_started("pack_order", task_id) yield env.timeout(sampler.sample(env.registry.get_config(path_id))) env.publish_event( key, { "path_id": path_id, "status": "finished", }, task="pack_order", instance=task_id, ) env.stats.task_finished("pack_order", task_id) def arrival_generator(env, sampler, packers): gap = env.registry.get_config("Shop.arrival.orders") task_id = 0 while True: yield env.timeout(sampler.sample(gap)) env.process(pack_order(env, sampler, packers, f"orders-{task_id + 1}", task_id)) task_id += 1 def run(): """Generates the history instantly, then tails live for LIVE_SECONDS.""" os.makedirs(base_path, exist_ok=True) try: admin = KafkaAdminConnector(bootstrap_servers=BOOTSTRAP_SERVERS, max_tasks=100) admin.create_topics( topics_config=[ {"name": EVENT_TOPIC, "partitions": 1}, {"name": TELEMETRY_TOPIC, "partitions": 1}, ] ) time.sleep(2) except Exception as e: logger.warning(f"Could not explicitly create topics: {e}") env = DynamicRealtimeEnvironment( factor=0.0, # unpaced, so the history costs no real time logical_start_time=LOGICAL_START_TIME, go_live_at=GO_LIVE_AT, # from here, one simulated second per real second strict=False, # a live run goes on when a slow sink makes it fall behind ) env.registry.register_sim_parameter(PARAMS) env.setup_egress( [ ParquetStorageEgress(path_router=history_router), KafkaEgress( event_topic=EVENT_TOPIC, telemetry_topic=TELEMETRY_TOPIC, bootstrap_servers=BOOTSTRAP_SERVERS, ), ], batch_size=2000, flush_interval=10.0, predicates=[is_history, is_live], # matched to the providers by position ) # The packers' readings every 30 simulation seconds env.setup_stats("Shop", "minimal", interval=30.0) packers = DynamicResource(env, "Shop", "packers") sampler = Sampler(rng=np.random.default_rng(42)) env.process(arrival_generator(env, sampler, packers)) logger.info( "Backfilling from %s to %s into '%s/', then tailing live to Kafka for %.0fs.", LOGICAL_START_TIME.strftime("%Y-%m-%d %H:%M:%S"), GO_LIVE_AT.strftime("%Y-%m-%d %H:%M:%S"), base_path, LIVE_SECONDS, ) try: env.run(until=HISTORY.total_seconds() + LIVE_SECONDS) finally: env.teardown() logger.info("Run complete. History is in '%s/', the tail is in Kafka.", base_path) if __name__ == "__main__": run() ``` ______________________________________________________________________ # Related Records Related records are rows that belong together across tables. Here every customer order has 1 to 5 line items with random products, prices and quantities, and a total computed from them. The orders and their items are written to two PostgreSQL tables, `orders` and `order_items`. Each tab shows the example written one way. In YAML a mapping payload is a constant and cannot hold random values, so the order generator is a Python process in `postgres_orders_logic.py`, referenced with `!python`. [Call Python from YAML](https://jaehyeon.me/desflow/latest/how-to/tools/yaml-advanced/index.md) explains how references work. The connection string names `odctl`, the database that the odctl `postgres` profile creates, with the user `user` and the password `password`. Look for each order's line items in `order_items`, with the same `order_id` as the order's row in `orders`, and for a `total_amount` that is the sum of its items. **What It Does** When the run starts, each `PostgresEgress` creates its table, `orders` or `order_items`, and `PostgresIngress` creates `simulation_params`, if they do not exist. The run then writes orders and their items until you stop it. Both egresses receive every record. Each keeps only the records whose `__table__` key names its table. ______________________________________________________________________ ## Before You Start The example needs Docker and the odctl profile `postgres`. Each Quick Start below starts the profile, and the Check the Result section stops it. [Services for the Examples](https://jaehyeon.me/desflow/latest/gallery/#services-for-the-examples) shows how to install odctl. ______________________________________________________________________ ## Steps ### Run It The generator is listed under `processes` with `kwargs`, so it is called as `order_generator(context, arrival="orders", max_items=5)`. It draws from `context.sampler.rng`, the random number generator seeded by `random_seed`, so a seeded run repeats the same orders. **Quick Start** `desflow examples get` downloads the example at the release you install, into a folder of its own. Pick uv or pip: ```bash # 1. Install uv tool install "desflow[postgres]" --with-executables-from "odctl>=1.0,<2" # 2. Download the example desflow examples get related-records --api yaml cd related-records/yaml # 3. Start its service odctl up postgres # 4. Run it (Ctrl + C to stop) desflow run postgres_orders.yaml ``` ```bash # 1. Install pip install "desflow[postgres]" "odctl>=1.0,<2" # 2. Download the example desflow examples get related-records --api yaml cd related-records/yaml # 3. Start its service odctl up postgres # 4. Run it (Ctrl + C to stop) desflow run postgres_orders.yaml ``` The generator is added with `add_process`, so it is called as `order_generator(context, arrival="orders", max_items=5)`. It draws from `context.sampler.rng`, the random number generator seeded by `random_seed`, so a seeded run repeats the same orders. **Quick Start** `desflow examples get` downloads the example at the release you install, into a folder of its own. Pick uv or pip: ```bash # 1. Install uv tool install "desflow[postgres]" --with-executables-from "odctl>=1.0,<2" # 2. Download the example desflow examples get related-records --api builder cd related-records/builder # 3. Start its service odctl up postgres # 4. Run it (Ctrl + C to stop) uv run --no-project --with "desflow[postgres]" postgres_orders_example.py ``` ```bash # 1. Install pip install "desflow[postgres]" "odctl>=1.0,<2" # 2. Download the example desflow examples get related-records --api builder cd related-records/builder # 3. Start its service odctl up postgres # 4. Run it (Ctrl + C to stop) python postgres_orders_example.py ``` The generator is a SimPy process started with `env.process`. It draws the gaps between orders and the order contents from one `Sampler` seeded with 42, in the same order as the other two versions, so it publishes the same orders. **Quick Start** `desflow examples get` downloads the example at the release you install, into a folder of its own. Pick uv or pip: ```bash # 1. Install uv tool install "desflow[postgres]" --with-executables-from "odctl>=1.0,<2" # 2. Download the example desflow examples get related-records --api low-level cd related-records/low-level # 3. Start its service odctl up postgres # 4. Run it (Ctrl + C to stop) uv run --no-project --with "desflow[postgres]" postgres_orders_example.py ``` ```bash # 1. Install pip install "desflow[postgres]" "odctl>=1.0,<2" # 2. Download the example desflow examples get related-records --api low-level cd related-records/low-level # 3. Start its service odctl up postgres # 4. Run it (Ctrl + C to stop) python postgres_orders_example.py ``` ### Change a Parameter Live While the run goes, raise the arrival rate from a second terminal. The command is the same for every form: ```bash # Change the order arrival rate of the running simulation docker exec -it postgres psql -U user -d odctl -c "INSERT INTO simulation_params (path, value) VALUES ('Shop.arrival.orders.rate', '5.0');" ``` ______________________________________________________________________ ## Check the Result The three tabs write the same records, which [a test](https://github.com/jaehyeon-kim/desflow/blob/v1.3.0/tests/docs/test_example_twins.py) checks by running each version unpaced. A real run writes each order as a row of `orders` and each line item as a row of `order_items`. Stop the run with Ctrl + C, leave the service up, and join the two tables for the first three orders: ```bash docker exec postgres psql -U user -d odctl -c "SELECT o.order_id, o.total_amount, count(i.order_item_id) AS items, round(sum(i.quantity * i.unit_price)::numeric, 2) AS items_total FROM orders o JOIN order_items i USING (order_id) GROUP BY o.order_id, o.total_amount ORDER BY o.order_id LIMIT 3;" ``` It prints `(3 rows)`. In every row `items_total` equals `total_amount` in value, though `total_amount` is a `REAL` column that `psql` prints without trailing zeros: the third row shows `332.3` and `332.30`. `items` is between 1 and 5. The first row is order 1 with 1 item and a total of 82.68, as in the records below; the later rows depend on the seed and the code in `postgres_orders_logic.py`. When you have checked the result, stop the service: ```bash odctl down postgres --volumes ``` In `related-records/yaml`, which `desflow examples get related-records --api yaml` creates, `desflow run postgres_orders.yaml --sample 2 --stdout` needs no database. It prints the first two records as JSON lines instead. They are the one line item of `orders-1`, then the order itself: ```text {"stream_type":"event","sim_ts":0.3141556656469718,"timestamp":"...","key":"orders-1","task":null,"instance":null,"value":{"order_item_id":1,"order_id":1,"product_id":22,"quantity":3,"unit_price":27.56}} {"stream_type":"event","sim_ts":0.3141556656469718,"timestamp":"...","key":"orders-1","task":null,"instance":null,"value":{"order_id":1,"customer_id":86,"total_amount":82.68,"status":"pending"}} ``` This command leaves out the `__table__` key that picks each record's table, because only a PostgreSQL sink uses it. It logs a warning that says so. The order's `total_amount` is its item's `quantity` times its `unit_price`. ______________________________________________________________________ ## Full Files Full files Files live in the [`examples/yaml/` folder](https://github.com/jaehyeon-kim/desflow/tree/v1.3.0/examples/yaml) of the repository, and the label on each block below is its path there. ```yaml # Orders with random line items, in YAML with one Python function. # # Each order arrival builds an order with 1 to 5 items, random prices and # quantities, and a total computed from them. A mapping payload is a constant and # cannot hold random values, so the generator is Python in postgres_orders_logic.py # beside this file, referenced with !python. Everything else is plain YAML. # # Two PostgresEgress instances are attached, one per table, and each keeps only the # records whose __table__ key names its table. Each creates its table at start. # # Needs a database: odctl up postgres. Runs until interrupted with Ctrl + C. # Run it from its folder with: desflow run postgres_orders.yaml simulation: {sim_id: Shop, factor: 1.0, random_seed: 42} ingress: - type: Postgres config: connection_dsn: postgresql://user:password@127.0.0.1:5432/odctl table_name: simulation_params egress: - type: Postgres config: connection_dsn: postgresql://user:password@127.0.0.1:5432/odctl tables: orders: columns: order_id: INT customer_id: INT total_amount: REAL status: TEXT timestamp: TIMESTAMP primary_key: order_id - type: Postgres config: connection_dsn: postgresql://user:password@127.0.0.1:5432/odctl tables: order_items: columns: order_item_id: INT order_id: INT product_id: INT quantity: INT unit_price: REAL primary_key: order_item_id arrivals: # No spawn: the process below waits on this arrival itself. orders: {dist: exponential, rate: 1.0} processes: # Called as order_generator(context, arrival="orders", max_items=5). - function: !python postgres_orders_logic.order_generator kwargs: {arrival: orders, max_items: 5} ``` ```python """Python for postgres_orders.yaml: an order generator with random line items.""" def order_generator(context, arrival: str, max_items: int): """Publishes an order and its items on every arrival. Draws from `context.sampler.rng`, the random number generator seeded by `random_seed`, so a seeded run repeats the same orders. The `__table__` key names the table each record is written to. """ rng = context.sampler.rng order_id = 1 item_id = 1 while True: # The order's key, such as orders-1, is the record key of all its records entity = yield context.wait_for_arrival(arrival) total = 0.0 for _ in range(int(rng.integers(1, max_items + 1))): price = round(float(rng.uniform(10.0, 50.0)), 2) quantity = int(rng.integers(1, 4)) total += price * quantity context.env.publish_event( entity.key, { "__table__": "order_items", "order_item_id": item_id, "order_id": order_id, "product_id": int(rng.integers(1, 51)), "quantity": quantity, "unit_price": price, }, ) item_id += 1 context.env.publish_event( entity.key, { "__table__": "orders", "order_id": order_id, "customer_id": int(rng.integers(1, 101)), "total_amount": round(total, 2), "status": "pending", }, ) order_id += 1 ``` ```python """ Orders with line items, builder API. The builder version of `yaml/advanced/postgres_orders.yaml`. Each order arrival builds an order with 1 to 5 items, random prices and quantities, and a total computed from them. Two PostgresEgress instances are attached, one per table, and each keeps only the records whose `__table__` key names its table. Each creates its table at start. Needs a database: odctl up postgres. Runs until interrupted with Ctrl + C. Set EXAMPLE_UNTIL to a number of simulation seconds to end the run at that time instead. """ import logging import os from desflow import PostgresEgress, PostgresIngress, SimulationContext logging.basicConfig( level=logging.INFO, format="%(levelname)s [%(asctime)s] %(message)s" ) DSN = "postgresql://user:password@127.0.0.1:5432/odctl" ORDERS = { "columns": { "order_id": "INT", "customer_id": "INT", "total_amount": "REAL", "status": "TEXT", "timestamp": "TIMESTAMP", }, "primary_key": "order_id", } ORDER_ITEMS = { "columns": { "order_item_id": "INT", "order_id": "INT", "product_id": "INT", "quantity": "INT", "unit_price": "REAL", }, "primary_key": "order_item_id", } def order_generator(context: SimulationContext, arrival: str, max_items: int): """Publishes an order and its items on every arrival. Draws from `context.sampler.rng`, the random number generator seeded by `random_seed`, so a seeded run repeats the same orders. The `__table__` key names the table each record is written to. """ rng = context.sampler.rng order_id = 1 item_id = 1 while True: # The order's key, such as orders-1, is the record key of all its records entity = yield context.wait_for_arrival(arrival) total = 0.0 for _ in range(int(rng.integers(1, max_items + 1))): price = round(float(rng.uniform(10.0, 50.0)), 2) quantity = int(rng.integers(1, 4)) total += price * quantity context.env.publish_event( entity.key, { "__table__": "order_items", "order_item_id": item_id, "order_id": order_id, "product_id": int(rng.integers(1, 51)), "quantity": quantity, "unit_price": price, }, ) item_id += 1 context.env.publish_event( entity.key, { "__table__": "orders", "order_id": order_id, "customer_id": int(rng.integers(1, 101)), "total_amount": round(total, 2), "status": "pending", }, ) order_id += 1 app = ( SimulationContext(sim_id="Shop", factor=1.0, random_seed=42) .add_ingress(PostgresIngress(DSN, table_name="simulation_params")) .add_egress(PostgresEgress(DSN, tables={"orders": ORDERS})) .add_egress(PostgresEgress(DSN, tables={"order_items": ORDER_ITEMS})) .add_arrival("orders", dist="exponential", rate=1.0) .add_process(order_generator, arrival="orders", max_items=5) ) # The simulation time, in seconds, at which the run ends. # When EXAMPLE_UNTIL is not set, the run goes on until Ctrl + C. EXAMPLE_UNTIL = float(os.getenv("EXAMPLE_UNTIL") or 0) or None if __name__ == "__main__": app.run(until=EXAMPLE_UNTIL) ``` ```python """ Orders with line items, low-level API. The low-level version of `builder/postgres_orders_example.py` and `yaml/advanced/postgres_orders.yaml`. It wires `DynamicRealtimeEnvironment`, the registry and the connectors by hand. With the same seed it publishes the same orders as the other two. Needs a database: odctl up postgres. Runs until interrupted with Ctrl + C. Set EXAMPLE_UNTIL to a number of simulation seconds to end the run at that time instead. """ import logging import os import numpy as np from desflow import ( DistributionConfig, DynamicRealtimeEnvironment, PostgresEgress, PostgresIngress, Sampler, SimParameter, ) logging.basicConfig( level=logging.INFO, format="%(levelname)s [%(asctime)s] %(message)s" ) DSN = "postgresql://user:password@127.0.0.1:5432/odctl" PARAMS = SimParameter( sim_id="Shop", arrival={"orders": DistributionConfig(dist="exponential", rate=1.0)}, ) ORDERS = { "columns": { "order_id": "INT", "customer_id": "INT", "total_amount": "REAL", "status": "TEXT", "timestamp": "TIMESTAMP", }, "primary_key": "order_id", } ORDER_ITEMS = { "columns": { "order_item_id": "INT", "order_id": "INT", "product_id": "INT", "quantity": "INT", "unit_price": "REAL", }, "primary_key": "order_item_id", } def order_generator(env, sampler: Sampler, max_items: int): """Publishes an order and its items on every arrival. The gaps come from the arrival's own random sequence and the order contents from `sampler.rng`, as in the builder version, so the two publish the same records. """ rng = sampler.rng arrival = env.registry.get_config("Shop.arrival.orders") order_id = 1 item_id = 1 while True: yield env.timeout(sampler.sample(arrival)) total = 0.0 for _ in range(int(rng.integers(1, max_items + 1))): price = round(float(rng.uniform(10.0, 50.0)), 2) quantity = int(rng.integers(1, 4)) total += price * quantity env.publish_event( f"orders-{order_id}", { "__table__": "order_items", "order_item_id": item_id, "order_id": order_id, "product_id": int(rng.integers(1, 51)), "quantity": quantity, "unit_price": price, }, ) item_id += 1 env.publish_event( f"orders-{order_id}", { "__table__": "orders", "order_id": order_id, "customer_id": int(rng.integers(1, 101)), "total_amount": round(total, 2), "status": "pending", }, ) order_id += 1 # The simulation time, in seconds, at which the run ends. # When EXAMPLE_UNTIL is not set, the run goes on until Ctrl + C. EXAMPLE_UNTIL = float(os.getenv("EXAMPLE_UNTIL") or 0) or None def run(until=None, factor=1.0): env = DynamicRealtimeEnvironment(factor=factor, strict=False) env.registry.register_sim_parameter(PARAMS) env.setup_ingress([PostgresIngress(DSN, table_name="simulation_params")]) env.setup_egress( [ PostgresEgress(DSN, tables={"orders": ORDERS}), PostgresEgress(DSN, tables={"order_items": ORDER_ITEMS}), ] ) sampler = Sampler(rng=np.random.default_rng(42)) env.process(order_generator(env, sampler, max_items=5)) try: env.run(until=until) finally: env.teardown() if __name__ == "__main__": run(until=EXAMPLE_UNTIL) ``` # Projects Using desflow These public projects generate their data with desflow. The first four are in [benchtop](https://github.com/jaehyeon-kim/benchtop). Each row says what the project does, what desflow simulates there and the desflow requirement in the project's `requirements.txt`. | Project | What it covers | | --------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | [Change Data Capture with Debezium](https://github.com/jaehyeon-kim/benchtop/tree/main/ecommerce-cdc) | every change to a shop's database, captured as it happens with Debezium and Kafka Connect. desflow simulates the shop and writes it to PostgreSQL. It requires `desflow[postgres,kafka]>=0.20.0`. | | [Live Game Leaderboards with Flink SQL](https://github.com/jaehyeon-kim/benchtop/tree/main/game-leaderboard) | live leaderboards for a mobile game, kept up to date by Flink SQL. desflow plays the game in real time, sends each score to Kafka and reads parameter changes from Kafka while it runs. It requires `desflow[kafka,confluent]>=0.20.0`. | | [Live Sales Dashboards](https://github.com/jaehyeon-kim/benchtop/tree/main/live-dashboard) | two dashboards that update themselves as a shop takes orders. desflow runs the shop in real time and writes every row to PostgreSQL. It requires `desflow[postgres]>=0.21.0`. | | [Air Quality Forecasting with a Feature Store](https://github.com/jaehyeon-kim/benchtop/tree/main/air-quality) | an MLOps project that forecasts daily air pollution (PM2.5) for the next seven days from weather forecasts, with a feature store, a monitoring dashboard and a chat assistant. desflow generates the hourly weather forecasts and PM2.5 readings, written to four Iceberg tables. It requires `desflow[iceberg]>=0.20.0`. | | [Agentic Analytics System](https://github.com/jaehyeon-kim/agentic-analytics-system) | conversational analytics over an Iceberg lakehouse, where an agent answers questions through a semantic layer. desflow generates 90 days of an online shop's history (customers, products, orders, order items, payments and returns), unpaced, as Parquet files in S3-compatible storage, which become the Iceberg tables. It requires `desflow[parquet]==0.20.0`. | | [Hot Strip Mill: Real-Time Online Machine Learning and Digital Twin](https://github.com/jaehyeon-kim/oml-digital-twin-hotrolling) | a model of a steel hot strip mill, trained online by a Flink job as the wear on its rolls drifts. desflow runs the mill in real time and sends prediction requests and the measured forces to Kafka. It requires `dynamic-des[kafka,dashboard]==0.12.0`, under desflow's earlier name. | # SimPy and desflow # SimPy and desflow desflow is built on [SimPy](https://simpy.readthedocs.io/), a Python library for discrete-event simulation. SimPy provides the event list, the clock, processes and resources, and desflow keeps all of them. This page teaches the SimPy constructs one at a time, each on the packing shop in plain SimPy with no desflow in it. A low-level desflow model is ordinary SimPy code with a few additions, which [Coming from SimPy](https://jaehyeon.me/desflow/latest/simpy/coming-from-simpy/#what-desflow-changes) lists. The code is plain SimPy 4.1.2, the version desflow is tested against. We confirmed each statement about a construct against SimPy's source in that version (`core.py`, `events.py`, `rt.py` and the `resources` package). Every function below runs as a script in the docs tests, and its output is the one shown. ______________________________________________________________________ ## Environment and the Event List An `Environment` holds the clock, `env.now`, and the event list. The list is ordered by time, then by priority, then by the order in which events were scheduled. Two events at one time therefore run in the order they were scheduled, unless one has the higher priority (`URGENT` is 0 and `NORMAL` is 1, and the lower number runs first). [What Is DES?](https://jaehyeon.me/desflow/latest/learn/what-is-des/index.md) explains why the clock jumps from event to event, and [Run Length](https://jaehyeon.me/desflow/latest/user-guide/time-and-pacing/run-length/index.md) shows how the order matters at the end of a run. `env.timeout(delay)` is an event that SimPy schedules `delay` seconds from now, and a negative delay raises `ValueError`. `env.step()` takes the earliest event, moves the clock to its time and runs the event's callbacks. `env.peek()` gives the time of the next event, or infinity when none is left. `env.run(until=...)` calls `step` until the time or the event you give it. The function below schedules two timeouts in the wrong order and steps through them. ```python def event_list(): """Two events scheduled out of order are processed in time order.""" env = simpy.Environment() env.timeout(2.6) # order 2 arrives env.timeout(1.5) # order 1 is packed seen = [] while env.peek() != math.inf: # peek is the time of the next event seen.append((env.peek(), env.now)) env.step() # take the earliest event, move the clock to its time return seen, env.now ``` Each pair is the time of the next event and the clock before the step. The event at 2.6 was scheduled first, but the list is ordered by time, so the event at 1.5 comes first and the clock ends at 2.6. ```text event list: [(1.5, 0), (2.6, 1.5)], clock at 2.6 ``` In desflow, `env` is a `DynamicRealtimeEnvironment`, which is a SimPy environment with pacing added. In the builder, `env.run(until=...)`, `env.step()` and `env.peek()` are `app.run(until=...)`, `app.step()` and `app.peek()`. In YAML, the end time is `run.until`. ______________________________________________________________________ ## Events and Callbacks An event is something that happens once. It starts pending. It becomes **triggered** when `succeed(value)` or `fail(exception)` is called, which schedules it. It becomes **processed** when the environment takes it from the list and runs its **callbacks**. A callback is a function that takes the event, and callbacks run in the order they were added. A process that yields an event waits on it by adding its own resume function to the callbacks, so one event can wake any number of processes. Calling `succeed` twice raises `RuntimeError`, and a failed event that nothing handles stops the run with its exception. In the shop, several parts of the model wait for an order to be packed. Here a callback and two couriers wait on one event, and the packer triggers it at 1.5 seconds. ```python def events(): """An event is triggered once, and its callbacks and waiting processes run when it is processed.""" env = simpy.Environment() packed = env.event() log = [] packed.callbacks.append( lambda event: log.append(f"callback at {env.now}: {event.value}") ) def courier(name): value = yield packed # every process waiting on the event resumes with its value log.append(f"{name} at {env.now}: {value}") env.process(courier("courier 1")) env.process(courier("courier 2")) def packer(): yield env.timeout(1.5) packed.succeed("order 1") # triggers the event, which schedules it for now env.process(packer()) env.run() return log, (packed.triggered, packed.processed, packed.ok) ``` The callback was added first, so it runs first, and both couriers resume at the same instant with the event's value. The last line shows the three states after the run: `triggered` and `processed` are both true, and `ok` is true because the event succeeded. ```text callback at 1.5: order 1 courier 1 at 1.5: order 1 courier 2 at 1.5: order 1 triggered, processed, ok: (True, True, True) ``` In desflow, a **signal** is an event that tasks wait for and fire, such as a restock. `Signal` is its low-level form, `add_signal` its builder form and `signals:` its YAML form. A signal is one-shot by default, as a SimPy event is, and `once: false` makes it fire again. A task's `listen: {signal: s, on: [...]}` adds callbacks to the next firing of the signal when the task starts, in the order they were added and before waiters added later, as `event.callbacks.append(f)` does. A signal whose firing was processed already takes no callback, which fails the task, as `event.callbacks.append` raises. A flow that wants to keep listening listens again. A failed event that nothing handles stops the run in all three forms, as it does in SimPy. `on_unhandled_failure: continue` publishes a `failed` record and goes on instead. [Failures](https://jaehyeon.me/desflow/latest/user-guide/tasks-and-processes/failures/index.md) explains both. ______________________________________________________________________ ## Processes and Waiting for a Process A **process** is a Python generator that SimPy runs: each `yield` hands SimPy an event, and the process resumes when that event is processed. `env.process(generator)` starts one. The process is itself an event, which triggers when the generator returns, with the return value. So a process can wait for another by yielding it, and it receives the other's return value. If the child raises an exception, the exception is raised in the parent at its `yield`. The shop below takes an order every 2 seconds. Each order starts a `pack` process and waits for it, and `pack` takes 1.5 seconds. ```python def processes(): """A process is a generator; yielding another process waits for it and returns its value.""" env = simpy.Environment() log = [] def pack(order): yield env.timeout(1.5) return f"order {order} packed" def shop(): for order in (1, 2): yield env.timeout(2) # time to the next arrival result = yield env.process(pack(order)) # wait for the child log.append((env.now, result)) env.process(shop()) env.run() return log ``` The first order arrives at 2 and is packed at 3.5. The second arrives 2 seconds after the first was packed, at 5.5, and is packed at 7.0. ```text [(3.5, 'order 1 packed'), (7.0, 'order 2 packed')] ``` In desflow, a task is a process, and `@app.task` and `@app.arrival_loop` write the common ones. A task waits for another task with `wait: {task: ...}` in YAML, `wait={"task": ...}` or `yield context.call(...)` in the builder, and reads the child's last payload as its value. A process you write yourself runs through `add_process`, which is an extension point. ______________________________________________________________________ ## Interrupts `process.interrupt(cause)` raises `simpy.Interrupt` inside the process, at the `yield` where it waits. The cause is any object, and the process reads it as `interrupt.cause`. The interrupt is scheduled as `URGENT`, so it takes effect before any other event at that time. A process that catches the exception may wait again, for the same event or a new one. A process that has ended, or the process itself, cannot be interrupted, and `interrupt` raises `RuntimeError`. Here a packer is interrupted for a break at 1.0 seconds, in the middle of a 1.5 second packing. It works out how much is left, takes the break, and finishes. ```python def interrupts(): """A packer is interrupted at 1.0 s and finds how much of the 1.5 s packing is left.""" env = simpy.Environment() log = [] def packer(): left = 1.5 while left > 0: started = env.now try: yield env.timeout(left) left = 0 except ( simpy.Interrupt ) as interrupt: # raised inside the process, at its yield left -= env.now - started log.append((env.now, interrupt.cause, left)) yield env.timeout(0.5) # the break log.append((env.now, "packed", 0)) process = env.process(packer()) def supervisor(): yield env.timeout(1.0) process.interrupt("break") # the cause is any object env.process(supervisor()) env.run() return log ``` The packer is interrupted at 1.0 with 0.5 seconds left, rests for 0.5, and finishes the rest at 2.0. ```text [(1.0, 'break', 0.5), (2.0, 'packed', 0)] ``` In desflow, `on_interrupt: resume`, `restart` or `abandon` on a task chooses what happens to the work in progress. This code does what `resume` does. `interrupt:` sends an interrupt. [Interruptions](https://jaehyeon.me/desflow/latest/learn/shop-logic/interruptions/index.md) uses all three. ______________________________________________________________________ ## Waiting for One or All `a | b` is an event that triggers when the first of `a` and `b` is processed, and `a & b` is one that triggers when both are. They are the `AnyOf` and `AllOf` classes, and `env.any_of(events)` and `env.all_of(events)` build them from a list. The value is a `ConditionValue`. It holds the events that had been processed when the condition is processed, so `event in result` tells you which ones, and `result.todict()` gives their values. A courier below waits for an order to be packed or for 1 second to pass, whichever is first. Then it waits for the packing and for another 3 seconds. ```python def conditions(): """`|` waits for the first of several events, `&` for all of them.""" env = simpy.Environment() log = [] def courier(): packed = env.timeout(2.0, value="packed") limit = env.timeout(1.0, value="limit") first = yield packed | limit # AnyOf: holds every event processed so far log.append((env.now, packed in first, limit in first)) both = yield packed & env.timeout(3.0) # AllOf: waits for both log.append((env.now, len(both.todict()))) env.process(courier()) env.run() return log ``` At 1.0 the limit was processed and the packing was not, so the courier stopped waiting. The second wait ends at 4.0, when the timeout created at 1.0 triggers, and both events are in its value. ```text [(1.0, False, True), (4.0, 2)] ``` In desflow, `wait: {any: ...}` and `wait: {all: ...}` in YAML and `wait={"any": ...}` in the builder wait on named branches of signals, tasks and timeouts. To wait on a computed list, as `env.all_of(events)` does, `wait` takes `each`, `group` and `branch`: `group` is `all`, `any`, `{at_least: ...}` or `{when: ...}`, and `branch` is the one leaf that each element waits on. [Wait for One or All](https://jaehyeon.me/desflow/latest/how-to/modelling/wait-for-one-or-all/index.md) shows ties, failures and the forms of `each`. ______________________________________________________________________ ## Resources A `Resource(env, capacity)` has `capacity` units, one by default. `request()` returns an event that triggers when a unit is free, and requests are served in the order they arrive. Used in a `with` block, a request is released when the block ends, and a request still waiting at that point is cancelled. `count` is the units in use, `users` the granted requests and `queue` the waiting ones. Three orders arrive at 0 and the shop has one packer. Each waits for the one before it. ```python def resource(): """Three orders at 0 s and one packer: each waits in the queue for the one before.""" env = simpy.Environment() packers = simpy.Resource(env, capacity=1) log = [] def order(name): with packers.request() as request: # leaving the block releases the packer yield request log.append((name, env.now)) yield env.timeout(1.5) for name in "ABC": env.process(order(name)) env.run() return log ``` ```text [('A', 0), ('B', 1.5), ('C', 3.0)] ``` `PriorityResource` takes a `priority` with each request: the lowest number is served first, and requests with the same priority are served in arrival order. In the shop below, the packer is busy with an order at 0. A standard order arrives at 0.5 and an express order at 1.0, and the express order is served first. ```python def priority(): """The packer is busy at 0 s; a lower priority number is served first, ties in arrival order.""" env = simpy.Environment() packers = simpy.PriorityResource(env, capacity=1) log = [] def order(name, priority, arrives): yield env.timeout(arrives) with packers.request(priority=priority) as request: yield request log.append((name, env.now)) yield env.timeout(1.5) env.process(order("first", priority=1, arrives=0)) env.process(order("standard", priority=1, arrives=0.5)) env.process(order("express", priority=0, arrives=1.0)) env.run() return log ``` ```text [('first', 0), ('express', 1.5), ('standard', 3.0)] ``` `PreemptiveResource` adds preemption: a request whose priority number is lower than a current user's, made with `preempt=True` (the default), takes that user's unit. The user is interrupted, and `interrupt.cause` is a `Preempted` object with `by`, `usage_since` and `resource`. The preempted process does not get the unit back, so it must request again if it wants to continue. Below, an express order arrives at 1.0 and interrupts a standard order that has used the packer since 0. ```python def preemptive(): """An express order takes the packer from a standard one, which is interrupted.""" env = simpy.Environment() packers = simpy.PreemptiveResource(env, capacity=1) log = [] def standard(): with packers.request(priority=1) as request: yield request try: yield env.timeout(1.5) log.append(("standard packed", env.now)) except simpy.Interrupt as interrupt: cause = interrupt.cause # a Preempted object log.append(("standard preempted", env.now, cause.usage_since)) def express(): yield env.timeout(1.0) with packers.request(priority=0) as request: # preempt=True is the default yield request yield env.timeout(1.0) log.append(("express packed", env.now)) env.process(standard()) env.process(express()) env.run() return log ``` ```text [('standard preempted', 1.0, 0), ('express packed', 2.0)] ``` In desflow, `DynamicResource` is all three: `queue: fifo` is `Resource`, `queue: lifo` serves the latest request first (SimPy has no class for it), `queue: priority` is `PriorityResource`, and `preempt: true` with it is `PreemptiveResource`. It also follows a capacity in the registry. [Resources](https://jaehyeon.me/desflow/latest/user-guide/resources/index.md) and [Priority and Preemption](https://jaehyeon.me/desflow/latest/user-guide/resources/priority-and-preemption/index.md) explain them. ______________________________________________________________________ ## Containers and Stores A `Container(env, capacity, init)` holds a quantity, such as boxes on a shelf. `put(amount)` waits while there is no room, and `get(amount)` waits until enough is held. `level` is the quantity held now. Waiting requests are served in order, so a large `get` at the head holds back smaller ones behind it. Here the packer needs 3 boxes while the shelf holds 2, so it waits for a delivery of 5 at 4 seconds. ```python def container(): """A shelf holds a quantity of boxes: a get for 3 waits until a put makes them available.""" env = simpy.Environment() shelf = simpy.Container(env, capacity=10, init=2) log = [] def packer(): yield shelf.get(3) log.append(("took 3 boxes", env.now, shelf.level)) def delivery(): yield env.timeout(4) yield shelf.put(5) # the waiting get is served as the boxes arrive env.process(packer()) env.process(delivery()) env.run() return log ``` The `get` is served as the delivery arrives, and the shelf then holds 4 of the 7 boxes. ```text [('took 3 boxes', 4, 4)] ``` A `Store` holds distinct items rather than a quantity. `put(item)` waits while it is full, and `get()` waits while it is empty and returns the oldest item. A `FilterStore` lets `get` take a function that picks the first item it accepts. A `PriorityStore` returns the smallest item first, and `PriorityItem(priority, item)` wraps items that cannot be compared. The three below hold the shop's parcels, which differ in size and in urgency. ```python def stores(): """A store holds distinct items; the filtered and priority kinds change which one a get returns.""" env = simpy.Environment() parcels = simpy.Store(env) by_size = simpy.FilterStore(env) by_urgency = simpy.PriorityStore(env) got = {} def run(): for name, size in (("p1", "small"), ("p2", "large"), ("p3", "small")): yield parcels.put(name) yield by_size.put((name, size)) yield by_urgency.put(simpy.PriorityItem(2, "standard")) yield by_urgency.put(simpy.PriorityItem(1, "express")) got["store"] = yield parcels.get() # first in, first out got["filter"] = yield by_size.get( lambda item: item[1] == "large" ) # first match got["priority"] = (yield by_urgency.get()).item # smallest priority first env.process(run()) env.run() return got ``` ```text {'store': 'p1', 'filter': ('p2', 'large'), 'priority': 'express'} ``` In desflow, a task's `put` and `get` use these: `put: {container: stock, amount: 2}` for a container, and `get: {store: parcels, filter: ...}` for a filtered store. A store declared with `priority: true` is a `PriorityStore`. `get_queue` and `put_queue`, each `{rank, ties}`, order the waiting gets and puts by an expression, as a resource's `queue` orders its requests, and a store whose `type` sets its own queues refuses them. The `SortedQueue` that a custom store type sets its own queue with stays valid. [Stores and Containers](https://jaehyeon.me/desflow/latest/user-guide/model-parts/stores-and-containers/index.md) and [Stock](https://jaehyeon.me/desflow/latest/learn/shop-logic/stock/index.md) explain them. ______________________________________________________________________ ## Real-time Environment `RealtimeEnvironment(factor)` is an environment whose clock follows the wall clock: a step of one time unit takes `factor` seconds of real time. With `strict=True`, the default, `step` raises `RuntimeError` when the model falls behind the wall clock by more than `factor` seconds. Set `strict=False` to let it catch up instead. `sync()` restarts the real-time reference from the present. Here one simulated second takes 0.2 seconds of real time, so a run of 2 simulated seconds takes at least 0.4 seconds. ```python def realtime(): """One simulated second takes 0.2 wall-clock seconds; the run lasts at least 2 x 0.2 s.""" env = simpy.rt.RealtimeEnvironment(factor=0.2) # strict=True is the default def packer(): yield env.timeout(2) env.process(packer()) started = time.monotonic() env.run() return env.now, time.monotonic() - started ``` ```text clock 2, wall clock at least 0.4 s: True ``` SimPy's `factor` is fixed when the environment is made. desflow's environment can switch to real time during a run, as the Clock and pacing row of [What desflow Changes](https://jaehyeon.me/desflow/latest/simpy/coming-from-simpy/#what-desflow-changes) shows. [Time and Pacing](https://jaehyeon.me/desflow/latest/user-guide/time-and-pacing/index.md) explains it. # Coming from SimPy If you have written a SimPy model, you already know most of what desflow needs. This page takes a plain SimPy model in the structure most tutorials teach and shows where each part goes in desflow. Nothing you know is lost: a desflow model is SimPy underneath. [SimPy and desflow](https://jaehyeon.me/desflow/latest/simpy/index.md) teaches each SimPy construct, and the last two sections of this page list what desflow changes and the form each construct takes in desflow. [SimPy Examples](https://jaehyeon.me/desflow/latest/simpy/examples/index.md) rewrites the seven examples that ship with SimPy, and an assistant with the [Agent Skill](https://jaehyeon.me/desflow/latest/ai/index.md) can port a SimPy program for you. The structure comes from the open book [HSMA: the little book of DES](https://des.hsma.co.uk/) by Dan Chalk, Sammi Rosser and Amy Heather, which teaches SimPy to health-service modellers. Its chapter [The Recommended Structure for DES Models](https://des.hsma.co.uk/recommended_structure_classes_for_des_models.html) splits a model into four classes: a class of global parameters, an entity class, a model class and a trial class. We read that chapter and the chapter on running large numbers of scenarios. The book's text is under CC BY-NC-SA, so none of it is copied here. The code below is our own. It models the packing shop and follows the same four-class shape. ______________________________________________________________________ ## Four Classes Look at the table for where each class goes. The sections after it explain each row on the shop. | In a plain SimPy model | In desflow | | -------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | | The global parameters class: arrival and packing times, packers, run length, number of runs | Arguments of `add_arrival`, `add_service` and `add_resource`, which are registry paths a run can change, and `add_variable` (`variables` in YAML) for values of your own | | The entity class: the thing that moves through the model, with the facts it remembers | An entity with `attributes`, and statistics that record each order's wait and service for you | | The model class: one run, with its environment, resources, arrival generator and journey generator | `SimulationContext`, with `@app.arrival_loop` for the arrival generator and `@app.task` for the journey | | The trial class: a loop that builds a model for each run number and collects one result per run | `replicate`, which runs a model `n` times from spawned seeds and gives an interval over the runs | ______________________________________________________________________ ## Global Parameters In the usual structure one class holds every number the model reads, and the model reads them as `G.packers`. This is the shop's. ```python class G: """Global parameters: read as G.packers, never instantiated.""" arrival_mean = 2.0 # seconds between orders pack_time = 1.5 # seconds to pack an order packers = 1 run_length = 3600 # seconds runs = 10 ``` In desflow these numbers are arguments of the parts they describe: | In `G` | In the builder | | ---------------------------------------------- | ------------------------------------------------------------------------------------------ | | `arrival_mean = 2.0` | `add_arrival("orders", dist="exponential", rate=0.5)`, an order every 2 seconds on average | | `pack_time = 1.5` | `add_service("packing", dist="constant", value=1.5)` | | `packers = 1` | `add_resource("packers", current_cap=1, max_cap=10)` | | `run_length` and `runs` | arguments of `run` and `replicate`, because they belong to the run and not to the system | | a number of your own, such as a conveyor speed | `add_variable`, or `variables` in YAML | Each value is stored in a registry under a path such as `Shop.resources.packers.current_cap`, and the model reads the registry whenever it needs the value. So a value can change while the run goes on, from a scenario or a connector, which a value in `G` cannot. Each change is checked before it is applied. [Live Parameters](https://jaehyeon.me/desflow/latest/user-guide/live-runs-and-connectors/live-parameters/index.md) lists the paths. ______________________________________________________________________ ## Entity Class The entity class is what travels through the model. Here an order carries its number and the time it waited. ```python class Order: """The entity: what travels through the model, and what it remembers.""" def __init__(self, order_id): self.id = order_id self.wait = 0.0 ``` In desflow an arrival creates an entity for you, and `attributes` on the arrival give it starting facts, such as `attributes={"express": 0}`. A task can read them to decide what comes next, and change them when it finishes. You do not store the wait yourself: the task records when the order queued, started and finished, and the statistics report the mean wait and service time of every task. [Task Flow](https://jaehyeon.me/desflow/latest/user-guide/model-parts/task-flow/#attributes) explains attributes. ______________________________________________________________________ ## Model Class The model class is one run. Its constructor makes the environment and the resources, one generator creates the arriving orders, and another is the journey of one order. ```python class Model: """One run of the shop.""" def __init__(self, run_number): self.env = simpy.Environment() self.random = random.Random(run_number) self.packers = simpy.Resource(self.env, capacity=G.packers) self.waits = [] def generate_orders(self): order_id = 0 while True: order_id += 1 self.env.process(self.pack_order(Order(order_id))) yield self.env.timeout(self.random.expovariate(1 / G.arrival_mean)) def pack_order(self, order): arrived = self.env.now with self.packers.request() as request: yield request order.wait = self.env.now - arrived self.waits.append(order.wait) yield self.env.timeout(G.pack_time) def run(self): self.env.process(self.generate_orders()) self.env.run(until=G.run_length) return statistics.mean(self.waits) ``` In desflow, `SimulationContext` is that class. It makes the environment, which is a SimPy environment, and the resources from the `add_` calls, so the constructor of your own class has nothing left to do. The arrival generator is `@app.arrival_loop`, and the journey is `@app.task`, which requests the resource, waits, holds it for the service time and releases it. The task replaces the `pack_order` method above, and it also publishes `queued`, `started` and a finished event as records. If the journey is more than one task, a task names the next one, as [A Flow of Tasks](https://jaehyeon.me/desflow/latest/learn/shop-logic/flow-of-tasks/index.md) shows. ______________________________________________________________________ ## Trial Class The trial class runs the model once for each run number and keeps one result per run. Here the run number also seeds the random generator, so each run differs and each can be repeated. ```python class Trial: """The runs of one design: one result for each.""" def run_trial(self): return [Model(run).run() for run in range(G.runs)] ``` In desflow this loop is `replicate`. It runs the model `n` times, gives each run its own seed spawned from one seed, reads the statistics at the end of each run, and returns the [interval](https://jaehyeon.me/desflow/latest/learn/concepts/output-analysis/#interval-and-half-width) for each measure you name. You do not write the loop, the seeding or the interval. [Replications](https://jaehyeon.me/desflow/latest/user-guide/results/replications/index.md) explains the options, and [Trusting Results](https://jaehyeon.me/desflow/latest/learn/studies/trusting-results/index.md) uses it on the shop. ______________________________________________________________________ ## Shop in desflow Here is the whole shop in desflow, with the trial loop beside it. The model is one function that builds a context, and the loop is one call. ```python def shop() -> SimulationContext: """The same shop: parameters in the registry, the entity and the statistics built in.""" app = SimulationContext(sim_id="Shop", factor=0) app.add_arrival("orders", dist="exponential", rate=1 / 2.0) app.add_service("packing", dist="constant", value=1.5) app.add_resource("packers", current_cap=1, max_cap=10) app.with_stats("typical", interval=3600) @app.task(service_id="packing", resource_id="packers") def pack_order(task_id): return {"event_type": "order_packed"} @app.arrival_loop("orders") def order_generator(context): task_id = 0 while True: order = yield context.wait_for_arrival("orders") context.spawn(pack_order(task_id, entity=order)) task_id += 1 return app def trial(): """The trial loop is `replicate`: one seed for each run, and an interval over the runs.""" result = replicate( shop, 10, seed=42, until=3600, measures=["tasks.pack_order.wait_mean"] ) return result.summary[0] ``` Four parts of the desflow version have no line in the SimPy one: - `context.wait_for_arrival("orders")` waits for the gap to the next order, drawn from the `orders` arrival's distribution, and returns the new order as an entity. - `entity=order` hands that order to the task, so every record of the task carries the order's key, such as `orders-1`. Without it the task starts an entity of its own. - The dictionary the task returns is the payload of its finished event, so `{"event_type": "order_packed"}` is published as a record. - `with_stats("typical", interval=3600)` switches on the built-in statistics, such as the mean wait that `replicate` reads, and publishes them every hour of simulated time. [Builder API](https://jaehyeon.me/desflow/latest/user-guide/writing-a-model/builder-api/#write-the-tasks) describes each call, and [Statistics](https://jaehyeon.me/desflow/latest/user-guide/results/statistics/#choose-a-level) lists the levels. Both versions run 10 times for one hour from an empty shop, so the two answers estimate the same thing. Each line of the output below gives the mean wait over the 10 runs and the half-width of its 95% interval. The two versions use different random numbers, so the values differ, but the check in the script asserts that they agree within their intervals. This shop is not the busy hour of the tutorials: it has one packer and an order every 2 seconds on average, so its mean wait differs from theirs. ```text plain SimPy: mean wait 2.30 ± 0.20 s over 10 runs desflow: mean wait 2.18 ± 0.24 s over 10 runs ``` What you take with you is the SimPy you wrote. A model can still be a SimPy generator inside desflow, through the [Low-level API](https://jaehyeon.me/desflow/latest/user-guide/writing-a-model/low-level-api/index.md), and it keeps the SimPy constructs it uses. What you leave behind is the code around it: the parameters class, the result bookkeeping and the trial loop. What you gain is [records](https://jaehyeon.me/desflow/latest/reference/records-and-telemetry/index.md), pacing, live parameters and the checks on [Output Analysis](https://jaehyeon.me/desflow/latest/learn/concepts/output-analysis/index.md). ______________________________________________________________________ ## What desflow Changes desflow keeps SimPy's event list, clock, processes and resources. It changes the six things in the table: | Part | In SimPy | In desflow | | ---------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | | Clock and pacing | `Environment` runs without waiting; `RealtimeEnvironment(factor, strict=True)` follows the wall clock and raises `RuntimeError` when the model falls behind | one class, `DynamicRealtimeEnvironment`, does both: `factor=0` runs without waiting, `go_live_at` switches to real time partway through a run (SimPy's `factor` cannot change once set), `logical_start_time` gives every record a date and time, and falling behind is reported as telemetry; `strict` raises `RuntimeError` as SimPy's does, with the defaults that [Strict Pacing](https://jaehyeon.me/desflow/latest/user-guide/time-and-pacing/clocks-and-pacing/#strict-pacing) gives; `sync()` is SimPy's, and `resume_pacing()` also moves the simulation anchor after a pause; `advance(until)` runs a started run in segments, as repeated `env.run(until=...)` does | | Processes | generators started with `env.process` | the same, and the builder adds `@app.task`, `@app.arrival_loop`, `@app.telemetry_loop` and `add_process`, which write the common ones for you | | Random times | none built in: a model calls `random` or NumPy itself | ten named distributions with checked parameters, drawn by a `Sampler` from the current values each time; each distribution draws from a random sequence of its own, made from the run's seed and its registry path | | Resources | `Resource`, `Container` and `Store` keep the capacity they were created with: it has no setter, so assigning a new one raises `AttributeError` (SimPy 4.1). `Resource` serves requests in the order they arrive, and `PriorityResource` by priority | `DynamicResource`, `DynamicContainer` and `DynamicStore` follow a capacity in the registry, and a resource that shrinks lets busy units finish. A resource serves its queue `fifo`, `lifo` or by `priority`, equal priorities first in, first out. `run()` builds the stores and containers a model declares, and tasks put to and get from them | | Parameters | Python variables, changed only by the model's own code | a registry of named paths, changed by connectors, scenarios or processes, with each change checked | | Output | whatever the model prints or logs | events and telemetry with a fixed shape, written to Kafka, Redis, PostgreSQL, files or Iceberg on background threads | ______________________________________________________________________ ## Each Construct in desflow Each row names a construct, its form in the three ways of writing a model, and the area of [SimPy Compatibility](https://jaehyeon.me/desflow/latest/simpy/compatibility/index.md) that lists its features with their status, the conformance checks that run them in plain SimPy and in all three forms, and the gaps. A construct with no native form in one of the three is marked there as a gap or a difference, with the reason. | SimPy construct | YAML | Builder | Low-level | Checks | | ------------------------------------------- | -------------------------------------------------------- | --------------------------------------------------------- | ------------------------------------------------- | ------------------------------------------------------------------------------------------------ | | `Environment`: `run`, `step`, `peek`, `now` | `run.until` | `app.run(until=)`, `app.step()`, `app.peek()` | `env.run(until=)` | [Environment](https://jaehyeon.me/desflow/latest/simpy/compatibility/#environment) | | `timeout` | a task with `service` and no `resource` | `@app.task(service_id=...)` | `yield env.timeout(delay)` | [Events and Timeout](https://jaehyeon.me/desflow/latest/simpy/compatibility/#events-and-timeout) | | Events and callbacks | `signals:`, `on:`, `listen:` | `add_signal`, `on=`, `listen=` | `Signal`, `event.callbacks.append(fn)` | [Events and Timeout](https://jaehyeon.me/desflow/latest/simpy/compatibility/#events-and-timeout) | | Processes and waiting for one | `wait: {task: ...}` | `wait={"task": ...}`, `context.call(...)` | `yield env.process(child())` | [Processes](https://jaehyeon.me/desflow/latest/simpy/compatibility/#processes) | | Interrupts | `interrupt:`, `on_interrupt` | `context.interrupt(...)`, `on_interrupt=` | `process.interrupt(cause)` | [Interrupts](https://jaehyeon.me/desflow/latest/simpy/compatibility/#interrupts) | | `AnyOf`, `AllOf` | `wait: {any: ...}`, `wait: {all: ...}` | `wait={"any": ...}`, `wait={"all": ...}` | `yield a \| b`, `yield a & b` | [Conditions](https://jaehyeon.me/desflow/latest/simpy/compatibility/#conditions) | | `Resource`, `PriorityResource` | `resource: packers`, `queue: priority` or `queue: lifo` | `@app.task(resource_id=...)`, `add_resource(queue=...)` | `with packers.request() as req: yield req` | [Resources](https://jaehyeon.me/desflow/latest/simpy/compatibility/#resources) | | `PreemptiveResource` | `preempt: true, queue: priority` | `add_resource(queue="priority", preempt=True)` | `DynamicResource(queue="priority", preempt=True)` | [Resources](https://jaehyeon.me/desflow/latest/simpy/compatibility/#resources) | | `Container` | `put` and `get` with `container` and `amount` | `put={"container": ...}`, `get={"container": ...}` | `yield stock.put(2)`, `yield stock.get(1)` | [Containers](https://jaehyeon.me/desflow/latest/simpy/compatibility/#containers) | | `Store`, `FilterStore`, `PriorityStore` | `put` and `get` with `store`, `filter`, `priority: true` | `put={"store": ...}`, `get={"store": ..., "filter": ...}` | `parcels.get(filter=...)` | [Stores](https://jaehyeon.me/desflow/latest/simpy/compatibility/#stores) | | `RealtimeEnvironment` | `simulation.factor`, `simulation.strict` | `SimulationContext(factor=, strict=)` | `DynamicRealtimeEnvironment(factor=)` | [Real-Time](https://jaehyeon.me/desflow/latest/simpy/compatibility/#real-time) | Every SimPy form in the table has a construct of its own in YAML and the Builder, so a model needs no Python for it. `!python` stays valid for code you write yourself, and `add_process` (Builder) or a process of the low-level API runs SimPy code as it is, as [Processes](https://jaehyeon.me/desflow/latest/user-guide/tasks-and-processes/processes/#a-process) shows. Where a SimPy construct has no form in one of the three, [SimPy Compatibility](https://jaehyeon.me/desflow/latest/simpy/compatibility/index.md) says so for that construct. [SimPy Compatibility](https://jaehyeon.me/desflow/latest/simpy/compatibility/index.md) lists, for each construct, the form that gives it. User Guide pages that build on SimPy name the parts they use in their How It Works section, starting with [Arrivals and Services](https://jaehyeon.me/desflow/latest/user-guide/model-parts/arrivals-and-services/index.md). # SimPy Examples SimPy's documentation ships seven example programs. Each page here takes one of them, shows SimPy's code piece by piece, and shows the same piece written in desflow as a YAML blueprint, with the builder API, and with the low-level API. Every desflow version is a file that `desflow examples get` downloads and a test runs. | Example | What it shows | | --------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------- | | [Bank Renege](https://jaehyeon.me/desflow/latest/simpy/examples/bank-renege/index.md) | customers who wait too long at a counter go away | | [Carwash](https://jaehyeon.me/desflow/latest/simpy/examples/carwash/index.md) | a car keeps a washing machine while the wash runs | | [Machine Shop](https://jaehyeon.me/desflow/latest/simpy/examples/machine-shop/index.md) | machines break down, and a repair preempts the repairman's other jobs | | [Movie Renege](https://jaehyeon.me/desflow/latest/simpy/examples/movie-renege/index.md) | a film that sells out sends its queue away | | [Gas Station Refueling](https://jaehyeon.me/desflow/latest/simpy/examples/gas-station-refuel/index.md) | cars drain a tank that a tank truck refills | | [Process Communication](https://jaehyeon.me/desflow/latest/simpy/examples/process-communication/index.md) | messages through a store, one to one and broadcast | | [Event Latency](https://jaehyeon.me/desflow/latest/simpy/examples/latency/index.md) | each message reaches the receiver after a fixed delay | ## How to Read the Pages Each page keeps the system of SimPy's example and changes three things that a reader would otherwise take for a difference in the model. - **Times are seconds.** SimPy's times have no unit. desflow reads each time unit as one second. In Carwash, Machine Shop and Movie Renege, SimPy counts minutes, and each of its minutes is one second here. A run of 20 minutes in SimPy is a run of 20 seconds in desflow. - **Numbers differ from SimPy's output.** desflow draws each random value from its own stream, named by the place where the value is used, such as `tasks.customer.patience`. A seed of 42 gives different numbers from SimPy's `random.seed(42)`. Each page shows SimPy's output beside the figures of the desflow run. The two have the same structure and different numbers. - **Machine Shop writes breakdowns as tasks.** SimPy interrupts the process that makes parts. The repair is then a request for the repairman, who also does other jobs. The page writes each machine's failures as a task that interrupts the machine's `part` task, so that the repair is an ordinary request at priority 1. SimPy's code is shown with its licence notice. [Coming from SimPy](https://jaehyeon.me/desflow/latest/simpy/coming-from-simpy/index.md) maps each SimPy construct to its desflow form, and [SimPy Compatibility](https://jaehyeon.me/desflow/latest/simpy/compatibility/index.md) lists what is supported. # Bank Renege One counter serves five customers, and a customer who waits longer than their patience goes away. This is SimPy's Bank Renege example, written in desflow. ______________________________________________________________________ ## Before You Start SimPy's example has one counter and 5 customers. The first customer arrives at time 0 and the others at exponential gaps with a mean of 10. Each customer has a patience drawn between 1 and 3, and goes away (reneges) if the counter is not free by then. A customer who reaches the counter is served for an exponential time with a mean of 12. SimPy counts no unit, and desflow reads each unit as one second. The example needs only desflow, which each Quick Start in [Run It](#run-it) installs, and no other service. `desflow examples get simpy-bank-renege --api yaml` downloads it, as [Get an Example](https://jaehyeon.me/desflow/latest/cli/#get-an-example) shows. [SimPy Examples](https://jaehyeon.me/desflow/latest/simpy/examples/index.md) says how these pages read SimPy's times and numbers. SimPy's own page for the example is [on its documentation site](https://simpy.readthedocs.io/en/4.1.2/examples/bank_renege.html). ______________________________________________________________________ ## Steps ### Customers Arrive SimPy's `source` starts a customer at time 0 and then one after each gap. ```python def source(env, number, interval, counter): """Source generates customers randomly""" for i in range(number): c = customer(env, f'Customer{i:02d}', counter, time_in_bank=12.0) env.process(c) t = random.expovariate(1.0 / interval) yield env.timeout(t) ``` The counter is a resource with one unit. The arrival `customers` has `first_at: 0`, so the first customer comes at time 0, and `max_events: 5`, so only five come. Its `key` names them `Customer00` to `Customer04`. ```yaml resources: counter: {current_cap: 1} arrivals: customers: dist: exponential rate: 0.1 first_at: 0 max_events: 5 key: {gen: sequence, format: "Customer{:02d}"} spawn: customer ``` `add_resource` declares the counter, and `add_arrival` takes the same `first_at`, `max_events` and `key` as the YAML. ```python app.add_resource("counter", current_cap=1) app.add_arrival( "customers", "exponential", rate=0.1, first_at=0, max_events=5, key=lambda n: "Customer{:02d}".format(n - 1), spawn="customer", ) ``` The low-level version keeps SimPy's `source` and draws each gap from desflow's `Sampler`, from the stream the arrival uses in the other two versions. ```python sampler = Sampler(seed=42) gap = DistributionConfig(dist="exponential", rate=0.1) gap.stream = "arrival.customers" # the sequence the blueprint's arrival draws from patiences = sampler.generator("tasks.customer.patience") services = sampler.generator("tasks.customer.service_time") counter = simpy.Resource(env, capacity=1) ``` ```python def source(): for i in range(NEW_CUSTOMERS): env.process(customer(f"Customer{i:02d}", i)) yield env.timeout(sampler.sample(gap)) env.process(source()) ``` ### Customer Waits or Reneges SimPy's `customer` requests the counter and waits for either the counter or its patience, whichever comes first. ```python def customer(env, name, counter, time_in_bank): """Customer arrives, is served and leaves.""" arrive = env.now print(f'{arrive:7.4f} {name}: Here I am') with counter.request() as req: patience = random.uniform(MIN_PATIENCE, MAX_PATIENCE) # Wait for the counter or abort at the end of our tether results = yield req | env.timeout(patience) wait = env.now - arrive if req in results: # We got to the counter print(f'{env.now:7.4f} {name}: Waited {wait:6.3f}') tib = random.expovariate(1.0 / time_in_bank) yield env.timeout(tib) print(f'{env.now:7.4f} {name}: Finished') else: # We reneged print(f'{env.now:7.4f} {name}: RENEGED after {wait:6.3f}') ``` `patience` is the longest wait for the counter, drawn uniform from 1 to 3 seconds for each customer. A customer whose patience ends first publishes `reneged` and leaves. The service time is exponential with a mean of 12 seconds, written as the rate 1/12. ```yaml tasks: customer: resource: counter patience: {gen: uniform, low: 1, high: 3} service_time: {gen: sample, dist: exponential, rate: 0.08333333333333333} payload: {event_type: finished} ``` The `customer` task takes `patience` and `service_time` as generators. ```python @app.task( name="customer", resource_id="counter", # Waits for the counter at most this long, then goes away patience=generator({"gen": "uniform", "low": 1, "high": 3}), service_time=generator( {"gen": "sample", "dist": "exponential", "rate": 0.08333333333333333} ), ) def customer(task_id): """Is served at the counter.""" return {"event_type": "finished"} ``` The `customer` function is SimPy's, with `req | env.timeout(patience)`. It publishes `reneged` when `req` is not in the result. ```python def customer(name, number): def publish(value): env.publish_event(name, value, task="customer", instance=number) with counter.request() as req: publish({"status": "queued"}) patience = float(patiences.uniform(1, 3)) # Waits for the counter at most `patience`, then goes away results = yield req | env.timeout(patience) if req in results: publish({"status": "started"}) yield env.timeout(float(services.exponential(12.0))) publish({"event_type": "finished"}) else: publish({"status": "reneged"}) ``` ### Run It `desflow run` loads the blueprint and runs it unpaced, because it sets `factor: 0`. Each record is printed to the terminal. **Quick Start** `desflow examples get` downloads the example at the release you install, into a folder of its own. Pick uv or pip: ```bash # 1. Install uv tool install desflow # 2. Download the example desflow examples get simpy-bank-renege --api yaml cd simpy-bank-renege/yaml # 3. Run it desflow run bank_renege.yaml ``` ```bash # 1. Install pip install desflow # 2. Download the example desflow examples get simpy-bank-renege --api yaml cd simpy-bank-renege/yaml # 3. Run it desflow run bank_renege.yaml ``` The script builds the model with the builder API, runs it unpaced, and prints each record to the terminal. **Quick Start** `desflow examples get` downloads the example at the release you install, into a folder of its own. Pick uv or pip: ```bash # 1. Install uv tool install desflow # 2. Download the example desflow examples get simpy-bank-renege --api builder cd simpy-bank-renege/builder # 3. Run it uv run --no-project --with desflow bank_renege_example.py ``` ```bash # 1. Install pip install desflow # 2. Download the example desflow examples get simpy-bank-renege --api builder cd simpy-bank-renege/builder # 3. Run it python bank_renege_example.py ``` The script wires the model by hand on `DynamicRealtimeEnvironment`, runs it unpaced, and prints each record to the terminal. **Quick Start** `desflow examples get` downloads the example at the release you install, into a folder of its own. Pick uv or pip: ```bash # 1. Install uv tool install desflow # 2. Download the example desflow examples get simpy-bank-renege --api low-level cd simpy-bank-renege/low-level # 3. Run it uv run --no-project --with desflow bank_renege_example.py ``` ```bash # 1. Install pip install desflow # 2. Download the example desflow examples get simpy-bank-renege --api low-level cd simpy-bank-renege/low-level # 3. Run it python bank_renege_example.py ``` ______________________________________________________________________ ## Check the Result Two of the five customers renege: `Customer03` and `Customer04`. `Customer00` is served from time 0 and finishes at 3.536 seconds. `Customer01` reaches the counter at 5.384 seconds and finishes at 10.53 seconds. `Customer02` reaches the counter at 10.53 seconds and finishes at 18.266 seconds. The run has no end time, so it stops when the last customer leaves. SimPy's own output, below, has customers who are served and customers who renege too. desflow draws each random value from its own stream, named by the place where the value is used, such as `tasks.customer.patience`. A seed of 42 therefore gives different numbers from SimPy's `random.seed(42)`. The system is the same. The figures are not. ```text Bank renege 0.0000 Customer00: Here I am 0.0000 Customer00: Waited 0.000 3.8595 Customer00: Finished 10.2006 Customer01: Here I am 10.2006 Customer01: Waited 0.000 12.7265 Customer02: Here I am 13.9003 Customer02: RENEGED after 1.174 23.7507 Customer01: Finished 34.9993 Customer03: Here I am 34.9993 Customer03: Waited 0.000 37.9599 Customer03: Finished 40.4798 Customer04: Here I am 40.4798 Customer04: Waited 0.000 43.1401 Customer04: Finished ``` The three versions in desflow print the same records, which [a test](https://github.com/jaehyeon-kim/desflow/blob/v1.3.0/tests/docs/test_example_twins.py) checks by running each version unpaced. Each record has `sim_ts`, the simulation time, and a key for the entity it belongs to. The statistics and the parameters that a live run can change are in the same stream, which SimPy's file does not have. ______________________________________________________________________ ## Full Files Full files The blueprint is `bank_renege.yaml`. ```yaml # Bank Renege: SimPy's bank_renege.py example, in YAML. # # The YAML version of bank_renege_example.py, which --api builder downloads. One # counter serves five customers. The first arrives at 0 and the others about 10 # seconds apart (exponential gaps). Each customer waits for the counter for a patience # drawn between 1 and 3 seconds, and goes away (reneged) if the counter is not free by # then. A customer at the counter is served for about 12 seconds (exponential). # # SimPy's example counts seconds, as desflow does. Each value is drawn from desflow's # random sequence for its place in the file, so the numbers differ from those SimPy # prints. # # Needs no containers. Runs unpaced and ends when the last customer leaves. # Run it from its folder with: desflow run bank_renege.yaml simulation: {sim_id: Bank, factor: 0, random_seed: 42} egress: - {type: Console} resources: counter: {current_cap: 1} arrivals: customers: dist: exponential rate: 0.1 first_at: 0 max_events: 5 key: {gen: sequence, format: "Customer{:02d}"} spawn: customer tasks: customer: resource: counter patience: {gen: uniform, low: 1, high: 3} service_time: {gen: sample, dist: exponential, rate: 0.08333333333333333} payload: {event_type: finished} ``` The script builds the model with the builder API. ```python """Bank Renege: SimPy's bank_renege.py example, builder API. One counter serves five customers. The first arrives at 0 and the others about 10 seconds apart (exponential gaps). Each customer waits for the counter for a patience drawn between 1 and 3 seconds, and goes away (reneged) if the counter is not free by then. A customer at the counter is served for about 12 seconds (exponential). SimPy's example counts seconds, as desflow does. Each value is drawn from desflow's random sequence for its place in the model, so the numbers differ from those SimPy prints. Needs no containers. Runs unpaced and ends when the last customer leaves. """ import logging from desflow import ConsoleEgress, SimulationContext from desflow.values import generator def build() -> SimulationContext: """Builds the bank.""" app = SimulationContext(sim_id="Bank", factor=0, random_seed=42) app.add_egress(ConsoleEgress()) app.add_resource("counter", current_cap=1) app.add_arrival( "customers", "exponential", rate=0.1, first_at=0, max_events=5, key=lambda n: "Customer{:02d}".format(n - 1), spawn="customer", ) @app.task( name="customer", resource_id="counter", # Waits for the counter at most this long, then goes away patience=generator({"gen": "uniform", "low": 1, "high": 3}), service_time=generator( {"gen": "sample", "dist": "exponential", "rate": 0.08333333333333333} ), ) def customer(task_id): """Is served at the counter.""" return {"event_type": "finished"} return app app = build() def run(model: SimulationContext = app) -> None: """Runs until the last customer leaves.""" model.run() if __name__ == "__main__": logging.basicConfig(level=logging.INFO, format="%(levelname)s %(message)s") run() ``` The script wires the model by hand on `DynamicRealtimeEnvironment`, with SimPy's own processes. ```python """Bank Renege: SimPy's bank_renege.py example, low-level API. The low-level version of `builder/simpy/bank_renege_example.py`: SimPy's own processes on a `DynamicRealtimeEnvironment`. They publish with `publish_event` the records that the YAML and builder versions publish: each customer's `queued` and `started`, its `reneged` or `finished`, and the number of the task's instance. One counter serves five customers. The first arrives at 0 and the others about 10 seconds apart. Each customer waits for the counter for a patience between 1 and 3 seconds, and goes away (reneged) if the counter is not free by then. A customer at the counter is served for about 12 seconds. SimPy's example counts seconds, as desflow does. Each value is drawn from desflow's `Sampler`, from the random sequence the YAML and builder versions use for the same place, so the three versions publish the same records. Needs no containers. Runs unpaced and ends when the last customer leaves. """ import logging import simpy from desflow import ( ConsoleEgress, DistributionConfig, DynamicRealtimeEnvironment, Sampler, ) NEW_CUSTOMERS = 5 UNTIL = None # the run ends when no event is left def build(env: DynamicRealtimeEnvironment) -> None: """Starts the customers' source on `env`.""" sampler = Sampler(seed=42) gap = DistributionConfig(dist="exponential", rate=0.1) gap.stream = "arrival.customers" # the sequence the blueprint's arrival draws from patiences = sampler.generator("tasks.customer.patience") services = sampler.generator("tasks.customer.service_time") counter = simpy.Resource(env, capacity=1) def customer(name, number): def publish(value): env.publish_event(name, value, task="customer", instance=number) with counter.request() as req: publish({"status": "queued"}) patience = float(patiences.uniform(1, 3)) # Waits for the counter at most `patience`, then goes away results = yield req | env.timeout(patience) if req in results: publish({"status": "started"}) yield env.timeout(float(services.exponential(12.0))) publish({"event_type": "finished"}) else: publish({"status": "reneged"}) def source(): for i in range(NEW_CUSTOMERS): env.process(customer(f"Customer{i:02d}", i)) yield env.timeout(sampler.sample(gap)) env.process(source()) def run() -> None: """Runs until the last customer leaves.""" env = DynamicRealtimeEnvironment(factor=0) env.setup_egress([ConsoleEgress()]) build(env) try: env.run(until=UNTIL) finally: env.teardown() if __name__ == "__main__": logging.basicConfig(level=logging.INFO, format="%(levelname)s %(message)s") run() ``` This is SimPy 4.1.2's `bank_renege.py`, with SimPy's licence notice added at the top and comment lines that mark the pieces shown above. Run with Python, it prints the output shown under Check the Result. ```python # SimPy 4.1.2, docs/examples/code/bank_renege.py, under SimPy's licence (LICENSE.rst): # # The MIT License (MIT) # # Copyright (c) 2013 Ontje Lünsdorf and Stefan Scherfke (also see AUTHORS.txt) # # Permission is hereby granted, free of charge, to any person obtaining a copy of # this software and associated documentation files (the "Software"), to deal in # the Software without restriction, including without limitation the rights to # use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of # the Software, and to permit persons to whom the Software is furnished to do so, # subject to the following conditions: # # The above copyright notice and this permission notice shall be included in all # copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS # FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR # COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER # IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN # CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. """ Bank renege example Covers: - Resources: Resource - Condition events Scenario: A counter with a random service time and customers who renege. Based on the program bank08.py from TheBank tutorial of SimPy 2. (KGM) """ import random import simpy RANDOM_SEED = 42 NEW_CUSTOMERS = 5 # Total number of customers INTERVAL_CUSTOMERS = 10.0 # Generate new customers roughly every x seconds MIN_PATIENCE = 1 # Min. customer patience MAX_PATIENCE = 3 # Max. customer patience def source(env, number, interval, counter): """Source generates customers randomly""" for i in range(number): c = customer(env, f'Customer{i:02d}', counter, time_in_bank=12.0) env.process(c) t = random.expovariate(1.0 / interval) yield env.timeout(t) def customer(env, name, counter, time_in_bank): """Customer arrives, is served and leaves.""" arrive = env.now print(f'{arrive:7.4f} {name}: Here I am') with counter.request() as req: patience = random.uniform(MIN_PATIENCE, MAX_PATIENCE) # Wait for the counter or abort at the end of our tether results = yield req | env.timeout(patience) wait = env.now - arrive if req in results: # We got to the counter print(f'{env.now:7.4f} {name}: Waited {wait:6.3f}') tib = random.expovariate(1.0 / time_in_bank) yield env.timeout(tib) print(f'{env.now:7.4f} {name}: Finished') else: # We reneged print(f'{env.now:7.4f} {name}: RENEGED after {wait:6.3f}') # Setup and start the simulation print('Bank renege') random.seed(RANDOM_SEED) env = simpy.Environment() # Start processes and run counter = simpy.Resource(env, capacity=1) env.process(source(env, NEW_CUSTOMERS, INTERVAL_CUSTOMERS, counter)) env.run() ``` ______________________________________________________________________ ## Sources - [SimPy 4.1.2, Bank Renege](https://simpy.readthedocs.io/en/4.1.2/examples/bank_renege.html): the original code and its output. - [SimPy's licence](https://gitlab.com/team-simpy/simpy/-/blob/master/LICENSE.rst): MIT, Copyright (c) 2013 Ontje Lünsdorf and Stefan Scherfke. The SimPy file above carries this notice. - [`examples/` in the desflow repository](https://github.com/jaehyeon-kim/desflow/tree/v1.3.0/examples): the three versions in desflow, under `simpy/` in each folder. # Carwash Cars take a washing machine and keep it while the wash runs. This is SimPy's Carwash example, written in desflow. ______________________________________________________________________ ## Before You Start SimPy's carwash has two machines. Four cars are waiting when it opens, and then a car arrives every 5 to 9 minutes. A wash takes 5 minutes and removes 50 to 99 percent of the dirt. The run lasts 20 minutes. desflow reads each of SimPy's minutes as one second, so the run lasts 20 seconds. The example needs only desflow, which each Quick Start in [Run It](#run-it) installs, and no other service. `desflow examples get simpy-carwash --api yaml` downloads it, as [Get an Example](https://jaehyeon.me/desflow/latest/cli/#get-an-example) shows. [SimPy Examples](https://jaehyeon.me/desflow/latest/simpy/examples/index.md) says how these pages read SimPy's times and numbers. SimPy's own page for the example is [on its documentation site](https://simpy.readthedocs.io/en/4.1.2/examples/carwash.html). ______________________________________________________________________ ## Steps ### Machines Wash SimPy's `Carwash` class holds the machines and has a `wash` method that takes the wash time and removes dirt. ```python class Carwash: """A carwash has a limited number of machines (``NUM_MACHINES``) to clean cars in parallel. Cars have to request one of the machines. When they got one, they can start the washing processes and wait for it to finish (which takes ``washtime`` minutes). """ def __init__(self, env, num_machines, washtime): self.env = env self.machine = simpy.Resource(env, num_machines) self.washtime = washtime def wash(self, car): """The washing processes. It takes a ``car`` processes and tries to clean it.""" yield self.env.timeout(self.washtime) pct_dirt = random.randint(50, 99) print(f"Carwash removed {pct_dirt}% of {car}'s dirt.") ``` `machine` is a resource with two units, and `wash` is a service that takes 5 seconds. The `wash` task is a task of its own: it takes the service time and publishes the dirt removed, an integer from 50 to 99, in `dirt_removed_pct`. ```yaml resources: machine: {current_cap: 2} services: wash: {dist: constant, value: 5} ``` ```yaml wash: service: wash payload: event_type: washed dirt_removed_pct: {gen: integer, bounds: [50, 99]} ``` `add_resource` and `add_service` declare the machines and the wash time, and the `wash` task publishes `dirt_removed_pct` from a template. ```python app.add_resource("machine", current_cap=2) app.add_service("wash", dist="constant", value=5) ``` ```python wash_payload = Template( { "event_type": "washed", "dirt_removed_pct": {"gen": "integer", "bounds": [50, 99]}, }, # The name gives the random sequence the YAML version's payload draws from name="tasks.wash", ) @app.task(name="wash", service_id="wash") def wash(task_id): """Washes the car.""" return wash_payload ``` The low-level version has SimPy's `simpy.Resource` for the machines and a `wash` function that draws the dirt removed from desflow's `Sampler`. ```python sampler = Sampler(seed=42) gaps = sampler.generator("arrivals.cars.gap") dirt = sampler.generator("tasks.wash.payload.dirt_removed_pct") machine = simpy.Resource(env, NUM_MACHINES) numbers = {task: itertools.count() for task in ("car", "washing", "wash")} ``` ```python def wash(name): number = next(numbers["wash"]) publish( name, "wash", number, { "path_id": WASH, "sim_id": "Carwash", "service": "wash", "status": "started", }, ) yield env.timeout(WASHTIME) removed = int(dirt.integers(50, 100)) publish( name, "wash", number, {"event_type": "washed", "dirt_removed_pct": removed} ) ``` ### Car Is Washed SimPy's `car` requests a machine, keeps it while the wash runs, and then leaves. ```python def car(env, name, cw): """The car process (each car has a ``name``) arrives at the carwash (``cw``) and requests a cleaning machine. It then starts the washing process, waits for it to finish and leaves to never come back ... """ print(f'{name} arrives at the carwash at {env.now:.2f}.') with cw.machine.request() as request: yield request print(f'{name} enters the carwash at {env.now:.2f}.') yield env.process(cw.wash(name)) print(f'{name} leaves the carwash at {env.now:.2f}.') ``` `car` takes a machine with `seize: machine`, which keeps the unit after the task ends. `washing` waits for the `wash` task to finish with `wait: {task: wash}`, and then gives the machine back with `release: machine`. ```yaml tasks: car: seize: machine payload: {event_type: enters} next: washing # The car keeps its machine until the wash, a task of its own, has finished washing: wait: {task: wash} payload: {event_type: leaves} release: machine ``` The `car` and `washing` tasks take `seize`, `wait` and `release` as the YAML does. ```python @app.task(name="car", seize="machine", next="washing") def car(task_id): """Takes a machine and keeps it.""" return {"event_type": "enters"} # The car keeps its machine until the wash, a task of its own, has finished @app.task(name="washing", wait={"task": "wash"}, release="machine") def washing(task_id): """Leaves once its wash has finished.""" return {"event_type": "leaves"} ``` The `car` function is SimPy's `with machine.request()` block. It runs the wash as a process and publishes the records of the three tasks. ```python def car(name): number = next(numbers["car"]) with machine.request() as request: publish(name, "car", number, {"status": "queued"}) yield request publish(name, "car", number, {"status": "started"}) publish(name, "car", number, {"event_type": "enters"}) # The car keeps its machine until the wash has finished waiting = next(numbers["washing"]) publish(name, "washing", waiting, {"status": "queued"}) yield env.process(wash(name)) publish(name, "washing", waiting, {"status": "started"}) publish(name, "washing", waiting, {"event_type": "leaves"}) ``` ### Cars Arrive SimPy's `setup` starts four cars at time 0 and then a car after each gap of 5 to 9 minutes. ```python def setup(env, num_machines, washtime, t_inter): """Create a carwash, a number of initial cars and keep creating cars approx. every ``t_inter`` minutes.""" # Create the carwash carwash = Carwash(env, num_machines, washtime) car_count = itertools.count() # Create 4 initial cars for _ in range(4): env.process(car(env, f'Car {next(car_count)}', carwash)) # Create more cars while the simulation is running while True: yield env.timeout(random.randint(t_inter - 2, t_inter + 2)) env.process(car(env, f'Car {next(car_count)}', carwash)) ``` `initial: 4` starts four cars at time 0. After that, a car arrives after `gap`, an integer from 5 to 9 seconds. ```yaml arrivals: cars: initial: 4 gap: {gen: integer, bounds: [5, 9]} spawn: car key: {gen: sequence, format: "Car {}"} ``` `add_arrival` takes `initial` and `gap` as the YAML does. The `size` argument of `build` sets the number of cars at the start. ```python app.add_arrival( "cars", gap=generator({"gen": "integer", "bounds": [5, 9]}), key=lambda n: "Car {}".format(n - 1), initial=size, spawn="car", ) ``` The `setup` function is SimPy's. It draws each gap from desflow's `Sampler`. ```python def setup(): for i in range(size): env.process(car(f"Car {i}")) i = size while True: yield env.timeout(int(gaps.integers(5, 10))) env.process(car(f"Car {i}")) i += 1 env.process(setup()) ``` ### Run It `desflow run` loads the blueprint and runs it unpaced, because it sets `factor: 0`. Each record is printed to the terminal. **Quick Start** `desflow examples get` downloads the example at the release you install, into a folder of its own. Pick uv or pip: ```bash # 1. Install uv tool install desflow # 2. Download the example desflow examples get simpy-carwash --api yaml cd simpy-carwash/yaml # 3. Run it desflow run carwash.yaml ``` ```bash # 1. Install pip install desflow # 2. Download the example desflow examples get simpy-carwash --api yaml cd simpy-carwash/yaml # 3. Run it desflow run carwash.yaml ``` The script builds the model with the builder API, runs it unpaced, and prints each record to the terminal. **Quick Start** `desflow examples get` downloads the example at the release you install, into a folder of its own. Pick uv or pip: ```bash # 1. Install uv tool install desflow # 2. Download the example desflow examples get simpy-carwash --api builder cd simpy-carwash/builder # 3. Run it uv run --no-project --with desflow carwash_example.py ``` ```bash # 1. Install pip install desflow # 2. Download the example desflow examples get simpy-carwash --api builder cd simpy-carwash/builder # 3. Run it python carwash_example.py ``` The script wires the model by hand on `DynamicRealtimeEnvironment`, runs it unpaced, and prints each record to the terminal. **Quick Start** `desflow examples get` downloads the example at the release you install, into a folder of its own. Pick uv or pip: ```bash # 1. Install uv tool install desflow # 2. Download the example desflow examples get simpy-carwash --api low-level cd simpy-carwash/low-level # 3. Run it uv run --no-project --with desflow carwash_example.py ``` ```bash # 1. Install pip install desflow # 2. Download the example desflow examples get simpy-carwash --api low-level cd simpy-carwash/low-level # 3. Run it python carwash_example.py ``` ______________________________________________________________________ ## Check the Result Six cars enter the carwash in the 20 seconds. Cars 0 to 3 are waiting at time 0, car 4 arrives at 9 seconds and car 5 at 15 seconds. Cars 0 and 1 finish washing at 5 seconds, cars 2 and 3 at 10 seconds and car 4 at 15 seconds. Car 5 starts its wash at 15 seconds and would finish at 20 seconds, when the run ends, so the records show no wash finished for it. SimPy's example prints the percentage of dirt removed in a line of text. Here it is the `dirt_removed_pct` field of each `washed` record. desflow draws each random value from its own stream, named by the place where the value is used, such as `arrivals.cars.gap`. A seed of 42 therefore gives different numbers from SimPy's `random.seed(42)`. The system is the same. The figures are not. ```text Carwash Check out http://youtu.be/fXXmeP9TvBg while simulating ... ;-) Car 0 arrives at the carwash at 0.00. Car 1 arrives at the carwash at 0.00. Car 2 arrives at the carwash at 0.00. Car 3 arrives at the carwash at 0.00. Car 0 enters the carwash at 0.00. Car 1 enters the carwash at 0.00. Car 4 arrives at the carwash at 5.00. Carwash removed 97% of Car 0's dirt. Carwash removed 67% of Car 1's dirt. Car 0 leaves the carwash at 5.00. Car 1 leaves the carwash at 5.00. Car 2 enters the carwash at 5.00. Car 3 enters the carwash at 5.00. Car 5 arrives at the carwash at 10.00. Carwash removed 64% of Car 2's dirt. Carwash removed 58% of Car 3's dirt. Car 2 leaves the carwash at 10.00. Car 3 leaves the carwash at 10.00. Car 4 enters the carwash at 10.00. Car 5 enters the carwash at 10.00. Carwash removed 97% of Car 4's dirt. Carwash removed 56% of Car 5's dirt. Car 4 leaves the carwash at 15.00. Car 5 leaves the carwash at 15.00. Car 6 arrives at the carwash at 16.00. Car 6 enters the carwash at 16.00. ``` The three versions in desflow print the same records, which [a test](https://github.com/jaehyeon-kim/desflow/blob/v1.3.0/tests/docs/test_example_twins.py) checks by running each version unpaced. Each record has `sim_ts`, the simulation time, and a key for the entity it belongs to. The statistics and the parameters that a live run can change are in the same stream, which SimPy's file does not have. ______________________________________________________________________ ## Full Files Full files The blueprint is `carwash.yaml`. ```yaml # Carwash: SimPy's carwash.py example, in YAML. # # The YAML version of carwash_example.py, which --api builder downloads. A carwash has # two washing machines. Four cars wait when it opens. A car takes a machine, keeps it # while the wash runs (a task of its own that removes 50 to 99 percent of the dirt), # and then leaves. # # SimPy's example counts minutes, and here each of its minutes is one second. So a car # arrives every 5 to 9 seconds, a wash takes 5 seconds, and the run ends after 20 # seconds, SimPy's 20 minutes. Each value is drawn from desflow's random sequence for # its place in the file, so the numbers differ from those SimPy prints. # # Needs no containers. Runs unpaced and ends after 20 simulation seconds. # Run it from its folder with: desflow run carwash.yaml simulation: {sim_id: Carwash, factor: 0, random_seed: 42} egress: - {type: Console} resources: machine: {current_cap: 2} services: wash: {dist: constant, value: 5} arrivals: cars: initial: 4 gap: {gen: integer, bounds: [5, 9]} spawn: car key: {gen: sequence, format: "Car {}"} tasks: car: seize: machine payload: {event_type: enters} next: washing # The car keeps its machine until the wash, a task of its own, has finished washing: wait: {task: wash} payload: {event_type: leaves} release: machine wash: service: wash payload: event_type: washed dirt_removed_pct: {gen: integer, bounds: [50, 99]} run: {until: 20} ``` The script builds the model with the builder API. ```python """Carwash: SimPy's carwash.py example, builder API. A carwash has two washing machines. Four cars wait when it opens. A car takes a machine, keeps it while the wash runs (a task of its own that removes 50 to 99 percent of the dirt), and then leaves. SimPy's example counts minutes, and here each of its minutes is one second. So a car arrives every 5 to 9 seconds, a wash takes 5 seconds, and the run ends after 20 seconds, SimPy's 20 minutes. Each value is drawn from desflow's random sequence for its place in the model, so the numbers differ from those SimPy prints. Needs no containers. Runs unpaced and ends after 20 simulation seconds. """ import logging from desflow import ConsoleEgress, SimulationContext from desflow.values import Template, generator def build(size: int = 4) -> SimulationContext: """Builds the carwash, with `size` cars waiting when it opens.""" app = SimulationContext(sim_id="Carwash", factor=0, random_seed=42) app.add_egress(ConsoleEgress()) app.add_resource("machine", current_cap=2) app.add_service("wash", dist="constant", value=5) app.add_arrival( "cars", gap=generator({"gen": "integer", "bounds": [5, 9]}), key=lambda n: "Car {}".format(n - 1), initial=size, spawn="car", ) @app.task(name="car", seize="machine", next="washing") def car(task_id): """Takes a machine and keeps it.""" return {"event_type": "enters"} # The car keeps its machine until the wash, a task of its own, has finished @app.task(name="washing", wait={"task": "wash"}, release="machine") def washing(task_id): """Leaves once its wash has finished.""" return {"event_type": "leaves"} wash_payload = Template( { "event_type": "washed", "dirt_removed_pct": {"gen": "integer", "bounds": [50, 99]}, }, # The name gives the random sequence the YAML version's payload draws from name="tasks.wash", ) @app.task(name="wash", service_id="wash") def wash(task_id): """Washes the car.""" return wash_payload return app app = build() def run(model: SimulationContext = app) -> None: """Runs 20 simulation seconds.""" model.run(until=20) if __name__ == "__main__": logging.basicConfig(level=logging.INFO, format="%(levelname)s %(message)s") run() ``` The script wires the model by hand on `DynamicRealtimeEnvironment`, with SimPy's own processes. ```python """Carwash: SimPy's carwash.py example, low-level API. The low-level version of `builder/simpy/carwash_example.py`: SimPy's own processes on a `DynamicRealtimeEnvironment`. They publish with `publish_event` the records that the YAML and builder versions publish: each task's `queued` and `started`, its own events, and the number of the task's instance. A carwash has two washing machines. Four cars wait when it opens. A car takes a machine, keeps it while the wash runs (removing 50 to 99 percent of the dirt), and then leaves. SimPy's example counts minutes, and here each of its minutes is one second. So a car arrives every 5 to 9 seconds, a wash takes 5 seconds, and the run ends after 20 seconds, SimPy's 20 minutes. Each value is drawn from desflow's `Sampler`, from the random sequence the YAML and builder versions use for the same place, so the three versions publish the same records. Needs no containers. Runs unpaced and ends after 20 simulation seconds. """ import itertools import logging import simpy from desflow import ConsoleEgress, DynamicRealtimeEnvironment, Sampler NUM_MACHINES = 2 WASHTIME = 5 UNTIL = 20 WASH = "Carwash.service.wash" # the service that the wash's started record names def build(env: DynamicRealtimeEnvironment, size: int = 4) -> None: """Starts the carwash on `env`, with `size` cars waiting when it opens.""" sampler = Sampler(seed=42) gaps = sampler.generator("arrivals.cars.gap") dirt = sampler.generator("tasks.wash.payload.dirt_removed_pct") machine = simpy.Resource(env, NUM_MACHINES) numbers = {task: itertools.count() for task in ("car", "washing", "wash")} def publish(name, task, number, value): env.publish_event(name, value, task=task, instance=number) def wash(name): number = next(numbers["wash"]) publish( name, "wash", number, { "path_id": WASH, "sim_id": "Carwash", "service": "wash", "status": "started", }, ) yield env.timeout(WASHTIME) removed = int(dirt.integers(50, 100)) publish( name, "wash", number, {"event_type": "washed", "dirt_removed_pct": removed} ) def car(name): number = next(numbers["car"]) with machine.request() as request: publish(name, "car", number, {"status": "queued"}) yield request publish(name, "car", number, {"status": "started"}) publish(name, "car", number, {"event_type": "enters"}) # The car keeps its machine until the wash has finished waiting = next(numbers["washing"]) publish(name, "washing", waiting, {"status": "queued"}) yield env.process(wash(name)) publish(name, "washing", waiting, {"status": "started"}) publish(name, "washing", waiting, {"event_type": "leaves"}) def setup(): for i in range(size): env.process(car(f"Car {i}")) i = size while True: yield env.timeout(int(gaps.integers(5, 10))) env.process(car(f"Car {i}")) i += 1 env.process(setup()) def run() -> None: """Runs 20 simulation seconds.""" env = DynamicRealtimeEnvironment(factor=0) env.setup_egress([ConsoleEgress()]) build(env) try: env.run(until=UNTIL) finally: env.teardown() if __name__ == "__main__": logging.basicConfig(level=logging.INFO, format="%(levelname)s %(message)s") run() ``` This is SimPy 4.1.2's `carwash.py`, with SimPy's licence notice added at the top and comment lines that mark the pieces shown above. Run with Python, it prints the output shown under Check the Result. ```python # SimPy 4.1.2, docs/examples/code/carwash.py, under SimPy's licence (LICENSE.rst): # # The MIT License (MIT) # # Copyright (c) 2013 Ontje Lünsdorf and Stefan Scherfke (also see AUTHORS.txt) # # Permission is hereby granted, free of charge, to any person obtaining a copy of # this software and associated documentation files (the "Software"), to deal in # the Software without restriction, including without limitation the rights to # use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of # the Software, and to permit persons to whom the Software is furnished to do so, # subject to the following conditions: # # The above copyright notice and this permission notice shall be included in all # copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS # FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR # COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER # IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN # CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. """ Carwash example. Covers: - Waiting for other processes - Resources: Resource Scenario: A carwash has a limited number of washing machines and defines a washing processes that takes some (random) time. Car processes arrive at the carwash at a random time. If one washing machine is available, they start the washing process and wait for it to finish. If not, they wait until they can use one. """ import itertools import random import simpy # fmt: off RANDOM_SEED = 42 NUM_MACHINES = 2 # Number of machines in the carwash WASHTIME = 5 # Minutes it takes to clean a car T_INTER = 7 # Create a car every ~7 minutes SIM_TIME = 20 # Simulation time in minutes # fmt: on class Carwash: """A carwash has a limited number of machines (``NUM_MACHINES``) to clean cars in parallel. Cars have to request one of the machines. When they got one, they can start the washing processes and wait for it to finish (which takes ``washtime`` minutes). """ def __init__(self, env, num_machines, washtime): self.env = env self.machine = simpy.Resource(env, num_machines) self.washtime = washtime def wash(self, car): """The washing processes. It takes a ``car`` processes and tries to clean it.""" yield self.env.timeout(self.washtime) pct_dirt = random.randint(50, 99) print(f"Carwash removed {pct_dirt}% of {car}'s dirt.") def car(env, name, cw): """The car process (each car has a ``name``) arrives at the carwash (``cw``) and requests a cleaning machine. It then starts the washing process, waits for it to finish and leaves to never come back ... """ print(f'{name} arrives at the carwash at {env.now:.2f}.') with cw.machine.request() as request: yield request print(f'{name} enters the carwash at {env.now:.2f}.') yield env.process(cw.wash(name)) print(f'{name} leaves the carwash at {env.now:.2f}.') def setup(env, num_machines, washtime, t_inter): """Create a carwash, a number of initial cars and keep creating cars approx. every ``t_inter`` minutes.""" # Create the carwash carwash = Carwash(env, num_machines, washtime) car_count = itertools.count() # Create 4 initial cars for _ in range(4): env.process(car(env, f'Car {next(car_count)}', carwash)) # Create more cars while the simulation is running while True: yield env.timeout(random.randint(t_inter - 2, t_inter + 2)) env.process(car(env, f'Car {next(car_count)}', carwash)) # Setup and start the simulation print('Carwash') print('Check out http://youtu.be/fXXmeP9TvBg while simulating ... ;-)') random.seed(RANDOM_SEED) # This helps to reproduce the results # Create an environment and start the setup process env = simpy.Environment() env.process(setup(env, NUM_MACHINES, WASHTIME, T_INTER)) # Execute! env.run(until=SIM_TIME) ``` ______________________________________________________________________ ## Sources - [SimPy 4.1.2, Carwash](https://simpy.readthedocs.io/en/4.1.2/examples/carwash.html): the original code and its output. - [SimPy's licence](https://gitlab.com/team-simpy/simpy/-/blob/master/LICENSE.rst): MIT, Copyright (c) 2013 Ontje Lünsdorf and Stefan Scherfke. The SimPy file above carries this notice. - [`examples/` in the desflow repository](https://github.com/jaehyeon-kim/desflow/tree/v1.3.0/examples): the three versions in desflow, under `simpy/` in each folder. # Machine Shop Ten machines make parts and break down, and one repairman repairs them before doing other jobs. This is SimPy's Machine Shop example, written in desflow. ______________________________________________________________________ ## Before You Start SimPy's shop has 10 machines. Each makes parts without end. A part takes a normal time with a mean of 10 minutes and a standard deviation of 2, never below 0. Each machine breaks down after an exponential time with a mean of 300 minutes, unless it is already broken. A broken machine waits for the one repairman, at priority 1, for a 30 minute repair, and then finishes its part. Between repairs the repairman does other jobs of 30 minutes at priority 2. A repair preempts such a job, and the job resumes afterwards. The run lasts 4 weeks, which is 40320 minutes. desflow reads each of SimPy's minutes as one second. SimPy breaks a machine by calling `interrupt` on the process that makes parts. The repair is then a request for the repairman, who is a resource that the other jobs use too. The example writes the breakdowns as tasks, so that the repair is an ordinary request at priority 1: each machine has a `break_loop` task that waits for the next failure and interrupts the machine's `part` task, and the `part` task starts the repair when it is interrupted. The example needs only desflow, which each Quick Start in [Run It](#run-it) installs, and no other service. `desflow examples get simpy-machine-shop --api yaml` downloads it, as [Get an Example](https://jaehyeon.me/desflow/latest/cli/#get-an-example) shows. [SimPy Examples](https://jaehyeon.me/desflow/latest/simpy/examples/index.md) says how these pages read SimPy's times and numbers. SimPy's own page for the example is [on its documentation site](https://simpy.readthedocs.io/en/4.1.2/examples/machine_shop.html). ______________________________________________________________________ ## Steps ### Times Are Drawn SimPy draws the times with two functions, one for the time of a part and one for the time to a failure. desflow draws each time where it is used: the part time on the `part` task and the time to a failure on the `break_loop` task, both shown in the next step. The shop's own settings come first. ```python def time_per_part(): """Return actual processing time for a concrete part.""" t = random.normalvariate(PT_MEAN, PT_SIGMA) # The normalvariate can be negative, but we want only positive times. while t <= 0: t = random.normalvariate(PT_MEAN, PT_SIGMA) return t def time_to_failure(): """Return time until next failure for a machine.""" return random.expovariate(BREAK_MEAN) ``` `repairman` is a resource with one unit that serves a priority queue and lets a request of higher priority preempt the unit's user. `repair_time` is a service of 30 seconds. `parts_made` counts the parts of each machine, and `target` names the machine that a failure breaks. ```yaml variables: target: -1 parts_made: {} resources: repairman: {current_cap: 1, queue: priority, preempt: true} services: repair_time: {dist: constant, value: 30} ``` `add_resource`, `add_variable` and `add_service` declare the same parts. ```python app.add_resource("repairman", current_cap=1, queue="priority", preempt=True) app.add_variable("target", -1) app.add_variable("parts_made", {}) app.add_service("repair_time", dist="constant", value=30) ``` The low-level version has SimPy's `PreemptiveResource` for the repairman, and a `DistributionConfig` for each of the two times, so that it draws from the same streams as the other versions. ```python sampler = Sampler(seed=42) part = DistributionConfig(dist="truncated_normal", mean=10, std=2, low=0) part.stream = "tasks.part.service_time" # the sequence the blueprint draws from failure = DistributionConfig(dist="exponential", rate=0.0033333333333333335) failure.stream = "tasks.break_loop.wait.timeout" repairman = simpy.PreemptiveResource(env, capacity=1) names: dict = {} # each machine's process, by the name its records carry numbers = {task: itertools.count() for task in TASKS} ``` ### Machine Works and Breaks SimPy's `Machine` class makes parts in a loop. A second process, `break_machine`, interrupts the first after each failure time unless the machine is already broken. The interrupted machine asks for the repairman at priority 1, repairs, and goes on with the time it had left. ```python class Machine: """A machine produces parts and may get broken every now and then. If it breaks, it requests a *repairman* and continues the production after the it is repaired. A machine has a *name* and a number of *parts_made* thus far. """ def __init__(self, env, name, repairman): self.env = env self.name = name self.parts_made = 0 self.broken = False # Start "working" and "break_machine" processes for this machine. self.process = env.process(self.working(repairman)) env.process(self.break_machine()) def working(self, repairman): """Produce parts as long as the simulation runs. While making a part, the machine may break multiple times. Request a repairman when this happens. """ while True: # Start making a new part done_in = time_per_part() while done_in: start = self.env.now try: # Working on the part yield self.env.timeout(done_in) done_in = 0 # Set to 0 to exit while loop. except simpy.Interrupt: self.broken = True done_in -= self.env.now - start # How much time left? # Request a repairman. This will preempt its "other_job". with repairman.request(priority=1) as req: yield req yield self.env.timeout(REPAIR_TIME) self.broken = False # Part is done. self.parts_made += 1 def break_machine(self): """Break the machine every now and then.""" while True: yield self.env.timeout(time_to_failure()) if not self.broken: # Only break the machine if it is currently working. self.process.interrupt() ``` `machines` starts ten machines at time 0. `start_machine` starts each machine's `break_loop` and goes to `part`. `part` takes a truncated normal time and repeats with `next: part`. With `on_interrupt: resume` an interrupted part keeps the time it had left, and `on_interrupt_run: begin_repair` starts the repair. `repair` asks for the repairman at priority 1. `break_loop` waits an exponential time, and then interrupts the `part` of its machine, if that machine is not broken. ```yaml machines: initial: 10 spawn: start_machine key: {gen: sequence, format: "Machine {}"} attributes: id: {gen: sequence} parts_made: 0 broken: 0 ``` ```yaml start_machine: payload: {event_type: machine_started} spawn: {task: break_loop, copy_attributes: true} next: part part: service_time: {gen: sample, dist: truncated_normal, mean: 10, std: 2, low: 0} on_interrupt: resume on_interrupt_run: begin_repair set: parts_made: {gen: expr, expr: "attr.parts_made + 1"} on: - path: MachineShop.variables.parts_made value: gen: expr expr: "set_key(registry['MachineShop.variables.parts_made'], process.key, get_key(registry['MachineShop.variables.parts_made'], process.key, 0) + 1)" payload: {event_type: part_made} next: part begin_repair: payload: {event_type: broken} set: {broken: 1} next: repair repair: resource: repairman priority: 1 service: repair_time set: {broken: 0} payload: {event_type: repaired} # The machine's failures: one wait for each, then an interrupt of its part break_loop: wait: timeout: {gen: sample, dist: exponential, rate: 0.0033333333333333335} payload: {event_type: tick} on: - path: MachineShop.variables.target value: {gen: expr, expr: "attr.id"} - interrupt: task: part where: "attr.id == registry['MachineShop.variables.target'] and attr.broken == 0" next: break_loop ``` The same tasks, with the same keys on `add_task`. ```python app.add_initial_arrival( "machines", size, key=lambda n: "Machine {}".format(n - 1), attributes={"id": generator({"gen": "sequence"}), "parts_made": 0, "broken": 0}, spawn="start_machine", ) ``` ```python @app.task( name="start_machine", spawn={"task": "break_loop", "copy_attributes": True}, next="part", ) def start_machine(task_id): """Starts the machine and its failures.""" return {"event_type": "machine_started"} @app.task( name="part", service_time=generator( { "gen": "sample", "dist": "truncated_normal", "mean": 10, "std": 2, "low": 0, } ), on_interrupt="resume", on_interrupt_run="begin_repair", set={"parts_made": generator({"gen": "expr", "expr": "attr.parts_made + 1"})}, on=[ { "path": "MachineShop.variables.parts_made", "value": generator( { "gen": "expr", "expr": "set_key(registry['MachineShop.variables.parts_made'], process.key, get_key(registry['MachineShop.variables.parts_made'], process.key, 0) + 1)", } ), } ], next="part", ) def part(task_id): """Makes a part.""" return {"event_type": "part_made"} @app.task(name="begin_repair", set={"broken": 1}, next="repair") def begin_repair(task_id): """Marks the machine broken.""" return {"event_type": "broken"} @app.task( name="repair", resource_id="repairman", priority=1, service_id="repair_time", set={"broken": 0}, ) def repair(task_id): """Repairs the machine.""" return {"event_type": "repaired"} # The machine's failures: one wait for each, then an interrupt of its part @app.task( name="break_loop", wait={ "timeout": generator( {"gen": "sample", "dist": "exponential", "rate": 0.0033333333333333335} ) }, on=[ { "path": "MachineShop.variables.target", "value": generator({"gen": "expr", "expr": "attr.id"}), }, { "interrupt": { "task": "part", "where": "attr.id == registry['MachineShop.variables.target'] and attr.broken == 0", } }, ], next="break_loop", ) def break_loop(task_id): """Breaks the machine down.""" return {"event_type": "tick"} ``` `Machine` is SimPy's class. Its `working` method catches the `Interrupt`, publishes the records and calls `repair`. ```python class Machine: """A machine that makes parts and breaks down now and then.""" def __init__(self, name, number): self.name = name self.number = number self.broken = False self.process = env.process(self.working()) names[self.process] = name def working(self): env.process(self.break_machine()) started = {"event_type": "machine_started"} publish(self.name, "start_machine", next(numbers["start_machine"]), started) while True: making = next(numbers["part"]) publish(self.name, "part", making, {"status": "started"}) done_in = sampler.sample(part) while done_in: start = env.now try: yield env.timeout(done_in) done_in = 0 except simpy.Interrupt: interrupted = {"status": "interrupted", "cause": None} publish(self.name, "part", making, interrupted) broken = {"event_type": "broken"} publish( self.name, "begin_repair", next(numbers["begin_repair"]), broken, ) self.broken = True done_in -= env.now - start yield from self.repair() publish(self.name, "part", making, {"status": "resumed"}) publish(self.name, "part", making, {"event_type": "part_made"}) def repair(self): number = next(numbers["repair"]) publish( self.name, "repair", number, {"path_id": REPAIR, **REPAIR_NAMES, "status": "queued"}, ) # The repair goes before the repairman's other jobs with repairman.request(priority=1) as req: yield req publish( self.name, "repair", number, {"path_id": REPAIR, **REPAIR_NAMES, "status": "started"}, ) yield env.timeout(REPAIR_TIME) publish(self.name, "repair", number, {"event_type": "repaired"}) self.broken = False def break_machine(self): name = f"break_loop-{self.number + 1}" while True: number = next(numbers["break_loop"]) publish(name, "break_loop", number, {"status": "queued"}) yield env.timeout(sampler.sample(failure)) publish(name, "break_loop", number, {"status": "started"}) publish(name, "break_loop", number, {"event_type": "tick"}) if not self.broken: self.process.interrupt() ``` ### Repairman Does Other Jobs SimPy's `other_jobs` asks for the repairman at priority 2 and works on a 30 minute job. A repair preempts it, and the job resumes with the time it had left. ```python def other_jobs(env, repairman): """The repairman's other (unimportant) job.""" while True: # Start a new job done_in = JOB_DURATION while done_in: # Retry the job until it is done. # Its priority is lower than that of machine repairs. with repairman.request(priority=2) as req: yield req start = env.now try: yield env.timeout(done_in) done_in = 0 except simpy.Interrupt: done_in -= env.now - start ``` The arrival `others` starts one `other_job` task at time 0. The task asks for the repairman at priority 2, takes 30 seconds, resumes after a preemption with `on_interrupt: resume`, and starts again with `next: other_job`. ```yaml others: {initial: 1, spawn: other_job} ``` ```yaml other_job: resource: repairman priority: 2 service_time: 30 on_interrupt: resume payload: {event_type: other_done} next: other_job ``` `add_initial_arrival` starts the task, and the task takes the same keys. ```python app.add_initial_arrival("others", 1, spawn="other_job") ``` ```python @app.task( name="other_job", resource_id="repairman", priority=2, service_time=30, on_interrupt="resume", next="other_job", ) def other_job(task_id): """Does one of the repairman's other jobs.""" return {"event_type": "other_done"} ``` `other_jobs` is SimPy's function. The last block starts the ten machines and the repairman's jobs. ```python def other_jobs(name): while True: number = next(numbers["other_job"]) publish(name, "other_job", number, {"status": "queued"}) done_in = JOB_DURATION status = "started" while done_in: with repairman.request(priority=2) as req: yield req publish(name, "other_job", number, {"status": status}) start = env.now try: yield env.timeout(done_in) done_in = 0 except simpy.Interrupt as interrupt: preempted = interrupt.cause publish( name, "other_job", number, { "status": "preempted", "resource": "repairman", "preempted_by": names[preempted.by], "usage_since": preempted.usage_since, }, ) done_in -= env.now - start status = "resumed" publish(name, "other_job", number, {"event_type": "other_done"}) ``` ```python for number in range(size): Machine(f"Machine {number}", number) env.process(other_jobs("others-1")) ``` ### Run It `desflow run` loads the blueprint and runs it unpaced, because it sets `factor: 0`. Each record is printed to the terminal. **Quick Start** `desflow examples get` downloads the example at the release you install, into a folder of its own. Pick uv or pip: ```bash # 1. Install uv tool install desflow # 2. Download the example desflow examples get simpy-machine-shop --api yaml cd simpy-machine-shop/yaml # 3. Run it desflow run machine_shop.yaml ``` ```bash # 1. Install pip install desflow # 2. Download the example desflow examples get simpy-machine-shop --api yaml cd simpy-machine-shop/yaml # 3. Run it desflow run machine_shop.yaml ``` The script builds the model with the builder API, runs it unpaced, and prints each record to the terminal. **Quick Start** `desflow examples get` downloads the example at the release you install, into a folder of its own. Pick uv or pip: ```bash # 1. Install uv tool install desflow # 2. Download the example desflow examples get simpy-machine-shop --api builder cd simpy-machine-shop/builder # 3. Run it uv run --no-project --with desflow machine_shop_example.py ``` ```bash # 1. Install pip install desflow # 2. Download the example desflow examples get simpy-machine-shop --api builder cd simpy-machine-shop/builder # 3. Run it python machine_shop_example.py ``` The script wires the model by hand on `DynamicRealtimeEnvironment`, runs it unpaced, and prints each record to the terminal. **Quick Start** `desflow examples get` downloads the example at the release you install, into a folder of its own. Pick uv or pip: ```bash # 1. Install uv tool install desflow # 2. Download the example desflow examples get simpy-machine-shop --api low-level cd simpy-machine-shop/low-level # 3. Run it uv run --no-project --with desflow machine_shop_example.py ``` ```bash # 1. Install pip install desflow # 2. Download the example desflow examples get simpy-machine-shop --api low-level cd simpy-machine-shop/low-level # 3. Run it python machine_shop_example.py ``` ______________________________________________________________________ ## Check the Result In the 40320 seconds the ten machines make 33906 parts. Machine 8 makes the most, 3494, and Machine 9 the fewest, 3284. In SimPy's output, below, the machines make between 3185 and 3387 parts each. 1040 machines break down and 1039 repairs finish, because the last repair is still running when the run ends. The repairman finishes 304 other jobs, and a repair preempts a job 269 times. SimPy's example does not print these counts. Here each one is a record with the machine's key, and the preempted job's record names the repair that preempted it. desflow draws each random value from its own stream, named by the place where the value is used, such as `tasks.part.service_time`. A seed of 42 therefore gives different numbers from SimPy's `random.seed(42)`. The system is the same. The figures are not. ```text Machine shop Machine shop results after 4 weeks Machine 0 made 3251 parts. Machine 1 made 3273 parts. Machine 2 made 3242 parts. Machine 3 made 3343 parts. Machine 4 made 3387 parts. Machine 5 made 3244 parts. Machine 6 made 3269 parts. Machine 7 made 3185 parts. Machine 8 made 3302 parts. Machine 9 made 3279 parts. ``` The three versions in desflow print the same records, which [a test](https://github.com/jaehyeon-kim/desflow/blob/v1.3.0/tests/docs/test_example_twins.py) checks by running each version unpaced. Each record has `sim_ts`, the simulation time, and a key for the entity it belongs to. The statistics and the parameters that a live run can change are in the same stream, which SimPy's file does not have. ______________________________________________________________________ ## Full Files Full files The blueprint is `machine_shop.yaml`. ```yaml # Machine Shop: SimPy's machine_shop.py example, in YAML. # # The YAML version of machine_shop_example.py, which --api builder downloads. A shop # has ten machines, each making parts without end; a part's time is normal with # standard deviation 2, never below 0. Each machine breaks down after an exponential # time, unless it is already broken. A broken machine waits for the one repairman, at # priority 1, for its repair, and then finishes its part. Between repairs the # repairman does other jobs at priority 2, which a repair preempts and which resume # afterwards. # # SimPy's example counts minutes, and here each of its minutes is one second. So a # part takes about 10 seconds, a machine breaks down about every 300 seconds, a repair # and another job each take 30 seconds, and the run ends after 40320 seconds, SimPy's # four weeks. Each value is drawn from desflow's random sequence for its place in the # file, so the numbers differ from those SimPy prints. # # The breakdowns are written as tasks: each machine's `break_loop` waits for the # next failure and interrupts the machine's `part`, whose `on_interrupt_run` starts the # repair. `MachineShop.variables.parts_made` counts the parts of each machine. # # Needs no containers. Runs unpaced and ends after 40320 simulation seconds. # Run it from its folder with: desflow run machine_shop.yaml simulation: {sim_id: MachineShop, factor: 0, random_seed: 42} egress: - {type: Console} variables: target: -1 parts_made: {} resources: repairman: {current_cap: 1, queue: priority, preempt: true} services: repair_time: {dist: constant, value: 30} arrivals: machines: initial: 10 spawn: start_machine key: {gen: sequence, format: "Machine {}"} attributes: id: {gen: sequence} parts_made: 0 broken: 0 others: {initial: 1, spawn: other_job} tasks: start_machine: payload: {event_type: machine_started} spawn: {task: break_loop, copy_attributes: true} next: part part: service_time: {gen: sample, dist: truncated_normal, mean: 10, std: 2, low: 0} on_interrupt: resume on_interrupt_run: begin_repair set: parts_made: {gen: expr, expr: "attr.parts_made + 1"} on: - path: MachineShop.variables.parts_made value: gen: expr expr: "set_key(registry['MachineShop.variables.parts_made'], process.key, get_key(registry['MachineShop.variables.parts_made'], process.key, 0) + 1)" payload: {event_type: part_made} next: part begin_repair: payload: {event_type: broken} set: {broken: 1} next: repair repair: resource: repairman priority: 1 service: repair_time set: {broken: 0} payload: {event_type: repaired} # The machine's failures: one wait for each, then an interrupt of its part break_loop: wait: timeout: {gen: sample, dist: exponential, rate: 0.0033333333333333335} payload: {event_type: tick} on: - path: MachineShop.variables.target value: {gen: expr, expr: "attr.id"} - interrupt: task: part where: "attr.id == registry['MachineShop.variables.target'] and attr.broken == 0" next: break_loop other_job: resource: repairman priority: 2 service_time: 30 on_interrupt: resume payload: {event_type: other_done} next: other_job run: {until: 40320} ``` The script builds the model with the builder API. ```python """Machine Shop: SimPy's machine_shop.py example, builder API. A shop has ten machines, each making parts without end; a part's time is normal with standard deviation 2, never below 0. Each machine breaks down after an exponential time, unless it is already broken. A broken machine waits for the one repairman, at priority 1, for its repair, and then finishes its part. Between repairs the repairman does other jobs at priority 2, which a repair preempts and which resume afterwards. SimPy's example counts minutes, and here each of its minutes is one second. So a part takes about 10 seconds, a machine breaks down about every 300 seconds, a repair and another job each take 30 seconds, and the run ends after 40320 seconds, SimPy's four weeks. Each value is drawn from desflow's random sequence for its place in the model, so the numbers differ from those SimPy prints. The breakdowns are written as tasks: each machine's `break_loop` waits for the next failure and interrupts the machine's `part`, whose `on_interrupt_run` starts the repair. `MachineShop.variables.parts_made` counts the parts of each machine. Needs no containers. Runs unpaced and ends after 40320 simulation seconds. """ import logging from desflow import ConsoleEgress, SimulationContext from desflow.values import generator def build(size: int = 10) -> SimulationContext: """Builds the shop, with `size` machines.""" app = SimulationContext(sim_id="MachineShop", factor=0, random_seed=42) app.add_egress(ConsoleEgress()) app.add_resource("repairman", current_cap=1, queue="priority", preempt=True) app.add_variable("target", -1) app.add_variable("parts_made", {}) app.add_service("repair_time", dist="constant", value=30) app.add_initial_arrival( "machines", size, key=lambda n: "Machine {}".format(n - 1), attributes={"id": generator({"gen": "sequence"}), "parts_made": 0, "broken": 0}, spawn="start_machine", ) app.add_initial_arrival("others", 1, spawn="other_job") @app.task( name="start_machine", spawn={"task": "break_loop", "copy_attributes": True}, next="part", ) def start_machine(task_id): """Starts the machine and its failures.""" return {"event_type": "machine_started"} @app.task( name="part", service_time=generator( { "gen": "sample", "dist": "truncated_normal", "mean": 10, "std": 2, "low": 0, } ), on_interrupt="resume", on_interrupt_run="begin_repair", set={"parts_made": generator({"gen": "expr", "expr": "attr.parts_made + 1"})}, on=[ { "path": "MachineShop.variables.parts_made", "value": generator( { "gen": "expr", "expr": "set_key(registry['MachineShop.variables.parts_made'], process.key, get_key(registry['MachineShop.variables.parts_made'], process.key, 0) + 1)", } ), } ], next="part", ) def part(task_id): """Makes a part.""" return {"event_type": "part_made"} @app.task(name="begin_repair", set={"broken": 1}, next="repair") def begin_repair(task_id): """Marks the machine broken.""" return {"event_type": "broken"} @app.task( name="repair", resource_id="repairman", priority=1, service_id="repair_time", set={"broken": 0}, ) def repair(task_id): """Repairs the machine.""" return {"event_type": "repaired"} # The machine's failures: one wait for each, then an interrupt of its part @app.task( name="break_loop", wait={ "timeout": generator( {"gen": "sample", "dist": "exponential", "rate": 0.0033333333333333335} ) }, on=[ { "path": "MachineShop.variables.target", "value": generator({"gen": "expr", "expr": "attr.id"}), }, { "interrupt": { "task": "part", "where": "attr.id == registry['MachineShop.variables.target'] and attr.broken == 0", } }, ], next="break_loop", ) def break_loop(task_id): """Breaks the machine down.""" return {"event_type": "tick"} @app.task( name="other_job", resource_id="repairman", priority=2, service_time=30, on_interrupt="resume", next="other_job", ) def other_job(task_id): """Does one of the repairman's other jobs.""" return {"event_type": "other_done"} return app app = build() def run(model: SimulationContext = app) -> None: """Runs 40320 seconds, SimPy's four weeks counted in minutes.""" model.run(until=4 * 7 * 24 * 60) if __name__ == "__main__": logging.basicConfig(level=logging.INFO, format="%(levelname)s %(message)s") run() ``` The script wires the model by hand on `DynamicRealtimeEnvironment`, with SimPy's own processes. ```python """Machine Shop: SimPy's machine_shop.py example, low-level API. The low-level version of `builder/simpy/machine_shop_example.py`: SimPy's own `Machine` and `other_jobs` on a `DynamicRealtimeEnvironment`. They publish with `publish_event` the records that the YAML and builder versions publish: each task's `queued`, `started`, `interrupted`, `preempted` and `resumed`, its own events, and the number of the task's instance. A shop has ten machines, each making parts without end. Each machine breaks down now and then, unless it is already broken. A broken machine waits for the one repairman, at priority 1, and then finishes its part. Between repairs the repairman does other jobs at priority 2, which a repair preempts and which resume afterwards. SimPy's example counts minutes, and here each of its minutes is one second. So a part takes about 10 seconds, a machine breaks down about every 300 seconds, a repair and another job each take 30 seconds, and the run ends after 40320 seconds, SimPy's four weeks. Each value is drawn from desflow's `Sampler`, from the random sequence the YAML and builder versions use for the same place, so the three versions publish the same records. Needs no containers. Runs unpaced and ends after 40320 simulation seconds. """ import itertools import logging import simpy from desflow import ( ConsoleEgress, DistributionConfig, DynamicRealtimeEnvironment, Sampler, ) REPAIR_TIME = 30 JOB_DURATION = 30 NUM_MACHINES = 10 UNTIL = 4 * 7 * 24 * 60 # SimPy's four weeks in minutes, read as seconds REPAIR = "MachineShop.service.repair_time" # the service a repair's records name REPAIR_NAMES = {"sim_id": "MachineShop", "service": "repair_time"} TASKS = ("start_machine", "part", "begin_repair", "repair", "break_loop", "other_job") def build(env: DynamicRealtimeEnvironment, size: int = NUM_MACHINES) -> None: """Starts `size` machines and the repairman's other jobs on `env`.""" sampler = Sampler(seed=42) part = DistributionConfig(dist="truncated_normal", mean=10, std=2, low=0) part.stream = "tasks.part.service_time" # the sequence the blueprint draws from failure = DistributionConfig(dist="exponential", rate=0.0033333333333333335) failure.stream = "tasks.break_loop.wait.timeout" repairman = simpy.PreemptiveResource(env, capacity=1) names: dict = {} # each machine's process, by the name its records carry numbers = {task: itertools.count() for task in TASKS} def publish(name, task, number, value): env.publish_event(name, value, task=task, instance=number) class Machine: """A machine that makes parts and breaks down now and then.""" def __init__(self, name, number): self.name = name self.number = number self.broken = False self.process = env.process(self.working()) names[self.process] = name def working(self): env.process(self.break_machine()) started = {"event_type": "machine_started"} publish(self.name, "start_machine", next(numbers["start_machine"]), started) while True: making = next(numbers["part"]) publish(self.name, "part", making, {"status": "started"}) done_in = sampler.sample(part) while done_in: start = env.now try: yield env.timeout(done_in) done_in = 0 except simpy.Interrupt: interrupted = {"status": "interrupted", "cause": None} publish(self.name, "part", making, interrupted) broken = {"event_type": "broken"} publish( self.name, "begin_repair", next(numbers["begin_repair"]), broken, ) self.broken = True done_in -= env.now - start yield from self.repair() publish(self.name, "part", making, {"status": "resumed"}) publish(self.name, "part", making, {"event_type": "part_made"}) def repair(self): number = next(numbers["repair"]) publish( self.name, "repair", number, {"path_id": REPAIR, **REPAIR_NAMES, "status": "queued"}, ) # The repair goes before the repairman's other jobs with repairman.request(priority=1) as req: yield req publish( self.name, "repair", number, {"path_id": REPAIR, **REPAIR_NAMES, "status": "started"}, ) yield env.timeout(REPAIR_TIME) publish(self.name, "repair", number, {"event_type": "repaired"}) self.broken = False def break_machine(self): name = f"break_loop-{self.number + 1}" while True: number = next(numbers["break_loop"]) publish(name, "break_loop", number, {"status": "queued"}) yield env.timeout(sampler.sample(failure)) publish(name, "break_loop", number, {"status": "started"}) publish(name, "break_loop", number, {"event_type": "tick"}) if not self.broken: self.process.interrupt() def other_jobs(name): while True: number = next(numbers["other_job"]) publish(name, "other_job", number, {"status": "queued"}) done_in = JOB_DURATION status = "started" while done_in: with repairman.request(priority=2) as req: yield req publish(name, "other_job", number, {"status": status}) start = env.now try: yield env.timeout(done_in) done_in = 0 except simpy.Interrupt as interrupt: preempted = interrupt.cause publish( name, "other_job", number, { "status": "preempted", "resource": "repairman", "preempted_by": names[preempted.by], "usage_since": preempted.usage_since, }, ) done_in -= env.now - start status = "resumed" publish(name, "other_job", number, {"event_type": "other_done"}) for number in range(size): Machine(f"Machine {number}", number) env.process(other_jobs("others-1")) def run() -> None: """Runs 40320 seconds, SimPy's four weeks counted in minutes.""" env = DynamicRealtimeEnvironment(factor=0) env.setup_egress([ConsoleEgress()]) build(env) try: env.run(until=UNTIL) finally: env.teardown() if __name__ == "__main__": logging.basicConfig(level=logging.INFO, format="%(levelname)s %(message)s") run() ``` This is SimPy 4.1.2's `machine_shop.py`, with SimPy's licence notice added at the top and comment lines that mark the pieces shown above. Run with Python, it prints the output shown under Check the Result. ```python # SimPy 4.1.2, docs/examples/code/machine_shop.py, under SimPy's licence (LICENSE.rst): # # The MIT License (MIT) # # Copyright (c) 2013 Ontje Lünsdorf and Stefan Scherfke (also see AUTHORS.txt) # # Permission is hereby granted, free of charge, to any person obtaining a copy of # this software and associated documentation files (the "Software"), to deal in # the Software without restriction, including without limitation the rights to # use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of # the Software, and to permit persons to whom the Software is furnished to do so, # subject to the following conditions: # # The above copyright notice and this permission notice shall be included in all # copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS # FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR # COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER # IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN # CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. """ Machine shop example Covers: - Interrupts - Resources: PreemptiveResource Scenario: A workshop has *n* identical machines. A stream of jobs (enough to keep the machines busy) arrives. Each machine breaks down periodically. Repairs are carried out by one repairman. The repairman has other, less important tasks to perform, too. Broken machines preempt these tasks. The repairman continues them when he is done with the machine repair. The workshop works continuously. """ import random import simpy # fmt: off RANDOM_SEED = 42 PT_MEAN = 10.0 # Avg. processing time in minutes PT_SIGMA = 2.0 # Sigma of processing time MTTF = 300.0 # Mean time to failure in minutes BREAK_MEAN = 1 / MTTF # Param. for expovariate distribution REPAIR_TIME = 30.0 # Time it takes to repair a machine in minutes JOB_DURATION = 30.0 # Duration of other jobs in minutes NUM_MACHINES = 10 # Number of machines in the machine shop WEEKS = 4 # Simulation time in weeks SIM_TIME = WEEKS * 7 * 24 * 60 # Simulation time in minutes # fmt: on def time_per_part(): """Return actual processing time for a concrete part.""" t = random.normalvariate(PT_MEAN, PT_SIGMA) # The normalvariate can be negative, but we want only positive times. while t <= 0: t = random.normalvariate(PT_MEAN, PT_SIGMA) return t def time_to_failure(): """Return time until next failure for a machine.""" return random.expovariate(BREAK_MEAN) class Machine: """A machine produces parts and may get broken every now and then. If it breaks, it requests a *repairman* and continues the production after the it is repaired. A machine has a *name* and a number of *parts_made* thus far. """ def __init__(self, env, name, repairman): self.env = env self.name = name self.parts_made = 0 self.broken = False # Start "working" and "break_machine" processes for this machine. self.process = env.process(self.working(repairman)) env.process(self.break_machine()) def working(self, repairman): """Produce parts as long as the simulation runs. While making a part, the machine may break multiple times. Request a repairman when this happens. """ while True: # Start making a new part done_in = time_per_part() while done_in: start = self.env.now try: # Working on the part yield self.env.timeout(done_in) done_in = 0 # Set to 0 to exit while loop. except simpy.Interrupt: self.broken = True done_in -= self.env.now - start # How much time left? # Request a repairman. This will preempt its "other_job". with repairman.request(priority=1) as req: yield req yield self.env.timeout(REPAIR_TIME) self.broken = False # Part is done. self.parts_made += 1 def break_machine(self): """Break the machine every now and then.""" while True: yield self.env.timeout(time_to_failure()) if not self.broken: # Only break the machine if it is currently working. self.process.interrupt() def other_jobs(env, repairman): """The repairman's other (unimportant) job.""" while True: # Start a new job done_in = JOB_DURATION while done_in: # Retry the job until it is done. # Its priority is lower than that of machine repairs. with repairman.request(priority=2) as req: yield req start = env.now try: yield env.timeout(done_in) done_in = 0 except simpy.Interrupt: done_in -= env.now - start # Setup and start the simulation print('Machine shop') random.seed(RANDOM_SEED) # This helps to reproduce the results # Create an environment and start the setup process env = simpy.Environment() repairman = simpy.PreemptiveResource(env, capacity=1) machines = [Machine(env, f'Machine {i}', repairman) for i in range(NUM_MACHINES)] env.process(other_jobs(env, repairman)) # Execute! env.run(until=SIM_TIME) # Analysis/results print(f'Machine shop results after {WEEKS} weeks') for machine in machines: print(f'{machine.name} made {machine.parts_made} parts.') ``` ______________________________________________________________________ ## Sources - [SimPy 4.1.2, Machine Shop](https://simpy.readthedocs.io/en/4.1.2/examples/machine_shop.html): the original code and its output. - [SimPy's licence](https://gitlab.com/team-simpy/simpy/-/blob/master/LICENSE.rst): MIT, Copyright (c) 2013 Ontje Lünsdorf and Stefan Scherfke. The SimPy file above carries this notice. - [`examples/` in the desflow repository](https://github.com/jaehyeon-kim/desflow/tree/v1.3.0/examples): the three versions in desflow, under `simpy/` in each folder. # Movie Renege A ticket counter sells tickets for three films, and a film that sells out sends its queue away. This is SimPy's Movie Renege example, written in desflow. ______________________________________________________________________ ## Before You Start SimPy's theatre has one ticket counter and three films with 50 tickets each. A moviegoer arrives about every 0.5 minutes (exponential gaps), picks a film and 1 to 6 tickets, and joins the queue only while the film has tickets. At the counter, a moviegoer who asks for more tickets than are left argues for 0.5 minutes and leaves. Otherwise the sale takes 1 minute. When fewer than 2 tickets are left, the film is sold out and everyone still queueing for it leaves (reneges). The run lasts 120 minutes. desflow reads each of SimPy's minutes as one second. The example needs only desflow, which each Quick Start in [Run It](#run-it) installs, and no other service. `desflow examples get simpy-movie-renege --api yaml` downloads it, as [Get an Example](https://jaehyeon.me/desflow/latest/cli/#get-an-example) shows. [SimPy Examples](https://jaehyeon.me/desflow/latest/simpy/examples/index.md) says how these pages read SimPy's times and numbers. SimPy's own page for the example is [on its documentation site](https://simpy.readthedocs.io/en/4.1.2/examples/movie_renege.html). ______________________________________________________________________ ## Steps ### Theater SimPy's `theater` holds the counter, the tickets left for each film, the time each film sold out and the number of moviegoers who left each queue. ```python class Theater(NamedTuple): counter: simpy.Resource movies: List[str] available: Dict[str, int] sold_out: Dict[str, simpy.Event] when_sold_out: Dict[str, Optional[float]] num_renegers: Dict[str, int] ``` `available`, `when_sold_out` and `num_renegers` are variables that hold one number for each film. `counter` is a resource with one unit. `sold_out` is a signal family with one member for each film, and `once: true` makes a member fire one time. ```yaml variables: available: {Python Unchained: 50, Kill Process: 50, Pulp Implementation: 50} when_sold_out: {} num_renegers: {Python Unchained: 0, Kill Process: 0, Pulp Implementation: 0} resources: counter: {current_cap: 1} signals: sold_out: {family: true, once: true} ``` `add_resource`, `add_variable` and `add_signal` declare the same parts. ```python app.add_resource("counter", current_cap=1) app.add_variable("available", {movie: 50 for movie in MOVIES}) app.add_variable("when_sold_out", {}) app.add_variable("num_renegers", {movie: 0 for movie in MOVIES}) app.add_signal("sold_out", family=True, once=True) ``` The low-level version has SimPy's `simpy.Resource` for the counter, a dictionary for the tickets left and one `env.event()` for each film. ```python counter = simpy.Resource(env, capacity=1) available = {movie: TICKETS for movie in MOVIES} sold_out = {movie: env.event() for movie in MOVIES} numbers = {task: itertools.count() for task in TASKS} ``` ### Moviegoers Arrive SimPy's `customer_arrivals` starts a moviegoer after each exponential gap, with a random film and a number of tickets. ```python def customer_arrivals(env, theater): """Create new *moviegoers* until the sim time reaches 120.""" while True: yield env.timeout(random.expovariate(1 / 0.5)) movie = random.choice(theater.movies) num_tickets = random.randint(1, 6) if theater.available[movie]: env.process(moviegoer(env, movie, num_tickets, theater)) ``` The arrival `goers` has exponential gaps at the rate 2 a second. Each moviegoer has two attributes: `movie`, one of the three films, and `tickets`, an integer from 1 to 6. ```yaml arrivals: goers: dist: exponential rate: 2 spawn: moviegoer attributes: movie: gen: one_of choices: [Python Unchained, Kill Process, Pulp Implementation] tickets: {gen: integer, bounds: [1, 6]} ``` `add_arrival` takes the same `attributes`, written as generators. ```python app.add_arrival( "goers", "exponential", rate=2, attributes={ "movie": generator({"gen": "one_of", "choices": MOVIES}), "tickets": generator({"gen": "integer", "bounds": [1, 6]}), }, spawn="moviegoer", ) ``` `customer_arrivals` is SimPy's function. It draws the gap, the film and the number of tickets from desflow's `Sampler`. ```python def customer_arrivals(): for number in itertools.count(1): yield env.timeout(sampler.sample(gap)) movie = MOVIES[int(movie_choices.integers(len(MOVIES)))] num_tickets = int(ticket_counts.integers(1, 7)) env.process(moviegoer(f"goers-{number}", movie, num_tickets)) env.process(customer_arrivals()) ``` ### Moviegoer Waits or Leaves SimPy's `moviegoer` requests the counter. It waits for either its turn or the film to sell out. If the film sells out first, the moviegoer leaves. ```python def moviegoer(env, movie, num_tickets, theater): """A moviegoer tries to by a number of tickets (*num_tickets*) for a certain *movie* in a *theater*. If the movie becomes sold out, she leaves the theater. If she gets to the counter, she tries to buy a number of tickets. If not enough tickets are left, she argues with the teller and leaves. If at most one ticket is left after the moviegoer bought her tickets, the *sold out* event for this movie is triggered causing all remaining moviegoers to leave. """ with theater.counter.request() as my_turn: # Wait until it's our turn or until the movie is sold out result = yield my_turn | theater.sold_out[movie] # Check if it's our turn or if movie is sold out if my_turn not in result: theater.num_renegers[movie] += 1 return # Check if enough tickets left. if theater.available[movie] < num_tickets: # Moviegoer leaves after some discussion yield env.timeout(0.5) return # Buy tickets theater.available[movie] -= num_tickets if theater.available[movie] < SELLOUT_THRESHOLD: # Trigger the "sold out" event for the movie theater.sold_out[movie].succeed() theater.when_sold_out[movie] = env.now theater.available[movie] = 0 yield env.timeout(1) ``` `balk` stops a moviegoer from joining when the film has no tickets left. `open` places a request for the counter and calls it `slot`, and `wait: any` waits for the turn or for the `sold_out` signal of the moviegoer's film, whichever comes first. If the turn came first the moviegoer goes to `serve`. Otherwise it goes to `leave`, which cancels the request and counts a moviegoer who reneged. ```yaml moviegoer: balk: "registry['Movie.variables.available'][attr.movie] == 0" open: slot: {request: counter} wait: any: turn: {handle: slot} out: signal: {of: sold_out, key: "attr.movie"} payload: {event_type: at_counter} next: when: - {condition: "wait.turn.done", task: serve} default: leave leave: cancel: slot release: {handle: slot} payload: event_type: reneged movie: {gen: expr, expr: attr.movie} on: - path: Movie.variables.num_renegers value: gen: expr expr: "set_key(registry['Movie.variables.num_renegers'], attr.movie, get_key(registry['Movie.variables.num_renegers'], attr.movie, 0) + 1)" ``` The same two tasks, with `open`, `wait` and `next` as in the YAML. ```python @app.task( name="moviegoer", balk="registry['Movie.variables.available'][attr.movie] == 0", open={"slot": {"request": "counter"}}, wait={ "any": { "turn": {"handle": "slot"}, "out": {"signal": {"of": "sold_out", "key": "attr.movie"}}, } }, next={ "when": [{"condition": "wait.turn.done", "task": "serve"}], "default": "leave", }, ) def moviegoer(task_id): """Waits for the counter or for the movie to sell out.""" return {"event_type": "at_counter"} leave_payload = Template( {"event_type": "reneged", "movie": {"gen": "expr", "expr": "attr.movie"}}, name="leave", ) @app.task( name="leave", cancel="slot", release={"handle": "slot"}, on=[ { "path": "Movie.variables.num_renegers", "value": generator( { "gen": "expr", "expr": "set_key(registry['Movie.variables.num_renegers'], attr.movie, get_key(registry['Movie.variables.num_renegers'], attr.movie, 0) + 1)", } ), } ], ) def leave(task_id): """Leaves the queue: the movie sold out.""" return leave_payload ``` `moviegoer` is SimPy's function, with `turn | sold_out[movie]`. This block shows its first part, up to the moviegoer who leaves. ```python def moviegoer(name, movie, num_tickets): number = next(numbers["moviegoer"]) def publish(task, value, instance=None): """Publishes `value` as `instance` of `task`, or as a new instance.""" step = next(numbers[task]) if instance is None else instance env.publish_event(name, value, task=task, instance=step) return step if available[movie] == 0: # sold out: does not join the queue publish("moviegoer", {"status": "balked"}, number) return # The task's wait and the counter's request it opens each publish queued publish("moviegoer", {"status": "queued"}, number) publish("moviegoer", {"status": "queued"}, number) turn = counter.request() result = yield turn | sold_out[movie] if turn in result: # the request publishes started as it is granted publish("moviegoer", {"status": "started"}, number) publish("moviegoer", {"status": "started"}, number) publish("moviegoer", {"event_type": "at_counter"}, number) if turn not in result: # the movie sold out while it queued turn.cancel() if turn.triggered: counter.release(turn) publish("leave", {"event_type": "reneged", "movie": movie}) return ``` ### Counter Sells or Argues At the counter SimPy's `moviegoer` checks the tickets left. A moviegoer who asks for too many argues and leaves. Otherwise the tickets are bought, and the film is sold out when fewer than 2 are left. `serve` goes to `argue` when the film has fewer tickets left than the moviegoer asks for. `argue` takes 0.5 seconds and releases the counter. Otherwise `buy` takes the tickets from `available`, and `check` goes to `sold` when fewer than 2 are left. ```yaml serve: payload: {event_type: served} next: when: - condition: "registry['Movie.variables.available'][attr.movie] < attr.tickets" task: argue default: buy argue: service_time: 0.5 payload: {event_type: argued} release: {handle: slot} buy: payload: {event_type: bought} on: - path: Movie.variables.available value: gen: expr expr: "set_key(registry['Movie.variables.available'], attr.movie, registry['Movie.variables.available'][attr.movie] - attr.tickets)" next: check check: payload: {event_type: checked} next: when: - condition: "registry['Movie.variables.available'][attr.movie] < 2" task: sold default: finish ``` The tasks `serve`, `argue`, `buy` and `check`, with the same rules. ```python @app.task( name="serve", next={ "when": [ { "condition": "registry['Movie.variables.available'][attr.movie] < attr.tickets", "task": "argue", } ], "default": "buy", }, ) def serve(task_id): """Reaches the counter.""" return {"event_type": "served"} @app.task(name="argue", service_time=0.5, release={"handle": "slot"}) def argue(task_id): """Asks for more tickets than are left.""" return {"event_type": "argued"} @app.task( name="buy", on=[ { "path": "Movie.variables.available", "value": generator( { "gen": "expr", "expr": "set_key(registry['Movie.variables.available'], attr.movie, registry['Movie.variables.available'][attr.movie] - attr.tickets)", } ), } ], next="check", ) def buy(task_id): """Buys the tickets.""" return {"event_type": "bought"} @app.task( name="check", next={ "when": [ { "condition": "registry['Movie.variables.available'][attr.movie] < 2", "task": "sold", } ], "default": "finish", }, ) def check(task_id): """Checks how many tickets are left.""" return {"event_type": "checked"} ``` The middle of the same `moviegoer` function. ```python publish("serve", {"event_type": "served"}) if available[movie] < num_tickets: arguing = publish("argue", {"status": "started"}) yield env.timeout(0.5) publish("argue", {"event_type": "argued"}, arguing) counter.release(turn) return publish("buy", {"event_type": "bought"}) available[movie] -= num_tickets publish("check", {"event_type": "checked"}) ``` ### Film Sells Out When a film is sold out, SimPy's `moviegoer` fires the film's event, which sends the queue away, and records the time. The sale takes 1 minute and the counter is released. `sold` fires the `sold_out` signal of the film, which ends the wait of everyone queueing for it. It also records the time and sets the tickets left to 0, so later moviegoers balk. `finish` takes 1 second and releases the counter. ```yaml sold: payload: event_type: sold_out movie: {gen: expr, expr: attr.movie} on: - fire: signal: {of: sold_out, key: "attr.movie"} - path: Movie.variables.when_sold_out value: gen: expr expr: "set_key(registry['Movie.variables.when_sold_out'], attr.movie, t)" - path: Movie.variables.available value: gen: expr expr: "set_key(registry['Movie.variables.available'], attr.movie, 0)" next: finish finish: service_time: 1 payload: {event_type: done} release: {handle: slot} ``` The tasks `sold` and `finish`, with the same rules. ```python sold_payload = Template( {"event_type": "sold_out", "movie": {"gen": "expr", "expr": "attr.movie"}}, name="sold", ) @app.task( name="sold", on=[ {"fire": {"signal": {"of": "sold_out", "key": "attr.movie"}}}, { "path": "Movie.variables.when_sold_out", "value": generator( { "gen": "expr", "expr": "set_key(registry['Movie.variables.when_sold_out'], attr.movie, t)", } ), }, { "path": "Movie.variables.available", "value": generator( { "gen": "expr", "expr": "set_key(registry['Movie.variables.available'], attr.movie, 0)", } ), }, ], next="finish", ) def sold(task_id): """Sells the movie out, which sends its queue away.""" return sold_payload @app.task(name="finish", service_time=1, release={"handle": "slot"}) def finish(task_id): """Finishes the sale.""" return {"event_type": "done"} ``` The end of the same `moviegoer` function. ```python if available[movie] < 2: publish("sold", {"event_type": "sold_out", "movie": movie}) sold_out[movie].succeed() available[movie] = 0 finishing = publish("finish", {"status": "started"}) yield env.timeout(1) publish("finish", {"event_type": "done"}, finishing) counter.release(turn) ``` ### Run It `desflow run` loads the blueprint and runs it unpaced, because it sets `factor: 0`. Each record is printed to the terminal. **Quick Start** `desflow examples get` downloads the example at the release you install, into a folder of its own. Pick uv or pip: ```bash # 1. Install uv tool install desflow # 2. Download the example desflow examples get simpy-movie-renege --api yaml cd simpy-movie-renege/yaml # 3. Run it desflow run movie_renege.yaml ``` ```bash # 1. Install pip install desflow # 2. Download the example desflow examples get simpy-movie-renege --api yaml cd simpy-movie-renege/yaml # 3. Run it desflow run movie_renege.yaml ``` The script builds the model with the builder API, runs it unpaced, and prints each record to the terminal. **Quick Start** `desflow examples get` downloads the example at the release you install, into a folder of its own. Pick uv or pip: ```bash # 1. Install uv tool install desflow # 2. Download the example desflow examples get simpy-movie-renege --api builder cd simpy-movie-renege/builder # 3. Run it uv run --no-project --with desflow movie_renege_example.py ``` ```bash # 1. Install pip install desflow # 2. Download the example desflow examples get simpy-movie-renege --api builder cd simpy-movie-renege/builder # 3. Run it python movie_renege_example.py ``` The script wires the model by hand on `DynamicRealtimeEnvironment`, runs it unpaced, and prints each record to the terminal. **Quick Start** `desflow examples get` downloads the example at the release you install, into a folder of its own. Pick uv or pip: ```bash # 1. Install uv tool install desflow # 2. Download the example desflow examples get simpy-movie-renege --api low-level cd simpy-movie-renege/low-level # 3. Run it uv run --no-project --with desflow movie_renege_example.py ``` ```bash # 1. Install pip install desflow # 2. Download the example desflow examples get simpy-movie-renege --api low-level cd simpy-movie-renege/low-level # 3. Run it python movie_renege_example.py ``` ______________________________________________________________________ ## Check the Result `Pulp Implementation` sells out at 21.793 seconds, `Kill Process` at 41.793 seconds and `Python Unchained` at 44.293 seconds. 18 moviegoers leave the queue for `Python Unchained`, 17 for `Kill Process` and 9 for `Pulp Implementation`. 44 sales go through, and 197 moviegoers find their film sold out and do not join a queue. SimPy's output, below, has the films selling out at 38, 43 and 28 minutes, with 16, 5 and 5 moviegoers leaving. SimPy prints no count of moviegoers who find a film sold out. Here each one has a `balked` record. desflow draws each random value from its own stream, named by the place where the value is used, such as `arrivals.goers.attributes.tickets`. A seed of 42 therefore gives different numbers from SimPy's `random.seed(42)`. The system is the same. The figures are not. ```text Movie renege Movie "Python Unchained" sold out 38.0 minutes after ticket counter opening. Number of people leaving queue when film sold out: 16 Movie "Kill Process" sold out 43.0 minutes after ticket counter opening. Number of people leaving queue when film sold out: 5 Movie "Pulp Implementation" sold out 28.0 minutes after ticket counter opening. Number of people leaving queue when film sold out: 5 ``` The three versions in desflow print the same records, which [a test](https://github.com/jaehyeon-kim/desflow/blob/v1.3.0/tests/docs/test_example_twins.py) checks by running each version unpaced. Each record has `sim_ts`, the simulation time, and a key for the entity it belongs to. The statistics and the parameters that a live run can change are in the same stream, which SimPy's file does not have. ______________________________________________________________________ ## Full Files Full files The blueprint is `movie_renege.yaml`. ```yaml # Movie Renege: SimPy's movie_renege.py example, in YAML. # # The YAML version of movie_renege_example.py, which --api builder downloads. A movie # theatre has one ticket counter and three movies with 50 tickets each. A moviegoer # arrives at exponential gaps, picks a movie and 1 to 6 tickets, and does not join the # queue once the movie is sold out. At the counter, a moviegoer who asks for more # tickets than are left argues and leaves; otherwise the sale goes ahead. When fewer # than 2 tickets are left the movie is sold out, and everyone still queueing for it # leaves (reneged). # # SimPy's example counts minutes, and here each of its minutes is one second. So a # moviegoer arrives about every 0.5 seconds, an argument takes 0.5 seconds, a sale 1 # second, and the run ends after 120 seconds, SimPy's 120 minutes. Each value is drawn # from desflow's random sequence for its place in the file, so the numbers differ from # those SimPy prints. # # The counter is a request opened by the moviegoer and held across the tasks that # follow, and each movie's sold-out event is one member of the signal family # `sold_out`. # # Needs no containers. Runs unpaced and ends after 120 simulation seconds. # Run it from its folder with: desflow run movie_renege.yaml simulation: {sim_id: Movie, factor: 0, random_seed: 42} egress: - {type: Console} variables: available: {Python Unchained: 50, Kill Process: 50, Pulp Implementation: 50} when_sold_out: {} num_renegers: {Python Unchained: 0, Kill Process: 0, Pulp Implementation: 0} resources: counter: {current_cap: 1} signals: sold_out: {family: true, once: true} arrivals: goers: dist: exponential rate: 2 spawn: moviegoer attributes: movie: gen: one_of choices: [Python Unchained, Kill Process, Pulp Implementation] tickets: {gen: integer, bounds: [1, 6]} tasks: moviegoer: balk: "registry['Movie.variables.available'][attr.movie] == 0" open: slot: {request: counter} wait: any: turn: {handle: slot} out: signal: {of: sold_out, key: "attr.movie"} payload: {event_type: at_counter} next: when: - {condition: "wait.turn.done", task: serve} default: leave leave: cancel: slot release: {handle: slot} payload: event_type: reneged movie: {gen: expr, expr: attr.movie} on: - path: Movie.variables.num_renegers value: gen: expr expr: "set_key(registry['Movie.variables.num_renegers'], attr.movie, get_key(registry['Movie.variables.num_renegers'], attr.movie, 0) + 1)" serve: payload: {event_type: served} next: when: - condition: "registry['Movie.variables.available'][attr.movie] < attr.tickets" task: argue default: buy argue: service_time: 0.5 payload: {event_type: argued} release: {handle: slot} buy: payload: {event_type: bought} on: - path: Movie.variables.available value: gen: expr expr: "set_key(registry['Movie.variables.available'], attr.movie, registry['Movie.variables.available'][attr.movie] - attr.tickets)" next: check check: payload: {event_type: checked} next: when: - condition: "registry['Movie.variables.available'][attr.movie] < 2" task: sold default: finish sold: payload: event_type: sold_out movie: {gen: expr, expr: attr.movie} on: - fire: signal: {of: sold_out, key: "attr.movie"} - path: Movie.variables.when_sold_out value: gen: expr expr: "set_key(registry['Movie.variables.when_sold_out'], attr.movie, t)" - path: Movie.variables.available value: gen: expr expr: "set_key(registry['Movie.variables.available'], attr.movie, 0)" next: finish finish: service_time: 1 payload: {event_type: done} release: {handle: slot} run: {until: 120} ``` The script builds the model with the builder API. ```python """Movie Renege: SimPy's movie_renege.py example, builder API. A movie theatre has one ticket counter and three movies with 50 tickets each. A moviegoer arrives at exponential gaps, picks a movie and 1 to 6 tickets, and does not join the queue once the movie is sold out. At the counter, a moviegoer who asks for more tickets than are left argues and leaves; otherwise the sale goes ahead. When fewer than 2 tickets are left the movie is sold out, and everyone still queueing for it leaves (reneged). SimPy's example counts minutes, and here each of its minutes is one second. So a moviegoer arrives about every 0.5 seconds, an argument takes 0.5 seconds, a sale 1 second, and the run ends after 120 seconds, SimPy's 120 minutes. Each value is drawn from desflow's random sequence for its place in the model, so the numbers differ from those SimPy prints. The counter is a request opened by the moviegoer and held across the tasks that follow, and each movie's sold-out event is one member of the signal family `sold_out`. Needs no containers. Runs unpaced and ends after 120 simulation seconds. """ import logging from desflow import ConsoleEgress, SimulationContext from desflow.values import Template, generator MOVIES = ["Python Unchained", "Kill Process", "Pulp Implementation"] def build() -> SimulationContext: """Builds the theatre.""" app = SimulationContext(sim_id="Movie", factor=0, random_seed=42) app.add_egress(ConsoleEgress()) app.add_resource("counter", current_cap=1) app.add_variable("available", {movie: 50 for movie in MOVIES}) app.add_variable("when_sold_out", {}) app.add_variable("num_renegers", {movie: 0 for movie in MOVIES}) app.add_signal("sold_out", family=True, once=True) app.add_arrival( "goers", "exponential", rate=2, attributes={ "movie": generator({"gen": "one_of", "choices": MOVIES}), "tickets": generator({"gen": "integer", "bounds": [1, 6]}), }, spawn="moviegoer", ) @app.task( name="moviegoer", balk="registry['Movie.variables.available'][attr.movie] == 0", open={"slot": {"request": "counter"}}, wait={ "any": { "turn": {"handle": "slot"}, "out": {"signal": {"of": "sold_out", "key": "attr.movie"}}, } }, next={ "when": [{"condition": "wait.turn.done", "task": "serve"}], "default": "leave", }, ) def moviegoer(task_id): """Waits for the counter or for the movie to sell out.""" return {"event_type": "at_counter"} leave_payload = Template( {"event_type": "reneged", "movie": {"gen": "expr", "expr": "attr.movie"}}, name="leave", ) @app.task( name="leave", cancel="slot", release={"handle": "slot"}, on=[ { "path": "Movie.variables.num_renegers", "value": generator( { "gen": "expr", "expr": "set_key(registry['Movie.variables.num_renegers'], attr.movie, get_key(registry['Movie.variables.num_renegers'], attr.movie, 0) + 1)", } ), } ], ) def leave(task_id): """Leaves the queue: the movie sold out.""" return leave_payload @app.task( name="serve", next={ "when": [ { "condition": "registry['Movie.variables.available'][attr.movie] < attr.tickets", "task": "argue", } ], "default": "buy", }, ) def serve(task_id): """Reaches the counter.""" return {"event_type": "served"} @app.task(name="argue", service_time=0.5, release={"handle": "slot"}) def argue(task_id): """Asks for more tickets than are left.""" return {"event_type": "argued"} @app.task( name="buy", on=[ { "path": "Movie.variables.available", "value": generator( { "gen": "expr", "expr": "set_key(registry['Movie.variables.available'], attr.movie, registry['Movie.variables.available'][attr.movie] - attr.tickets)", } ), } ], next="check", ) def buy(task_id): """Buys the tickets.""" return {"event_type": "bought"} @app.task( name="check", next={ "when": [ { "condition": "registry['Movie.variables.available'][attr.movie] < 2", "task": "sold", } ], "default": "finish", }, ) def check(task_id): """Checks how many tickets are left.""" return {"event_type": "checked"} sold_payload = Template( {"event_type": "sold_out", "movie": {"gen": "expr", "expr": "attr.movie"}}, name="sold", ) @app.task( name="sold", on=[ {"fire": {"signal": {"of": "sold_out", "key": "attr.movie"}}}, { "path": "Movie.variables.when_sold_out", "value": generator( { "gen": "expr", "expr": "set_key(registry['Movie.variables.when_sold_out'], attr.movie, t)", } ), }, { "path": "Movie.variables.available", "value": generator( { "gen": "expr", "expr": "set_key(registry['Movie.variables.available'], attr.movie, 0)", } ), }, ], next="finish", ) def sold(task_id): """Sells the movie out, which sends its queue away.""" return sold_payload @app.task(name="finish", service_time=1, release={"handle": "slot"}) def finish(task_id): """Finishes the sale.""" return {"event_type": "done"} return app app = build() def run(model: SimulationContext = app) -> None: """Runs 120 simulation seconds.""" model.run(until=120) if __name__ == "__main__": logging.basicConfig(level=logging.INFO, format="%(levelname)s %(message)s") run() ``` The script wires the model by hand on `DynamicRealtimeEnvironment`, with SimPy's own processes. ```python """Movie Renege: SimPy's movie_renege.py example, low-level API. The low-level version of `builder/simpy/movie_renege_example.py`: SimPy's own `moviegoer` and `customer_arrivals` on a `DynamicRealtimeEnvironment`. They publish with `publish_event` the records that the YAML and builder versions publish: each task's `queued`, `started` and `balked`, its own events, and the number of the task's instance. A movie theatre has one ticket counter and three movies with 50 tickets each. A moviegoer picks a movie and 1 to 6 tickets, and does not join the queue once the movie is sold out. At the counter, a moviegoer who asks for more tickets than are left argues and leaves; otherwise the sale goes ahead. When fewer than 2 tickets are left the movie is sold out, and everyone still queueing for it leaves. SimPy's example counts minutes, and here each of its minutes is one second. So a moviegoer arrives about every 0.5 seconds, an argument takes 0.5 seconds, a sale 1 second, and the run ends after 120 seconds, SimPy's 120 minutes. Each value is drawn from desflow's `Sampler`, from the random sequence the YAML and builder versions use for the same place, so the three versions publish the same records. Needs no containers. Runs unpaced and ends after 120 simulation seconds. """ import itertools import logging import simpy from desflow import ( ConsoleEgress, DistributionConfig, DynamicRealtimeEnvironment, Sampler, ) MOVIES = ["Python Unchained", "Kill Process", "Pulp Implementation"] TICKETS = 50 UNTIL = 120 TASKS = ("moviegoer", "leave", "serve", "argue", "buy", "check", "sold", "finish") def build(env: DynamicRealtimeEnvironment) -> None: """Starts the moviegoers' arrivals on `env`.""" sampler = Sampler(seed=42) gap = DistributionConfig(dist="exponential", rate=2) gap.stream = "arrival.goers" # the sequence the blueprint's arrival draws from movie_choices = sampler.generator("arrivals.goers.attributes.movie") ticket_counts = sampler.generator("arrivals.goers.attributes.tickets") counter = simpy.Resource(env, capacity=1) available = {movie: TICKETS for movie in MOVIES} sold_out = {movie: env.event() for movie in MOVIES} numbers = {task: itertools.count() for task in TASKS} def moviegoer(name, movie, num_tickets): number = next(numbers["moviegoer"]) def publish(task, value, instance=None): """Publishes `value` as `instance` of `task`, or as a new instance.""" step = next(numbers[task]) if instance is None else instance env.publish_event(name, value, task=task, instance=step) return step if available[movie] == 0: # sold out: does not join the queue publish("moviegoer", {"status": "balked"}, number) return # The task's wait and the counter's request it opens each publish queued publish("moviegoer", {"status": "queued"}, number) publish("moviegoer", {"status": "queued"}, number) turn = counter.request() result = yield turn | sold_out[movie] if turn in result: # the request publishes started as it is granted publish("moviegoer", {"status": "started"}, number) publish("moviegoer", {"status": "started"}, number) publish("moviegoer", {"event_type": "at_counter"}, number) if turn not in result: # the movie sold out while it queued turn.cancel() if turn.triggered: counter.release(turn) publish("leave", {"event_type": "reneged", "movie": movie}) return publish("serve", {"event_type": "served"}) if available[movie] < num_tickets: arguing = publish("argue", {"status": "started"}) yield env.timeout(0.5) publish("argue", {"event_type": "argued"}, arguing) counter.release(turn) return publish("buy", {"event_type": "bought"}) available[movie] -= num_tickets publish("check", {"event_type": "checked"}) if available[movie] < 2: publish("sold", {"event_type": "sold_out", "movie": movie}) sold_out[movie].succeed() available[movie] = 0 finishing = publish("finish", {"status": "started"}) yield env.timeout(1) publish("finish", {"event_type": "done"}, finishing) counter.release(turn) def customer_arrivals(): for number in itertools.count(1): yield env.timeout(sampler.sample(gap)) movie = MOVIES[int(movie_choices.integers(len(MOVIES)))] num_tickets = int(ticket_counts.integers(1, 7)) env.process(moviegoer(f"goers-{number}", movie, num_tickets)) env.process(customer_arrivals()) def run() -> None: """Runs 120 simulation seconds.""" env = DynamicRealtimeEnvironment(factor=0) env.setup_egress([ConsoleEgress()]) build(env) try: env.run(until=UNTIL) finally: env.teardown() if __name__ == "__main__": logging.basicConfig(level=logging.INFO, format="%(levelname)s %(message)s") run() ``` This is SimPy 4.1.2's `movie_renege.py`, with SimPy's licence notice added at the top and comment lines that mark the pieces shown above. Run with Python, it prints the output shown under Check the Result. ```python # SimPy 4.1.2, docs/examples/code/movie_renege.py, under SimPy's licence (LICENSE.rst): # # The MIT License (MIT) # # Copyright (c) 2013 Ontje Lünsdorf and Stefan Scherfke (also see AUTHORS.txt) # # Permission is hereby granted, free of charge, to any person obtaining a copy of # this software and associated documentation files (the "Software"), to deal in # the Software without restriction, including without limitation the rights to # use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of # the Software, and to permit persons to whom the Software is furnished to do so, # subject to the following conditions: # # The above copyright notice and this permission notice shall be included in all # copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS # FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR # COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER # IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN # CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. """ Movie renege example Covers: - Resources: Resource - Condition events - Shared events Scenario: A movie theatre has one ticket counter selling tickets for three movies (next show only). When a movie is sold out, all people waiting to buy tickets for that movie renege (leave queue). """ from __future__ import annotations import random from typing import Dict, List, NamedTuple, Optional import simpy RANDOM_SEED = 42 TICKETS = 50 # Number of tickets per movie SELLOUT_THRESHOLD = 2 # Fewer tickets than this is a sellout SIM_TIME = 120 # Simulate until def moviegoer(env, movie, num_tickets, theater): """A moviegoer tries to by a number of tickets (*num_tickets*) for a certain *movie* in a *theater*. If the movie becomes sold out, she leaves the theater. If she gets to the counter, she tries to buy a number of tickets. If not enough tickets are left, she argues with the teller and leaves. If at most one ticket is left after the moviegoer bought her tickets, the *sold out* event for this movie is triggered causing all remaining moviegoers to leave. """ with theater.counter.request() as my_turn: # Wait until it's our turn or until the movie is sold out result = yield my_turn | theater.sold_out[movie] # Check if it's our turn or if movie is sold out if my_turn not in result: theater.num_renegers[movie] += 1 return # Check if enough tickets left. if theater.available[movie] < num_tickets: # Moviegoer leaves after some discussion yield env.timeout(0.5) return # Buy tickets theater.available[movie] -= num_tickets if theater.available[movie] < SELLOUT_THRESHOLD: # Trigger the "sold out" event for the movie theater.sold_out[movie].succeed() theater.when_sold_out[movie] = env.now theater.available[movie] = 0 yield env.timeout(1) def customer_arrivals(env, theater): """Create new *moviegoers* until the sim time reaches 120.""" while True: yield env.timeout(random.expovariate(1 / 0.5)) movie = random.choice(theater.movies) num_tickets = random.randint(1, 6) if theater.available[movie]: env.process(moviegoer(env, movie, num_tickets, theater)) class Theater(NamedTuple): counter: simpy.Resource movies: List[str] available: Dict[str, int] sold_out: Dict[str, simpy.Event] when_sold_out: Dict[str, Optional[float]] num_renegers: Dict[str, int] # Setup and start the simulation print('Movie renege') random.seed(RANDOM_SEED) env = simpy.Environment() # Create movie theater movies = ['Python Unchained', 'Kill Process', 'Pulp Implementation'] theater = Theater( counter=simpy.Resource(env, capacity=1), movies=movies, available=dict.fromkeys(movies, TICKETS), sold_out={movie: env.event() for movie in movies}, when_sold_out=dict.fromkeys(movies), num_renegers=dict.fromkeys(movies, 0), ) # Start process and run env.process(customer_arrivals(env, theater)) env.run(until=SIM_TIME) # Analysis/results for movie in movies: if theater.sold_out[movie]: sellout_time = theater.when_sold_out[movie] num_renegers = theater.num_renegers[movie] print( f'Movie "{movie}" sold out {sellout_time:.1f} minutes ' f'after ticket counter opening.' ) print(f' Number of people leaving queue when film sold out: {num_renegers}') ``` ______________________________________________________________________ ## Sources - [SimPy 4.1.2, Movie Renege](https://simpy.readthedocs.io/en/4.1.2/examples/movie_renege.html): the original code and its output. - [SimPy's licence](https://gitlab.com/team-simpy/simpy/-/blob/master/LICENSE.rst): MIT, Copyright (c) 2013 Ontje Lünsdorf and Stefan Scherfke. The SimPy file above carries this notice. - [`examples/` in the desflow repository](https://github.com/jaehyeon-kim/desflow/tree/v1.3.0/examples): the three versions in desflow, under `simpy/` in each folder. # Gas Station Refueling Cars take fuel from a station's tank, and a control process calls a tank truck when the tank runs low. This is SimPy's Gas Station Refueling example, written in desflow. ______________________________________________________________________ ## Before You Start SimPy's gas station has two pumps and a tank of 200 litres. A car arrives every 30 to 300 seconds with 5 to 25 litres left in its 50 litre tank. It waits for a pump, takes the fuel it needs from the station's tank, and refuels at 2 litres a second. A control process checks the tank every 10 seconds. When the tank is below 25 percent, it calls a tank truck, which arrives 300 seconds later and fills the tank. The run lasts 1000 seconds. The example needs only desflow, which each Quick Start in [Run It](#run-it) installs, and no other service. `desflow examples get simpy-gas-station-refuel --api yaml` downloads it, as [Get an Example](https://jaehyeon.me/desflow/latest/cli/#get-an-example) shows. [SimPy Examples](https://jaehyeon.me/desflow/latest/simpy/examples/index.md) says how these pages read SimPy's times and numbers. SimPy's own page for the example is [on its documentation site](https://simpy.readthedocs.io/en/4.1.2/examples/gas_station_refuel.html). ______________________________________________________________________ ## Steps ### Car Refuels SimPy's `car` requests a pump, takes the fuel it needs from the tank, and refuels at 2 litres a second. ```python def car(name, env, gas_station, station_tank): """A car arrives at the gas station for refueling. It requests one of the gas station's fuel pumps and tries to get the desired amount of fuel from it. If the station's fuel tank is depleted, the car has to wait for the tank truck to arrive. """ car_tank_level = random.randint(*CAR_TANK_LEVEL) print(f'{env.now:6.1f} s: {name} arrived at gas station') with gas_station.request() as req: # Request one of the gas pumps yield req # Get the required amount of fuel fuel_required = CAR_TANK_SIZE - car_tank_level yield station_tank.get(fuel_required) # The "actual" refueling process takes some time yield env.timeout(fuel_required / REFUELING_SPEED) print(f'{env.now:6.1f} s: {name} refueled with {fuel_required:.1f}L') ``` `pumps` is a resource with two units and `tank` is a container of 200 litres, full at the start. The `car` task takes a pump, gets `50 - attr.level` litres from the tank, and refuels for `(50 - attr.level) / 2` seconds. `attr.level` is the fuel the car has left. ```yaml resources: pumps: {current_cap: 2} containers: tank: {current_cap: 200, level: 200} ``` ```yaml car: resource: pumps get: {container: tank, amount: "50 - attr.level"} service_time: "(50 - attr.level) / 2" payload: event_type: refueled litres: {gen: expr, expr: "50 - attr.level"} ``` `add_resource` and `add_container` declare the pumps and the tank. The `car` task takes `get` and `service_time` as expressions on the car's attribute. ```python app.add_resource("pumps", current_cap=2) app.add_container("tank", current_cap=200, level=200) ``` ```python car_payload = Template( { "event_type": "refueled", "litres": {"gen": "expr", "expr": "50 - attr.level"}, }, name="car", ) @app.task( name="car", resource_id="pumps", get={"container": "tank", "amount": "50 - attr.level"}, service_time="(50 - attr.level) / 2", ) def car(task_id): """Refuels at a pump.""" return car_payload ``` The low-level version has SimPy's `simpy.Resource` and `simpy.Container`, and SimPy's `car` function with records published for it. ```python gas_station = simpy.Resource(env, 2) station_tank = simpy.Container(env, STATION_TANK_SIZE, init=STATION_TANK_SIZE) ``` ```python def car(name, car_tank_level): number = next(numbers["car"]) with gas_station.request() as req: publish(name, "car", number, {"status": "queued"}) yield req fuel_required = CAR_TANK_SIZE - car_tank_level yield station_tank.get(fuel_required) publish(name, "car", number, {"status": "started"}) yield env.timeout(fuel_required / REFUELING_SPEED) publish( name, "car", number, {"event_type": "refueled", "litres": fuel_required} ) ``` ### Control Calls the Truck SimPy's `gas_station_control` checks the tank every 10 seconds and, below 25 percent, calls the truck and waits for it. ```python def gas_station_control(env, station_tank): """Periodically check the level of the gas station tank and call the tank truck if the level falls below a threshold.""" while True: if station_tank.level / station_tank.capacity * 100 < THRESHOLD: # We need to call the tank truck now! print(f'{env.now:6.1f} s: Calling tank truck') # Wait for the tank truck to arrive and refuel the station tank yield env.process(tank_truck(env, station_tank)) yield env.timeout(10) # Check every 10 seconds ``` The `control` task checks `level.tank / 200 * 100 < 25` in its `next` rule. When the tank is low it goes to `call_truck`, and then to `await_truck`, which waits for the `truck` task to finish. Otherwise it goes to `pause`, which waits 10 seconds and returns to `control`. ```yaml control: payload: {event_type: checked} next: when: - {condition: "level.tank / 200 * 100 < 25", task: call_truck} default: pause call_truck: payload: {event_type: truck_called} next: await_truck await_truck: wait: {task: truck} payload: {event_type: truck_returned} next: pause ``` ```yaml pause: service_time: 10 payload: {event_type: waited} next: control ``` The same tasks, with `next` and `wait` as in the YAML. ```python @app.task( name="control", next={ "when": [ {"condition": "level.tank / 200 * 100 < 25", "task": "call_truck"} ], "default": "pause", }, ) def control(task_id): """Checks the level of the tank.""" return {"event_type": "checked"} @app.task(name="call_truck", next="await_truck") def call_truck(task_id): """Calls the tank truck.""" return {"event_type": "truck_called"} @app.task(name="await_truck", wait={"task": "truck"}, next="pause") def await_truck(task_id): """Waits for the tank truck.""" return {"event_type": "truck_returned"} ``` ```python @app.task(name="pause", service_time=10, next="control") def pause(task_id): """Waits until the next check.""" return {"event_type": "waited"} ``` `gas_station_control` is SimPy's loop. It runs `tank_truck` as a process and waits for it. ```python def gas_station_control(name): while True: publish( name, "control", next(numbers["control"]), {"event_type": "checked"} ) if station_tank.level / station_tank.capacity * 100 < THRESHOLD: call = next(numbers["call_truck"]) publish(name, "call_truck", call, {"event_type": "truck_called"}) waiting = next(numbers["await_truck"]) publish(name, "await_truck", waiting, {"status": "queued"}) yield env.process(tank_truck(name)) publish(name, "await_truck", waiting, {"status": "started"}) publish(name, "await_truck", waiting, {"event_type": "truck_returned"}) pause = next(numbers["pause"]) publish(name, "pause", pause, {"status": "started"}) yield env.timeout(10) publish(name, "pause", pause, {"event_type": "waited"}) ``` ### Truck Fills the Tank SimPy's `tank_truck` waits 300 seconds and then fills the tank. ```python def tank_truck(env, station_tank): """Arrives at the gas station after a certain delay and refuels it.""" yield env.timeout(TANK_TRUCK_TIME) amount = station_tank.capacity - station_tank.level station_tank.put(amount) print( f'{env.now:6.1f} s: Tank truck arrived and refuelled station with {amount:.1f}L' ) ``` The `truck` task waits `service_time: 300` and then puts `200 - level.tank` litres into the container, which fills it. ```yaml truck: service_time: 300 put: {container: tank, amount: "200 - level.tank"} payload: event_type: truck_arrived litres: {gen: expr, expr: "200 - level.tank"} ``` The `truck` task takes `service_time` and `put` as the YAML does. ```python truck_payload = Template( { "event_type": "truck_arrived", "litres": {"gen": "expr", "expr": "200 - level.tank"}, }, name="truck", ) @app.task( name="truck", service_time=300, put={"container": "tank", "amount": "200 - level.tank"}, ) def truck(task_id): """Fills the tank on arrival.""" return truck_payload ``` `tank_truck` is SimPy's function. ```python def tank_truck(name): number = next(numbers["truck"]) publish(name, "truck", number, {"status": "started"}) yield env.timeout(TANK_TRUCK_TIME) amount = station_tank.capacity - station_tank.level yield station_tank.put(amount) publish( name, "truck", number, {"event_type": "truck_arrived", "litres": amount} ) ``` ### Cars Arrive SimPy's `car_generator` starts a car after each gap of 30 to 300 seconds, each with its own fuel level. ```python def car_generator(env, gas_station, station_tank): """Generate new cars that arrive at the gas station.""" for i in itertools.count(): yield env.timeout(random.randint(*T_INTER)) env.process(car(f'Car {i}', env, gas_station, station_tank)) ``` The arrival `cars` draws its `gap` from 30 to 300 seconds and gives each car an attribute `level` from 5 to 25 litres. The arrival `control` starts the control process once at time 0. ```yaml arrivals: control: {initial: 1, spawn: control} cars: gap: {gen: integer, bounds: [30, 300]} spawn: car key: {gen: sequence, format: "Car {}"} attributes: level: {gen: integer, bounds: [5, 25]} ``` `add_arrival` takes `gap` and `attributes`, and `add_initial_arrival` starts the control process. ```python app.add_initial_arrival("control", 1, spawn="control") app.add_arrival( "cars", gap=generator({"gen": "integer", "bounds": [30, 300]}), key=lambda n: "Car {}".format(n - 1), attributes={"level": generator({"gen": "integer", "bounds": [5, 25]})}, spawn="car", ) ``` `car_generator` draws the gap and the fuel level from desflow's `Sampler`. ```python def car_generator(): for i in itertools.count(): yield env.timeout(int(gaps.integers(30, 301))) env.process(car(f"Car {i}", int(levels.integers(5, 26)))) env.process(gas_station_control("control-1")) env.process(car_generator()) ``` ### Run It `desflow run` loads the blueprint and runs it unpaced, because it sets `factor: 0`. Each record is printed to the terminal. **Quick Start** `desflow examples get` downloads the example at the release you install, into a folder of its own. Pick uv or pip: ```bash # 1. Install uv tool install desflow # 2. Download the example desflow examples get simpy-gas-station-refuel --api yaml cd simpy-gas-station-refuel/yaml # 3. Run it desflow run gas_station_refuel.yaml ``` ```bash # 1. Install pip install desflow # 2. Download the example desflow examples get simpy-gas-station-refuel --api yaml cd simpy-gas-station-refuel/yaml # 3. Run it desflow run gas_station_refuel.yaml ``` The script builds the model with the builder API, runs it unpaced, and prints each record to the terminal. **Quick Start** `desflow examples get` downloads the example at the release you install, into a folder of its own. Pick uv or pip: ```bash # 1. Install uv tool install desflow # 2. Download the example desflow examples get simpy-gas-station-refuel --api builder cd simpy-gas-station-refuel/builder # 3. Run it uv run --no-project --with desflow gas_station_refuel_example.py ``` ```bash # 1. Install pip install desflow # 2. Download the example desflow examples get simpy-gas-station-refuel --api builder cd simpy-gas-station-refuel/builder # 3. Run it python gas_station_refuel_example.py ``` The script wires the model by hand on `DynamicRealtimeEnvironment`, runs it unpaced, and prints each record to the terminal. **Quick Start** `desflow examples get` downloads the example at the release you install, into a folder of its own. Pick uv or pip: ```bash # 1. Install uv tool install desflow # 2. Download the example desflow examples get simpy-gas-station-refuel --api low-level cd simpy-gas-station-refuel/low-level # 3. Run it uv run --no-project --with desflow gas_station_refuel_example.py ``` ```bash # 1. Install pip install desflow # 2. Download the example desflow examples get simpy-gas-station-refuel --api low-level cd simpy-gas-station-refuel/low-level # 3. Run it python gas_station_refuel_example.py ``` ______________________________________________________________________ ## Check the Result Five cars refuel in the 1000 seconds. The control task finds the tank below 25 percent at 820 seconds and calls the truck. The truck needs 300 seconds, so it would arrive at 1120 seconds, after the run ends, and the records show no truck arrival. In SimPy's output, below, the truck is called at 460 seconds and arrives at 760 seconds. Here the cars arrive at other times, so the tank is low later. desflow draws each random value from its own stream, named by the place where the value is used, such as `arrivals.cars.gap`. A seed of 42 therefore gives different numbers from SimPy's `random.seed(42)`. The system is the same. The figures are not. ```text Gas Station refuelling 87.0 s: Car 0 arrived at gas station 105.5 s: Car 0 refueled with 37.0L 129.0 s: Car 1 arrived at gas station 148.0 s: Car 1 refueled with 38.0L 284.0 s: Car 2 arrived at gas station 305.0 s: Car 2 refueled with 42.0L 385.0 s: Car 3 arrived at gas station 398.5 s: Car 3 refueled with 27.0L 459.0 s: Car 4 arrived at gas station 460.0 s: Calling tank truck 481.0 s: Car 4 refueled with 44.0L 705.0 s: Car 5 arrived at gas station 750.0 s: Car 6 arrived at gas station 760.0 s: Tank truck arrived and refuelled station with 188.0L 779.0 s: Car 6 refueled with 38.0L 781.5 s: Car 5 refueled with 43.0L 891.0 s: Car 7 arrived at gas station 904.0 s: Car 7 refueled with 26.0L ``` The three versions in desflow print the same records, which [a test](https://github.com/jaehyeon-kim/desflow/blob/v1.3.0/tests/docs/test_example_twins.py) checks by running each version unpaced. Each record has `sim_ts`, the simulation time, and a key for the entity it belongs to. The statistics and the parameters that a live run can change are in the same stream, which SimPy's file does not have. ______________________________________________________________________ ## Full Files Full files The blueprint is `gas_station_refuel.yaml`. ```yaml # Gas Station Refueling: SimPy's gas_station_refuel.py example, in YAML. # # The YAML version of gas_station_refuel_example.py, which --api builder downloads. A # gas station has two pumps and a tank of 200 litres. A car arrives every 30 to 300 # seconds with 5 to 25 litres left in its 50 litre tank. It waits for a pump, takes # the fuel it needs from the station's tank and refuels at 2 litres a second. A control # task checks the tank every 10 seconds, and when it is below 25 percent it calls a # tank truck, which arrives 300 seconds later and fills the tank. # # Each value is drawn from desflow's random sequence for its place in the file, so the # numbers differ from those SimPy prints. # # Needs no containers. Runs unpaced and ends after 1000 simulation seconds. # Run it from its folder with: desflow run gas_station_refuel.yaml simulation: {sim_id: GasStation, factor: 0, random_seed: 42} egress: - {type: Console} resources: pumps: {current_cap: 2} containers: tank: {current_cap: 200, level: 200} arrivals: control: {initial: 1, spawn: control} cars: gap: {gen: integer, bounds: [30, 300]} spawn: car key: {gen: sequence, format: "Car {}"} attributes: level: {gen: integer, bounds: [5, 25]} tasks: car: resource: pumps get: {container: tank, amount: "50 - attr.level"} service_time: "(50 - attr.level) / 2" payload: event_type: refueled litres: {gen: expr, expr: "50 - attr.level"} control: payload: {event_type: checked} next: when: - {condition: "level.tank / 200 * 100 < 25", task: call_truck} default: pause call_truck: payload: {event_type: truck_called} next: await_truck await_truck: wait: {task: truck} payload: {event_type: truck_returned} next: pause truck: service_time: 300 put: {container: tank, amount: "200 - level.tank"} payload: event_type: truck_arrived litres: {gen: expr, expr: "200 - level.tank"} pause: service_time: 10 payload: {event_type: waited} next: control run: {until: 1000} ``` The script builds the model with the builder API. ```python """Gas Station Refueling: SimPy's gas_station_refuel.py example, builder API. A gas station has two pumps and a tank of 200 litres. A car arrives every 30 to 300 seconds with 5 to 25 litres left in its 50 litre tank. It waits for a pump, takes the fuel it needs from the station's tank and refuels at 2 litres a second. A control task checks the tank every 10 seconds, and when it is below 25 percent it calls a tank truck, which arrives 300 seconds later and fills the tank. Each value is drawn from desflow's random sequence for its place in the model, so the numbers differ from those SimPy prints. Needs no containers. Runs unpaced and ends after 1000 simulation seconds. """ import logging from desflow import ConsoleEgress, SimulationContext from desflow.values import Template, generator def build() -> SimulationContext: """Builds the gas station.""" app = SimulationContext(sim_id="GasStation", factor=0, random_seed=42) app.add_egress(ConsoleEgress()) app.add_resource("pumps", current_cap=2) app.add_container("tank", current_cap=200, level=200) app.add_initial_arrival("control", 1, spawn="control") app.add_arrival( "cars", gap=generator({"gen": "integer", "bounds": [30, 300]}), key=lambda n: "Car {}".format(n - 1), attributes={"level": generator({"gen": "integer", "bounds": [5, 25]})}, spawn="car", ) car_payload = Template( { "event_type": "refueled", "litres": {"gen": "expr", "expr": "50 - attr.level"}, }, name="car", ) @app.task( name="car", resource_id="pumps", get={"container": "tank", "amount": "50 - attr.level"}, service_time="(50 - attr.level) / 2", ) def car(task_id): """Refuels at a pump.""" return car_payload @app.task( name="control", next={ "when": [ {"condition": "level.tank / 200 * 100 < 25", "task": "call_truck"} ], "default": "pause", }, ) def control(task_id): """Checks the level of the tank.""" return {"event_type": "checked"} @app.task(name="call_truck", next="await_truck") def call_truck(task_id): """Calls the tank truck.""" return {"event_type": "truck_called"} @app.task(name="await_truck", wait={"task": "truck"}, next="pause") def await_truck(task_id): """Waits for the tank truck.""" return {"event_type": "truck_returned"} truck_payload = Template( { "event_type": "truck_arrived", "litres": {"gen": "expr", "expr": "200 - level.tank"}, }, name="truck", ) @app.task( name="truck", service_time=300, put={"container": "tank", "amount": "200 - level.tank"}, ) def truck(task_id): """Fills the tank on arrival.""" return truck_payload @app.task(name="pause", service_time=10, next="control") def pause(task_id): """Waits until the next check.""" return {"event_type": "waited"} return app app = build() def run(model: SimulationContext = app) -> None: """Runs 1000 simulation seconds.""" model.run(until=1000) if __name__ == "__main__": logging.basicConfig(level=logging.INFO, format="%(levelname)s %(message)s") run() ``` The script wires the model by hand on `DynamicRealtimeEnvironment`, with SimPy's own processes. ```python """Gas Station Refueling: SimPy's gas_station_refuel.py example, low-level API. The low-level version of `builder/simpy/gas_station_refuel_example.py`: SimPy's own processes on a `DynamicRealtimeEnvironment`. They publish with `publish_event` the records that the YAML and builder versions publish: each task's `queued` and `started`, its own events, and the number of the task's instance. A gas station has two pumps and a tank of 200 litres. A car arrives every 30 to 300 seconds with 5 to 25 litres left in its 50 litre tank. It waits for a pump, takes the fuel it needs from the station's tank and refuels at 2 litres a second. A control process checks the tank every 10 seconds, and when it is below 25 percent it calls a tank truck, which arrives 300 seconds later and fills the tank. Each value is drawn from desflow's `Sampler`, from the random sequence the YAML and builder versions use for the same place, so the three versions publish the same records. Needs no containers. Runs unpaced and ends after 1000 simulation seconds. """ import itertools import logging import simpy from desflow import ConsoleEgress, DynamicRealtimeEnvironment, Sampler STATION_TANK_SIZE = 200 # litres THRESHOLD = 25 # percent of the tank that calls the truck CAR_TANK_SIZE = 50 # litres REFUELING_SPEED = 2 # litres a second TANK_TRUCK_TIME = 300 # seconds UNTIL = 1000 def build(env: DynamicRealtimeEnvironment) -> None: """Starts the control process and the cars on `env`.""" sampler = Sampler(seed=42) gaps = sampler.generator("arrivals.cars.gap") levels = sampler.generator("arrivals.cars.attributes.level") gas_station = simpy.Resource(env, 2) station_tank = simpy.Container(env, STATION_TANK_SIZE, init=STATION_TANK_SIZE) numbers = { task: itertools.count() for task in ("car", "control", "call_truck", "await_truck", "truck", "pause") } def publish(name, task, number, value): env.publish_event(name, value, task=task, instance=number) def car(name, car_tank_level): number = next(numbers["car"]) with gas_station.request() as req: publish(name, "car", number, {"status": "queued"}) yield req fuel_required = CAR_TANK_SIZE - car_tank_level yield station_tank.get(fuel_required) publish(name, "car", number, {"status": "started"}) yield env.timeout(fuel_required / REFUELING_SPEED) publish( name, "car", number, {"event_type": "refueled", "litres": fuel_required} ) def tank_truck(name): number = next(numbers["truck"]) publish(name, "truck", number, {"status": "started"}) yield env.timeout(TANK_TRUCK_TIME) amount = station_tank.capacity - station_tank.level yield station_tank.put(amount) publish( name, "truck", number, {"event_type": "truck_arrived", "litres": amount} ) def gas_station_control(name): while True: publish( name, "control", next(numbers["control"]), {"event_type": "checked"} ) if station_tank.level / station_tank.capacity * 100 < THRESHOLD: call = next(numbers["call_truck"]) publish(name, "call_truck", call, {"event_type": "truck_called"}) waiting = next(numbers["await_truck"]) publish(name, "await_truck", waiting, {"status": "queued"}) yield env.process(tank_truck(name)) publish(name, "await_truck", waiting, {"status": "started"}) publish(name, "await_truck", waiting, {"event_type": "truck_returned"}) pause = next(numbers["pause"]) publish(name, "pause", pause, {"status": "started"}) yield env.timeout(10) publish(name, "pause", pause, {"event_type": "waited"}) def car_generator(): for i in itertools.count(): yield env.timeout(int(gaps.integers(30, 301))) env.process(car(f"Car {i}", int(levels.integers(5, 26)))) env.process(gas_station_control("control-1")) env.process(car_generator()) def run() -> None: """Runs 1000 simulation seconds.""" env = DynamicRealtimeEnvironment(factor=0) env.setup_egress([ConsoleEgress()]) build(env) try: env.run(until=UNTIL) finally: env.teardown() if __name__ == "__main__": logging.basicConfig(level=logging.INFO, format="%(levelname)s %(message)s") run() ``` This is SimPy 4.1.2's `gas_station_refuel.py`, with SimPy's licence notice added at the top and comment lines that mark the pieces shown above. Run with Python, it prints the output shown under Check the Result. ```python # SimPy 4.1.2, docs/examples/code/gas_station_refuel.py, under SimPy's licence (LICENSE.rst): # # The MIT License (MIT) # # Copyright (c) 2013 Ontje Lünsdorf and Stefan Scherfke (also see AUTHORS.txt) # # Permission is hereby granted, free of charge, to any person obtaining a copy of # this software and associated documentation files (the "Software"), to deal in # the Software without restriction, including without limitation the rights to # use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of # the Software, and to permit persons to whom the Software is furnished to do so, # subject to the following conditions: # # The above copyright notice and this permission notice shall be included in all # copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS # FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR # COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER # IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN # CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. """ Gas Station Refueling example Covers: - Resources: Resource - Resources: Container - Waiting for other processes Scenario: A gas station has a limited number of gas pumps that share a common fuel reservoir. Cars randomly arrive at the gas station, request one of the fuel pumps and start refueling from that reservoir. A gas station control process observes the gas station's fuel level and calls a tank truck for refueling if the station's level drops below a threshold. """ import itertools import random import simpy # fmt: off RANDOM_SEED = 42 STATION_TANK_SIZE = 200 # Size of the gas station tank (liters) THRESHOLD = 25 # Station tank minimum level (% of full) CAR_TANK_SIZE = 50 # Size of car fuel tanks (liters) CAR_TANK_LEVEL = [5, 25] # Min/max levels of car fuel tanks (liters) REFUELING_SPEED = 2 # Rate of refuelling car fuel tank (liters / second) TANK_TRUCK_TIME = 300 # Time it takes tank truck to arrive (seconds) T_INTER = [30, 300] # Interval between car arrivals [min, max] (seconds) SIM_TIME = 1000 # Simulation time (seconds) # fmt: on def car(name, env, gas_station, station_tank): """A car arrives at the gas station for refueling. It requests one of the gas station's fuel pumps and tries to get the desired amount of fuel from it. If the station's fuel tank is depleted, the car has to wait for the tank truck to arrive. """ car_tank_level = random.randint(*CAR_TANK_LEVEL) print(f'{env.now:6.1f} s: {name} arrived at gas station') with gas_station.request() as req: # Request one of the gas pumps yield req # Get the required amount of fuel fuel_required = CAR_TANK_SIZE - car_tank_level yield station_tank.get(fuel_required) # The "actual" refueling process takes some time yield env.timeout(fuel_required / REFUELING_SPEED) print(f'{env.now:6.1f} s: {name} refueled with {fuel_required:.1f}L') def gas_station_control(env, station_tank): """Periodically check the level of the gas station tank and call the tank truck if the level falls below a threshold.""" while True: if station_tank.level / station_tank.capacity * 100 < THRESHOLD: # We need to call the tank truck now! print(f'{env.now:6.1f} s: Calling tank truck') # Wait for the tank truck to arrive and refuel the station tank yield env.process(tank_truck(env, station_tank)) yield env.timeout(10) # Check every 10 seconds def tank_truck(env, station_tank): """Arrives at the gas station after a certain delay and refuels it.""" yield env.timeout(TANK_TRUCK_TIME) amount = station_tank.capacity - station_tank.level station_tank.put(amount) print( f'{env.now:6.1f} s: Tank truck arrived and refuelled station with {amount:.1f}L' ) def car_generator(env, gas_station, station_tank): """Generate new cars that arrive at the gas station.""" for i in itertools.count(): yield env.timeout(random.randint(*T_INTER)) env.process(car(f'Car {i}', env, gas_station, station_tank)) # Setup and start the simulation print('Gas Station refuelling') random.seed(RANDOM_SEED) # Create environment and start processes env = simpy.Environment() gas_station = simpy.Resource(env, 2) station_tank = simpy.Container(env, STATION_TANK_SIZE, init=STATION_TANK_SIZE) env.process(gas_station_control(env, station_tank)) env.process(car_generator(env, gas_station, station_tank)) # Execute! env.run(until=SIM_TIME) ``` ______________________________________________________________________ ## Sources - [SimPy 4.1.2, Gas Station Refueling](https://simpy.readthedocs.io/en/4.1.2/examples/gas_station_refuel.html): the original code and its output. - [SimPy's licence](https://gitlab.com/team-simpy/simpy/-/blob/master/LICENSE.rst): MIT, Copyright (c) 2013 Ontje Lünsdorf and Stefan Scherfke. The SimPy file above carries this notice. - [`examples/` in the desflow repository](https://github.com/jaehyeon-kim/desflow/tree/v1.3.0/examples): the three versions in desflow, under `simpy/` in each folder. # Process Communication A generator puts messages into a pipe and a consumer takes them, first from one pipe and then from two. This is SimPy's Process Communication example, written in desflow. ______________________________________________________________________ ## Before You Start SimPy's example has a generator that puts a message into a store every 6 to 10 time units. The message holds the time it was sent. A consumer takes a message and then works on it for 4 to 8 time units, so it takes some messages late. The run lasts 100 time units. SimPy runs the example twice: once with one consumer (one to one), and once with two consumers that each have a pipe of their own, which the generator fills with a broadcast pipe (one to many). SimPy counts no unit, and desflow reads each unit as one second. The example has two blueprints, `process_communication.yaml` for one to one and `process_communication_broadcast.yaml` for one to many, and a builder and a low-level file for each. `desflow examples get` downloads both. The example needs only desflow, which each Quick Start in [Run It](#run-it) installs, and no other service. `desflow examples get simpy-process-communication --api yaml` downloads it, as [Get an Example](https://jaehyeon.me/desflow/latest/cli/#get-an-example) shows. [SimPy Examples](https://jaehyeon.me/desflow/latest/simpy/examples/index.md) says how these pages read SimPy's times and numbers. SimPy's own page for the example is [on its documentation site](https://simpy.readthedocs.io/en/4.1.2/examples/process_communication.html). ______________________________________________________________________ ## Steps ### Generator Sends SimPy's `message_generator` waits 6 to 10 time units and puts a message with the time it was sent into the pipe, without waiting for the put. ```python def message_generator(name, env, out_pipe): """A process which randomly generates messages.""" while True: # wait for next transmission yield env.timeout(random.randint(6, 10)) # messages are time stamped to later check if the consumer was # late getting them. Note, using event.triggered to do this may # result in failure due to FIFO nature of simulation yields. # (i.e. if at the same env.now, message_generator puts a message # in the pipe first and then message_consumer gets from pipe, # the event.triggered will be True in the other order it will be # False msg = (env.now, f'{name} says hello at {env.now}') out_pipe.put(msg) ``` `pipe` is a store. The arrival `generator` starts one `speak` task after each gap of 6 to 10 seconds. The task puts an item with the time it was sent, `sent`, and a text into the store. `wait: false` means the task does not wait for the put to finish, as in SimPy. ```yaml stores: pipe: {} ``` ```yaml generator: gap: {gen: integer, bounds: [6, 10]} spawn: speak ``` ```yaml speak: payload: {event_type: said} # The generator does not wait for its put, as SimPy's `out_pipe.put(msg)` does not put: store: pipe wait: false item: sent: {gen: expr, expr: t} text: gen: format template: "Generator A says hello at {now:g}" names: now: {gen: expr, expr: t} ``` `add_store` and `add_arrival` declare the pipe and the generator, and the `speak` task takes `put` with the same item. ```python app.add_store("pipe") ``` ```python app.add_arrival( "generator", gap=generator({"gen": "integer", "bounds": [6, 10]}), spawn="speak", ) ``` ```python @app.task( name="speak", put={ "store": "pipe", "wait": False, "item": { "sent": generator({"gen": "expr", "expr": "t"}), "text": generator( { "gen": "format", "template": "Generator A says hello at {now:g}", "names": {"now": {"gen": "expr", "expr": "t"}}, } ), }, }, ) def speak(task_id): """Puts a message into the pipe.""" return {"event_type": "said"} ``` `message_generator` is SimPy's function. It draws each gap from desflow's `Sampler` and publishes a `said` record. ```python sampler = Sampler(seed=42) gaps = sampler.generator("arrivals.generator.gap") busy_times = sampler.generator("tasks.busy.service_time") pipe = simpy.Store(env) numbers = {task: itertools.count() for task in ("listen", "busy")} ``` ```python def message_generator(name, out_pipe): for number in itertools.count(1): yield env.timeout(int(gaps.integers(6, 11))) msg = (env.now, f"{name} says hello at {env.now:g}") out_pipe.put(msg) # not waited for, as in SimPy's example env.publish_event( f"generator-{number}", {"event_type": "said"}, task="speak", instance=number - 1, ) ``` ### Consumer Gets SimPy's `message_consumer` takes a message from the pipe, prints it, and works on it for 4 to 8 time units. It is late for a message that was sent before it asked for it. ```python def message_consumer(name, env, in_pipe): """A process which consumes messages.""" while True: # Get event for message pipe msg = yield in_pipe.get() if msg[0] < env.now: # if message was already put into pipe, then # message_consumer was late getting to it. Depending on what # is being modeled this, may, or may not have some # significance print( f'LATE Getting Message: at time {env.now}: ' f'{name} received message: {msg[1]}' ) else: # message_consumer is synchronized with message_generator print(f'at time {env.now}: {name} received message: {msg[1]}.') # Process does some other work, which may result in missing messages yield env.timeout(random.randint(4, 8)) ``` The arrival `consumer` starts one `listen` task at time 0. `listen` takes the next item from the store and publishes `received`, with `late` true when the message waited in the store before the task took it, `item.sent < t`. `busy` works for 4 to 8 seconds and goes back to `listen`. ```yaml consumer: {initial: 1, spawn: listen} ``` ```yaml listen: get: {store: pipe} payload: event_type: received late: {gen: expr, expr: "item.sent < t"} text: {gen: expr, expr: "item.text"} next: busy busy: service_time: {gen: integer, bounds: [4, 8]} payload: {event_type: handled} next: listen ``` `add_initial_arrival` starts the consumer, and the tasks `listen` and `busy` take `get`, `next` and `service_time`. ```python app.add_initial_arrival("consumer", size, spawn="listen") ``` ```python listen_payload = Template( { "event_type": "received", "late": {"gen": "expr", "expr": "item.sent < t"}, "text": {"gen": "expr", "expr": "item.text"}, }, name="listen", ) @app.task(name="listen", get={"store": "pipe"}, next="busy") def listen(task_id): """Takes the next message.""" return listen_payload @app.task( name="busy", service_time=generator({"gen": "integer", "bounds": [4, 8]}), next="listen", ) def busy(task_id): """Works on the message.""" return {"event_type": "handled"} ``` `message_consumer` is SimPy's function. The last block starts the generator and the consumer. ```python def message_consumer(key, in_pipe): def publish(task, number, value): env.publish_event(key, value, task=task, instance=number) while True: listen = next(numbers["listen"]) publish("listen", listen, {"status": "queued"}) msg = yield in_pipe.get() publish("listen", listen, {"status": "started"}) # The message is late when it waited in the pipe received = { "event_type": "received", "late": msg[0] < env.now, "text": msg[1], } publish("listen", listen, received) busy = next(numbers["busy"]) publish("busy", busy, {"status": "started"}) yield env.timeout(int(busy_times.integers(4, 9))) publish("busy", busy, {"event_type": "handled"}) ``` ```python env.process(message_generator("Generator A", pipe)) for number in range(1, size + 1): env.process(message_consumer(f"consumer-{number}", pipe)) ``` ### Broadcast Pipe SimPy's `BroadcastPipe` keeps one store for each consumer and puts each message into all of them. ```python class BroadcastPipe: """A Broadcast pipe that allows one process to send messages to many. This construct is useful when message consumers are running at different rates than message generators and provides an event buffering to the consuming processes. The parameters are used to create a new :class:`~simpy.resources.store.Store` instance each time :meth:`get_output_conn()` is called. """ def __init__(self, env, capacity=simpy.core.Infinity): self.env = env self.capacity = capacity self.pipes = [] def put(self, value): """Broadcast a *value* to all receivers.""" if not self.pipes: raise RuntimeError('There are no output pipes.') events = [store.put(value) for store in self.pipes] return self.env.all_of(events) # Condition event for all "events" def get_output_conn(self): """Get a new output connection for this broadcast pipe. The return value is a :class:`~simpy.resources.store.Store`. """ pipe = simpy.Store(self.env, capacity=self.capacity) self.pipes.append(pipe) return pipe ``` In `process_communication_broadcast.yaml`, `pipe` is a store family with two members. The `speak` task makes the message and goes to `send`, which opens one branch for each member of `pipe` and puts the message into it. Each consumer has an attribute `idx` and takes from the member with that number. ```yaml stores: pipe: {family: true, members: 2} ``` ```yaml consumer_a: initial: 1 spawn: listen attributes: {idx: 0} consumer_b: initial: 1 spawn: listen attributes: {idx: 1} ``` ```yaml speak: payload: event_type: said sent: {gen: expr, expr: t} text: gen: format template: "Generator A says hello at {now:g}" names: now: {gen: expr, expr: t} next: send send: open: sends: each: "members(pipe)" branch: put: store: {of: pipe, key: "each.value"} payload: {event_type: sent} ``` ```yaml listen: get: store: {of: pipe, key: "attr.idx"} payload: event_type: received late: {gen: expr, expr: "item.sent < t"} text: {gen: expr, expr: "item.text"} next: busy busy: service_time: {gen: integer, bounds: [4, 8]} payload: {event_type: handled} next: listen ``` `add_store` takes `family=True` and `members=2`, and the `send` task opens one branch for each member. ```python app.add_store("pipe", family=True, members=2) ``` ```python app.add_initial_arrival("consumer_a", size, spawn="listen", attributes={"idx": 0}) app.add_initial_arrival("consumer_b", 1, spawn="listen", attributes={"idx": 1}) ``` ```python speak_payload = Template( { "event_type": "said", "sent": {"gen": "expr", "expr": "t"}, "text": { "gen": "format", "template": "Generator A says hello at {now:g}", "names": {"now": {"gen": "expr", "expr": "t"}}, }, }, name="speak", ) # The message is the payload of `speak`, which each put of `send` takes as its item @app.task(name="speak", next="send") def speak(task_id): """Makes a message.""" return speak_payload @app.task( name="send", open={ "sends": { "each": "members(pipe)", "branch": {"put": {"store": {"of": "pipe", "key": "each.value"}}}, } }, ) def send(task_id): """Puts the message into every pipe.""" return {"event_type": "sent"} ``` ```python listen_payload = Template( { "event_type": "received", "late": {"gen": "expr", "expr": "item.sent < t"}, "text": {"gen": "expr", "expr": "item.text"}, }, name="listen", ) @app.task( name="listen", get={"store": {"of": "pipe", "key": "attr.idx"}}, next="busy" ) def listen(task_id): """Takes the next message of its own pipe.""" return listen_payload @app.task( name="busy", service_time=generator({"gen": "integer", "bounds": [4, 8]}), next="listen", ) def busy(task_id): """Works on the message.""" return {"event_type": "handled"} ``` `BroadcastPipe` is SimPy's class, with one store for each consumer. The generator and the consumer are SimPy's functions again. ```python class BroadcastPipe: """A pipe that puts each message into the store of every consumer.""" def __init__(self, env: DynamicRealtimeEnvironment): self.env = env self.pipes: list = [] def put(self, value): """Puts `value` into every output store.""" return self.env.all_of([pipe.put(value) for pipe in self.pipes]) def get_output_conn(self): """A new store that receives every message from now on.""" pipe = simpy.Store(self.env) self.pipes.append(pipe) return pipe ``` ```python def message_generator(name, out_pipe): for number in itertools.count(1): yield env.timeout(int(gaps.integers(6, 11))) key = f"generator-{number}" msg = { "event_type": "said", "sent": env.now, "text": f"{name} says hello at {env.now:g}", } out_pipe.put(msg) # not waited for, as in SimPy's example env.publish_event(key, msg, task="speak", instance=number - 1) env.publish_event( key, {"event_type": "sent"}, task="send", instance=number - 1 ) ``` ```python def message_consumer(key, in_pipe): def publish(task, number, value): env.publish_event(key, value, task=task, instance=number) while True: listen = next(numbers["listen"]) publish("listen", listen, {"status": "queued"}) msg = yield in_pipe.get() publish("listen", listen, {"status": "started"}) # The message is late when it waited in the pipe received = { "event_type": "received", "late": msg["sent"] < env.now, "text": msg["text"], } publish("listen", listen, received) busy = next(numbers["busy"]) publish("busy", busy, {"status": "started"}) yield env.timeout(int(busy_times.integers(4, 9))) publish("busy", busy, {"event_type": "handled"}) ``` ```python env.process(message_generator("Generator A", bc_pipe)) for number in range(1, size + 1): env.process(message_consumer(f"consumer_a-{number}", pipes[0])) env.process(message_consumer("consumer_b-1", pipes[1])) ``` ### Run It `desflow run` loads the blueprint and runs it unpaced, because it sets `factor: 0`. Each record is printed to the terminal. **Quick Start** `desflow examples get` downloads the example at the release you install, into a folder of its own. Pick uv or pip: ```bash # 1. Install uv tool install desflow # 2. Download the example desflow examples get simpy-process-communication --api yaml cd simpy-process-communication/yaml # 3. Run it desflow run process_communication.yaml ``` ```bash # 1. Install pip install desflow # 2. Download the example desflow examples get simpy-process-communication --api yaml cd simpy-process-communication/yaml # 3. Run it desflow run process_communication.yaml ``` The one to many run is the second blueprint: ```bash desflow run process_communication_broadcast.yaml ``` The script builds the model with the builder API, runs it unpaced, and prints each record to the terminal. **Quick Start** `desflow examples get` downloads the example at the release you install, into a folder of its own. Pick uv or pip: ```bash # 1. Install uv tool install desflow # 2. Download the example desflow examples get simpy-process-communication --api builder cd simpy-process-communication/builder # 3. Run it uv run --no-project --with desflow process_communication_example.py ``` ```bash # 1. Install pip install desflow # 2. Download the example desflow examples get simpy-process-communication --api builder cd simpy-process-communication/builder # 3. Run it python process_communication_example.py ``` The one to many run is the second file: ```bash uv run --no-project --with desflow process_communication_broadcast_example.py ``` The script wires the model by hand on `DynamicRealtimeEnvironment`, runs it unpaced, and prints each record to the terminal. **Quick Start** `desflow examples get` downloads the example at the release you install, into a folder of its own. Pick uv or pip: ```bash # 1. Install uv tool install desflow # 2. Download the example desflow examples get simpy-process-communication --api low-level cd simpy-process-communication/low-level # 3. Run it uv run --no-project --with desflow process_communication_example.py ``` ```bash # 1. Install pip install desflow # 2. Download the example desflow examples get simpy-process-communication --api low-level cd simpy-process-communication/low-level # 3. Run it python process_communication_example.py ``` The one to many run is the second file: ```bash uv run --no-project --with desflow process_communication_broadcast_example.py ``` ______________________________________________________________________ ## Check the Result In the one to one run the generator sends 13 messages in the 100 seconds, and the consumer receives 12. The first message is sent at 8 seconds and received at once. The consumer finishes 11 of them. No message is late: the consumer is free each time one of the first 12 messages is sent, so it takes each one at once. The 13th message is sent at 99 seconds, while the consumer is still working on the 12th, so it is not taken before the run ends. In the one to many run the generator also sends 13 messages, and each consumer receives 12. No receipt is late. SimPy prints one line for each message taken, and its output for the one to one run is shown below. desflow draws each random value from its own stream, named by the place where the value is used, such as `arrivals.generator.gap`. A seed of 42 therefore gives different numbers from SimPy's `random.seed(42)`. The system is the same. The figures are not. ```text Process communication One-to-one pipe communication at time 6: Consumer A received message: Generator A says hello at 6. at time 12: Consumer A received message: Generator A says hello at 12. at time 19: Consumer A received message: Generator A says hello at 19. at time 26: Consumer A received message: Generator A says hello at 26. at time 36: Consumer A received message: Generator A says hello at 36. at time 46: Consumer A received message: Generator A says hello at 46. at time 52: Consumer A received message: Generator A says hello at 52. at time 58: Consumer A received message: Generator A says hello at 58. LATE Getting Message: at time 66: Consumer A received message: Generator A says hello at 65 at time 75: Consumer A received message: Generator A says hello at 75. at time 85: Consumer A received message: Generator A says hello at 85. at time 95: Consumer A received message: Generator A says hello at 95. One-to-many pipe communication at time 10: Consumer A received message: Generator A says hello at 10. at time 10: Consumer B received message: Generator A says hello at 10. at time 18: Consumer A received message: Generator A says hello at 18. at time 18: Consumer B received message: Generator A says hello at 18. at time 27: Consumer A received message: Generator A says hello at 27. at time 27: Consumer B received message: Generator A says hello at 27. at time 34: Consumer A received message: Generator A says hello at 34. at time 34: Consumer B received message: Generator A says hello at 34. at time 40: Consumer A received message: Generator A says hello at 40. LATE Getting Message: at time 41: Consumer B received message: Generator A says hello at 40 at time 46: Consumer A received message: Generator A says hello at 46. LATE Getting Message: at time 47: Consumer B received message: Generator A says hello at 46 at time 56: Consumer A received message: Generator A says hello at 56. at time 56: Consumer B received message: Generator A says hello at 56. at time 65: Consumer A received message: Generator A says hello at 65. at time 65: Consumer B received message: Generator A says hello at 65. at time 74: Consumer A received message: Generator A says hello at 74. at time 74: Consumer B received message: Generator A says hello at 74. at time 82: Consumer A received message: Generator A says hello at 82. at time 82: Consumer B received message: Generator A says hello at 82. at time 92: Consumer A received message: Generator A says hello at 92. at time 92: Consumer B received message: Generator A says hello at 92. at time 98: Consumer B received message: Generator A says hello at 98. at time 98: Consumer A received message: Generator A says hello at 98. ``` The three versions in desflow print the same records, which [a test](https://github.com/jaehyeon-kim/desflow/blob/v1.3.0/tests/docs/test_example_twins.py) checks by running each version unpaced. Each record has `sim_ts`, the simulation time, and a key for the entity it belongs to. The statistics and the parameters that a live run can change are in the same stream, which SimPy's file does not have. ______________________________________________________________________ ## Full Files Full files The blueprint is `process_communication.yaml`. The second blueprint, `process_communication_broadcast.yaml`, is the one to many run. ```yaml # Process Communication: SimPy's process_communication.py example, one to one, in YAML. # # The YAML version of process_communication_example.py, which --api builder downloads. # A generator puts a message into a store every 6 to 10 seconds, stamped with the time # it was sent. A consumer takes each message and then works on it for 4 to 8 seconds, # so it is late for some messages: `late` is true when the message waited in the store. # process_communication_broadcast.yaml sends each message to two consumers. # # Each value is drawn from desflow's random sequence for its place in the file, so the # numbers differ from those SimPy prints. # # Needs no containers. Runs unpaced and ends after 100 simulation seconds. # Run it from its folder with: desflow run process_communication.yaml simulation: {sim_id: Pipes, factor: 0, random_seed: 42} egress: - {type: Console} stores: pipe: {} arrivals: generator: gap: {gen: integer, bounds: [6, 10]} spawn: speak consumer: {initial: 1, spawn: listen} tasks: speak: payload: {event_type: said} # The generator does not wait for its put, as SimPy's `out_pipe.put(msg)` does not put: store: pipe wait: false item: sent: {gen: expr, expr: t} text: gen: format template: "Generator A says hello at {now:g}" names: now: {gen: expr, expr: t} listen: get: {store: pipe} payload: event_type: received late: {gen: expr, expr: "item.sent < t"} text: {gen: expr, expr: "item.text"} next: busy busy: service_time: {gen: integer, bounds: [4, 8]} payload: {event_type: handled} next: listen run: {until: 100} ``` ```yaml # Process Communication: SimPy's process_communication.py example, broadcast, in YAML. # # The YAML version of process_communication_broadcast_example.py, which --api builder # downloads. A generator makes a message every 6 to 10 seconds, stamped with the time it # was sent, and puts a copy into each of two pipes without waiting. Two consumers each # take the messages of their own pipe and work on each for 4 to 8 seconds, so they are # late for some messages: `late` is true when the message waited in its pipe. # # Each value is drawn from desflow's random sequence for its place in the file, so the # numbers differ from those SimPy prints. # # Needs no containers. Runs unpaced and ends after 100 simulation seconds. # Run it from its folder with: desflow run process_communication_broadcast.yaml simulation: {sim_id: Pipes, factor: 0, random_seed: 42} egress: - {type: Console} stores: pipe: {family: true, members: 2} arrivals: generator: gap: {gen: integer, bounds: [6, 10]} spawn: speak consumer_a: initial: 1 spawn: listen attributes: {idx: 0} consumer_b: initial: 1 spawn: listen attributes: {idx: 1} tasks: # The message is the payload of `speak`, which each put of `send` takes as its item speak: payload: event_type: said sent: {gen: expr, expr: t} text: gen: format template: "Generator A says hello at {now:g}" names: now: {gen: expr, expr: t} next: send send: open: sends: each: "members(pipe)" branch: put: store: {of: pipe, key: "each.value"} payload: {event_type: sent} listen: get: store: {of: pipe, key: "attr.idx"} payload: event_type: received late: {gen: expr, expr: "item.sent < t"} text: {gen: expr, expr: "item.text"} next: busy busy: service_time: {gen: integer, bounds: [4, 8]} payload: {event_type: handled} next: listen run: {until: 100} ``` The script builds the model with the builder API. ```python """Process Communication: SimPy's process_communication.py example, one to one, builder API. A generator puts a message into a store every 6 to 10 seconds, stamped with the time it was sent. A consumer takes each message and then works on it for 4 to 8 seconds, so it is late for some messages: `late` is true when the message waited in the store. `process_communication_broadcast_example.py` sends each message to two consumers. Each value is drawn from desflow's random sequence for its place in the model, so the numbers differ from those SimPy prints. Needs no containers. Runs unpaced and ends after 100 simulation seconds. """ import logging from desflow import ConsoleEgress, SimulationContext from desflow.values import Template, generator def build(size: int = 1) -> SimulationContext: """Builds the pipe, with `size` consumers.""" app = SimulationContext(sim_id="Pipes", factor=0, random_seed=42) app.add_egress(ConsoleEgress()) app.add_store("pipe") app.add_arrival( "generator", gap=generator({"gen": "integer", "bounds": [6, 10]}), spawn="speak", ) app.add_initial_arrival("consumer", size, spawn="listen") # The generator does not wait for its put, as SimPy's `out_pipe.put(msg)` does not @app.task( name="speak", put={ "store": "pipe", "wait": False, "item": { "sent": generator({"gen": "expr", "expr": "t"}), "text": generator( { "gen": "format", "template": "Generator A says hello at {now:g}", "names": {"now": {"gen": "expr", "expr": "t"}}, } ), }, }, ) def speak(task_id): """Puts a message into the pipe.""" return {"event_type": "said"} listen_payload = Template( { "event_type": "received", "late": {"gen": "expr", "expr": "item.sent < t"}, "text": {"gen": "expr", "expr": "item.text"}, }, name="listen", ) @app.task(name="listen", get={"store": "pipe"}, next="busy") def listen(task_id): """Takes the next message.""" return listen_payload @app.task( name="busy", service_time=generator({"gen": "integer", "bounds": [4, 8]}), next="listen", ) def busy(task_id): """Works on the message.""" return {"event_type": "handled"} return app app = build() def run(model: SimulationContext = app) -> None: """Runs 100 simulation seconds.""" model.run(until=100) if __name__ == "__main__": logging.basicConfig(level=logging.INFO, format="%(levelname)s %(message)s") run() ``` ```python """Process Communication: SimPy's process_communication.py example, broadcast, builder API. A generator makes a message every 6 to 10 seconds, stamped with the time it was sent, and puts a copy into each of two pipes without waiting. Two consumers each take the messages of their own pipe and work on each for 4 to 8 seconds, so they are late for some messages: `late` is true when the message waited in its pipe. Each value is drawn from desflow's random sequence for its place in the model, so the numbers differ from those SimPy prints. Needs no containers. Runs unpaced and ends after 100 simulation seconds. """ import logging from desflow import ConsoleEgress, SimulationContext from desflow.values import Template, generator def build(size: int = 1) -> SimulationContext: """Builds the two pipes, with `size` consumers on the first.""" app = SimulationContext(sim_id="Pipes", factor=0, random_seed=42) app.add_egress(ConsoleEgress()) app.add_store("pipe", family=True, members=2) app.add_arrival( "generator", gap=generator({"gen": "integer", "bounds": [6, 10]}), spawn="speak", ) app.add_initial_arrival("consumer_a", size, spawn="listen", attributes={"idx": 0}) app.add_initial_arrival("consumer_b", 1, spawn="listen", attributes={"idx": 1}) speak_payload = Template( { "event_type": "said", "sent": {"gen": "expr", "expr": "t"}, "text": { "gen": "format", "template": "Generator A says hello at {now:g}", "names": {"now": {"gen": "expr", "expr": "t"}}, }, }, name="speak", ) # The message is the payload of `speak`, which each put of `send` takes as its item @app.task(name="speak", next="send") def speak(task_id): """Makes a message.""" return speak_payload @app.task( name="send", open={ "sends": { "each": "members(pipe)", "branch": {"put": {"store": {"of": "pipe", "key": "each.value"}}}, } }, ) def send(task_id): """Puts the message into every pipe.""" return {"event_type": "sent"} listen_payload = Template( { "event_type": "received", "late": {"gen": "expr", "expr": "item.sent < t"}, "text": {"gen": "expr", "expr": "item.text"}, }, name="listen", ) @app.task( name="listen", get={"store": {"of": "pipe", "key": "attr.idx"}}, next="busy" ) def listen(task_id): """Takes the next message of its own pipe.""" return listen_payload @app.task( name="busy", service_time=generator({"gen": "integer", "bounds": [4, 8]}), next="listen", ) def busy(task_id): """Works on the message.""" return {"event_type": "handled"} return app app = build() def run(model: SimulationContext = app) -> None: """Runs 100 simulation seconds.""" model.run(until=100) if __name__ == "__main__": logging.basicConfig(level=logging.INFO, format="%(levelname)s %(message)s") run() ``` The script wires the model by hand on `DynamicRealtimeEnvironment`, with SimPy's own processes. ```python """Process Communication: SimPy's process_communication.py example, one to one, low-level API. The low-level version of `builder/simpy/process_communication_example.py`: SimPy's own `message_generator` and `message_consumer` on a `DynamicRealtimeEnvironment`. They publish with `publish_event` the records that the YAML and builder versions publish: each task's `queued` and `started`, its own events, and the number of the task's instance. A generator puts a message into a store every 6 to 10 seconds, stamped with the time it was sent. A consumer takes each message and then works on it for 4 to 8 seconds, so it is late for some messages. Each value is drawn from desflow's `Sampler`, from the random sequence the YAML and builder versions use for the same place, so the three versions publish the same records. Needs no containers. Runs unpaced and ends after 100 simulation seconds. """ import itertools import logging import simpy from desflow import ConsoleEgress, DynamicRealtimeEnvironment, Sampler UNTIL = 100 def build(env: DynamicRealtimeEnvironment, size: int = 1) -> None: """Starts the generator and `size` consumers on `env`.""" sampler = Sampler(seed=42) gaps = sampler.generator("arrivals.generator.gap") busy_times = sampler.generator("tasks.busy.service_time") pipe = simpy.Store(env) numbers = {task: itertools.count() for task in ("listen", "busy")} def message_generator(name, out_pipe): for number in itertools.count(1): yield env.timeout(int(gaps.integers(6, 11))) msg = (env.now, f"{name} says hello at {env.now:g}") out_pipe.put(msg) # not waited for, as in SimPy's example env.publish_event( f"generator-{number}", {"event_type": "said"}, task="speak", instance=number - 1, ) def message_consumer(key, in_pipe): def publish(task, number, value): env.publish_event(key, value, task=task, instance=number) while True: listen = next(numbers["listen"]) publish("listen", listen, {"status": "queued"}) msg = yield in_pipe.get() publish("listen", listen, {"status": "started"}) # The message is late when it waited in the pipe received = { "event_type": "received", "late": msg[0] < env.now, "text": msg[1], } publish("listen", listen, received) busy = next(numbers["busy"]) publish("busy", busy, {"status": "started"}) yield env.timeout(int(busy_times.integers(4, 9))) publish("busy", busy, {"event_type": "handled"}) env.process(message_generator("Generator A", pipe)) for number in range(1, size + 1): env.process(message_consumer(f"consumer-{number}", pipe)) def run() -> None: """Runs 100 simulation seconds.""" env = DynamicRealtimeEnvironment(factor=0) env.setup_egress([ConsoleEgress()]) build(env) try: env.run(until=UNTIL) finally: env.teardown() if __name__ == "__main__": logging.basicConfig(level=logging.INFO, format="%(levelname)s %(message)s") run() ``` ```python """Process Communication: SimPy's process_communication.py example, broadcast, low-level API. The low-level version of `builder/simpy/process_communication_broadcast_example.py`: SimPy's own `BroadcastPipe`, `message_generator` and `message_consumer` on a `DynamicRealtimeEnvironment`. They publish with `publish_event` the records that the YAML and builder versions publish: each task's `queued` and `started`, its own events, and the number of the task's instance. A generator makes a message every 6 to 10 seconds, stamped with the time it was sent, and puts a copy into each of two pipes without waiting. Two consumers each take the messages of their own pipe and work on each for 4 to 8 seconds. Each value is drawn from desflow's `Sampler`, from the random sequence the YAML and builder versions use for the same place, so the three versions publish the same records. Needs no containers. Runs unpaced and ends after 100 simulation seconds. """ import itertools import logging import simpy from desflow import ConsoleEgress, DynamicRealtimeEnvironment, Sampler UNTIL = 100 class BroadcastPipe: """A pipe that puts each message into the store of every consumer.""" def __init__(self, env: DynamicRealtimeEnvironment): self.env = env self.pipes: list = [] def put(self, value): """Puts `value` into every output store.""" return self.env.all_of([pipe.put(value) for pipe in self.pipes]) def get_output_conn(self): """A new store that receives every message from now on.""" pipe = simpy.Store(self.env) self.pipes.append(pipe) return pipe def build(env: DynamicRealtimeEnvironment, size: int = 1) -> None: """Starts the generator, `size` consumers on the first pipe and one on the second.""" sampler = Sampler(seed=42) gaps = sampler.generator("arrivals.generator.gap") busy_times = sampler.generator("tasks.busy.service_time") bc_pipe = BroadcastPipe(env) pipes = [bc_pipe.get_output_conn(), bc_pipe.get_output_conn()] numbers = {task: itertools.count() for task in ("listen", "busy")} def message_generator(name, out_pipe): for number in itertools.count(1): yield env.timeout(int(gaps.integers(6, 11))) key = f"generator-{number}" msg = { "event_type": "said", "sent": env.now, "text": f"{name} says hello at {env.now:g}", } out_pipe.put(msg) # not waited for, as in SimPy's example env.publish_event(key, msg, task="speak", instance=number - 1) env.publish_event( key, {"event_type": "sent"}, task="send", instance=number - 1 ) def message_consumer(key, in_pipe): def publish(task, number, value): env.publish_event(key, value, task=task, instance=number) while True: listen = next(numbers["listen"]) publish("listen", listen, {"status": "queued"}) msg = yield in_pipe.get() publish("listen", listen, {"status": "started"}) # The message is late when it waited in the pipe received = { "event_type": "received", "late": msg["sent"] < env.now, "text": msg["text"], } publish("listen", listen, received) busy = next(numbers["busy"]) publish("busy", busy, {"status": "started"}) yield env.timeout(int(busy_times.integers(4, 9))) publish("busy", busy, {"event_type": "handled"}) env.process(message_generator("Generator A", bc_pipe)) for number in range(1, size + 1): env.process(message_consumer(f"consumer_a-{number}", pipes[0])) env.process(message_consumer("consumer_b-1", pipes[1])) def run() -> None: """Runs 100 simulation seconds.""" env = DynamicRealtimeEnvironment(factor=0) env.setup_egress([ConsoleEgress()]) build(env) try: env.run(until=UNTIL) finally: env.teardown() if __name__ == "__main__": logging.basicConfig(level=logging.INFO, format="%(levelname)s %(message)s") run() ``` This is SimPy 4.1.2's `process_communication.py`, with SimPy's licence notice added at the top and comment lines that mark the pieces shown above. Run with Python, it prints the output shown under Check the Result. ```python # SimPy 4.1.2, docs/examples/code/process_communication.py, under SimPy's licence (LICENSE.rst): # # The MIT License (MIT) # # Copyright (c) 2013 Ontje Lünsdorf and Stefan Scherfke (also see AUTHORS.txt) # # Permission is hereby granted, free of charge, to any person obtaining a copy of # this software and associated documentation files (the "Software"), to deal in # the Software without restriction, including without limitation the rights to # use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of # the Software, and to permit persons to whom the Software is furnished to do so, # subject to the following conditions: # # The above copyright notice and this permission notice shall be included in all # copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS # FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR # COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER # IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN # CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. """ Process communication example Covers: - Resources: Store Scenario: This example shows how to interconnect simulation model elements together using :class:`~simpy.resources.store.Store` for one-to-one, and many-to-one asynchronous processes. For one-to-many a simple BroadCastPipe class is constructed from Store. When Useful: When a consumer process does not always wait on a generating process and these processes run asynchronously. This example shows how to create a buffer and also tell is the consumer process was late yielding to the event from a generating process. This is also useful when some information needs to be broadcast to many receiving processes Finally, using pipes can simplify how processes are interconnected to each other in a simulation model. Example By: Keith Smith """ import random import simpy import simpy.core RANDOM_SEED = 42 SIM_TIME = 100 class BroadcastPipe: """A Broadcast pipe that allows one process to send messages to many. This construct is useful when message consumers are running at different rates than message generators and provides an event buffering to the consuming processes. The parameters are used to create a new :class:`~simpy.resources.store.Store` instance each time :meth:`get_output_conn()` is called. """ def __init__(self, env, capacity=simpy.core.Infinity): self.env = env self.capacity = capacity self.pipes = [] def put(self, value): """Broadcast a *value* to all receivers.""" if not self.pipes: raise RuntimeError('There are no output pipes.') events = [store.put(value) for store in self.pipes] return self.env.all_of(events) # Condition event for all "events" def get_output_conn(self): """Get a new output connection for this broadcast pipe. The return value is a :class:`~simpy.resources.store.Store`. """ pipe = simpy.Store(self.env, capacity=self.capacity) self.pipes.append(pipe) return pipe def message_generator(name, env, out_pipe): """A process which randomly generates messages.""" while True: # wait for next transmission yield env.timeout(random.randint(6, 10)) # messages are time stamped to later check if the consumer was # late getting them. Note, using event.triggered to do this may # result in failure due to FIFO nature of simulation yields. # (i.e. if at the same env.now, message_generator puts a message # in the pipe first and then message_consumer gets from pipe, # the event.triggered will be True in the other order it will be # False msg = (env.now, f'{name} says hello at {env.now}') out_pipe.put(msg) def message_consumer(name, env, in_pipe): """A process which consumes messages.""" while True: # Get event for message pipe msg = yield in_pipe.get() if msg[0] < env.now: # if message was already put into pipe, then # message_consumer was late getting to it. Depending on what # is being modeled this, may, or may not have some # significance print( f'LATE Getting Message: at time {env.now}: ' f'{name} received message: {msg[1]}' ) else: # message_consumer is synchronized with message_generator print(f'at time {env.now}: {name} received message: {msg[1]}.') # Process does some other work, which may result in missing messages yield env.timeout(random.randint(4, 8)) # Setup and start the simulation print('Process communication') random.seed(RANDOM_SEED) env = simpy.Environment() # For one-to-one or many-to-one type pipes, use Store pipe = simpy.Store(env) env.process(message_generator('Generator A', env, pipe)) env.process(message_consumer('Consumer A', env, pipe)) print('\nOne-to-one pipe communication\n') env.run(until=SIM_TIME) # For one-to many use BroadcastPipe # (Note: could also be used for one-to-one,many-to-one or many-to-many) env = simpy.Environment() bc_pipe = BroadcastPipe(env) env.process(message_generator('Generator A', env, bc_pipe)) env.process(message_consumer('Consumer A', env, bc_pipe.get_output_conn())) env.process(message_consumer('Consumer B', env, bc_pipe.get_output_conn())) print('\nOne-to-many pipe communication\n') env.run(until=SIM_TIME) ``` ______________________________________________________________________ ## Sources - [SimPy 4.1.2, Process Communication](https://simpy.readthedocs.io/en/4.1.2/examples/process_communication.html): the original code and its output. - [SimPy's licence](https://gitlab.com/team-simpy/simpy/-/blob/master/LICENSE.rst): MIT, Copyright (c) 2013 Ontje Lünsdorf and Stefan Scherfke. The SimPy file above carries this notice. - [`examples/` in the desflow repository](https://github.com/jaehyeon-kim/desflow/tree/v1.3.0/examples): the three versions in desflow, under `simpy/` in each folder. # Event Latency A sender puts a message on a cable every 5 seconds, the cable delivers it 10 seconds later, and a receiver takes each message as it arrives. This is SimPy's Event Latency example, written in desflow. ______________________________________________________________________ ## Before You Start SimPy's example keeps the delay of a cable outside the sender and the receiver. The sender puts a message on the cable every 5 time units. The cable holds each message for 10 time units and then puts it into a store. The receiver takes each message from the store. The run lasts 100 time units. SimPy counts no unit, and desflow reads each unit as one second. Nothing in this example is random, so the times are the same as SimPy's. The example needs only desflow, which each Quick Start in [Run It](#run-it) installs, and no other service. `desflow examples get simpy-latency --api yaml` downloads it, as [Get an Example](https://jaehyeon.me/desflow/latest/cli/#get-an-example) shows. [SimPy Examples](https://jaehyeon.me/desflow/latest/simpy/examples/index.md) says how these pages read SimPy's times and numbers. SimPy's own page for the example is [on its documentation site](https://simpy.readthedocs.io/en/4.1.2/examples/latency.html). ______________________________________________________________________ ## Steps ### Cable Delays Messages SimPy's `Cable` class starts a process for each message. The process waits for the delay and then puts the message into a store. The sender and the receiver never see the delay. ```python class Cable: """This class represents the propagation through a cable.""" def __init__(self, env, delay): self.env = env self.delay = delay self.store = simpy.Store(env) def latency(self, value): yield self.env.timeout(self.delay) self.store.put(value) def put(self, value): self.env.process(self.latency(value)) def get(self): return self.store.get() ``` A store named `cable` holds the delivered messages. The `latency` task is the cable's process: it waits `service_time: 10` seconds and then puts its message, `arg.msg`, into the store. ```yaml stores: cable: {} ``` ```yaml latency: service_time: 10 put: store: cable item: {gen: expr, expr: "arg.msg"} payload: {event_type: delivered} ``` `add_store` declares the store, and a `latency` task with `service_time` and `put` is the cable's process. ```python app.add_store("cable") ``` ```python @app.task( name="latency", service_time=10, put={"store": "cable", "item": generator({"gen": "expr", "expr": "arg.msg"})}, ) def latency(task_id): """Delivers the message into the cable's store after the delay.""" return {"event_type": "delivered"} ``` The low-level version keeps SimPy's `Cable` class. Its `latency` method also publishes the task's records with `publish_event`. ```python class Cable: """A cable that delivers each value `delay` seconds after it was put in.""" def __init__(self, env: DynamicRealtimeEnvironment, delay: float): self.env = env self.delay = delay self.store = simpy.Store(env) self.numbers = itertools.count(1) self.instances = itertools.count() def latency(self, name, value): number = next(self.instances) def publish(record): self.env.publish_event(name, record, task="latency", instance=number) publish({"status": "started"}) yield self.env.timeout(self.delay) done = self.store.put(value) done.callbacks.append(lambda _: publish({"event_type": "delivered"})) def put(self, value): """Sends `value`, which travels on its own.""" name = f"latency-{next(self.numbers)}" self.env.process(self.latency(name, value)) def get(self): """The next value delivered.""" return self.store.get() ``` ### Sender Sends SimPy's `sender` waits 5 time units, then puts a message on the cable, and repeats. ```python def sender(env, cable): """A process which randomly generates messages.""" while True: # wait for next transmission yield env.timeout(5) cable.put(f'Sender sent this at {env.now}') ``` An arrival with a constant gap of 5 seconds starts one `send` task for each message. The task starts a `latency` task with the message text as its argument and goes on at once, so the sender never waits for the cable. ```yaml sender: {dist: constant, value: 5, spawn: send} ``` ```yaml send: payload: {event_type: sent} # Each message travels on its own, so the sender goes on at once spawn: task: latency args: msg: gen: format template: "Sender sent this at {now:g}" names: now: {gen: expr, expr: t} ``` `add_arrival` starts one `send` task every 5 seconds, and the task's `spawn` starts the `latency` task with the message as its argument. ```python app.add_arrival("sender", "constant", value=5, spawn="send") ``` ```python # Each message travels on its own, so the sender goes on at once @app.task( name="send", spawn={ "task": "latency", "args": { "msg": generator( { "gen": "format", "template": "Sender sent this at {now:g}", "names": {"now": {"gen": "expr", "expr": "t"}}, } ) }, }, ) def send(task_id): """Sends a message.""" return {"event_type": "sent"} ``` The sender is SimPy's loop. It also publishes a `sent` record for each message. ```python def sender(): for number in itertools.count(1): yield env.timeout(5) env.publish_event( f"sender-{number}", {"event_type": "sent"}, task="send", instance=number - 1, ) cable.put(f"Sender sent this at {env.now:g}") ``` ### Receiver Gets SimPy's `receiver` takes a message from the cable and prints it, and repeats. ```python def receiver(env, cable): """A process which consumes messages.""" while True: # Get event for message pipe msg = yield cable.get() print(f'Received this at {env.now} while {msg}') ``` One `receive` task starts at time 0. It takes the next message from the store, publishes it as `received`, and starts again with `next: receive`. ```yaml receiver: {initial: 1, spawn: receive} ``` ```yaml receive: get: {store: cable} payload: event_type: received msg: {gen: expr, expr: item} next: receive ``` `add_initial_arrival` starts one `receive` task at time 0. The task takes from the store and starts again with `next`. ```python app.add_initial_arrival("receiver", size, spawn="receive") ``` ```python receive_payload = Template( {"event_type": "received", "msg": {"gen": "expr", "expr": "item"}}, name="receive", ) @app.task(name="receive", get={"store": "cable"}, next="receive") def receive(task_id): """Takes the next message.""" return receive_payload ``` The receiver is SimPy's loop around `cable.get()`. The last block starts the sender and the receiver. ```python def receiver(name): def publish(number, record): env.publish_event(name, record, task="receive", instance=number) while True: number = next(gets) # each message is taken by a new instance publish(number, {"status": "queued"}) msg = yield cable.get() publish(number, {"status": "started"}) publish(number, {"event_type": "received", "msg": msg}) ``` ```python env.process(sender()) for number in range(1, size + 1): env.process(receiver(f"receiver-{number}")) ``` ### Run It `desflow run` loads the blueprint and runs it unpaced, because it sets `factor: 0`. Each record is printed to the terminal. **Quick Start** `desflow examples get` downloads the example at the release you install, into a folder of its own. Pick uv or pip: ```bash # 1. Install uv tool install desflow # 2. Download the example desflow examples get simpy-latency --api yaml cd simpy-latency/yaml # 3. Run it desflow run latency.yaml ``` ```bash # 1. Install pip install desflow # 2. Download the example desflow examples get simpy-latency --api yaml cd simpy-latency/yaml # 3. Run it desflow run latency.yaml ``` The script builds the model with the builder API, runs it unpaced, and prints each record to the terminal. **Quick Start** `desflow examples get` downloads the example at the release you install, into a folder of its own. Pick uv or pip: ```bash # 1. Install uv tool install desflow # 2. Download the example desflow examples get simpy-latency --api builder cd simpy-latency/builder # 3. Run it uv run --no-project --with desflow latency_example.py ``` ```bash # 1. Install pip install desflow # 2. Download the example desflow examples get simpy-latency --api builder cd simpy-latency/builder # 3. Run it python latency_example.py ``` The script wires the model by hand on `DynamicRealtimeEnvironment`, runs it unpaced, and prints each record to the terminal. **Quick Start** `desflow examples get` downloads the example at the release you install, into a folder of its own. Pick uv or pip: ```bash # 1. Install uv tool install desflow # 2. Download the example desflow examples get simpy-latency --api low-level cd simpy-latency/low-level # 3. Run it uv run --no-project --with desflow latency_example.py ``` ```bash # 1. Install pip install desflow # 2. Download the example desflow examples get simpy-latency --api low-level cd simpy-latency/low-level # 3. Run it python latency_example.py ``` ______________________________________________________________________ ## Check the Result The first message is sent at 5 seconds and the receiver gets it at 15 seconds, as the record `Sender sent this at 5`. By 100 seconds the sender has sent 19 messages and the receiver has received 17. The last one received arrives at 95 seconds and reads `Sender sent this at 85`. The two newest messages are still on the cable when the run ends. SimPy prints one line for each message received, and its file is shown below. The times in it are the same as the times here. ```text Event Latency Received this at 15 while Sender sent this at 5 Received this at 20 while Sender sent this at 10 Received this at 25 while Sender sent this at 15 Received this at 30 while Sender sent this at 20 Received this at 35 while Sender sent this at 25 Received this at 40 while Sender sent this at 30 Received this at 45 while Sender sent this at 35 Received this at 50 while Sender sent this at 40 Received this at 55 while Sender sent this at 45 Received this at 60 while Sender sent this at 50 Received this at 65 while Sender sent this at 55 Received this at 70 while Sender sent this at 60 Received this at 75 while Sender sent this at 65 Received this at 80 while Sender sent this at 70 Received this at 85 while Sender sent this at 75 Received this at 90 while Sender sent this at 80 Received this at 95 while Sender sent this at 85 ``` The three versions in desflow print the same records, which [a test](https://github.com/jaehyeon-kim/desflow/blob/v1.3.0/tests/docs/test_example_twins.py) checks by running each version unpaced. Each record has `sim_ts`, the simulation time, and a key for the entity it belongs to. The statistics and the parameters that a live run can change are in the same stream, which SimPy's file does not have. ______________________________________________________________________ ## Full Files Full files The blueprint is `latency.yaml`. ```yaml # Event Latency: SimPy's latency.py example, in YAML. # # The YAML version of latency_example.py, which --api builder downloads. A sender # sends a message every 5 seconds over a cable. The cable delivers each message into a # store 10 seconds later, and a receiver takes each message as it arrives. # # Needs no containers. Runs unpaced and ends after 100 simulation seconds. # Run it from its folder with: desflow run latency.yaml simulation: {sim_id: Cable, factor: 0, random_seed: 42} egress: - {type: Console} stores: cable: {} arrivals: sender: {dist: constant, value: 5, spawn: send} receiver: {initial: 1, spawn: receive} tasks: send: payload: {event_type: sent} # Each message travels on its own, so the sender goes on at once spawn: task: latency args: msg: gen: format template: "Sender sent this at {now:g}" names: now: {gen: expr, expr: t} latency: service_time: 10 put: store: cable item: {gen: expr, expr: "arg.msg"} payload: {event_type: delivered} receive: get: {store: cable} payload: event_type: received msg: {gen: expr, expr: item} next: receive run: {until: 100} ``` The script builds the model with the builder API. ```python """Event Latency: SimPy's latency.py example, builder API. A sender sends a message every 5 seconds over a cable. The cable delivers each message into a store 10 seconds later, and a receiver takes each message as it arrives. Needs no containers. Runs unpaced and ends after 100 simulation seconds. """ import logging from desflow import ConsoleEgress, SimulationContext from desflow.values import Template, generator def build(size: int = 1) -> SimulationContext: """Builds the cable, with `size` receivers.""" app = SimulationContext(sim_id="Cable", factor=0, random_seed=42) app.add_egress(ConsoleEgress()) app.add_store("cable") app.add_arrival("sender", "constant", value=5, spawn="send") app.add_initial_arrival("receiver", size, spawn="receive") # Each message travels on its own, so the sender goes on at once @app.task( name="send", spawn={ "task": "latency", "args": { "msg": generator( { "gen": "format", "template": "Sender sent this at {now:g}", "names": {"now": {"gen": "expr", "expr": "t"}}, } ) }, }, ) def send(task_id): """Sends a message.""" return {"event_type": "sent"} @app.task( name="latency", service_time=10, put={"store": "cable", "item": generator({"gen": "expr", "expr": "arg.msg"})}, ) def latency(task_id): """Delivers the message into the cable's store after the delay.""" return {"event_type": "delivered"} receive_payload = Template( {"event_type": "received", "msg": {"gen": "expr", "expr": "item"}}, name="receive", ) @app.task(name="receive", get={"store": "cable"}, next="receive") def receive(task_id): """Takes the next message.""" return receive_payload return app app = build() def run(model: SimulationContext = app) -> None: """Runs 100 simulation seconds.""" model.run(until=100) if __name__ == "__main__": logging.basicConfig(level=logging.INFO, format="%(levelname)s %(message)s") run() ``` The script wires the model by hand on `DynamicRealtimeEnvironment`, with SimPy's own processes. ```python """Event Latency: SimPy's latency.py example, low-level API. The low-level version of `builder/simpy/latency_example.py`: SimPy's own `Cable`, sender and receiver on a `DynamicRealtimeEnvironment`. They publish with `publish_event` the records that the YAML and builder versions publish: each task's `queued` and `started`, its own events, and the number of the task's instance. A sender sends a message every 5 seconds over a cable. The cable delivers each message into a store 10 seconds later, and a receiver takes each message as it arrives. Needs no containers. Runs unpaced and ends after 100 simulation seconds. """ import itertools import logging import simpy from desflow import ConsoleEgress, DynamicRealtimeEnvironment UNTIL = 100 class Cable: """A cable that delivers each value `delay` seconds after it was put in.""" def __init__(self, env: DynamicRealtimeEnvironment, delay: float): self.env = env self.delay = delay self.store = simpy.Store(env) self.numbers = itertools.count(1) self.instances = itertools.count() def latency(self, name, value): number = next(self.instances) def publish(record): self.env.publish_event(name, record, task="latency", instance=number) publish({"status": "started"}) yield self.env.timeout(self.delay) done = self.store.put(value) done.callbacks.append(lambda _: publish({"event_type": "delivered"})) def put(self, value): """Sends `value`, which travels on its own.""" name = f"latency-{next(self.numbers)}" self.env.process(self.latency(name, value)) def get(self): """The next value delivered.""" return self.store.get() def build(env: DynamicRealtimeEnvironment, size: int = 1) -> None: """Starts the sender and `size` receivers on `env`.""" cable = Cable(env, 10) gets = itertools.count() def sender(): for number in itertools.count(1): yield env.timeout(5) env.publish_event( f"sender-{number}", {"event_type": "sent"}, task="send", instance=number - 1, ) cable.put(f"Sender sent this at {env.now:g}") def receiver(name): def publish(number, record): env.publish_event(name, record, task="receive", instance=number) while True: number = next(gets) # each message is taken by a new instance publish(number, {"status": "queued"}) msg = yield cable.get() publish(number, {"status": "started"}) publish(number, {"event_type": "received", "msg": msg}) env.process(sender()) for number in range(1, size + 1): env.process(receiver(f"receiver-{number}")) def run() -> None: """Runs 100 simulation seconds.""" env = DynamicRealtimeEnvironment(factor=0) env.setup_egress([ConsoleEgress()]) build(env) try: env.run(until=UNTIL) finally: env.teardown() if __name__ == "__main__": logging.basicConfig(level=logging.INFO, format="%(levelname)s %(message)s") run() ``` This is SimPy 4.1.2's `latency.py`, with SimPy's licence notice added at the top and comment lines that mark the pieces shown above. Run with Python, it prints the output shown under Check the Result. ```python # SimPy 4.1.2, docs/examples/code/latency.py, under SimPy's licence (LICENSE.rst): # # The MIT License (MIT) # # Copyright (c) 2013 Ontje Lünsdorf and Stefan Scherfke (also see AUTHORS.txt) # # Permission is hereby granted, free of charge, to any person obtaining a copy of # this software and associated documentation files (the "Software"), to deal in # the Software without restriction, including without limitation the rights to # use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of # the Software, and to permit persons to whom the Software is furnished to do so, # subject to the following conditions: # # The above copyright notice and this permission notice shall be included in all # copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS # FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR # COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER # IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN # CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. """ Event Latency example Covers: - Resources: Store Scenario: This example shows how to separate the time delay of events between processes from the processes themselves. When Useful: When modeling physical things such as cables, RF propagation, etc. it better encapsulation to keep this propagation mechanism outside of the sending and receiving processes. Can also be used to interconnect processes sending messages Example by: Keith Smith """ import simpy SIM_DURATION = 100 class Cable: """This class represents the propagation through a cable.""" def __init__(self, env, delay): self.env = env self.delay = delay self.store = simpy.Store(env) def latency(self, value): yield self.env.timeout(self.delay) self.store.put(value) def put(self, value): self.env.process(self.latency(value)) def get(self): return self.store.get() def sender(env, cable): """A process which randomly generates messages.""" while True: # wait for next transmission yield env.timeout(5) cable.put(f'Sender sent this at {env.now}') def receiver(env, cable): """A process which consumes messages.""" while True: # Get event for message pipe msg = yield cable.get() print(f'Received this at {env.now} while {msg}') # Setup and start the simulation print('Event Latency') env = simpy.Environment() cable = Cable(env, 10) env.process(sender(env, cable)) env.process(receiver(env, cable)) env.run(until=SIM_DURATION) ``` ______________________________________________________________________ ## Sources - [SimPy 4.1.2, Event Latency](https://simpy.readthedocs.io/en/4.1.2/examples/latency.html): the original code and its output. - [SimPy's licence](https://gitlab.com/team-simpy/simpy/-/blob/master/LICENSE.rst): MIT, Copyright (c) 2013 Ontje Lünsdorf and Stefan Scherfke. The SimPy file above carries this notice. - [`examples/` in the desflow repository](https://github.com/jaehyeon-kim/desflow/tree/v1.3.0/examples): the three versions in desflow, under `simpy/` in each folder. # SimPy Compatibility This page lists every modelling feature of SimPy 4.1.2, 98 in all, and how to write each one in desflow. The features are grouped by the part of SimPy they belong to. Each feature starts with what it does in SimPy, in bold, and a link to the page that explains it. Below that are its form in SimPy, in YAML, in the Builder API and in the low-level API, how desflow differs in a detail where it does, and the tests that check it. - **Native: 96.** A conformance test runs a plain SimPy 4.1.2 model and the same model in desflow, and compares the event times, outcomes and balances. - **Gap: 1.** desflow gives other times, order or values than SimPy, or has no key for the feature. Each gap has an id and says how to get SimPy's behaviour. - **Difference kept by design: 1.** desflow behaves differently on purpose, for the reason given. [Where desflow Differs](#where-desflow-differs), at the end of the page, explains each gap and difference. ## Environment **Starts the simulation clock at a given time instead of 0.** Explained in [Initial time](https://jaehyeon.me/desflow/latest/user-guide/time-and-pacing/run-length/#initial-time). - SimPy: `Environment(initial_time)` - YAML: `simulation.initial_time` - Builder: `SimulationContext(..., initial_time=100)` - Low-level: `DynamicRealtimeEnvironment(initial_time=100)` Checked by 1 test in [`c6_run_control`](https://github.com/jaehyeon-kim/desflow/blob/v1.3.0/tests/conformance/test_c6_run_control.py). **Gives the current simulation time.** Explained in [Current time](https://jaehyeon.me/desflow/latest/user-guide/time-and-pacing/#read-the-current-time). - SimPy: `Environment.now` - YAML: `t` in a condition, such as `t < 110` - Builder: `context.env.now` - Low-level: `env.now` Checked by 1 test in [`c6_run_control`](https://github.com/jaehyeon-kim/desflow/blob/v1.3.0/tests/conformance/test_c6_run_control.py). **Gives the process whose code is running at this moment.** Explained in [The running process](https://jaehyeon.me/desflow/latest/user-guide/tasks-and-processes/processes/#how-it-works). - SimPy: `Environment.active_process` - YAML: `process.name`, `process.instance`, `process.target` in a condition - Builder: `context.env.active_process`; `.name` and `.target` on a process - Low-level: `env.active_process.name`, `.target` Checked by 7 tests in [`c1_process_interaction`](https://github.com/jaehyeon-kim/desflow/blob/v1.3.0/tests/conformance/test_c1_process_interaction.py) (5), [`c2_wait_for_one_or_all`](https://github.com/jaehyeon-kim/desflow/blob/v1.3.0/tests/conformance/test_c2_wait_for_one_or_all.py) (1) and [`yaml_only`](https://github.com/jaehyeon-kim/desflow/blob/v1.3.0/tests/conformance/test_yaml_only.py) (1). **Starts a process that runs alongside the one that started it, which carries on without waiting.** Explained in [Start a flow without waiting for it](https://jaehyeon.me/desflow/latest/user-guide/tasks-and-processes/signals-and-waiting/#start-a-flow-without-waiting). - SimPy: `env.process(...)` without `yield` - YAML: `spawn: {task: courier}` - Builder: `@app.task(spawn=...)`, or `context.spawn(generator)` - Low-level: `env.process(generator)` Checked by 23 tests in [`c1_processes`](https://github.com/jaehyeon-kim/desflow/blob/v1.3.0/tests/conformance/test_c1_processes.py) (2), [`builder_additions`](https://github.com/jaehyeon-kim/desflow/blob/v1.3.0/tests/conformance/test_builder_additions.py) (6) and [`yaml_only`](https://github.com/jaehyeon-kim/desflow/blob/v1.3.0/tests/conformance/test_yaml_only.py) (15). **Puts an event on the schedule with a priority and a delay.** Explained in [Schedule an event with a priority](https://jaehyeon.me/desflow/latest/user-guide/tasks-and-processes/signals-and-waiting/#actions-when-an-event-happens). - SimPy: `Environment.schedule(event, priority, delay)` - YAML: `fire: {signal: s, after: 5 s}` on a signal with `once: true` - Builder: `{"fire": {"signal": "s", "after": 5}}` in `on=`, or `context.env.schedule(event, priority, delay)` - Low-level: `env.schedule(event, priority, delay)` Checked by 5 tests in [`c6_environment`](https://github.com/jaehyeon-kim/desflow/blob/v1.3.0/tests/conformance/test_c6_environment.py) (3), [`c2_wait_for_one_or_all`](https://github.com/jaehyeon-kim/desflow/blob/v1.3.0/tests/conformance/test_c2_wait_for_one_or_all.py) (1) and [`c1_events`](https://github.com/jaehyeon-kim/desflow/blob/v1.3.0/tests/conformance/test_c1_events.py) (1). **Orders events due at the same time: an urgent event is processed before a normal one.** Explained in [Urgent and normal event priorities](https://jaehyeon.me/desflow/latest/user-guide/tasks-and-processes/signals-and-waiting/#actions-when-an-event-happens). - SimPy: `URGENT` and `NORMAL` event priorities - YAML: `fire: {signal: s, urgent: true}` or `fire: {signal: s, priority: 2}` on a signal with `once: true` - Builder: `{"fire": {"signal": "s", "urgent": True}}` in `on=` (`"priority": 2` for another priority), or `simpy.events.URGENT` in `context.env.schedule` - Low-level: `env.schedule(event, URGENT)` Checked by 3 tests in [`c6_environment`](https://github.com/jaehyeon-kim/desflow/blob/v1.3.0/tests/conformance/test_c6_environment.py) (2) and [`yaml_only`](https://github.com/jaehyeon-kim/desflow/blob/v1.3.0/tests/conformance/test_yaml_only.py) (1). **Processes events due at the same time and with the same priority in the order they were scheduled.** Explained in [Wait for one event](https://jaehyeon.me/desflow/latest/how-to/modelling/wait-for-one-or-all/#wait-for-the-first). - SimPy: Events at one time run in the order they were scheduled - YAML: `wait: {any: {stock: {signal: restocked}, limit: {timeout: 3}}}` - Builder: `wait={"any": {...}}` - Low-level: `yield a | b` - Where desflow differs: Losing signal, timeout and condition branches are dropped when the wait ends; losing child flows keep running, as SimPy leaves processes running. A request branch not yet granted when the wait ends is cancelled; a SimPy `with` block held over the rest of the task leaves it queued. Checked by 8 tests in [`c2_wait_for_one_or_all`](https://github.com/jaehyeon-kim/desflow/blob/v1.3.0/tests/conformance/test_c2_wait_for_one_or_all.py) (2) and [`yaml_only`](https://github.com/jaehyeon-kim/desflow/blob/v1.3.0/tests/conformance/test_yaml_only.py) (6). **Gives the time of the next scheduled event, or infinity when none is left.** Explained in [Inspect next event time](https://jaehyeon.me/desflow/latest/user-guide/time-and-pacing/run-length/#step-and-peek). - SimPy: `Environment.peek()` - YAML: `run: {steps: true}` publishes `peek` after each step, or `SimulationContext.from_yaml(path).start()`, then `.peek()` - Builder: `app.peek()` - Low-level: `env.peek()` Checked by 1 test in [`c6_end_conditions`](https://github.com/jaehyeon-kim/desflow/blob/v1.3.0/tests/conformance/test_c6_end_conditions.py). **Processes the next event, and raises `EmptySchedule` when none is left.** Explained in [Step one event](https://jaehyeon.me/desflow/latest/user-guide/time-and-pacing/run-length/#step-and-peek). - SimPy: `Environment.step()` - YAML: `run: {steps: true}`, or `SimulationContext.from_yaml(path).start()`, then `.step()` - Builder: `app.start()`, `app.step()`, `app.close()` - Low-level: `env.step()` - Where desflow differs: `run.steps` publishes the step count and the clock after each step of a run; stepping a model by hand is for a script, which steps the context from `from_yaml` as it steps a builder context. Checked by 4 tests in [`c6_end_conditions`](https://github.com/jaehyeon-kim/desflow/blob/v1.3.0/tests/conformance/test_c6_end_conditions.py) (1), [`c6_run_control`](https://github.com/jaehyeon-kim/desflow/blob/v1.3.0/tests/conformance/test_c6_run_control.py) (1) and [`yaml_only`](https://github.com/jaehyeon-kim/desflow/blob/v1.3.0/tests/conformance/test_yaml_only.py) (2). **Steps through the events of the model one at a time from a script.** Explained in [A step processes only the model's events](https://jaehyeon.me/desflow/latest/user-guide/time-and-pacing/run-length/#step-and-peek). - SimPy: A step processes only the model's events - YAML: `SimulationContext.from_yaml(path).start()`, then `.step()` and `.peek()`; `processes:` entries are model events - Builder: `app.start()`, `app.step()`, `app.peek()`; `add_process` functions are model events - Low-level: `env.step()` and `env.peek()` - Where desflow differs: With only desflow's own events left, `step()` raises `EmptySchedule` and `peek()` gives infinity, but the queue is not empty: `run()` and `finish()` with an `until` still process those events, and a run with no `until` ends when only they are left. Checked by 7 tests in [`c6_end_conditions`](https://github.com/jaehyeon-kim/desflow/blob/v1.3.0/tests/conformance/test_c6_end_conditions.py). **Runs until no event is left.** Explained in [A run with no until](https://jaehyeon.me/desflow/latest/user-guide/time-and-pacing/run-length/#run-length_1). - SimPy: `run()` with no `until` - YAML: `run:` with no `until` - Builder: `app.run()` with no `until` - Low-level: `env.run()` with no `until` Checked by 5 tests in [`c6_end_conditions`](https://github.com/jaehyeon-kim/desflow/blob/v1.3.0/tests/conformance/test_c6_end_conditions.py). **Runs until the clock reaches a given time.** Explained in [Stop at a time](https://jaehyeon.me/desflow/latest/user-guide/time-and-pacing/run-length/#run-length_1). - SimPy: `run(until=time)` - YAML: `run.until`, or `run.segments` for several stops with a `look` at each - Builder: `app.run(until=...)` - Low-level: `env.run(until=...)` Checked by 3 tests in [`c6_run_control`](https://github.com/jaehyeon-kim/desflow/blob/v1.3.0/tests/conformance/test_c6_run_control.py) (1) and [`yaml_only`](https://github.com/jaehyeon-kim/desflow/blob/v1.3.0/tests/conformance/test_yaml_only.py) (2). **Runs until a given event is processed.** Explained in [Stop at an event](https://jaehyeon.me/desflow/latest/user-guide/time-and-pacing/run-length/#stop-early). - SimPy: `run(until=event)` - YAML: `run.stop: {signal: closing}` beside `run.until` - Builder: `app.run(until=..., stop={"signal": "closing"})`, a signal's name, or a function returning an event - Low-level: `env.run(until=event)` - Where desflow differs: When the stop and `until` fall at the same time, `until` ends the run first, as SimPy's own `until` would. Checked by 2 tests in [`c6_end_conditions`](https://github.com/jaehyeon-kim/desflow/blob/v1.3.0/tests/conformance/test_c6_end_conditions.py). **Returns the value of the event a run stops at, or raises its exception when it failed.** Explained in [Value of a run stopped at an event](https://jaehyeon.me/desflow/latest/user-guide/time-and-pacing/run-length/#stop-early). - SimPy: The value or exception of `run(until=event)` - YAML: `SimulationContext.from_yaml(path).run()` returns the value; `desflow run` exits with an error when the stop failed - Builder: `app.run(until=..., stop=...)` and `app.finish()` return the value - Low-level: `env.run(until=event)` Checked by 1 test in [`c6_end_conditions`](https://github.com/jaehyeon-kim/desflow/blob/v1.3.0/tests/conformance/test_c6_end_conditions.py). **Continues a stopped run up to a later time.** Explained in [Run in segments](https://jaehyeon.me/desflow/latest/user-guide/time-and-pacing/run-length/#run-in-segments). - SimPy: `run(until=t)` again with a later `t` - YAML: `app = SimulationContext.from_yaml(file)`, then `app.start()`, `app.advance(until)` and `app.finish()` - Builder: `app.start()`, `app.advance(until)`, `app.finish()` - Low-level: `env.run(until=)`, called again; `env.resume_pacing()` Checked by 9 tests in [`c6_end_conditions`](https://github.com/jaehyeon-kim/desflow/blob/v1.3.0/tests/conformance/test_c6_end_conditions.py) (8) and [`c6_pacing`](https://github.com/jaehyeon-kim/desflow/blob/v1.3.0/tests/conformance/test_c6_pacing.py) (1). **Runs the callbacks of the event a run stopped at when the run continues.** Explained in [Run in segments](https://jaehyeon.me/desflow/latest/user-guide/time-and-pacing/run-length/#run-in-segments). - SimPy: Callbacks of the stopping event run when the run resumes - YAML: `app = SimulationContext.from_yaml(file)`, then `app.start()`, `app.advance(until)` and `app.finish()` - Builder: `app.start()`, `app.advance(until)`, `app.finish()` - Low-level: `env.run(until=)`, called again; `env.resume_pacing()` Checked by 9 tests in [`c6_end_conditions`](https://github.com/jaehyeon-kim/desflow/blob/v1.3.0/tests/conformance/test_c6_end_conditions.py) (8) and [`c6_pacing`](https://github.com/jaehyeon-kim/desflow/blob/v1.3.0/tests/conformance/test_c6_pacing.py) (1). **Changes how the environment schedules or steps events, in a class of your own.** Explained in [Subclass the environment](https://jaehyeon.me/desflow/latest/user-guide/writing-a-model/blueprints/#run-on-your-own-environment). - SimPy: A subclass of `Environment` - YAML: `simulation: {environment: !python module.Env}` - Builder: `SimulationContext(environment=Env)` - Low-level: `class Env(DynamicRealtimeEnvironment)` Checked by 2 tests in [`c6_environment`](https://github.com/jaehyeon-kim/desflow/blob/v1.3.0/tests/conformance/test_c6_environment.py). ## Events and Timeout **Marks an event as successful with a value, and wakes every process that waits for it.** Explained in [Signal event success and value](https://jaehyeon.me/desflow/latest/user-guide/tasks-and-processes/signals-and-waiting/#wait-signals-and-child-flows). - SimPy: `Event.succeed(value)` waking every waiter - YAML: `signals: [restocked]`, `signal: restocked` on the firing task and `wait: {signal: restocked}`; `wait: {suspend: true}` and `resume: {task, where, value, limit}` wake instances that no signal names - Builder: `add_signal`, `@app.task(signal=...)`, `wait={"signal": ...}`, or `context.signal(name).fire(value)` - Low-level: `Signal(env, name)`: `yield signal.wait()` and `signal.fire(value)` Checked by 2 tests in [`c1_process_interaction`](https://github.com/jaehyeon-kim/desflow/blob/v1.3.0/tests/conformance/test_c1_process_interaction.py) (1) and [`yaml_only`](https://github.com/jaehyeon-kim/desflow/blob/v1.3.0/tests/conformance/test_yaml_only.py) (1). **Marks an event as failed with an exception, which is raised in every process that waits for it.** Explained in [Signal event failure](https://jaehyeon.me/desflow/latest/user-guide/tasks-and-processes/signals-and-waiting/#wait-signals-and-child-flows). - SimPy: `Event.fail(exception)` - YAML: a failing task with `signal`; its waiters fail with its reason - Builder: the same, or `context.signal(name).fail(reason)` - Low-level: `signal.fail(reason)`; waiters receive `SignalFailed` Checked by 1 test in [`c1_process_interaction`](https://github.com/jaehyeon-kim/desflow/blob/v1.3.0/tests/conformance/test_c1_process_interaction.py). **Lets an event succeed or fail only once.** Explained in [One-shot event](https://jaehyeon.me/desflow/latest/user-guide/tasks-and-processes/signals-and-waiting/#one-shot-signals). - SimPy: An event that triggers once - YAML: `signals: {closing: {}}`, or `once: false` to re-arm - Builder: `add_signal(name)`, or `once=False` to re-arm - Low-level: `Signal(env, name)`, or `once=False` to re-arm Checked by 2 tests in [`c1_events`](https://github.com/jaehyeon-kim/desflow/blob/v1.3.0/tests/conformance/test_c1_events.py). **Gives an event the outcome and value of another event, so one event can set off the next.** Explained in [Actions when an event happens](https://jaehyeon.me/desflow/latest/user-guide/tasks-and-processes/signals-and-waiting/#actions-when-an-event-happens). - SimPy: `Event.trigger(event)` - YAML: `on: [{fire: {signal, from}}, {spawn: {...}}]` on a task or a signal, `fire` with `fail`, `defused` and `priority`, `when` on an entry, and `listen` on a task for a callback added during the run - Builder: `on=[...]` on `@app.task` and `add_signal` - Low-level: `event.callbacks.append(fn)`, `ev.trigger(other)`, `ev.defused = True` Checked by 32 tests in [`c1_events`](https://github.com/jaehyeon-kim/desflow/blob/v1.3.0/tests/conformance/test_c1_events.py) (26), [`yaml_only`](https://github.com/jaehyeon-kim/desflow/blob/v1.3.0/tests/conformance/test_yaml_only.py) (4) and [`c3_interrupts`](https://github.com/jaehyeon-kim/desflow/blob/v1.3.0/tests/conformance/test_c3_interrupts.py) (2). **Holds the functions that run when an event is processed.** Explained in [Actions when an event happens](https://jaehyeon.me/desflow/latest/user-guide/tasks-and-processes/signals-and-waiting/#actions-when-an-event-happens). Gap M2: see [Where desflow Differs](#where-desflow-differs). - SimPy: `Event.callbacks` - YAML: `on: [{fire: {signal, from}}, {spawn: {...}}]` on a task or a signal, `fire` with `fail`, `defused` and `priority`, `when` on an entry, and `listen` on a task for a callback added during the run - Builder: `on=[...]` on `@app.task` and `add_signal` - Low-level: `event.callbacks.append(fn)`, `ev.trigger(other)`, `ev.defused = True` Checked by 32 tests in [`c1_events`](https://github.com/jaehyeon-kim/desflow/blob/v1.3.0/tests/conformance/test_c1_events.py) (26), [`yaml_only`](https://github.com/jaehyeon-kim/desflow/blob/v1.3.0/tests/conformance/test_yaml_only.py) (4) and [`c3_interrupts`](https://github.com/jaehyeon-kim/desflow/blob/v1.3.0/tests/conformance/test_c3_interrupts.py) (2). **Marks a failed event as handled, so its exception does not stop the run.** Explained in [Actions when an event happens](https://jaehyeon.me/desflow/latest/user-guide/tasks-and-processes/signals-and-waiting/#actions-when-an-event-happens). - SimPy: `Event.defused` - YAML: `on: [{fire: {signal, from}}, {spawn: {...}}]` on a task or a signal, `fire` with `fail`, `defused` and `priority`, `when` on an entry, and `listen` on a task for a callback added during the run - Builder: `on=[...]` on `@app.task` and `add_signal` - Low-level: `event.callbacks.append(fn)`, `ev.trigger(other)`, `ev.defused = True` Checked by 32 tests in [`c1_events`](https://github.com/jaehyeon-kim/desflow/blob/v1.3.0/tests/conformance/test_c1_events.py) (26), [`yaml_only`](https://github.com/jaehyeon-kim/desflow/blob/v1.3.0/tests/conformance/test_yaml_only.py) (4) and [`c3_interrupts`](https://github.com/jaehyeon-kim/desflow/blob/v1.3.0/tests/conformance/test_c3_interrupts.py) (2). **Stops the run with the exception of a failed event that no process or callback handles.** Explained in [Failure nobody handles](https://jaehyeon.me/desflow/latest/user-guide/tasks-and-processes/failures/#failures). - SimPy: A failed event nobody handles stops the run - YAML: `run: {on_unhandled_failure: continue}` to go on, `stop` is the default - Builder: `run(on_unhandled_failure=...)` or `start(on_unhandled_failure=...)` - Low-level: `DynamicRealtimeEnvironment(on_unhandled_failure=...)` Checked by 3 tests in [`c1_events`](https://github.com/jaehyeon-kim/desflow/blob/v1.3.0/tests/conformance/test_c1_events.py). **Tell whether an event has been triggered, has been processed and succeeded, and give its value.** Explained in [Event inspection](https://jaehyeon.me/desflow/latest/user-guide/tasks-and-processes/signals-and-waiting/#wait-signals-and-child-flows). - SimPy: `Event.triggered`, `processed`, `ok` and `value` - YAML: `signal..count`, `.ok` and `.value` in a condition - Builder: `context.signal(name).wait()` and its SimPy attributes, or the signal's `count`, `ok` and `value` - Low-level: the same attributes of SimPy events and `Signal` Checked by 1 test in [`c1_process_interaction`](https://github.com/jaehyeon-kim/desflow/blob/v1.3.0/tests/conformance/test_c1_process_interaction.py). **Combine events into one that waits for all of them (`&`) or for the first of them (`|`).** Explained in [Wait for one event](https://jaehyeon.me/desflow/latest/how-to/modelling/wait-for-one-or-all/#wait-for-the-first). - SimPy: `a & b` and `a | b` - YAML: `wait: {any: {stock: {signal: restocked}, limit: {timeout: 3}}}` - Builder: `wait={"any": {...}}` - Low-level: `yield a | b` - Where desflow differs: Losing signal, timeout and condition branches are dropped when the wait ends; losing child flows keep running, as SimPy leaves processes running. A request branch not yet granted when the wait ends is cancelled; a SimPy `with` block held over the rest of the task leaves it queued. Checked by 8 tests in [`c2_wait_for_one_or_all`](https://github.com/jaehyeon-kim/desflow/blob/v1.3.0/tests/conformance/test_c2_wait_for_one_or_all.py) (2) and [`yaml_only`](https://github.com/jaehyeon-kim/desflow/blob/v1.3.0/tests/conformance/test_yaml_only.py) (6). **An event that happens after a delay.** Explained in [Timed wait](https://jaehyeon.me/desflow/latest/user-guide/tasks-and-processes/tasks/#a-timed-step). - SimPy: `Timeout(delay)` - YAML: a task with `service` or `service_time` and no `resource` - Builder: `@app.task(service_id=...)` with no resource - Low-level: `yield env.timeout(delay)` Checked by 12 tests in [`c1_timed_wait`](https://github.com/jaehyeon-kim/desflow/blob/v1.3.0/tests/conformance/test_c1_timed_wait.py) (5), [`builder_additions`](https://github.com/jaehyeon-kim/desflow/blob/v1.3.0/tests/conformance/test_builder_additions.py) (2), [`yaml_only`](https://github.com/jaehyeon-kim/desflow/blob/v1.3.0/tests/conformance/test_yaml_only.py) (4) and [`c2_wait_for_one_or_all`](https://github.com/jaehyeon-kim/desflow/blob/v1.3.0/tests/conformance/test_c2_wait_for_one_or_all.py) (1). **An event that happens after a delay and carries a value.** Explained in [Timeout value](https://jaehyeon.me/desflow/latest/user-guide/tasks-and-processes/signals-and-waiting/#wait-signals-and-child-flows). - SimPy: `Timeout(delay, value)` - YAML: `wait: {timeout: {after: 40 s, value: ...}}` - Builder: the same mapping in `wait=` - Low-level: `env.timeout(delay, value)` Checked by 2 tests in [`c1_events`](https://github.com/jaehyeon-kim/desflow/blob/v1.3.0/tests/conformance/test_c1_events.py) (1) and [`yaml_only`](https://github.com/jaehyeon-kim/desflow/blob/v1.3.0/tests/conformance/test_yaml_only.py) (1). ## Processes **Starts a process and suspends the one that started it until the new process ends.** Explained in [Start and wait for a process](https://jaehyeon.me/desflow/latest/user-guide/tasks-and-processes/signals-and-waiting/#wait-signals-and-child-flows). - SimPy: Start a process and wait for it - YAML: `wait: {task: inspect}` - Builder: `wait={"task": "inspect"}`, or `yield context.call("inspect")` - Low-level: `yield env.process(child())` Checked by 13 tests in [`c1_process_interaction`](https://github.com/jaehyeon-kim/desflow/blob/v1.3.0/tests/conformance/test_c1_process_interaction.py) (5), [`yaml_only`](https://github.com/jaehyeon-kim/desflow/blob/v1.3.0/tests/conformance/test_yaml_only.py) (7) and [`generator_streams`](https://github.com/jaehyeon-kim/desflow/blob/v1.3.0/tests/conformance/test_generator_streams.py) (1). **Gives the waiting process the value a process returns when it ends.** Explained in [Process return value](https://jaehyeon.me/desflow/latest/user-guide/tasks-and-processes/signals-and-waiting/#wait-signals-and-child-flows). - SimPy: A process's return value - YAML: `wait.inspect.value.`, the last payload of the child flow - Builder: the same, or the value of `context.call(...)` - Low-level: `value = yield env.process(child())` Checked by 1 test in [`c1_process_interaction`](https://github.com/jaehyeon-kim/desflow/blob/v1.3.0/tests/conformance/test_c1_process_interaction.py). **Raises an exception from a process in the process that waits for it.** Explained in [Process failure](https://jaehyeon.me/desflow/latest/user-guide/tasks-and-processes/signals-and-waiting/#wait-signals-and-child-flows). - SimPy: An exception in a process reaches the process that waits for it - YAML: `fail`, `fail_reason` and `on_fail` on a task, and `on_fail` alone for a failed wait or step; a failure no `on_fail` handles fails the waiting task - Builder: the same, and a function that raises fails its task - Low-level: `try: yield env.process(child())` and `except` - Where desflow differs: By default (`on_unhandled_failure` is `stop`) a failure no task waits for stops the run, matching SimPy and the low-level API, where an exception nobody handles stops the run; under `on_unhandled_failure` of `continue` it ends the entity's flow in YAML and the builder, publishes `failed` and is counted, and the run goes on. Checked by 4 tests in [`c1_process_interaction`](https://github.com/jaehyeon-kim/desflow/blob/v1.3.0/tests/conformance/test_c1_process_interaction.py) (2), [`builder_additions`](https://github.com/jaehyeon-kim/desflow/blob/v1.3.0/tests/conformance/test_builder_additions.py) (1) and [`yaml_only`](https://github.com/jaehyeon-kim/desflow/blob/v1.3.0/tests/conformance/test_yaml_only.py) (1). **Tells whether a process is still running.** Explained in [Process inspection](https://jaehyeon.me/desflow/latest/user-guide/tasks-and-processes/signals-and-waiting/#wait-signals-and-child-flows). - SimPy: `Process.is_alive` - YAML: `wait..done`, `.ok` and `.value` after the wait - Builder: the process `context.spawn` and `context.call` return - Low-level: the process `env.process` returns Checked by 2 tests in [`c1_process_interaction`](https://github.com/jaehyeon-kim/desflow/blob/v1.3.0/tests/conformance/test_c1_process_interaction.py). **Gives the event a process waits for at this moment.** Explained in [The running process](https://jaehyeon.me/desflow/latest/user-guide/tasks-and-processes/processes/#how-it-works). - SimPy: `Process.target` - YAML: `process.name`, `process.instance`, `process.target` in a condition - Builder: `context.env.active_process`; `.name` and `.target` on a process - Low-level: `env.active_process.name`, `.target` Checked by 7 tests in [`c1_process_interaction`](https://github.com/jaehyeon-kim/desflow/blob/v1.3.0/tests/conformance/test_c1_process_interaction.py) (5), [`c2_wait_for_one_or_all`](https://github.com/jaehyeon-kim/desflow/blob/v1.3.0/tests/conformance/test_c2_wait_for_one_or_all.py) (1) and [`yaml_only`](https://github.com/jaehyeon-kim/desflow/blob/v1.3.0/tests/conformance/test_yaml_only.py) (1). **Gives the name of the function that started a process.** Explained in [The running process](https://jaehyeon.me/desflow/latest/user-guide/tasks-and-processes/processes/#how-it-works). - SimPy: `Process.name` - YAML: `process.name`, `process.instance`, `process.target` in a condition - Builder: `context.env.active_process`; `.name` and `.target` on a process - Low-level: `env.active_process.name`, `.target` Checked by 7 tests in [`c1_process_interaction`](https://github.com/jaehyeon-kim/desflow/blob/v1.3.0/tests/conformance/test_c1_process_interaction.py) (5), [`c2_wait_for_one_or_all`](https://github.com/jaehyeon-kim/desflow/blob/v1.3.0/tests/conformance/test_c2_wait_for_one_or_all.py) (1) and [`yaml_only`](https://github.com/jaehyeon-kim/desflow/blob/v1.3.0/tests/conformance/test_yaml_only.py) (1). **Suspends a process until another process, started earlier, ends.** Explained in [Wait for a process already running](https://jaehyeon.me/desflow/latest/user-guide/tasks-and-processes/signals-and-waiting/#wait-signals-and-child-flows). - SimPy: Wait for a process that is already running - YAML: `wait: {running: {task: charge, where: ...}}` - Builder: the same in `wait=`, or `yield` a process from `context.spawn` or `call` - Low-level: `yield process` Checked by 8 tests in [`c1_processes`](https://github.com/jaehyeon-kim/desflow/blob/v1.3.0/tests/conformance/test_c1_processes.py) (7) and [`yaml_only`](https://github.com/jaehyeon-kim/desflow/blob/v1.3.0/tests/conformance/test_yaml_only.py) (1). **Starts a process after a delay instead of now.** Explained in [Start a process after a delay](https://jaehyeon.me/desflow/latest/user-guide/tasks-and-processes/signals-and-waiting/#start-a-flow-without-waiting). - SimPy: `start_delayed(env, generator, delay)` - YAML: `spawn: {task: courier, after: 3 s}` - Builder: `spawn={"task", "after"}`, or `context.spawn(generator, delay=3)` - Low-level: `simpy.util.start_delayed(env, generator, 3)` Checked by 3 tests in [`c1_processes`](https://github.com/jaehyeon-kim/desflow/blob/v1.3.0/tests/conformance/test_c1_processes.py). ## Conditions **An event that happens when the first of several events happens.** Explained in [Wait for one event](https://jaehyeon.me/desflow/latest/how-to/modelling/wait-for-one-or-all/#wait-for-the-first). - SimPy: `AnyOf` and `env.any_of` - YAML: `wait: {any: {stock: {signal: restocked}, limit: {timeout: 3}}}` - Builder: `wait={"any": {...}}` - Low-level: `yield a | b` - Where desflow differs: Losing signal, timeout and condition branches are dropped when the wait ends; losing child flows keep running, as SimPy leaves processes running. A request branch not yet granted when the wait ends is cancelled; a SimPy `with` block held over the rest of the task leaves it queued. Checked by 8 tests in [`c2_wait_for_one_or_all`](https://github.com/jaehyeon-kim/desflow/blob/v1.3.0/tests/conformance/test_c2_wait_for_one_or_all.py) (2) and [`yaml_only`](https://github.com/jaehyeon-kim/desflow/blob/v1.3.0/tests/conformance/test_yaml_only.py) (6). **An event that happens when all of several events have happened.** Explained in [Wait for all events](https://jaehyeon.me/desflow/latest/how-to/modelling/wait-for-one-or-all/#wait-for-all). - SimPy: `AllOf` and `env.all_of` - YAML: `wait: {all: {...}}` - Builder: `wait={"all": {...}}` - Low-level: `yield a & b` Checked by 9 tests in [`c2_wait_for_one_or_all`](https://github.com/jaehyeon-kim/desflow/blob/v1.3.0/tests/conformance/test_c2_wait_for_one_or_all.py) (2) and [`yaml_only`](https://github.com/jaehyeon-kim/desflow/blob/v1.3.0/tests/conformance/test_yaml_only.py) (7). **Gives the events of a condition that have happened, with their values, in the order of the condition.** Explained in [Wait for one event](https://jaehyeon.me/desflow/latest/how-to/modelling/wait-for-one-or-all/#wait-for-the-first). - SimPy: `ConditionValue` - YAML: `wait: {any: {stock: {signal: restocked}, limit: {timeout: 3}}}` - Builder: `wait={"any": {...}}` - Low-level: `yield a | b` - Where desflow differs: Losing signal, timeout and condition branches are dropped when the wait ends; losing child flows keep running, as SimPy leaves processes running. A request branch not yet granted when the wait ends is cancelled; a SimPy `with` block held over the rest of the task leaves it queued. Checked by 8 tests in [`c2_wait_for_one_or_all`](https://github.com/jaehyeon-kim/desflow/blob/v1.3.0/tests/conformance/test_c2_wait_for_one_or_all.py) (2) and [`yaml_only`](https://github.com/jaehyeon-kim/desflow/blob/v1.3.0/tests/conformance/test_yaml_only.py) (6). **Fails a condition at once when one of its events fails.** Explained in [Wait for all events](https://jaehyeon.me/desflow/latest/how-to/modelling/wait-for-one-or-all/#wait-for-all). - SimPy: A member that fails fails the condition - YAML: `wait: {all: {...}}` - Builder: `wait={"all": {...}}` - Low-level: `yield a & b` Checked by 9 tests in [`c2_wait_for_one_or_all`](https://github.com/jaehyeon-kim/desflow/blob/v1.3.0/tests/conformance/test_c2_wait_for_one_or_all.py) (2) and [`yaml_only`](https://github.com/jaehyeon-kim/desflow/blob/v1.3.0/tests/conformance/test_yaml_only.py) (7). **Builds a condition from other conditions, such as `(a & b) | c`.** Explained in [Nested and mixed conditions](https://jaehyeon.me/desflow/latest/how-to/modelling/wait-for-one-or-all/#nest-any-and-all). - SimPy: Nested and mixed conditions - YAML: `wait: {all: {look: {task: inspect}, either: {any: {...}}}}` - Builder: `wait={"all": {...}}` with nested groups - Low-level: `yield (a | b) & c` Checked by 3 tests in [`c2_conditions`](https://github.com/jaehyeon-kim/desflow/blob/v1.3.0/tests/conformance/test_c2_conditions.py). **Builds a condition with a rule of your own that decides when it happens.** Explained in [A condition with a custom rule](https://jaehyeon.me/desflow/latest/how-to/modelling/wait-for-one-or-all/#wait-for-some-of-them). - SimPy: `Condition(env, evaluate, events)` with a rule of your own - YAML: `wait: {at_least: 2, of: {...}}` - Builder: `wait={"at_least": 2, "of": {...}}` - Low-level: `Condition(env, lambda evs, c: c >= 2, [...])` Checked by 6 tests in [`c2_conditions`](https://github.com/jaehyeon-kim/desflow/blob/v1.3.0/tests/conformance/test_c2_conditions.py) (4) and [`yaml_only`](https://github.com/jaehyeon-kim/desflow/blob/v1.3.0/tests/conformance/test_yaml_only.py) (2). **Builds a condition from an empty list of events, which happens at once.** Explained in [A condition over no events](https://jaehyeon.me/desflow/latest/how-to/modelling/wait-for-one-or-all/#wait-for-nothing). - SimPy: A condition over no events - YAML: `wait: {any: {}}` or `wait: {all: {}}` - Builder: `wait={"any": {}}` - Low-level: `env.any_of([])` Checked by 1 test in [`c2_wait_for_one_or_all`](https://github.com/jaehyeon-kim/desflow/blob/v1.3.0/tests/conformance/test_c2_wait_for_one_or_all.py). **Uses a request, get or put as one of the events of a condition.** Explained in [Request, put or get as a wait branch](https://jaehyeon.me/desflow/latest/how-to/modelling/wait-for-one-or-all/#wait-for-a-unit-an-item-or-room). - SimPy: A request, get or put as a member of a condition - YAML: `wait: {request: packers}`, `wait: {get: {store: parcels}}`, `wait: {put: {store: ...}}` - Builder: `wait={"request": "packers"}` or `wait={"get": {...}}` - Low-level: `yield req | env.timeout(3)` Checked by 11 tests in [`c2_conditions`](https://github.com/jaehyeon-kim/desflow/blob/v1.3.0/tests/conformance/test_c2_conditions.py) (10) and [`c2_wait_for_one_or_all`](https://github.com/jaehyeon-kim/desflow/blob/v1.3.0/tests/conformance/test_c2_wait_for_one_or_all.py) (1). ## Interrupts **Raises an `Interrupt` in a process that is waiting, with a cause.** Explained in [Interrupt while waiting](https://jaehyeon.me/desflow/latest/learn/shop-logic/interruptions/#interrupt-a-task). - SimPy: `Process.interrupt(cause)` while the process waits - YAML: `interrupt: {task: waiter}` on a scenario step or a task; `on_interrupt` on the task - Builder: `context.interrupt("waiter")`; `@app.task(on_interrupt=...)` - Low-level: `process.interrupt(cause)`, caught as `simpy.Interrupt` - Where desflow differs: A task's own `spawn:` and `interrupt:` keys run in a fixed order, interrupt first, so one task cannot interrupt the instance it spawns with them. List a `spawn` and then an `interrupt` in `on:`, which run in the order written, or use `context.spawn` and `context.interrupt`. Checked by 5 tests in [`c3_interrupts`](https://github.com/jaehyeon-kim/desflow/blob/v1.3.0/tests/conformance/test_c3_interrupts.py) (3) and [`yaml_only`](https://github.com/jaehyeon-kim/desflow/blob/v1.3.0/tests/conformance/test_yaml_only.py) (2). **Interrupts a process during a delay, which ends the delay early.** Explained in [Interrupt during service](https://jaehyeon.me/desflow/latest/learn/shop-logic/interruptions/#resume-restart-or-abandon). - SimPy: An interrupt during a timeout - YAML: `on_interrupt: resume`, `restart` or `abandon`, and `on_interrupt_run` for a task that runs first - Builder: `@app.task(on_interrupt=...)` - Low-level: `except simpy.Interrupt`, then request again Checked by 27 tests in [`c3_interrupts`](https://github.com/jaehyeon-kim/desflow/blob/v1.3.0/tests/conformance/test_c3_interrupts.py) (14), [`c1_process_interaction`](https://github.com/jaehyeon-kim/desflow/blob/v1.3.0/tests/conformance/test_c1_process_interaction.py) (1) and [`yaml_only`](https://github.com/jaehyeon-kim/desflow/blob/v1.3.0/tests/conformance/test_yaml_only.py) (12). **The exception an interrupted process receives, and the cause given with it.** Explained in [Interrupt during service](https://jaehyeon.me/desflow/latest/learn/shop-logic/interruptions/#resume-restart-or-abandon). - SimPy: `Interrupt` and `Interrupt.cause` - YAML: `on_interrupt: resume`, `restart` or `abandon`, and `on_interrupt_run` for a task that runs first - Builder: `@app.task(on_interrupt=...)` - Low-level: `except simpy.Interrupt`, then request again Checked by 27 tests in [`c3_interrupts`](https://github.com/jaehyeon-kim/desflow/blob/v1.3.0/tests/conformance/test_c3_interrupts.py) (14), [`c1_process_interaction`](https://github.com/jaehyeon-kim/desflow/blob/v1.3.0/tests/conformance/test_c1_process_interaction.py) (1) and [`yaml_only`](https://github.com/jaehyeon-kim/desflow/blob/v1.3.0/tests/conformance/test_yaml_only.py) (12). **Delivers several interrupts sent at the same time one after another, in the order they were sent.** Explained in [Interrupt during service](https://jaehyeon.me/desflow/latest/learn/shop-logic/interruptions/#resume-restart-or-abandon). - SimPy: Several interrupts at one time arrive in order - YAML: `on_interrupt: resume`, `restart` or `abandon`, and `on_interrupt_run` for a task that runs first - Builder: `@app.task(on_interrupt=...)` - Low-level: `except simpy.Interrupt`, then request again Checked by 27 tests in [`c3_interrupts`](https://github.com/jaehyeon-kim/desflow/blob/v1.3.0/tests/conformance/test_c3_interrupts.py) (14), [`c1_process_interaction`](https://github.com/jaehyeon-kim/desflow/blob/v1.3.0/tests/conformance/test_c1_process_interaction.py) (1) and [`yaml_only`](https://github.com/jaehyeon-kim/desflow/blob/v1.3.0/tests/conformance/test_yaml_only.py) (12). **Lets an interrupted process wait again for the event it waited for before.** Explained in [Interrupt while waiting](https://jaehyeon.me/desflow/latest/learn/shop-logic/interruptions/#interrupt-a-task). - SimPy: A process waits again for the same event after an interrupt - YAML: `interrupt: {task: waiter}` on a scenario step or a task; `on_interrupt` on the task - Builder: `context.interrupt("waiter")`; `@app.task(on_interrupt=...)` - Low-level: `process.interrupt(cause)`, caught as `simpy.Interrupt` - Where desflow differs: A task's own `spawn:` and `interrupt:` keys run in a fixed order, interrupt first, so one task cannot interrupt the instance it spawns with them. List a `spawn` and then an `interrupt` in `on:`, which run in the order written, or use `context.spawn` and `context.interrupt`. Checked by 5 tests in [`c3_interrupts`](https://github.com/jaehyeon-kim/desflow/blob/v1.3.0/tests/conformance/test_c3_interrupts.py) (3) and [`yaml_only`](https://github.com/jaehyeon-kim/desflow/blob/v1.3.0/tests/conformance/test_yaml_only.py) (2). **Interrupts the calling process when a given event happens, most often the end of another process.** Explained in [Be told when an event happens](https://jaehyeon.me/desflow/latest/user-guide/tasks-and-processes/signals-and-waiting/#be-told-when-a-flow-ends). - SimPy: `subscribe_at(event)` - YAML: `subscribe: {task: charger}` - Builder: `@app.task(subscribe=...)`, or `context.subscribe(event)` - Low-level: `simpy.util.subscribe_at(event)` Checked by 3 tests in [`c1_processes`](https://github.com/jaehyeon-kim/desflow/blob/v1.3.0/tests/conformance/test_c1_processes.py) (2) and [`c1_process_interaction`](https://github.com/jaehyeon-kim/desflow/blob/v1.3.0/tests/conformance/test_c1_process_interaction.py) (1). ## Resources **Gives the maximum capacity of a resource, container or store.** Explained in [Initial resources](https://jaehyeon.me/desflow/latest/user-guide/time-and-pacing/run-length/#initial-time). - SimPy: `capacity` - YAML: `resources..current_cap` - Builder: `add_resource(name, current_cap=2, ...)` - Low-level: `CapacityConfig(current_cap=2, ...)` Checked by 7 tests in [`c6_initial_state`](https://github.com/jaehyeon-kim/desflow/blob/v1.3.0/tests/conformance/test_c6_initial_state.py) (1) and [`yaml_only`](https://github.com/jaehyeon-kim/desflow/blob/v1.3.0/tests/conformance/test_yaml_only.py) (6). **Asks for a unit of a resource and waits for it, then gives it back.** Explained in [Ordinary request and release](https://jaehyeon.me/desflow/latest/user-guide/resources/units-and-queues/#declare-a-resource). - SimPy: `Resource.request()` and `release(request)` - YAML: `resource: packers` on a task - Builder: `@app.task(resource_id="packers")` - Low-level: `with packers.request() as req: yield req` Checked by 10 tests in [`c4_resources`](https://github.com/jaehyeon-kim/desflow/blob/v1.3.0/tests/conformance/test_c4_resources.py) (1), [`low_level_surface`](https://github.com/jaehyeon-kim/desflow/blob/v1.3.0/tests/conformance/test_low_level_surface.py) (1) and [`yaml_only`](https://github.com/jaehyeon-kim/desflow/blob/v1.3.0/tests/conformance/test_yaml_only.py) (8). **Gives a resource one unit when no capacity is set.** Explained in [Resource capacity defaults to 1](https://jaehyeon.me/desflow/latest/user-guide/resources/units-and-queues/#declare-a-resource). - SimPy: Capacity defaults to 1 - YAML: `resources: {packers: {}}`; `current_cap: .inf` for no limit - Builder: `add_resource("packers")`; `current_cap=float("inf")` for no limit - Low-level: `DynamicResource(env, sim_id, name)` with no registry entry; `CapacityConfig(current_cap=float("inf"))` for no limit Checked by 2 tests in [`c4_resources`](https://github.com/jaehyeon-kim/desflow/blob/v1.3.0/tests/conformance/test_c4_resources.py). **Refuses a capacity of 0 or below for a resource, container or store.** Difference kept by design: see [Where desflow Differs](#where-desflow-differs). - SimPy: Capacity must be above 0 - YAML: `current_cap: 0` on a resource - Builder: `add_resource(name, current_cap=0)` - Low-level: `DynamicResource(env, ..., current_cap=0)` **Gives the number of units of a resource in use.** Explained in [Resource count, queue and users](https://jaehyeon.me/desflow/latest/user-guide/resources/units-and-queues/#read-the-queue-and-users). - SimPy: `Resource.count` - YAML: `users.` and `queue.` in a condition, such as `balk: queue.machine >= 2` - Builder: `get_resource(name).count`, `.users` and `.queue` - Low-level: `resource.count`, `.users` and `.queue`, the list of waiting requests in service order - Where desflow differs: A `lifo` queue serves the newest request first, which SimPy has no counterpart of. Checked by 6 tests in [`c4_resources`](https://github.com/jaehyeon-kim/desflow/blob/v1.3.0/tests/conformance/test_c4_resources.py) (3) and [`yaml_only`](https://github.com/jaehyeon-kim/desflow/blob/v1.3.0/tests/conformance/test_yaml_only.py) (3). **Gives the requests that wait for a unit of a resource.** Explained in [Resource count, queue and users](https://jaehyeon.me/desflow/latest/user-guide/resources/units-and-queues/#read-the-queue-and-users). - SimPy: `Resource.queue` - YAML: `users.` and `queue.` in a condition, such as `balk: queue.machine >= 2` - Builder: `get_resource(name).count`, `.users` and `.queue` - Low-level: `resource.count`, `.users` and `.queue`, the list of waiting requests in service order - Where desflow differs: A `lifo` queue serves the newest request first, which SimPy has no counterpart of. Checked by 6 tests in [`c4_resources`](https://github.com/jaehyeon-kim/desflow/blob/v1.3.0/tests/conformance/test_c4_resources.py) (3) and [`yaml_only`](https://github.com/jaehyeon-kim/desflow/blob/v1.3.0/tests/conformance/test_yaml_only.py) (3). **Gives the requests that hold a unit of a resource.** Explained in [Resource count, queue and users](https://jaehyeon.me/desflow/latest/user-guide/resources/units-and-queues/#read-the-queue-and-users). - SimPy: `Resource.users` - YAML: `users.` and `queue.` in a condition, such as `balk: queue.machine >= 2` - Builder: `get_resource(name).count`, `.users` and `.queue` - Low-level: `resource.count`, `.users` and `.queue`, the list of waiting requests in service order - Where desflow differs: A `lifo` queue serves the newest request first, which SimPy has no counterpart of. Checked by 6 tests in [`c4_resources`](https://github.com/jaehyeon-kim/desflow/blob/v1.3.0/tests/conformance/test_c4_resources.py) (3) and [`yaml_only`](https://github.com/jaehyeon-kim/desflow/blob/v1.3.0/tests/conformance/test_yaml_only.py) (3). **Gives back a unit of a resource when a `with` block ends, or cancels the request if the block ends before the grant.** Explained in [Cancel before a grant](https://jaehyeon.me/desflow/latest/user-guide/resources/units-and-queues/#cancel-and-release). - SimPy: `Request` as a context manager - YAML: `patience`, or an interrupt with `on_interrupt: abandon` - Builder: the same - Low-level: `request.cancel()`, or leaving the `with` block Checked by 6 tests in [`c4_resources`](https://github.com/jaehyeon-kim/desflow/blob/v1.3.0/tests/conformance/test_c4_resources.py) (2) and [`yaml_only`](https://github.com/jaehyeon-kim/desflow/blob/v1.3.0/tests/conformance/test_yaml_only.py) (4). **Withdraws a request that still waits for a unit.** Explained in [Cancel before a grant](https://jaehyeon.me/desflow/latest/user-guide/resources/units-and-queues/#cancel-and-release). - SimPy: `Request.cancel()` before the grant - YAML: `patience`, or an interrupt with `on_interrupt: abandon` - Builder: the same - Low-level: `request.cancel()`, or leaving the `with` block Checked by 6 tests in [`c4_resources`](https://github.com/jaehyeon-kim/desflow/blob/v1.3.0/tests/conformance/test_c4_resources.py) (2) and [`yaml_only`](https://github.com/jaehyeon-kim/desflow/blob/v1.3.0/tests/conformance/test_yaml_only.py) (4). **Gives back a unit that a request already holds.** Explained in [Cancel after a grant](https://jaehyeon.me/desflow/latest/user-guide/resources/units-and-queues/#cancel-and-release). - SimPy: `cancel()` after the grant - YAML: an interrupt with `on_interrupt: abandon` gives the unit back, as `release(request)` does; for a request made with `open`, `cancel` after the grant releases nothing, and `release: {handle: }` does - Builder: the same - Low-level: `request.cancel()` releases nothing; `resource.release(request)` Checked by 2 tests in [`c4_resources`](https://github.com/jaehyeon-kim/desflow/blob/v1.3.0/tests/conformance/test_c4_resources.py) (1) and [`yaml_only`](https://github.com/jaehyeon-kim/desflow/blob/v1.3.0/tests/conformance/test_yaml_only.py) (1). **The event that gives back a unit, and the request it gives back.** Explained in [Release event and its request](https://jaehyeon.me/desflow/latest/user-guide/resources/units-and-queues/#cancel-and-release). - SimPy: `Release` and `Release.request` - YAML: implicit: a task releases its units when it ends - Builder: `get_resource(name).release(request)` - Low-level: `resource.release(request)` returns a `DynamicRelease` whose `request` is the request Checked by 1 test in [`c4_resources`](https://github.com/jaehyeon-kim/desflow/blob/v1.3.0/tests/conformance/test_c4_resources.py). **Gives the time a request was granted its unit.** Explained in [Usage since](https://jaehyeon.me/desflow/latest/user-guide/resources/units-and-queues/#read-the-queue-and-users). - SimPy: `Request.usage_since` - YAML: `usage_since` in the `preempted` record - Builder: `get_resource(name).users[i].usage_since`, and the `preempted` record - Low-level: `request.usage_since` Checked by 1 test in [`c4_resources`](https://github.com/jaehyeon-kim/desflow/blob/v1.3.0/tests/conformance/test_c4_resources.py). **Holds units of more than one resource at the same time.** Explained in [Hold several resources](https://jaehyeon.me/desflow/latest/user-guide/resources/several-resources/#several-resources). - SimPy: Hold several resources at once - YAML: `resource: [picker, bench]`, acquired in that order; `keep` hands units to the next task; `seize` keeps a unit across later tasks until `release` - Builder: `@app.task(resource_id=["picker", "bench"], keep=[...])`, or `seize=` and `release=` - Low-level: nested `with` blocks - Where desflow differs: A model whose tasks acquire two resources in opposite orders gets a warning when it is built, because those tasks could each wait for ever; it runs as SimPy runs it. Two requests under one `all` wait are made together, so another task that acquires the two one after the other, in either order, gets the warning too. A task that keeps a unit for a task that requests it in its wait is refused, because the wait would queue behind the unit it keeps. Checked by 9 tests in [`c4_resources`](https://github.com/jaehyeon-kim/desflow/blob/v1.3.0/tests/conformance/test_c4_resources.py) (4), [`c1_process_interaction`](https://github.com/jaehyeon-kim/desflow/blob/v1.3.0/tests/conformance/test_c1_process_interaction.py) (1) and [`yaml_only`](https://github.com/jaehyeon-kim/desflow/blob/v1.3.0/tests/conformance/test_yaml_only.py) (4). **Leaves the queue when a unit is not granted within a time limit.** Explained in [Reneging](https://jaehyeon.me/desflow/latest/learn/shop-logic/patience/#leave-after-a-wait). - SimPy: Reneging: `req | env.timeout(patience)` - YAML: `patience: 3 min` on a task, and `on_renege` for the task that follows - Builder: `@app.task(..., patience=180)` - Low-level: `yield req | env.timeout(patience)`, then `req not in result` Checked by 15 tests in [`c7_patience`](https://github.com/jaehyeon-kim/desflow/blob/v1.3.0/tests/conformance/test_c7_patience.py) (10), [`yaml_only`](https://github.com/jaehyeon-kim/desflow/blob/v1.3.0/tests/conformance/test_yaml_only.py) (3) and [`builder_additions`](https://github.com/jaehyeon-kim/desflow/blob/v1.3.0/tests/conformance/test_builder_additions.py) (2). **Does not join the queue when a condition holds, such as the queue being too long.** Explained in [Balking](https://jaehyeon.me/desflow/latest/learn/shop-logic/patience/#refuse-to-join). - SimPy: Balking: a check before `request()` - YAML: `balk: ` on a task - Builder: `@app.task(..., balk="...")` - Low-level: an `if` before the request Checked by 2 tests in [`c7_patience`](https://github.com/jaehyeon-kim/desflow/blob/v1.3.0/tests/conformance/test_c7_patience.py). **Asks for a unit with a priority, and a lower number is served first.** Explained in [Priority request](https://jaehyeon.me/desflow/latest/user-guide/resources/priority-and-preemption/#task-priority). - SimPy: `PriorityResource.request(priority)` - YAML: `queue: priority` on the resource and `priority` on a task - Builder: `add_resource(..., queue="priority")` and `@app.task(priority=...)` - Low-level: `DynamicResource(..., queue="priority")` and `request(priority=...)` - Where desflow differs: Equal priorities are served first in, first out, as in SimPy; desflow also offers `fifo` and `lifo` queues, under which a request's priority is ignored. Checked by 7 tests in [`c4_resources`](https://github.com/jaehyeon-kim/desflow/blob/v1.3.0/tests/conformance/test_c4_resources.py) (2) and [`yaml_only`](https://github.com/jaehyeon-kim/desflow/blob/v1.3.0/tests/conformance/test_yaml_only.py) (5). **Gives a request priority 0 when none is set.** Explained in [Default request priority 0](https://jaehyeon.me/desflow/latest/user-guide/resources/priority-and-preemption/#task-priority). - SimPy: Default request priority 0 - YAML: a task with no `priority` on a `queue: priority` resource - Builder: `@app.task(resource_id=...)` with no `priority` - Low-level: `request()` with no priority Checked by 1 test in [`c4_resources`](https://github.com/jaehyeon-kim/desflow/blob/v1.3.0/tests/conformance/test_c4_resources.py). **Orders waiting requests by priority, then by the time they were made, then preempting before not preempting.** Explained in [Priority request](https://jaehyeon.me/desflow/latest/user-guide/resources/priority-and-preemption/#task-priority). - SimPy: Queue key `(priority, time, not preempt)` - YAML: `queue: priority` on the resource and `priority` on a task - Builder: `add_resource(..., queue="priority")` and `@app.task(priority=...)` - Low-level: `DynamicResource(..., queue="priority")` and `request(priority=...)` - Where desflow differs: Equal priorities are served first in, first out, as in SimPy; desflow also offers `fifo` and `lifo` queues, under which a request's priority is ignored. Checked by 7 tests in [`c4_resources`](https://github.com/jaehyeon-kim/desflow/blob/v1.3.0/tests/conformance/test_c4_resources.py) (2) and [`yaml_only`](https://github.com/jaehyeon-kim/desflow/blob/v1.3.0/tests/conformance/test_yaml_only.py) (5). **Lets a request with a higher priority take a unit from its user, unless it asks not to preempt.** Explained in [Priority preemption](https://jaehyeon.me/desflow/latest/user-guide/resources/priority-and-preemption/#preemption). - SimPy: `PreemptiveResource` and `request(preempt=False)` - YAML: `resources..preempt: true` with `queue: priority`; `preempt: false` on a task opts out, and `preempt` on a task, a `seize` or a `request` mapping can be an expression read for each request - Builder: `add_resource(..., queue="priority", preempt=True)` - Low-level: `DynamicResource(..., queue="priority", preempt=True)` and `request(priority, preempt=True)` Checked by 9 tests in [`c3_interrupts`](https://github.com/jaehyeon-kim/desflow/blob/v1.3.0/tests/conformance/test_c3_interrupts.py) (5) and [`yaml_only`](https://github.com/jaehyeon-kim/desflow/blob/v1.3.0/tests/conformance/test_yaml_only.py) (4). **Picks as the user to preempt the one whose request has the largest key: the lowest priority, then the latest.** Explained in [Priority preemption](https://jaehyeon.me/desflow/latest/user-guide/resources/priority-and-preemption/#preemption). - SimPy: The user to preempt is picked with `max` - YAML: `resources..preempt: true` with `queue: priority`; `preempt: false` on a task opts out, and `preempt` on a task, a `seize` or a `request` mapping can be an expression read for each request - Builder: `add_resource(..., queue="priority", preempt=True)` - Low-level: `DynamicResource(..., queue="priority", preempt=True)` and `request(priority, preempt=True)` Checked by 9 tests in [`c3_interrupts`](https://github.com/jaehyeon-kim/desflow/blob/v1.3.0/tests/conformance/test_c3_interrupts.py) (5) and [`yaml_only`](https://github.com/jaehyeon-kim/desflow/blob/v1.3.0/tests/conformance/test_yaml_only.py) (4). **The cause a preempted process receives: the process that took the unit, when the unit was granted, and the resource.** Explained in [Preemption cause](https://jaehyeon.me/desflow/latest/user-guide/resources/priority-and-preemption/#preemption). - SimPy: `Preempted` cause: `by`, `usage_since`, `resource` - YAML: `preempted_by` and `usage_since` in the `preempted` record - Builder: the same record - Low-level: `simpy.Interrupt.cause` is a `Preempted` with `by`, `usage_since` and `resource` Checked by 3 tests in [`c3_interrupts`](https://github.com/jaehyeon-kim/desflow/blob/v1.3.0/tests/conformance/test_c3_interrupts.py). **A waiting line that refuses a new request when a given number of requests already wait.** Explained in [A waiting line with a limit](https://jaehyeon.me/desflow/latest/learn/shop-logic/patience/#refuse-to-join). - SimPy: `SortedQueue(maxlen)`, a waiting line with a limit - YAML: `queue_limit: 5` on the resource; a scenario step, an `on:` entry or an ingress message can write the registry path `.resources..queue_limit` during the run, with a whole number or `null` for no limit - Builder: `add_resource(..., queue_limit=5)` - Low-level: `DynamicResource(..., queue_limit=5)`: `request()` raises `RuntimeError` - Where desflow differs: A task whose first resource refuses it publishes `balked` with the resource before it publishes `queued`, which SimPy has no counterpart of. Checked by 10 tests in [`c7_patience`](https://github.com/jaehyeon-kim/desflow/blob/v1.3.0/tests/conformance/test_c7_patience.py) (9) and [`yaml_only`](https://github.com/jaehyeon-kim/desflow/blob/v1.3.0/tests/conformance/test_yaml_only.py) (1). **Changes how a resource grants requests or keeps its waiting line, in a class of your own.** Explained in [Subclass a resource to change its rules](https://jaehyeon.me/desflow/latest/user-guide/resources/custom-resource-types/#custom-resource-types). - SimPy: A subclass of `PreemptiveResource` or `Resource` - YAML: `type: !python module.Class` on the resource; for a queue order and a preemption rule, `queue: {rank, ties}` and `preempt: {when, victim}` - Builder: `add_resource(..., type=Class)`, or `queue={...}` and `preempt={...}` - Low-level: a subclass of `ResourceBase`, built as `Class(env, sim_id, name)` Checked by 7 tests in [`c4_resources`](https://github.com/jaehyeon-kim/desflow/blob/v1.3.0/tests/conformance/test_c4_resources.py) (1) and [`yaml_only`](https://github.com/jaehyeon-kim/desflow/blob/v1.3.0/tests/conformance/test_yaml_only.py) (6). ## Containers **Adds an amount to a container, and waits while there is not enough space.** Explained in [Bounded quantity put](https://jaehyeon.me/desflow/latest/learn/shop-logic/stock/#take-and-restock). - SimPy: `Container.put(amount)` - YAML: `put: {container: stock, amount: 2}` on a task - Builder: `@app.task(put={"container": "stock", "amount": 2})` - Low-level: `yield stock.put(2)` Checked by 1 test in [`c5_bounded`](https://github.com/jaehyeon-kim/desflow/blob/v1.3.0/tests/conformance/test_c5_bounded.py). **Takes an amount from a container, and waits while there is not enough in it.** Explained in [Bounded quantity get](https://jaehyeon.me/desflow/latest/learn/shop-logic/stock/#take-and-restock). - SimPy: `Container.get(amount)` - YAML: `get: {container: stock, amount: 1}` on a task - Builder: `@app.task(get={"container": "stock", "amount": 1})` - Low-level: `yield stock.get(1)` Checked by 1 test in [`c5_bounded`](https://github.com/jaehyeon-kim/desflow/blob/v1.3.0/tests/conformance/test_c5_bounded.py). **Starts a container with an amount already in it.** Explained in [Initial inventory](https://jaehyeon.me/desflow/latest/user-guide/model-parts/stores-and-containers/#start-with-items-and-serve-by-priority). - SimPy: `Container(init=)` - YAML: `containers..level` and `stores..items` - Builder: `add_container(..., level=6)` and `add_store(..., items=[...])` - Low-level: `ContainerConfig(level=6)` and `DynamicStore(..., items=[...])` Checked by 4 tests in [`c6_initial_state`](https://github.com/jaehyeon-kim/desflow/blob/v1.3.0/tests/conformance/test_c6_initial_state.py) (1), [`low_level_surface`](https://github.com/jaehyeon-kim/desflow/blob/v1.3.0/tests/conformance/test_low_level_surface.py) (2) and [`yaml_only`](https://github.com/jaehyeon-kim/desflow/blob/v1.3.0/tests/conformance/test_yaml_only.py) (1). **Gives the amount a container holds.** Explained in [Wait for a shared condition](https://jaehyeon.me/desflow/latest/user-guide/tasks-and-processes/signals-and-waiting/#wait-signals-and-child-flows). - SimPy: `Container.level` - YAML: `wait: {condition: level.stock >= 5}` - Builder: `wait={"condition": "level.stock >= 5"}` - Low-level: `env.watch_changes(check)`, or a SimPy loop Checked by 1 test in [`c1_process_interaction`](https://github.com/jaehyeon-kim/desflow/blob/v1.3.0/tests/conformance/test_c1_process_interaction.py). **Gives a container no upper limit when no capacity is set.** Explained in [Container with no capacity limit](https://jaehyeon.me/desflow/latest/user-guide/model-parts/stores-and-containers/#declare-them). - SimPy: Capacity defaults to infinity - YAML: `containers.` with no `current_cap`, or `current_cap: .inf` - Builder: `add_container("tank")` - Low-level: `DynamicContainer(env, "Dock", "tank")` Checked by 1 test in [`c5_unbounded`](https://github.com/jaehyeon-kim/desflow/blob/v1.3.0/tests/conformance/test_c5_unbounded.py). ## Stores **Adds an item to a store, and waits while the store is full.** Explained in [Bounded store put](https://jaehyeon.me/desflow/latest/user-guide/model-parts/stores-and-containers/#take-and-add). - SimPy: `Store.put(item)` - YAML: `put: {store: parcels}` on a task - Builder: `@app.task(put={"store": "parcels"})` - Low-level: `yield parcels.put(item)` Checked by 3 tests in [`c5_bounded`](https://github.com/jaehyeon-kim/desflow/blob/v1.3.0/tests/conformance/test_c5_bounded.py) (1), [`c5_inventory`](https://github.com/jaehyeon-kim/desflow/blob/v1.3.0/tests/conformance/test_c5_inventory.py) (1) and [`yaml_only`](https://github.com/jaehyeon-kim/desflow/blob/v1.3.0/tests/conformance/test_yaml_only.py) (1). **Takes the first item from a store, and waits while the store is empty.** Explained in [Bounded store get](https://jaehyeon.me/desflow/latest/user-guide/model-parts/stores-and-containers/#take-and-add). - SimPy: `Store.get()` - YAML: `get: {store: parcels}` on a task - Builder: `@app.task(get={"store": "parcels"})` - Low-level: `item = yield parcels.get()` Checked by 1 test in [`c5_bounded`](https://github.com/jaehyeon-kim/desflow/blob/v1.3.0/tests/conformance/test_c5_bounded.py). **Grants one waiting get for each put made at the same time.** Explained in [Equal-time puts and gets](https://jaehyeon.me/desflow/latest/user-guide/model-parts/stores-and-containers/#take-and-add). - SimPy: One waiting get is granted per put at one time - YAML: `get: {store: parcels}` and `put: {store: parcels}` on tasks - Builder: `@app.task(get={"store": "parcels"})` - Low-level: `yield parcels.put(item)`, `item = yield parcels.get()` - Where desflow differs: While a get with a filter waits, the store grants as SimPy's `FilterStore` does, looking at every waiting get each time. Once no filtered get waits, it grants one get per trigger, as `Store` does, where `FilterStore` goes on to the next. With filtered and unfiltered gets in one queue, gets at the same instant can therefore resume in a different order than in `FilterStore`; each get receives the same item. Checked by 2 tests in [`c5_store_order`](https://github.com/jaehyeon-kim/desflow/blob/v1.3.0/tests/conformance/test_c5_store_order.py). **Starts a store with items already in it.** Explained in [Initial inventory](https://jaehyeon.me/desflow/latest/user-guide/model-parts/stores-and-containers/#start-with-items-and-serve-by-priority). - SimPy: A store that starts with items - YAML: `containers..level` and `stores..items` - Builder: `add_container(..., level=6)` and `add_store(..., items=[...])` - Low-level: `ContainerConfig(level=6)` and `DynamicStore(..., items=[...])` Checked by 4 tests in [`c6_initial_state`](https://github.com/jaehyeon-kim/desflow/blob/v1.3.0/tests/conformance/test_c6_initial_state.py) (1), [`low_level_surface`](https://github.com/jaehyeon-kim/desflow/blob/v1.3.0/tests/conformance/test_low_level_surface.py) (2) and [`yaml_only`](https://github.com/jaehyeon-kim/desflow/blob/v1.3.0/tests/conformance/test_yaml_only.py) (1). **Gives the items a store holds.** Explained in [Read a store's items](https://jaehyeon.me/desflow/latest/user-guide/model-parts/stores-and-containers/#registry-paths-readings-and-conditions). - SimPy: `Store.items` - YAML: `count(parcels) > 3`, `payload.sku in items(shelf, item.sku)` - Builder: `wait={"condition": "count(parcels) > 3"}` - Low-level: `len(parcels.items)`, `sku in [i["sku"] for i in shelf.items]` Checked by 4 tests in [`c5_store_items`](https://github.com/jaehyeon-kim/desflow/blob/v1.3.0/tests/conformance/test_c5_store_items.py). **Gives a store no upper limit when no capacity is set.** Explained in [Store with no capacity limit](https://jaehyeon.me/desflow/latest/user-guide/model-parts/stores-and-containers/#declare-them). - SimPy: Capacity defaults to infinity - YAML: `stores.` with no `current_cap`, or `current_cap: .inf` - Builder: `add_store("parcels")` - Low-level: `DynamicStore(env, "Shop", "parcels")` Checked by 1 test in [`c5_unbounded`](https://github.com/jaehyeon-kim/desflow/blob/v1.3.0/tests/conformance/test_c5_unbounded.py). **A store that gives out its items smallest first, and the wrapper that pairs an item with a priority.** Explained in [Priority item storage](https://jaehyeon.me/desflow/latest/user-guide/model-parts/stores-and-containers/#start-with-items-and-serve-by-priority). - SimPy: `PriorityStore` and `PriorityItem` - YAML: `stores..priority: true` and a `put` with `priority`; `get_queue` and `put_queue` of a store or container rank the waiting gets and puts by an expression - Builder: `add_store(..., priority=True)` and `put={"store": ..., "priority": ...}` - Low-level: `DynamicStore(..., priority=True)` with `simpy.PriorityItem` Checked by 5 tests in [`c5_priority_store`](https://github.com/jaehyeon-kim/desflow/blob/v1.3.0/tests/conformance/test_c5_priority_store.py) (2) and [`yaml_only`](https://github.com/jaehyeon-kim/desflow/blob/v1.3.0/tests/conformance/test_yaml_only.py) (3). **Ranks the items of a priority store by any value that can be ordered, such as a number, a string or a tuple.** Explained in [Priorities of any orderable type](https://jaehyeon.me/desflow/latest/user-guide/model-parts/stores-and-containers/#start-with-items-and-serve-by-priority). - SimPy: Priorities of any orderable type - YAML: `put: {store: queue, priority: [1, urgent]}` - Builder: `put={"store": "queue", "priority": (1, "urgent")}` - Low-level: `simpy.PriorityItem((1, "urgent"), item)` Checked by 3 tests in [`c5_priority_store`](https://github.com/jaehyeon-kim/desflow/blob/v1.3.0/tests/conformance/test_c5_priority_store.py). **Takes the first item of a store that a given function accepts.** Explained in [Filtered retrieval](https://jaehyeon.me/desflow/latest/user-guide/model-parts/stores-and-containers/#pick-an-item-or-give-up-waiting). - SimPy: `FilterStore.get(filter)` - YAML: `get: {store: parcels, filter: item.area == attr.area}` - Builder: `get={"store": "parcels", "filter": ...}`, a condition or a function of the item - Low-level: `parcels.get(filter=lambda item: ...)` - Where desflow differs: A priority store takes no filter, because SimPy has no store that both ranks and filters. Checked by 3 tests in [`c5_inventory`](https://github.com/jaehyeon-kim/desflow/blob/v1.3.0/tests/conformance/test_c5_inventory.py) (1) and [`builder_additions`](https://github.com/jaehyeon-kim/desflow/blob/v1.3.0/tests/conformance/test_builder_additions.py) (2). **Give the puts and gets that wait at a store or container.** Explained in [Put and get queues of a store or container](https://jaehyeon.me/desflow/latest/user-guide/model-parts/stores-and-containers/#registry-paths-readings-and-conditions). - SimPy: `put_queue` and `get_queue` - YAML: `wait: {condition: putters.dock > 2}`, `getters.dock == 0` - Builder: `wait={"condition": "putters.dock > 2"}` - Low-level: `dock.put_queue`, `dock.get_queue` Checked by 5 tests in [`c5_queues`](https://github.com/jaehyeon-kim/desflow/blob/v1.3.0/tests/conformance/test_c5_queues.py) (3) and [`low_level_surface`](https://github.com/jaehyeon-kim/desflow/blob/v1.3.0/tests/conformance/test_low_level_surface.py) (2). **Cancel a waiting put or get, by hand or when a `with` block ends before the grant.** Explained in [Cancel store get](https://jaehyeon.me/desflow/latest/user-guide/model-parts/stores-and-containers/#pick-an-item-or-give-up-waiting). - SimPy: `Put` and `Get` as context managers, and `cancel()` - YAML: `patience` on a task with a store `get` - Builder: `@app.task(get={"store": ...}, patience=...)` - Low-level: `get.cancel()` Checked by 1 test in [`c5_inventory`](https://github.com/jaehyeon-kim/desflow/blob/v1.3.0/tests/conformance/test_c5_inventory.py). **Tries waiting gets and puts in the order they joined their queue.** Explained in [Equal-time puts and gets](https://jaehyeon.me/desflow/latest/user-guide/model-parts/stores-and-containers/#take-and-add). - SimPy: Grant rules: waiting gets and puts are tried in queue order - YAML: `get: {store: parcels}` and `put: {store: parcels}` on tasks - Builder: `@app.task(get={"store": "parcels"})` - Low-level: `yield parcels.put(item)`, `item = yield parcels.get()` - Where desflow differs: While a get with a filter waits, the store grants as SimPy's `FilterStore` does, looking at every waiting get each time. Once no filtered get waits, it grants one get per trigger, as `Store` does, where `FilterStore` goes on to the next. With filtered and unfiltered gets in one queue, gets at the same instant can therefore resume in a different order than in `FilterStore`; each get receives the same item. Checked by 2 tests in [`c5_store_order`](https://github.com/jaehyeon-kim/desflow/blob/v1.3.0/tests/conformance/test_c5_store_order.py). **Changes what a put or get does to a store or container, in a class of your own.** Explained in [Custom store and container types](https://jaehyeon.me/desflow/latest/user-guide/model-parts/stores-and-containers/#custom-store-and-container-types). - SimPy: A custom store or container with `_do_put` and `_do_get` - YAML: `stores..type: !python pkg.module.MyStore` - Builder: `add_store(..., type=MyStore)` - Low-level: `class MyStore(StoreBase)` Checked by 3 tests in [`c5_custom_types`](https://github.com/jaehyeon-kim/desflow/blob/v1.3.0/tests/conformance/test_c5_custom_types.py). **Changes how the puts and gets that wait are kept, in a class of your own.** Explained in [Custom put and get queue types](https://jaehyeon.me/desflow/latest/user-guide/model-parts/stores-and-containers/#custom-store-and-container-types). - SimPy: Custom `PutQueue` and `GetQueue` types - YAML: `stores..type: !python pkg.module.MyStore`, with `PutQueue` and `GetQueue` set on the class - Builder: `add_store(..., type=MyStore)` - Low-level: `class MyStore(StoreBase): PutQueue = MyQueue` Checked by 2 tests in [`c5_custom_types`](https://github.com/jaehyeon-kim/desflow/blob/v1.3.0/tests/conformance/test_c5_custom_types.py). **Changes the put and get events of a store or container, in a class of your own.** Explained in [Custom put and get event classes](https://jaehyeon.me/desflow/latest/user-guide/model-parts/stores-and-containers/#custom-store-and-container-types). - SimPy: Custom `Put` and `Get` event classes - YAML: `stores..type: !python pkg.module.MyStore`, with `put` and `get` set on the class - Builder: `add_store(..., type=MyStore)` - Low-level: `class MyStore(StoreBase): put = BoundClass(MyPut)` Checked by 1 test in [`c5_custom_types`](https://github.com/jaehyeon-kim/desflow/blob/v1.3.0/tests/conformance/test_c5_custom_types.py). **Makes a put or get and carries on at once, without waiting for it to be granted.** Explained in [A put or get the process does not wait for](https://jaehyeon.me/desflow/latest/user-guide/model-parts/stores-and-containers/#take-and-add). - SimPy: A put or get the process does not wait for - YAML: `put: {store: dock, wait: false}` on a task - Builder: `put={"store": "dock", "wait": False}` - Low-level: `dock.put(item)` without `yield` Checked by 4 tests in [`c5_no_wait`](https://github.com/jaehyeon-kim/desflow/blob/v1.3.0/tests/conformance/test_c5_no_wait.py). ## Real-Time **Runs the simulation in step with the wall clock, with each time unit taking `factor` seconds.** Explained in [Real-time factor](https://jaehyeon.me/desflow/latest/user-guide/time-and-pacing/clocks-and-pacing/#factor). - SimPy: `RealtimeEnvironment(factor)` - YAML: `simulation.factor` - Builder: `SimulationContext(factor=)` - Low-level: `DynamicRealtimeEnvironment(factor=)` Checked by 1 test in [`c6_pacing`](https://github.com/jaehyeon-kim/desflow/blob/v1.3.0/tests/conformance/test_c6_pacing.py). **Raises `RuntimeError` when processing falls behind the wall clock by more than `factor` seconds.** Explained in [Strict pacing](https://jaehyeon.me/desflow/latest/user-guide/time-and-pacing/clocks-and-pacing/#strict-pacing). - SimPy: `strict`: a step that falls behind raises `RuntimeError` - YAML: `simulation.strict` - Builder: `SimulationContext(strict=True)` - Low-level: `DynamicRealtimeEnvironment(strict=True)` Checked by 1 test in [`c6_pacing`](https://github.com/jaehyeon-kim/desflow/blob/v1.3.0/tests/conformance/test_c6_pacing.py). **Turns strict mode on by default, so falling behind raises `RuntimeError` unless `strict=False` is set.** Explained in [Strict by default](https://jaehyeon.me/desflow/latest/user-guide/time-and-pacing/clocks-and-pacing/#strict-pacing). - SimPy: `strict` defaults to true - YAML: `simulation.strict`, default `true` when `factor` is above 0 or `go_live_at` is set - Builder: `SimulationContext(strict=None)`, the default, resolves the same way - Low-level: `DynamicRealtimeEnvironment(strict=None)`, the default, resolves the same way Checked by 4 tests in [`c6_pacing`](https://github.com/jaehyeon-kim/desflow/blob/v1.3.0/tests/conformance/test_c6_pacing.py). **Sets the real-time clock to the wall clock now, so a delay before the run does not count as falling behind.** Explained in [Sync with the wall clock](https://jaehyeon.me/desflow/latest/user-guide/time-and-pacing/clocks-and-pacing/#strict-pacing). - SimPy: `sync()` - YAML: `run: {sync: true}` syncs as the run starts, and `sync: true` on a segment as that segment starts, or `app.start()`, then `app.env.sync()` - Builder: `app.env.sync()` after `start()`; the builder syncs once when it builds a strict run - Low-level: `env.sync()` Checked by 3 tests in [`c6_pacing`](https://github.com/jaehyeon-kim/desflow/blob/v1.3.0/tests/conformance/test_c6_pacing.py) (1) and [`yaml_only`](https://github.com/jaehyeon-kim/desflow/blob/v1.3.0/tests/conformance/test_yaml_only.py) (2). ## Where desflow Differs **Holds the functions that run when an event is processed.** In [Events and Timeout](#events-and-timeout). - SimPy: `Event.callbacks` - **Gap M2:** A Builder `on=` refuses a callable. A generator started with `add_process` can add a function to an event's callbacks. **Refuses a capacity of 0 or below for a resource, container or store.** In [Resources](#resources). - SimPy: Capacity must be above 0 - **Difference kept by design:** A resource, store or container may have a capacity of 0, at the start or later, because its capacity changes during a run: a shift with no packers, a shelf that is closed. At capacity 0 a resource grants no request, and a store or container accepts no put, until the capacity rises; a get still takes what a store or container holds. # Reference # YAML Keys Every key a blueprint file takes, generated from the JSON Schema that ships with desflow. [YAML Blueprints](https://jaehyeon.me/desflow/latest/user-guide/writing-a-model/blueprints/index.md) explains how a file is read. [Set Up Your Editor](https://jaehyeon.me/desflow/latest/how-to/tools/set-up-your-editor/index.md) shows how to have your editor complete and check these keys as you type. Each section below is a top-level key. A table lists the keys that an entry of it takes, and a section follows for each entry nested in it. Where a value is a number, a whole number, `true` or `false`, or one of a fixed set of names, a `${VAR}` or `${VAR:-default}` reference is also accepted, and a number can also be written in quotes, such as `'1000'`. A duration such as `5 min` is accepted where the type says Duration. A key typed `Value` takes a constant or a generator, and `Generator` is the generator part of a type: a mapping with a `gen` key that names its kind, such as `{gen: integer, bounds: [1, 6]}`. [What a Generator Is](https://jaehyeon.me/desflow/latest/generators/#what-a-generator-is) explains both. ## simulation Type: mapping. Required. The `simulation` section: the arguments of `SimulationContext`. `logical_start_time` and `go_live_at` take `now`, a signed duration from now such as `-1d` or `-10m`, an ISO datetime, or a `!python` datetime. Both read the same `now`, the moment the file is validated, so `-10m` and `now` are exactly ten minutes apart. `now` and a time without an offset are read in `timezone`, an IANA name, UTC by default. `strict` makes a step raise `RuntimeError` when the run is more than `factor` seconds behind the wall clock, as SimPy's real-time environment does. Left unset it is true for a paced run or one with `go_live_at`, and false at `factor: 0` with no `go_live_at`. At `factor: 0`, `strict: true` raises once the wall clock has moved, as SimPy's does. `environment` is a subclass of `DynamicRealtimeEnvironment` the run is built on. `log_level` sets how much desflow logs: the level of the `desflow` logger, set when the context is built. `desflow run --log-level` overrides it, and the other commands log at WARNING whatever it says. | Key | Type | Default | | -------------------- | ----------------------------------------- | -------- | | `sim_id` | text | required | | `factor` | number | `1.0` | | `random_seed` | integer | none | | `timezone` | text | none | | `logical_start_time` | Time | none | | `go_live_at` | Time | none | | `warmup` | integer or number or Duration | none | | `initial_time` | integer or number or Duration | `0.0` | | `lag_interval` | number or Duration | none | | `strict` | boolean | none | | `environment` | !python reference | none | | `log_level` | `debug` or `info` or `warning` or `error` | none | ## resources Type: mapping of names to [Resource](#resources). Optional. A `resources` entry: its capacity, the order its queue is served in, whether a request of a lower priority value preempts a user, how many requests may wait, the class it is built from, and how it breaks down. `current_cap` defaults to 1 and `max_cap` to `current_cap`, so `{}` is a resource of one unit. `.inf` makes a resource with no limit. `type` is a `!python` subclass of `ResourceBase`. `queue` is `fifo`, `lifo`, `priority`, or a `{rank, ties}` rule that ranks each request by an expression; `preempt` is true or false, or a `{when, victim}` rule, and needs `queue: priority` or a rank. `queue_limit` is also the registry path `.resources..queue_limit`, so a scenario, an `on:` entry or an ingress message can change it: the new limit applies from the next request and removes nobody who waits, and `null` is no limit. `family: true` makes the entry a family: one resource for each key, made from this entry. `members` is a count place read once when the run is built, for the keys 0 to n - 1; without it the family starts empty. A task names a member with `{of: , key: }`, and a member is made at its first use. In a family, `current_cap` and `max_cap` may be expression text, read once when a member is made. | Key | Type | Default | | ------------- | -------------------------------------- | -------- | | `current_cap` | integer or number or text | none | | `max_cap` | integer or number or text | none | | `queue` | text or [QueueRule](#queuerule) | `"fifo"` | | `preempt` | boolean or [PreemptRule](#preemptrule) | `false` | | `queue_limit` | integer | none | | `type` | !python reference | none | | `breakdown` | [Breakdown](#breakdown) | none | | `family` | boolean | `false` | | `members` | Generator or integer or text | none | ### QueueRule A `queue` of a resource, or a `get_queue` or `put_queue` of a store or container, written as a rank: `rank` is an expression read once as each request, get or put is made, in the scope of the task that makes it, and the lowest rank is served first. `ties` orders equal ranks: `fifo` (the default) serves the oldest first and `lifo` the latest first. On a resource, `ties` orders the queue only: it changes neither a request's key nor who preempts. | Key | Type | Default | | ------ | ---------------- | -------- | | `rank` | text | required | | `ties` | `fifo` or `lifo` | `"fifo"` | ### PreemptRule A `preempt` of a resource written as a rule. `when` is tested when a request finds no free unit, and the request takes the unit if it holds. `victim` gives each holder a value, and the holder with the highest value is the one `when` is tested on, the first granted among equals. Both read `request.rank`, `request.time`, `request.preempt` and `request.key`, and `holder.rank`, `holder.time`, `holder.preempt`, `holder.key`, `holder.since` and `holder.attr.`, and the run's own names, `t`, `users.`, `queue.`, `level.` and `registry[...]`. With neither, the rule is SimPy's: the holder whose key sorts last is taken when it sorts after the request's. | Key | Type | Default | | -------- | ---- | ------- | | `when` | text | none | | `victim` | text | none | ### Breakdown A resource's `breakdown`: the time to each failure, the repair time, whether the tasks being served are interrupted or finish, and which time the time to failure counts. `clock: calendar` (the default) counts it from the start or the last repair, busy or idle. `clock: busy` counts it only while the resource holds at least one unit; a time to failure of 0 then fails at the grant. | Key | Type | Default | | ----------------- | ------------------------- | ------------- | | `time_to_failure` | [Distribution](#services) | required | | `repair` | [Distribution](#services) | required | | `work` | `interrupt` or `finish` | `"interrupt"` | | `clock` | `calendar` or `busy` | `"calendar"` | ## containers Type: mapping of names to [Container](#containers). Optional. A `containers` entry: its capacity, the largest level, its starting level and the class it is built from. `current_cap` defaults to `max_cap`, and with neither the container has no limit; `.inf` is no limit too. `max_cap` defaults to `current_cap`. `type` is a `!python` subclass of `ContainerBase`. `get_queue` and `put_queue` rank the waiting gets and puts by an expression, as a resource's `queue` ranks its requests; they are not allowed with `type`. With `family: true` the entry is a family of containers, as for a resource, and `current_cap`, `max_cap` and `level` may be expression text. | Key | Type | Default | | ------------- | ---------------------------- | ------- | | `current_cap` | integer or number or text | none | | `max_cap` | integer or number or text | none | | `level` | integer or number or text | `0` | | `type` | !python reference | none | | `get_queue` | [QueueRule](#queuerule) | none | | `put_queue` | [QueueRule](#queuerule) | none | | `family` | boolean | `false` | | `members` | Generator or integer or text | none | ## stores Type: mapping of names to [Store](#stores). Optional. A `stores` entry: how many items it holds, whether it serves by priority, the items it holds when the run starts, and the class it is built from. `current_cap` defaults to `max_cap`, and with neither the store has no limit; `.inf` is no limit too. `max_cap` defaults to `current_cap`. A capacity is a whole number or `.inf`. `items` are returned in the order given; a priority store's items are `[priority, item]` pairs. `type` is a `!python` subclass of `StoreBase`, which sets its own order, so it cannot be given with `priority`. An item is a constant or a `{gen: ...}` generator, drawn once when the run starts. `get_queue` and `put_queue` rank the waiting gets and puts by an expression, as a resource's `queue` ranks its requests; `priority` still ranks the items. They are not allowed with `type`. With `family: true` the entry is a family of stores, as for a resource, each member made with the `items` given. | Key | Type | Default | | ------------- | ---------------------------- | ------- | | `current_cap` | integer or number or text | none | | `max_cap` | integer or number or text | none | | `priority` | boolean | `false` | | `items` | list of Value | | | `type` | !python reference | none | | `get_queue` | [QueueRule](#queuerule) | none | | `put_queue` | [QueueRule](#queuerule) | none | | `family` | boolean | `false` | | `members` | Generator or integer or text | none | ## services Type: mapping of names to [Distribution](#services). Optional. A `services` entry: a distribution family and its parameters. Time-valued parameters (`mean`, `std`, `low`, `mode`, `high`, `scale`, `value`, and an `empirical`'s `values` and `edges`) take seconds or a duration such as `5 min`; `rate` is a number per second. An `exponential` takes `mean`, the average gap, in place of `rate`, and its registry path is still `rate`, 1 / `mean`. | Key | Type | Default | | --------- | ------------------------------------- | -------- | | `dist` | text | required | | `rate` | integer or number | none | | `mean` | integer or number or Duration | none | | `std` | integer or number or Duration | none | | `low` | integer or number or Duration | none | | `value` | integer or number or Duration | none | | `high` | integer or number or Duration | none | | `mode` | integer or number or Duration | none | | `shape` | integer or number | none | | `scale` | integer or number or Duration | none | | `values` | list of integer or number or Duration | none | | `weights` | list of number | none | | `edges` | list of number or Duration | none | | `counts` | list of number | none | | `p` | integer or number | none | ## arrivals Type: mapping of names to [Arrival](#arrivals). Optional. An `arrivals` entry: a distribution, or a `replay` of recorded rows, the task it spawns, and the attributes each entity it starts carries. File order is creation order: arrivals are made in the order they are written, then the `processes`. Events due at one time run in the order they were scheduled, so this order decides only ties between first due times. An `attributes` value is a constant or a `{gen: ...}` generator, drawn once for each entity when it starts, in the order the entities are made. A mapping with a `gen` key is a generator; `{gen: literal, value: ...}` keeps a mapping as data. The gaps come from exactly one of `dist`, `replay` or `gap`. `gap` is a number of seconds, a duration such as `5 min`, an expression or a generator, read at the start of each gap, so a gap may read `registry[...]`, `level.` and `t`. `first_at` is the simulation time of the first arrival, which waits for it in place of a gap; the gaps after it follow. A time already past arrives at once. `max_events` is how many times the arrival starts its task, in all: the arrival stops after the last, and its last start draws no further gap. A start whose key belongs to an entity of the arrival that is still running is skipped with a warning and counts as one. `group` is how many entities one arrival starts, a count place read once at each arrival, after the gap: 0 or less starts nobody and the next gap still runs, and a dropped or empty arrival uses no key number. `initial` creates that many entities when the run is built, after the arrival's source starts and in file order, with the arrival's keys, and an arrival with `initial` alone needs no `dist`, `replay` or `gap`. `active: false` makes a source that starts off, and a task, an `on:` entry or a scenario step turns it on or off with `activate` and `deactivate`. With `off_mode: drop`, the default, the clock keeps running and an arrival while off starts nobody. With `restart` the pending arrival is dropped when the source goes off and `activate` starts a full new gap. An action on a source already in that state does nothing, and an arrival that falls at the instant of an action whose event comes first is dropped. `count` makes that many entities, each with a loop of its own: it starts its task after each gap, `first_at` is the time of its first start, and `max_events` is how many times each entity starts. `keys` is a list of keys instead, one entity for each, and gives the number. `keys` may also be a mapping of each key to its own attributes, fixed values or generators, which are merged over the arrival's `attributes`: a key's value wins, and a key's generator draws from a sequence of its own. `stagger` is the time between the starts of two entities, read after each one. `key` is a value place read once for each entity, for its key; `vars` are named values read once for each entity before its attributes and key, which read them as bare names. Every one of these places reads the run only: `attr` is refused in them, because the entity has none yet. `count` has no argument of `add_arrival`; `max_events` and `vars` do. `count`, `keys`, `first_at` and `stagger` do not apply to a replay. `count`, `keys`, `max_events` and `stagger` set how the arrival starts its task, so each needs `spawn`; `stagger` also needs `count` or `keys`. `key`, `vars`, `gap` and `first_at` are read by `wait_for_arrival` too, so an arrival without `spawn` may carry them. | Key | Type | Default | | ------------ | ------------------------------------------------------------------------ | -------- | | `dist` | text | none | | `rate` | integer or number | none | | `mean` | integer or number or Duration | none | | `std` | integer or number or Duration | none | | `low` | integer or number or Duration | none | | `value` | integer or number or Duration | none | | `high` | integer or number or Duration | none | | `mode` | integer or number or Duration | none | | `shape` | integer or number | none | | `scale` | integer or number or Duration | none | | `values` | list of integer or number or Duration | none | | `weights` | list of number | none | | `edges` | list of number or Duration | none | | `counts` | list of number | none | | `p` | integer or number | none | | `replay` | [Replay](#replay) | none | | `gap` | Generator or integer or number or text or Duration or expression | none | | `first_at` | integer or number or Duration | none | | `count` | Generator or integer or text | none | | `keys` | list of integer or text or mapping of names to mapping of names to Value | none | | `key` | Value | none | | `vars` | mapping of names to Value | | | `stagger` | Generator or integer or number or text or Duration or expression | `0` | | `max_events` | Generator or integer or text | none | | `spawn` | text | none | | `attributes` | mapping of names to Value | | | `group` | Generator or integer or text | `1` | | `active` | boolean | `true` | | `off_mode` | `drop` or `restart` | `"drop"` | | `initial` | integer | `0` | ### Replay An arrival's `replay`: the rows of a local file, each one arrival at its time. `path` is a CSV or Parquet file, relative to the blueprint; `time` its column of times; `unit` `ms`, `s`, `min` or `h` from the start of the run, or `timestamp` for a date and time read from `simulation.logical_start_time`; `fields` the columns each entity carries, or `all`; `on_invalid` `error` or `skip` for a row with no valid time. | Key | Type | Default | | ------------ | ------------------------------------------ | --------- | | `path` | text | required | | `time` | text | `"time"` | | `unit` | `ms` or `s` or `min` or `h` or `timestamp` | `"s"` | | `fields` | text or list of text | `"all"` | | `on_invalid` | `error` or `skip` | `"error"` | ## variables Type: mapping. Optional. ## signals Type: mapping of names to [SignalSpec](#signals) or list of names. Optional. A `signals` entry in the mapping form: `{closing: {once: true, on: [...]}}`. A signal fires once, as SimPy's `Event` does, unless it says `once: false`, which re-arms it after each firing. `on` lists actions run when the signal fires, as a task's `on` lists actions run when it ends. `defused: true` makes every failure of the signal that no waiter handles go unraised, as a callback's `event.defused = True` does; without it, a one-shot signal's failure with no waiter stops the run under `on_unhandled_failure: stop`. `family: true` makes the entry a family of signals, one for each key, as for a resource; `members` makes the keys 0 to n - 1 when the run is built. | Key | Type | Default | | --------- | ---------------------------- | ------- | | `once` | boolean | `true` | | `on` | list of [OnEntry](#onentry) | | | `defused` | boolean | `false` | | `family` | boolean | `false` | | `members` | Generator or integer or text | none | ### OnEntry One entry of an `on:` list: exactly one of a fire, spawn, interrupt or resume action, or a `path` with a `value` as a scenario step sets a registry value. A `value` is a constant or a `{gen: ...}` generator evaluated when the entry runs; a mapping with no `gen` key is data, and a generator nested in it is stored as written. `when` is an expression read when the entry would run: a false result skips the entry, and one that fails is a run failure. | Key | Type | Default | | ------------ | ----------------------------------- | ------- | | `fire` | [FireAction](#fireaction) | none | | `spawn` | [SpawnAction](#spawnaction) | none | | `interrupt` | [InterruptAction](#interruptaction) | none | | `resume` | [ResumeSpec](#resumespec) | none | | `activate` | text or list of text | none | | `deactivate` | text or list of text | none | | `path` | text | none | | `value` | Value | none | | `when` | text | none | ### FireAction An `on:` fire action: fire `signal` with a `value` (a constant, or a `{gen: ...}` generator evaluated when the action runs; a mapping with no `gen` key is data, and a generator nested in it is stored as written), or with the outcome `from` copies from a signal or a task. `urgent` runs the firing ahead of the other events at its time, `priority` orders it among them (the lowest number first), and `after` delays it, as SimPy's `env.schedule(event, priority, delay)` does. All three need a one-shot signal. `urgent` is priority 0, `priority` is an integer that is 1 when it is left out, and the two are not given together. `fail: true` fails the signal in place of firing it, as `Event.fail` does, and `value` is the reason; the task that fired goes on. `defused: true` is for a failure that no waiter handles: it does not stop the run, as `event.defused = True` does (`signals..defused` does the same for every failure of a signal). | Key | Type | Default | | ---------- | ----------------------------- | -------- | | `signal` | text or [Ref](#ref) | required | | `value` | Value | none | | `from` | text | none | | `urgent` | boolean | `false` | | `after` | integer or number or Duration | none | | `priority` | integer | none | | `fail` | boolean | `false` | | `defused` | boolean | `false` | ### Ref A name a task computes, where a task names a resource, a store, a container or a signal: `{of: , key: }` is the member of a family that `key` gives, made when it is first used, and `{of: , lowest: }` is the member whose value is the lowest, `lowest` being read once for each member as `member.key`, `member.users`, `member.queue`, `member.level`, `member.count`, `member.putters` and `member.getters`. `of` may be a list of declared names, and `key` then gives one of them. A reference takes `key` or `lowest`, not both. | Key | Type | Default | | -------- | -------------------- | -------- | | `of` | text or list of text | required | | `key` | text or integer | none | | `lowest` | text | none | ### SpawnAction A `spawn:` key or an `on:` spawn action: start `task` as a new entity, after an optional delay. `count` is how many entities one spawn starts: a whole number, an expression or a generator, read once in the parent's step (0 or less starts none, as `range` gives none). `copy_attributes: true` gives each child a copy of the parent's attributes, one level deep, so a nested mapping stays shared with the parent; `parent` is the parent's key as always. `args` gives each child its local names, read there as `arg.`; each value is read in the parent's step, once for each child. `after` applies to each child. | Key | Type | Default | | ----------------- | ----------------------------- | -------- | | `task` | text | required | | `after` | integer or number or Duration | none | | `count` | Generator or integer or text | `1` | | `copy_attributes` | boolean | `false` | | `args` | mapping of names to Value | none | ### InterruptAction An `interrupt` on a task or a scenario step: interrupt every running instance of `task` whose `where` condition holds, with `cause`, a constant or a `{gen: ...}` generator evaluated at the moment of the interrupt. A task's own `interrupt` may instead give `handle`, the name of a child flow the task or an earlier task of its flow opened with `open`, and interrupts that one child, as `process.interrupt(cause)` does; it takes no `where`, and it fails the run when the child has ended. A scenario step and an `on:` entry take `task` only. | Key | Type | Default | | -------- | --------------- | ------- | | `task` | text | none | | `handle` | text | none | | `index` | integer or text | none | | `where` | text | none | | `cause` | Value | none | ### ResumeSpec A `resume`, a task key and an `on:` entry: wakes the instances of `task` that are suspended in a `wait: {suspend: true}`, in the order they suspended, as `event.succeed(value)` wakes the process that waits for the event. `where` keeps the instances whose scope it holds for (as `interrupt` reads it), `limit` is how many to wake at most (no `limit` wakes all, and 0 wakes nobody), and `value` is what each one's `wait.suspend.value` reads. `limit` and `value` are read once for each `resume`. A `resume` that finds nobody suspended does nothing. | Key | Type | Default | | ------- | ---------------------------- | -------- | | `task` | text | required | | `where` | text | none | | `value` | Value | none | | `limit` | Generator or integer or text | none | ## tasks Type: mapping of names to [Task](#tasks). Optional. A `tasks` entry, built with `SimulationContext.task`. Text in a value place stays text. A time place reads a number as seconds, text `time_to_seconds` accepts as a duration, and other text as an expression. `payload` is the value of the `finished` event: a mapping, or a `!python` function called as `payload(task_id, context)`. `payload: null` publishes no `finished` record and the task runs its other steps; a store `put` on such a task is refused, because the put carries the payload. `id_field` adds the task id to a mapping payload under that key, `key_field` names the payload field whose value becomes the key of the finished event, and so the Kafka message key (the `queued` and `started` records keep the entity's key; a payload without the field fails the run), `item_field` adds the item its store `get` took, and `attributes` adds the named entity attributes. `key` is a value place for the key of the task's records, drawn once for each instance at its first record and written as text; it replaces `key_field`, and the two are not given together. A task with a `service` and no `resource` is a timed step; one with neither, and no `get`, emits its payload as soon as it is spawned. `service_time` is the task's own time, in place of a `service`, and the two are not given together: seconds, a duration such as `30 s`, an expression, or a `{gen: ...}` generator, read after the task has its resource and, for a `get`, its item. It may read `vars_once` and `vars` as bare names, and `item.` after a store get. A result below 0 fails the run. A task with a `resource` needs a `service` or a `service_time`. `priority` is a number or an expression such as `attr.priority`, for a resource whose `queue` is `priority`. `patience` is seconds, a duration such as `30 s`, an expression or a generator; `balk` is a condition checked before the task joins the queue. `resource` is one resource or a list, acquired in the order listed; `keep` hands units to the next task. `on_interrupt` is `resume`, `restart` or `abandon`, and `interrupt` interrupts the running instances of a task when this one finishes. `wait` is what the task waits for first: a signal, a child task, a timeout or a condition, or any or all of several. `signal` names a signal the task fires when it finishes. `fail` is a condition checked after the service: when it holds the task publishes `failed` with `fail_reason`, and goes to `on_fail`. `fail_reason` is text, or a `{gen: ...}` generator read in the step the failure happens, and it is the `reason` of the record, of the failed `signal` and of `upstream.reason`. `get` and `put` take from and add to a store or container. `next` is a task name, `when` rules or `weights`, whose values are numbers or expressions read when the task finishes, with one draw for the choice. `set` gives the entity attribute values when the task finishes. `set_args` writes this process's own local names, read as `arg.` by this task and by the tasks that follow in the same flow (not by a child flow, which has its own). It is read after `set`, so a payload reads the value from before the write. A parent passes names to a child with `args` on a `task` branch of its `wait`, or on a `spawn`; a read of a name that was neither passed nor written is a run failure. `activate` and `deactivate` turn the sources of the named arrivals on and off when the task finishes, after `set_args`. `cause.` reads why the task was interrupted, in a task that an `on_interrupt_next` edge reaches: `by`, `usage_since` and `resource` after a preemption, `value` after an `interrupt`, and `left`, the service time that was left. `upstream.` is the payload of the task that routed here, `item` is the whole item a store get took, and it lasts through the `next` chain. `on_interrupt_run` names a task that runs as a child flow of the same entity after each interrupt or preemption the task meets under `resume` or `restart`, and the task then goes on with the time left, or a new time under `restart`, as a SimPy loop `try: yield env.timeout(left) except Interrupt: yield from repair()` does. The child runs in the task's process. An interrupt that arrives while it runs reaches the child at its next wait and follows the child's own `on_interrupt`. The child reads `cause.` as a task reached by `on_interrupt_next` does. It is refused with `abandon`, with a `resource` and with a request in the `wait`, because it is for work that holds no unit of its own. A child that fails fails the task. `on_renege` and `on_balk` name the task an instance goes to after it reneges (its `patience` ran out) or balks (its `balk` condition holds, or the line of its resource, `seize` or `open` is full), in place of the end of its flow. The instance still publishes `reneged` or `balked`, and that task reads the record as `upstream.status`. `on_fail` needs no `fail`: a failed `wait`, a failed child flow, a step that raises and an expression that cannot be evaluated go to it, and it reads the failure as `upstream.status` and `upstream.reason`. An interrupt is not a failure, and `on_fail` does not see it. `suspend` and `resume` are described on their models. `open` names branches that start at once and are not waited for, so a later step can wait for, cancel, release or interrupt them by name. A branch of `open` is a `timeout`, `request`, `get`, `put`, `task` or `signal`, or an `any` or `all` group of `timeout`, `task`, `signal` and `handle` branches. The other kinds a `wait` takes (`condition`, `running`, `at_least`, `when`) are refused at load, as is a `request`, `get` or `put` inside a group. `listen` adds callbacks to a signal or to an opened name when the task starts, after `open` and before `wait`: its `on` entries run on the next firing of the event, in the order the callbacks were added, as `event.callbacks.append(f)` does. An `on` entry of a task, a signal or a `listen` may carry a `when` expression that skips the entry when it is false. The cause of an interrupt, the holders of a resource and the entries of a queue are lists and mappings an expression reads: `held(m)` and `waiting(m)` for a resource, `putting(s)` and `getting(s)` for a store or container, `running(task)` and `running(task, condition)`, `peek()`, `process.key` and `process.flow_name`, `signal..processed`, and in the `when` of a wait group `done_count`. A value place takes a constant, a list, a mapping or a `{gen: ...}` generator: a mapping with a `gen` key is a generator, and `{gen: literal, value: ...}` keeps a mapping as data. The kinds of `gen` are `uniform`, `integer`, `normal`, `sample`, `one_of`, `weighted`, `pick`, `switch` (key `on`), `when`, `boolean`, `uuid`, `sequence`, `now`, `format_time`, `format`, `lower`, `upper`, `fake`, `add`, `subtract`, `multiply`, `divide`, `min`, `max`, `expr`, `var`, `attr`, `entity`, `param`, `repeat`, `literal`, `object`, `call`, `row`, `lookup`, `previous`, `upstream` and `aggregate`; `null_rate`, `unique`, `omit_rate` and `omit_when` go on any of them. `payload` may be such a mapping, or one generator that gives a mapping or null. A null gives a `finished` record whose value is null, which a Kafka sink with `envelope: false` writes as a tombstone. `id_field`, `item_field` and `attributes` need a mapping, so with them a null fails the task, which `on_fail` handles as any failure. `key_field` needs a mapping too, and with it a null fails the run, as a payload without the field does. A store `put` on the task puts the null as its item. `set` values and the `cause` of an interrupt are evaluated when the task finishes or interrupts. `vars_once` names are drawn once for each entity and task, at the first use, and may be read by a `wait` timeout `value`. `vars` are drawn in order, once for each instance of the task: when it starts if `on_start` is given, otherwise after the service, just before the payload; a `service_time` that reads a var draws it first. `{gen: entity}` gives the entity's key, in a task only. A var reads the vars above it with `{gen: var, name: ...}` or as a bare name in an `expr`. `on_start` values are published as one event record when the task starts. `finish_vars` are drawn after the service and may read the vars. A bare var name also reads in `put`, `fail` and `next.when`, but not in `next.weights`, which read the entity and the run. A var name is an identifier, not a name an expression already uses, and is in one of the three groups only. Every generator node draws from its own stream of the run's seed, so adding a node does not change the draws of the others. A task keeps its last `history` finished payloads (default 1,000,000) when a `lookup` or `aggregate` in the file names it, or when `history` is written. A task that looks up another does not start before the other has a row: an arrival's start is dropped, and one INFO line says how long the task waited in simulation time. A task reached by `next` that has no row to look up ends its flow in the same way. `previous` reads the last finished payload of the same task on the same stream: the arrival, or the entity for an arrival with `count` or `keys`. `upstream` reads the payload of the task that routed here, in a task reached by `next`. `aggregate` is `mean`, `sum`, `min`, `max` or `count` over the last rows of a task that `where`, an expression over the row's fields, keeps. An expression uses Python's arithmetic: `/` gives a float, and `//` rounds down and gives an integer for two integers. `and` and `or` stop at the first operand that decides the result and do not absorb an error: an operand that cannot be evaluated fails the expression. `**` raises to a power (an integer power above 10000 is refused), `abs`, `min`, `max`, `round`, `floor`, `ceil`, `sqrt`, `exp`, `log`, `log10`, `sin`, `cos` and `tan` are calls on numbers, `clamp(x, low, high)` keeps `x` from `low` to `high`, `pi` and `e` are the constants of Python's `math` module (a var or `names` entry of the same name hides one), and `has(attr.x)` is true when the entity has the attribute `x`. An expression also reads a process's local names `arg.`, the interrupt that reached the task as `cause.`, the payload of the task that routed here as `upstream.` (at any depth), `process.key` and `process.flow_name`, the bare `item` and `item_priority` after a store get, and `signal..processed`. `held()`, `waiting()`, `putting()` and `getting()` give lists of mappings (with `entity`, and `rank`, `time`, `preempt`, `key` and `since` for a resource, `item` for a store put and `amount` for a container); `running([, ])` counts the instances of a task, and `peek()` is the time of the next event. Lists `[1, 2]`, mappings `{'a': 1}`, one-clause comprehensions `[x * 2 for x in list if x > 1]`, subscripts and slices, `is None`, `in`, and dotted reads at any depth work on them. The functions `len`, `sum`, `sorted`, `range`, `any`, `all`, `str`, `int`, `float`, `bool`, `get_key(mapping, key, default)`, `set_key(mapping, key, value)` and `drop_key(mapping, key)` work on lists and mappings; `min` and `max` take a list. `set_key` and `drop_key` give a new mapping. A reading makes at most 1,000,000 items, and `%` on text is refused. | Key | Type | Default | | ------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ---------- | | `service` | text | none | | `service_time` | Generator or integer or number or text or Duration or expression | none | | `resource` | text or [Ref](#ref) or list of text or [Ref](#ref) | none | | `payload` | Payload or !python reference | required | | `id_field` | text | none | | `key` | Value | none | | `key_field` | text | none | | `item_field` | text | none | | `attributes` | list of text | | | `priority` | integer or number or text | none | | `patience` | Generator or integer or number or text or Duration or expression | none | | `balk` | text | none | | `get` | [TransferStep](#transferstep) | none | | `put` | [TransferStep](#transferstep) | none | | `next` | text or [Next](#next) | none | | `set` | mapping of names to Value | | | `set_args` | mapping of names to Value | | | `activate` | text or list of text | none | | `deactivate` | text or list of text | none | | `vars` | mapping of names to Value | | | `vars_once` | mapping of names to Value | | | `on_start` | mapping of names to Value | | | `finish_vars` | mapping of names to Value | | | `history` | integer | `1000000` | | `wait` | [SignalWait](#signalwait) or [TaskWait](#taskwait) or [TimeoutWait](#timeoutwait) or [ConditionWait](#conditionwait) or [AnyWait](#anywait) or [AllWait](#allwait) or [AtLeastWait](#atleastwait) or [WhenWait](#whenwait) or [RequestWait](#requestwait) or [GetWait](#getwait) or [PutWait](#putwait) or [RunningWait](#runningwait) or [HandleWait](#handlewait) or [SuspendWait](#suspendwait) or [EachWait](#eachwait) | none | | `open` | mapping of names to [SignalWait](#signalwait) or [TaskWait](#taskwait) or [TimeoutWait](#timeoutwait) or [ConditionWait](#conditionwait) or [AnyWait](#anywait) or [AllWait](#allwait) or [AtLeastWait](#atleastwait) or [WhenWait](#whenwait) or [RequestWait](#requestwait) or [GetWait](#getwait) or [PutWait](#putwait) or [RunningWait](#runningwait) or [HandleWait](#handlewait) or [EachWait](#eachwait) | none | | `listen` | [ListenSpec](#listenspec) | none | | `cancel` | text or [HandleRef](#handleref) | none | | `seize` | text or [SeizeSpec](#seizespec) | none | | `release` | text or [Ref](#ref) or [ReleaseSpec](#releasespec) | none | | `signal` | text or [Ref](#ref) | none | | `fail` | text | none | | `fail_reason` | Value | none | | `on_fail` | text | none | | `on_renege` | text | none | | `on_balk` | text | none | | `keep` | list of text | | | `preempt` | boolean or text | `true` | | `on_interrupt` | `resume` or `restart` or `abandon` | `"resume"` | | `on_interrupt_next` | text | none | | `on_interrupt_run` | text | none | | `interrupt` | [InterruptAction](#interruptaction) | none | | `resume` | [ResumeSpec](#resumespec) | none | | `batch` | [BatchSpec](#batchspec) | none | | `spawn` | [SpawnAction](#spawnaction) | none | | `subscribe` | mapping | none | | `on` | list of [OnEntry](#onentry) | | ### TransferStep A task's `get` or `put`: one `container` with an `amount`, or one `store`. `amount` is a number or an expression such as `payload.quantity`, and 1 when it is left out. `priority` is for a put into a priority store, lowest served first, and 0 when it is left out. Text is an expression such as `attr.priority`; any other value is used as written: a number, a list (which orders element by element, as a tuple does), a mapping, null, a date or a bool. `filter` is a condition for a store get, such as `item.size == attr.size`, where `item.` reads the item offered: the get takes the oldest item that matches. `wait: false` makes the get or put and does not wait for it: the task goes on at once. `item` is for a store `put`: the value to put, a constant, text, a list, a mapping or a `{gen: ...}` generator read as the put is made, a generator nested at any depth of a mapping or list included; left out, the put adds the task's payload. The bare name `item` in `{gen: expr, expr: item}` is the whole item a get took, so `item: {gen: expr, expr: item}` puts it back. | Key | Type | Default | | ----------- | ------------------------- | ------- | | `container` | text or [Ref](#ref) | none | | `store` | text or [Ref](#ref) | none | | `amount` | integer or number or text | `1.0` | | `priority` | None | `0.0` | | `filter` | text | none | | `wait` | boolean | `true` | | `item` | Value | none | ### Next A task's `next`: `when` rules with an optional `default`, or `weights`. | Key | Type | Default | | --------- | ---------------------------------- | ------- | | `when` | list of [Rule](#rule) | | | `default` | text | none | | `weights` | mapping of names to number or text | none | ### Rule A `next.when` entry: a condition and the task it leads to. | Key | Type | Default | | ----------- | ---- | -------- | | `condition` | text | required | | `task` | text | required | ### SignalWait A `wait` branch for a signal's next firing, or for a member of a family of signals, `{signal: {of: , key: }}`. | Key | Type | Default | | -------- | ------------------- | -------- | | `signal` | text or [Ref](#ref) | required | ### TaskWait A `wait` branch for a child flow: it starts `task` for the same entity. `args` are value places read in the parent's scope when the child starts, and the child flow reads them as `arg.`; each child has its own, as a SimPy process has its own arguments. | Key | Type | Default | | ------ | ------------------------- | -------- | | `task` | text | required | | `args` | mapping of names to Value | none | ### TimeoutWait A `wait` branch of a time place: a number of seconds, a duration such as `30 s`, an expression, a `{gen: ...}` generator, or `{after, value}` with a value the waiter receives. An expression or a generator is read when the wait starts. | Key | Type | Default | | --------- | ----------------------------------------------------------------------- | -------- | | `timeout` | Generator or integer or number or text or [TimeoutAfter](#timeoutafter) | required | ### TimeoutAfter A `wait` timeout with a value: `{after: 40 s, value: ...}`, as SimPy's `env.timeout(delay, value)` carries a value the waiter receives. The value is a constant or a `{gen: ...}` generator evaluated when the wait starts, so it may read `vars_once` names but no `vars`. `after` is a time place: seconds, a duration, an expression or a generator, read when the wait starts. | Key | Type | Default | | ------- | -------------------------------------- | -------- | | `after` | Generator or integer or number or text | required | | `value` | Value | none | ### ConditionWait A `wait` branch for a condition, checked again after each change. | Key | Type | Default | | ----------- | ---- | -------- | | `condition` | text | required | ### AnyWait A `wait` done when the first of its named branches is. | Key | Type | Default | | ----- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -------- | | `any` | mapping of names to [SignalWait](#signalwait) or [TaskWait](#taskwait) or [TimeoutWait](#timeoutwait) or [ConditionWait](#conditionwait) or [AnyWait](#anywait) or [AllWait](#allwait) or [AtLeastWait](#atleastwait) or [WhenWait](#whenwait) or [RequestWait](#requestwait) or [GetWait](#getwait) or [PutWait](#putwait) or [RunningWait](#runningwait) or [HandleWait](#handlewait) or [SuspendWait](#suspendwait) or [EachWait](#eachwait) | required | ### AllWait A `wait` done when every one of its named branches is. | Key | Type | Default | | ----- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -------- | | `all` | mapping of names to [SignalWait](#signalwait) or [TaskWait](#taskwait) or [TimeoutWait](#timeoutwait) or [ConditionWait](#conditionwait) or [AnyWait](#anywait) or [AllWait](#allwait) or [AtLeastWait](#atleastwait) or [WhenWait](#whenwait) or [RequestWait](#requestwait) or [GetWait](#getwait) or [PutWait](#putwait) or [RunningWait](#runningwait) or [HandleWait](#handlewait) or [SuspendWait](#suspendwait) or [EachWait](#eachwait) | required | ### AtLeastWait A `wait` done when at least `at_least` of its named branches are. | Key | Type | Default | | ---------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -------- | | `at_least` | integer | required | | `of` | mapping of names to [SignalWait](#signalwait) or [TaskWait](#taskwait) or [TimeoutWait](#timeoutwait) or [ConditionWait](#conditionwait) or [AnyWait](#anywait) or [AllWait](#allwait) or [AtLeastWait](#atleastwait) or [WhenWait](#whenwait) or [RequestWait](#requestwait) or [GetWait](#getwait) or [PutWait](#putwait) or [RunningWait](#runningwait) or [HandleWait](#handlewait) or [SuspendWait](#suspendwait) or [EachWait](#eachwait) | required | ### WhenWait A `wait` done when the expression `when` holds. It is read each time a branch of `of` is processed, and once at the start for a branch already processed, as SimPy's `Condition(env, evaluate, events)` does. It reads `wait..done`, `.ok` and `.value` of the branches and `done_count`. A branch that fails fails the wait, and an empty `of` succeeds at once. | Key | Type | Default | | ------ | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -------- | | `when` | text | required | | `of` | mapping of names to [SignalWait](#signalwait) or [TaskWait](#taskwait) or [TimeoutWait](#timeoutwait) or [ConditionWait](#conditionwait) or [AnyWait](#anywait) or [AllWait](#allwait) or [AtLeastWait](#atleastwait) or [WhenWait](#whenwait) or [RequestWait](#requestwait) or [GetWait](#getwait) or [PutWait](#putwait) or [RunningWait](#runningwait) or [HandleWait](#handlewait) or [SuspendWait](#suspendwait) or [EachWait](#eachwait) | required | ### RequestWait A `wait` branch for a resource unit: the task holds it if it wins. | Key | Type | Default | | --------- | -------------------------------------------------- | -------- | | `request` | text or [Ref](#ref) or [RequestSpec](#requestspec) | required | ### RequestSpec A `request` of a `wait` or an `open` with options: the `resource`, a `priority` (a number or an expression read as the request is made) and a `preempt` flag (true or false, or an expression). With a mapping, the task's `priority` and `preempt` do not apply to this request: a key it leaves out is SimPy's default, priority 0 and preempt true. With a name they do. | Key | Type | Default | | ---------- | ------------------------- | -------- | | `resource` | text or [Ref](#ref) | required | | `priority` | integer or number or text | none | | `preempt` | boolean or text | none | ### GetWait A `wait` branch for a store or container get. | Key | Type | Default | | ----- | ----------------------------- | -------- | | `get` | [TransferStep](#transferstep) | required | ### PutWait A `wait` branch for a store or container put. | Key | Type | Default | | ----- | ----------------------------- | -------- | | `put` | [TransferStep](#transferstep) | required | ### RunningWait A `wait` branch for the running instances of a task: done when they all end. | Key | Type | Default | | --------- | ------------------------------- | -------- | | `running` | [RunningTarget](#runningtarget) | required | ### RunningTarget A `running` wait branch target: the task whose running instances to wait for, narrowed by an optional `where` condition read in each instance's scope. The wait is for the end of the instance's task, or, with `whole_flow: true`, for the end of the whole flow the instance belongs to (its `next` chain and the tasks it waits for in child flows), as `yield process` waits for a SimPy process. A flow selected that way is any flow of the model that is running when the wait begins, or that ended while an instance of a task with such a wait was running and still is; a flow with no match ends the wait at once. Its last task's payload is the branch's value. | Key | Type | Default | | ------------ | ------- | -------- | | `task` | text | required | | `where` | text | none | | `whole_flow` | boolean | `false` | ### HandleWait A `wait` branch for an event that `open` made: `handle` is the name it was opened under. A handle already processed gives its value at once, and a handle waited for through an interrupt under `resume` or `restart` is the same event after it, with its first end and its place in the queue. `index` names one element of an opened `each` group; it is read when the wait starts. | Key | Type | Default | | -------- | --------------- | -------- | | `handle` | text | required | | `index` | integer or text | none | ### SuspendWait A `wait` branch that suspends the instance until a `resume` of another task wakes it (`suspend: true`). The branch's value is the `value` of that `resume`, so `wait.suspend.value` reads it. An interrupt that reaches a suspended instance follows the task's `on_interrupt`: under `resume` the instance stays suspended in its place, under `restart` it suspends again behind the others, and under `abandon` it ends. `open` does not take it. | Key | Type | Default | | --------- | ------- | -------- | | `suspend` | boolean | required | ### EachWait A `wait` on a computed number of events: `branch` is made once for each element of `each`, in order, when the wait starts. `each` is a whole number, a list, an expression or a generator, read once. Inside `branch`, `each.index` is the place from 0 and `each.value` is the element, or the index when `each` is a number. `group` is `all` (the default), `any`, `{at_least: n}` or `{when: expression}`. An empty `each` is done at once. `wait..values` and `.flags` are lists in element order. | Key | Type | Default | | -------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -------- | | `each` | Generator or integer or text or list of any value | required | | `group` | `all` or `any` or [AtLeastGroup](#atleastgroup) or [WhenGroup](#whengroup) | `"all"` | | `branch` | [SignalWait](#signalwait) or [TaskWait](#taskwait) or [TimeoutWait](#timeoutwait) or [ConditionWait](#conditionwait) or [AnyWait](#anywait) or [AllWait](#allwait) or [AtLeastWait](#atleastwait) or [WhenWait](#whenwait) or [RequestWait](#requestwait) or [GetWait](#getwait) or [PutWait](#putwait) or [RunningWait](#runningwait) or [HandleWait](#handlewait) or [SuspendWait](#suspendwait) or [EachWait](#eachwait) | required | ### AtLeastGroup The `group` of an `each` wait done when at least `at_least` elements are, a whole number or an expression read when the wait starts. | Key | Type | Default | | ---------- | --------------- | -------- | | `at_least` | integer or text | required | ### WhenGroup The `group` of an `each` wait done when the expression `when` holds, read as for a `when` wait, with `done_count` and `wait..values` and `.flags`. | Key | Type | Default | | ------ | ---- | -------- | | `when` | text | required | ### ListenSpec A task's `listen`: callbacks added to an event, as `event.callbacks.append(f)` does, when the task starts, after its `open` and before it waits. Exactly one of `signal` and `handle` names the event: a signal, or a member of a family of signals `{of: , key: }`, takes the callbacks on its next firing; a `handle` is an event the flow opened, and `index` picks one element of an opened `each` group. `on` lists the entries to run, each read in the scope of the entity that listens. They run once, on the next firing of the signal or the event of the handle, in the order the callbacks were added: before the waiters added later and after the ones added earlier. To go on listening, a flow listens again. A signal whose firing was processed already, or an event that was processed, takes no callback, which fails the task as `event.callbacks.append` raising does. | Key | Type | Default | | -------- | --------------------------- | ------- | | `signal` | text or [Ref](#ref) | none | | `handle` | text | none | | `index` | integer or text | none | | `on` | list of [OnEntry](#onentry) | | ### HandleRef The name of an opened event, as `{handle: }`, or one element of an opened `each` group, as `{handle: , index: }`. | Key | Type | Default | | -------- | --------------- | -------- | | `handle` | text | required | | `index` | integer or text | none | ### SeizeSpec A `seize` with options: the `resource`, a `priority` (a number or an expression read as the request is made), a `preempt` flag (true or false, or an expression), and a `patience`, which is the task's patience for the time it waits for the unit. `priority` and `preempt` default to the task's. A task gives its `patience` on the task or here, not both. | Key | Type | Default | | ---------- | ---------------------------------------------------------------- | -------- | | `resource` | text or [Ref](#ref) | required | | `priority` | integer or number or text | none | | `preempt` | boolean or text | none | | `patience` | Generator or integer or number or text or Duration or expression | none | ### ReleaseSpec A `release` with options: `{handle: }` frees the unit of that opened request, and `{resource, task, where}` frees the units of `resource` that the instances of `task` hold, however they asked (`resource`, `seize`, `open` or a `request` in a wait) and whichever flow they are in, oldest grant first; `where` is read in the instance's scope, and without it every holder of that task is freed. The holder is not told. A resource name alone frees the oldest unit of it that the flow holds. | Key | Type | Default | | ---------- | ------------------- | ------- | | `handle` | text | none | | `index` | integer or text | none | | `resource` | text or [Ref](#ref) | none | | `task` | text | none | | `where` | text | none | ### BatchSpec A task's `batch`: its members wait together and one run of the task's `resource` and service serves them all. The batch closes when `size` members have joined, `timeout` after its first member, or when `close_when` holds as a member joins, whichever is first. `size` is a number, or text read as an expression in the scope of the first member when it joins; 1 or below closes the batch at its first member. `close_when` reads `batch.size` (how many members it holds) and `batch.age` (seconds since its first member). `name` names the batch and defaults to the task's name: tasks with the same `name` share one open batch, so they must have the same `size`, `timeout`, `close_when`, `resource` and service (`service` or `service_time`), or the file is refused at load. Values are compared by what they mean, so a generator written the same way, an expression with other spacing and a number written as text agree. Each member keeps its own `on_interrupt`, `patience`, payload and `next`, and follows its own `next` in the order the members joined. | Key | Type | Default | | ------------ | ---------------------------------------------------------------- | -------- | | `name` | text | none | | `size` | integer or number or text | required | | `timeout` | Generator or integer or number or text or Duration or expression | none | | `close_when` | text | none | ## telemetry Type: list of [Telemetry](#telemetry). Optional. A `telemetry` entry: custom readings published every `interval` seconds. It takes exactly one of `function` and `readings`. `function` is a `!python` function called as `function(context)`, which publishes with `context.publish`. `readings` maps a reading name to an expression read over the run (`level.`, `users.`, `queue.`, `signal.`, `registry[...]`, `t` and the functions of the expression language, and no name of an entity or a task). Each interval publishes one telemetry record for each reading, named `.`, as `context.publish` names one, in the order the readings are written. An expression that cannot be evaluated stops the run. Resource, store and container readings come from `stats` instead. | Key | Type | Default | | ---------- | ------------------------ | -------- | | `interval` | number | required | | `function` | !python reference | none | | `readings` | mapping of names to text | none | ## processes Type: list of [Process](#processes) or !python reference. Optional. A `processes` entry: a generator function and extra keyword arguments. The function is called as `function(context, **kwargs)` when the run starts. The processes are made after the arrivals, in the order they are written. | Key | Type | Default | | ---------- | ----------------- | -------- | | `function` | !python reference | required | | `kwargs` | mapping | | ## scenario Type: list of [ScenarioStep](#scenario). Optional. A `scenario` entry: at simulation time `at`, set `path` to `value`, publish a ground-truth record of `record`, or both. `at` is seconds from the start of the run, or a duration such as `"10 min"`. A step with a `record` publishes a ground-truth record, `stream_type: label`, with the path, the value before and after, and the `record` mapping, to the sinks with `when: labels` only. A step with an `interrupt` interrupts the running instances of a task, as a task's `interrupt` does. A step with `activate` or `deactivate`, an arrival name or a list of them, turns those arrivals on or off, as a task's `activate` and `deactivate` do, in place of a `path` and `value`; each arrival must have a `spawn`. A `value` and each `record` value are constants or `{gen: ...}` generators: `value` is evaluated just before the change and `record` just after it. | Key | Type | Default | | ------------ | ----------------------------------- | -------- | | `at` | integer or number or Duration | required | | `path` | text | none | | `value` | Value | none | | `record` | mapping of names to Value | none | | `interrupt` | [InterruptAction](#interruptaction) | none | | `activate` | text or list of text | none | | `deactivate` | text or list of text | none | ## ingress Type: list of [Connector](#ingress). Optional. An `ingress` entry: a connector type and its constructor arguments. `type` is a short name such as `Kafka`, or a `!python` class for a connector from another package. | Key | Type | Default | | -------- | ------------------------------- | -------- | | `type` | short name or !python reference | required | | `config` | mapping | | ## egress Type: list of [EgressConnector](#egress). Optional. An `egress` entry, with the per-provider options of `add_egress`. `when` is `history`, `live`, `events`, `telemetry`, `labels`, `trace`, a mapping `{expr: ...}` or a `!python` function taking one record. `history` sends the records stamped before `simulation.go_live_at`, and `live` sends the records stamped at or after it. `events` sends the event records and `telemetry` the telemetry records. `labels` sends the ground-truth records of scenario steps with a `record`, and nothing else. `trace` sends the records of `stats.trace`, one for each event the environment processes, and nothing else; no other entry receives them. `envelope: false` makes the entry plain output: the sink writes each event's value without the record around it (`stream_type`, `sim_ts`, `timestamp`, `key`, `task` and `instance`), and it receives no telemetry record and no `queued` or `started` record of a task. A Kafka sink sends a null value as a tombstone, a message with the record's key and a null value, and sends any other value that is not a mapping as JSON. A Redis sink sends a value that is not a mapping as JSON, null included. A storage, Iceberg or PostgreSQL sink skips it, with one warning. The message key of Kafka stays the record's key, and a `topic_router` still receives the whole record. Ground-truth records of a `when: labels` entry are not affected. | Key | Type | Default | | ---------------- | ------------------------------------------------------------------------------------------------------------------- | -------- | | `type` | short name or !python reference | required | | `config` | mapping | | | `when` | `history` or `live` or `events` or `telemetry` or `labels` or `trace` or [WhenExpr](#whenexpr) or !python reference | none | | `envelope` | boolean | `true` | | `batch_size` | integer | none | | `flush_interval` | number | none | ### WhenExpr An egress `when` written as an expression: `when: {expr: }`. The expression reads the record the sink is offered: `record.stream_type` (`event` or `telemetry`), `record.key`, `record.task` and `record.value.`. A name the record lacks reads as None, so `record.value.event_type == 'order_packed'` is false for a telemetry record and for an event without that field. The sink receives the record when the expression is true. An expression that fails on a record, such as `record.value.amount > 100` on a record whose value has no `amount`, fails the run. | Key | Type | Default | | ------ | ---- | -------- | | `expr` | text | required | ## batching Type: [Batching](#batching). Optional. The `batching` section: the arguments of `with_batching`. | Key | Type | Default | | --------------------- | ------- | -------- | | `batch_size` | integer | required | | `flush_interval` | number | required | | `max_queued_batches` | integer | none | | `drain_stall_seconds` | number | none | ## stats Type: [Stats](#stats) or level name. Optional. The `stats` section: the built-in statistics level and how often to publish. Written as a level alone (`stats: basic`) or as a mapping (`stats: {level: all, interval: 60}`). The interval is in seconds or a duration such as `5 min`. A mapping needs a `level`, unless it sets only `trace`, when the level is `none`. `on_change: true` also publishes a resource's readings at each `request` and `release` call on it, so it needs a level above `none`. `trace: true` publishes one record for each event the environment processes, of the kind `trace`, to the egress entries with `when: trace`. | Key | Type | Default | | ----------- | ---------------------------------------------------- | ------- | | `level` | `none` or `minimal` or `basic` or `typical` or `all` | | | `interval` | integer or number or Duration | `10.0` | | `on_change` | boolean | `false` | | `trace` | boolean | `false` | ## run Type: mapping. Optional. The `run` section. `before` lists `!python` functions called with no arguments before the run starts, for setup such as creating topics or tables. `stop` ends the run before `until` at the next firing of a signal, `{signal: name}`, or when a condition first holds, `{condition: ...}`. `drain`, `true` or `{limit: 1 h}`, stops the arrivals at `until` and runs on until no entity is left in the model. `segments` runs the model in parts and publishes a reading after each, as a SimPy program that calls `env.run(until=...)` in a loop does: a list of `RunSegment`, or `{every: