All articles →

100 Exercises / Simulation / Simulation 100 Exercises

Introduction to Agent-Based Simulation in Manufacturing | 10 Practical ABM Practices to Learn with Python

Explore worker and AGV behavior with Python agent models. Compare congestion, ordering rules and learning while checking model assumptions.

Deciphering the Manufacturing Floor Through the ‘Movement of Individuals’: 10 Agent-Based Simulation Practices

Exercises No.051–No.060 model equipment, workers, transport vehicles and business partners as agents. Using fictional data and Python, we examine how individual rules affect congestion, delivery times, inventory, profit and the spread of improvement practices.

This article adapts notebooks used in corporate training by Surikobo or its representative, Hiroshi Wayama, with permission from the client companies. All data listed is fictional and has no relation whatsoever to real companies, factories, or figures.

Introduction: Practical Challenges in Manufacturing Covered in This Article

The target is a fictional factory that assembles a wide variety of parts. On site, there are workers with different skills, multiple AGVs, and business partners with varying delivery schedules and supply stability. The decisions we want to consider are: (1) safe flow lines, (2) transport rules, (3) supplier diversification, (4) establishment of improvement behaviors, and (5) introduction of autonomous control.

Common situations on site

Even if the monthly average occupancy rate is reasonable, the aisles may become congested only after breaks. Even with order volumes that meet average demand, a single delay by one company can cause a line stoppage. Also, even when notifying standard tasks, the speed of penetration varies depending on the consultation relationship on site. If individual differences and interactions are eliminated and aggregated, these phenomena cannot be explained.

Why is this issue so difficult to judge?

Let si(t)s_i(t) be the state of agent ii, ai(t)a_i(t) its action and Ni(t)N_i(t) its neighborhood. A conceptual update is

si(t+1)=fi(si(t),ai(t),{sj(t):j∈Ni(t)},εi(t)).\begin{aligned} s_i(t+1)=f_i\bigl(&s_i(t),a_i(t),\\ &\{s_j(t):j\in N_i(t)\},\varepsilon_i(t)\bigr). \end{aligned}

The overall KPI is K(t)=g(s1(t),…,sn(t))K(t)=g(s_1(t),\ldots,s_n(t)). Nonlinear rules and changing neighborhoods can make a single average agent a poor substitute for individual agents. Compare alternative assumptions and check which interactions materially change the result.

Exercises covered in this article

No.ThemeJudgment in the manufacturing industry
051What is ABM?Distinguishing between aggregation models and individual models
052Agent DesignDefinition of State, Behavior, and Rules
053CrowdEvacuation and Passageway Congestion Evaluation
054traffic flowAGV Density and Transport Capacity
055MarketImpact of Price, Quality, and Delivery Times on orders
056Infectious diseasesAbsence risk through contact
057supply chainOrder chains and bullwhips
058OrganizationPromotion of Improvement Behaviors
059Integration with Reinforcement LearningLearning Transport Rules by Condition
060Getting Started with MesaStandard Form of Model Implementation

Preparing the Python environment

The random number generator is unified to default_rng, and each experiment explicitly specifies the seed. Graphs are paired with comparable units and axes.

Run cells in order. [IN: n] marks an input and [OUT: n] its output; cells with no displayed result have no output label. Expand the setup panels to see longer code. Reproduce results by initializing the generator and running the same calls in the same order in the same library environment. Version numbers in outputs describe the recorded run. The examples also use IPython display and japanize-matplotlib for Japanese labels where present.

Setup code: Environment and random generator (expand)
[IN: 1]
import sys
from IPython.display import display
import numpy as np
import pandas as pd
import matplotlib
import matplotlib.pyplot as plt
from dataclasses import dataclass

import japanize_matplotlib

pd.set_option("display.precision", 2)
print(f"Python {sys.version.split()[0]}")
print(
    f"numpy {np.__version__} / pandas {pd.__version__} / matplotlib {matplotlib.__version__}"
)
[OUT: 1]
Python 3.14.4
numpy 2.5.1 / pandas 3.0.3 / matplotlib 3.11.0

Creation of Fictional Data

Assign 30 workers skills, walking speed, readiness to improve, and assigned teams. This is not an individual evaluation, but an example of input for a model with individual differences. In practice, labor and management must agree on anonymization, granularity, and purpose of use.

Setup code: Fictional data and shared functions (expand)
[IN: 2]
rng = np.random.default_rng(1606)
n_workers = 30
workers = pd.DataFrame(
    {
        "worker_id": [f"W{i:02d}" for i in range(1, n_workers + 1)],
        "team": rng.choice(list("ABC"), n_workers),
        "skill": np.clip(rng.normal(0.75, 0.12, n_workers), 0.4, 1.0),
        "walk_speed_m_s": np.clip(rng.normal(1.25, 0.15, n_workers), 0.8, 1.6),
        "improvement_receptivity": rng.beta(3, 2, n_workers),
    }
)
workers.head()
[OUT: 2]
worker_id team skill walk_speed_m_s improvement_receptivity
0 W01 B 0.81 1.48 0.82
1 W02 A 0.64 1.32 0.79
2 W03 B 0.78 0.81 0.49
3 W04 B 0.73 1.46 0.53
4 W05 C 0.45 1.33 0.74

No.051: What is ABM?

Practical context

Leaving heterogeneity that disappears in aggregate data, we observe the process by which overall KPIs emerge from local rules. In factories, even with the same average processing capacity, stagnation can vary depending on skill imbalances and supportive behaviors.

Modeling approach

For each job, independently draw a worker’s skill and use it as a Bernoulli success probability. Because the worker is redrawn for every job, the marginal success probability is the mean skill pˉ\bar p. Daily output therefore has the same Binomial(120,pˉ)\mathrm{Binomial}(120,\bar p) distribution as the homogeneous model.

Python example

[IN: 3]
rng = np.random.default_rng(51)
days, jobs = 500, 120
hetero = np.array(
    [(rng.random(jobs) < rng.choice(workers.skill, jobs)).sum() for _ in range(days)]
)
mean_skill = workers.skill.mean()
homogeneous = rng.binomial(jobs, mean_skill, days)
result_051 = pd.DataFrame(
    {
        "model": ["heterogeneous worker", "average worker"],
        "average number of completed": [hetero.mean(), homogeneous.mean()],
        "5th percentile": [np.quantile(hetero, 0.05), np.quantile(homogeneous, 0.05)],
    }
)
display(result_051.round(1))
plt.figure(figsize=(7, 3.5))
plt.hist(hetero, bins=15, alpha=0.65, label="heterogeneous")
plt.hist(homogeneous, bins=15, alpha=0.55, label="homogeneous")
plt.title("Distribution of daily completed counts")
plt.xlabel("Completed units per day")
plt.ylabel("number of days")
plt.grid(alpha=0.3)
plt.legend()
plt.tight_layout()
plt.show()
[OUT: 3]
model average number of completed 5th percentile
0 heterogeneous worker 83.6 75.0
1 average worker 83.1 75.0

Distribution of daily completed counts

Interpreting the results

The two distributions are identical in theory. Differences in the displayed means or fifth percentiles arise from finite simulation samples. This example does not demonstrate extra risk from heterogeneity. Persistent worker assignments, fatigue or interactions are needed for individual differences to affect the aggregate distribution.

No.052: Agent Design

Practical context

The explainability of a model depends on who can define what to observe and how it operates in business terms. Increasing attributes is not necessarily better; only the differences necessary for decision-making are retained.

Modeling approach

Workers have skill, fatigue and cumulative production (produced). They rest when fatigue exceeds 0.75; otherwise they attempt a job with a fatigue-adjusted success probability. All workers start with zero fatigue, which tends to synchronize their breaks.

Python example

[IN: 4]
@dataclass
class WorkerAgent:
    skill: float
    fatigue: float = 0.0
    produced: int = 0

    def step(self, rng):
        if self.fatigue > 0.75:
            self.fatigue = max(0, self.fatigue - 0.35)
            return "Break"
        success = rng.random() < self.skill * (1 - 0.35 * self.fatigue)
        self.produced += int(success)
        self.fatigue = min(1, self.fatigue + 0.08)
        return "Production"


rng = np.random.default_rng(52)
agents = [WorkerAgent(s) for s in workers.skill[:8]]
records = []
for t in range(40):
    for i, a in enumerate(agents):
        records.append((t, i, a.step(rng), a.fatigue, a.produced))
trace_052 = pd.DataFrame(
    records,
    columns=["point in time", "agent", "action", "fatigue", "cumulative production"],
)
display(trace_052.groupby("action").size().rename("number of times").to_frame())
avg = trace_052.groupby("point in time").fatigue.mean()
plt.figure(figsize=(7, 3.5))
plt.plot(avg.index, avg.values)
plt.title("Average fatigue time transition")
plt.xlabel("point in time")
plt.ylabel("Fatigue level")
plt.grid(alpha=0.3)
plt.tight_layout()
plt.show()
[OUT: 4]
number of times
action
Break 48
Production 272

Average fatigue time transition

Interpreting the results

You can see that the break rule periodically reduces fatigue. In practice, fatigue levels are not arbitrarily estimated; instead, break records, workload, and ergonomic rationales are used, and they are utilized for process design rather than personal monitoring.

No.053: Crowd Simulation

Practical context

During shifts or evacuations, if everyone chooses the shortest route, exits will get congested. Compare peak density with evacuation completion time and use it to make investment decisions regarding aisle width and guidance policies.

Modeling approach

This static model assigns 120 people to exits serving 3 and 2.5 people per minute. Under fixed routing, about 80% choose the first exit. Under adaptive routing, people choose the less-assigned exit with probability 85%; otherwise they follow fixed routing. The model does not simulate travel, physical contact or changing corridor density.

Python example

[IN: 5]
def evacuate(seed, adaptive, n=120):
    rng = np.random.default_rng(seed)
    queues = [0, 0]
    done = []
    for _ in range(n):
        choice = (
            int(np.argmin(queues))
            if adaptive and rng.random() < 0.85
            else int(rng.random() > 0.8)
        )
        queues[choice] += 1
        done.append(queues[choice] / [3.0, 2.5][choice])
    return max(done), max(queues)


rows = []
for policy in [False, True]:
    vals = [evacuate(s, policy) for s in range(300)]
    rows.append(
        [
            "Fixed routing" if not policy else "Adaptive routing",
            np.mean(vals, 0)[0],
            np.quantile(np.array(vals)[:, 0], 0.95),
            np.mean(vals, 0)[1],
        ]
    )
result_053 = pd.DataFrame(
    rows,
    columns=[
        "policy",
        "Average Evacuation Time",
        "95th percentile evacuation time",
        "Maximum people assigned to one exit",
    ],
)
display(result_053.round(1))
plt.figure(figsize=(6, 3.5))
plt.bar(result_053.policy, result_053["95th percentile evacuation time"])
plt.title("Evacuation Times by Guidance Policy")
plt.xlabel("guidance policy")
plt.ylabel("95th percentile evacuation time [minutes]")
plt.grid(axis="y", alpha=0.3)
plt.tight_layout()
plt.show()
[OUT: 5]
policy Average Evacuation Time 95th percentile evacuation time Maximum people assigned to one exit
0 Fixed routing 32.0 34.3 96.0
1 Adaptive routing 23.9 24.0 60.2

Evacuation Times by Guidance Policy

Interpreting the results

A reduction in the 95th percentile of evacuation time can help compare routing policies. However, safety design is not finalized solely for this model; priority is given to regulations, on-site training, and expert reviews.

No.054: Traffic Flow Simulation

Practical context

Increasing the number of AGVs does not necessarily mean the transport volume will increase proportionally. We see the limit effect of adding more vehicles, including speed reductions caused by intersection interference and following.

Modeling approach

Assume nn AGVs on a 100 m route, giving density k=n/100k=n/100 vehicles/m. Add individual noise to v=v0(1−k/kjam)v=v_0(1-k/k_{\mathrm{jam}}) and compute flow as q=kvq=kv. This is a simplified density–speed comparison, not an explicit simulation of vehicle following or collision avoidance.

Python example

[IN: 6]
rng = np.random.default_rng(54)
rows = []
for n in range(2, 31, 2):
    density = n / 100
    speeds = np.clip(rng.normal(1.5 * (1 - density / 0.38), 0.06, n), 0.05, None)
    rows.append((n, speeds.mean(), density * speeds.mean() * 3600))
result_054 = pd.DataFrame(
    rows, columns=["number_of_agvs", "average_speed_m_s", "flow_vehicles_per_hour"]
)
display(result_054.loc[result_054.flow_vehicles_per_hour.nlargest(3).index].round(2))
plt.figure(figsize=(7, 3.5))
plt.plot(result_054.number_of_agvs, result_054.flow_vehicles_per_hour, marker="o")
plt.title("AGV count and transport flow")
plt.xlabel("AGVs (vehicles)")
plt.ylabel("Flow (vehicle passages/hour)")
plt.grid(alpha=0.3)
plt.tight_layout()
plt.show()
[OUT: 6]
number_of_agvs average_speed_m_s flow_vehicles_per_hour
8 18 0.80 515.30
10 22 0.65 515.08
9 20 0.71 511.15

AGV count and transport flow

Interpreting the results

Adding AGVs beyond the peak can lower flow because speed falls. A practical model should also include intersection occupancy, charging, failures and priority rules. Compare route separation as well as fleet size.

No.055: Market Simulation

Practical context

Orders in manufacturing vary not only by price but also by the composition of customer groups that respond to quality and delivery times. Compare on a customer-by-customer basis whether price reductions or quality investments are more effective for gross margins.

Modeling approach

Customer ii chooses our offer when its utility Ui=−wp,ip+wq,iq−wl,il+εiU_i=-w_{p,i}p+w_{q,i}q-w_{l,i}l+\varepsilon_i exceeds the competitor’s utility. Preference weights vary by customer.

Python example

[IN: 7]
rng = np.random.default_rng(55)
n = 1000
w = rng.dirichlet([3, 4, 2], n)
competitor = -w[:, 0] * 100 + w[:, 1] * 82 - w[:, 2] * 8
scenarios = {
    "Current Status": (102, 85, 7, 35),
    "Price reduction": (96, 85, 7, 29),
    "Quality Investment": (102, 92, 6, 33),
}
rows = []
for name, (p, q, l, margin) in scenarios.items():
    utility = -w[:, 0] * p + w[:, 1] * q - w[:, 2] * l + rng.normal(0, 2, n)
    share = (utility > competitor).mean()
    rows.append((name, share, share * n * margin))
result_055 = pd.DataFrame(rows, columns=["policy", "Order rate", "gross_profit_index"])
display(result_055.round(2))
plt.figure(figsize=(6, 3.5))
plt.bar(result_055.policy, result_055.gross_profit_index)
plt.title("Expected gross profit by market strategy")
plt.xlabel("policy")
plt.ylabel("gross_profit_index")
plt.grid(axis="y", alpha=0.3)
plt.tight_layout()
plt.show()
[OUT: 7]
policy Order rate gross_profit_index
0 Current Status 0.66 23240.0
1 Price reduction 0.94 27202.0
2 Quality Investment 0.94 30954.0

Expected gross profit by market strategy

Interpreting the results

The maximum order rate and maximum gross profit may not match. It is important to calibrate the weights by customer segment based on actual performance and confirm that the policy rankings remain robust even when competitive conditions are set.

No.056: Infectious Disease Simulation

Practical context

The spread of infection not only affects employee health but also leads to skill shortages and delayed deliveries due to simultaneous absenteeism. We evaluate the business continuity effects of measures to reduce inter-team contact.

Modeling approach

Agents have susceptible (S), infected (I) or recovered (R) states. For cc contacts with infected agents, daily infection probability is 1−(1−β)c1-(1-\beta)^c. The team-separation scenario approximates reduced mixing by halving every pair’s contact probability from 0.07 to 0.035; it does not construct explicit teams. Cumulative infections include both infected and recovered agents at the end.

Python example

[IN: 8]
def outbreak(seed, split, n=80, days=35):
    rng = np.random.default_rng(seed)
    state = np.zeros(n, int)
    state[0] = 1
    age = np.zeros(n, int)
    peak = 1
    for _ in range(days):
        inf = np.where(state == 1)[0]
        new = []
        for i in np.where(state == 0)[0]:
            contacts = sum((rng.random(len(inf)) < (0.035 if split else 0.07)))
            if rng.random() < 1 - (1 - 0.12) ** contacts:
                new.append(i)
        age[inf] += 1
        state[np.array(new, int)] = 1
        state[(state == 1) & (age >= 6)] = 2
        peak = max(peak, (state == 1).sum())
    return peak, (state != 0).sum()


rows = []
for split in [False, True]:
    a = np.array([outbreak(s, split) for s in range(400)])
    rows.append(
        (
            "usually" if not split else "Reduced contact",
            a[:, 0].mean(),
            np.quantile(a[:, 0], 0.95),
            a[:, 1].mean(),
        )
    )
result_056 = pd.DataFrame(
    rows,
    columns=[
        "working_arrangements",
        "Average peak infection",
        "95th percentile peak infections",
        "Average cumulative infections",
    ],
)
display(result_056.round(1))
plt.figure(figsize=(6, 3.5))
plt.bar(result_056.working_arrangements, result_056["95th percentile peak infections"])
plt.title("Risk of simultaneous infection by work type")
plt.xlabel("working_arrangements")
plt.ylabel("95th percentile peak infections [people]")
plt.grid(axis="y", alpha=0.3)
plt.tight_layout()
plt.show()
[OUT: 8]
working_arrangements Average peak infection 95th percentile peak infections Average cumulative infections
0 usually 52.7 61.0 77.1
1 Reduced contact 20.1 36.0 49.2

Risk of simultaneous infection by work type

Interpreting the results

Team separation can suppress peaks and reduce simultaneous absenteeism for critical skills. This is not a medical forecast. Actual measures follow public guidance and the advice of occupational physicians, limiting the model to considering the staffing capacity of BCPs.

No.057: Supply Chain Simulation

Practical context

When each stage places orders based solely on their own inventory, even small fluctuations in demand are amplified upstream. Identify the trade-off between reducing stockouts and increasing inventory.

Modeling approach

At each of three stages, update net inventory by receipts from the previous order minus current downstream demand, then order up to a target. Negative inventory represents backlog. Replenishment takes one period. Forecasts use downstream orders without sharing and final customer demand with sharing. Replenishment is assumed to arrive in full, so upstream supply shortages and shipment rationing are outside this model.

Python example

[IN: 9]
def chain(seed, shared, T=100):
    rng = np.random.default_rng(seed)
    demand = np.maximum(0, rng.normal(20, 3, T))
    inventory = np.full(3, 40.0)
    pipeline = np.full(3, 20.0)
    forecast = np.full(3, 20.0)
    orders = []

    for customer_demand in demand:
        downstream_demand = customer_demand
        stage_orders = []
        for stage in range(3):
            # Net stock = previous stock + receipts - downstream demand; negatives are backlog.
            inventory[stage] += pipeline[stage] - downstream_demand
            signal = customer_demand if shared else downstream_demand
            forecast[stage] = 0.5 * forecast[stage] + 0.5 * signal
            target_stock = 2 * forecast[stage]
            order = max(0, target_stock - inventory[stage])
            # Assume the entire order arrives in the next period.
            pipeline[stage] = order
            stage_orders.append(order)
            downstream_demand = order
        orders.append(stage_orders)

    return demand, np.asarray(orders)


rows = []
for shared in [False, True]:
    d, o = chain(57, shared)
    rows.append(
        (
            "individual judgment" if not shared else "Demand sharing",
            *(o.var(0) / d.var()),
        )
    )
result_057 = pd.DataFrame(
    rows,
    columns=[
        "Method",
        "Retail bullwhip ratio",
        "Wholesale Bullwhip Ratio",
        "Factory Bullwhip Ratio",
    ],
)
display(result_057.round(2))
plt.figure(figsize=(7, 3.5))
x = np.arange(3)
plt.bar(x - 0.18, result_057.iloc[0, 1:], 0.36, label="individual judgment")
plt.bar(x + 0.18, result_057.iloc[1, 1:], 0.36, label="Demand sharing")
plt.xticks(x, ["Retail", "Wholesale", "Factory"])
plt.title("Amplification of Order Fluctuations")
plt.xlabel("stage")
plt.ylabel("Order variance / demand variance")
plt.grid(axis="y", alpha=0.3)
plt.legend()
plt.tight_layout()
plt.show()
[OUT: 9]
Method Retail bullwhip ratio Wholesale Bullwhip Ratio Factory Bullwhip Ratio
0 individual judgment 4.62 17.61 53.21
1 Demand sharing 4.62 10.18 16.53

Amplification of Order Fluctuations

Interpreting the results

If demand sharing reduces upstream variance, the benefits of EDI and common dashboards can be converted into inventory and capacity planning. Lead time, minimum lot, and supply constraints are added before deciding to change the contract.

No.058: Organizational Simulation

Practical context

Even if the content of improvement measures is correct, they may not take root depending on consultation or managerial intervention. We will consider how to select trainees and assign on-site leaders.

Modeling approach

Build a worker consultation network and calculate the probability of adopting an improvement next week from peer adoption and individual receptivity. Compare training three random workers with training the three most connected workers. Adoption means taking up the improvement, not hiring employees.

Python example

[IN: 10]
rng = np.random.default_rng(58)
n = 30
A = (rng.random((n, n)) < 0.12).astype(int)
A = np.triu(A, 1)
A = A + A.T
degree = A.sum(1)


def diffuse(seed, targeted):
    rng = np.random.default_rng(seed)
    adopted = np.zeros(n, bool)
    initial = np.argsort(degree)[-3:] if targeted else rng.choice(n, 3, False)
    adopted[initial] = True
    hist = [adopted.sum()]
    for _ in range(15):
        ratio = (A @ adopted) / np.maximum(degree, 1)
        p = np.clip(
            0.03 + 0.55 * ratio + workers.improvement_receptivity.to_numpy() * 0.12,
            0,
            1,
        )
        adopted |= rng.random(n) < p
        hist.append(adopted.sum())
    return hist


h_random = np.mean([diffuse(s, False) for s in range(200)], 0)
h_target = np.mean([diffuse(s, True) for s in range(200)], 0)
result_058 = pd.DataFrame(
    {"week": range(16), "random_education": h_random, "centerer_education": h_target}
)
display(result_058.tail().round(1))
plt.figure(figsize=(7, 3.5))
plt.plot(result_058.week, result_058.random_education, label="random_education")
plt.plot(result_058.week, result_058.centerer_education, label="centerer_education")
plt.title("Mean number of improvement adopters")
plt.xlabel("week")
plt.ylabel("Workers adopting the improvement")
plt.grid(alpha=0.3)
plt.legend()
plt.tight_layout()
plt.show()
[OUT: 10]
week random_education centerer_education
11 11 29.9 30.0
12 12 30.0 30.0
13 13 30.0 30.0
14 14 30.0 30.0
15 15 30.0 30.0

Mean number of improvement adopters

Interpreting the results

Training well-connected workers first may spread an improvement faster. Use this result to design support roles, with consent and privacy protection, rather than as an individual performance rating.

No.059: Integration with Reinforcement Learning

Practical context

With fixed rules, it can be difficult to make transport decisions suitable for both normal and busy conditions. It uses the simulator as a safe trial environment to learn state-specific rules.

Modeling approach

States are low, medium and high congestion; actions are the normal route and a detour. Rewards are negative travel time and detour cost. Use the update below:

Q(s,a)←Q(s,a)+α{r+γmax⁡a′Q(s′,a′)+α{−Q(s,a)}.\begin{aligned} Q(s,a)\leftarrow{}&Q(s,a)\\ &+\alpha\bigl\{r+\gamma\max_{a'}Q(s',a')\\ &\phantom{+\alpha\bigl\{}-Q(s,a)\bigr\}. \end{aligned}

Each iteration samples a state and one transition. Actions do not affect transition probabilities here, so the example mainly compares immediate costs by state.

Python example

[IN: 11]
rng = np.random.default_rng(59)
Q = np.zeros((3, 2))
alpha = 0.12
gamma = 0.9
eps = 0.15
rewards = []
for ep in range(3000):
    s = rng.integers(0, 3)
    a = rng.integers(0, 2) if rng.random() < eps else np.argmax(Q[s])
    congestion = [1, 4, 9][s]
    delay = (congestion + rng.normal(0, 0.7)) if a == 0 else (3.2 + rng.normal(0, 0.4))
    r = -delay - (0.8 if a == 1 else 0)
    ns = min(2, max(0, s + rng.choice([-1, 0, 1], p=[0.2, 0.6, 0.2])))
    Q[s, a] += alpha * (r + gamma * Q[ns].max() - Q[s, a])
    rewards.append(r)
policy = pd.DataFrame(
    {
        "congestion condition": ["low", "middle", "high"],
        "Selective behavior": np.where(Q.argmax(1) == 0, "Normal route", "detour"),
        "usuallyQ": Q[:, 0],
        "detourQ": Q[:, 1],
    }
)
display(policy.round(2))
roll = pd.Series(rewards).rolling(150).mean()
plt.figure(figsize=(7, 3.5))
plt.plot(roll)
plt.title("Moving average rewards during learning")
plt.xlabel("Learning iteration")
plt.ylabel("Average Return")
plt.grid(alpha=0.3)
plt.tight_layout()
plt.show()
[OUT: 11]
congestion condition Selective behavior usuallyQ detourQ
0 low Normal route -23.11 -25.20
1 middle detour -32.70 -30.13
2 high detour -39.13 -33.02

Moving average rewards during learning

Interpreting the results

In this run, the learned policy uses the normal route at low congestion and a detour at medium and high congestion. Check these rules offline before deployment, and define action limits, manual overrides and monitoring KPIs.

No.060: Introduction to Mesa

Practical context

To continue using ABM, it is necessary to implement separate agents, models, schedulers, and data collection. Mesa is a Python framework that provides this structure.

Modeling approach

The code does not use Mesa itself. MiniModel groups existing WorkerAgent instances and provides stepping and KPI collection to illustrate ABM structure. Migrating to Mesa requires adapting the code to the installed version’s Agent, Model, AgentSet and DataCollector APIs.

Python example

[IN: 12]
class MiniModel:
    def __init__(self, seed=60, n=20):
        self.rng = np.random.default_rng(seed)
        self.agents = [WorkerAgent(float(s)) for s in workers.skill[:n]]
        self.history = []

    def step(self):
        actions = [a.step(self.rng) for a in self.agents]
        self.history.append(
            {
                "step": len(self.history),
                "total_output": sum(a.produced for a in self.agents),
                "resting": actions.count("Break"),
            }
        )


model = MiniModel()
for _ in range(50):
    model.step()
result_060 = pd.DataFrame(model.history)
display(result_060.tail())
fig, ax1 = plt.subplots(figsize=(7, 3.5))
ax1.plot(result_060.step, result_060.total_output, label="cumulative production")
ax1.set_xlabel("Step")
ax1.set_ylabel("cumulative production [units]")
ax2 = ax1.twinx()
ax2.plot(
    result_060.step,
    result_060.resting,
    color="tab:orange",
    alpha=0.6,
    label="Resting workers",
)
ax2.set_ylabel("Resting workers")
ax1.set_title("Model KPI collection")
ax1.grid(alpha=0.3)
fig.tight_layout()
plt.show()
[OUT: 12]
step total_output resting
45 45 462 0
46 46 474 0
47 47 483 0
48 48 483 20
49 49 494 0

Model KPI collection

Interpreting the results

Separating model structure from KPI collection makes rule changes and validation easier. We design operational processes that include model specifications, SEED management, unit testing, sensitivity analysis, and calibration against actual results, rather than simply adopting Mesa itself.

Practical takeaways

What all 10 have in common is that they clearly indicate “variation, contact, and local judgment” rather than the average. ABM allows you to compare measures such as increasing fleets, separating teams, sharing information, and selecting training targets before deploying them to the field. On the other hand, the result is the consequence of assumptions. Rather than a single prediction value, you should report the distribution of multiple seeds, the lower and upper quantiles, and the boundaries where the order of the initiative changes.

Preparing for practical use

  1. Defining decision-making in advance: Specify the decision, its deadline and the cost of choosing poorly.
  2. Agreeing on boundaries and granularity: Prepare the specification document for processes, time units, subjects, conditions, actions, and external conditions.
  3. Separate calibration from validation: Parameters are matched during certain periods, and reproducibility is checked during different periods and shifts.
  4. Conduct sensitivity analysis: Specifies uncertain inputs such as contact rate or processing power, and the conditions under which the conclusion is reversed.
  5. Incorporating on-site reviews: Workers and managers check for exceptions, tacit knowledge, and safety constraints not found in the model.
  6. Determine operational responsibilities: Define criteria for data updates, version management, approvals, monitoring, and decommissioning.

Conclusion

No.051–060 links the basics of ABM to crowds, traffic, markets, infections, supply chains, organization, reinforcement learning, and implementation structures in manufacturing decision-making. Starting with a small, explainable model and gradually refining it while learning from track record gaps helps balance ROI and on-site trust.

Consultations for Corporations

At Surikobo, we support everything from problem organization to model design, PoC, and on-site operations, covering areas such as in-factory logistics, production and inventory, supply chain, and personnel allocation. You can consult with us from the stage of “Not sure if the data is sufficient” or “Which is better, commercial tools or in-house ones?”

📩 Contact Us: www.surikobo.co.jp/contact Please feel free to consult us first.