Compare policies with polymorphic functions

Goal: keep a process unchanged while swapping the decision logic inside it, and compare the alternatives fairly in one experiment.

Many studies are about policies: how much to reorder, which job to serve next, where to route a part, when to call in extra staff. The process around the decision stays the same; only the decision changes. Cimba Python expresses this with two features working together:

  • polymorphic functions: the decision is a @cb.function on a policy model, and each policy class overrides it;

  • model sweeps: the policy is a child model, and sweeping that child runs every policy as its own design point, in one experiment.

The complete example is tutorial/policy_comparison.py.

The policy interface

The base class declares the decision and its signature. Every parameter and the return value are annotated:

class Policy(cb.Model):
    """How much to order, given stock on hand and the inventory position."""

    @cb.function
    def order_quantity(self, on_hand: float, position: float) -> float:
        return 0.0

Each policy is a subclass that overrides the function with the same signature, and can have its own parameters:

class MinMax(Policy):
    """When the position falls to the minimum, order up to the maximum."""

    minimum: cb.Param[float] = 40.0
    maximum: cb.Param[float] = 120.0

    @cb.function
    def order_quantity(self, on_hand: float, position: float) -> float:
        if position <= self.minimum:
            return self.maximum - position
        return 0.0
class FixedQuantity(Policy):
    """When the position falls to the reorder point, order a fixed batch."""

    reorder_point: cb.Param[float] = 45.0
    batch: cb.Param[float] = 80.0

    @cb.function
    def order_quantity(self, on_hand: float, position: float) -> float:
        return self.batch if position <= self.reorder_point else 0.0

A policy can also have its own processes. This one reviews on a weekly clock and orders only when a review is due:

class PeriodicReview(Policy):
    """Review once a week (its own process) and order back up to a level."""

    level: cb.Param[float] = 130.0
    period: cb.Param[float] = 7.0
    due: bool = False

    @cb.process
    def clock(self):
        while True:
            cb.hold(self.period)
            self.due = True

    @cb.function
    def order_quantity(self, on_hand: float, position: float) -> float:
        if not self.due:
            return 0.0
        self.due = False
        return max(0.0, self.level - position)

The process that doesn’t change

The store holds its policy as a child model, policy: Policy, so any subclass fits, and it asks the policy what to order. It never mentions a concrete policy:

@cb.process
def trade(self):
    while True:
        cb.hold(1.0)
        demand = self.demand.next()
        sold = min(demand, self.on_hand)            # unmet demand is lost
        self.on_hand -= sold
        self.position -= sold                     # position = on hand + on order
        self.daily_demand.record(demand)
        self.daily_sales.record(sold)
        self.daily_stock.record(self.on_hand)
        quantity = self.policy.order_quantity(self.on_hand, self.position)
        if quantity > 0.0:
            cb.spawn(Delivery, store=self, quantity=quantity)
            self.position += quantity
            self.daily_orders.record(1.0)
        else:
            self.daily_orders.record(0.0)

Calls through a child, a reference or a list use the implementation of the model’s actual class, even though the store’s code only knows Policy. This is dynamic dispatch, as in ordinary Python. It’s implemented with a per-class function table, so the store is compiled once and never recompiled when the policy changes.

One experiment, every policy

Sweep the child. Pass the policy objects to cb.sweep, as separate arguments or as one list:

def policy_study() -> Store:
    """A store whose policy is swept: one design point per policy."""
    store = Store()
    store.policy = cb.sweep(  # pyright: ignore[reportAttributeAccessIssue]
        OrderUpTo(), MinMax(), FixedQuantity(), PeriodicReview())
    return store
def compare_policies(*, replications: int = 50, seed: int = 11):
    store = policy_study()
    results = cb.Experiment(
        store, replications=replications,
        window=cb.Window(warmup=30.0, duration=365.0), seed=seed,
    ).run()
    if results.failed.any():
        raise RuntimeError(f"{results.failed.sum()} policy trials failed")
    return store, results

A swept child model gives one model tree per option. The trials of a design point contain the store and only that point’s policy. The other policies don’t exist there at all, so their processes (like PeriodicReview’s clock) and hooks never run anywhere but in their own design point.

        ---
config:
  layout: elk
---
flowchart LR
  n0["store: Store"]
  n1["store.policy#0: OrderUpTo"]
  n2["store.policy#1: MinMax"]
  n3["store.policy#2: FixedQuantity"]
  n4["store.policy#3: PeriodicReview"]
  n0 -->|"policy (option 0)"| n1
  n0 -->|"policy (option 1)"| n2
  n0 -->|"policy (option 2)"| n3
  n0 -->|"policy (option 3)"| n4
    

In diagrams, the options appear as policy (option i) edges to store.policy#i. Inside a trial, each option is simply store.policy.

$ uv run python tutorial/policy_comparison.py
policy          fill rate  mean stock  orders/wk
OrderUpTo           0.983        42.7       6.98
MinMax              0.897        42.1       0.85
FixedQuantity       0.913        40.9       0.96
PeriodicReview      0.932        52.4       1.00
fill rate, MinMax - OrderUpTo: -0.0864 (95% CI -0.0915 .. -0.0814)
fill rate, FixedQuantity - OrderUpTo: -0.0699 (95% CI -0.0742 .. -0.0656)
fill rate, PeriodicReview - OrderUpTo: -0.0513 (95% CI -0.0550 .. -0.0476)

results.levels(store.policy) returns the policy objects, one per design point. Ordering every day keeps the fill rate at 98.3%, but it costs seven orders a week. The two reorder-point policies order less than once a week at about the same stock, but lose 7–9 points of fill rate. The weekly review orders exactly once a week and sits in between, at the price of more stock. Because all four design points see the same demand and lead times (common random numbers, with one stream per input), compare gives tight, paired intervals.

Reading results per policy

Results for the store cover every design point. Results for a policy object cover only the design points where it was selected. Elsewhere its outputs are nan, because it wasn’t there:

weekly = results.levels(store.policy)[3]
results[weekly].some_output          # values in row 3, nan in rows 0-2

Tuning within a policy

Policy parameters are ordinary Param fields, so they sweep too, and sweeps inside an option cross with the model sweep:

daily, weekly = OrderUpTo(), PeriodicReview()
weekly.level = cb.sweep(110.0, 130.0, 150.0)
store = Store()
store.policy = cb.sweep(daily, weekly)       # 2 x 3 = 6 design points

Sweeps cross, so OrderUpTo also runs once per level value even though that parameter doesn’t affect it. Those three design points repeat the same trials. When that matters, use separate options instead:

lean, generous = MinMax(), MinMax()
generous.minimum = 60.0
store = Store()
store.policy = cb.sweep(OrderUpTo(), lean, generous)

Staffing calendars

When to have how many staff is a policy too. A shift calendar is an ordinary process that holds and calls set_capacity in a cycle:

class Office(cb.Model):
    clerks: cb.Resource = cb.Resource(capacity=0)
    day: cb.Param[int] = 5
    evening: cb.Param[int] = 2
    utilization: cb.Output[float]

    @cb.process(priority=10)                 # before same-time arrivals
    def shifts(self):
        while True:                          # 08-16, 16-20, closed overnight
            self.clerks.set_capacity(self.day)
            cb.hold(8.0)
            self.clerks.set_capacity(self.evening)
            cb.hold(4.0)
            self.clerks.set_capacity(0)      # finish the customer at hand
            cb.hold(12.0)

    @cb.on_end
    def collect(self):
        self.utilization = self.clerks.utilization()

The default mode="finish" lets clerks finish the customer at hand when a shift ends. mode="preempt" sends them home at once: the customers being served see -1 from their hold, keep their remaining work in their own fields, and acquire again. utilization() divides by the capacity that was actually staffed, so closed hours don’t count as idle time.

day and evening are parameters, so they sweep like any other. To compare calendars of different shapes, put the shifts process on a calendar child model with a cb.Ref back to the office, and sweep the child as above.

Any of several roles

A task that either a clerk or a senior can do waits for one unit of either with cb.acquire_any. The request waits in both queues, takes the first unit either grants, and competes first come, first served with work that needs one role in particular:

@cb.process
def customer(self):
    roles = (self.clerks, self.seniors)
    role = cb.acquire_any(roles)       # the clerk if both are free
    cb.hold(self.service.next())
    roles[role].release()

When the roles that can do a task come from data, build one pool per set of roles on the host and acquire from the pool. A list[cb.Ref[cb.Resource]] references resources held elsewhere in the tree, and its length is configuration, so pools of any size share one compiled process:

class Role(cb.Model):
    res: cb.Resource = cb.Resource(capacity=1)

class Pool(cb.Model):
    resources: list[cb.Ref[cb.Resource]]

class Task(cb.Model):
    pool: cb.Ref[Pool]
    service: cb.Param[float] = 4.0

    @cb.process
    def work(self):
        role = cb.acquire_any(self.pool.resources)
        cb.hold(self.service)
        self.pool.resources[role].release()

class Staffing(cb.Model):
    roles: list[Role]
    pools: list[Pool]
    tasks: list[Task]

    def __init__(self, staff: dict[str, int], needs: list[tuple[str, ...]]):
        names = list(staff)
        self.roles = [Role() for _ in names]
        for role, name in zip(self.roles, names):
            role.res.initial_capacity = staff[name]
        pools = {}
        for need in needs:
            if need not in pools:
                pools[need] = Pool()
                pools[need].resources = [self.roles[names.index(n)].res for n in need]
        self.pools = list(pools.values())
        self.tasks = [Task() for _ in needs]
        for task, need in zip(self.tasks, needs):
            task.pool = pools[need]

The members are checked when the experiment is built: each must be a resource of this tree. See References to entities.

Each role keeps its own calendar: a set_capacity that opens a shift grants waiting acquire_any requests like any other. List the role you would rather use first; it only decides between roles that are free at the same moment. For a rule that isn’t “one unit of any”, such as “two clerks or one senior”, wait on a cb.Condition(observe=(self.clerks, self.seniors)) with a predicate for the rule, then acquire what it found (see Observing entities).

Rules for @cb.function

  • Explicit. Only methods decorated with @cb.function can be called from compiled code. Calling an undecorated method gives a compile error that says so.

  • Annotated. Parameters are float, int, bool or a model class. The return type is one of those or None. Defaults are allowed for scalar parameters. Arguments are passed by position.

  • Same signature when overriding, and the override must also carry @cb.function. Both are checked when the class is first used.

  • Can do anything a process can: read and write fields, use entities and inputs, call other functions (recursion works), spawn models, and even block with cb.hold or get. Don’t block inside a function called from a predicate or event.

  • Plain Python on the host. OrderUpTo().order_quantity(0.0, 40.0) runs as a normal method, which is handy for unit-testing policy logic.

  • Names reserved by cimba.Model (such as describe) can’t be used.

Rules for sweeping a model

  • Sweep a child field (policy: Policy) with model objects of that type. Each option gets its own model tree, and each trial contains only its design point’s option.

  • Options must not be used anywhere else in the tree; a reference into an option from outside would dangle in the other trees, and cb.Experiment(...) rejects it, naming the design point. Link such a reference to the child instead, policies, targets = cb.sweeps([a, b], [a.node, b.node]), so it follows the selected option. An option may reference the rest of the model, for example a policy with a store: cb.Ref["Store"] back-reference.

  • Classes are compiled once, however many options and design points there are. results.meta.variants reports how many model trees were run.

  • The model sweep crosses with every other sweep, including sweeps of parameters inside the options.