Publish Gradio console bundle
Browse files- space-bundle/README.md +32 -0
- space-bundle/app.py +142 -0
- space-bundle/requirements.txt +5 -0
- space-bundle/src/omnitower/__init__.py +3 -0
- space-bundle/src/omnitower/admission.py +62 -0
- space-bundle/src/omnitower/allocation.py +156 -0
- space-bundle/src/omnitower/constants.py +59 -0
- space-bundle/src/omnitower/generator.py +214 -0
- space-bundle/src/omnitower/lns_solver.py +80 -0
- space-bundle/src/omnitower/metrics.py +94 -0
- space-bundle/src/omnitower/models.py +118 -0
- space-bundle/src/omnitower/network.py +68 -0
- space-bundle/src/omnitower/omnitower/__init__.py +3 -0
- space-bundle/src/omnitower/omnitower/admission.py +62 -0
- space-bundle/src/omnitower/omnitower/allocation.py +156 -0
- space-bundle/src/omnitower/omnitower/constants.py +59 -0
- space-bundle/src/omnitower/omnitower/generator.py +214 -0
- space-bundle/src/omnitower/omnitower/lns_solver.py +80 -0
- space-bundle/src/omnitower/omnitower/metrics.py +96 -0
- space-bundle/src/omnitower/omnitower/models.py +118 -0
- space-bundle/src/omnitower/omnitower/network.py +79 -0
- space-bundle/src/omnitower/omnitower/options.py +84 -0
- space-bundle/src/omnitower/omnitower/pipeline.py +70 -0
- space-bundle/src/omnitower/omnitower/returns.py +77 -0
- space-bundle/src/omnitower/omnitower/visualization.py +47 -0
- space-bundle/src/omnitower/options.py +84 -0
- space-bundle/src/omnitower/pipeline.py +70 -0
- space-bundle/src/omnitower/returns.py +77 -0
- space-bundle/src/omnitower/visualization.py +47 -0
space-bundle/README.md
ADDED
|
@@ -0,0 +1,32 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
---
|
| 2 |
+
title: Omnichannel Fulfillment and Returns Control Tower
|
| 3 |
+
emoji: 📦
|
| 4 |
+
colorFrom: blue
|
| 5 |
+
colorTo: green
|
| 6 |
+
sdk: gradio
|
| 7 |
+
sdk_version: 5.50.0
|
| 8 |
+
app_file: app.py
|
| 9 |
+
pinned: false
|
| 10 |
+
license: mit
|
| 11 |
+
tags:
|
| 12 |
+
- operations-research
|
| 13 |
+
- supply-chain
|
| 14 |
+
- inventory-allocation
|
| 15 |
+
- order-fulfillment
|
| 16 |
+
- reverse-logistics
|
| 17 |
+
- network-flow
|
| 18 |
+
- gradio
|
| 19 |
+
---
|
| 20 |
+
|
| 21 |
+
# Omnichannel Fulfillment and Returns Control Tower
|
| 22 |
+
|
| 23 |
+
Joint order allocation across stores, distribution centers, regional
|
| 24 |
+
warehouses, cross-docks, and suppliers — with dynamic admission control,
|
| 25 |
+
adaptive large-neighborhood reoptimization, assortment substitution, and
|
| 26 |
+
rule-based reverse logistics for returns.
|
| 27 |
+
|
| 28 |
+
Run five network scenarios (peak-season surge, regional stockout,
|
| 29 |
+
high-return category wave, DC capacity outage, green-logistics push),
|
| 30 |
+
inspect network KPIs and the Adaptive Large Neighborhood Search
|
| 31 |
+
improvement curve, and compare Fast vs. Economical vs. Green delivery
|
| 32 |
+
options for the same order.
|
space-bundle/app.py
ADDED
|
@@ -0,0 +1,142 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Gradio console for the Omnichannel Fulfillment and Returns Control Tower."""
|
| 2 |
+
|
| 3 |
+
from __future__ import annotations
|
| 4 |
+
|
| 5 |
+
import sys
|
| 6 |
+
from pathlib import Path
|
| 7 |
+
|
| 8 |
+
ROOT = Path(__file__).resolve().parent
|
| 9 |
+
sys.path.insert(0, str(ROOT / "src"))
|
| 10 |
+
|
| 11 |
+
import gradio as gr
|
| 12 |
+
|
| 13 |
+
from omnitower.generator import SCENARIOS, list_scenarios
|
| 14 |
+
from omnitower.pipeline import run_scenario, run_delivery_options_for_order
|
| 15 |
+
from omnitower.visualization import kpi_bar, cost_history_plot, returns_disposition_pie, delivery_options_plot, inventory_impact_table
|
| 16 |
+
|
| 17 |
+
SCENARIO_CHOICES = [(v, k) for k, v in SCENARIOS.items()]
|
| 18 |
+
|
| 19 |
+
|
| 20 |
+
def run_demo(scenario_key: str, delivery_option: str, n_orders: int, lns_iterations: int, seed: int, use_admission: bool):
|
| 21 |
+
result = run_scenario(
|
| 22 |
+
scenario_key,
|
| 23 |
+
seed=int(seed),
|
| 24 |
+
n_orders=int(n_orders),
|
| 25 |
+
delivery_option=delivery_option,
|
| 26 |
+
lns_iterations=int(lns_iterations),
|
| 27 |
+
use_admission_control=bool(use_admission),
|
| 28 |
+
)
|
| 29 |
+
metrics = result.metrics.to_dict()
|
| 30 |
+
event_md = "\n".join(f"- {e.description}" for e in result.network.events)
|
| 31 |
+
kpi_md = "\n".join(f"- **{k.replace('_', ' ').title()}**: {v}" for k, v in metrics.items())
|
| 32 |
+
admission_md = f"Orders deferred to backorder by dynamic admission control: **{result.admission_rejections}**"
|
| 33 |
+
returns_md = (
|
| 34 |
+
f"Returns generated: **{result.return_summary['n_returns']}** · "
|
| 35 |
+
f"Resell rate: **{result.return_summary['resell_rate']:.0%}** · "
|
| 36 |
+
f"Handling cost: **${result.return_summary['total_handling_cost_usd']:,.2f}** · "
|
| 37 |
+
f"Recovered value: **${result.return_summary['total_recovered_value_usd']:,.2f}**"
|
| 38 |
+
)
|
| 39 |
+
|
| 40 |
+
kpi_fig = kpi_bar(metrics)
|
| 41 |
+
cost_fig = cost_history_plot(result.cost_history)
|
| 42 |
+
returns_fig = returns_disposition_pie(result.return_summary["by_disposition"])
|
| 43 |
+
|
| 44 |
+
return (
|
| 45 |
+
f"### Scenario Event\n{event_md}\n\n### Network KPIs\n{kpi_md}\n\n{admission_md}",
|
| 46 |
+
returns_md,
|
| 47 |
+
kpi_fig,
|
| 48 |
+
cost_fig,
|
| 49 |
+
returns_fig,
|
| 50 |
+
)
|
| 51 |
+
|
| 52 |
+
|
| 53 |
+
def run_options(scenario_key: str, order_index: int, seed: int):
|
| 54 |
+
network, results = run_delivery_options_for_order(scenario_key, order_index=int(order_index), seed=int(seed))
|
| 55 |
+
fig = delivery_options_plot(results)
|
| 56 |
+
table = [[r.option, r.total_cost_usd, r.total_lead_time_hours, r.total_carbon_kg, ", ".join(r.report["nodes_used"])] for r in results]
|
| 57 |
+
impact_table = inventory_impact_table(results)
|
| 58 |
+
return fig, table, impact_table
|
| 59 |
+
|
| 60 |
+
|
| 61 |
+
with gr.Blocks(title="Omnichannel Fulfillment and Returns Control Tower", theme=gr.themes.Soft()) as demo:
|
| 62 |
+
gr.Markdown(
|
| 63 |
+
"# Omnichannel Fulfillment and Returns Control Tower\n"
|
| 64 |
+
"Joint order allocation across stores, distribution centers, cross-docks, "
|
| 65 |
+
"and suppliers, with dynamic admission control, adaptive large-neighborhood "
|
| 66 |
+
"reoptimization, and rule-based reverse logistics for returns."
|
| 67 |
+
)
|
| 68 |
+
|
| 69 |
+
with gr.Tab("Fulfillment Network Run"):
|
| 70 |
+
with gr.Row():
|
| 71 |
+
scenario = gr.Dropdown(choices=SCENARIO_CHOICES, value=list_scenarios()[0], label="Network scenario")
|
| 72 |
+
option = gr.Radio(choices=[("Fast", "fast"), ("Economical", "economical"), ("Green", "green")], value="economical", label="Delivery objective")
|
| 73 |
+
with gr.Row():
|
| 74 |
+
n_orders = gr.Slider(60, 400, value=200, step=20, label="Orders in the horizon")
|
| 75 |
+
iterations = gr.Slider(5, 60, value=25, step=5, label="ALNS iterations")
|
| 76 |
+
with gr.Row():
|
| 77 |
+
seed = gr.Slider(1, 100, value=42, step=1, label="Random seed")
|
| 78 |
+
admission = gr.Checkbox(value=True, label="Enable dynamic admission control")
|
| 79 |
+
run_btn = gr.Button("Run Network", variant="primary")
|
| 80 |
+
|
| 81 |
+
with gr.Row():
|
| 82 |
+
kpi_out = gr.Markdown()
|
| 83 |
+
returns_out = gr.Markdown()
|
| 84 |
+
with gr.Row():
|
| 85 |
+
kpi_plot_out = gr.Plot(label="Network KPIs")
|
| 86 |
+
cost_plot_out = gr.Plot(label="ALNS Cost Improvement")
|
| 87 |
+
returns_plot_out = gr.Plot(label="Return Disposition Mix")
|
| 88 |
+
|
| 89 |
+
run_btn.click(
|
| 90 |
+
run_demo,
|
| 91 |
+
inputs=[scenario, option, n_orders, iterations, seed, admission],
|
| 92 |
+
outputs=[kpi_out, returns_out, kpi_plot_out, cost_plot_out, returns_plot_out],
|
| 93 |
+
)
|
| 94 |
+
|
| 95 |
+
with gr.Tab("Fast vs. Economical vs. Green"):
|
| 96 |
+
gr.Markdown(
|
| 97 |
+
"For a single order, compares the three delivery options requested in the "
|
| 98 |
+
"brief and shows the effect each choice has on downstream inventory and "
|
| 99 |
+
"picking-capacity availability."
|
| 100 |
+
)
|
| 101 |
+
with gr.Row():
|
| 102 |
+
o_scenario = gr.Dropdown(choices=SCENARIO_CHOICES, value="green_logistics_push", label="Network scenario")
|
| 103 |
+
o_index = gr.Slider(0, 50, value=0, step=1, label="Order index")
|
| 104 |
+
o_seed = gr.Slider(1, 100, value=42, step=1, label="Random seed")
|
| 105 |
+
options_btn = gr.Button("Compare Delivery Options", variant="primary")
|
| 106 |
+
options_plot = gr.Plot(label="Cost / Lead Time / Carbon by Option")
|
| 107 |
+
options_table = gr.Dataframe(
|
| 108 |
+
headers=["Option", "Cost (USD)", "Lead Time (hours)", "Carbon (kg)", "Nodes Used"],
|
| 109 |
+
label="Option Summary",
|
| 110 |
+
)
|
| 111 |
+
impact_table = gr.Dataframe(
|
| 112 |
+
headers=["Option", "Node", "SKU", "Qty Consumed", "Inventory Before", "Inventory After"],
|
| 113 |
+
label="Inventory and Capacity Impact",
|
| 114 |
+
)
|
| 115 |
+
options_btn.click(run_options, inputs=[o_scenario, o_index, o_seed], outputs=[options_plot, options_table, impact_table])
|
| 116 |
+
|
| 117 |
+
with gr.Tab("About"):
|
| 118 |
+
gr.Markdown(
|
| 119 |
+
"""
|
| 120 |
+
### Decisions modeled
|
| 121 |
+
- Which fulfillment node serves each order line (DC, regional warehouse, cross-dock, or ship-from-store)
|
| 122 |
+
- Whether an order is split across multiple sources
|
| 123 |
+
- Whether a substitute SKU is offered when the requested SKU is unavailable
|
| 124 |
+
- Standard vs. express (and a carbon-weighted "green") shipping mode
|
| 125 |
+
- Whether an incoming order is admitted immediately or deferred to backorder under scarce inventory
|
| 126 |
+
- Where a returned unit is routed: restock at the store, restock at the DC, repair, recycle, or dispose
|
| 127 |
+
- Whether a returned unit is resold or scrapped
|
| 128 |
+
|
| 129 |
+
### Models
|
| 130 |
+
- **Order allocation**: Greedy Marginal Cost heuristic ranking every candidate source by weighted transport, picking, lead-time, and carbon cost
|
| 131 |
+
- **Allocation improvement**: Adaptive Large Neighborhood Search — destroy a batch of orders, reinsert by priority, keep only if network cost improves
|
| 132 |
+
- **Dynamic admission control**: bid-price-style scarcity scoring that defers low-priority orders competing for scarce stock
|
| 133 |
+
- **Assortment substitution**: substitute-group lookup triggered on stockout
|
| 134 |
+
- **Reverse logistics**: rule-based return disposition and resell/scrap decisioning
|
| 135 |
+
|
| 136 |
+
### Stack
|
| 137 |
+
NetworkX · Plotly · Gradio 5.x · Static explorer
|
| 138 |
+
"""
|
| 139 |
+
)
|
| 140 |
+
|
| 141 |
+
if __name__ == "__main__":
|
| 142 |
+
demo.launch()
|
space-bundle/requirements.txt
ADDED
|
@@ -0,0 +1,5 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
networkx>=3.2
|
| 2 |
+
numpy>=1.26
|
| 3 |
+
pandas>=2.0
|
| 4 |
+
plotly>=5.18
|
| 5 |
+
gradio>=5.50
|
space-bundle/src/omnitower/__init__.py
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Omnichannel Fulfillment and Returns Control Tower — core optimization engine."""
|
| 2 |
+
|
| 3 |
+
__version__ = "1.0.0"
|
space-bundle/src/omnitower/admission.py
ADDED
|
@@ -0,0 +1,62 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Dynamic admission control.
|
| 2 |
+
|
| 3 |
+
Approximates a bid-price control policy: rather than a static allocation
|
| 4 |
+
rule, each incoming order is scored against the *current* scarcity of the
|
| 5 |
+
SKUs it requests (remaining pooled inventory vs. remaining forecast demand
|
| 6 |
+
for the rest of the horizon). Orders that would consume disproportionately
|
| 7 |
+
scarce stock for a low-margin / low-priority order are queued as
|
| 8 |
+
backorders instead of being admitted immediately, protecting inventory for
|
| 9 |
+
higher-value demand still expected to arrive.
|
| 10 |
+
"""
|
| 11 |
+
|
| 12 |
+
from __future__ import annotations
|
| 13 |
+
|
| 14 |
+
from dataclasses import dataclass
|
| 15 |
+
|
| 16 |
+
from .models import Network, Order
|
| 17 |
+
from .allocation import AllocationState
|
| 18 |
+
from .constants import DEFAULT_MARGIN_RATE, BACKORDER_PENALTY_USD
|
| 19 |
+
|
| 20 |
+
PRIORITY_WEIGHT = {"vip": 1.6, "premium": 1.25, "standard": 1.0}
|
| 21 |
+
|
| 22 |
+
|
| 23 |
+
@dataclass
|
| 24 |
+
class AdmissionDecision:
|
| 25 |
+
order_id: str
|
| 26 |
+
admitted: bool
|
| 27 |
+
reason: str
|
| 28 |
+
scarcity_score: float
|
| 29 |
+
|
| 30 |
+
|
| 31 |
+
def _scarcity_score(network: Network, state: AllocationState, order: Order, remaining_demand_factor: float) -> float:
|
| 32 |
+
scores = []
|
| 33 |
+
for line in order.lines:
|
| 34 |
+
total_remaining = sum(qty for (node, sku), qty in state.inventory.items() if sku == line.sku_id)
|
| 35 |
+
forecast_need = max(1.0, total_remaining * 0.0 + remaining_demand_factor * line.qty_requested * 6.0)
|
| 36 |
+
if total_remaining <= 0:
|
| 37 |
+
scores.append(1.0)
|
| 38 |
+
else:
|
| 39 |
+
scores.append(min(1.0, forecast_need / (total_remaining + forecast_need)))
|
| 40 |
+
return sum(scores) / max(1, len(scores))
|
| 41 |
+
|
| 42 |
+
|
| 43 |
+
def evaluate_admission(
|
| 44 |
+
network: Network,
|
| 45 |
+
state: AllocationState,
|
| 46 |
+
order: Order,
|
| 47 |
+
remaining_demand_factor: float = 0.5,
|
| 48 |
+
scarcity_threshold: float = 0.82,
|
| 49 |
+
) -> AdmissionDecision:
|
| 50 |
+
scarcity = _scarcity_score(network, state, order, remaining_demand_factor)
|
| 51 |
+
priority_weight = PRIORITY_WEIGHT.get(order.priority_class, 1.0)
|
| 52 |
+
effective_threshold = scarcity_threshold * priority_weight
|
| 53 |
+
order_value = sum(network.skus[l.sku_id].unit_price * l.qty_requested for l in order.lines if l.sku_id in network.skus)
|
| 54 |
+
margin_value = order_value * DEFAULT_MARGIN_RATE
|
| 55 |
+
|
| 56 |
+
if scarcity < effective_threshold or margin_value > BACKORDER_PENALTY_USD * 20:
|
| 57 |
+
return AdmissionDecision(order.order_id, True, "accepted: inventory scarcity within threshold for priority class", round(scarcity, 3))
|
| 58 |
+
return AdmissionDecision(order.order_id, False, "deferred to backorder: scarce stock reserved for expected higher-value demand", round(scarcity, 3))
|
| 59 |
+
|
| 60 |
+
|
| 61 |
+
def evaluate_all(network: Network, state: AllocationState, remaining_demand_factor: float = 0.5) -> list[AdmissionDecision]:
|
| 62 |
+
return [evaluate_admission(network, state, order, remaining_demand_factor) for order in network.orders]
|
space-bundle/src/omnitower/allocation.py
ADDED
|
@@ -0,0 +1,156 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Order allocation optimizer: Inventory Allocation + Order Fulfillment.
|
| 2 |
+
|
| 3 |
+
Implements the "Greedy Marginal Cost" scalable heuristic referenced in the
|
| 4 |
+
project brief: for every order line, candidate fulfillment nodes are ranked
|
| 5 |
+
by the marginal cost of serving that unit from that node (transport +
|
| 6 |
+
picking + packing, weighted by the chosen delivery objective), subject to
|
| 7 |
+
live inventory and daily picking-capacity pools that are decremented as the
|
| 8 |
+
order stream is processed. Split shipments and ship-from-store are native
|
| 9 |
+
outcomes of the ranking rather than a separate rule.
|
| 10 |
+
"""
|
| 11 |
+
|
| 12 |
+
from __future__ import annotations
|
| 13 |
+
|
| 14 |
+
from dataclasses import dataclass, field
|
| 15 |
+
|
| 16 |
+
from .models import Network, Order, OrderLine
|
| 17 |
+
from .network import build_graph, distance_km, transport_cost, carbon_kg, candidate_sources
|
| 18 |
+
from .constants import (
|
| 19 |
+
COST_PER_PICK_USD,
|
| 20 |
+
COST_PER_PACK_USD,
|
| 21 |
+
COST_PER_SPLIT_SHIPMENT_USD,
|
| 22 |
+
LEAD_TIME_HOURS_PER_100KM_STANDARD,
|
| 23 |
+
LEAD_TIME_HOURS_PER_100KM_EXPRESS,
|
| 24 |
+
LEAD_TIME_HOURS_PER_100KM_GREEN,
|
| 25 |
+
)
|
| 26 |
+
|
| 27 |
+
OBJECTIVE_WEIGHTS = {
|
| 28 |
+
# (cost_weight, time_weight, carbon_weight)
|
| 29 |
+
"fast": (0.15, 0.75, 0.10),
|
| 30 |
+
"economical": (0.75, 0.10, 0.15),
|
| 31 |
+
"green": (0.15, 0.10, 0.75),
|
| 32 |
+
}
|
| 33 |
+
|
| 34 |
+
|
| 35 |
+
@dataclass
|
| 36 |
+
class AllocationState:
|
| 37 |
+
inventory: dict[tuple[str, str], float]
|
| 38 |
+
capacity: dict[str, float]
|
| 39 |
+
|
| 40 |
+
|
| 41 |
+
def build_state(network: Network) -> AllocationState:
|
| 42 |
+
inv = {}
|
| 43 |
+
for rec in network.inventory:
|
| 44 |
+
inv[(rec.node_id, rec.sku_id)] = rec.on_hand_qty * rec.accuracy
|
| 45 |
+
cap = {n.node_id: float(n.daily_pick_capacity) for n in network.nodes.values()}
|
| 46 |
+
return AllocationState(inventory=inv, capacity=cap)
|
| 47 |
+
|
| 48 |
+
|
| 49 |
+
def _mode_for_option(option: str) -> str:
|
| 50 |
+
return {"fast": "express", "economical": "standard", "green": "green"}[option]
|
| 51 |
+
|
| 52 |
+
|
| 53 |
+
def _lead_time_hours(distance: float, mode: str) -> float:
|
| 54 |
+
rate = {
|
| 55 |
+
"express": LEAD_TIME_HOURS_PER_100KM_EXPRESS,
|
| 56 |
+
"green": LEAD_TIME_HOURS_PER_100KM_GREEN,
|
| 57 |
+
}.get(mode, LEAD_TIME_HOURS_PER_100KM_STANDARD)
|
| 58 |
+
return 2.0 + (distance / 100.0) * rate
|
| 59 |
+
|
| 60 |
+
|
| 61 |
+
def _score_source(graph, node, sku_id, demand_node_id, node_meta, option, state: AllocationState) -> tuple[float, dict]:
|
| 62 |
+
dist = distance_km(graph, node, demand_node_id)
|
| 63 |
+
if dist == float("inf"):
|
| 64 |
+
return float("inf"), {}
|
| 65 |
+
mode = _mode_for_option(option)
|
| 66 |
+
link_mode = "express" if mode == "express" else "standard"
|
| 67 |
+
t_cost = transport_cost(dist, link_mode)
|
| 68 |
+
pick_cost = COST_PER_PICK_USD * node_meta.picking_cost_multiplier
|
| 69 |
+
pack_cost = COST_PER_PACK_USD
|
| 70 |
+
lead_hours = _lead_time_hours(dist, mode)
|
| 71 |
+
carbon = carbon_kg(dist, mode)
|
| 72 |
+
cw, tw, cbw = OBJECTIVE_WEIGHTS[option]
|
| 73 |
+
# normalize roughly to comparable scales before weighting
|
| 74 |
+
score = cw * (t_cost + pick_cost + pack_cost) + tw * lead_hours + cbw * (carbon * 0.5)
|
| 75 |
+
breakdown = {
|
| 76 |
+
"distance_km": round(dist, 1),
|
| 77 |
+
"transport_cost_usd": round(t_cost, 2),
|
| 78 |
+
"pick_cost_usd": round(pick_cost, 2),
|
| 79 |
+
"pack_cost_usd": round(pack_cost, 2),
|
| 80 |
+
"lead_time_hours": round(lead_hours, 1),
|
| 81 |
+
"carbon_kg": round(carbon, 2),
|
| 82 |
+
"ship_mode": mode,
|
| 83 |
+
}
|
| 84 |
+
return score, breakdown
|
| 85 |
+
|
| 86 |
+
|
| 87 |
+
def _find_substitute(network: Network, sku_id: str, state: AllocationState, source_pool: list[str]) -> str | None:
|
| 88 |
+
sku = network.skus[sku_id]
|
| 89 |
+
for other in network.skus.values():
|
| 90 |
+
if other.sku_id == sku_id or other.substitute_group != sku.substitute_group:
|
| 91 |
+
continue
|
| 92 |
+
if any(state.inventory.get((n, other.sku_id), 0) >= 1 for n in source_pool):
|
| 93 |
+
return other.sku_id
|
| 94 |
+
return None
|
| 95 |
+
|
| 96 |
+
|
| 97 |
+
def allocate_order(network: Network, order: Order, option: str, state: AllocationState, graph=None) -> dict:
|
| 98 |
+
graph = graph or build_graph(network)
|
| 99 |
+
sources = candidate_sources(network, order.demand_node_id)
|
| 100 |
+
used_nodes: set[str] = set()
|
| 101 |
+
line_reports = []
|
| 102 |
+
|
| 103 |
+
for line in order.lines:
|
| 104 |
+
remaining = line.qty_requested
|
| 105 |
+
line.qty_fulfilled = 0
|
| 106 |
+
while remaining > 0:
|
| 107 |
+
ranked = []
|
| 108 |
+
for node_id in sources:
|
| 109 |
+
node_meta = network.nodes[node_id]
|
| 110 |
+
avail = state.inventory.get((node_id, line.sku_id), 0)
|
| 111 |
+
cap = state.capacity.get(node_id, 0)
|
| 112 |
+
if avail < 1 or cap < 1:
|
| 113 |
+
continue
|
| 114 |
+
score, breakdown = _score_source(graph, node_id, line.sku_id, order.demand_node_id, node_meta, option, state)
|
| 115 |
+
if score == float("inf"):
|
| 116 |
+
continue
|
| 117 |
+
ranked.append((score, node_id, breakdown))
|
| 118 |
+
if not ranked:
|
| 119 |
+
substitute = _find_substitute(network, line.sku_id, state, sources)
|
| 120 |
+
if substitute and line.substituted_sku_id is None:
|
| 121 |
+
line.substituted_sku_id = substitute
|
| 122 |
+
line.sku_id = substitute
|
| 123 |
+
continue
|
| 124 |
+
break
|
| 125 |
+
ranked.sort(key=lambda x: x[0])
|
| 126 |
+
score, node_id, breakdown = ranked[0]
|
| 127 |
+
take = min(remaining, state.inventory[(node_id, line.sku_id)], state.capacity[node_id])
|
| 128 |
+
take = max(1, int(take))
|
| 129 |
+
state.inventory[(node_id, line.sku_id)] -= take
|
| 130 |
+
state.capacity[node_id] -= take
|
| 131 |
+
line.qty_fulfilled += take
|
| 132 |
+
line.source_node_id = node_id
|
| 133 |
+
used_nodes.add(node_id)
|
| 134 |
+
remaining -= take
|
| 135 |
+
line_reports.append({"sku_id": line.sku_id, "node_id": node_id, "qty": take, **breakdown})
|
| 136 |
+
line.backordered_qty = remaining
|
| 137 |
+
|
| 138 |
+
order.split_shipment = len(used_nodes) > 1
|
| 139 |
+
order.chosen_delivery_option = option
|
| 140 |
+
total_backorder = sum(l.backordered_qty for l in order.lines)
|
| 141 |
+
order.accepted = total_backorder < sum(l.qty_requested for l in order.lines)
|
| 142 |
+
return {
|
| 143 |
+
"order_id": order.order_id,
|
| 144 |
+
"delivery_option": option,
|
| 145 |
+
"split_shipment": order.split_shipment,
|
| 146 |
+
"nodes_used": sorted(used_nodes),
|
| 147 |
+
"line_reports": line_reports,
|
| 148 |
+
"total_backordered_qty": total_backorder,
|
| 149 |
+
}
|
| 150 |
+
|
| 151 |
+
|
| 152 |
+
def allocate_all(network: Network, option: str = "economical") -> tuple[AllocationState, list[dict]]:
|
| 153 |
+
state = build_state(network)
|
| 154 |
+
graph = build_graph(network)
|
| 155 |
+
reports = [allocate_order(network, order, option, state, graph) for order in network.orders]
|
| 156 |
+
return state, reports
|
space-bundle/src/omnitower/constants.py
ADDED
|
@@ -0,0 +1,59 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Shared constants and cost coefficients for the control tower."""
|
| 2 |
+
|
| 3 |
+
from __future__ import annotations
|
| 4 |
+
|
| 5 |
+
NODE_TYPES = [
|
| 6 |
+
"store",
|
| 7 |
+
"central_dc",
|
| 8 |
+
"regional_wh",
|
| 9 |
+
"supplier",
|
| 10 |
+
"cross_dock",
|
| 11 |
+
"return_center",
|
| 12 |
+
"repair_center",
|
| 13 |
+
"recycle_center",
|
| 14 |
+
]
|
| 15 |
+
|
| 16 |
+
SHIP_MODE_STANDARD = "standard"
|
| 17 |
+
SHIP_MODE_EXPRESS = "express"
|
| 18 |
+
|
| 19 |
+
DELIVERY_OPTIONS = ["fast", "economical", "green"]
|
| 20 |
+
|
| 21 |
+
# Approximate cost / emission coefficients used across the demo scenarios.
|
| 22 |
+
COST_PER_KM_STANDARD_USD = 0.055
|
| 23 |
+
COST_PER_KM_EXPRESS_USD = 0.145
|
| 24 |
+
COST_PER_PICK_USD = 1.35
|
| 25 |
+
COST_PER_PACK_USD = 0.85
|
| 26 |
+
COST_PER_SPLIT_SHIPMENT_USD = 3.20
|
| 27 |
+
CARBON_KG_PER_KM_STANDARD = 0.18
|
| 28 |
+
CARBON_KG_PER_KM_EXPRESS = 0.34
|
| 29 |
+
CARBON_KG_PER_KM_GREEN = 0.07 # consolidated / low-carbon linehaul
|
| 30 |
+
|
| 31 |
+
LEAD_TIME_HOURS_PER_100KM_STANDARD = 2.4
|
| 32 |
+
LEAD_TIME_HOURS_PER_100KM_EXPRESS = 0.9
|
| 33 |
+
LEAD_TIME_HOURS_PER_100KM_GREEN = 3.6
|
| 34 |
+
|
| 35 |
+
RETURN_HANDLING_COST_USD = {
|
| 36 |
+
"restock_store": 1.10,
|
| 37 |
+
"restock_dc": 1.60,
|
| 38 |
+
"repair": 6.50,
|
| 39 |
+
"recycle": 2.20,
|
| 40 |
+
"dispose": 3.00,
|
| 41 |
+
}
|
| 42 |
+
|
| 43 |
+
RETURN_RECOVERY_VALUE_FACTOR = {
|
| 44 |
+
"restock_store": 0.92,
|
| 45 |
+
"restock_dc": 0.88,
|
| 46 |
+
"repair": 0.55,
|
| 47 |
+
"recycle": 0.06,
|
| 48 |
+
"dispose": 0.0,
|
| 49 |
+
}
|
| 50 |
+
|
| 51 |
+
DEFAULT_MARGIN_RATE = 0.34
|
| 52 |
+
BACKORDER_PENALTY_USD = 4.50
|
| 53 |
+
CANCELLATION_PENALTY_USD = 9.00
|
| 54 |
+
WORKING_CAPITAL_DAYS_HELD = {
|
| 55 |
+
"central_dc": 21,
|
| 56 |
+
"regional_wh": 14,
|
| 57 |
+
"store": 9,
|
| 58 |
+
"cross_dock": 2,
|
| 59 |
+
}
|
space-bundle/src/omnitower/generator.py
ADDED
|
@@ -0,0 +1,214 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Synthetic omnichannel network and demand scenario generator.
|
| 2 |
+
|
| 3 |
+
Builds a reproducible multi-echelon network (central DC, regional warehouses,
|
| 4 |
+
stores, suppliers, cross-dock, return/repair/recycle centers), a SKU
|
| 5 |
+
catalog with substitute groups, noisy inventory, and a day's worth of
|
| 6 |
+
multi-line orders, then applies one of the demo scenario archetypes.
|
| 7 |
+
"""
|
| 8 |
+
|
| 9 |
+
from __future__ import annotations
|
| 10 |
+
|
| 11 |
+
import random
|
| 12 |
+
from math import radians, sin, cos, asin, sqrt
|
| 13 |
+
|
| 14 |
+
from .models import Node, SKU, InventoryRecord, TransportLink, Order, OrderLine, ScenarioEvent, Network
|
| 15 |
+
|
| 16 |
+
CATEGORIES = ["apparel", "footwear", "electronics_accessory", "home_goods", "beauty"]
|
| 17 |
+
SUBSTITUTE_GROUPS = {
|
| 18 |
+
"apparel": ["APP-A", "APP-B"],
|
| 19 |
+
"footwear": ["SHOE-A"],
|
| 20 |
+
"electronics_accessory": ["ELEC-A"],
|
| 21 |
+
"home_goods": ["HOME-A", "HOME-B"],
|
| 22 |
+
"beauty": ["BEAUTY-A"],
|
| 23 |
+
}
|
| 24 |
+
BASE_RETURN_RATE = {
|
| 25 |
+
"apparel": 0.22,
|
| 26 |
+
"footwear": 0.17,
|
| 27 |
+
"electronics_accessory": 0.06,
|
| 28 |
+
"home_goods": 0.05,
|
| 29 |
+
"beauty": 0.03,
|
| 30 |
+
}
|
| 31 |
+
|
| 32 |
+
SCENARIOS = {
|
| 33 |
+
"peak_season_surge": "Peak-season demand surge with tight picking capacity",
|
| 34 |
+
"regional_stockout": "Regional warehouse stockout forcing ship-from-store",
|
| 35 |
+
"high_return_category_wave": "Apparel high-return wave stressing reverse logistics",
|
| 36 |
+
"capacity_constrained_dc": "Central DC capacity outage shifting flow to regional network",
|
| 37 |
+
"green_logistics_push": "Corporate mandate to minimize carbon emissions this week",
|
| 38 |
+
}
|
| 39 |
+
|
| 40 |
+
|
| 41 |
+
def _haversine_km(lat1: float, lon1: float, lat2: float, lon2: float) -> float:
|
| 42 |
+
r = 6371.0
|
| 43 |
+
dlat, dlon = radians(lat2 - lat1), radians(lon2 - lon1)
|
| 44 |
+
a = sin(dlat / 2) ** 2 + cos(radians(lat1)) * cos(radians(lat2)) * sin(dlon / 2) ** 2
|
| 45 |
+
return 2 * r * asin(sqrt(a))
|
| 46 |
+
|
| 47 |
+
|
| 48 |
+
def _make_nodes(rng: random.Random, n_stores: int) -> dict[str, Node]:
|
| 49 |
+
nodes: dict[str, Node] = {}
|
| 50 |
+
nodes["DC1"] = Node("DC1", "central_dc", "Central Distribution Center", 39.10, -94.58, daily_pick_capacity=6000, picking_cost_multiplier=0.85)
|
| 51 |
+
nodes["RWH-E"] = Node("RWH-E", "regional_wh", "Regional Warehouse East", 40.71, -74.01, daily_pick_capacity=2600, picking_cost_multiplier=0.95)
|
| 52 |
+
nodes["RWH-W"] = Node("RWH-W", "regional_wh", "Regional Warehouse West", 34.05, -118.24, daily_pick_capacity=2600, picking_cost_multiplier=0.95)
|
| 53 |
+
nodes["SUP1"] = Node("SUP1", "supplier", "Primary Supplier Hub", 41.88, -87.63, daily_pick_capacity=4000, picking_cost_multiplier=1.10)
|
| 54 |
+
nodes["XDOCK1"] = Node("XDOCK1", "cross_dock", "Regional Cross-Dock", 38.63, -90.20, daily_pick_capacity=3200, picking_cost_multiplier=0.70)
|
| 55 |
+
nodes["RET1"] = Node("RET1", "return_center", "Returns Processing Center", 39.77, -86.16, daily_pick_capacity=1800, picking_cost_multiplier=1.0)
|
| 56 |
+
nodes["REPAIR1"] = Node("REPAIR1", "repair_center", "Repair & Refurbishment Center", 39.77, -86.20, daily_pick_capacity=600, picking_cost_multiplier=1.0)
|
| 57 |
+
nodes["RECY1"] = Node("RECY1", "recycle_center", "Recycling & Recovery Center", 39.80, -86.10, daily_pick_capacity=900, picking_cost_multiplier=1.0)
|
| 58 |
+
|
| 59 |
+
for i in range(n_stores):
|
| 60 |
+
lat = 30.0 + rng.uniform(0, 15.0)
|
| 61 |
+
lon = -122.0 + rng.uniform(0, 45.0)
|
| 62 |
+
sid = f"ST{i:03d}"
|
| 63 |
+
nodes[sid] = Node(sid, "store", f"Store {i:03d}", round(lat, 3), round(lon, 3), daily_pick_capacity=rng.randint(120, 320), picking_cost_multiplier=1.25)
|
| 64 |
+
return nodes
|
| 65 |
+
|
| 66 |
+
|
| 67 |
+
def _make_skus(rng: random.Random, n_skus: int) -> dict[str, SKU]:
|
| 68 |
+
skus: dict[str, SKU] = {}
|
| 69 |
+
for i in range(n_skus):
|
| 70 |
+
cat = CATEGORIES[i % len(CATEGORIES)]
|
| 71 |
+
group = SUBSTITUTE_GROUPS[cat][i % len(SUBSTITUTE_GROUPS[cat])]
|
| 72 |
+
cost = round(rng.uniform(8, 90), 2)
|
| 73 |
+
skus[f"SKU{i:04d}"] = SKU(
|
| 74 |
+
sku_id=f"SKU{i:04d}",
|
| 75 |
+
category=cat,
|
| 76 |
+
unit_price=round(cost * rng.uniform(1.5, 2.6), 2),
|
| 77 |
+
unit_cost=cost,
|
| 78 |
+
weight_kg=round(rng.uniform(0.2, 4.5), 2),
|
| 79 |
+
substitute_group=group,
|
| 80 |
+
return_rate=round(BASE_RETURN_RATE[cat] * rng.uniform(0.7, 1.3), 3),
|
| 81 |
+
)
|
| 82 |
+
return skus
|
| 83 |
+
|
| 84 |
+
|
| 85 |
+
def _make_inventory(rng: random.Random, nodes: dict[str, Node], skus: dict[str, SKU]) -> list[InventoryRecord]:
|
| 86 |
+
inv = []
|
| 87 |
+
fulfillment_nodes = [n for n in nodes.values() if n.node_type in ("central_dc", "regional_wh", "store", "cross_dock", "supplier")]
|
| 88 |
+
for node in fulfillment_nodes:
|
| 89 |
+
base_qty = {"central_dc": 800, "regional_wh": 300, "cross_dock": 150, "supplier": 5000, "store": 25}[node.node_type]
|
| 90 |
+
for sku in skus.values():
|
| 91 |
+
qty = max(0, int(rng.gauss(base_qty, base_qty * 0.35)))
|
| 92 |
+
accuracy = round(rng.uniform(0.88, 0.99), 3)
|
| 93 |
+
inv.append(InventoryRecord(node.node_id, sku.sku_id, qty, accuracy))
|
| 94 |
+
return inv
|
| 95 |
+
|
| 96 |
+
|
| 97 |
+
def _make_links(nodes: dict[str, Node]) -> list[TransportLink]:
|
| 98 |
+
links = []
|
| 99 |
+
sources = [n for n in nodes.values() if n.node_type in ("central_dc", "regional_wh", "cross_dock", "supplier", "store")]
|
| 100 |
+
dests = [n for n in nodes.values() if n.node_type in ("store", "regional_wh", "cross_dock", "return_center")]
|
| 101 |
+
for o in sources:
|
| 102 |
+
for d in dests:
|
| 103 |
+
if o.node_id == d.node_id:
|
| 104 |
+
continue
|
| 105 |
+
dist = round(_haversine_km(o.lat, o.lon, d.lat, d.lon), 1)
|
| 106 |
+
links.append(TransportLink(o.node_id, d.node_id, dist, "standard"))
|
| 107 |
+
links.append(TransportLink(o.node_id, d.node_id, dist, "express"))
|
| 108 |
+
return links
|
| 109 |
+
|
| 110 |
+
|
| 111 |
+
def _make_orders(rng: random.Random, nodes: dict[str, Node], skus: dict[str, SKU], n_orders: int, demand_multiplier: float) -> list[Order]:
|
| 112 |
+
stores = [n for n in nodes.values() if n.node_type == "store"]
|
| 113 |
+
sku_ids = list(skus.keys())
|
| 114 |
+
orders = []
|
| 115 |
+
n_orders = max(1, int(n_orders * demand_multiplier))
|
| 116 |
+
for i in range(n_orders):
|
| 117 |
+
demand_node = rng.choice(stores)
|
| 118 |
+
channel = rng.choice(["online"] * 7 + ["store"] * 3)
|
| 119 |
+
priority = rng.choice(["standard"] * 6 + ["premium"] * 3 + ["vip"] * 1)
|
| 120 |
+
n_lines = rng.randint(1, 3)
|
| 121 |
+
lines = []
|
| 122 |
+
for _ in range(n_lines):
|
| 123 |
+
sku_id = rng.choice(sku_ids)
|
| 124 |
+
lines.append(OrderLine(sku_id=sku_id, qty_requested=rng.randint(1, 3)))
|
| 125 |
+
orders.append(
|
| 126 |
+
Order(
|
| 127 |
+
order_id=f"ORD{i:05d}",
|
| 128 |
+
demand_node_id=demand_node.node_id,
|
| 129 |
+
channel=channel,
|
| 130 |
+
priority_class=priority,
|
| 131 |
+
lines=lines,
|
| 132 |
+
placed_at_hour=rng.randint(0, 23),
|
| 133 |
+
)
|
| 134 |
+
)
|
| 135 |
+
return orders
|
| 136 |
+
|
| 137 |
+
|
| 138 |
+
def _apply_scenario(rng: random.Random, scenario_key: str, network: Network) -> ScenarioEvent:
|
| 139 |
+
if scenario_key == "peak_season_surge":
|
| 140 |
+
event = ScenarioEvent(
|
| 141 |
+
"peak_season_surge",
|
| 142 |
+
"Demand spikes 65% while picking capacity stays flat across all fulfillment nodes",
|
| 143 |
+
affected_node_ids=list(network.nodes.keys()),
|
| 144 |
+
capacity_factor=1.0,
|
| 145 |
+
demand_multiplier=1.65,
|
| 146 |
+
)
|
| 147 |
+
network.orders = _make_orders(rng, network.nodes, network.skus, len(network.orders), 1.65)
|
| 148 |
+
elif scenario_key == "regional_stockout":
|
| 149 |
+
affected = "RWH-E"
|
| 150 |
+
for rec in network.inventory:
|
| 151 |
+
if rec.node_id == affected:
|
| 152 |
+
rec.on_hand_qty = int(rec.on_hand_qty * 0.08)
|
| 153 |
+
event = ScenarioEvent(
|
| 154 |
+
"regional_stockout",
|
| 155 |
+
f"{network.nodes[affected].name} inventory collapses to 8% of nominal, forcing ship-from-store",
|
| 156 |
+
affected_node_ids=[affected],
|
| 157 |
+
capacity_factor=1.0,
|
| 158 |
+
)
|
| 159 |
+
elif scenario_key == "high_return_category_wave":
|
| 160 |
+
for sku in network.skus.values():
|
| 161 |
+
if sku.category == "apparel":
|
| 162 |
+
sku.return_rate = round(min(0.55, sku.return_rate * 2.1), 3)
|
| 163 |
+
event = ScenarioEvent(
|
| 164 |
+
"high_return_category_wave",
|
| 165 |
+
"Apparel return rate more than doubles after a sizing-related quality issue",
|
| 166 |
+
affected_node_ids=["RET1", "REPAIR1"],
|
| 167 |
+
)
|
| 168 |
+
elif scenario_key == "capacity_constrained_dc":
|
| 169 |
+
network.nodes["DC1"].daily_pick_capacity = int(network.nodes["DC1"].daily_pick_capacity * 0.35)
|
| 170 |
+
event = ScenarioEvent(
|
| 171 |
+
"capacity_constrained_dc",
|
| 172 |
+
"Central DC picking capacity cut to 35% after a conveyor outage",
|
| 173 |
+
affected_node_ids=["DC1"],
|
| 174 |
+
capacity_factor=0.35,
|
| 175 |
+
)
|
| 176 |
+
elif scenario_key == "green_logistics_push":
|
| 177 |
+
event = ScenarioEvent(
|
| 178 |
+
"green_logistics_push",
|
| 179 |
+
"Corporate mandate to weight the carbon objective heavily in this week's allocation",
|
| 180 |
+
affected_node_ids=list(network.nodes.keys()),
|
| 181 |
+
)
|
| 182 |
+
else:
|
| 183 |
+
raise ValueError(f"Unknown scenario key: {scenario_key}")
|
| 184 |
+
return event
|
| 185 |
+
|
| 186 |
+
|
| 187 |
+
def generate_network(scenario_key: str, seed: int = 42, n_stores: int = 24, n_skus: int = 60, n_orders: int = 260) -> Network:
|
| 188 |
+
if scenario_key not in SCENARIOS:
|
| 189 |
+
raise ValueError(f"Unknown scenario '{scenario_key}'. Options: {list(SCENARIOS)}")
|
| 190 |
+
rng = random.Random(seed)
|
| 191 |
+
nodes = _make_nodes(rng, n_stores)
|
| 192 |
+
skus = _make_skus(rng, n_skus)
|
| 193 |
+
inventory = _make_inventory(rng, nodes, skus)
|
| 194 |
+
links = _make_links(nodes)
|
| 195 |
+
orders = _make_orders(rng, nodes, skus, n_orders, 1.0)
|
| 196 |
+
|
| 197 |
+
network = Network(
|
| 198 |
+
scenario_id=f"{scenario_key}_seed{seed}",
|
| 199 |
+
scenario_name=SCENARIOS[scenario_key],
|
| 200 |
+
description=SCENARIOS[scenario_key],
|
| 201 |
+
nodes=nodes,
|
| 202 |
+
skus=skus,
|
| 203 |
+
inventory=inventory,
|
| 204 |
+
links=links,
|
| 205 |
+
orders=orders,
|
| 206 |
+
events=[],
|
| 207 |
+
)
|
| 208 |
+
event = _apply_scenario(rng, scenario_key, network)
|
| 209 |
+
network.events.append(event)
|
| 210 |
+
return network
|
| 211 |
+
|
| 212 |
+
|
| 213 |
+
def list_scenarios() -> list[str]:
|
| 214 |
+
return list(SCENARIOS.keys())
|
space-bundle/src/omnitower/lns_solver.py
ADDED
|
@@ -0,0 +1,80 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Adaptive Large Neighborhood Search improvement over the greedy allocation.
|
| 2 |
+
|
| 3 |
+
The greedy marginal-cost allocator (`allocation.py`) is fast and scalable
|
| 4 |
+
but processes orders in a fixed sequence, so early orders can lock in
|
| 5 |
+
sources that would have been better reserved for later, higher-value
|
| 6 |
+
orders. This module repeatedly (a) destroys a random subset of already
|
| 7 |
+
allocated orders, releasing their inventory/capacity back into the pool,
|
| 8 |
+
and (b) re-inserts them in an order driven by priority and margin, keeping
|
| 9 |
+
the change only if total network cost improves — a lightweight ALNS loop
|
| 10 |
+
sized for interactive demo latency rather than production scale.
|
| 11 |
+
"""
|
| 12 |
+
|
| 13 |
+
from __future__ import annotations
|
| 14 |
+
|
| 15 |
+
import random
|
| 16 |
+
import copy
|
| 17 |
+
|
| 18 |
+
from .models import Network
|
| 19 |
+
from .allocation import AllocationState, build_state, allocate_order
|
| 20 |
+
from .network import build_graph
|
| 21 |
+
|
| 22 |
+
|
| 23 |
+
def _network_cost(network: Network, reports: dict[str, dict]) -> float:
|
| 24 |
+
total = 0.0
|
| 25 |
+
for report in reports.values():
|
| 26 |
+
for lr in report["line_reports"]:
|
| 27 |
+
total += lr.get("transport_cost_usd", 0) + lr.get("pick_cost_usd", 0) + lr.get("pack_cost_usd", 0)
|
| 28 |
+
if report["split_shipment"]:
|
| 29 |
+
total += 3.20
|
| 30 |
+
total += report["total_backordered_qty"] * 4.5
|
| 31 |
+
return total
|
| 32 |
+
|
| 33 |
+
|
| 34 |
+
def improve_allocation(network: Network, option: str = "economical", iterations: int = 25, destroy_fraction: float = 0.15, seed: int = 3) -> tuple[AllocationState, dict[str, dict], list[float]]:
|
| 35 |
+
rng = random.Random(seed)
|
| 36 |
+
graph = build_graph(network)
|
| 37 |
+
state = build_state(network)
|
| 38 |
+
reports = {}
|
| 39 |
+
order_by_id = {o.order_id: o for o in network.orders}
|
| 40 |
+
|
| 41 |
+
ordered = sorted(network.orders, key=lambda o: (-{"vip": 3, "premium": 2, "standard": 1}[o.priority_class], o.placed_at_hour))
|
| 42 |
+
for order in ordered:
|
| 43 |
+
reports[order.order_id] = allocate_order(network, order, option, state, graph)
|
| 44 |
+
|
| 45 |
+
history = [_network_cost(network, reports)]
|
| 46 |
+
order_ids = list(order_by_id.keys())
|
| 47 |
+
|
| 48 |
+
for _ in range(iterations):
|
| 49 |
+
k = max(1, int(len(order_ids) * destroy_fraction))
|
| 50 |
+
destroyed_ids = rng.sample(order_ids, k)
|
| 51 |
+
|
| 52 |
+
trial_state = AllocationState(inventory=dict(state.inventory), capacity=dict(state.capacity))
|
| 53 |
+
trial_reports = dict(reports)
|
| 54 |
+
trial_orders = {oid: copy.deepcopy(order_by_id[oid]) for oid in destroyed_ids}
|
| 55 |
+
|
| 56 |
+
for oid in destroyed_ids:
|
| 57 |
+
old_report = reports[oid]
|
| 58 |
+
for lr in old_report["line_reports"]:
|
| 59 |
+
trial_state.inventory[(lr["node_id"], lr["sku_id"])] = trial_state.inventory.get((lr["node_id"], lr["sku_id"]), 0) + lr["qty"]
|
| 60 |
+
trial_state.capacity[lr["node_id"]] = trial_state.capacity.get(lr["node_id"], 0) + lr["qty"]
|
| 61 |
+
|
| 62 |
+
reinsert_order_of_ids = sorted(
|
| 63 |
+
destroyed_ids,
|
| 64 |
+
key=lambda oid: -{"vip": 3, "premium": 2, "standard": 1}[order_by_id[oid].priority_class],
|
| 65 |
+
)
|
| 66 |
+
for oid in reinsert_order_of_ids:
|
| 67 |
+
trial_reports[oid] = allocate_order(network, trial_orders[oid], option, trial_state, graph)
|
| 68 |
+
|
| 69 |
+
new_cost = _network_cost(network, trial_reports)
|
| 70 |
+
if new_cost <= history[-1]:
|
| 71 |
+
state = trial_state
|
| 72 |
+
reports = trial_reports
|
| 73 |
+
for oid in destroyed_ids:
|
| 74 |
+
order_by_id[oid] = trial_orders[oid]
|
| 75 |
+
history.append(new_cost)
|
| 76 |
+
else:
|
| 77 |
+
history.append(history[-1])
|
| 78 |
+
|
| 79 |
+
network.orders = list(order_by_id.values())
|
| 80 |
+
return state, reports, history
|
space-bundle/src/omnitower/metrics.py
ADDED
|
@@ -0,0 +1,94 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Network-level KPI computation."""
|
| 2 |
+
|
| 3 |
+
from __future__ import annotations
|
| 4 |
+
|
| 5 |
+
from dataclasses import dataclass, asdict
|
| 6 |
+
|
| 7 |
+
from .models import Network
|
| 8 |
+
from .constants import DEFAULT_MARGIN_RATE, BACKORDER_PENALTY_USD, CANCELLATION_PENALTY_USD, WORKING_CAPITAL_DAYS_HELD
|
| 9 |
+
|
| 10 |
+
|
| 11 |
+
@dataclass
|
| 12 |
+
class NetworkMetrics:
|
| 13 |
+
gross_margin_usd: float
|
| 14 |
+
fill_rate: float
|
| 15 |
+
on_time_sla_rate: float
|
| 16 |
+
n_split_shipments: int
|
| 17 |
+
split_shipment_rate: float
|
| 18 |
+
picking_workload_units: int
|
| 19 |
+
return_handling_cost_usd: float
|
| 20 |
+
total_carbon_kg: float
|
| 21 |
+
working_capital_usd: float
|
| 22 |
+
n_orders: int
|
| 23 |
+
n_backordered_orders: int
|
| 24 |
+
|
| 25 |
+
def to_dict(self) -> dict:
|
| 26 |
+
return asdict(self)
|
| 27 |
+
|
| 28 |
+
|
| 29 |
+
def compute_metrics(network: Network, reports: dict[str, dict], return_summary: dict | None = None, sla_hours: float = 48.0) -> NetworkMetrics:
|
| 30 |
+
gross_margin = 0.0
|
| 31 |
+
total_requested = 0
|
| 32 |
+
total_fulfilled = 0
|
| 33 |
+
n_split = 0
|
| 34 |
+
picking_units = 0
|
| 35 |
+
total_carbon = 0.0
|
| 36 |
+
on_time = 0
|
| 37 |
+
n_orders_with_lines = 0
|
| 38 |
+
n_backordered_orders = 0
|
| 39 |
+
|
| 40 |
+
order_by_id = {o.order_id: o for o in network.orders}
|
| 41 |
+
|
| 42 |
+
for order_id, report in reports.items():
|
| 43 |
+
order = order_by_id.get(order_id)
|
| 44 |
+
if order is None:
|
| 45 |
+
continue
|
| 46 |
+
n_orders_with_lines += 1
|
| 47 |
+
if report["split_shipment"]:
|
| 48 |
+
n_split += 1
|
| 49 |
+
max_lead = 0.0
|
| 50 |
+
for lr in report["line_reports"]:
|
| 51 |
+
sku = network.skus.get(lr["sku_id"])
|
| 52 |
+
unit_price = sku.unit_price if sku else 0.0
|
| 53 |
+
unit_cost = sku.unit_cost if sku else unit_price * (1 - DEFAULT_MARGIN_RATE)
|
| 54 |
+
gross_margin += (unit_price - unit_cost) * lr["qty"]
|
| 55 |
+
gross_margin -= lr.get("transport_cost_usd", 0) + lr.get("pick_cost_usd", 0) + lr.get("pack_cost_usd", 0)
|
| 56 |
+
picking_units += lr["qty"]
|
| 57 |
+
total_carbon += lr.get("carbon_kg", 0.0)
|
| 58 |
+
max_lead = max(max_lead, lr.get("lead_time_hours", 0.0))
|
| 59 |
+
if max_lead and max_lead <= sla_hours:
|
| 60 |
+
on_time += 1
|
| 61 |
+
if report["total_backordered_qty"] > 0:
|
| 62 |
+
gross_margin -= report["total_backordered_qty"] * BACKORDER_PENALTY_USD
|
| 63 |
+
n_backordered_orders += 1
|
| 64 |
+
total_requested += sum(l.qty_requested for l in order.lines)
|
| 65 |
+
total_fulfilled += sum(l.qty_fulfilled for l in order.lines)
|
| 66 |
+
|
| 67 |
+
return_cost = return_summary["total_handling_cost_usd"] if return_summary else 0.0
|
| 68 |
+
if return_summary:
|
| 69 |
+
gross_margin -= return_cost
|
| 70 |
+
gross_margin += return_summary.get("total_recovered_value_usd", 0.0)
|
| 71 |
+
|
| 72 |
+
working_capital = 0.0
|
| 73 |
+
for rec in network.inventory:
|
| 74 |
+
node = network.nodes.get(rec.node_id)
|
| 75 |
+
sku = network.skus.get(rec.sku_id)
|
| 76 |
+
if not node or not sku:
|
| 77 |
+
continue
|
| 78 |
+
days_held = WORKING_CAPITAL_DAYS_HELD.get(node.node_type, 10)
|
| 79 |
+
working_capital += rec.on_hand_qty * sku.unit_cost * (days_held / 365.0) * 12
|
| 80 |
+
|
| 81 |
+
n_orders = max(1, n_orders_with_lines)
|
| 82 |
+
return NetworkMetrics(
|
| 83 |
+
gross_margin_usd=round(gross_margin, 2),
|
| 84 |
+
fill_rate=round(total_fulfilled / total_requested, 4) if total_requested else 1.0,
|
| 85 |
+
on_time_sla_rate=round(on_time / n_orders, 4),
|
| 86 |
+
n_split_shipments=n_split,
|
| 87 |
+
split_shipment_rate=round(n_split / n_orders, 4),
|
| 88 |
+
picking_workload_units=picking_units,
|
| 89 |
+
return_handling_cost_usd=round(return_cost, 2),
|
| 90 |
+
total_carbon_kg=round(total_carbon, 2),
|
| 91 |
+
working_capital_usd=round(working_capital, 2),
|
| 92 |
+
n_orders=n_orders_with_lines,
|
| 93 |
+
n_backordered_orders=n_backordered_orders,
|
| 94 |
+
)
|
space-bundle/src/omnitower/models.py
ADDED
|
@@ -0,0 +1,118 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Domain model for the omnichannel fulfillment and returns network."""
|
| 2 |
+
|
| 3 |
+
from __future__ import annotations
|
| 4 |
+
|
| 5 |
+
from dataclasses import dataclass, field, asdict
|
| 6 |
+
from typing import Optional
|
| 7 |
+
|
| 8 |
+
|
| 9 |
+
@dataclass
|
| 10 |
+
class Node:
|
| 11 |
+
node_id: str
|
| 12 |
+
node_type: str
|
| 13 |
+
name: str
|
| 14 |
+
lat: float
|
| 15 |
+
lon: float
|
| 16 |
+
daily_pick_capacity: int = 800
|
| 17 |
+
picking_cost_multiplier: float = 1.0
|
| 18 |
+
|
| 19 |
+
|
| 20 |
+
@dataclass
|
| 21 |
+
class SKU:
|
| 22 |
+
sku_id: str
|
| 23 |
+
category: str
|
| 24 |
+
unit_price: float
|
| 25 |
+
unit_cost: float
|
| 26 |
+
weight_kg: float
|
| 27 |
+
substitute_group: str
|
| 28 |
+
return_rate: float
|
| 29 |
+
resalable: bool = True
|
| 30 |
+
|
| 31 |
+
|
| 32 |
+
@dataclass
|
| 33 |
+
class InventoryRecord:
|
| 34 |
+
node_id: str
|
| 35 |
+
sku_id: str
|
| 36 |
+
on_hand_qty: int
|
| 37 |
+
accuracy: float = 0.94 # fraction of on_hand_qty that is actually pickable
|
| 38 |
+
|
| 39 |
+
|
| 40 |
+
@dataclass
|
| 41 |
+
class TransportLink:
|
| 42 |
+
origin_id: str
|
| 43 |
+
dest_id: str
|
| 44 |
+
distance_km: float
|
| 45 |
+
ship_mode: str = "standard"
|
| 46 |
+
|
| 47 |
+
|
| 48 |
+
@dataclass
|
| 49 |
+
class OrderLine:
|
| 50 |
+
sku_id: str
|
| 51 |
+
qty_requested: int
|
| 52 |
+
qty_fulfilled: int = 0
|
| 53 |
+
substituted_sku_id: Optional[str] = None
|
| 54 |
+
source_node_id: Optional[str] = None
|
| 55 |
+
backordered_qty: int = 0
|
| 56 |
+
cancelled_qty: int = 0
|
| 57 |
+
|
| 58 |
+
|
| 59 |
+
@dataclass
|
| 60 |
+
class Order:
|
| 61 |
+
order_id: str
|
| 62 |
+
demand_node_id: str
|
| 63 |
+
channel: str # "online" or "store"
|
| 64 |
+
priority_class: str
|
| 65 |
+
lines: list[OrderLine]
|
| 66 |
+
placed_at_hour: int
|
| 67 |
+
accepted: bool = True
|
| 68 |
+
split_shipment: bool = False
|
| 69 |
+
chosen_delivery_option: str = "economical"
|
| 70 |
+
|
| 71 |
+
|
| 72 |
+
@dataclass
|
| 73 |
+
class ReturnItem:
|
| 74 |
+
return_id: str
|
| 75 |
+
order_id: str
|
| 76 |
+
sku_id: str
|
| 77 |
+
qty: int
|
| 78 |
+
quality_score: float
|
| 79 |
+
origin_node_id: str
|
| 80 |
+
disposition: str = "" # restock_store, restock_dc, repair, recycle, dispose
|
| 81 |
+
resold: bool = False
|
| 82 |
+
|
| 83 |
+
|
| 84 |
+
@dataclass
|
| 85 |
+
class ScenarioEvent:
|
| 86 |
+
event_type: str
|
| 87 |
+
description: str
|
| 88 |
+
affected_node_ids: list[str] = field(default_factory=list)
|
| 89 |
+
capacity_factor: float = 1.0
|
| 90 |
+
demand_multiplier: float = 1.0
|
| 91 |
+
|
| 92 |
+
|
| 93 |
+
@dataclass
|
| 94 |
+
class Network:
|
| 95 |
+
scenario_id: str
|
| 96 |
+
scenario_name: str
|
| 97 |
+
description: str
|
| 98 |
+
nodes: dict[str, Node]
|
| 99 |
+
skus: dict[str, SKU]
|
| 100 |
+
inventory: list[InventoryRecord]
|
| 101 |
+
links: list[TransportLink]
|
| 102 |
+
orders: list[Order]
|
| 103 |
+
events: list[ScenarioEvent]
|
| 104 |
+
|
| 105 |
+
def to_dict(self) -> dict:
|
| 106 |
+
return {
|
| 107 |
+
"scenario_id": self.scenario_id,
|
| 108 |
+
"scenario_name": self.scenario_name,
|
| 109 |
+
"description": self.description,
|
| 110 |
+
"nodes": {k: asdict(v) for k, v in self.nodes.items()},
|
| 111 |
+
"skus": {k: asdict(v) for k, v in self.skus.items()},
|
| 112 |
+
"inventory": [asdict(i) for i in self.inventory],
|
| 113 |
+
"links": [asdict(l) for l in self.links],
|
| 114 |
+
"orders": [
|
| 115 |
+
{**asdict(o), "lines": [asdict(ln) for ln in o.lines]} for o in self.orders
|
| 116 |
+
],
|
| 117 |
+
"events": [asdict(e) for e in self.events],
|
| 118 |
+
}
|
space-bundle/src/omnitower/network.py
ADDED
|
@@ -0,0 +1,68 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Graph utilities: distance lookup and candidate-source ranking.
|
| 2 |
+
|
| 3 |
+
A lightweight NetworkX directed graph indexes transport links so the
|
| 4 |
+
allocation and routing modules can query distance / mode without
|
| 5 |
+
re-scanning the flat link list on every call.
|
| 6 |
+
"""
|
| 7 |
+
|
| 8 |
+
from __future__ import annotations
|
| 9 |
+
|
| 10 |
+
import networkx as nx
|
| 11 |
+
|
| 12 |
+
from .models import Network
|
| 13 |
+
from .constants import (
|
| 14 |
+
COST_PER_KM_STANDARD_USD,
|
| 15 |
+
COST_PER_KM_EXPRESS_USD,
|
| 16 |
+
CARBON_KG_PER_KM_STANDARD,
|
| 17 |
+
CARBON_KG_PER_KM_EXPRESS,
|
| 18 |
+
CARBON_KG_PER_KM_GREEN,
|
| 19 |
+
)
|
| 20 |
+
|
| 21 |
+
FULFILLMENT_NODE_TYPES = ("central_dc", "regional_wh", "cross_dock", "supplier", "store")
|
| 22 |
+
|
| 23 |
+
|
| 24 |
+
def build_graph(network: Network) -> nx.DiGraph:
|
| 25 |
+
graph = nx.DiGraph()
|
| 26 |
+
for node in network.nodes.values():
|
| 27 |
+
graph.add_node(node.node_id, node_type=node.node_type, capacity=node.daily_pick_capacity)
|
| 28 |
+
for link in network.links:
|
| 29 |
+
graph.add_edge(
|
| 30 |
+
link.origin_id,
|
| 31 |
+
link.dest_id,
|
| 32 |
+
**{f"distance_km_{link.ship_mode}": link.distance_km},
|
| 33 |
+
)
|
| 34 |
+
return graph
|
| 35 |
+
|
| 36 |
+
|
| 37 |
+
def distance_km(graph: nx.DiGraph, origin_id: str, dest_id: str) -> float:
|
| 38 |
+
if origin_id == dest_id:
|
| 39 |
+
return 0.0
|
| 40 |
+
data = graph.get_edge_data(origin_id, dest_id, default=None)
|
| 41 |
+
if data is None:
|
| 42 |
+
return float("inf")
|
| 43 |
+
for key, value in data.items():
|
| 44 |
+
if key.startswith("distance_km_"):
|
| 45 |
+
return value
|
| 46 |
+
return float("inf")
|
| 47 |
+
|
| 48 |
+
|
| 49 |
+
def transport_cost(distance: float, mode: str) -> float:
|
| 50 |
+
if distance == 0:
|
| 51 |
+
return 0.0
|
| 52 |
+
rate = COST_PER_KM_EXPRESS_USD if mode == "express" else COST_PER_KM_STANDARD_USD
|
| 53 |
+
return distance * rate
|
| 54 |
+
|
| 55 |
+
|
| 56 |
+
def carbon_kg(distance: float, mode: str) -> float:
|
| 57 |
+
if distance == 0:
|
| 58 |
+
return 0.0
|
| 59 |
+
factor = {
|
| 60 |
+
"express": CARBON_KG_PER_KM_EXPRESS,
|
| 61 |
+
"green": CARBON_KG_PER_KM_GREEN,
|
| 62 |
+
}.get(mode, CARBON_KG_PER_KM_STANDARD)
|
| 63 |
+
return distance * factor
|
| 64 |
+
|
| 65 |
+
|
| 66 |
+
def candidate_sources(network: Network, demand_node_id: str) -> list[str]:
|
| 67 |
+
"""All nodes that can physically fulfill an order for a given demand node."""
|
| 68 |
+
return [n.node_id for n in network.nodes.values() if n.node_type in FULFILLMENT_NODE_TYPES]
|
space-bundle/src/omnitower/omnitower/__init__.py
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Omnichannel Fulfillment and Returns Control Tower — core optimization engine."""
|
| 2 |
+
|
| 3 |
+
__version__ = "1.0.0"
|
space-bundle/src/omnitower/omnitower/admission.py
ADDED
|
@@ -0,0 +1,62 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Dynamic admission control.
|
| 2 |
+
|
| 3 |
+
Approximates a bid-price control policy: rather than a static allocation
|
| 4 |
+
rule, each incoming order is scored against the *current* scarcity of the
|
| 5 |
+
SKUs it requests (remaining pooled inventory vs. remaining forecast demand
|
| 6 |
+
for the rest of the horizon). Orders that would consume disproportionately
|
| 7 |
+
scarce stock for a low-margin / low-priority order are queued as
|
| 8 |
+
backorders instead of being admitted immediately, protecting inventory for
|
| 9 |
+
higher-value demand still expected to arrive.
|
| 10 |
+
"""
|
| 11 |
+
|
| 12 |
+
from __future__ import annotations
|
| 13 |
+
|
| 14 |
+
from dataclasses import dataclass
|
| 15 |
+
|
| 16 |
+
from .models import Network, Order
|
| 17 |
+
from .allocation import AllocationState
|
| 18 |
+
from .constants import DEFAULT_MARGIN_RATE, BACKORDER_PENALTY_USD
|
| 19 |
+
|
| 20 |
+
PRIORITY_WEIGHT = {"vip": 1.6, "premium": 1.25, "standard": 1.0}
|
| 21 |
+
|
| 22 |
+
|
| 23 |
+
@dataclass
|
| 24 |
+
class AdmissionDecision:
|
| 25 |
+
order_id: str
|
| 26 |
+
admitted: bool
|
| 27 |
+
reason: str
|
| 28 |
+
scarcity_score: float
|
| 29 |
+
|
| 30 |
+
|
| 31 |
+
def _scarcity_score(network: Network, state: AllocationState, order: Order, remaining_demand_factor: float) -> float:
|
| 32 |
+
scores = []
|
| 33 |
+
for line in order.lines:
|
| 34 |
+
total_remaining = sum(qty for (node, sku), qty in state.inventory.items() if sku == line.sku_id)
|
| 35 |
+
forecast_need = max(1.0, total_remaining * 0.0 + remaining_demand_factor * line.qty_requested * 6.0)
|
| 36 |
+
if total_remaining <= 0:
|
| 37 |
+
scores.append(1.0)
|
| 38 |
+
else:
|
| 39 |
+
scores.append(min(1.0, forecast_need / (total_remaining + forecast_need)))
|
| 40 |
+
return sum(scores) / max(1, len(scores))
|
| 41 |
+
|
| 42 |
+
|
| 43 |
+
def evaluate_admission(
|
| 44 |
+
network: Network,
|
| 45 |
+
state: AllocationState,
|
| 46 |
+
order: Order,
|
| 47 |
+
remaining_demand_factor: float = 0.5,
|
| 48 |
+
scarcity_threshold: float = 0.82,
|
| 49 |
+
) -> AdmissionDecision:
|
| 50 |
+
scarcity = _scarcity_score(network, state, order, remaining_demand_factor)
|
| 51 |
+
priority_weight = PRIORITY_WEIGHT.get(order.priority_class, 1.0)
|
| 52 |
+
effective_threshold = scarcity_threshold * priority_weight
|
| 53 |
+
order_value = sum(network.skus[l.sku_id].unit_price * l.qty_requested for l in order.lines if l.sku_id in network.skus)
|
| 54 |
+
margin_value = order_value * DEFAULT_MARGIN_RATE
|
| 55 |
+
|
| 56 |
+
if scarcity < effective_threshold or margin_value > BACKORDER_PENALTY_USD * 20:
|
| 57 |
+
return AdmissionDecision(order.order_id, True, "accepted: inventory scarcity within threshold for priority class", round(scarcity, 3))
|
| 58 |
+
return AdmissionDecision(order.order_id, False, "deferred to backorder: scarce stock reserved for expected higher-value demand", round(scarcity, 3))
|
| 59 |
+
|
| 60 |
+
|
| 61 |
+
def evaluate_all(network: Network, state: AllocationState, remaining_demand_factor: float = 0.5) -> list[AdmissionDecision]:
|
| 62 |
+
return [evaluate_admission(network, state, order, remaining_demand_factor) for order in network.orders]
|
space-bundle/src/omnitower/omnitower/allocation.py
ADDED
|
@@ -0,0 +1,156 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Order allocation optimizer: Inventory Allocation + Order Fulfillment.
|
| 2 |
+
|
| 3 |
+
Implements the "Greedy Marginal Cost" scalable heuristic referenced in the
|
| 4 |
+
project brief: for every order line, candidate fulfillment nodes are ranked
|
| 5 |
+
by the marginal cost of serving that unit from that node (transport +
|
| 6 |
+
picking + packing, weighted by the chosen delivery objective), subject to
|
| 7 |
+
live inventory and daily picking-capacity pools that are decremented as the
|
| 8 |
+
order stream is processed. Split shipments and ship-from-store are native
|
| 9 |
+
outcomes of the ranking rather than a separate rule.
|
| 10 |
+
"""
|
| 11 |
+
|
| 12 |
+
from __future__ import annotations
|
| 13 |
+
|
| 14 |
+
from dataclasses import dataclass, field
|
| 15 |
+
|
| 16 |
+
from .models import Network, Order, OrderLine
|
| 17 |
+
from .network import build_graph, distance_km, transport_cost, carbon_kg, candidate_sources
|
| 18 |
+
from .constants import (
|
| 19 |
+
COST_PER_PICK_USD,
|
| 20 |
+
COST_PER_PACK_USD,
|
| 21 |
+
COST_PER_SPLIT_SHIPMENT_USD,
|
| 22 |
+
LEAD_TIME_HOURS_PER_100KM_STANDARD,
|
| 23 |
+
LEAD_TIME_HOURS_PER_100KM_EXPRESS,
|
| 24 |
+
LEAD_TIME_HOURS_PER_100KM_GREEN,
|
| 25 |
+
)
|
| 26 |
+
|
| 27 |
+
OBJECTIVE_WEIGHTS = {
|
| 28 |
+
# (cost_weight, time_weight, carbon_weight)
|
| 29 |
+
"fast": (0.15, 0.75, 0.10),
|
| 30 |
+
"economical": (0.75, 0.10, 0.15),
|
| 31 |
+
"green": (0.15, 0.10, 0.75),
|
| 32 |
+
}
|
| 33 |
+
|
| 34 |
+
|
| 35 |
+
@dataclass
|
| 36 |
+
class AllocationState:
|
| 37 |
+
inventory: dict[tuple[str, str], float]
|
| 38 |
+
capacity: dict[str, float]
|
| 39 |
+
|
| 40 |
+
|
| 41 |
+
def build_state(network: Network) -> AllocationState:
|
| 42 |
+
inv = {}
|
| 43 |
+
for rec in network.inventory:
|
| 44 |
+
inv[(rec.node_id, rec.sku_id)] = rec.on_hand_qty * rec.accuracy
|
| 45 |
+
cap = {n.node_id: float(n.daily_pick_capacity) for n in network.nodes.values()}
|
| 46 |
+
return AllocationState(inventory=inv, capacity=cap)
|
| 47 |
+
|
| 48 |
+
|
| 49 |
+
def _mode_for_option(option: str) -> str:
|
| 50 |
+
return {"fast": "express", "economical": "standard", "green": "green"}[option]
|
| 51 |
+
|
| 52 |
+
|
| 53 |
+
def _lead_time_hours(distance: float, mode: str) -> float:
|
| 54 |
+
rate = {
|
| 55 |
+
"express": LEAD_TIME_HOURS_PER_100KM_EXPRESS,
|
| 56 |
+
"green": LEAD_TIME_HOURS_PER_100KM_GREEN,
|
| 57 |
+
}.get(mode, LEAD_TIME_HOURS_PER_100KM_STANDARD)
|
| 58 |
+
return 2.0 + (distance / 100.0) * rate
|
| 59 |
+
|
| 60 |
+
|
| 61 |
+
def _score_source(graph, node, sku_id, demand_node_id, node_meta, option, state: AllocationState) -> tuple[float, dict]:
|
| 62 |
+
dist = distance_km(graph, node, demand_node_id)
|
| 63 |
+
if dist == float("inf"):
|
| 64 |
+
return float("inf"), {}
|
| 65 |
+
mode = _mode_for_option(option)
|
| 66 |
+
link_mode = "express" if mode == "express" else "standard"
|
| 67 |
+
t_cost = transport_cost(dist, link_mode)
|
| 68 |
+
pick_cost = COST_PER_PICK_USD * node_meta.picking_cost_multiplier
|
| 69 |
+
pack_cost = COST_PER_PACK_USD
|
| 70 |
+
lead_hours = _lead_time_hours(dist, mode)
|
| 71 |
+
carbon = carbon_kg(dist, mode)
|
| 72 |
+
cw, tw, cbw = OBJECTIVE_WEIGHTS[option]
|
| 73 |
+
# normalize roughly to comparable scales before weighting
|
| 74 |
+
score = cw * (t_cost + pick_cost + pack_cost) + tw * lead_hours + cbw * (carbon * 0.5)
|
| 75 |
+
breakdown = {
|
| 76 |
+
"distance_km": round(dist, 1),
|
| 77 |
+
"transport_cost_usd": round(t_cost, 2),
|
| 78 |
+
"pick_cost_usd": round(pick_cost, 2),
|
| 79 |
+
"pack_cost_usd": round(pack_cost, 2),
|
| 80 |
+
"lead_time_hours": round(lead_hours, 1),
|
| 81 |
+
"carbon_kg": round(carbon, 2),
|
| 82 |
+
"ship_mode": mode,
|
| 83 |
+
}
|
| 84 |
+
return score, breakdown
|
| 85 |
+
|
| 86 |
+
|
| 87 |
+
def _find_substitute(network: Network, sku_id: str, state: AllocationState, source_pool: list[str]) -> str | None:
|
| 88 |
+
sku = network.skus[sku_id]
|
| 89 |
+
for other in network.skus.values():
|
| 90 |
+
if other.sku_id == sku_id or other.substitute_group != sku.substitute_group:
|
| 91 |
+
continue
|
| 92 |
+
if any(state.inventory.get((n, other.sku_id), 0) >= 1 for n in source_pool):
|
| 93 |
+
return other.sku_id
|
| 94 |
+
return None
|
| 95 |
+
|
| 96 |
+
|
| 97 |
+
def allocate_order(network: Network, order: Order, option: str, state: AllocationState, graph=None) -> dict:
|
| 98 |
+
graph = graph or build_graph(network)
|
| 99 |
+
sources = candidate_sources(network, order.demand_node_id, exclude_demand_node=(order.channel == "online"))
|
| 100 |
+
used_nodes: set[str] = set()
|
| 101 |
+
line_reports = []
|
| 102 |
+
|
| 103 |
+
for line in order.lines:
|
| 104 |
+
remaining = line.qty_requested
|
| 105 |
+
line.qty_fulfilled = 0
|
| 106 |
+
while remaining > 0:
|
| 107 |
+
ranked = []
|
| 108 |
+
for node_id in sources:
|
| 109 |
+
node_meta = network.nodes[node_id]
|
| 110 |
+
avail = state.inventory.get((node_id, line.sku_id), 0)
|
| 111 |
+
cap = state.capacity.get(node_id, 0)
|
| 112 |
+
if avail < 1 or cap < 1:
|
| 113 |
+
continue
|
| 114 |
+
score, breakdown = _score_source(graph, node_id, line.sku_id, order.demand_node_id, node_meta, option, state)
|
| 115 |
+
if score == float("inf"):
|
| 116 |
+
continue
|
| 117 |
+
ranked.append((score, node_id, breakdown))
|
| 118 |
+
if not ranked:
|
| 119 |
+
substitute = _find_substitute(network, line.sku_id, state, sources)
|
| 120 |
+
if substitute and line.substituted_sku_id is None:
|
| 121 |
+
line.substituted_sku_id = substitute
|
| 122 |
+
line.sku_id = substitute
|
| 123 |
+
continue
|
| 124 |
+
break
|
| 125 |
+
ranked.sort(key=lambda x: x[0])
|
| 126 |
+
score, node_id, breakdown = ranked[0]
|
| 127 |
+
take = min(remaining, state.inventory[(node_id, line.sku_id)], state.capacity[node_id])
|
| 128 |
+
take = max(1, int(take))
|
| 129 |
+
state.inventory[(node_id, line.sku_id)] -= take
|
| 130 |
+
state.capacity[node_id] -= take
|
| 131 |
+
line.qty_fulfilled += take
|
| 132 |
+
line.source_node_id = node_id
|
| 133 |
+
used_nodes.add(node_id)
|
| 134 |
+
remaining -= take
|
| 135 |
+
line_reports.append({"sku_id": line.sku_id, "node_id": node_id, "qty": take, **breakdown})
|
| 136 |
+
line.backordered_qty = remaining
|
| 137 |
+
|
| 138 |
+
order.split_shipment = len(used_nodes) > 1
|
| 139 |
+
order.chosen_delivery_option = option
|
| 140 |
+
total_backorder = sum(l.backordered_qty for l in order.lines)
|
| 141 |
+
order.accepted = total_backorder < sum(l.qty_requested for l in order.lines)
|
| 142 |
+
return {
|
| 143 |
+
"order_id": order.order_id,
|
| 144 |
+
"delivery_option": option,
|
| 145 |
+
"split_shipment": order.split_shipment,
|
| 146 |
+
"nodes_used": sorted(used_nodes),
|
| 147 |
+
"line_reports": line_reports,
|
| 148 |
+
"total_backordered_qty": total_backorder,
|
| 149 |
+
}
|
| 150 |
+
|
| 151 |
+
|
| 152 |
+
def allocate_all(network: Network, option: str = "economical") -> tuple[AllocationState, list[dict]]:
|
| 153 |
+
state = build_state(network)
|
| 154 |
+
graph = build_graph(network)
|
| 155 |
+
reports = [allocate_order(network, order, option, state, graph) for order in network.orders]
|
| 156 |
+
return state, reports
|
space-bundle/src/omnitower/omnitower/constants.py
ADDED
|
@@ -0,0 +1,59 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Shared constants and cost coefficients for the control tower."""
|
| 2 |
+
|
| 3 |
+
from __future__ import annotations
|
| 4 |
+
|
| 5 |
+
NODE_TYPES = [
|
| 6 |
+
"store",
|
| 7 |
+
"central_dc",
|
| 8 |
+
"regional_wh",
|
| 9 |
+
"supplier",
|
| 10 |
+
"cross_dock",
|
| 11 |
+
"return_center",
|
| 12 |
+
"repair_center",
|
| 13 |
+
"recycle_center",
|
| 14 |
+
]
|
| 15 |
+
|
| 16 |
+
SHIP_MODE_STANDARD = "standard"
|
| 17 |
+
SHIP_MODE_EXPRESS = "express"
|
| 18 |
+
|
| 19 |
+
DELIVERY_OPTIONS = ["fast", "economical", "green"]
|
| 20 |
+
|
| 21 |
+
# Approximate cost / emission coefficients used across the demo scenarios.
|
| 22 |
+
COST_PER_KM_STANDARD_USD = 0.055
|
| 23 |
+
COST_PER_KM_EXPRESS_USD = 0.145
|
| 24 |
+
COST_PER_PICK_USD = 1.35
|
| 25 |
+
COST_PER_PACK_USD = 0.85
|
| 26 |
+
COST_PER_SPLIT_SHIPMENT_USD = 3.20
|
| 27 |
+
CARBON_KG_PER_KM_STANDARD = 0.18
|
| 28 |
+
CARBON_KG_PER_KM_EXPRESS = 0.34
|
| 29 |
+
CARBON_KG_PER_KM_GREEN = 0.07 # consolidated / low-carbon linehaul
|
| 30 |
+
|
| 31 |
+
LEAD_TIME_HOURS_PER_100KM_STANDARD = 2.4
|
| 32 |
+
LEAD_TIME_HOURS_PER_100KM_EXPRESS = 0.9
|
| 33 |
+
LEAD_TIME_HOURS_PER_100KM_GREEN = 3.6
|
| 34 |
+
|
| 35 |
+
RETURN_HANDLING_COST_USD = {
|
| 36 |
+
"restock_store": 1.10,
|
| 37 |
+
"restock_dc": 1.60,
|
| 38 |
+
"repair": 6.50,
|
| 39 |
+
"recycle": 2.20,
|
| 40 |
+
"dispose": 3.00,
|
| 41 |
+
}
|
| 42 |
+
|
| 43 |
+
RETURN_RECOVERY_VALUE_FACTOR = {
|
| 44 |
+
"restock_store": 0.92,
|
| 45 |
+
"restock_dc": 0.88,
|
| 46 |
+
"repair": 0.55,
|
| 47 |
+
"recycle": 0.06,
|
| 48 |
+
"dispose": 0.0,
|
| 49 |
+
}
|
| 50 |
+
|
| 51 |
+
DEFAULT_MARGIN_RATE = 0.34
|
| 52 |
+
BACKORDER_PENALTY_USD = 4.50
|
| 53 |
+
CANCELLATION_PENALTY_USD = 9.00
|
| 54 |
+
WORKING_CAPITAL_DAYS_HELD = {
|
| 55 |
+
"central_dc": 21,
|
| 56 |
+
"regional_wh": 14,
|
| 57 |
+
"store": 9,
|
| 58 |
+
"cross_dock": 2,
|
| 59 |
+
}
|
space-bundle/src/omnitower/omnitower/generator.py
ADDED
|
@@ -0,0 +1,214 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Synthetic omnichannel network and demand scenario generator.
|
| 2 |
+
|
| 3 |
+
Builds a reproducible multi-echelon network (central DC, regional warehouses,
|
| 4 |
+
stores, suppliers, cross-dock, return/repair/recycle centers), a SKU
|
| 5 |
+
catalog with substitute groups, noisy inventory, and a day's worth of
|
| 6 |
+
multi-line orders, then applies one of the demo scenario archetypes.
|
| 7 |
+
"""
|
| 8 |
+
|
| 9 |
+
from __future__ import annotations
|
| 10 |
+
|
| 11 |
+
import random
|
| 12 |
+
from math import radians, sin, cos, asin, sqrt
|
| 13 |
+
|
| 14 |
+
from .models import Node, SKU, InventoryRecord, TransportLink, Order, OrderLine, ScenarioEvent, Network
|
| 15 |
+
|
| 16 |
+
CATEGORIES = ["apparel", "footwear", "electronics_accessory", "home_goods", "beauty"]
|
| 17 |
+
SUBSTITUTE_GROUPS = {
|
| 18 |
+
"apparel": ["APP-A", "APP-B"],
|
| 19 |
+
"footwear": ["SHOE-A"],
|
| 20 |
+
"electronics_accessory": ["ELEC-A"],
|
| 21 |
+
"home_goods": ["HOME-A", "HOME-B"],
|
| 22 |
+
"beauty": ["BEAUTY-A"],
|
| 23 |
+
}
|
| 24 |
+
BASE_RETURN_RATE = {
|
| 25 |
+
"apparel": 0.22,
|
| 26 |
+
"footwear": 0.17,
|
| 27 |
+
"electronics_accessory": 0.06,
|
| 28 |
+
"home_goods": 0.05,
|
| 29 |
+
"beauty": 0.03,
|
| 30 |
+
}
|
| 31 |
+
|
| 32 |
+
SCENARIOS = {
|
| 33 |
+
"peak_season_surge": "Peak-season demand surge with tight picking capacity",
|
| 34 |
+
"regional_stockout": "Regional warehouse stockout forcing ship-from-store",
|
| 35 |
+
"high_return_category_wave": "Apparel high-return wave stressing reverse logistics",
|
| 36 |
+
"capacity_constrained_dc": "Central DC capacity outage shifting flow to regional network",
|
| 37 |
+
"green_logistics_push": "Corporate mandate to minimize carbon emissions this week",
|
| 38 |
+
}
|
| 39 |
+
|
| 40 |
+
|
| 41 |
+
def _haversine_km(lat1: float, lon1: float, lat2: float, lon2: float) -> float:
|
| 42 |
+
r = 6371.0
|
| 43 |
+
dlat, dlon = radians(lat2 - lat1), radians(lon2 - lon1)
|
| 44 |
+
a = sin(dlat / 2) ** 2 + cos(radians(lat1)) * cos(radians(lat2)) * sin(dlon / 2) ** 2
|
| 45 |
+
return 2 * r * asin(sqrt(a))
|
| 46 |
+
|
| 47 |
+
|
| 48 |
+
def _make_nodes(rng: random.Random, n_stores: int) -> dict[str, Node]:
|
| 49 |
+
nodes: dict[str, Node] = {}
|
| 50 |
+
nodes["DC1"] = Node("DC1", "central_dc", "Central Distribution Center", 39.10, -94.58, daily_pick_capacity=6000, picking_cost_multiplier=0.85)
|
| 51 |
+
nodes["RWH-E"] = Node("RWH-E", "regional_wh", "Regional Warehouse East", 40.71, -74.01, daily_pick_capacity=2600, picking_cost_multiplier=0.95)
|
| 52 |
+
nodes["RWH-W"] = Node("RWH-W", "regional_wh", "Regional Warehouse West", 34.05, -118.24, daily_pick_capacity=2600, picking_cost_multiplier=0.95)
|
| 53 |
+
nodes["SUP1"] = Node("SUP1", "supplier", "Primary Supplier Hub", 41.88, -87.63, daily_pick_capacity=4000, picking_cost_multiplier=1.10)
|
| 54 |
+
nodes["XDOCK1"] = Node("XDOCK1", "cross_dock", "Regional Cross-Dock", 38.63, -90.20, daily_pick_capacity=3200, picking_cost_multiplier=0.70)
|
| 55 |
+
nodes["RET1"] = Node("RET1", "return_center", "Returns Processing Center", 39.77, -86.16, daily_pick_capacity=1800, picking_cost_multiplier=1.0)
|
| 56 |
+
nodes["REPAIR1"] = Node("REPAIR1", "repair_center", "Repair & Refurbishment Center", 39.77, -86.20, daily_pick_capacity=600, picking_cost_multiplier=1.0)
|
| 57 |
+
nodes["RECY1"] = Node("RECY1", "recycle_center", "Recycling & Recovery Center", 39.80, -86.10, daily_pick_capacity=900, picking_cost_multiplier=1.0)
|
| 58 |
+
|
| 59 |
+
for i in range(n_stores):
|
| 60 |
+
lat = 30.0 + rng.uniform(0, 15.0)
|
| 61 |
+
lon = -122.0 + rng.uniform(0, 45.0)
|
| 62 |
+
sid = f"ST{i:03d}"
|
| 63 |
+
nodes[sid] = Node(sid, "store", f"Store {i:03d}", round(lat, 3), round(lon, 3), daily_pick_capacity=rng.randint(120, 320), picking_cost_multiplier=1.25)
|
| 64 |
+
return nodes
|
| 65 |
+
|
| 66 |
+
|
| 67 |
+
def _make_skus(rng: random.Random, n_skus: int) -> dict[str, SKU]:
|
| 68 |
+
skus: dict[str, SKU] = {}
|
| 69 |
+
for i in range(n_skus):
|
| 70 |
+
cat = CATEGORIES[i % len(CATEGORIES)]
|
| 71 |
+
group = SUBSTITUTE_GROUPS[cat][i % len(SUBSTITUTE_GROUPS[cat])]
|
| 72 |
+
cost = round(rng.uniform(8, 90), 2)
|
| 73 |
+
skus[f"SKU{i:04d}"] = SKU(
|
| 74 |
+
sku_id=f"SKU{i:04d}",
|
| 75 |
+
category=cat,
|
| 76 |
+
unit_price=round(cost * rng.uniform(1.5, 2.6), 2),
|
| 77 |
+
unit_cost=cost,
|
| 78 |
+
weight_kg=round(rng.uniform(0.2, 4.5), 2),
|
| 79 |
+
substitute_group=group,
|
| 80 |
+
return_rate=round(BASE_RETURN_RATE[cat] * rng.uniform(0.7, 1.3), 3),
|
| 81 |
+
)
|
| 82 |
+
return skus
|
| 83 |
+
|
| 84 |
+
|
| 85 |
+
def _make_inventory(rng: random.Random, nodes: dict[str, Node], skus: dict[str, SKU]) -> list[InventoryRecord]:
|
| 86 |
+
inv = []
|
| 87 |
+
fulfillment_nodes = [n for n in nodes.values() if n.node_type in ("central_dc", "regional_wh", "store", "cross_dock", "supplier")]
|
| 88 |
+
for node in fulfillment_nodes:
|
| 89 |
+
base_qty = {"central_dc": 800, "regional_wh": 300, "cross_dock": 150, "supplier": 5000, "store": 25}[node.node_type]
|
| 90 |
+
for sku in skus.values():
|
| 91 |
+
qty = max(0, int(rng.gauss(base_qty, base_qty * 0.35)))
|
| 92 |
+
accuracy = round(rng.uniform(0.88, 0.99), 3)
|
| 93 |
+
inv.append(InventoryRecord(node.node_id, sku.sku_id, qty, accuracy))
|
| 94 |
+
return inv
|
| 95 |
+
|
| 96 |
+
|
| 97 |
+
def _make_links(nodes: dict[str, Node]) -> list[TransportLink]:
|
| 98 |
+
links = []
|
| 99 |
+
sources = [n for n in nodes.values() if n.node_type in ("central_dc", "regional_wh", "cross_dock", "supplier", "store")]
|
| 100 |
+
dests = [n for n in nodes.values() if n.node_type in ("store", "regional_wh", "cross_dock", "return_center")]
|
| 101 |
+
for o in sources:
|
| 102 |
+
for d in dests:
|
| 103 |
+
if o.node_id == d.node_id:
|
| 104 |
+
continue
|
| 105 |
+
dist = round(_haversine_km(o.lat, o.lon, d.lat, d.lon), 1)
|
| 106 |
+
links.append(TransportLink(o.node_id, d.node_id, dist, "standard"))
|
| 107 |
+
links.append(TransportLink(o.node_id, d.node_id, dist, "express"))
|
| 108 |
+
return links
|
| 109 |
+
|
| 110 |
+
|
| 111 |
+
def _make_orders(rng: random.Random, nodes: dict[str, Node], skus: dict[str, SKU], n_orders: int, demand_multiplier: float) -> list[Order]:
|
| 112 |
+
stores = [n for n in nodes.values() if n.node_type == "store"]
|
| 113 |
+
sku_ids = list(skus.keys())
|
| 114 |
+
orders = []
|
| 115 |
+
n_orders = max(1, int(n_orders * demand_multiplier))
|
| 116 |
+
for i in range(n_orders):
|
| 117 |
+
demand_node = rng.choice(stores)
|
| 118 |
+
channel = rng.choice(["online"] * 7 + ["store"] * 3)
|
| 119 |
+
priority = rng.choice(["standard"] * 6 + ["premium"] * 3 + ["vip"] * 1)
|
| 120 |
+
n_lines = rng.randint(1, 3)
|
| 121 |
+
lines = []
|
| 122 |
+
for _ in range(n_lines):
|
| 123 |
+
sku_id = rng.choice(sku_ids)
|
| 124 |
+
lines.append(OrderLine(sku_id=sku_id, qty_requested=rng.randint(1, 3)))
|
| 125 |
+
orders.append(
|
| 126 |
+
Order(
|
| 127 |
+
order_id=f"ORD{i:05d}",
|
| 128 |
+
demand_node_id=demand_node.node_id,
|
| 129 |
+
channel=channel,
|
| 130 |
+
priority_class=priority,
|
| 131 |
+
lines=lines,
|
| 132 |
+
placed_at_hour=rng.randint(0, 23),
|
| 133 |
+
)
|
| 134 |
+
)
|
| 135 |
+
return orders
|
| 136 |
+
|
| 137 |
+
|
| 138 |
+
def _apply_scenario(rng: random.Random, scenario_key: str, network: Network) -> ScenarioEvent:
|
| 139 |
+
if scenario_key == "peak_season_surge":
|
| 140 |
+
event = ScenarioEvent(
|
| 141 |
+
"peak_season_surge",
|
| 142 |
+
"Demand spikes 65% while picking capacity stays flat across all fulfillment nodes",
|
| 143 |
+
affected_node_ids=list(network.nodes.keys()),
|
| 144 |
+
capacity_factor=1.0,
|
| 145 |
+
demand_multiplier=1.65,
|
| 146 |
+
)
|
| 147 |
+
network.orders = _make_orders(rng, network.nodes, network.skus, len(network.orders), 1.65)
|
| 148 |
+
elif scenario_key == "regional_stockout":
|
| 149 |
+
affected = "RWH-E"
|
| 150 |
+
for rec in network.inventory:
|
| 151 |
+
if rec.node_id == affected:
|
| 152 |
+
rec.on_hand_qty = int(rec.on_hand_qty * 0.08)
|
| 153 |
+
event = ScenarioEvent(
|
| 154 |
+
"regional_stockout",
|
| 155 |
+
f"{network.nodes[affected].name} inventory collapses to 8% of nominal, forcing ship-from-store",
|
| 156 |
+
affected_node_ids=[affected],
|
| 157 |
+
capacity_factor=1.0,
|
| 158 |
+
)
|
| 159 |
+
elif scenario_key == "high_return_category_wave":
|
| 160 |
+
for sku in network.skus.values():
|
| 161 |
+
if sku.category == "apparel":
|
| 162 |
+
sku.return_rate = round(min(0.55, sku.return_rate * 2.1), 3)
|
| 163 |
+
event = ScenarioEvent(
|
| 164 |
+
"high_return_category_wave",
|
| 165 |
+
"Apparel return rate more than doubles after a sizing-related quality issue",
|
| 166 |
+
affected_node_ids=["RET1", "REPAIR1"],
|
| 167 |
+
)
|
| 168 |
+
elif scenario_key == "capacity_constrained_dc":
|
| 169 |
+
network.nodes["DC1"].daily_pick_capacity = int(network.nodes["DC1"].daily_pick_capacity * 0.35)
|
| 170 |
+
event = ScenarioEvent(
|
| 171 |
+
"capacity_constrained_dc",
|
| 172 |
+
"Central DC picking capacity cut to 35% after a conveyor outage",
|
| 173 |
+
affected_node_ids=["DC1"],
|
| 174 |
+
capacity_factor=0.35,
|
| 175 |
+
)
|
| 176 |
+
elif scenario_key == "green_logistics_push":
|
| 177 |
+
event = ScenarioEvent(
|
| 178 |
+
"green_logistics_push",
|
| 179 |
+
"Corporate mandate to weight the carbon objective heavily in this week's allocation",
|
| 180 |
+
affected_node_ids=list(network.nodes.keys()),
|
| 181 |
+
)
|
| 182 |
+
else:
|
| 183 |
+
raise ValueError(f"Unknown scenario key: {scenario_key}")
|
| 184 |
+
return event
|
| 185 |
+
|
| 186 |
+
|
| 187 |
+
def generate_network(scenario_key: str, seed: int = 42, n_stores: int = 24, n_skus: int = 60, n_orders: int = 260) -> Network:
|
| 188 |
+
if scenario_key not in SCENARIOS:
|
| 189 |
+
raise ValueError(f"Unknown scenario '{scenario_key}'. Options: {list(SCENARIOS)}")
|
| 190 |
+
rng = random.Random(seed)
|
| 191 |
+
nodes = _make_nodes(rng, n_stores)
|
| 192 |
+
skus = _make_skus(rng, n_skus)
|
| 193 |
+
inventory = _make_inventory(rng, nodes, skus)
|
| 194 |
+
links = _make_links(nodes)
|
| 195 |
+
orders = _make_orders(rng, nodes, skus, n_orders, 1.0)
|
| 196 |
+
|
| 197 |
+
network = Network(
|
| 198 |
+
scenario_id=f"{scenario_key}_seed{seed}",
|
| 199 |
+
scenario_name=SCENARIOS[scenario_key],
|
| 200 |
+
description=SCENARIOS[scenario_key],
|
| 201 |
+
nodes=nodes,
|
| 202 |
+
skus=skus,
|
| 203 |
+
inventory=inventory,
|
| 204 |
+
links=links,
|
| 205 |
+
orders=orders,
|
| 206 |
+
events=[],
|
| 207 |
+
)
|
| 208 |
+
event = _apply_scenario(rng, scenario_key, network)
|
| 209 |
+
network.events.append(event)
|
| 210 |
+
return network
|
| 211 |
+
|
| 212 |
+
|
| 213 |
+
def list_scenarios() -> list[str]:
|
| 214 |
+
return list(SCENARIOS.keys())
|
space-bundle/src/omnitower/omnitower/lns_solver.py
ADDED
|
@@ -0,0 +1,80 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Adaptive Large Neighborhood Search improvement over the greedy allocation.
|
| 2 |
+
|
| 3 |
+
The greedy marginal-cost allocator (`allocation.py`) is fast and scalable
|
| 4 |
+
but processes orders in a fixed sequence, so early orders can lock in
|
| 5 |
+
sources that would have been better reserved for later, higher-value
|
| 6 |
+
orders. This module repeatedly (a) destroys a random subset of already
|
| 7 |
+
allocated orders, releasing their inventory/capacity back into the pool,
|
| 8 |
+
and (b) re-inserts them in an order driven by priority and margin, keeping
|
| 9 |
+
the change only if total network cost improves — a lightweight ALNS loop
|
| 10 |
+
sized for interactive demo latency rather than production scale.
|
| 11 |
+
"""
|
| 12 |
+
|
| 13 |
+
from __future__ import annotations
|
| 14 |
+
|
| 15 |
+
import random
|
| 16 |
+
import copy
|
| 17 |
+
|
| 18 |
+
from .models import Network
|
| 19 |
+
from .allocation import AllocationState, build_state, allocate_order
|
| 20 |
+
from .network import build_graph
|
| 21 |
+
|
| 22 |
+
|
| 23 |
+
def _network_cost(network: Network, reports: dict[str, dict]) -> float:
|
| 24 |
+
total = 0.0
|
| 25 |
+
for report in reports.values():
|
| 26 |
+
for lr in report["line_reports"]:
|
| 27 |
+
total += lr.get("transport_cost_usd", 0) + lr.get("pick_cost_usd", 0) + lr.get("pack_cost_usd", 0)
|
| 28 |
+
if report["split_shipment"]:
|
| 29 |
+
total += 3.20
|
| 30 |
+
total += report["total_backordered_qty"] * 4.5
|
| 31 |
+
return total
|
| 32 |
+
|
| 33 |
+
|
| 34 |
+
def improve_allocation(network: Network, option: str = "economical", iterations: int = 25, destroy_fraction: float = 0.15, seed: int = 3) -> tuple[AllocationState, dict[str, dict], list[float]]:
|
| 35 |
+
rng = random.Random(seed)
|
| 36 |
+
graph = build_graph(network)
|
| 37 |
+
state = build_state(network)
|
| 38 |
+
reports = {}
|
| 39 |
+
order_by_id = {o.order_id: o for o in network.orders}
|
| 40 |
+
|
| 41 |
+
ordered = sorted(network.orders, key=lambda o: (-{"vip": 3, "premium": 2, "standard": 1}[o.priority_class], o.placed_at_hour))
|
| 42 |
+
for order in ordered:
|
| 43 |
+
reports[order.order_id] = allocate_order(network, order, option, state, graph)
|
| 44 |
+
|
| 45 |
+
history = [_network_cost(network, reports)]
|
| 46 |
+
order_ids = list(order_by_id.keys())
|
| 47 |
+
|
| 48 |
+
for _ in range(iterations):
|
| 49 |
+
k = max(1, int(len(order_ids) * destroy_fraction))
|
| 50 |
+
destroyed_ids = rng.sample(order_ids, k)
|
| 51 |
+
|
| 52 |
+
trial_state = AllocationState(inventory=dict(state.inventory), capacity=dict(state.capacity))
|
| 53 |
+
trial_reports = dict(reports)
|
| 54 |
+
trial_orders = {oid: copy.deepcopy(order_by_id[oid]) for oid in destroyed_ids}
|
| 55 |
+
|
| 56 |
+
for oid in destroyed_ids:
|
| 57 |
+
old_report = reports[oid]
|
| 58 |
+
for lr in old_report["line_reports"]:
|
| 59 |
+
trial_state.inventory[(lr["node_id"], lr["sku_id"])] = trial_state.inventory.get((lr["node_id"], lr["sku_id"]), 0) + lr["qty"]
|
| 60 |
+
trial_state.capacity[lr["node_id"]] = trial_state.capacity.get(lr["node_id"], 0) + lr["qty"]
|
| 61 |
+
|
| 62 |
+
reinsert_order_of_ids = sorted(
|
| 63 |
+
destroyed_ids,
|
| 64 |
+
key=lambda oid: -{"vip": 3, "premium": 2, "standard": 1}[order_by_id[oid].priority_class],
|
| 65 |
+
)
|
| 66 |
+
for oid in reinsert_order_of_ids:
|
| 67 |
+
trial_reports[oid] = allocate_order(network, trial_orders[oid], option, trial_state, graph)
|
| 68 |
+
|
| 69 |
+
new_cost = _network_cost(network, trial_reports)
|
| 70 |
+
if new_cost <= history[-1]:
|
| 71 |
+
state = trial_state
|
| 72 |
+
reports = trial_reports
|
| 73 |
+
for oid in destroyed_ids:
|
| 74 |
+
order_by_id[oid] = trial_orders[oid]
|
| 75 |
+
history.append(new_cost)
|
| 76 |
+
else:
|
| 77 |
+
history.append(history[-1])
|
| 78 |
+
|
| 79 |
+
network.orders = list(order_by_id.values())
|
| 80 |
+
return state, reports, history
|
space-bundle/src/omnitower/omnitower/metrics.py
ADDED
|
@@ -0,0 +1,96 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Network-level KPI computation."""
|
| 2 |
+
|
| 3 |
+
from __future__ import annotations
|
| 4 |
+
|
| 5 |
+
from dataclasses import dataclass, asdict
|
| 6 |
+
|
| 7 |
+
from .models import Network
|
| 8 |
+
from .constants import DEFAULT_MARGIN_RATE, BACKORDER_PENALTY_USD, CANCELLATION_PENALTY_USD, WORKING_CAPITAL_DAYS_HELD
|
| 9 |
+
|
| 10 |
+
|
| 11 |
+
@dataclass
|
| 12 |
+
class NetworkMetrics:
|
| 13 |
+
gross_margin_usd: float
|
| 14 |
+
fill_rate: float
|
| 15 |
+
on_time_sla_rate: float
|
| 16 |
+
n_split_shipments: int
|
| 17 |
+
split_shipment_rate: float
|
| 18 |
+
picking_workload_units: int
|
| 19 |
+
return_handling_cost_usd: float
|
| 20 |
+
total_carbon_kg: float
|
| 21 |
+
working_capital_usd: float
|
| 22 |
+
n_orders: int
|
| 23 |
+
n_backordered_orders: int
|
| 24 |
+
|
| 25 |
+
def to_dict(self) -> dict:
|
| 26 |
+
return asdict(self)
|
| 27 |
+
|
| 28 |
+
|
| 29 |
+
def compute_metrics(network: Network, reports: dict[str, dict] | list[dict], return_summary: dict | None = None, sla_hours: float = 48.0) -> NetworkMetrics:
|
| 30 |
+
if isinstance(reports, list):
|
| 31 |
+
reports = {r["order_id"]: r for r in reports}
|
| 32 |
+
gross_margin = 0.0
|
| 33 |
+
total_requested = 0
|
| 34 |
+
total_fulfilled = 0
|
| 35 |
+
n_split = 0
|
| 36 |
+
picking_units = 0
|
| 37 |
+
total_carbon = 0.0
|
| 38 |
+
on_time = 0
|
| 39 |
+
n_orders_with_lines = 0
|
| 40 |
+
n_backordered_orders = 0
|
| 41 |
+
|
| 42 |
+
order_by_id = {o.order_id: o for o in network.orders}
|
| 43 |
+
|
| 44 |
+
for order_id, report in reports.items():
|
| 45 |
+
order = order_by_id.get(order_id)
|
| 46 |
+
if order is None:
|
| 47 |
+
continue
|
| 48 |
+
n_orders_with_lines += 1
|
| 49 |
+
if report["split_shipment"]:
|
| 50 |
+
n_split += 1
|
| 51 |
+
max_lead = 0.0
|
| 52 |
+
for lr in report["line_reports"]:
|
| 53 |
+
sku = network.skus.get(lr["sku_id"])
|
| 54 |
+
unit_price = sku.unit_price if sku else 0.0
|
| 55 |
+
unit_cost = sku.unit_cost if sku else unit_price * (1 - DEFAULT_MARGIN_RATE)
|
| 56 |
+
gross_margin += (unit_price - unit_cost) * lr["qty"]
|
| 57 |
+
gross_margin -= lr.get("transport_cost_usd", 0) + lr.get("pick_cost_usd", 0) + lr.get("pack_cost_usd", 0)
|
| 58 |
+
picking_units += lr["qty"]
|
| 59 |
+
total_carbon += lr.get("carbon_kg", 0.0)
|
| 60 |
+
max_lead = max(max_lead, lr.get("lead_time_hours", 0.0))
|
| 61 |
+
if max_lead and max_lead <= sla_hours:
|
| 62 |
+
on_time += 1
|
| 63 |
+
if report["total_backordered_qty"] > 0:
|
| 64 |
+
gross_margin -= report["total_backordered_qty"] * BACKORDER_PENALTY_USD
|
| 65 |
+
n_backordered_orders += 1
|
| 66 |
+
total_requested += sum(l.qty_requested for l in order.lines)
|
| 67 |
+
total_fulfilled += sum(l.qty_fulfilled for l in order.lines)
|
| 68 |
+
|
| 69 |
+
return_cost = return_summary["total_handling_cost_usd"] if return_summary else 0.0
|
| 70 |
+
if return_summary:
|
| 71 |
+
gross_margin -= return_cost
|
| 72 |
+
gross_margin += return_summary.get("total_recovered_value_usd", 0.0)
|
| 73 |
+
|
| 74 |
+
working_capital = 0.0
|
| 75 |
+
for rec in network.inventory:
|
| 76 |
+
node = network.nodes.get(rec.node_id)
|
| 77 |
+
sku = network.skus.get(rec.sku_id)
|
| 78 |
+
if not node or not sku:
|
| 79 |
+
continue
|
| 80 |
+
days_held = WORKING_CAPITAL_DAYS_HELD.get(node.node_type, 10)
|
| 81 |
+
working_capital += rec.on_hand_qty * sku.unit_cost * (days_held / 365.0) * 12
|
| 82 |
+
|
| 83 |
+
n_orders = max(1, n_orders_with_lines)
|
| 84 |
+
return NetworkMetrics(
|
| 85 |
+
gross_margin_usd=round(gross_margin, 2),
|
| 86 |
+
fill_rate=round(total_fulfilled / total_requested, 4) if total_requested else 1.0,
|
| 87 |
+
on_time_sla_rate=round(on_time / n_orders, 4),
|
| 88 |
+
n_split_shipments=n_split,
|
| 89 |
+
split_shipment_rate=round(n_split / n_orders, 4),
|
| 90 |
+
picking_workload_units=picking_units,
|
| 91 |
+
return_handling_cost_usd=round(return_cost, 2),
|
| 92 |
+
total_carbon_kg=round(total_carbon, 2),
|
| 93 |
+
working_capital_usd=round(working_capital, 2),
|
| 94 |
+
n_orders=n_orders_with_lines,
|
| 95 |
+
n_backordered_orders=n_backordered_orders,
|
| 96 |
+
)
|
space-bundle/src/omnitower/omnitower/models.py
ADDED
|
@@ -0,0 +1,118 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Domain model for the omnichannel fulfillment and returns network."""
|
| 2 |
+
|
| 3 |
+
from __future__ import annotations
|
| 4 |
+
|
| 5 |
+
from dataclasses import dataclass, field, asdict
|
| 6 |
+
from typing import Optional
|
| 7 |
+
|
| 8 |
+
|
| 9 |
+
@dataclass
|
| 10 |
+
class Node:
|
| 11 |
+
node_id: str
|
| 12 |
+
node_type: str
|
| 13 |
+
name: str
|
| 14 |
+
lat: float
|
| 15 |
+
lon: float
|
| 16 |
+
daily_pick_capacity: int = 800
|
| 17 |
+
picking_cost_multiplier: float = 1.0
|
| 18 |
+
|
| 19 |
+
|
| 20 |
+
@dataclass
|
| 21 |
+
class SKU:
|
| 22 |
+
sku_id: str
|
| 23 |
+
category: str
|
| 24 |
+
unit_price: float
|
| 25 |
+
unit_cost: float
|
| 26 |
+
weight_kg: float
|
| 27 |
+
substitute_group: str
|
| 28 |
+
return_rate: float
|
| 29 |
+
resalable: bool = True
|
| 30 |
+
|
| 31 |
+
|
| 32 |
+
@dataclass
|
| 33 |
+
class InventoryRecord:
|
| 34 |
+
node_id: str
|
| 35 |
+
sku_id: str
|
| 36 |
+
on_hand_qty: int
|
| 37 |
+
accuracy: float = 0.94 # fraction of on_hand_qty that is actually pickable
|
| 38 |
+
|
| 39 |
+
|
| 40 |
+
@dataclass
|
| 41 |
+
class TransportLink:
|
| 42 |
+
origin_id: str
|
| 43 |
+
dest_id: str
|
| 44 |
+
distance_km: float
|
| 45 |
+
ship_mode: str = "standard"
|
| 46 |
+
|
| 47 |
+
|
| 48 |
+
@dataclass
|
| 49 |
+
class OrderLine:
|
| 50 |
+
sku_id: str
|
| 51 |
+
qty_requested: int
|
| 52 |
+
qty_fulfilled: int = 0
|
| 53 |
+
substituted_sku_id: Optional[str] = None
|
| 54 |
+
source_node_id: Optional[str] = None
|
| 55 |
+
backordered_qty: int = 0
|
| 56 |
+
cancelled_qty: int = 0
|
| 57 |
+
|
| 58 |
+
|
| 59 |
+
@dataclass
|
| 60 |
+
class Order:
|
| 61 |
+
order_id: str
|
| 62 |
+
demand_node_id: str
|
| 63 |
+
channel: str # "online" or "store"
|
| 64 |
+
priority_class: str
|
| 65 |
+
lines: list[OrderLine]
|
| 66 |
+
placed_at_hour: int
|
| 67 |
+
accepted: bool = True
|
| 68 |
+
split_shipment: bool = False
|
| 69 |
+
chosen_delivery_option: str = "economical"
|
| 70 |
+
|
| 71 |
+
|
| 72 |
+
@dataclass
|
| 73 |
+
class ReturnItem:
|
| 74 |
+
return_id: str
|
| 75 |
+
order_id: str
|
| 76 |
+
sku_id: str
|
| 77 |
+
qty: int
|
| 78 |
+
quality_score: float
|
| 79 |
+
origin_node_id: str
|
| 80 |
+
disposition: str = "" # restock_store, restock_dc, repair, recycle, dispose
|
| 81 |
+
resold: bool = False
|
| 82 |
+
|
| 83 |
+
|
| 84 |
+
@dataclass
|
| 85 |
+
class ScenarioEvent:
|
| 86 |
+
event_type: str
|
| 87 |
+
description: str
|
| 88 |
+
affected_node_ids: list[str] = field(default_factory=list)
|
| 89 |
+
capacity_factor: float = 1.0
|
| 90 |
+
demand_multiplier: float = 1.0
|
| 91 |
+
|
| 92 |
+
|
| 93 |
+
@dataclass
|
| 94 |
+
class Network:
|
| 95 |
+
scenario_id: str
|
| 96 |
+
scenario_name: str
|
| 97 |
+
description: str
|
| 98 |
+
nodes: dict[str, Node]
|
| 99 |
+
skus: dict[str, SKU]
|
| 100 |
+
inventory: list[InventoryRecord]
|
| 101 |
+
links: list[TransportLink]
|
| 102 |
+
orders: list[Order]
|
| 103 |
+
events: list[ScenarioEvent]
|
| 104 |
+
|
| 105 |
+
def to_dict(self) -> dict:
|
| 106 |
+
return {
|
| 107 |
+
"scenario_id": self.scenario_id,
|
| 108 |
+
"scenario_name": self.scenario_name,
|
| 109 |
+
"description": self.description,
|
| 110 |
+
"nodes": {k: asdict(v) for k, v in self.nodes.items()},
|
| 111 |
+
"skus": {k: asdict(v) for k, v in self.skus.items()},
|
| 112 |
+
"inventory": [asdict(i) for i in self.inventory],
|
| 113 |
+
"links": [asdict(l) for l in self.links],
|
| 114 |
+
"orders": [
|
| 115 |
+
{**asdict(o), "lines": [asdict(ln) for ln in o.lines]} for o in self.orders
|
| 116 |
+
],
|
| 117 |
+
"events": [asdict(e) for e in self.events],
|
| 118 |
+
}
|
space-bundle/src/omnitower/omnitower/network.py
ADDED
|
@@ -0,0 +1,79 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Graph utilities: distance lookup and candidate-source ranking.
|
| 2 |
+
|
| 3 |
+
A lightweight NetworkX directed graph indexes transport links so the
|
| 4 |
+
allocation and routing modules can query distance / mode without
|
| 5 |
+
re-scanning the flat link list on every call.
|
| 6 |
+
"""
|
| 7 |
+
|
| 8 |
+
from __future__ import annotations
|
| 9 |
+
|
| 10 |
+
import networkx as nx
|
| 11 |
+
|
| 12 |
+
from .models import Network
|
| 13 |
+
from .constants import (
|
| 14 |
+
COST_PER_KM_STANDARD_USD,
|
| 15 |
+
COST_PER_KM_EXPRESS_USD,
|
| 16 |
+
CARBON_KG_PER_KM_STANDARD,
|
| 17 |
+
CARBON_KG_PER_KM_EXPRESS,
|
| 18 |
+
CARBON_KG_PER_KM_GREEN,
|
| 19 |
+
)
|
| 20 |
+
|
| 21 |
+
FULFILLMENT_NODE_TYPES = ("central_dc", "regional_wh", "cross_dock", "supplier", "store")
|
| 22 |
+
|
| 23 |
+
|
| 24 |
+
def build_graph(network: Network) -> nx.DiGraph:
|
| 25 |
+
graph = nx.DiGraph()
|
| 26 |
+
for node in network.nodes.values():
|
| 27 |
+
graph.add_node(node.node_id, node_type=node.node_type, capacity=node.daily_pick_capacity)
|
| 28 |
+
for link in network.links:
|
| 29 |
+
graph.add_edge(
|
| 30 |
+
link.origin_id,
|
| 31 |
+
link.dest_id,
|
| 32 |
+
**{f"distance_km_{link.ship_mode}": link.distance_km},
|
| 33 |
+
)
|
| 34 |
+
return graph
|
| 35 |
+
|
| 36 |
+
|
| 37 |
+
def distance_km(graph: nx.DiGraph, origin_id: str, dest_id: str) -> float:
|
| 38 |
+
if origin_id == dest_id:
|
| 39 |
+
return 0.0
|
| 40 |
+
data = graph.get_edge_data(origin_id, dest_id, default=None)
|
| 41 |
+
if data is None:
|
| 42 |
+
return float("inf")
|
| 43 |
+
for key, value in data.items():
|
| 44 |
+
if key.startswith("distance_km_"):
|
| 45 |
+
return value
|
| 46 |
+
return float("inf")
|
| 47 |
+
|
| 48 |
+
|
| 49 |
+
def transport_cost(distance: float, mode: str) -> float:
|
| 50 |
+
if distance == 0:
|
| 51 |
+
return 0.0
|
| 52 |
+
rate = COST_PER_KM_EXPRESS_USD if mode == "express" else COST_PER_KM_STANDARD_USD
|
| 53 |
+
return distance * rate
|
| 54 |
+
|
| 55 |
+
|
| 56 |
+
def carbon_kg(distance: float, mode: str) -> float:
|
| 57 |
+
if distance == 0:
|
| 58 |
+
return 0.0
|
| 59 |
+
factor = {
|
| 60 |
+
"express": CARBON_KG_PER_KM_EXPRESS,
|
| 61 |
+
"green": CARBON_KG_PER_KM_GREEN,
|
| 62 |
+
}.get(mode, CARBON_KG_PER_KM_STANDARD)
|
| 63 |
+
return distance * factor
|
| 64 |
+
|
| 65 |
+
|
| 66 |
+
def candidate_sources(network: Network, demand_node_id: str, exclude_demand_node: bool = False) -> list[str]:
|
| 67 |
+
"""All nodes that can physically fulfill an order for a given demand node.
|
| 68 |
+
|
| 69 |
+
For online orders the demand node is the customer's assigned store
|
| 70 |
+
catchment, not a shelf the customer is standing in front of, so the
|
| 71 |
+
demand node itself is excluded from candidate sources — otherwise
|
| 72 |
+
every order would trivially "self-fulfill" from its own store with
|
| 73 |
+
zero transport cost, masking the multi-echelon allocation problem.
|
| 74 |
+
"""
|
| 75 |
+
return [
|
| 76 |
+
n.node_id
|
| 77 |
+
for n in network.nodes.values()
|
| 78 |
+
if n.node_type in FULFILLMENT_NODE_TYPES and not (exclude_demand_node and n.node_id == demand_node_id)
|
| 79 |
+
]
|
space-bundle/src/omnitower/omnitower/options.py
ADDED
|
@@ -0,0 +1,84 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Highlighted scenario: three delivery options per order.
|
| 2 |
+
|
| 3 |
+
For a single order, computes the Fast / Economical / Green allocation
|
| 4 |
+
independently (each against a snapshot of the current inventory and
|
| 5 |
+
capacity pools) and reports the effect each option would have on future
|
| 6 |
+
inventory and remaining warehouse/store picking capacity, so a planner can
|
| 7 |
+
compare the three before committing to one.
|
| 8 |
+
"""
|
| 9 |
+
|
| 10 |
+
from __future__ import annotations
|
| 11 |
+
|
| 12 |
+
import copy
|
| 13 |
+
from dataclasses import dataclass
|
| 14 |
+
|
| 15 |
+
from .models import Network, Order
|
| 16 |
+
from .allocation import AllocationState, allocate_order, build_state
|
| 17 |
+
from .network import build_graph
|
| 18 |
+
from .constants import DELIVERY_OPTIONS
|
| 19 |
+
|
| 20 |
+
|
| 21 |
+
@dataclass
|
| 22 |
+
class OptionResult:
|
| 23 |
+
option: str
|
| 24 |
+
report: dict
|
| 25 |
+
total_cost_usd: float
|
| 26 |
+
total_lead_time_hours: float
|
| 27 |
+
total_carbon_kg: float
|
| 28 |
+
inventory_impact: list[dict]
|
| 29 |
+
capacity_impact: list[dict]
|
| 30 |
+
|
| 31 |
+
|
| 32 |
+
def _totals(report: dict) -> tuple[float, float, float]:
|
| 33 |
+
cost = sum(r.get("transport_cost_usd", 0) + r.get("pick_cost_usd", 0) + r.get("pack_cost_usd", 0) for r in report["line_reports"])
|
| 34 |
+
lead = max((r.get("lead_time_hours", 0) for r in report["line_reports"]), default=0.0)
|
| 35 |
+
carbon = sum(r.get("carbon_kg", 0) for r in report["line_reports"])
|
| 36 |
+
if report["split_shipment"]:
|
| 37 |
+
cost += 3.20
|
| 38 |
+
return round(cost, 2), round(lead, 1), round(carbon, 2)
|
| 39 |
+
|
| 40 |
+
|
| 41 |
+
def compare_delivery_options(network: Network, order: Order, base_state: AllocationState) -> list[OptionResult]:
|
| 42 |
+
graph = build_graph(network)
|
| 43 |
+
results = []
|
| 44 |
+
for option in DELIVERY_OPTIONS:
|
| 45 |
+
state_copy = AllocationState(inventory=dict(base_state.inventory), capacity=dict(base_state.capacity))
|
| 46 |
+
order_copy = copy.deepcopy(order)
|
| 47 |
+
report = allocate_order(network, order_copy, option, state_copy, graph)
|
| 48 |
+
cost, lead, carbon = _totals(report)
|
| 49 |
+
|
| 50 |
+
inv_impact = []
|
| 51 |
+
cap_impact = []
|
| 52 |
+
touched_nodes = set()
|
| 53 |
+
for line_report in report["line_reports"]:
|
| 54 |
+
node_id, sku_id = line_report["node_id"], line_report["sku_id"]
|
| 55 |
+
inv_impact.append(
|
| 56 |
+
{
|
| 57 |
+
"node_id": node_id,
|
| 58 |
+
"sku_id": sku_id,
|
| 59 |
+
"qty_consumed": line_report["qty"],
|
| 60 |
+
"remaining_after": round(state_copy.inventory.get((node_id, sku_id), 0), 1),
|
| 61 |
+
"starting": round(base_state.inventory.get((node_id, sku_id), 0), 1),
|
| 62 |
+
}
|
| 63 |
+
)
|
| 64 |
+
touched_nodes.add(node_id)
|
| 65 |
+
for node_id in touched_nodes:
|
| 66 |
+
cap_impact.append(
|
| 67 |
+
{
|
| 68 |
+
"node_id": node_id,
|
| 69 |
+
"capacity_remaining_after": round(state_copy.capacity.get(node_id, 0), 1),
|
| 70 |
+
"capacity_starting": round(base_state.capacity.get(node_id, 0), 1),
|
| 71 |
+
}
|
| 72 |
+
)
|
| 73 |
+
results.append(
|
| 74 |
+
OptionResult(
|
| 75 |
+
option=option,
|
| 76 |
+
report=report,
|
| 77 |
+
total_cost_usd=cost,
|
| 78 |
+
total_lead_time_hours=lead,
|
| 79 |
+
total_carbon_kg=carbon,
|
| 80 |
+
inventory_impact=inv_impact,
|
| 81 |
+
capacity_impact=cap_impact,
|
| 82 |
+
)
|
| 83 |
+
)
|
| 84 |
+
return results
|
space-bundle/src/omnitower/omnitower/pipeline.py
ADDED
|
@@ -0,0 +1,70 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""End-to-end orchestration: generate -> allocate/admit -> improve -> return -> measure."""
|
| 2 |
+
|
| 3 |
+
from __future__ import annotations
|
| 4 |
+
|
| 5 |
+
from dataclasses import dataclass
|
| 6 |
+
|
| 7 |
+
from .models import Network
|
| 8 |
+
from .generator import generate_network
|
| 9 |
+
from .allocation import allocate_all, build_state
|
| 10 |
+
from .admission import evaluate_all
|
| 11 |
+
from .lns_solver import improve_allocation
|
| 12 |
+
from .returns import generate_returns, summarize_returns
|
| 13 |
+
from .metrics import compute_metrics, NetworkMetrics
|
| 14 |
+
from .options import compare_delivery_options, OptionResult
|
| 15 |
+
|
| 16 |
+
|
| 17 |
+
@dataclass
|
| 18 |
+
class PipelineResult:
|
| 19 |
+
network: Network
|
| 20 |
+
reports: dict[str, dict]
|
| 21 |
+
admission_rejections: int
|
| 22 |
+
return_summary: dict
|
| 23 |
+
metrics: NetworkMetrics
|
| 24 |
+
cost_history: list[float]
|
| 25 |
+
|
| 26 |
+
|
| 27 |
+
def run_scenario(
|
| 28 |
+
scenario_key: str,
|
| 29 |
+
seed: int = 42,
|
| 30 |
+
n_stores: int = 24,
|
| 31 |
+
n_skus: int = 60,
|
| 32 |
+
n_orders: int = 260,
|
| 33 |
+
delivery_option: str = "economical",
|
| 34 |
+
lns_iterations: int = 25,
|
| 35 |
+
use_admission_control: bool = True,
|
| 36 |
+
) -> PipelineResult:
|
| 37 |
+
network = generate_network(scenario_key, seed=seed, n_stores=n_stores, n_skus=n_skus, n_orders=n_orders)
|
| 38 |
+
|
| 39 |
+
admission_rejections = 0
|
| 40 |
+
if use_admission_control:
|
| 41 |
+
preview_state = build_state(network)
|
| 42 |
+
decisions = evaluate_all(network, preview_state)
|
| 43 |
+
rejected_ids = {d.order_id for d in decisions if not d.admitted}
|
| 44 |
+
admission_rejections = len(rejected_ids)
|
| 45 |
+
network.orders = [o for o in network.orders if o.order_id not in rejected_ids]
|
| 46 |
+
|
| 47 |
+
state, reports, history = improve_allocation(network, option=delivery_option, iterations=lns_iterations, seed=seed)
|
| 48 |
+
|
| 49 |
+
fulfilled_orders = [o for o in network.orders if any(l.qty_fulfilled > 0 for l in o.lines)]
|
| 50 |
+
returns = generate_returns(network, fulfilled_orders, seed=seed + 1)
|
| 51 |
+
return_summary = summarize_returns(network, returns)
|
| 52 |
+
|
| 53 |
+
metrics = compute_metrics(network, reports, return_summary)
|
| 54 |
+
|
| 55 |
+
return PipelineResult(
|
| 56 |
+
network=network,
|
| 57 |
+
reports=reports,
|
| 58 |
+
admission_rejections=admission_rejections,
|
| 59 |
+
return_summary=return_summary,
|
| 60 |
+
metrics=metrics,
|
| 61 |
+
cost_history=history,
|
| 62 |
+
)
|
| 63 |
+
|
| 64 |
+
|
| 65 |
+
def run_delivery_options_for_order(scenario_key: str, order_index: int = 0, seed: int = 42) -> tuple[Network, list[OptionResult]]:
|
| 66 |
+
network = generate_network(scenario_key, seed=seed)
|
| 67 |
+
state = build_state(network)
|
| 68 |
+
order = network.orders[order_index]
|
| 69 |
+
results = compare_delivery_options(network, order, state)
|
| 70 |
+
return network, results
|
space-bundle/src/omnitower/omnitower/returns.py
ADDED
|
@@ -0,0 +1,77 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Reverse logistics: return generation, routing, and resell decisioning.
|
| 2 |
+
|
| 3 |
+
For each fulfilled order line, a return is sampled using the SKU's return
|
| 4 |
+
probability. Each return gets a quality score (condition on arrival) and is
|
| 5 |
+
then routed to the store (fast restock), the central DC, the repair
|
| 6 |
+
center, the recycle center, or disposal — the "resell vs. scrap" decision
|
| 7 |
+
required by the brief — using a rule-based disposition policy that mirrors
|
| 8 |
+
what a reverse-logistics control tower would encode.
|
| 9 |
+
"""
|
| 10 |
+
|
| 11 |
+
from __future__ import annotations
|
| 12 |
+
|
| 13 |
+
import random
|
| 14 |
+
|
| 15 |
+
from .models import Network, Order, ReturnItem
|
| 16 |
+
from .constants import RETURN_HANDLING_COST_USD, RETURN_RECOVERY_VALUE_FACTOR
|
| 17 |
+
|
| 18 |
+
|
| 19 |
+
def _disposition(sku_resalable: bool, quality: float, category: str) -> str:
|
| 20 |
+
if not sku_resalable or quality < 0.25:
|
| 21 |
+
return "recycle" if category in ("electronics_accessory", "home_goods") else "dispose"
|
| 22 |
+
if quality >= 0.85:
|
| 23 |
+
return "restock_store"
|
| 24 |
+
if quality >= 0.60:
|
| 25 |
+
return "restock_dc"
|
| 26 |
+
if quality >= 0.35:
|
| 27 |
+
return "repair"
|
| 28 |
+
return "recycle"
|
| 29 |
+
|
| 30 |
+
|
| 31 |
+
def generate_returns(network: Network, orders: list[Order], seed: int = 7) -> list[ReturnItem]:
|
| 32 |
+
rng = random.Random(seed)
|
| 33 |
+
returns: list[ReturnItem] = []
|
| 34 |
+
rid = 0
|
| 35 |
+
for order in orders:
|
| 36 |
+
for line in order.lines:
|
| 37 |
+
if line.qty_fulfilled <= 0 or line.sku_id not in network.skus:
|
| 38 |
+
continue
|
| 39 |
+
sku = network.skus[line.sku_id]
|
| 40 |
+
for _ in range(line.qty_fulfilled):
|
| 41 |
+
if rng.random() >= sku.return_rate:
|
| 42 |
+
continue
|
| 43 |
+
quality = max(0.0, min(1.0, rng.gauss(0.68, 0.22)))
|
| 44 |
+
disposition = _disposition(sku.resalable, quality, sku.category)
|
| 45 |
+
returns.append(
|
| 46 |
+
ReturnItem(
|
| 47 |
+
return_id=f"RET{rid:05d}",
|
| 48 |
+
order_id=order.order_id,
|
| 49 |
+
sku_id=sku.sku_id,
|
| 50 |
+
qty=1,
|
| 51 |
+
quality_score=round(quality, 3),
|
| 52 |
+
origin_node_id=order.demand_node_id,
|
| 53 |
+
disposition=disposition,
|
| 54 |
+
resold=disposition in ("restock_store", "restock_dc"),
|
| 55 |
+
)
|
| 56 |
+
)
|
| 57 |
+
rid += 1
|
| 58 |
+
return returns
|
| 59 |
+
|
| 60 |
+
|
| 61 |
+
def summarize_returns(network: Network, returns: list[ReturnItem]) -> dict:
|
| 62 |
+
total_handling_cost = 0.0
|
| 63 |
+
total_recovered_value = 0.0
|
| 64 |
+
by_disposition: dict[str, int] = {}
|
| 65 |
+
for r in returns:
|
| 66 |
+
total_handling_cost += RETURN_HANDLING_COST_USD.get(r.disposition, 3.0)
|
| 67 |
+
sku = network.skus.get(r.sku_id)
|
| 68 |
+
unit_price = sku.unit_price if sku else 0.0
|
| 69 |
+
total_recovered_value += unit_price * RETURN_RECOVERY_VALUE_FACTOR.get(r.disposition, 0.0)
|
| 70 |
+
by_disposition[r.disposition] = by_disposition.get(r.disposition, 0) + 1
|
| 71 |
+
return {
|
| 72 |
+
"n_returns": len(returns),
|
| 73 |
+
"total_handling_cost_usd": round(total_handling_cost, 2),
|
| 74 |
+
"total_recovered_value_usd": round(total_recovered_value, 2),
|
| 75 |
+
"resell_rate": round(sum(1 for r in returns if r.resold) / len(returns), 3) if returns else 0.0,
|
| 76 |
+
"by_disposition": by_disposition,
|
| 77 |
+
}
|
space-bundle/src/omnitower/omnitower/visualization.py
ADDED
|
@@ -0,0 +1,47 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Plotly chart builders for the interactive console."""
|
| 2 |
+
|
| 3 |
+
from __future__ import annotations
|
| 4 |
+
|
| 5 |
+
import plotly.graph_objects as go
|
| 6 |
+
|
| 7 |
+
from .options import OptionResult
|
| 8 |
+
|
| 9 |
+
|
| 10 |
+
def kpi_bar(metrics: dict) -> go.Figure:
|
| 11 |
+
keys = ["gross_margin_usd", "fill_rate", "on_time_sla_rate", "split_shipment_rate", "total_carbon_kg", "working_capital_usd"]
|
| 12 |
+
labels = ["Gross Margin ($)", "Fill Rate", "On-Time SLA Rate", "Split Shipment Rate", "Carbon (kg)", "Working Capital ($)"]
|
| 13 |
+
values = [metrics.get(k, 0) for k in keys]
|
| 14 |
+
fig = go.Figure(go.Bar(x=labels, y=values, marker_color="#2563eb"))
|
| 15 |
+
fig.update_layout(title="Network KPIs", template="plotly_white", height=420)
|
| 16 |
+
return fig
|
| 17 |
+
|
| 18 |
+
|
| 19 |
+
def cost_history_plot(history: list[float]) -> go.Figure:
|
| 20 |
+
fig = go.Figure(go.Scatter(y=history, mode="lines+markers", line=dict(color="#16a34a")))
|
| 21 |
+
fig.update_layout(title="ALNS Improvement — Network Cost per Iteration", xaxis_title="Iteration", yaxis_title="Total Cost (USD)", template="plotly_white", height=380)
|
| 22 |
+
return fig
|
| 23 |
+
|
| 24 |
+
|
| 25 |
+
def returns_disposition_pie(by_disposition: dict) -> go.Figure:
|
| 26 |
+
labels = list(by_disposition.keys())
|
| 27 |
+
values = list(by_disposition.values())
|
| 28 |
+
fig = go.Figure(go.Pie(labels=labels, values=values, hole=0.35))
|
| 29 |
+
fig.update_layout(title="Return Disposition Mix", template="plotly_white", height=380)
|
| 30 |
+
return fig
|
| 31 |
+
|
| 32 |
+
|
| 33 |
+
def delivery_options_plot(results: list[OptionResult]) -> go.Figure:
|
| 34 |
+
fig = go.Figure()
|
| 35 |
+
fig.add_trace(go.Bar(name="Cost (USD)", x=[r.option for r in results], y=[r.total_cost_usd for r in results], marker_color="#2563eb"))
|
| 36 |
+
fig.add_trace(go.Bar(name="Lead Time (hours)", x=[r.option for r in results], y=[r.total_lead_time_hours for r in results], marker_color="#f59e0b"))
|
| 37 |
+
fig.add_trace(go.Bar(name="Carbon (kg)", x=[r.option for r in results], y=[r.total_carbon_kg for r in results], marker_color="#16a34a"))
|
| 38 |
+
fig.update_layout(barmode="group", title="Fast vs. Economical vs. Green — Same Order", template="plotly_white", height=420)
|
| 39 |
+
return fig
|
| 40 |
+
|
| 41 |
+
|
| 42 |
+
def inventory_impact_table(results: list[OptionResult]) -> list[list]:
|
| 43 |
+
rows = []
|
| 44 |
+
for r in results:
|
| 45 |
+
for imp in r.inventory_impact:
|
| 46 |
+
rows.append([r.option, imp["node_id"], imp["sku_id"], imp["qty_consumed"], imp["starting"], imp["remaining_after"]])
|
| 47 |
+
return rows
|
space-bundle/src/omnitower/options.py
ADDED
|
@@ -0,0 +1,84 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Highlighted scenario: three delivery options per order.
|
| 2 |
+
|
| 3 |
+
For a single order, computes the Fast / Economical / Green allocation
|
| 4 |
+
independently (each against a snapshot of the current inventory and
|
| 5 |
+
capacity pools) and reports the effect each option would have on future
|
| 6 |
+
inventory and remaining warehouse/store picking capacity, so a planner can
|
| 7 |
+
compare the three before committing to one.
|
| 8 |
+
"""
|
| 9 |
+
|
| 10 |
+
from __future__ import annotations
|
| 11 |
+
|
| 12 |
+
import copy
|
| 13 |
+
from dataclasses import dataclass
|
| 14 |
+
|
| 15 |
+
from .models import Network, Order
|
| 16 |
+
from .allocation import AllocationState, allocate_order, build_state
|
| 17 |
+
from .network import build_graph
|
| 18 |
+
from .constants import DELIVERY_OPTIONS
|
| 19 |
+
|
| 20 |
+
|
| 21 |
+
@dataclass
|
| 22 |
+
class OptionResult:
|
| 23 |
+
option: str
|
| 24 |
+
report: dict
|
| 25 |
+
total_cost_usd: float
|
| 26 |
+
total_lead_time_hours: float
|
| 27 |
+
total_carbon_kg: float
|
| 28 |
+
inventory_impact: list[dict]
|
| 29 |
+
capacity_impact: list[dict]
|
| 30 |
+
|
| 31 |
+
|
| 32 |
+
def _totals(report: dict) -> tuple[float, float, float]:
|
| 33 |
+
cost = sum(r.get("transport_cost_usd", 0) + r.get("pick_cost_usd", 0) + r.get("pack_cost_usd", 0) for r in report["line_reports"])
|
| 34 |
+
lead = max((r.get("lead_time_hours", 0) for r in report["line_reports"]), default=0.0)
|
| 35 |
+
carbon = sum(r.get("carbon_kg", 0) for r in report["line_reports"])
|
| 36 |
+
if report["split_shipment"]:
|
| 37 |
+
cost += 3.20
|
| 38 |
+
return round(cost, 2), round(lead, 1), round(carbon, 2)
|
| 39 |
+
|
| 40 |
+
|
| 41 |
+
def compare_delivery_options(network: Network, order: Order, base_state: AllocationState) -> list[OptionResult]:
|
| 42 |
+
graph = build_graph(network)
|
| 43 |
+
results = []
|
| 44 |
+
for option in DELIVERY_OPTIONS:
|
| 45 |
+
state_copy = AllocationState(inventory=dict(base_state.inventory), capacity=dict(base_state.capacity))
|
| 46 |
+
order_copy = copy.deepcopy(order)
|
| 47 |
+
report = allocate_order(network, order_copy, option, state_copy, graph)
|
| 48 |
+
cost, lead, carbon = _totals(report)
|
| 49 |
+
|
| 50 |
+
inv_impact = []
|
| 51 |
+
cap_impact = []
|
| 52 |
+
touched_nodes = set()
|
| 53 |
+
for line_report in report["line_reports"]:
|
| 54 |
+
node_id, sku_id = line_report["node_id"], line_report["sku_id"]
|
| 55 |
+
inv_impact.append(
|
| 56 |
+
{
|
| 57 |
+
"node_id": node_id,
|
| 58 |
+
"sku_id": sku_id,
|
| 59 |
+
"qty_consumed": line_report["qty"],
|
| 60 |
+
"remaining_after": round(state_copy.inventory.get((node_id, sku_id), 0), 1),
|
| 61 |
+
"starting": round(base_state.inventory.get((node_id, sku_id), 0), 1),
|
| 62 |
+
}
|
| 63 |
+
)
|
| 64 |
+
touched_nodes.add(node_id)
|
| 65 |
+
for node_id in touched_nodes:
|
| 66 |
+
cap_impact.append(
|
| 67 |
+
{
|
| 68 |
+
"node_id": node_id,
|
| 69 |
+
"capacity_remaining_after": round(state_copy.capacity.get(node_id, 0), 1),
|
| 70 |
+
"capacity_starting": round(base_state.capacity.get(node_id, 0), 1),
|
| 71 |
+
}
|
| 72 |
+
)
|
| 73 |
+
results.append(
|
| 74 |
+
OptionResult(
|
| 75 |
+
option=option,
|
| 76 |
+
report=report,
|
| 77 |
+
total_cost_usd=cost,
|
| 78 |
+
total_lead_time_hours=lead,
|
| 79 |
+
total_carbon_kg=carbon,
|
| 80 |
+
inventory_impact=inv_impact,
|
| 81 |
+
capacity_impact=cap_impact,
|
| 82 |
+
)
|
| 83 |
+
)
|
| 84 |
+
return results
|
space-bundle/src/omnitower/pipeline.py
ADDED
|
@@ -0,0 +1,70 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""End-to-end orchestration: generate -> allocate/admit -> improve -> return -> measure."""
|
| 2 |
+
|
| 3 |
+
from __future__ import annotations
|
| 4 |
+
|
| 5 |
+
from dataclasses import dataclass
|
| 6 |
+
|
| 7 |
+
from .models import Network
|
| 8 |
+
from .generator import generate_network
|
| 9 |
+
from .allocation import allocate_all, build_state
|
| 10 |
+
from .admission import evaluate_all
|
| 11 |
+
from .lns_solver import improve_allocation
|
| 12 |
+
from .returns import generate_returns, summarize_returns
|
| 13 |
+
from .metrics import compute_metrics, NetworkMetrics
|
| 14 |
+
from .options import compare_delivery_options, OptionResult
|
| 15 |
+
|
| 16 |
+
|
| 17 |
+
@dataclass
|
| 18 |
+
class PipelineResult:
|
| 19 |
+
network: Network
|
| 20 |
+
reports: dict[str, dict]
|
| 21 |
+
admission_rejections: int
|
| 22 |
+
return_summary: dict
|
| 23 |
+
metrics: NetworkMetrics
|
| 24 |
+
cost_history: list[float]
|
| 25 |
+
|
| 26 |
+
|
| 27 |
+
def run_scenario(
|
| 28 |
+
scenario_key: str,
|
| 29 |
+
seed: int = 42,
|
| 30 |
+
n_stores: int = 24,
|
| 31 |
+
n_skus: int = 60,
|
| 32 |
+
n_orders: int = 260,
|
| 33 |
+
delivery_option: str = "economical",
|
| 34 |
+
lns_iterations: int = 25,
|
| 35 |
+
use_admission_control: bool = True,
|
| 36 |
+
) -> PipelineResult:
|
| 37 |
+
network = generate_network(scenario_key, seed=seed, n_stores=n_stores, n_skus=n_skus, n_orders=n_orders)
|
| 38 |
+
|
| 39 |
+
admission_rejections = 0
|
| 40 |
+
if use_admission_control:
|
| 41 |
+
preview_state = build_state(network)
|
| 42 |
+
decisions = evaluate_all(network, preview_state)
|
| 43 |
+
rejected_ids = {d.order_id for d in decisions if not d.admitted}
|
| 44 |
+
admission_rejections = len(rejected_ids)
|
| 45 |
+
network.orders = [o for o in network.orders if o.order_id not in rejected_ids]
|
| 46 |
+
|
| 47 |
+
state, reports, history = improve_allocation(network, option=delivery_option, iterations=lns_iterations, seed=seed)
|
| 48 |
+
|
| 49 |
+
fulfilled_orders = [o for o in network.orders if any(l.qty_fulfilled > 0 for l in o.lines)]
|
| 50 |
+
returns = generate_returns(network, fulfilled_orders, seed=seed + 1)
|
| 51 |
+
return_summary = summarize_returns(network, returns)
|
| 52 |
+
|
| 53 |
+
metrics = compute_metrics(network, reports, return_summary)
|
| 54 |
+
|
| 55 |
+
return PipelineResult(
|
| 56 |
+
network=network,
|
| 57 |
+
reports=reports,
|
| 58 |
+
admission_rejections=admission_rejections,
|
| 59 |
+
return_summary=return_summary,
|
| 60 |
+
metrics=metrics,
|
| 61 |
+
cost_history=history,
|
| 62 |
+
)
|
| 63 |
+
|
| 64 |
+
|
| 65 |
+
def run_delivery_options_for_order(scenario_key: str, order_index: int = 0, seed: int = 42) -> tuple[Network, list[OptionResult]]:
|
| 66 |
+
network = generate_network(scenario_key, seed=seed)
|
| 67 |
+
state = build_state(network)
|
| 68 |
+
order = network.orders[order_index]
|
| 69 |
+
results = compare_delivery_options(network, order, state)
|
| 70 |
+
return network, results
|
space-bundle/src/omnitower/returns.py
ADDED
|
@@ -0,0 +1,77 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Reverse logistics: return generation, routing, and resell decisioning.
|
| 2 |
+
|
| 3 |
+
For each fulfilled order line, a return is sampled using the SKU's return
|
| 4 |
+
probability. Each return gets a quality score (condition on arrival) and is
|
| 5 |
+
then routed to the store (fast restock), the central DC, the repair
|
| 6 |
+
center, the recycle center, or disposal — the "resell vs. scrap" decision
|
| 7 |
+
required by the brief — using a rule-based disposition policy that mirrors
|
| 8 |
+
what a reverse-logistics control tower would encode.
|
| 9 |
+
"""
|
| 10 |
+
|
| 11 |
+
from __future__ import annotations
|
| 12 |
+
|
| 13 |
+
import random
|
| 14 |
+
|
| 15 |
+
from .models import Network, Order, ReturnItem
|
| 16 |
+
from .constants import RETURN_HANDLING_COST_USD, RETURN_RECOVERY_VALUE_FACTOR
|
| 17 |
+
|
| 18 |
+
|
| 19 |
+
def _disposition(sku_resalable: bool, quality: float, category: str) -> str:
|
| 20 |
+
if not sku_resalable or quality < 0.25:
|
| 21 |
+
return "recycle" if category in ("electronics_accessory", "home_goods") else "dispose"
|
| 22 |
+
if quality >= 0.85:
|
| 23 |
+
return "restock_store"
|
| 24 |
+
if quality >= 0.60:
|
| 25 |
+
return "restock_dc"
|
| 26 |
+
if quality >= 0.35:
|
| 27 |
+
return "repair"
|
| 28 |
+
return "recycle"
|
| 29 |
+
|
| 30 |
+
|
| 31 |
+
def generate_returns(network: Network, orders: list[Order], seed: int = 7) -> list[ReturnItem]:
|
| 32 |
+
rng = random.Random(seed)
|
| 33 |
+
returns: list[ReturnItem] = []
|
| 34 |
+
rid = 0
|
| 35 |
+
for order in orders:
|
| 36 |
+
for line in order.lines:
|
| 37 |
+
if line.qty_fulfilled <= 0 or line.sku_id not in network.skus:
|
| 38 |
+
continue
|
| 39 |
+
sku = network.skus[line.sku_id]
|
| 40 |
+
for _ in range(line.qty_fulfilled):
|
| 41 |
+
if rng.random() >= sku.return_rate:
|
| 42 |
+
continue
|
| 43 |
+
quality = max(0.0, min(1.0, rng.gauss(0.68, 0.22)))
|
| 44 |
+
disposition = _disposition(sku.resalable, quality, sku.category)
|
| 45 |
+
returns.append(
|
| 46 |
+
ReturnItem(
|
| 47 |
+
return_id=f"RET{rid:05d}",
|
| 48 |
+
order_id=order.order_id,
|
| 49 |
+
sku_id=sku.sku_id,
|
| 50 |
+
qty=1,
|
| 51 |
+
quality_score=round(quality, 3),
|
| 52 |
+
origin_node_id=order.demand_node_id,
|
| 53 |
+
disposition=disposition,
|
| 54 |
+
resold=disposition in ("restock_store", "restock_dc"),
|
| 55 |
+
)
|
| 56 |
+
)
|
| 57 |
+
rid += 1
|
| 58 |
+
return returns
|
| 59 |
+
|
| 60 |
+
|
| 61 |
+
def summarize_returns(network: Network, returns: list[ReturnItem]) -> dict:
|
| 62 |
+
total_handling_cost = 0.0
|
| 63 |
+
total_recovered_value = 0.0
|
| 64 |
+
by_disposition: dict[str, int] = {}
|
| 65 |
+
for r in returns:
|
| 66 |
+
total_handling_cost += RETURN_HANDLING_COST_USD.get(r.disposition, 3.0)
|
| 67 |
+
sku = network.skus.get(r.sku_id)
|
| 68 |
+
unit_price = sku.unit_price if sku else 0.0
|
| 69 |
+
total_recovered_value += unit_price * RETURN_RECOVERY_VALUE_FACTOR.get(r.disposition, 0.0)
|
| 70 |
+
by_disposition[r.disposition] = by_disposition.get(r.disposition, 0) + 1
|
| 71 |
+
return {
|
| 72 |
+
"n_returns": len(returns),
|
| 73 |
+
"total_handling_cost_usd": round(total_handling_cost, 2),
|
| 74 |
+
"total_recovered_value_usd": round(total_recovered_value, 2),
|
| 75 |
+
"resell_rate": round(sum(1 for r in returns if r.resold) / len(returns), 3) if returns else 0.0,
|
| 76 |
+
"by_disposition": by_disposition,
|
| 77 |
+
}
|
space-bundle/src/omnitower/visualization.py
ADDED
|
@@ -0,0 +1,47 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Plotly chart builders for the interactive console."""
|
| 2 |
+
|
| 3 |
+
from __future__ import annotations
|
| 4 |
+
|
| 5 |
+
import plotly.graph_objects as go
|
| 6 |
+
|
| 7 |
+
from .options import OptionResult
|
| 8 |
+
|
| 9 |
+
|
| 10 |
+
def kpi_bar(metrics: dict) -> go.Figure:
|
| 11 |
+
keys = ["gross_margin_usd", "fill_rate", "on_time_sla_rate", "split_shipment_rate", "total_carbon_kg", "working_capital_usd"]
|
| 12 |
+
labels = ["Gross Margin ($)", "Fill Rate", "On-Time SLA Rate", "Split Shipment Rate", "Carbon (kg)", "Working Capital ($)"]
|
| 13 |
+
values = [metrics.get(k, 0) for k in keys]
|
| 14 |
+
fig = go.Figure(go.Bar(x=labels, y=values, marker_color="#2563eb"))
|
| 15 |
+
fig.update_layout(title="Network KPIs", template="plotly_white", height=420)
|
| 16 |
+
return fig
|
| 17 |
+
|
| 18 |
+
|
| 19 |
+
def cost_history_plot(history: list[float]) -> go.Figure:
|
| 20 |
+
fig = go.Figure(go.Scatter(y=history, mode="lines+markers", line=dict(color="#16a34a")))
|
| 21 |
+
fig.update_layout(title="ALNS Improvement — Network Cost per Iteration", xaxis_title="Iteration", yaxis_title="Total Cost (USD)", template="plotly_white", height=380)
|
| 22 |
+
return fig
|
| 23 |
+
|
| 24 |
+
|
| 25 |
+
def returns_disposition_pie(by_disposition: dict) -> go.Figure:
|
| 26 |
+
labels = list(by_disposition.keys())
|
| 27 |
+
values = list(by_disposition.values())
|
| 28 |
+
fig = go.Figure(go.Pie(labels=labels, values=values, hole=0.35))
|
| 29 |
+
fig.update_layout(title="Return Disposition Mix", template="plotly_white", height=380)
|
| 30 |
+
return fig
|
| 31 |
+
|
| 32 |
+
|
| 33 |
+
def delivery_options_plot(results: list[OptionResult]) -> go.Figure:
|
| 34 |
+
fig = go.Figure()
|
| 35 |
+
fig.add_trace(go.Bar(name="Cost (USD)", x=[r.option for r in results], y=[r.total_cost_usd for r in results], marker_color="#2563eb"))
|
| 36 |
+
fig.add_trace(go.Bar(name="Lead Time (hours)", x=[r.option for r in results], y=[r.total_lead_time_hours for r in results], marker_color="#f59e0b"))
|
| 37 |
+
fig.add_trace(go.Bar(name="Carbon (kg)", x=[r.option for r in results], y=[r.total_carbon_kg for r in results], marker_color="#16a34a"))
|
| 38 |
+
fig.update_layout(barmode="group", title="Fast vs. Economical vs. Green — Same Order", template="plotly_white", height=420)
|
| 39 |
+
return fig
|
| 40 |
+
|
| 41 |
+
|
| 42 |
+
def inventory_impact_table(results: list[OptionResult]) -> list[list]:
|
| 43 |
+
rows = []
|
| 44 |
+
for r in results:
|
| 45 |
+
for imp in r.inventory_impact:
|
| 46 |
+
rows.append([r.option, imp["node_id"], imp["sku_id"], imp["qty_consumed"], imp["starting"], imp["remaining_after"]])
|
| 47 |
+
return rows
|