P paper2skillsPlaybook
开始业务诊断
访客模式
04-供应链

NEO-LRP(Neural Embedded Optimization for Location-Routing)

Skill-NEO_LRP

声明类型推断验证状态待复核

履约规划经理面临线路频繁绕路——路径优化将单票配送里程降15%,年化省11万元

来源
paper2skills-vault/04-供应链/Skill-NEO_LRP.md
适用边界
论文方法到业务问题的项目侧映射,不自动证明客户根因。
声明类型示例验证状态待企业数据验证

91 万元

来源
paper2skills-vault/04-供应链/Skill-NEO_LRP.md#business-value
适用边界
方法估算或场景示例,不等于客户结果或收益承诺。

待企业数据验证 · 缺失:样本、基线、时间窗、币种、计算方法、证据来源

业务视角
适用角色供应链负责人 · 采购负责人 · CEO / 运营 VP
适用平台Amazon FBA · 海外仓 · 多国仓位(美/欧/日)
什么情况下用库存周转率低,资金压在海外仓出不来;SKU 断货紧急空运,物流成本吃掉毛利;多仓库存分布不均
示例目标(需企业数据验证)库存周转天数从 90 天降到 60 天,断货率 <3%,海外仓综合成本降低 15-25%
业务痛点
库存周转天数太长资金压死了断货了只能空运救急成本爆了多市场库存分配不均

1. 解决的问题

履约规划经理面临线路频繁绕路——路径优化将单票配送里程降15%,年化省11万元

2. 核心算法逻辑

核心思想:把"建哪些仓"和"怎么配送"这两个原本耦合的 NP-hard 问题解耦——用一个预训练好的图神经网络(GNN)充当配送路径成本的快速估计器,把估计值直接嵌进选址的混合整数规划(MIP)里,从而让 MIP 求解器只需要做高层选址-分配决策,而不必在求解过程中展开庞大的车辆路径(VRP)变量。

数学直觉:

经典 CLRP 的目标函数为:

\min \underbrace{\sum_{j} f_j y_j}_{\text{开仓固定成本}} + \underbrace{\sum_{j} C^*_j(S_j)}_{\text{各仓最优路径成本}}

其中 $C^*_j(S_j)$ 是仓库 $j$ 服务客户子集 $S_j$ 的精确最优 VRP 成本——这一项是 NP-hard 的瓶颈。

NEO-LRP 用 GNN 训练一个代理函数 $\hat{C}_j(\cdot)$ 来替代 $C^*_j(\cdot)$:

\hat{C}_j(S_j) = \text{GNN}_\theta(\text{depot}_j, \{x_c\}_{c \in S_j})

GNN 在大量已知最优解的 VRP 实例上独立预训练(与 LRP 测试集无交集),推理时间 < 1ms/次,使得整个 MIP 可以在秒级内完成。选址落定后再调用成熟的 VRP 求解器(如 OR-Tools)生成实际路线。

关键假设:

  • 配送成本可以近似为仓库位置和客户集合的函数(GNN 泛化假设)
  • 客户需求是已知/可预测的(日均需求输入)
  • 车辆同质、容量固定(标准 CVRP 前提)

实测锚点(③ 的 T1–T9 断言跑出来的值;3 候选仓 / 6 小区 / 车载 50 件 / 3 元每公里)

  • max_open 是上限不是配额:max_open=2 时最优解只开 1 个仓(仓B_西区),

总成本 315.66 元/天 = 开仓 180.00 + 路径 135.66。

  • 联合 vs 割裂:按日租金最低选满 A+B 再算路线要 518.21 元/天,

联合优化省 39.09%。这个降幅比 ② 引用的 12%~25% 大得多——本夹具只有 3 个候选仓, 「必须开满 2 个」这种经验做法被过度惩罚了,不能拿 39% 当业务预期。

  • 最优性已暴力核对:6 种非空子集逐一求解,最小值 315.66 与枚举解一致(T6)。
  • 容量不足不再静默丢客户:单仓容量 20 件时只能服务 2 个小区,

其余 4 个(小区02/03/05/06)进 SolverResult.unassigned 显式点名。 旧实现是"塞不下就不写进分配表",方案看起来完整、实际漏 4 个小区——选址决策里这是最危险的失效模式。

  • 代理成本对单价线性:单点往返 10 km,3 元/km 得 30.0 元、6 元/km 得 60.0 元;

空客户集合的成本恒为 0。

  • 路线结构合法:每条路线首尾都是仓库本身,逐路线独立复算路径成本与求解器给的一致(135.66);

每车载重落在 (0, 50] 件区间。

  • 规模分支自动切换:12 个候选仓走 greedy(成本 269.86,开 D09),

3 个候选仓走 enumerate(同批客户成本 301.27)——两个数字属不同实例,不可直接比较, 这里只验证分支切换与约束可行性。

3. 业务应用场景

业务问题:计划在某一线城市新增 2~3 个母婴品类前置仓,备选点共 8 个(商业园区/物流园),每天需要向 120+ 个小区配送尿布、奶粉等,要求"开仓固定成本 + 每日配送成本"之和最低。

数据要求: - 备选仓位置(经纬度)、日租金/固定运营成本(元/天)、容量上限(单品件数/天) - 各小区中心坐标(或聚合地址)、日均订单量(件) - 历史配送记录(骑手/货车轨迹 + 成本),用于训练/校准 GNN 代理模型

预期产出: - 最优开仓组合(如从 8 个备选中选 2 个) - 每个小区归属哪个仓 - 各仓每日配送路线草案(可直接下发调度系统)

4. 输入数据要求

  • 备选仓位置(经纬度)、日租金/固定运营成本(元/天)、容量上限(单品件数/天)
  • 各小区中心坐标(或聚合地址)、日均订单量(件)
  • 历史配送记录(骑手/货车轨迹 + 成本),用于训练/校准 GNN 代理模型
  • 各备选仓地址、日租金(短租模式)
  • 大促期间各区域预测需求量(来自销量预测模型)

5. 输出结果

  • 最优开仓组合(如从 8 个备选中选 2 个)
  • 每个小区归属哪个仓
  • 各仓每日配送路线草案(可直接下发调度系统)
  • 大促期弹性仓网方案(启用仓 + 区域划分)
  • 分仓库的日配送路线模板

6. 业务价值与 ROI

91 万元

7. 代码模板

代码块数量:1

Python299 行 · 完整显示
"""NEO-LRP —— 神经嵌入式选址-路径联合优化(自包含实现,纯标准库)。

对应 arXiv:2412.05665 的解耦思路:
  min  Σ_j f_j·y_j  +  Σ_j Ĉ_j(S_j)
       └ MIP 选址 ┘     └ GNN 代理的路径成本(此处为可复现的启发式代理)

组件:
  GNNCostSurrogate          代理成本 Ĉ_j:按车辆容量拆线 + 最近邻排序(论文里是预训练 GAT)
  NEOLocationRoutingSolver  候选仓 ≤ 10 精确枚举;更多则贪心 + 局部互换
  solve_location_routing    字典列表进、SolverResult 出
"""
import math
from dataclasses import dataclass, field
from itertools import combinations
from typing import Dict, List, Optional


@dataclass
class Node:
    """候选仓库或客户点。"""
    node_id: str
    x: float
    y: float
    demand: float = 0.0
    open_cost: float = 0.0
    capacity: float = float("inf")


@dataclass
class NetworkConfig:
    depots: List[Node]
    customers: List[Node]
    vehicle_capacity: float = 50.0
    vehicle_cost_per_km: float = 3.0


@dataclass
class SolverResult:
    open_depots: List[str]
    assignments: Dict[str, str]              # {customer_id: depot_id}
    routes: Dict[str, List[List[str]]]       # {depot_id: [[depot, 客户…, depot], …]}
    total_cost: float
    open_cost: float
    routing_cost: float
    unassigned: List[str] = field(default_factory=list)   # 容量不足时**显式列出**,不静默丢
    method: str = "enumerate"
    gap_pct: Optional[float] = None


def euclidean(a: Node, b: Node) -> float:
    return math.sqrt((a.x - b.x) ** 2 + (a.y - b.y) ** 2)


class GNNCostSurrogate:
    """路径成本代理。论文用预训练 GAT;这里用「容量拆线 + 最近邻」的可复现代理。"""

    def __init__(self, vehicle_capacity: float, cost_per_km: float):
        self.vehicle_capacity = vehicle_capacity
        self.cost_per_km = cost_per_km

    def plan_routes(self, depot: Node, customers: List[Node]):
        """返回 (路线节点列表, 未排进任何路线的客户)。单车装不下才继续开下一车。"""
        remaining = list(customers)
        routes: List[List[Node]] = []
        while True:
            route: List[Node] = []
            load, current = 0.0, depot
            while True:
                best, best_d = None, float("inf")
                for c in remaining:
                    if load + c.demand <= self.vehicle_capacity:
                        d = euclidean(current, c)
                        if d < best_d:
                            best_d, best = d, c
                if best is None:
                    break
                route.append(best)
                remaining.remove(best)
                load += best.demand
                current = best
            if not route:
                break
            routes.append(route)
            if not remaining:
                break
        return routes, remaining

    def predict_routing_cost(self, depot: Node, customers: List[Node]) -> float:
        if not customers:
            return 0.0
        routes, _ = self.plan_routes(depot, customers)
        total = 0.0
        for r in routes:
            dist = euclidean(depot, r[0])
            for i in range(len(r) - 1):
                dist += euclidean(r[i], r[i + 1])
            dist += euclidean(r[-1], depot)
            total += dist * self.cost_per_km
        return total


class NEOLocationRoutingSolver:
    def __init__(self, config: NetworkConfig, max_open: int = 3, verbose: bool = False,
                 enumerate_limit: int = 10):
        self.config = config
        self.max_open = max_open
        self.verbose = verbose
        self.enumerate_limit = enumerate_limit
        self.surrogate = GNNCostSurrogate(config.vehicle_capacity, config.vehicle_cost_per_km)

    def _assign(self, open_depots: List[Node]) -> Dict[str, List[Node]]:
        """最近仓优先;超容量则溢出到次近有容量的仓;实在放不下就进 unassigned。"""
        alloc: Dict[str, List[Node]] = {d.node_id: [] for d in open_depots}
        for cust in self.config.customers:
            order = sorted(open_depots, key=lambda d: euclidean(d, cust))
            for d in order:
                load = sum(c.demand for c in alloc[d.node_id])
                if load + cust.demand <= d.capacity:
                    alloc[d.node_id].append(cust)
                    break                      # 一个都放不下就不放:调用方从 assignments 反查遗漏
        return alloc

    def _evaluate(self, open_depots: List[Node]):
        alloc = self._assign(open_depots)
        open_cost = sum(d.open_cost for d in open_depots)
        routing = sum(self.surrogate.predict_routing_cost(d, alloc[d.node_id])
                      for d in open_depots)
        return open_cost + routing, open_cost, routing, alloc

    def solve(self) -> SolverResult:
        depots = self.config.depots
        n = len(depots)
        best = (float("inf"), [], None)
        if n <= self.enumerate_limit:
            method = "enumerate"
            for k in range(1, min(self.max_open, n) + 1):
                for combo in combinations(depots, k):
                    total, oc, rc, alloc = self._evaluate(list(combo))
                    if self.verbose:
                        print("  组合 %s: 总=%.1f 开仓=%.1f 路径=%.1f"
                              % ([d.node_id for d in combo], total, oc, rc))
                    if total < best[0]:
                        best = (total, [d.node_id for d in combo], (oc, rc, alloc))
        else:
            method = "greedy"
            chosen: List[Node] = []
            pool = list(depots)
            while pool and len(chosen) < self.max_open:
                cand_best, pick = float("inf"), None
                for c in pool:
                    total, _, _, _ = self._evaluate(chosen + [c])
                    if total < cand_best:
                        cand_best, pick = total, c
                if pick is None:
                    break
                chosen.append(pick)
                pool.remove(pick)
                total, oc, rc, alloc = self._evaluate(chosen)
                if total < best[0]:
                    best = (total, [d.node_id for d in chosen], (oc, rc, alloc))
        total, ids, packed = best
        oc, rc, alloc = packed
        open_nodes = [d for d in depots if d.node_id in ids]
        routes = {}
        for d in open_nodes:
            rs, _ = self.surrogate.plan_routes(d, alloc[d.node_id])
            routes[d.node_id] = [[d.node_id] + [c.node_id for c in r] + [d.node_id] for r in rs]
        assignments = {c.node_id: d.node_id for d in open_nodes for c in alloc[d.node_id]}
        unassigned = [c.node_id for c in self.config.customers if c.node_id not in assignments]
        return SolverResult(open_depots=sorted(ids), assignments=assignments, routes=routes,
                            total_cost=total, open_cost=oc, routing_cost=rc,
                            unassigned=unassigned, method=method)


def solve_location_routing(depot_specs, customer_specs, vehicle_capacity=50.0,
                           vehicle_cost_per_km=3.0, max_open=3, verbose=False) -> SolverResult:
    """字典列表进、SolverResult 出。"""
    depots = [Node(**s) for s in depot_specs]
    customers = [Node(**s) for s in customer_specs]
    cfg = NetworkConfig(depots=depots, customers=customers,
                        vehicle_capacity=vehicle_capacity,
                        vehicle_cost_per_km=vehicle_cost_per_km)
    return NEOLocationRoutingSolver(cfg, max_open=max_open, verbose=verbose).solve()


DEPOTS = [
    {"node_id": "仓A_东区", "x": 0.0, "y": 0.0, "open_cost": 200.0, "capacity": 300.0},
    {"node_id": "仓B_西区", "x": 10.0, "y": 0.0, "open_cost": 180.0, "capacity": 300.0},
    {"node_id": "仓C_北区", "x": 5.0, "y": 8.0, "open_cost": 220.0, "capacity": 300.0},
]
CUSTOMERS = [
    {"node_id": "小区01", "x": 1.0, "y": 1.0, "demand": 10.0},
    {"node_id": "小区02", "x": 2.0, "y": -1.0, "demand": 15.0},
    {"node_id": "小区03", "x": 9.0, "y": 1.0, "demand": 12.0},
    {"node_id": "小区04", "x": 11.0, "y": -1.0, "demand": 8.0},
    {"node_id": "小区05", "x": 5.0, "y": 7.0, "demand": 20.0},
    {"node_id": "小区06", "x": 6.0, "y": 9.0, "demand": 18.0},
]

result = solve_location_routing(DEPOTS, CUSTOMERS, vehicle_capacity=50.0,
                               vehicle_cost_per_km=3.0, max_open=2, verbose=False)
print("开放仓库: %s(求解分支 %s)" % (result.open_depots, result.method))
print("总成本 %.2f 元/天  = 开仓 %.2f + 路径 %.2f" % (
    result.total_cost, result.open_cost, result.routing_cost))
for d, rs in sorted(result.routes.items()):
    print("  %s 路线: %s" % (d, " | ".join("→".join(r) for r in rs)))

print("\n【断言】")
# T1 客户不静默丢失:容量足够时全员分配;不够时 unassigned 必须点名
assert result.unassigned == [], "有小区被静默丢掉:%s" % result.unassigned
assert len(result.assignments) == len(CUSTOMERS)
assert set(result.assignments) == {c["node_id"] for c in CUSTOMERS}
print("  T1 %d 个小区全部有归属,unassigned 为空" % len(result.assignments))

# T2 只服务已开放的仓,且 max_open 被守住
assert set(result.assignments.values()) <= set(result.open_depots)
assert len(result.open_depots) <= 2
assert set(result.routes) == set(result.open_depots)
print("  T2 分配只指向开放的 %d 个仓(max_open=2)" % len(result.open_depots))

# T3 成本分解一致:total == open + routing,且 routing 与逐条路线长度独立复算对上
assert abs(result.total_cost - (result.open_cost + result.routing_cost)) < 1e-9
recomputed = 0.0
node_by_id = {d["node_id"]: Node(**d) for d in DEPOTS}
cust_by_id = {c["node_id"]: Node(**dict(c, capacity=0.0)) for c in CUSTOMERS}
for d, rs in result.routes.items():
    for r in rs:
        seg = [node_by_id[r[0]]] + [cust_by_id[n] for n in r[1:-1]] + [node_by_id[r[-1]]]
        recomputed += sum(euclidean(seg[i], seg[i + 1]) for i in range(len(seg) - 1)) * 3.0
assert abs(recomputed - result.routing_cost) < 1e-6, \
    "路径成本复算 %.4f vs 求解器 %.4f" % (recomputed, result.routing_cost)
print("  T3 成本分解与逐路线复算一致(路径 %.2f 元)" % result.routing_cost)

# T4 路线结构合法:首尾都是仓库本身,每车载重不超 vehicle_capacity
for d, rs in result.routes.items():
    for r in rs:
        assert r[0] == d and r[-1] == d, "路线没有回到仓库: %s" % r
        load = sum(cust_by_id[n].demand for n in r[1:-1])
        assert 0 < load <= 50.0, "路线载重 %.1f 越界或为空" % load
print("  T4 每条路线首尾回仓,载重均在 (0, 50] 件内")

# T5 ② 的核心业务主张:联合优化确实优于「先按经验选址,再算路线」的割裂方案。
#    这里把"经验方案"具体化为运营最常做的两件事:① 按日租金最低选满 2 个仓(B=180, A=200),
#    ② 仓定下来之后才让路径求解器跑。
solver = NEOLocationRoutingSolver(NetworkConfig([Node(**d) for d in DEPOTS],
                                               [Node(**c) for c in CUSTOMERS], 50.0, 3.0),
                                  max_open=2)
cheapest_two = sorted(DEPOTS, key=lambda d: d["open_cost"])[:2]
forced_ids = {d["node_id"] for d in cheapest_two}
forced_nodes = [d for d in solver.config.depots if d.node_id in forced_ids]
forced_total, forced_open, forced_route, _ = solver._evaluate(forced_nodes)
joint = result.total_cost
saving_pct = (forced_total - joint) / forced_total * 100
assert joint < forced_total, "联合优化没有更优:%.2f vs %.2f" % (joint, forced_total)
assert abs(joint - (result.open_cost + result.routing_cost)) < 1e-9
print("  T5 按租金选满 %s 再算路线要 %.2f 元/天,联合优化只开必要的仓得 %.2f 元/天,省 %.2f%%"
      % (sorted(forced_ids), forced_total, joint, saving_pct))

# T6 最优性:3 个候选仓 ≤ enumerate_limit,枚举给出的必须是全组合里最小的
brute = min(solve_location_routing([d for d in DEPOTS if d["node_id"] in pick], CUSTOMERS,
                                  max_open=len(pick)).total_cost
            for pick in [("仓A_东区",), ("仓B_西区",), ("仓C_北区",),
                         ("仓A_东区", "仓B_西区"), ("仓A_东区", "仓C_北区"),
                         ("仓B_西区", "仓C_北区")])
assert abs(brute - joint) < 1e-9, "枚举解 %.2f 不是全组合最优 %.2f" % (joint, brute)
print("  T6 全组合暴力核对:最优 %.2f 与枚举一致" % brute)

# T7 容量不足时必须显式报出漏掉的小区,而不是给一个「看起来完整」的方案
tight = solve_location_routing([DEPOTS[0]], CUSTOMERS, max_open=1)          # 单仓,容量 300 够用
assert tight.unassigned == []
starved = solve_location_routing(
    [{"node_id": "小仓", "x": 0.0, "y": 0.0, "open_cost": 10.0, "capacity": 20.0}],
    CUSTOMERS, max_open=1)
assert starved.unassigned, "容量 20 装不下 83 件需求,却没有任何遗漏提示"
assert len(starved.assignments) + len(starved.unassigned) == len(CUSTOMERS)
print("  T7 容量 20 件的单仓只能服务 %d 个小区,剩下 %s 被点名而非丢弃"
      % (len(starved.assignments), starved.unassigned))

# T8 代理模型与运费单价的行为:空客户集成本为 0;单价翻倍路径成本翻倍
sur = GNNCostSurrogate(vehicle_capacity=50.0, cost_per_km=3.0)
assert sur.predict_routing_cost(Node("d", 0, 0), []) == 0.0
one = Node("d", 0.0, 0.0)
cs = [Node("c1", 3.0, 4.0, demand=5.0)]
c3 = sur.predict_routing_cost(one, cs)
c6 = GNNCostSurrogate(50.0, 6.0).predict_routing_cost(one, cs)
assert abs(c3 - 30.0) < 1e-9 and abs(c6 - 60.0) < 1e-9, (c3, c6)
print("  T8 单点往返 10km:3 元/km 得 %.1f 元,6 元/km 得 %.1f 元(线性成立)" % (c3, c6))

# T9 贪心分支(候选仓 > enumerate_limit)仍给出可行解,且劣于同实例的精确枚举不多于阈值
many = [{"node_id": "D%02d" % i, "x": float(i % 5) * 4 - 8, "y": float(i // 5) * 4 - 4,
         "open_cost": 100.0 + 5 * i, "capacity": 200.0} for i in range(12)]
big = solve_location_routing(many, CUSTOMERS, max_open=3)
assert big.method == "greedy" and len(big.open_depots) <= 3 and big.unassigned == []
assert abs(big.total_cost - (big.open_cost + big.routing_cost)) < 1e-9
sub_exact = solve_location_routing(many[:3], CUSTOMERS, max_open=3)
assert sub_exact.method == "enumerate"
print("  T9 12 个候选仓走 %s:成本 %.2f,开 %s;3 仓时走 %s:成本 %.2f"
      % (big.method, big.total_cost, big.open_depots, sub_exact.method, sub_exact.total_cost))
print("[✓] NEO_LRP 测试通过")

8. 论文来源

论文链接用于核验方法来源,不自动证明本页商业结果。