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:
importasyncioimportqueueimportshutilimporttempfilefrompathlibimportPathclassCapture:"""An egress that keeps every event it receives."""def__init__(self):self.events=[]asyncdefrun(self,egress_queue):try:whileTrue:try:batch=egress_queue.get_nowait()self.events+=[rforrinbatchifr["stream_type"]=="event"]exceptqueue.Empty:awaitasyncio.sleep(0.005)exceptasyncio.CancelledError:passdef_events(task:str,capture:Capture)->list:return[eforeincapture.eventsife["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 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.<branch>.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.<branch>.done in a gen: expr field:
simulation:{sim_id:Shop, factor:0}signals:[restocked]arrivals:orders:replay:{path:orders.csv}spawn:orderrestocks:replay:{path:restocks.csv}spawn:restocktasks:order:wait:any:stock:{signal:restocked}limit:{timeout:30}# wait.<branch>.done is true for each branch that was done when the wait endedpayload:event_type:resumeddone:stock:{gen:expr, expr:wait.stock.done}limit:{gen:expr, expr:wait.limit.done}restock:signal:restockedpayload:{boxes:6}run:{until:60}
first_yaml(gap) replays the order at 0 and the restock at gap from CSV files:
defrun_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"}. """withtempfile.TemporaryDirectory()astmp:folder=Path(tmp)shutil.copy(blueprint,folder)forfile,rowsinarrivals.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.untilreturncapturedeffirst_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"]deftwo_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"]defall_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"))foreincapture.eventsife["task"]in("order","inspect")ande["value"].get("status")!="started"]defsuspend_and_resume_yaml(blueprint="wait_suspend.yaml")->list:capture=run_blueprint(Path(blueprint),{})return[(e["sim_ts"],e["value"]["by"])forein_events("hold",capture)ife["value"].get("event_type")=="released"]defeach_of_three_yaml(blueprint="wait_each.yaml")->tuple:packed=_events("order",run_blueprint(Path(blueprint),{}))[-1]returnpacked["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=[eforein_events("order",capture)if"granted"ine["value"]]late=[eforein_events("late_order",capture)if"event_type"ine["value"]]return(packed[0]["sim_ts"],packed[0]["value"]["granted"],late[0]["sim_ts"]iflateelseNone,)defpool_of_requests_yaml(blueprint="wait_pool.yaml")->tuple:return_pool_result(run_blueprint(Path(blueprint),{}))
def_shop():app=SimulationContext("Shop",factor=0)capture=Capture()app.add_egress(capture)returnapp,capturedeffirst(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}}})deforder(task_id,wait):# `wait` holds each branch's done, ok and valueseen.update({name:branch["done"]forname,branchinwait.items()})return{"event_type":"resumed"}@app.task(signal="restocked")defrestock(task_id):return{"boxes":6}defscript(context):context.spawn(order(0))yieldcontext.env.timeout(gap)context.spawn(restock(0))app.add_process(script)app.run(until=60)returnseen
deffirst(gap:float)->dict:"""Which branches were done when the order's wait ended."""env=DynamicRealtimeEnvironment(factor=0)restocked=Signal(env,"restocked")seen={}deforder():branches={"stock":restocked.wait(),"limit":env.timeout(30)}done=yieldenv.any_of(list(branches.values()))# The value of AnyOf holds the events that had happenedseen.update({name:eventindoneforname,eventinbranches.items()})defrestock():yieldenv.timeout(gap)restocked.fire({"boxes":6})env.process(order())env.process(restock())env.run(until=60)env.teardown()returnseen
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 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:
deftwo_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"}}})deforder(task_id,wait):seen.update({name:branch["done"]forname,branchinwait.items()})return{"event_type":"resumed"}@app.task(signal="boxes")defdeliver_boxes(task_id):return{"item":"boxes"}@app.task(signal="labels")defdeliver_labels(task_id):return{"item":"labels"}defscript(context):context.spawn(order(0))yieldcontext.env.timeout(5)context.spawn(deliver_boxes(0))context.spawn(deliver_labels(0))app.add_process(script)app.run(until=10)returnseen
deftwo_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={}deforder():branches={"boxes":boxes.wait(),"labels":labels.wait()}done=yieldenv.any_of(list(branches.values()))seen.update({name:eventindoneforname,eventinbranches.items()})defdeliver():yieldenv.timeout(5)boxes.fire({"item":"boxes"})labels.fire({"item":"labels"})env.process(order())env.process(deliver())env.run(until=10)env.teardown()returnseen
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:
simulation:{sim_id:Shop, factor:0}signals:[restocked]services:inspecting:{dist:constant, value:4}arrivals:orders:replay:{path:orders.csv}spawn:orderrestocks:replay:{path:restocks.csv}spawn:restocktasks:order:wait:all:stock:{signal:restocked}check:{task:inspect}payload:{event_type:resumed}inspect:service:inspectingpayload:{event_type:inspected}restock:signal:restockedfail:attr.broken == 1# from the broken column of restocks.csvfail_reason:broken deliverypayload:{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.
defall_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"}}})deforder(task_id):return{"event_type":"resumed"}@app.task(service_id="inspecting")definspect(task_id):return{"event_type":"inspected"}@app.task(signal="restocked",fail="attr.broken == 1",fail_reason="broken delivery")defrestock(task_id):return{"boxes":6}defscript(context):context.spawn(order(0))yieldcontext.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"))foreincapture.eventsife["task"]in("order","inspect")ande["value"].get("status")!="started"]
defall_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=[]definspect():yieldenv.timeout(4)seen.append((env.now,"inspect","finished"))deforder():seen.append((env.now,"order","queued"))try:yieldenv.all_of([restocked.wait(),env.process(inspect())])exceptSignalFailed:# A failed branch fails the AllOf at once; the inspection runs onseen.append((env.now,"order","failed"))defrestock():yieldenv.timeout(2)restocked.fail("broken delivery")env.process(order())env.process(restock())env.run(until=10)env.teardown()returnseen
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 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:
# Go on once the invoice is printed and either two boxes are taken or 5 seconds passwait: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.<name> 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:
# Go on once two of the three checks have answeredwait:at_least:2of: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: <expression>, 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.<branch>.done, .ok and .value of each branch, and done_count. A branch that fails fails the wait, and an empty of succeeds at once.
# Go on when the expression holds, read each time a branch is processedwait:when:done_count >= 2 and wait.stock.doneof: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.<branch>.value is the request.
A get takes an item, and wait.<branch>.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:
# 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 packingwait:any:unit:request:{resource:packers, priority:1, preempt:false}limit:{timeout:30 s}
@app.task(wait=...) takes the same mapping as a dict.
# 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).
# Put the closed order's payload on the shelf, waiting while the shelf is fullwait: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: 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.
Here three orders park, at 1, 2 and 3 seconds, and a truck at 5 seconds wakes the two oldest:
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 resumehold:wait:{suspend:true}payload:event_type:releasedby:{gen:expr, expr:wait.suspend.value}# Wakes the two oldest parked orders; the third stays parkedunload:resume:{task:hold, limit:2, value:truck-1}payload:{event_type:unloaded}run:{until:10}
defsuspend_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})defhold(task_id,wait):# wait["suspend"]["value"] is the value of the resume that woke the orderwoken.append((float(app.env.now),wait["suspend"]["value"]))return{"event_type":"released"}@app.task(resume={"task":"hold","limit":2,"value":"truck-1"})defunload(task_id):return{"event_type":"unloaded"}defscript(context):fornumberinrange(3):yieldcontext.env.timeout(1)context.spawn(hold(number))yieldcontext.env.timeout(2)context.spawn(unload(0))app.add_process(script)app.run(until=10)returnwoken
defsuspend_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 firstwoken=[]defhold():wake=env.event()parked.append(wake)value=yieldwake# the value of the succeed() that wakes itwoken.append((env.now,value))deforders():for_inrange(3):yieldenv.timeout(1)env.process(hold())deftruck():yieldenv.timeout(5)forwakeinparked[:2]:# the oldest firstwake.succeed("truck-1")env.process(orders())env.process(truck())env.run(until=10)env.teardown()returnwoken
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.
Here an order packs three boxes of 2, 5 and 9 seconds, and goes on when two are packed:
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 elementgroup:{at_least:2}# done when two branches arebranch:# each.value is the elementtimeout:{after:each.value}payload:event_type:packedflags:{gen:expr, expr:wait.boxes.flags}# which branches were donerun:{until:30}
defeach_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"}},}}})deforder(task_id,wait):seen["done"]=(float(app.env.now),wait["boxes"]["flags"])return{"event_type":"packed"}defscript(context):context.spawn(order(0))yieldcontext.env.timeout(0)app.add_process(script)app.run(until=30)returnseen["done"]
fromsimpy.eventsimportConditiondefeach_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={}deforder():boxes=[env.timeout(seconds)forsecondsin(2,5,9)]done=yieldCondition(env,lambdaevents,count:count>=2,boxes)seen["done"]=(env.now,[boxindoneforboxinboxes])env.process(order())env.run(until=30)env.teardown()returnseen["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: <expression>}, 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:
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 oncepool:each:3branch:{request:packers}wait:{handle:pool, index:0}# the first of themservice_time:2cancel:pool# the requests not yet granted: the second and the thirdrelease:{handle:pool, index:0}# the unit of the first, when the task endspayload:event_type:packedgranted:{gen:expr, expr:handle.pool.flags}late_order:resource:packersservice_time:1payload:{event_type:late_packed}run:{until:30}
defpool_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."""fromdesflow.valuesimportTemplateapp,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 thirdrelease={"handle":"pool","index":0},)deforder(task_id):returnpacked@app.task(resource_id="packers",service_time=1)deflate_order(task_id):return{"event_type":"late_packed"}defscript(context):context.spawn(order(0))yieldcontext.env.timeout(1)context.spawn(late_order(0))app.add_process(script)app.run(until=30)return_pool_result(capture)
fromsimpyimportResourcedefpool_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}deforder():pool=[packers.request()for_inrange(3)]yieldpool[0]yieldenv.timeout(2)# the serviceforrequestinpool[1:]:request.cancel()# a request not granted leaves the linepackers.release(pool[0])seen["done"]=(env.now,[request.triggeredforrequestinpool])deflate_order():yieldenv.timeout(1)withpackers.request()asrequest:yieldrequestyieldenv.timeout(1)seen["late"]=env.nowenv.process(order())env.process(late_order())env.run(until=30)env.teardown()finished,granted=seen["done"]returnfinished,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:
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::
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:
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())
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. 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:
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 shows how to download and run it.
# 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.yamlsimulation:{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 firstorder:wait:any:stock:{signal:restocked}limit:{timeout:30}payload:{event_type:waited}next:when:-{condition:wait.stock.done, task:pack}default:refundpack: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 restockedrestock:wait:all:delivery:{timeout:10}count:{task:count_stock}signal:restockedpayload:{event_type:restocked}count_stock:service:countingpayload:{event_type:counted}stats:basicrun:{until:10 min}
"""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 ispacked after a restock or refunded at the limit. A restock waits for both itsdelivery and a stock count, then fires the signal the orders wait for. The scriptruns 10 minutes at factor 0 and prints how many orders were packed and refunded, andthe times of the restocks: python wait_for_one_or_all_example.py."""fromdesflowimportSimulationContextapp=(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",},)deforder(task_id):return{"event_type":"waited"}@app.task()defpack(task_id):return{"event_type":"packed"}@app.task()defrefund(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",)defrestock(task_id):restocked_at.append(app.env.now)return{"event_type":"restocked"}@app.task(service_id="counting")defcount_stock(task_id):return{"event_type":"counted"}defoutcome()->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"]fortaskin("pack","refund")}return{**counts,"restocked_at":restocked_at}if__name__=="__main__":print(outcome())
"""Wait for one or all, low-level API: a shop where orders wait for a restock or atime limit.The low-level version of wait_for_one_or_all_example.py. Each order waits for thenext restock or 30 seconds, whichever comes first, and is packed after a restock orrefunded at the limit. A restock waits for both its delivery and a stock count, thenfires the signal the orders wait for. The script runs 10 minutes at factor 0 andprints how many orders were packed and refunded, and the times of the restocks:python wait_for_one_or_all_example_low_level.py."""importitertoolsfromdesflowimport(DistributionConfig,DynamicRealtimeEnvironment,Sampler,SimParameter,Signal,)PARAMS=SimParameter(sim_id="Shop",arrival={"orders":DistributionConfig(dist="exponential",rate=0.1)},)defoutcome()->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 firstdeforder():stock=restocked.wait()done=yieldenv.any_of([stock,env.timeout(30)])counts["pack"ifstockindoneelse"refund"]+=1defcount_stock():yieldenv.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 restockeddefrestock():yieldenv.all_of([env.timeout(10),env.process(count_stock())])restocked_at.append(env.now)restocked.fire()deforders(sampler):gap=env.registry.get_config("Shop.arrival.orders")whileTrue:yieldenv.timeout(sampler.sample(gap))env.process(order())defdeliveries():for_initertools.count():yieldenv.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())