Skip to content

How do I route entities by a rule I write in Python?

Chance and conditions cover most routing, but sometimes the rule is code. A LOGIC block calls a class you write and goes down the link it returns. The script sends light parcels one way and heavy ones the other.

import types

from nagasim import build as nb


class ByWeight:
    """Light parcels go down link 0, heavy ones down link 1. The links are numbered in the order
    they are drawn from the LOGIC block."""

    def execute(self, entity, ctx):
        return 0 if entity.weight <= 5 else 1


rules = types.ModuleType("my_rules")           # in a project this is your own module: run(logic=my_rules)
rules.ByWeight = ByWeight

m = nb.Model(time_limit=200)
parcels = m.create(distribution=nb.Constant(value=2))
weigh = m.assign(assignments=[{"target": "entity.weight", "expr": "UNIF(0, 10)"}])
sorter = m.logic("Sorter", logic_class="ByWeight")
parcels >> weigh >> sorter
sorter >> m.dispose("Light lane")
sorter >> m.dispose("Heavy lane")

results = m.run(seed=1, logic=rules)
flow = results["material_flow_summary"]
print(flow[flow["From"] == "Sorter"][["From", "To", "Entities"]].to_string(index=False))

Save it as recipe-custom-routing.py and run it with python. The script seeds itself, so the numbers below are the same on your machine.

  From         To  Entities
Sorter Light lane        49
Sorter Heavy lane        52

How it works

  1. The class needs an execute(self, entity, ctx) method that returns the index of the outgoing link: 0 for the first link drawn, 1 for the second.
  2. You pass the module that holds the class to run(logic=...); only the caller names it, and a model file cannot.
  3. The material_flow_summary frame shows how many parcels took each link.

Elements used

Back to all recipes.