Skip to main content

黏菌启发的轻量级路径规划库 — BFS 气味扩散 + 加权概率爬行

Project description

SlimeMold v0.3.0

BFS 气味扩散 + 加权概率爬行。受黏菌(Physarum polycephalum)觅食行为启发。 BFS scent diffusion + weighted random crawl. Inspired by slime mold foraging behavior.

零依赖核心。Python 3.10+。Win / Mac 原生。 Zero-dependency core. Python 3.10+. Win / Mac native.


什么是 SlimeMold

What is SlimeMold

SlimeMold 是一个 Python 路径规划库。你把二维网格地图给它,告诉它起点和终点,它返回一条路径。 SlimeMold is a Python pathfinding library. Give it a 2D grid map, tell it where to start and where to go, and it returns a path.

它不是 A*。不是 Dijkstra。它是黏菌。 It's not A*. Not Dijkstra. It's slime mold.

真实黏菌(Physarum polycephalum)没有大脑,却能找到食物之间的最短路径。SlimeMold 模拟了这个过程:从目标点向外扩散化学信号(BFS),然后代理沿着气味梯度向目标爬行。听起来像科幻,但算法很朴素——甚至有点可爱。 Real slime molds have no brain, yet they find the shortest routes between food sources. SlimeMold simulates this: diffuse chemical signals outward from the goal (BFS), then crawl along the scent gradient toward the target. Sounds sci-fi, but the algorithm is plain—arguably cute.

from slime_mold import SlimeMold

grid = [
    [0, 0, 0, 0, 0],
    [0, 1, 1, 1, 0],
    [0, 0, 0, 0, 0],
    [0, 1, 1, 1, 0],
    [0, 0, 0, 0, 0],
]

sm = SlimeMold(grid)
path = sm.find_path((0, 0), (4, 4))
print(path)  # [(0, 0), (1, 0), (2, 0), ...]

哲学

Philosophy

SlimeMold 遵循 SilentStudio 统一开发哲学。此处不展开,详见 SilentStudio 哲学文档。 SlimeMold follows the SilentStudio development philosophy. Details are in the SilentStudio philosophy document.

在 SlimeMold 中的体现: As reflected in SlimeMold:

  • 代码干净。 注释说人话,不写科幻小说。 Clean code. Comments say what they mean. No sci-fi.
  • 报错精确。 你传了错的参数,库告诉你哪个参数错了、收到了什么、应该是什么。不让你翻源码。 Precise errors. Wrong argument? The library tells you which one, what it got, and what it expected. No source-diving.

安装

Installation

# 核心库 — 零依赖
# Core library — zero dependencies
pip install slimemold

# 带可视化窗口
# With visualization window
pip install slimemold[view]

# 大图加速(> 500×500)
# Large map acceleration (> 500×500)
pip install slimemold[numpy]

# 全家桶
# Full package
pip install slimemold[view,numpy]

Python 3.10 ~ 3.14 全部支持。 Supports Python 3.10 through 3.14.


30 秒上手

30-Second Quickstart

from slime_mold import SlimeMold

# 0 = 可通行, 1 = 障碍物
# 0 = passable, 1 = obstacle
grid = [
    [0, 0, 0, 0, 0],
    [0, 1, 1, 1, 0],
    [0, 0, 0, 0, 0],
    [0, 1, 1, 1, 0],
    [0, 0, 0, 0, 0],
]

sm = SlimeMold(grid)

# 默认 optimal — 加权概率探索
# Default optimal — weighted random crawl
path = sm.find_path((0, 0), (4, 4))
print(path)

# 严格最短
# Strict shortest path
path = sm.find_path((0, 0), (4, 4), strategy="shortest")

# 打开可视化窗口(需要 pip install slimemold[view])
# Open visualization window (requires pip install slimemold[view])
sm.window(start=(0, 0), goal=(4, 4))

核心概念

Core Concepts

地图

The Grid

地图是一个二维整数列表。0 = 可通行。1 = 障碍物。就这么简单。没有权重,没有代价,没有"半透明墙"。 The grid is a 2D list of integers. 0 = passable. 1 = obstacle. That's it. No weights, no costs, no semi-permeable walls.

grid = [
    [0, 0, 0, 0],  # 第 0 行 / row 0
    [0, 1, 1, 0],  # 第 1 行 / row 1
    [0, 0, 0, 0],  # 第 2 行 / row 2
]

所有行的长度必须相等。传入不规则网格会在构造时立刻报错。 All rows must be the same length. Irregular grids raise an error immediately on construction.

地图最大支持多少?没有硬性限制。超过 500×500 时会温和提示你装 slimemold[numpy] 以获得更好性能。 How big can the grid be? No hard limit. A gentle warning suggests slimemold[numpy] for grids larger than 500×500.

气味场

The Scent Field

当你调用 find_path(start, goal) 时,SlimeMold 首先从终点做一次 BFS 扩散,给每个可通行格子标上"到终点的最短步数"。这就是气味场。 When you call find_path(start, goal), SlimeMold first runs a BFS from the goal, labeling every passable cell with its shortest distance to the goal. This is the scent field.

终点标记为 0
Goal is labeled 0
终点周围一格标记为 1
Cells adjacent to goal are labeled 1
再外一圈标记为 2
The next ring is labeled 2
以此类推...
And so on...

气味场会被缓存。同一个终点连续寻路时,BFS 只跑一次。 The scent field is cached. Consecutive pathfinding to the same goal runs BFS only once.

爬行策略

Crawl Strategies

有了气味场之后,代理从起点出发,每一步选择"气味更浓"(值更小)的邻居,直到到达终点(值 = 0)。 Once the scent field is ready, an agent starts at the starting point and moves each step to a neighbor with a stronger scent (smaller value), until it reaches the goal (value = 0).

这个过程中有两个策略可选:"shortest""optimal"(默认)。 There are two strategies to choose from: "shortest" and "optimal" (default).


API 参考

API Reference

SlimeMold(grid)

构造一个路径规划器实例。 Construct a pathfinding solver instance.

参数 Param 类型 Type 说明 Description
grid List[List[int]] 二维网格。0=可通行,1=障碍物。2D grid. 0=passable, 1=obstacle.
sm = SlimeMold(grid)

如果 grid 为空,或各行长度不一致,立刻抛出 ValueError。 Raises ValueError immediately if grid is empty or rows have inconsistent lengths.

如果地图 > 250,000 格且未安装 NumPy,发出 UserWarning。 Emits a UserWarning if the grid exceeds 250,000 cells and NumPy is not installed.

find_path(start, goal, ...)

计算从起点到终点的路径。 Compute a path from start to goal.

参数 Param 类型 Type 默认 Default 说明 Description
start Tuple[int, int] 必填 required 起点坐标 (row, col)。Start position.
goal Tuple[int, int] 必填 required 终点坐标 (row, col)。Goal position.
strategy "optimal" | "shortest" "optimal" 爬行策略。Crawl strategy.
exploration_rate float 0.15 探索强度,0.01.0,仅 "optimal" 生效。Exploration strength, 0.01.0. Only for "optimal".

返回值 / ReturnsList[Tuple[int, int]] — 从起点到终点的路径列表(含起终点)。不可达时返回 []。 A list of coordinates from start to goal (inclusive). Returns [] when unreachable.

# 默认 optimal
path = sm.find_path((0, 0), (4, 4))

# 严格最短
path = sm.find_path((0, 0), (4, 4), strategy="shortest")

# 高探索率 — 路径更多样化
# High exploration — more diverse paths
path = sm.find_path((0, 0), (4, 4), exploration_rate=0.5)

# 关闭探索 — 等价 shortest
# No exploration — equivalent to shortest
path = sm.find_path((0, 0), (4, 4), exploration_rate=0.0)

get_path_data(start, goal, ...)

返回路径规划的完整中间数据,供你自己渲染。 Return complete intermediate data for custom rendering.

参数 Param 类型 Type 默认 Default 说明 Description
start Tuple[int, int] 必填 required 起点。Start.
goal Tuple[int, int] 必填 required 终点。Goal.
strategy str "optimal" 策略。Strategy.
exploration_rate float 0.15 探索率。Exploration rate.

返回值 / ReturnsDict[str, Any]

data = sm.get_path_data((0, 0), (4, 4))
# data = {
#     "grid": [[0, 0, ...], ...],      # 原始地图 / original grid
#     "scent": [[5, 4, ...], ...],      # 气味梯度场 / scent field
#     "path": [(0, 0), (0, 1), ...],    # 路径 / path
#     "start": (0, 0),                  # 起点 / start
#     "goal": (4, 4),                   # 终点 / goal
#     "strategy": "optimal",            # 策略 / strategy
#     "exploration_rate": 0.15,         # 探索率 / exploration rate
#     "steps": 8,                       # 路径步数(不含起点) / path steps (excluding start)
# }

拿到 data 后你可以用 matplotlib、pygame、Unity、网页 Canvas 随便画。SlimeMold 只负责算,不绑定渲染。 With data you can render with matplotlib, pygame, Unity, a web canvas—whatever you want. SlimeMold does the math, not the drawing.

window()

打开 Qt 可视化窗口。首次调用时才加载 PySide6。 Open a Qt visualization window. PySide6 is imported only on first call.

参数 Param 类型 Type 默认 Default 说明 Description
start Tuple[int, int] (0, 0) 起点。Start.
goal Tuple[int, int] 右下角 bottom-right 终点。Goal.
strategy str "optimal" 策略。Strategy.
exploration_rate float 0.15 探索率。Exploration rate.
cell_size int 40 每格像素。Pixels per cell.
delay float 0.03 每步动画间隔(秒)。Animation delay per step (seconds).
title str "SlimeMold" 窗口标题。Window title.
verbose bool True 控制台同步输出。Console output on.
console_format "rich" | "json" | "plain" "rich" 控制台格式。Console format.
style dict {} 自定义样式(覆盖默认值)。Custom style (overrides defaults).
# 简单调用
# Simple call
sm.window(start=(0, 0), goal=(9, 9))

# 自定义样式
# Custom style
sm.window(
    start=(0, 0), goal=(4, 4),
    style={
        "floor": "#1e1e2e",
        "wall": "#45475a",
        "path": "#f5c2e7",
        "start_label": "起",
        "goal_label": "终",
    }
)

# 关闭控制台输出
# Silent console
sm.window(start=(0, 0), goal=(4, 4), verbose=False)

# JSON 格式控制台输出
# JSON console format
sm.window(start=(0, 0), goal=(4, 4), console_format="json")

路径策略详解

Strategies in Depth

shortest — 严格最短

shortest — Strict Steepest Descent

每一步严格选择气味最浓(值最小)的邻居。在无权网格中,这保证是全局最短路径,因为 BFS 已经精确计算了每个格子到终点的最短步数。 Every step strictly chooses the neighbor with the strongest scent (smallest value). In an unweighted grid, this guarantees the globally shortest path, because BFS already computed the exact shortest distance from every cell to the goal.

path = sm.find_path((0, 0), (4, 4), strategy="shortest")
# 每次返回相同的最短路径
# Always returns the same shortest path

适用场景:确定性的最短路径需求,如 NPC 常规移动、配送路线规划。 Use when: you need deterministic shortest paths, like NPC movement or delivery route planning.

optimal — 加权概率探索

optimal — Weighted Random Crawl

每一步以加权概率选择方向。气味越浓(值越小)被选中的概率越大,但也存在概率选择次优方向。 Each step chooses a direction with weighted probability. Stronger scents get higher probability, but suboptimal directions still have a chance.

path = sm.find_path((0, 0), (4, 4), strategy="optimal")
# 每次可能返回不同的路径
# May return a different path each time

这不是 bug。这正是真实黏菌的行为——先广泛探索,再收缩最优路径。 This is not a bug. This is how real slime molds behave—explore broadly first, then contract to optimal routes.

优势 Advantages

  • 不完全信息地图下更鲁棒。临时障碍出现时,有概率已经绕开。 More robust in partially-known maps. If a temporary obstacle appears, there's a chance you've already detoured.
  • 多代理并发时自然分散流量,避免拥堵。 Naturally distributes traffic when multiple agents pathfind simultaneously.
  • 路径多样化,更接近真实黏菌行为。 Diverse paths, closer to real slime mold behavior.

劣势 Disadvantages

  • 路径长度可能比最短长 20-50%。 Path length may exceed the shortest by 20-50%.
  • 同一地图两次调用可能返回不同路径。 Two calls on the same map may return different paths.
  • 有随机数开销(微小)。 Minor random number overhead.

探索率怎么调

Tuning exploration_rate

值 Value 行为 Behavior 适用场景 Use Case
0.0 等价 shortest。Same as shortest. 确定性需求。Deterministic.
0.05 偶尔绕路。Rarely detours. 近乎最短,微多样性。Near-shortest, slight variety.
0.15 默认。85% 走最短方向。Default. 85% shortest. 通用场景。General purpose.
0.3 显著多样化。Noticeably diverse. 多代理分散。Multi-agent distribution.
0.5 高度随机。Highly random. 探索性任务。Exploratory tasks.
1.0 几乎纯随机(但不走回头路)。Nearly pure random (but no backtracking). 混沌测试。Chaos testing.
# 调整探索率
# Tune exploration rate
sm.find_path(start, goal, exploration_rate=0.05)   # 接近最短 / near-shortest
sm.find_path(start, goal, exploration_rate=0.30)   # 强探索 / high exploration

报错系统

Error System

SlimeMold 的报错系统是它的核心特色之一。每一个错误都在算法执行前被拦截,精确指明问题所在。你不会看到模糊的系统异常——只会看到具体的、可操作的错误信息。 SlimeMold's error system is one of its defining features. Every error is intercepted before the algorithm runs, pinpointing exactly what went wrong. You will never see vague system exceptions—only specific, actionable error messages.

拦截清单

Intercept Checklist

SlimeMold 在 find_path() 入口处设置了完整的入参防火墙。以下所有情况都会被精确拦截: SlimeMold has a complete parameter validation firewall at the entry of find_path(). All of the following are precisely intercepted:

参数类型错误 / Wrong parameter type:

sm.find_path(None, (4, 4))
# → InvalidParameterError: 参数 'start' 必须是 tuple or list,实际收到 NoneType。
# → InvalidParameterError: Parameter 'start' must be tuple or list, got NoneType.

sm.find_path((0, 0), "右下角")
# → InvalidParameterError: 参数 'goal' 必须是 tuple or list,实际收到 str。

sm.find_path(42, (4, 4))
# → InvalidParameterError: 参数 'start' 必须是 tuple or list,实际收到 int。

sm.find_path((0, 0), {"row": 4, "col": 4})
# → InvalidParameterError: 参数 'goal' 必须是 tuple or list,实际收到 dict。

坐标长度错误 / Wrong coordinate length:

sm.find_path((0,), (4, 4))
# → InvalidParameterError: start 必须有 2 个元素,实际有 1 个。
# → InvalidParameterError: start must have 2 elements, got 1.

sm.find_path((0, 0), (1, 2, 3, 4, 5))
# → InvalidParameterError: goal 必须有 2 个元素,实际有 5 个。

sm.find_path((), (4, 4))
# → InvalidParameterError: start 必须有 2 个元素,实际有 0 个。

坐标类型错误 / Wrong coordinate type:

sm.find_path(("a", "b"), (4, 4))
# → InvalidParameterError: start 坐标必须是 int 类型,实际收到 (str, str)。
# → InvalidParameterError: start coordinates must be int, got (str, str).

sm.find_path((0, 0), (2.5, 3.14))
# → InvalidParameterError: goal 坐标必须是 int 类型,实际收到 (float, float)。

坐标越界 / Out-of-bounds coordinates:

sm.find_path((-1, 0), (4, 4))
# → OutOfBoundsError: 起点 (-1, 0) 超出地图边界。地图尺寸: 4x4(索引从0开始)。
# → OutOfBoundsError: start (-1, 0) is out of bounds. Map size: 4x4 (0-indexed).

sm.find_path((0, 0), (999, 999))
# → OutOfBoundsError: 终点 (999, 999) 超出地图边界。地图尺寸: 4x4(索引从0开始)。

坐标在障碍物上 / Coordinates on obstacle:

sm.find_path((1, 1), (4, 4))
# → BlockedCellError: 起点 (1, 1) 落在障碍物上。
# → BlockedCellError: start (1, 1) is on an obstacle.

sm.find_path((0, 0), (1, 1))
# → BlockedCellError: 终点 (1, 1) 落在障碍物上。

策略名无效 / Invalid strategy:

sm.find_path((0, 0), (4, 4), strategy="光速")
# → InvalidParameterError: strategy 只能是 'shortest' 或 'optimal',收到 '光速'。

sm.find_path((0, 0), (4, 4), strategy="🚀")
# → InvalidParameterError: strategy 只能是 'shortest' 或 'optimal',收到 '🚀'。

sm.find_path((0, 0), (4, 4), strategy="")
# → InvalidParameterError: strategy 只能是 'shortest' 或 'optimal',收到 ''。

sm.find_path((0, 0), (4, 4), strategy=None)
# → InvalidParameterError: strategy 只能是 'shortest' 或 'optimal',收到 'None'。

探索率越界 / exploration_rate out of range:

sm.find_path((0, 0), (4, 4), exploration_rate=-0.5)
# → InvalidParameterError: exploration_rate 必须在 0.0~1.0 之间,收到 -0.5。
# → InvalidParameterError: exploration_rate must be between 0.0 and 1.0, got -0.5.

sm.find_path((0, 0), (4, 4), exploration_rate=1.5)
# → InvalidParameterError: exploration_rate 必须在 0.0~1.0 之间,收到 1.5。

sm.find_path((0, 0), (4, 4), exploration_rate=float('nan'))
# → InvalidParameterError: exploration_rate 必须在 0.0~1.0 之间,收到 nan。

sm.find_path((0, 0), (4, 4), exploration_rate=float('inf'))
# → InvalidParameterError: exploration_rate 必须在 0.0~1.0 之间,收到 inf。

网格构造错误 / Grid construction error:

SlimeMold([])
# → ValueError: grid 不能为空,且所有行长度必须相等

SlimeMold([[0, 0], [0, 0, 0]])
# → ValueError: grid 不能为空,且所有行长度必须相等

可视化依赖缺失 / Missing visualization dependency:

sm.window(start=(0, 0), goal=(4, 4))
# 如果未安装 PySide6 / If PySide6 is not installed:
# → ImportError: SlimeMold 的可视化功能需要 PySide6。
#               请执行: pip install slimemold[view]
# → ImportError: SlimeMold visualization requires PySide6.
#                Run: pip install slimemold[view]

多语言

Multilingual Support

自动检测系统语言,加载对应文本。当前支持简体中文(zh_CN)和英语(en_US,兜底)。 Automatically detects system language and loads the corresponding strings. Currently supports Simplified Chinese (zh_CN) and English (en_US, fallback).

检测到不支持的语言时,降级为英语并附加道歉: When an unsupported language is detected, falls back to English with an apology:

It has been detected that your language is ja_JP.
However, SlimeMold v0.3.0 does not yet support your language.
We sincerely apologize for this.

控制台输出

Console Output

window() 支持三种控制台输出格式。通过 console_format 参数设置。 window() supports three console output formats, set via the console_format parameter.

rich 格式(默认)

Rich Format (Default)

带颜色、emoji、进度条。需要终端支持 ANSI 转义码(Win10+、macOS、Linux 都支持)。 With colors, emoji, and a progress bar. Requires ANSI escape code support (Win10+, macOS, Linux).

SlimeMold (0, 0) → (9, 9)  策略: shortest  总步数: 18
  ────────────────────────────────────────
  ● 步 1/17  |  (0, 1)  |  剩余 16   [█░░░░░░░░░░░░░░░░░░░]
  ● 步 2/17  |  (0, 2)  |  剩余 15   [██░░░░░░░░░░░░░░░░░░]
  ...
  ● 步 17/17  |  (8, 9)  |  剩余 0   [████████████████████]
  ────────────────────────────────────────
  ✓ 完成  总步数: 17  策略: shortest

json 格式

JSON Format

每行一个 JSON 对象,适合日志采集和管道处理。 One JSON object per line. Suitable for log ingestion and pipeline processing.

{"event": "start", "start": [0, 0], "goal": [4, 4], "strategy": "optimal", "total_steps": 8}
{"step": 1, "total": 7, "row": 0, "col": 1, "remaining": 6}
{"step": 2, "total": 7, "row": 0, "col": 2, "remaining": 5}
{"event": "done", "steps": 7, "strategy": "optimal"}

plain 格式

Plain Format

纯文本,无颜色,无 emoji。适合重定向到文件或 CI/CD 日志。 Plain text, no color, no emoji. Suitable for file redirection or CI/CD logs.

(0, 0) → (4, 4)  strategy=shortest  total=8 steps
────────────────────────────────────────
  步 1/7  |  (0, 1)  |  剩余 6
  步 2/7  |  (0, 2)  |  剩余 5
✓ done  steps=7  strategy=shortest

关闭输出

Silent Mode

verbose=False — 控制台完全静默,只显示窗口。 verbose=False — console is completely silent. Window only.

sm.window(start=(0, 0), goal=(4, 4), verbose=False)

可视化窗口

Visualization Window

基本用法

Basic Usage

sm.window(start=(0, 0), goal=(9, 9), strategy="shortest")

打开一个 Qt 窗口,包含: Opens a Qt window containing:

  • 网格地图(米色地板,深灰障碍物) Grid map (cream floor, dark gray walls)
  • 起点标记(红色方块 + S) Start marker (red square + S)
  • 终点标记(绿色方块 + G) Goal marker (green square + G)
  • 橙黄色圆点逐帧画出路径 Orange-yellow dots animating the path frame by frame
  • 底部状态栏显示步数和当前坐标 Status bar showing step count and current position
  • 右上角 X 关闭窗口 Close button (X) in the top-right corner

自定义样式

Custom Style

通过 style 字典覆盖任何默认颜色或标签。 Override any default color or label via the style dict.

# 默认值 / Defaults:
DEFAULT_STYLE = {
    "floor": "#f0f0e8",        # 可通行地板 / passable floor
    "wall": "#2d2d2d",         # 障碍物 / wall
    "wall_border": "#1a1a1a",  # 障碍物边框 / wall border
    "path": "#f39c12",         # 路径圆点 / path dots
    "path_border": "#e67e22",  # 路径圆点边框 / path dot border
    "start": "#e74c3c",        # 起点 / start marker
    "goal": "#2ecc71",         # 终点 / goal marker
    "start_label": "S",        # 起点文字 / start label
    "goal_label": "G",         # 终点文字 / goal label
    "background": "#1a1a1a",   # 背景 / background
    "font": "Monaco",          # 字体 / font
}

# 暗色主题示例 / Dark theme example:
sm.window(
    start=(0, 0), goal=(4, 6),
    style={
        "floor": "#1e1e2e",
        "wall": "#45475a",
        "wall_border": "#313244",
        "path": "#f5c2e7",
        "path_border": "#cba6f7",
        "start": "#a6e3a1",
        "goal": "#fab387",
        "start_label": "起",
        "goal_label": "终",
        "background": "#11111b",
    }
)

只改你关心的项,未指定的保持默认值。不用全写。 Only specify the keys you want to change. Unspecified keys keep their defaults.

无 PySide6 时

When PySide6 is Not Installed

如果没有装 slimemold[view],调用 sm.window() 时会抛出友好提示: If slimemold[view] is not installed, calling sm.window() raises a friendly error:

ImportError: SlimeMold 的可视化功能需要 PySide6
请执行: pip install slimemold[view]

核心算法不受影响。find_path()get_path_data() 永远零依赖。 Core algorithm is unaffected. find_path() and get_path_data() are always zero-dependency.


性能基准

Performance Benchmarks

测试环境 / Test environment: Python 3.14, Windows 11 ARM64, no NumPy.

地图 Grid 操作 Operation 耗时 Duration
10×10 BFS + 寻路 / BFS + crawl < 0.001ms
100×100 BFS + 寻路 / BFS + crawl ~0.004ms
100×100 缓存命中 / cache hit ~0.0002ms
100×100 100 次 optimal / 100× optimal ~0.03ms
200×200 螺旋迷宫 / spiral maze ~24ms
2000×2000 构造 / construction ~31ms
1×100000 直线寻路 / straight line ~128ms

缓存对同一终点自动生效,无需配置。 Caching works automatically for the same goal. No configuration needed.


真实场景示例

Real-World Examples

游戏寻路

RTS Game Pathfinding

基地到矿区,5 个兵种同时寻路。 Base to mining zone, 5 units pathfinding simultaneously.

rts_map = [
    [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
    [0, 1, 1, 1, 0, 1, 1, 1, 1, 1, 0, 1, 1, 1, 0],
    [0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 1, 0],
    [1, 1, 0, 1, 1, 1, 1, 1, 0, 1, 1, 1, 0, 1, 0],
    [0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0],
    [0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 0],
    [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
]

sm = SlimeMold(rts_map)

# shortest: 15 步 / 15 steps
path = sm.find_path((6, 0), (6, 14), strategy="shortest")

# optimal: 每个兵种可能走不同路线
# optimal: each unit may take a different route
for i in range(5):
    p = sm.find_path((6, 0), (6, 14), strategy="optimal")

物流仓储

Warehouse Picking

仓库入口 → 取货 → 打包 → 出口,三段接力寻路。 Entrance → pickup → packing → exit. Three-leg relay pathfinding.

warehouse = [
    [0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0],
    [0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0],
    [0, 1, 0, 0, 0, 1, 0, 0, 0, 1, 0],
    [0, 1, 1, 1, 0, 1, 1, 1, 0, 1, 0],
    [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
]

sm = SlimeMold(warehouse)
leg1 = sm.find_path((4, 0), (0, 2))   # 入口→取货 / entrance→pickup
leg2 = sm.find_path((0, 2), (0, 8))   # 取货→打包 / pickup→packing
leg3 = sm.find_path((0, 8), (4, 10))  # 打包→出口 / packing→exit

扫地机器人

Robot Vacuum

客厅到充电座,最短 vs 探索模式。 Living room to charging dock. Shortest vs exploration mode.

living_room = [
    [0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
    [0, 0, 0, 1, 1, 1, 0, 0, 0, 0],
    [0, 0, 0, 0, 0, 1, 0, 1, 1, 0],
    [0, 1, 0, 0, 0, 0, 0, 0, 0, 0],
    [0, 1, 0, 1, 1, 0, 0, 1, 0, 0],
    [0, 0, 0, 0, 0, 0, 0, 1, 0, 0],
    [0, 1, 1, 0, 0, 1, 0, 0, 0, 0],
    [0, 0, 0, 0, 0, 1, 0, 0, 0, 0],
]

sm = SlimeMold(living_room)
path_shortest = sm.find_path((7, 0), (0, 9), strategy="shortest")
path_optimal  = sm.find_path((7, 0), (0, 9), strategy="optimal", exploration_rate=0.2)
# optimal 有概率绕开突然出现的障碍物(如掉在地上的袜子)
# optimal has a chance to detour around sudden obstacles (like a sock on the floor)

城市交通

City Commute

家 → 公司 → 餐厅 → 家。晚高峰某路段封闭后自动绕行。 Home → office → restaurant → home. Automatic detour when a road closes during rush hour.

city = [
    [0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0],
    [0, 1, 1, 0, 1, 0, 1, 1, 1, 1, 1, 0],
    [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
    [0, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 0],
    [0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0],
    [0, 1, 1, 1, 1, 1, 0, 1, 1, 0, 1, 0],
    [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
]

sm = SlimeMold(city)

# 早晨通勤 / Morning commute
to_office = sm.find_path((6, 0), (0, 11))       # 家→公司 / home→office
to_lunch  = sm.find_path((0, 11), (6, 6))       # 公司→餐厅 / office→restaurant
to_home   = sm.find_path((6, 6), (6, 0))        # 餐厅→家 / restaurant→home

# 晚高峰封路 / Road closed during rush hour
city[3][2] = 1
sm_night = SlimeMold(city)
detour = sm_night.find_path((6, 0), (0, 11))    # 自动绕行 / auto detour

# 多个骑手同时出发 / Multiple couriers dispatching simultaneously
for dest in [(0, 2), (0, 8), (3, 7), (6, 11), (4, 10)]:
    path = sm.find_path((6, 0), dest, strategy="optimal", exploration_rate=0.15)

项目结构

Project Structure

SlimeMold/
├── slime_mold/
│   ├── __init__.py              # 包入口,暴露 SlimeMold / package entry
│   ├── core.py                  # 核心引擎 BFS + 爬行 / core engine
│   ├── exceptions/
│   │   ├── __init__.py          # 异常导出 / exception exports
│   │   ├── base.py              # SlimeMoldError 基类 / exception base classes
│   │   ├── localizer.py         # 多语言加载器 / multilingual loader
│   │   └── lang/
│   │       ├── zh_CN.lang       # 简体中文 / Simplified Chinese
│   │       └── en_US.lang       # 英语(兜底)/ English (fallback)
│   └── utils/
│       ├── __init__.py
│       ├── console.py           # 控制台多格式输出 / multi-format console
│       └── visualizer.py        # Qt 可视化窗口 / Qt visualization window
├── tests/
│   ├── test_all.py              # 全功能测试 87 项 / full test suite
│   ├── test_best.py             # 极限压力测试 121 项 / extreme stress tests
│   ├── test_real.py             # 真实场景 / real-world scenarios
│   ├── test_err.py              # 中文报错验证 / Chinese error intercept test
│   ├── test_err_en.py           # 英文报错验证 / English error intercept test
│   └── test_window_all.py       # 可视化全覆盖 / visualization full coverage
├── examples/
│   └── basic_pathfinding.py     # 基础示例 / basic example
├── pyproject.toml               # 打包配置 / packaging config
├── README.md
└── LICENSE

常见问题

FAQ

Q: 为什么不用 A*?A* 不是更快吗? Q: Why not use A*? Isn't A* faster?

A: 在无权网格上,BFS 已经是最优解。A* 的优势体现在有权图上——而 SlimeMold 的哲学是保持简单。无权网格 + BFS = 精确最短,没有启发式函数,没有优先队列。简单即快。 On unweighted grids, BFS is already optimal. A* shines on weighted graphs—and SlimeMold's philosophy is simplicity. Unweighted grid + BFS = exact shortest path. No heuristic, no priority queue. Simple is fast.

Q: 有权重地图支持吗? Q: Does it support weighted grids?

A: 暂不支持。当前地图只有 0(能走)和 1(不能走)。有权重是未来计划,但它会以独立模块出现,不会污染核心 API。 Not yet. Currently the grid is only 0 (passable) and 1 (blocked). Weighted grids are planned for a future module, and will not pollute the core API.

Q: 为什么叫 SlimeMold? Q: Why the name SlimeMold?

A: 黏菌(Physarum polycephalum)是地球上最神奇的生物之一。没有神经系统,却能解决最短路径、网络优化、甚至动态重规划。SlimeMold 的 BFS 扩散 + 梯度爬行,正是它觅食行为的计算抽象。 Slime molds are among the most fascinating organisms on Earth. No nervous system, yet they solve shortest paths, network optimization, and dynamic replanning. SlimeMold's BFS diffusion + gradient crawl is the computational abstraction of their foraging behavior.

Q: 可视化窗口能不能导出图片? Q: Can the visualization window export images?

A: 目前不能。但你可以用 get_path_data() 拿到所有数据,然后用 matplotlib 或任何你喜欢的工具画图导出。 Not yet. But you can use get_path_data() to get all the data, then render and export with matplotlib or any tool you prefer.

Q: optimal 策略怎么调才能得到最多样的路径? Q: How do I tune optimal for maximum path diversity?

A: exploration_rate=0.3~0.5 是多样化的甜点区。太低接近 shortest,太高接近随机游走。 exploration_rate=0.3~0.5 is the sweet spot for diversity. Too low approaches shortest. Too high approaches random walk.

Q: 我能贡献代码吗? Q: Can I contribute?

A: 欢迎。任何 PR 请先跑 python tests/test_all.py,确保 87 项全过。报错信息必须精确,注释必须说人话。 Welcome. Please run python tests/test_all.py and ensure all 87 pass before submitting a PR. Error messages must be precise. Comments must be plain language.


未来计划

Roadmap

  • SlimeMold.Clustering — 多源同时扩散,自动发现数据簇数。无需预设 K 值。 Multi-source simultaneous diffusion. Automatic cluster discovery. No K required.

  • SlimeMold.Recovery — 网络中断时的快速修复路径。 Fast path repair when the network breaks.

  • 分块 BFS — 支持 10000×10000 及更大的地图。 Chunked BFS — support for 10000×10000 and larger grids.

  • 更多语言包。社区贡献欢迎。 More language packs. Community contributions welcome.

  • 有权重地图模块(独立,不污染核心)。 Weighted grid module (standalone, doesn't pollute core).


许可证与版权

License & Copyright

MIT License.

© SilentStudio. Developed by SlimeMoldDev, a division of SilentCodeTeams.
© SilentStudio。由 SilentCodeTeams 旗下的 SlimeMoldDev 开发。

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

slimemold-0.3.1.tar.gz (65.4 kB view details)

Uploaded Source

Built Distribution

If you're not sure about the file name format, learn more about wheel file names.

slimemold-0.3.1-py3-none-any.whl (28.5 kB view details)

Uploaded Python 3

File details

Details for the file slimemold-0.3.1.tar.gz.

File metadata

  • Download URL: slimemold-0.3.1.tar.gz
  • Upload date:
  • Size: 65.4 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.2.0 CPython/3.14.6

File hashes

Hashes for slimemold-0.3.1.tar.gz
Algorithm Hash digest
SHA256 369fa97e6e7a451464449c3910a3179a4f6d101ee55ece2a5aed4483afbe0028
MD5 69705abcfdac289cdeabb30e1c81aed7
BLAKE2b-256 9275dd2a1d4bbcae35ebb828edbe46ae07374a0e2e17560f0901873232123aa1

See more details on using hashes here.

File details

Details for the file slimemold-0.3.1-py3-none-any.whl.

File metadata

  • Download URL: slimemold-0.3.1-py3-none-any.whl
  • Upload date:
  • Size: 28.5 kB
  • Tags: Python 3
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.2.0 CPython/3.14.6

File hashes

Hashes for slimemold-0.3.1-py3-none-any.whl
Algorithm Hash digest
SHA256 764068afc0bf8a67ac431b2646b7e1ce13914e7ea6d3e3b0416e76fef22d620b
MD5 c2be81f7da7c51799a29149c64cfe26c
BLAKE2b-256 0241e78313567ec2aee3715f82d16f916e7d9cb0c28662ed5411e2fcd93a30c5

See more details on using hashes here.

Supported by

AWS Cloud computing and Security Sponsor Datadog Monitoring Depot Continuous Integration Fastly CDN Google Download Analytics Pingdom Monitoring Sentry Error logging StatusPage Status page