On this tutorial, we construct a sophisticated, absolutely autonomous logistics simulation wherein a number of sensible supply vans function inside a dynamic city-wide street community. We design the system so that every truck behaves as an agent able to bidding on supply orders, planning optimum routes, managing battery ranges, in search of charging stations, and maximizing revenue via self-interested decision-making. By means of every code snippet, we discover how agentic behaviors emerge from easy guidelines, how competitors shapes order allocation, and the way a graph-based world allows sensible motion, routing, and useful resource constraints. Take a look at the FULL CODES right here.
import networkx as nx
import matplotlib.pyplot as plt
import random
import time
from IPython.show import clear_output
from dataclasses import dataclass, discipline
from typing import Listing, Dict, Non-obligatory
NUM_NODES = 30
CONNECTION_RADIUS = 0.25
NUM_AGENTS = 5
STARTING_BALANCE = 1000
FUEL_PRICE = 2.0
PAYOUT_MULTIPLIER = 5.0
BATTERY_CAPACITY = 100
CRITICAL_BATTERY = 25
@dataclass
class Order:
id: str
target_node: int
weight_kg: int
payout: float
standing: str = "pending"
class AgenticTruck:
def __init__(self, agent_id, start_node, graph, capability=100):
self.id = agent_id
self.current_node = start_node
self.graph = graph
self.battery = BATTERY_CAPACITY
self.stability = STARTING_BALANCE
self.capability = capability
self.state = "IDLE"
self.path: Listing[int] = []
self.current_order: Non-obligatory[Order] = None
self.target_node: int = start_node
We arrange all of the core constructing blocks of the simulation, together with imports, international parameters, and the essential information constructions. We additionally outline the AgenticTruck class and initialize key attributes, together with place, battery, stability, and working state. We lay the muse for all agent behaviors to evolve. Take a look at the FULL CODES right here.
def get_path_cost(self, begin, finish):
attempt:
size = nx.shortest_path_length(self.graph, begin, finish, weight="weight")
path = nx.shortest_path(self.graph, begin, finish, weight="weight")
return size, path
besides nx.NetworkXNoPath:
return float('inf'), []
def find_nearest_charger(self):
chargers = [n for n, attr in self.graph.nodes(data=True) if attr.get('type') == 'charger']
best_charger = None
min_dist = float('inf')
best_path = []
for charger in chargers:
dist, path = self.get_path_cost(self.current_node, charger)
if dist < min_dist:
min_dist = dist
best_charger = charger
best_path = path
return best_charger, best_path
def calculate_bid(self, order):
if order.weight_kg > self.capability:
return float('inf')
if self.state != "IDLE" or self.battery < CRITICAL_BATTERY:
return float('inf')
dist_to_target, _ = self.get_path_cost(self.current_node, order.target_node)
fuel_cost = dist_to_target * FUEL_PRICE
expected_profit = order.payout - fuel_cost
if expected_profit < 10:
return float('inf')
return dist_to_target
def assign_order(self, order):
self.current_order = order
self.state = "MOVING"
self.target_node = order.target_node
_, self.path = self.get_path_cost(self.current_node, self.target_node)
if self.path: self.path.pop(0)
def go_charge(self):
charger_node, path = self.find_nearest_charger()
if charger_node isn't None:
self.state = "TO_CHARGER"
self.target_node = charger_node
self.path = path
if self.path: self.path.pop(0)
We implement superior decision-making logic for the vans. We calculate shortest paths, determine close by charging stations, and consider whether or not an order is worthwhile and possible. We additionally put together the truck to simply accept assignments or proactively search charging when wanted. Take a look at the FULL CODES right here.
def step(self):
if self.state == "IDLE" and self.battery < CRITICAL_BATTERY:
self.go_charge()
if self.state == "CHARGING":
self.battery += 10
self.stability -= 5
if self.battery >= 100:
self.battery = 100
self.state = "IDLE"
return
if self.path:
next_node = self.path[0]
edge_data = self.graph.get_edge_data(self.current_node, next_node)
distance = edge_data['weight']
self.current_node = next_node
self.path.pop(0)
self.battery -= (distance * 2)
self.stability -= (distance * FUEL_PRICE)
if not self.path:
if self.state == "MOVING":
self.stability += self.current_order.payout
self.current_order.standing = "accomplished"
self.current_order = None
self.state = "IDLE"
elif self.state == "TO_CHARGER":
self.state = "CHARGING"
We handle the step-by-step actions of every truck because the simulation runs. We deal with battery recharging, monetary impacts of motion, gas consumption, and order completion. We be sure that brokers transition easily between states, akin to shifting, charging, and idling. Take a look at the FULL CODES right here.
class Simulation:
def __init__(self):
self.setup_graph()
self.setup_agents()
self.orders = []
self.order_count = 0
def setup_graph(self):
self.G = nx.random_geometric_graph(NUM_NODES, CONNECTION_RADIUS)
for (u, v) in self.G.edges():
self.G.edges[u, v]['weight'] = random.uniform(1.0, 3.0)
for i in self.G.nodes():
r = random.random()
if r < 0.15:
self.G.nodes[i]['type'] = 'charger'
self.G.nodes[i]['color'] = 'purple'
else:
self.G.nodes[i]['type'] = 'home'
self.G.nodes[i]['color'] = '#A0CBE2'
def setup_agents(self):
self.brokers = []
for i in vary(NUM_AGENTS):
start_node = random.randint(0, NUM_NODES-1)
cap = random.selection([50, 100, 200])
self.brokers.append(AgenticTruck(i, start_node, self.G, capability=cap))
def generate_order(self):
goal = random.randint(0, NUM_NODES-1)
weight = random.randint(10, 120)
payout = random.randint(50, 200)
order = Order(id=f"ORD-{self.order_count}", target_node=goal, weight_kg=weight, payout=payout)
self.orders.append(order)
self.order_count += 1
return order
def run_market(self):
for order in self.orders:
if order.standing == "pending":
bids = {agent: agent.calculate_bid(order) for agent in self.brokers}
valid_bids = {okay: v for okay, v in bids.objects() if v != float('inf')}
if valid_bids:
winner = min(valid_bids, key=valid_bids.get)
winner.assign_order(order)
order.standing = "assigned"
We create the simulated world and orchestrate agent interactions. We generate the graph-based metropolis, spawn vans with various capacities, and produce new supply orders. We additionally implement a easy market the place brokers bid for duties primarily based on profitability and distance. Take a look at the FULL CODES right here.
def step(self):
if random.random() < 0.3:
self.generate_order()
self.run_market()
for agent in self.brokers:
agent.step()
def visualize(self, step_num):
clear_output(wait=True)
plt.determine(figsize=(10, 8))
pos = nx.get_node_attributes(self.G, 'pos')
node_colors = [self.G.nodes[n]['color'] for n in self.G.nodes()]
nx.draw(self.G, pos, node_color=node_colors, with_labels=True, node_size=300, edge_color="grey", alpha=0.6)
for agent in self.brokers:
x, y = pos[agent.current_node]
jitter_x = x + random.uniform(-0.02, 0.02)
jitter_y = y + random.uniform(-0.02, 0.02)
colour="inexperienced" if agent.state == "IDLE" else ('orange' if agent.state == "MOVING" else 'purple')
plt.plot(jitter_x, jitter_y, marker="s", markersize=12, colour=colour, markeredgecolor="black")
plt.textual content(jitter_x, jitter_y+0.03, f"A{agent.id}n${int(agent.stability)}n{int(agent.battery)}%",
fontsize=8, ha="heart", fontweight="daring", bbox=dict(facecolor="white", alpha=0.7, pad=1))
for order in self.orders:
if order.standing in ["assigned", "pending"]:
ox, oy = pos[order.target_node]
plt.plot(ox, oy, marker="*", markersize=15, colour="gold", markeredgecolor="black")
plt.title(f"Graph-Primarily based Logistics Swarm | Step: {step_num}nRed Nodes = Chargers | Gold Stars = Orders", fontsize=14)
plt.present()
print("Initializing Superior Simulation...")
sim = Simulation()
for t in vary(60):
sim.step()
sim.visualize(t)
time.sleep(0.5)
print("Simulation Completed.")
We step via the complete simulation loop and visualize the logistics swarm in actual time. We replace agent states, draw the community, show energetic orders, and animate every truck’s motion. By operating this loop, we observe the emergent coordination and competitors that outline our multi-agent logistics ecosystem.
In conclusion, we noticed how the person parts, graph era, autonomous routing, battery administration, auctions, and visualization, come collectively to type a dwelling, evolving system of agentic vans. We watch as brokers negotiate workloads, compete for worthwhile alternatives, and reply to environmental pressures akin to distance, gas prices, and charging wants. By operating the simulation, we observe emergent dynamics that mirror real-world fleet conduct, offering a robust sandbox for experimenting with logistics intelligence.
Take a look at the FULL CODES right here. Additionally, be at liberty to observe us on Twitter and don’t neglect to hitch our 100k+ ML SubReddit and Subscribe to our Publication. Wait! are you on telegram? now you’ll be able to be a part of us on telegram as properly.
Asif Razzaq is the CEO of Marktechpost Media Inc.. As a visionary entrepreneur and engineer, Asif is dedicated to harnessing the potential of Synthetic Intelligence for social good. His most up-to-date endeavor is the launch of an Synthetic Intelligence Media Platform, Marktechpost, which stands out for its in-depth protection of machine studying and deep studying information that’s each technically sound and simply comprehensible by a large viewers. The platform boasts of over 2 million month-to-month views, illustrating its recognition amongst audiences.
Elevate your perspective with NextTech Information, the place innovation meets perception.
Uncover the newest breakthroughs, get unique updates, and join with a worldwide community of future-focused thinkers.
Unlock tomorrow’s developments at present: learn extra, subscribe to our e-newsletter, and turn into a part of the NextTech group at NextTech-news.com

