5. An assembly line

A production line is a chain of stations. Parts arrive, wait, get processed, and move on. Throughput is limited by the slowest station, the bottleneck, and finding it is the first question anyone asks. This chapter builds a three-station line where individual parts flow between stations, then uses captured data, diagrams and a crossed sweep to find the bottleneck and fix it.

The full script is tutorial/tut_5_1.py.

Parts that carry their own history

Each part is a small dynamic model with just enough fields to measure its journey:

class Part(cb.Model):
    part_id: int
    arrival_system: float
    station_entry: float

It has no processes. Stations push it around. A model without behavior is perfectly fine: it’s a record that lives in the simulation and can be stored, passed and released.

Stations hand parts downstream

 1class Station(cb.Model):
 2    processing_time: cb.Input[float] = inputs.dist.exponential(mean=5.0)
 3    inbox: cb.Store[Part]
 4    downstream: cb.Ref["Station"] | None
 5    finished: cb.Ref[FinishedParts] | None
 6    resource: cb.Resource
 7    wait_time: cb.Dataset
 8    avg_wait_time: cb.Output[float]
 9    utilization: cb.Output[float]
10
11    def __init__(self, name: str, mean_processing_time: float, *,
12                 downstream=None, finished=None):
13        self.name = name
14        self.processing_time = inputs.dist.exponential(mean=mean_processing_time)
15        self.downstream = downstream
16        self.finished = finished
17
18    @cb.process
19    def server(self):
20        while True:
21            part = self.inbox.get()
22            self.wait_time.record(cb.now() - part.station_entry)
23            self.resource.acquire()
24            cb.hold(self.processing_time.next())
25            self.resource.release()
26            part.station_entry = cb.now()
27            if self.downstream is not None:
28                self.downstream.inbox.put(part)
29            elif self.finished is not None:
30                self.finished.inbox.put(part)
31
32    @cb.on_end
33    def station_stats(self):
34        self.avg_wait_time = self.wait_time.sample_mean()
35        self.utilization = 100.0 * self.resource.mean_in_use()

Things to notice:

  • Typed inboxes. inbox: cb.Store[Part] holds part handles. self.inbox.get() returns a Part view, so part.station_entry is a normal field access, and put refuses anything that isn’t a Part when the class is compiled.

  • Optional references. downstream: cb.Ref["Station"] | None may be None: the last station has no downstream station and hands parts to the FinishedParts sink instead. The if self.downstream is not None test works in compiled code exactly as it reads.

  • Host-only attributes. self.name = name (line 13) is not declared as a field. It’s an ordinary Python attribute that the compiled code never sees. That’s handy for labels you use when printing results.

  • A resource per station. The server acquires the station’s resource while processing, so mean_in_use() becomes the station’s utilization.

The line itself creates the stations back to front, so each one can be given its downstream neighbour, and spawns parts into station 1:

def __init__(self, duration=SIMULATION_TIME):
    self.duration = duration
    self.finished_parts = FinishedParts(self)
    self.station_3 = Station(STATION_NAMES[2], STATION_MEANS[2],
                             finished=self.finished_parts)
    self.station_2 = Station(STATION_NAMES[1], STATION_MEANS[1],
                             downstream=self.station_3)
    self.station_1 = Station(STATION_NAMES[0], STATION_MEANS[0],
                             downstream=self.station_2)
    self.system = cb.Container()
    self.system.capture()
    self.cycle_time = cb.Dataset()
    self.cycle_time.capture()
    for station in (self.station_1, self.station_2, self.station_3):
        station.wait_time = cb.Dataset()
        station.wait_time.capture()
@cb.process
def arrivals(self):
    while True:
        cb.hold(self.arrival_gap.next())
        self.generated_parts += 1
        part = cb.spawn(Part, part_id=self.generated_parts,
                        arrival_system=cb.now(), station_entry=cb.now())
        self.system.put(1)
        self.station_1.inbox.put(part)

The system container counts parts in the system: up by one on arrival, down by one when FinishedParts releases a part. Its time-weighted mean level is the average work in progress.

Capturing what happened

The constructor also captures three kinds of history: the WIP container, the cycle-time dataset and each station’s wait-time dataset. After the run, each captured entity is a Signal indexed by design point and replication:

def plot_results(model: AssemblyLine, results: cb.Results) -> None:
    try:
        import matplotlib.pyplot as plt  # pyright: ignore[reportMissingImports]
    except ModuleNotFoundError as exc:
        raise SystemExit("Install the plot extra to create figures") from exc
    PLOT_DIR.mkdir(parents=True, exist_ok=True)
    _, cycle_times = results[model].cycle_time.trial(0, 0)
    _, axes = plt.subplots(1, 2, figsize=(12, 4))
    axes[0].hist(cycle_times, bins=20)
    axes[0].set_title("Part cycle time")
    axes[0].set_xlabel("Minutes")
    utilizations = [results[station].utilization[0, 0] for station in
                    (model.station_1, model.station_2, model.station_3)]
    axes[1].bar(STATION_NAMES, utilizations)
    axes[1].set_title("Station utilization")
    axes[1].set_ylabel("Percent")
    plt.tight_layout()
    plt.savefig(PLOT_DIR / "assembly_line.png", dpi=150)

For a captured dataset, trial(p, r) returns (times, values) where times is empty and values holds every recorded sample: here, every part’s cycle time. For a captured container or resource you get the full step history of its level.

Seeing the structure

When a model has more than a couple of parts, a picture helps. cimba.diagrams draws two, straight from the configured model, without compiling or running it:

from cimba import diagrams

line = AssemblyLine()
print(diagrams.structure(line).to_mermaid())       # who owns and references whom
print(diagrams.process_graph(line).to_mermaid())   # how processes interact

The structure shows ownership (solid) and references (dotted). The labels, assemblyline.station_2 and so on, are the canonical paths Cimba uses in error messages and provenance:

        ---
config:
  layout: elk
---
flowchart LR
  n0["assemblyline: AssemblyLine"]
  n1["assemblyline.finished_parts: FinishedParts"]
  n2["assemblyline.station_1: Station"]
  n3["assemblyline.station_2: Station"]
  n4["assemblyline.station_3: Station"]
  n0 -->|finished_parts| n1
  n0 -->|station_1| n2
  n0 -->|station_2| n3
  n0 -->|station_3| n4
  n1 -.->|line| n0
  n2 -.->|downstream| n3
  n3 -.->|downstream| n4
  n4 -.->|finished| n1
    

The process graph follows a part through the line. Arrivals spawn it and put it in station 1’s inbox. Each server gets it, acquires its resource, reads a processing time and puts the part downstream, until the finishing process records the cycle time:

        ---
config:
  layout: elk
---
flowchart LR
  subgraph g0["assemblyline: AssemblyLine"]
    n0[/"arrival_gap · exponential"/]
    n1["system · Container"]
    n2["cycle_time · Dataset"]
    n3(["arrivals"])
  end
  subgraph g1["assemblyline.finished_parts: FinishedParts"]
    n4["inbox · Store[Part]"]
    n5(["finish"])
  end
  subgraph g2["assemblyline.station_1: Station"]
    n6["inbox · Store[Part]"]
    n7[/"processing_time · exponential"/]
    n8["resource · Resource"]
    n9["wait_time · Dataset"]
    n10(["server"])
  end
  subgraph g3["assemblyline.station_2: Station"]
    n11["inbox · Store[Part]"]
    n12[/"processing_time · exponential"/]
    n13["resource · Resource"]
    n14["wait_time · Dataset"]
    n15(["server"])
  end
  subgraph g4["assemblyline.station_3: Station"]
    n16["inbox · Store[Part]"]
    n17[/"processing_time · exponential"/]
    n18["resource · Resource"]
    n19["wait_time · Dataset"]
    n20(["server"])
  end
  subgraph g5["Part (spawned)"]
    n21[["new Part"]]
  end
  n0 -->|next| n3
  n3 -->|spawn| n21
  n3 -->|put| n1
  n3 -->|put| n6
  n4 -->|get| n5
  n5 -->|record| n2
  n1 -->|get| n5
  n6 -->|get| n10
  n10 -->|record| n9
  n8 -->|acquire| n10
  n7 -->|next| n10
  n10 -->|release| n8
  n10 -->|put| n11
  n11 -->|get| n15
  n15 -->|record| n14
  n13 -->|acquire| n15
  n12 -->|next| n15
  n15 -->|release| n13
  n15 -->|put| n16
  n16 -->|get| n20
  n20 -->|record| n19
  n18 -->|acquire| n20
  n17 -->|next| n20
  n20 -->|release| n18
  n20 -->|put| n4
    

Both return a cimba.diagrams.Graph that renders to Mermaid or Graphviz DOT. The script saves both as .mmd files next to its plots. See Draw your model for everything they can show.

Reading the results

$ uv run python tutorial/tut_5_1.py
--- Simulation Results Analysis (Cimba) ---
Total parts produced: 1389
Average cycle time: 3023.54 minutes
Maximum cycle time: 5948.39 minutes
Throughput rate: 0.14 parts/minute
Station 1: wait 2135.80 min, utilization 99.77%
Station 2: wait 1487.98 min, utilization 99.97%
Station 3: wait 4.63 min, utilization 55.85%
Average parts in system: 1031.00
Maximum parts in system: 2064
Parts still in system: 2062

Something is badly wrong, and the model tells us exactly what. Parts arrive every 3 minutes on average (0.33 per minute), but only 0.14 per minute leave. Work in progress climbs to over 2,000 parts and is still climbing when the window closes. Stations 1 and 2 are busy essentially all the time.

The mean processing times are 5, 7 and 4 minutes. Station 2 can finish at most 1/7 ≈ 0.143 parts per minute, which matches the measured throughput: station 2 is the bottleneck. Station 1 (1/5 per minute) is also slower than the arrivals, and station 3 is starved.

Fixing the bottleneck with a crossed sweep

Suppose we can speed up stations 1 and 2 to a mean of 2.5 minutes each. Which upgrades do we need? Each station’s processing time is an input, so we can sweep its source, and two independent sweeps cross:

line = AssemblyLine()
line.station_1.processing_time = cb.sweep(inputs.dist.exponential(mean=5.0),
                                          inputs.dist.exponential(mean=2.5))
line.station_2.processing_time = cb.sweep(inputs.dist.exponential(mean=7.0),
                                          inputs.dist.exponential(mean=2.5))

results = cb.Experiment(line, replications=10,
                        window=cb.Window(duration=10_000.0), seed=45).run()
cb.analysis.summary(results[line].throughput_rate).mean

Point

Station 1 mean

Station 2 mean

Throughput (parts/min)

0

5.0

7.0

0.140

1

5.0

2.5

0.199

2

2.5

7.0

0.140

3

2.5

2.5

0.249

This is the classic shifting bottleneck. Speeding up station 1 alone (point 2) changes nothing, because station 2 still limits the line. Speeding up station 2 alone (point 1) lifts throughput to station 1’s limit of 0.2. Upgrading both (point 3) helps most, but throughput stops at 0.25, not 0.33: now station 3, at 4 minutes per part, is the bottleneck.

Two sweeps give 2 × 2 = 4 design points. Design points are ordered like nested loops, with the first sweep found in the model tree as the outer loop. results.levels(sweep) returns each point’s value on any axis, so you never need to work the order out by hand. If you want two sweeps to move together instead of crossing, create them with cb.sweeps (see Experiments).

What you learned

  • Dynamic models can be pure data records passed between typed stores.

  • Ref[M] | None expresses optional links; undeclared attributes stay in Python.

  • Captured datasets and containers give per-trial raw data for plots.

  • cimba.diagrams.structure and process_graph draw the configured structure and the process interactions.

  • Independent sweeps cross into a full factorial design, and sweeping input sources is as easy as sweeping parameters.

The next chapter, 6. A data-driven supply chain, turns to what makes Cimba Python different: driving a model with real data.