4. A weather-gated harbor
Larger models are built from parts: the physical plant, the environment, the flow of work. Each part has its own fields and processes, and the parts need to see each other. This chapter builds a harbor from four cooperating models and introduces the most flexible way to wait in Cimba: waiting for a condition.
The scenario, from the C library’s tutorial 4:
Small and large ships arrive at random. To dock, a ship needs a free berth of its size, enough tugboats (one for a small ship, three for a large one), a free radio channel, and safe conditions: wind below its limit and water deep enough for its draught.
Wind changes hourly. Water depth follows the tides, pushed up or down by the wind.
After unloading, the ship needs the tugs and the radio again to leave.
We want the time ships spend in the harbor, and how busy the tugs and berths
are. The full script is tutorial/tut_4_1.py.
Designing the model tree
Start with the parts and how they relate, not the code. The harbor owns three parts, and ships are spawned into it during the trial:
---
config:
layout: elk
---
flowchart LR
n0["harbor: Harbor"]
n1["harbor.sea: SeaConditions"]
n2["harbor.facilities: HarborFacilities"]
n3["harbor.traffic: ShipTraffic"]
n0 -->|sea| n1
n0 -->|facilities| n2
n0 -->|traffic| n3
n1 -.->|harbor| n0
n3 -.->|harbor| n0
Solid arrows mean owns; dotted arrows are references. Each part is a model class. The root owns the three parts as children and builds them in its constructor:
def __init__(self, *, mean_wind=5.0, reference_depth=15.0,
arrival_rate=0.5, percent_large=0.25, num_tugs=10,
num_berths_small=6, num_berths_large=3,
unload_avg_small=8.0, unload_avg_large=12.0):
self.reference_depth = reference_depth
self.percent_large = percent_large
self.facilities = HarborFacilities(
int(num_tugs), int(num_berths_small), int(num_berths_large))
self.sea = SeaConditions(self, mean_wind)
self.traffic = ShipTraffic(
self, arrival_rate, unload_avg_small, unload_avg_large)
Notice SeaConditions(self, mean_wind): the children get a reference
back to the harbor, because the tide process needs the harbor’s
reference_depth parameter and the ships need everything. References may
point anywhere in the tree: up, down or sideways. Cycles are fine, since a
Ref is just a pointer, not ownership.
The constructor also turns plain Python arguments into configuration. Some
become Param values (reference_depth, percent_large), some become
entity capacities, and some become input sources. That’s the pattern for
reusable models: take domain arguments in __init__, turn them into fields.
The facilities are just entities with capacities:
class HarborFacilities(cb.Model):
tugs: cb.Resource
berths_small: cb.Resource
berths_large: cb.Resource
comms: cb.Resource
harbormaster: cb.Condition
def __init__(self, num_tugs, num_berths_small, num_berths_large):
self.tugs = cb.Resource(capacity=num_tugs)
self.berths_small = cb.Resource(capacity=num_berths_small)
self.berths_large = cb.Resource(capacity=num_berths_large)
self.comms = cb.Resource(capacity=1)
The environment
Weather and tide are two processes on the SeaConditions model:
class SeaConditions(cb.Model):
harbor: cb.Ref["Harbor"]
wind_source: cb.Input[float] = inputs.dist.rayleigh(scale=5.0)
direction_source: cb.Input[float] = inputs.dist.pert(
low=0.0, mode=225.0, high=360.0)
wind_mag: float = 0.0
wind_dir: float = 0.0
water_depth: float = 0.0
def __init__(self, harbor, mean_wind):
self.harbor = harbor
self.wind_source = inputs.dist.rayleigh(scale=mean_wind)
@cb.process(priority=1)
def weather(self):
while True:
self.wind_mag = 0.5 * self.wind_source.next() + 0.5 * self.wind_mag
self.wind_dir = self.direction_source.next()
cb.hold(1.0)
@cb.process
def tide(self):
while True:
t = cb.now()
pi = np.pi
astronomical = (self.harbor.reference_depth +
np.sin(2.0 * pi * t / 12.4) +
0.5 * np.sin(2.0 * pi * t / 24.0) +
0.25 * np.sin(2.0 * pi * t / (0.5 * 29.5 * 24)))
wind_effect = (0.5 * self.wind_mag - 0.5 * self.wind_mag *
np.sin(self.wind_dir * pi / 180.0))
self.water_depth = astronomical + wind_effect
self.harbor.facilities.harbormaster.signal()
cb.hold(1.0)
A few things are worth pointing out:
wind_sourceanddirection_sourceare inputs, with default sources on the class and a per-instance override in__init__. Wind is exactly the kind of variability you might later drive with measured weather data.The weather process has
priority=1. Both processes wake up every hour. When two events fall at the same instant, the higher priority runs first, so the tide always sees this hour’s wind.The tide calls NumPy (
np.sin,np.pi) inside compiled code. Numba supports most of NumPy’s math.After updating the depth, the tide calls
self.harbor.facilities.harbormaster.signal(). We’ll see why next.
Waiting for a condition
A ship can dock only when five things are true at once: depth, wind, tugs,
berth, and (a moment later) radio. You can’t express that as a single
acquire. The ship waits until its entry conditions hold, then acquires
the resources it needs.
That’s a Condition. Processes wait on it with
wait_until(predicate); anyone who changes something relevant calls
signal(). When a condition is signalled, the engine re-evaluates each
waiting process’s predicate, a method marked @cb.predicate that
returns True or False, and wakes those whose predicate holds.
The ship’s voyage starts like this:
@cb.process
def voyage(self):
facilities = self.harbor.facilities
if self.size == LARGE:
berths = facilities.berths_large
else:
berths = facilities.berths_small
facilities.harbormaster.wait_until(self.can_enter)
The ship’s predicate checks depth, wind, tugs and berths. wait_until checks
it before blocking and again when signalled, keeping the entry rules on the ship.
@cb.predicate
def can_enter(self):
sea = self.harbor.sea
facilities = self.harbor.facilities
berths = (facilities.berths_large if self.size == LARGE else
facilities.berths_small)
return (sea.water_depth >= self.min_depth and
sea.wind_mag <= self.max_wind and
facilities.tugs.available() >= self.tugs_needed and
berths.available() >= 1)
The other half of the contract is signalling. The tide signals every hour, and
every ship signals when it releases tugs or a berth. A missing signal() is
the classic condition bug: waiters sleep forever because nobody told them the
world changed.
Tip
Predicates are compiled like processes and follow the same rules.
A related tool is the event: a method marked @cb.event that you
schedule with cb.schedule(self.method, delay). It runs once at that
time, outside any process, and returns a Scheduled handle you can
cancel(). Events are handy for one-off happenings such as a shift
change or a deadline.
Once cleared, the ship grabs what it needs in order, and releases in order:
berths.acquire(1)
facilities.tugs.acquire(self.tugs_needed)
facilities.comms.acquire()
cb.hold(self.harbor.traffic.radio_delay.next())
facilities.comms.release()
cb.hold(self.harbor.traffic.movement.next())
facilities.tugs.release(self.tugs_needed)
facilities.harbormaster.signal()
if self.size == LARGE:
cb.hold(self.harbor.traffic.unload_large.next())
else:
cb.hold(self.harbor.traffic.unload_small.next())
facilities.tugs.acquire(self.tugs_needed)
facilities.comms.acquire()
cb.hold(self.harbor.traffic.radio_delay.next())
facilities.comms.release()
cb.hold(self.harbor.traffic.movement.next())
berths.release(1)
facilities.tugs.release(self.tugs_needed)
facilities.harbormaster.signal()
if self.size == LARGE:
self.harbor.traffic.time_large.record(cb.now() - self.arrival)
else:
self.harbor.traffic.time_small.record(cb.now() - self.arrival)
self.harbor.traffic.departed.put(self)
Every duration comes from an input on ShipTraffic. The ship reaches them
through its reference: self.harbor.traffic.unload_large.next(). Inputs are
fields like any other, so they can live wherever they belong conceptually.
The whole picture
With all the processes written, cimba.diagrams.process_graph() shows
how they meet. Each ship’s single voyage process touches every facility,
every traffic input and both datasets. Weather and tide run on their own and
talk to the ships only through the harbormaster condition.
---
config:
layout: elk
---
flowchart LR
subgraph g1["harbor.sea: SeaConditions"]
n0[/"wind_source · rayleigh"/]
n1[/"direction_source · pert"/]
n2(["weather"])
n3(["tide"])
end
subgraph g2["harbor.facilities: HarborFacilities"]
n4["harbormaster · Condition"]
n5["tugs · Resource"]
n6["berths_small · Resource"]
n7["berths_large · Resource"]
n8["comms · Resource"]
end
subgraph g3["harbor.traffic: ShipTraffic"]
n9[/"arrival_gap · exponential"/]
n10[/"radio_delay · gamma"/]
n11[/"movement · pert"/]
n12[/"unload_small · pert"/]
n13[/"unload_large · pert"/]
n14["departed · Store[Ship]"]
n15["time_small · Dataset"]
n16["time_large · Dataset"]
n17(["arrivals"])
n18(["departures"])
end
subgraph g4["Ship (spawned)"]
n19[["new Ship"]]
n20(["voyage"])
end
n0 -->|next| n2
n1 -->|next| n2
n3 -->|signal| n4
n9 -->|next| n17
n17 -->|spawn| n19
n14 -->|get| n18
n4 -->|wait| n20
n7 -->|acquire| n20
n6 -->|acquire| n20
n5 -->|acquire| n20
n8 -->|acquire| n20
n10 -->|next| n20
n20 -->|release| n8
n11 -->|next| n20
n20 -->|release| n5
n20 -->|signal| n4
n13 -->|next| n20
n12 -->|next| n20
n20 -->|release| n7
n20 -->|release| n6
n20 -->|record| n16
n20 -->|record| n15
n20 -->|put| n14
Ships as values in a store
The last line of the voyage hands the ship itself to a store:
self.harbor.traffic.departed.put(self). On the other side, a departures
process releases each ship:
@cb.process
def arrivals(self):
while True:
cb.hold(self.arrival_gap.next())
size = int(cb.random.bernoulli(self.harbor.percent_large))
cb.spawn(Ship, harbor=self.harbor, size=size,
tugs_needed=TUGS_NEEDED[size],
max_wind=MAX_WIND[size], min_depth=MIN_DEPTH[size],
arrival=cb.now())
@cb.process
def departures(self):
while True:
cb.release(self.departed.get())
departed: cb.Store[Ship] is a FIFO store of ship handles. Stores are typed
(Store[int], Store[float] or Store[SomeModel]), so what comes out
of get() is fully usable. Here the store is a tidy way to hand the ship’s
lifetime back to the traffic model.
Running and reading the results
$ uv run python tutorial/tut_4_1.py
cimba 3.0.0: 20 harbor trials in 2.24 s
n_small: 3273.900
n_large: 1089.450
avg_time_small: 10.861
avg_time_large: 17.139
tug_util: 0.876
berth_small_util: 3.810
berth_large_util: 1.827
A year of harbor operations, 20 times, in about two seconds. Large ships spend 17 hours in port against 11 for small ones: they unload longer, and their stricter depth and wind limits keep them waiting for the weather.
Comparing designs fairly
The point of a model like this is to ask what if. Two kinds of change are possible, and Cimba handles them slightly differently.
Changing a parameter. percent_large is a Param, so it can be
swept inside one experiment:
harbor = Harbor()
share = cb.sweep(0.15, 0.25, 0.35)
harbor.percent_large = share
window = cb.Window(warmup=24.0, duration=HOURS_PER_YEAR)
results = cb.Experiment(harbor, replications=20, window=window, seed=7).run()
print(results.levels(share))
print(cb.analysis.summary(results[harbor].avg_time_large).mean)
print(cb.analysis.compare(results[harbor].avg_time_large, a=0, b=2))
(0.15, 0.25, 0.35)
[15.17 17.13 26.46]
Comparison(a=0, b=2, n=20, difference=11.30, lower=10.28, upper=12.31)
Going from 15% to 35% large ships adds 11.3 hours (95% CI 10.3–12.3) to each large ship’s stay.
Changing structure. The number of tugs is a resource capacity, part of the model’s structure, so it is set when the model is built, not swept. Build one model per variant and run each with the same seed:
import numpy as np
samples = []
for tugs in (8, 10):
variant = Harbor(num_tugs=tugs)
results = cb.Experiment(variant, replications=20, window=window, seed=7).run()
samples.append(results[variant].avg_time_small.values[0])
print(cb.analysis.compare(np.vstack(samples), a=0, b=1))
Comparison(a=0, b=1, n=20, difference=-0.00016, lower=-0.00025, upper=-0.00008)
Same seed plus same model structure means the same random stream for every input. Ship k of replication r arrives at the same moment with the same cargo in both variants, so the comparison is paired. The effect of two extra tugs is tiny: less than a second per ship. Yet the interval excludes zero, because pairing strips out almost all the noise. Common random numbers let you detect small effects; whether they matter is your call.
tutorial/tut_4_2.py uses the same technique to compare one versus two
large berths in a harbor that handles only large ships. With one berth, that
harbor can’t keep up at all.
What you learned
Build models from parts: child models for ownership,
Reffor everything else, and__init__to turn domain arguments into fields.Condition.wait_until(predicate)+signal()waits until any predicate holds;@cb.event+cb.scheduleruns one-off timed actions.@cb.process(priority=...)orders simultaneous events.Store[M]passes typed model handles between processes.Sweep
Paramvalues in one experiment; compare structural variants with separate experiments that share a seed. Both are paired comparisons.
Next, in 5. An assembly line, we push parts through a production line and learn to look inside a run with captured histories and diagrams.