Modeling API
Everything on this page is imported from cimba, conventionally as
import cimba as cb. Calls marked compiled work only inside compiled
model methods; on the host they raise cimba.modeling.NotInCompiledCode.
Model
- class cimba.Model
Base class of every model. Subclass it and declare fields with annotations and behavior with decorated methods. Constructing an instance has no side effects: nothing is compiled or run until an experiment runs.
Assigning attributes is validated: a
sweep()is accepted only byParam,Input,Seriesand child-model fields. A field typed with anenum.IntEnumaccepts members, or anintthat is one of the enum’s values (stored as that member); anything else raisesModelDefinitionError.Input/Seriesfields accept sources or sweeps of sources; optional inputs also acceptNone. A child sweep must contain models of the field’s type.- describe()
Return a tuple with one dict per model instance in the tree:
{"label": path, "class": name, "fields": ((name, kind), ...)}.
- attached(owner, field)
Host-only hook, called after this model is assigned to an owned child field or list. Every child sweep option receives the hook.
owneris the parent model,fieldits field name. The default does nothing; override it to bind aRefto the owner. Reference assignments do not call it. Class-default children are copied and attached once per owner during assembly. Reassign a list to attach newly added children.
Field types
A plain annotated float, int, bool or enum.IntEnum
(on_hand: float = 0.0) is a per-trial value: it starts at its value in every trial and compiled code
may change it. A static model needs a value, on the class or the instance.
The wrappers below give a field a role on top of that.
- class cimba.Param[T]
A trial-constant value of type
float,int,boolor anenum.IntEnum. It can be set on the class, the instance, or as a sweep. An enum value is stored natively as the member’s integer value and reads as the member in compiled code and on the host. Decisions requirefloat,intorbool.
- class cimba.Output[T]
A per-trial value that is also a result: its value at the end of the trial is collected as
Samples. It starts each trial at its default, if it has one (revenue: cb.Output[float] = 0.0), otherwise atnan(float) or0(int,bool,enum.IntEnum), so processes can count into it directly. An enum output is collected as its integer values.
- class cimba.Ref[M]
A reference to another model instance of class
M(or a subclass). Writecb.Ref[M] | Nonefor an optional reference. Forward references by string are allowed:cb.Ref["Harbor"].Compiled:
model.field = otherpoints it at another model of classMor a subclass, static or spawned; another class is a compile error. An optional reference may be assignedNone. An optional value assigned to a required reference fails the trial if it isNone, as does using aNonereference as a model.Mmay also be an entity class:cb.Ref[cb.Resource],cb.Ref[cb.Store[int]]and so on for every entity kind, andlist[cb.Ref[cb.Resource]]for a list. Assign it an entity that a model of the same tree holds (pool.resources = [role.res for role in roles]). When the experiment is built, a value that is not such an entity, an entity of another tree (or of a swept option the tree doesn’t contain), or one held by a field of another type (aStore[float]for acb.Ref[cb.Store[int]]) raisesModelDefinitionErrornaming the field; the items of an entity list can’t beNone.Compiled: a referenced entity is the entity itself: all its methods, indexing and
len()of a list, with bounds checks as for any list. It can be assigned another entity of its type, and passed tospawn().
- class cimba.Array(contents=0)
A per-instance table of
int,floatorbool, declared asx: cb.Array[int].contentsis a nonnegative length (that many zeros, orFalse) or a list of initial values. Assign it as a class default or on the host; it may be asweep()of arrays. A spawned model takes anintlength as its spawn argument, or uses the class default.Compiled:
a[i],a[i] = v,a[i] += v,len(a)andfor x in a. An index outside0 .. len(a) - 1fails the trial. A released spawned model’s arrays are freed: their length is0. Arrays are not results.
- class cimba.Input[T]
A sequence input of
float,intorbool. Bind a source on the class (default) or the instance.Input[T] | Noneallows no binding:remaining()is zero, whilenext()fails the trial.- next()
Compiled. Return the next value and advance the cursor. If the source is exhausted, the exhaustion policy applies.
- remaining()
Compiled. Values left in a finite source;
-1for a distribution.
- class cimba.Series(*, step, origin=0.0)
A time-indexed input. Declare it as
x: cb.Series[float] = cb.Series(step=1.0, origin=0.0);stepmust be positive. Time t maps to bucketfloor((t - origin) / step).- now()
Compiled. The value of the bucket containing the current time.
- at(time)
Compiled. The value of the bucket containing
time(not beforeorigin).
Other annotations: a model class (child; it may be assigned a
sweep() of model objects, giving one model tree per option),
list[M] (owned children),
and list[cb.Ref[M]] (references, items may be None; for an entity
class M, entity references, items may not be None). Unannotated
attributes are host-only.
Entities
Entity methods are compiled, except capture() and the constructors.
- class cimba.Container(initial=0)
A counted level with integer amounts. Each trial starts with
initialunits (a nonnegative integer).- put(amount)
- get(amount)
Add or remove
amountunits.gettakes what is present and blocks until the rest arrives. Waiting calls are served by process priority, then first come, first served, but agetthat has taken part of its amount rejoins the line behind waiting calls of equal priority each time it waits again.
- level()
- mean_level()
- max_level()
Current level; time-weighted mean and maximum over the measurement window.
Amounts must be
int; afloatamount is a compile-time error.
- class cimba.FractionalContainer(initial=0.0, *, capacity=inf, decimals=6)
A level with
floatamounts, kept in fixed point withdecimalsdecimal places (anintfrom 0 to 12). Each trial starts withinitial, a finite nonnegative number no greater thancapacity.- put(amount) float
- get(amount) float
Add or remove
amount, rounded half away from zero todecimalsplaces.putfills tocapacityand blocks until there is room for the rest;gettakes what is present and blocks until the rest arrives. Both return the amount moved: the roundedamount, or less if the wait was interrupted. Amounts must be finite and nonnegative, and an unlimited level must stay below 264 quanta.
- round(amount) float
amount, of either sign, rounded half away from zero todecimalsplaces asputandgetround it. Round an amount computed outside the level – a sum, a ratio, a share – so it compares exactly withlevel():round(0.1 + 0.2) == 0.3.
- level()
- mean_level()
- max_level()
Current level; time-weighted mean and maximum over the measurement window.
- class cimba.Store(*, capacity=1_000_000_000)
A FIFO store of values, declared
Store[int],Store[float]orStore[M]for a model classM.- put(value)
Append
value; blocks while the store is full. ForStore[M],valuemust be a model of classM(checked at compile time).
- get()
Remove and return the oldest item; blocks while empty.
- length()
Number of items (model-valued stores).
- capture()
Host. Keep the length history.
- class cimba.PriorityStore(*, capacity=1_000_000_000)
A store ordered by integer priority, higher first, FIFO among equals.
- put(value, priority=0)
- get()
- length()
- enqueue(value, priority=0)
Insert and return a ticket (model-valued stores).
- position(ticket)
Number of items ahead of the ticket.
- cancel(ticket)
Remove the ticketed item;
Falseif it was already taken.
- class cimba.Resource(*, capacity=1)
A pool of identical units.
capacityis the number each trial starts with, a nonnegativeint(zero is a closed pool). On the host it is theinitial_capacityattribute; model code reads the current capacity withcapacity()and changes it withset_capacity().- acquire(amount=1, priority=None)
Take
amountunits, waiting for any that aren’t free. Returns a signal:0once all are held. If the wait is interrupted, the call returns the signal and the process holds what it held before the call.Waiting requests are served by request priority, higher first, and first come, first served among equal priorities. Only the request at the front is served: one that can’t be fully served yet keeps the units it has taken so far and blocks the requests behind it, even if they would fit. It keeps its place in line each time it waits again, so a later request of equal priority is never served first.
priority=Noneranks the request at the process priority and follows it:Process.priority_set()moves the waiting request and the units it holds. Anintranks the request at that value instead, andpriority_setdoesn’t move it. Either way, the process priority still orders the process’s events, including its wakeup when the request is granted, so a high request priority gets a process to the front of the queue without making it run before other processes at the same instant.A process’s units in one resource are one holding, ranked at the priority of its latest
acquireorpreemptcall. A call that is interrupted gives the holding its previous priority back.
- preempt(amount=1, priority=None)
As
acquire(), but first takes units from holders whose holding priority is strictly lower than the request priority: the lowest first and, among equals, the one whose holding started most recently. A preempted holder loses all its units in this resource and sees signal-1. If that is still not enough, the request waits in line for the rest. Returns a signal.
- release(amount=1)
- available()
Free units: the capacity minus the units in use, or
0while the units in use are at or above the capacity.
- capacity()
The current capacity.
- set_capacity(n, *, mode='finish')
Change the capacity to
n, a nonnegativeint; a negativenfails the trial. Setting the current capacity again does nothing. It never waits, so it works in processes, functions and hooks.Raising it grants waiting requests at once, in queue order. Lowering it depends on
mode, a string literal resolved when the model compiles:"finish": holders keep their units, so the units in use may stay abovenfor a while. Nothing is granted until they drop belown, andavailable()is0meanwhile."preempt": holdings are taken in thepreempt()victim order, lowest holding priority first, the most recent among equals, until the units in use are at mostn. Each victim loses all its units in this resource and sees signal-1, waking at its own process priority. Room left belowngoes to waiting requests. The calling process is never its own victim.
A request larger than the current capacity waits until the capacity rises enough.
- mean_in_use()
Time-weighted mean units in use over the window.
- mean_capacity()
Time-weighted mean capacity over the window, sampled with the in-use history.
- utilization()
mean_in_use() / mean_capacity(): the time-weighted units in use over the time-weighted capacity, both over the window. It can exceed1while"finish"lets holders run past a lowered capacity, and it isnanwhen the window offered no capacity.
- capture()
Host. Keep the in-use history.
- class cimba.Condition(*, observe=())
A wait for an arbitrary predicate over model state.
observeis aResource,Store,PriorityStore,ContainerorFractionalContainer, or a tuple of them. Every change to an observed entity signals the condition, as ifsignal()were called right after it: a release, grant or capacity change of a resource, a put or get of a store or container. Model code then needs nosignal()of its own for those changes.Observation is structure, fixed for an experiment. Observed entities must belong to the same model tree; the experiment checks this when it is set up and raises
ModelDefinitionErrorotherwise. A condition declared as a class default can observe entities declared before it in the same class body. Every model instance gets its own copy of the class-default entities, observing each other’s copies.- observe(*entities) Condition
Host. Also observe
entities. Use it for entities that don’t exist when the condition is created, such as an owner’s inModel.attached(). Returns the condition.
- wait_until(predicate, timeout=math.inf) bool
Return immediately if
predicate(a@predicatemethod, passed uncalled) holds; otherwise wait until it holds after a signal, a timeout expires, or the process is interrupted. Return whether it holds when the wait ends.timeoutis nonnegative simulation time: infinity means no deadline and zero polls without blocking. The wait cancels only its own timer before returning.
- signal()
Re-evaluate waiting processes’ predicates and wake those that hold.
Decorators
- @cimba.process
- @cimba.process(*, copies=1, priority=0)
Run the method as a process of every instance:
copiesindependent coroutines, with schedulingpriority. Static processes start at time 0; processes of spawned models start at the spawn time.
- @cimba.on_start
Run once per instance before processes start (static models: bottom-up; spawned models: at spawn).
- @cimba.on_end
Run once per instance after the event loop (static models bottom-up, then live spawned models).
- @cimba.predicate
A method returning
bool, forCondition.wait_until().
- @cimba.event
A method run at a time set with
schedule(). It must not block.
- @cimba.function
A method callable from compiled code as
model.name(args). Every parameter is annotatedfloat,int,bool, anenum.IntEnumor a model class, and the return type is one of those orNone. An enum parameter takes members of that enum only. Scalar parameters may have defaults; arguments are positional. Subclasses may override it with the same signature (and the decorator). Calls dispatch on the model’s actual class, so a base-typed reference or list item runs its subclass’s override. Functions may block. On the host it is an ordinary method. The name must not be a field name or a name reserved byModel.
Verbs
All verbs are compiled.
- cimba.hold(duration)
Suspend the calling process for
durationtime units. Returns a signal.
- cimba.acquire_any(resources, priority=None) int
Take one unit from whichever of
resourcesgrants first and return its index inresources.resourcesis eithera nonempty tuple of
Resourceentities written in model code, such as(self.clerks, self.seniors)or(self.desk.clerks, self.back.clerks), ora
list[cb.Ref[cb.Resource]]field, such asself.pool.resources, whose members and length are configuration (seeRef). Its length is read when the call runs; an empty list fails the trial.
Anything else is a compile error. Both forms behave the same way. Listing a resource twice is allowed and returns its first index.
If any of them has a free unit, the call takes it at once from the first listed one that has.
Otherwise the request waits in every resource’s queue at the place a
Resource.acquire()made now would get there: same request priority, same arrival time. Each resource serves it in turn with its direct acquirers, by priority and then first come, first served.The first resource to grant serves it. The request leaves every other queue at that moment, so two resources never both grant it.
priorityworks as forResource.acquire():Noneranks the request at the process priority in every queue and followsProcess.priority_set(); anintfixes it. The unit is an ordinary holding of the resource that granted it: release it with that resource’srelease(), read it withheld(), and apreempt()can take it.If the wait ends otherwise, the call returns the negative signal and leaves no request behind in any queue:
-1when the process is preempted from another resource,-2(or another code) when interrupted. A process timer set withProcess.timer_set()bounds the wait; the call then returns the timer’s signal. Raising a resource’s capacity withset_capacity()can grant a waitingacquire_any; a resource without room never does.It takes one unit, never more: grabbing parts of an amount from several pools has no single fair answer. For anything other than “one unit of any of these”, wait on a
Conditionthat observes the resources.
- cimba.now()
Current simulated time.
- cimba.suspend()
Suspend until resumed, interrupted or woken by a timer. Returns the signal.
- cimba.spawn(ModelClass, **fields)
Create a dynamic model instance, set its fields, run its
on_starthooks, schedule its processes, and return a handle to it. Fields without a default must be supplied; input fields take an input of the caller. Enum fields take members of their enum. An array field takes anintlength (a zeroed array; a negative length fails the trial) or uses the class default. Optional inputs may be omitted or passed asNoneto bind an empty source.
- cimba.release(model)
Stop this model’s processes, including copies and pending starts. Releasing the caller’s own model ends the calling process. Static tree models keep their record, entities, children and
on_endhooks; spawned models are retired and skip theiron_endhooks, and their arrays are freed. Records are reclaimed at trial end, so references to them stay valid. Children continue independently. Releasing the same instance twice fails the trial.
- cimba.is_dynamic(model)
Return
Trueif this instance was created byspawn(), orFalsefor a static model in the configured tree. RemainsTrueafterrelease(): this reports creation mode, not whether the model is still active. Accepts model instances only.
- cimba.schedule(event, delay, priority=0)
Run the
@eventmethodeventafterdelay(≥ 0). Returns aScheduled.
- cimba.end_trial()
Stop the trial now: clear pending events and end the caller.
on_endhooks run and the trial succeeds.
- cimba.log(flags, message, value=None)
Write
message(a string literal) and an optional number to the engine log if a category inflagsis enabled.
Handles
- class cimba.Process(pointer)
A handle to a process.
cb.Process(pointer)rebuilds a handle from its integerpointerattribute.- pointer
- status()
0initialized,1running,2finished.
- priority_set(priority)
- interrupt(signal=-1, priority=0)
Wake the process from its current blocking call, which returns
signal. Use-2for “interrupted” or a positive custom code.
- resume(signal=0)
- timer_set(delay, signal)
Wake the process with
signalafterdelayunless it wakes first.
- timers_clear()
- class cimba.Scheduled
Returned by
schedule().- pending()
- cancel()
Cancel if pending; returns whether it was cancelled.
Engine utilities (host)
- cimba.engine_version()
Version string of the bundled Cimba engine.
- cimba.set_engine_log_level(flags)
Enable the log categories in the 32-bit mask
flags(0disables all) for subsequent runs.
- cimba.__version__
The Cimba Python version.