init
No files matched your search
@@ -0,0 +1,5 @@
|
|||||||
|
.cursor/
|
||||||
|
.pytest_cache/
|
||||||
|
**/*.pyc
|
||||||
|
**/__pycache__/
|
||||||
|
**/*.egg-info/
|
||||||
@@ -0,0 +1,109 @@
|
|||||||
|
# =============================================================================
|
||||||
|
|
||||||
|
# UAVSearch 完整配置 — 修改此文件即可运行,无需 CLI 参数
|
||||||
|
|
||||||
|
# =============================================================================
|
||||||
|
# -----------------------------------------------------------------------------
|
||||||
|
# [problem] 问题定义
|
||||||
|
# -----------------------------------------------------------------------------
|
||||||
|
[problem]
|
||||||
|
width = 1000.0 # 空域宽度 (m)
|
||||||
|
height = 800.0 # 空域高度 (m)
|
||||||
|
uavs = 7 # UAV 数量
|
||||||
|
radius = 50.0 # 传感器半径 (m)
|
||||||
|
speed = 15.0 # 飞行速度 (m/s)
|
||||||
|
depot_service = 60.0 # 站内换电/服务时间 (s)
|
||||||
|
seed = 64 # 随机种子(基线部署与优化器)
|
||||||
|
# 分区模式
|
||||||
|
# workload — 栅格最近站点划分(推荐,优化平滑)
|
||||||
|
# lloyd — Lloyd 松弛栅格划分
|
||||||
|
# voronoi — 站点 Voronoi 图
|
||||||
|
# uniform — 等面积条带(legacy,配 boustrophedon 常用)
|
||||||
|
partition = "voronoi"
|
||||||
|
# 路径规划器
|
||||||
|
# mtsp — 栅格航点 + TSP 闭环(推荐)
|
||||||
|
# boustrophedon — 牛耕/条带扫描
|
||||||
|
planner = "mtsp"
|
||||||
|
# 仿真指标栅格密度(见下方说明,不直接控制路径航点密度)
|
||||||
|
# 仿真栅格边长 cell_size = radius / grid_density
|
||||||
|
# 越大 → 栅格越细 → T_max/覆盖率/重叠率估计越准,但仿真更慢
|
||||||
|
# 推荐:mtsp 用 4~6;boustrophedon 用 3~5(路径已是条带,无需过细)
|
||||||
|
grid_density = 6.0
|
||||||
|
# uniform 分区条带方向;也影响 boustrophedon 扫描轴(auto 时 vertical→水平扫描)
|
||||||
|
# auto | vertical | horizontal
|
||||||
|
strip_direction = "auto"
|
||||||
|
# Lloyd 分区迭代次数(仅 partition = "lloyd" 时生效)
|
||||||
|
lloyd_iterations = 6
|
||||||
|
# 仿真时间步长 (s)
|
||||||
|
sim_dt = 0.5
|
||||||
|
# 站点搜索边界内缩比例(相对空域宽/高)
|
||||||
|
bounds_margin = 0.05
|
||||||
|
# -----------------------------------------------------------------------------
|
||||||
|
# [planner.boustrophedon] 牛耕规划器(planner = "boustrophedon" 时生效)
|
||||||
|
# -----------------------------------------------------------------------------
|
||||||
|
# 条带间距 = sweep_width_ratio × radius
|
||||||
|
# 默认 2.0 → 条带间距 = 2r,与传感器直径一致,保证无漏覆盖
|
||||||
|
# 调小(如 1.6)→ 条带更密、路径更长、覆盖冗余更大
|
||||||
|
# 调大(如 2.2)→ 条带更疏,可能出现漏覆盖
|
||||||
|
[planner.boustrophedon]
|
||||||
|
sweep_width_ratio = 2.0
|
||||||
|
# 扫描轴:x = 水平扫描线(条带沿 Y 堆叠);y = 垂直扫描线
|
||||||
|
# auto — 由 strip_direction 推断(vertical→x,horizontal→y)
|
||||||
|
sweep_axis = "auto"
|
||||||
|
# -----------------------------------------------------------------------------
|
||||||
|
# [planner.mtsp] mTSP 规划器(planner = "mtsp" 时生效)
|
||||||
|
# -----------------------------------------------------------------------------
|
||||||
|
# 航点间距 = waypoint_spacing_factor × radius
|
||||||
|
# 默认 √2 ≈ 1.414 → 栅格对角线间距,相邻航点传感器圆相交无漏
|
||||||
|
# 调小 → 航点更密、路径更长;调大 → 航点更疏,可能漏覆盖
|
||||||
|
[planner.mtsp]
|
||||||
|
waypoint_spacing_factor = 1.0
|
||||||
|
# -----------------------------------------------------------------------------
|
||||||
|
# [simulation] 仿真
|
||||||
|
# -----------------------------------------------------------------------------
|
||||||
|
[simulation]
|
||||||
|
duration = 200.0 # 基线/最终报告仿真时长 (s)
|
||||||
|
opt_duration = 100.0 # 优化搜索阶段每次评估的仿真时长 (s)
|
||||||
|
fast_eval_max_duration = 100.0 # fast_eval 仿真时长上限 (s)
|
||||||
|
fast_eval_grid_density_cap = 3.0 # fast_eval 时 grid_density 上限
|
||||||
|
show_progress = true # 是否显示 tqdm 进度条
|
||||||
|
# -----------------------------------------------------------------------------
|
||||||
|
# [objective] 优化目标
|
||||||
|
# -----------------------------------------------------------------------------
|
||||||
|
# 复合目标 J = weight_t_max × T* + weight_coverage × (1-覆盖率) + weight_overlap × 重叠率
|
||||||
|
# T* = T_max(primary = max_revisit)或 P_max(primary = max_patrol_period)
|
||||||
|
[objective]
|
||||||
|
primary = "max_revisit" # max_revisit | max_patrol_period
|
||||||
|
weight_t_max = 1.0
|
||||||
|
weight_coverage = 220.0
|
||||||
|
weight_overlap = 100.0
|
||||||
|
# -----------------------------------------------------------------------------
|
||||||
|
# [optimizer] 优化器(当前使用 method 指定的那一组)
|
||||||
|
# -----------------------------------------------------------------------------
|
||||||
|
[optimizer]
|
||||||
|
method = "mapso" # differential_evolution | local | hybrid | mapso
|
||||||
|
maxiter = 5 # DE/MAPSO 最大代数;hybrid 时 DE 用 maxiter//2
|
||||||
|
popsize = 8 # 种群规模
|
||||||
|
verbose = true # 打印每次评估日志
|
||||||
|
min_separation_ratio = 0.5 # 站点最小间距 = ratio × radius
|
||||||
|
# MAPSO(method = "mapso" 时生效)
|
||||||
|
[optimizer.mapso]
|
||||||
|
w = 0.729
|
||||||
|
c1 = 1.494
|
||||||
|
c2 = 1.494
|
||||||
|
vmax_ratio = 0.2
|
||||||
|
# 差分进化(method = differential_evolution 或 hybrid 的第一阶段)
|
||||||
|
[optimizer.differential_evolution]
|
||||||
|
tol = 0.05
|
||||||
|
atol = 0.05
|
||||||
|
polish = false
|
||||||
|
# 局部精修 L-BFGS-B(method = local 或 hybrid 的第二阶段)
|
||||||
|
[optimizer.local]
|
||||||
|
maxiter = 40
|
||||||
|
# -----------------------------------------------------------------------------
|
||||||
|
# [run] 运行
|
||||||
|
# -----------------------------------------------------------------------------
|
||||||
|
[run]
|
||||||
|
optimize = true
|
||||||
|
save = "output/dashboard.png"
|
||||||
|
show = true
|
||||||
@@ -0,0 +1,84 @@
|
|||||||
|
#!/usr/bin/env python3
|
||||||
|
"""Compare Voronoi+boustrophedon vs Voronoi+mTSP patrol planners."""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import argparse
|
||||||
|
from pathlib import Path
|
||||||
|
|
||||||
|
import matplotlib.pyplot as plt
|
||||||
|
|
||||||
|
from uavsearch.geometry import RectRegion
|
||||||
|
from uavsearch.partition import generate_uneven_positions
|
||||||
|
from uavsearch.planner import plan_boustrophedon_patrol, plan_mtsp_patrol
|
||||||
|
from uavsearch.sim import PatrolSimulator, compare_planners
|
||||||
|
|
||||||
|
|
||||||
|
def main() -> None:
|
||||||
|
parser = argparse.ArgumentParser(description="Compare patrol planners")
|
||||||
|
parser.add_argument("--width", type=float, default=1000.0)
|
||||||
|
parser.add_argument("--height", type=float, default=800.0)
|
||||||
|
parser.add_argument("--uavs", type=int, default=4)
|
||||||
|
parser.add_argument("--radius", type=float, default=50.0)
|
||||||
|
parser.add_argument("--speed", type=float, default=15.0)
|
||||||
|
parser.add_argument("--seed", type=int, default=42)
|
||||||
|
parser.add_argument("--duration", type=float, default=600.0)
|
||||||
|
parser.add_argument("--grid-density", type=float, default=4.0)
|
||||||
|
parser.add_argument("--save", type=str, default=None)
|
||||||
|
args = parser.parse_args()
|
||||||
|
|
||||||
|
region = RectRegion.from_size(args.width, args.height)
|
||||||
|
sweep_width = 2 * args.radius
|
||||||
|
initial_positions = generate_uneven_positions(region, args.uavs, seed=args.seed)
|
||||||
|
|
||||||
|
strip_paths, strip_partition = plan_boustrophedon_patrol(
|
||||||
|
region, args.uavs, sweep_width, initial_positions=initial_positions
|
||||||
|
)
|
||||||
|
mtsp_paths, mtsp_partition = plan_mtsp_patrol(
|
||||||
|
region, args.uavs, args.radius, initial_positions=initial_positions
|
||||||
|
)
|
||||||
|
|
||||||
|
sim_strip = PatrolSimulator(region, strip_paths, args.speed, args.radius, grid_density=args.grid_density)
|
||||||
|
sim_mtsp = PatrolSimulator(region, mtsp_paths, args.speed, args.radius, grid_density=args.grid_density)
|
||||||
|
m_strip = sim_strip.run(args.duration)
|
||||||
|
m_mtsp = sim_mtsp.run(args.duration)
|
||||||
|
|
||||||
|
print("Uneven initial positions -> uniform partitions:")
|
||||||
|
for cell in strip_partition.cells:
|
||||||
|
ix, iy = cell.initial_position
|
||||||
|
print(f" UAV {cell.uav_id} at ({ix:.1f}, {iy:.1f}) -> partition {cell.partition_id}")
|
||||||
|
print()
|
||||||
|
print("=== Uniform + Boustrophedon ===")
|
||||||
|
print(m_strip.summary())
|
||||||
|
print(f"Load balance: {sim_strip.load_balance_ratio():.2f}")
|
||||||
|
print()
|
||||||
|
print("=== Uniform + mTSP ===")
|
||||||
|
print(m_mtsp.summary())
|
||||||
|
print(f"Load balance: {sim_mtsp.load_balance_ratio():.2f}")
|
||||||
|
print()
|
||||||
|
ratio_strip = m_strip.max_revisit_time / max(m_strip.mean_revisit_time, 1e-9)
|
||||||
|
ratio_mtsp = m_mtsp.max_revisit_time / max(m_mtsp.mean_revisit_time, 1e-9)
|
||||||
|
print(f"T_max/T_mean — Boustrophedon: {ratio_strip:.2f}, mTSP: {ratio_mtsp:.2f}")
|
||||||
|
|
||||||
|
fig = compare_planners(
|
||||||
|
region,
|
||||||
|
strip_paths,
|
||||||
|
mtsp_paths,
|
||||||
|
args.speed,
|
||||||
|
args.radius,
|
||||||
|
args.duration,
|
||||||
|
strip_partition=strip_partition,
|
||||||
|
mtsp_partition=mtsp_partition,
|
||||||
|
)
|
||||||
|
|
||||||
|
if args.save:
|
||||||
|
out = Path(args.save)
|
||||||
|
out.parent.mkdir(parents=True, exist_ok=True)
|
||||||
|
fig.savefig(out, dpi=150, bbox_inches="tight")
|
||||||
|
print(f"Saved comparison to {out}")
|
||||||
|
else:
|
||||||
|
plt.show()
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
main()
|
||||||
@@ -0,0 +1,69 @@
|
|||||||
|
#!/usr/bin/env python3
|
||||||
|
"""Evaluate a fixed deployment (no optimization)."""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import argparse
|
||||||
|
from pathlib import Path
|
||||||
|
|
||||||
|
import matplotlib.pyplot as plt
|
||||||
|
|
||||||
|
from uavsearch.geometry import RectRegion
|
||||||
|
from uavsearch.problem import CoverageProblem, evaluate_deployment, random_deployment
|
||||||
|
from uavsearch.sim import PatrolVisualizer
|
||||||
|
|
||||||
|
|
||||||
|
def main() -> None:
|
||||||
|
parser = argparse.ArgumentParser(description="Evaluate one UAV deployment")
|
||||||
|
parser.add_argument("--width", type=float, default=1000.0)
|
||||||
|
parser.add_argument("--height", type=float, default=800.0)
|
||||||
|
parser.add_argument("--uavs", type=int, default=4)
|
||||||
|
parser.add_argument("--radius", type=float, default=50.0)
|
||||||
|
parser.add_argument("--speed", type=float, default=15.0)
|
||||||
|
parser.add_argument("--seed", type=int, default=42)
|
||||||
|
parser.add_argument("--partition", choices=["uniform", "voronoi"], default="uniform")
|
||||||
|
parser.add_argument("--grid-density", type=float, default=4.0)
|
||||||
|
parser.add_argument("--save", type=str, default=None)
|
||||||
|
args = parser.parse_args()
|
||||||
|
|
||||||
|
region = RectRegion.from_size(args.width, args.height)
|
||||||
|
problem = CoverageProblem(
|
||||||
|
region=region,
|
||||||
|
n_uavs=args.uavs,
|
||||||
|
sensor_radius=args.radius,
|
||||||
|
speed=args.speed,
|
||||||
|
partition_mode=args.partition,
|
||||||
|
grid_density=args.grid_density,
|
||||||
|
)
|
||||||
|
|
||||||
|
positions = random_deployment(problem, seed=args.seed)
|
||||||
|
result = evaluate_deployment(problem, positions)
|
||||||
|
|
||||||
|
print(f"Objective T_max = {result.objective_value:.2f}s")
|
||||||
|
print(result.summary_line())
|
||||||
|
|
||||||
|
from uavsearch.sim import PatrolSimulator
|
||||||
|
|
||||||
|
sim = PatrolSimulator(
|
||||||
|
region, result.solution.paths, args.speed, args.radius, grid_density=args.grid_density
|
||||||
|
)
|
||||||
|
sim.run(result.max_patrol_period * 2.5)
|
||||||
|
|
||||||
|
viz = PatrolVisualizer(region)
|
||||||
|
fig = viz.plot_simulation_snapshot(
|
||||||
|
sim,
|
||||||
|
result.solution.paths,
|
||||||
|
result.solution.metrics,
|
||||||
|
title="Deployment Evaluation",
|
||||||
|
partition=result.solution.partition,
|
||||||
|
)
|
||||||
|
|
||||||
|
if args.save:
|
||||||
|
Path(args.save).parent.mkdir(parents=True, exist_ok=True)
|
||||||
|
fig.savefig(args.save, dpi=150, bbox_inches="tight")
|
||||||
|
else:
|
||||||
|
plt.show()
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
main()
|
||||||
@@ -0,0 +1,276 @@
|
|||||||
|
#!/usr/bin/env python3
|
||||||
|
|
||||||
|
"""
|
||||||
|
|
||||||
|
Find UAV deployment positions that minimize the maximum coverage period T_max.
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
Reads settings from config.toml (project root by default).
|
||||||
|
|
||||||
|
"""
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
import argparse
|
||||||
|
|
||||||
|
import sys
|
||||||
|
|
||||||
|
from pathlib import Path
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
import matplotlib.pyplot as plt
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
from uavsearch import evaluate_deployment, load_config, optimize_deployment
|
||||||
|
|
||||||
|
from uavsearch.config import AppConfig
|
||||||
|
|
||||||
|
from uavsearch.problem import random_deployment
|
||||||
|
|
||||||
|
from uavsearch.sim import PatrolSimulator, PatrolVisualizer
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
def run(cfg: AppConfig) -> None:
|
||||||
|
|
||||||
|
problem = cfg.problem.build_problem(cfg.objective, cfg.planner, cfg.simulation)
|
||||||
|
|
||||||
|
p = cfg.problem
|
||||||
|
|
||||||
|
show_progress = cfg.simulation.show_progress
|
||||||
|
|
||||||
|
opt_sim = cfg.simulation.effective_opt_duration()
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
print("=== Problem ===", flush=True)
|
||||||
|
|
||||||
|
print(f"Region {p.width:.0f}x{p.height:.0f} m, N={p.uavs}, r={p.radius:.0f} m", flush=True)
|
||||||
|
|
||||||
|
print("Objective: minimize T_max (worst-point revisit period)", flush=True)
|
||||||
|
|
||||||
|
print(f"Partition: {p.partition}, planner: {p.planner}", flush=True)
|
||||||
|
|
||||||
|
print(
|
||||||
|
|
||||||
|
f"Method: {cfg.optimizer.method}, maxiter={cfg.optimizer.maxiter}, popsize={cfg.optimizer.popsize}",
|
||||||
|
|
||||||
|
flush=True,
|
||||||
|
|
||||||
|
)
|
||||||
|
|
||||||
|
print(flush=True)
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
print("=== Baseline (random deployment) ===", flush=True)
|
||||||
|
|
||||||
|
baseline_pos = random_deployment(problem, seed=p.seed)
|
||||||
|
|
||||||
|
baseline = evaluate_deployment(
|
||||||
|
|
||||||
|
problem, baseline_pos, sim_duration=cfg.simulation.duration, show_progress=show_progress
|
||||||
|
|
||||||
|
)
|
||||||
|
|
||||||
|
print(baseline.summary_line(), flush=True)
|
||||||
|
|
||||||
|
print(flush=True)
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
if not cfg.run.optimize:
|
||||||
|
|
||||||
|
print("run.optimize=false, skipping optimization.", flush=True)
|
||||||
|
|
||||||
|
return
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
print("=== Optimizing ===", flush=True)
|
||||||
|
|
||||||
|
opt = optimize_deployment(
|
||||||
|
|
||||||
|
problem,
|
||||||
|
|
||||||
|
method=cfg.optimizer.method,
|
||||||
|
|
||||||
|
seed=p.seed,
|
||||||
|
|
||||||
|
maxiter=cfg.optimizer.maxiter,
|
||||||
|
|
||||||
|
popsize=cfg.optimizer.popsize,
|
||||||
|
|
||||||
|
sim_duration=opt_sim,
|
||||||
|
|
||||||
|
initial_guess=baseline_pos,
|
||||||
|
|
||||||
|
show_progress=show_progress,
|
||||||
|
|
||||||
|
mapso_params=cfg.optimizer.mapso,
|
||||||
|
|
||||||
|
)
|
||||||
|
|
||||||
|
best = opt.best
|
||||||
|
|
||||||
|
print(f"Evaluations: {opt.n_evaluations}", flush=True)
|
||||||
|
|
||||||
|
print(best.summary_line(), flush=True)
|
||||||
|
|
||||||
|
improve = (baseline.objective_value - best.objective_value) / max(baseline.objective_value, 1e-9)
|
||||||
|
|
||||||
|
print(f"T_max: {baseline.objective_value:.1f}s -> {best.objective_value:.1f}s ({improve:+.1%})", flush=True)
|
||||||
|
|
||||||
|
_print_positions("Baseline:", baseline.solution.initial_positions)
|
||||||
|
|
||||||
|
_print_positions("Optimized:", best.solution.initial_positions)
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
print("\n=== Rendering figures ===", flush=True)
|
||||||
|
|
||||||
|
region = problem.region
|
||||||
|
|
||||||
|
viz = PatrolVisualizer(region)
|
||||||
|
|
||||||
|
fig, axes = plt.subplots(2, 3, figsize=(22, 13))
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
viz.plot_partition(baseline.solution.partition, ax=axes[0, 0], title="Baseline partition")
|
||||||
|
|
||||||
|
viz.plot_paths(
|
||||||
|
|
||||||
|
baseline.solution.paths,
|
||||||
|
|
||||||
|
ax=axes[0, 1],
|
||||||
|
|
||||||
|
title=f"Baseline patrol\nT_max={baseline.max_revisit_time:.1f}s",
|
||||||
|
|
||||||
|
partition=baseline.solution.partition,
|
||||||
|
|
||||||
|
)
|
||||||
|
|
||||||
|
sim_b = PatrolSimulator(
|
||||||
|
|
||||||
|
region, baseline.solution.paths, p.speed, p.radius,
|
||||||
|
|
||||||
|
grid_density=p.grid_density, depot_service_time=p.depot_service,
|
||||||
|
|
||||||
|
)
|
||||||
|
|
||||||
|
sim_b.run(baseline.max_patrol_period * 3.0, show_progress=show_progress)
|
||||||
|
|
||||||
|
viz.plot_heatmap(sim_b.grid.idle_map(), ax=axes[0, 2], title="Baseline idle time")
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
viz.plot_partition(best.solution.partition, ax=axes[1, 0], title="Optimized partition")
|
||||||
|
|
||||||
|
viz.plot_paths(
|
||||||
|
|
||||||
|
best.solution.paths,
|
||||||
|
|
||||||
|
ax=axes[1, 1],
|
||||||
|
|
||||||
|
title=f"Optimized patrol\nT_max={best.max_revisit_time:.1f}s",
|
||||||
|
|
||||||
|
partition=best.solution.partition,
|
||||||
|
|
||||||
|
)
|
||||||
|
|
||||||
|
sim_o = PatrolSimulator(
|
||||||
|
|
||||||
|
region, best.solution.paths, p.speed, p.radius,
|
||||||
|
|
||||||
|
grid_density=p.grid_density, depot_service_time=p.depot_service,
|
||||||
|
|
||||||
|
)
|
||||||
|
|
||||||
|
sim_o.run(best.max_patrol_period * 3.0, show_progress=show_progress)
|
||||||
|
|
||||||
|
viz.plot_heatmap(sim_o.grid.idle_map(), ax=axes[1, 2], title="Optimized idle time")
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
fig.suptitle(
|
||||||
|
|
||||||
|
f"Coverage Period Minimization — T_max {baseline.objective_value:.1f}s -> {best.objective_value:.1f}s",
|
||||||
|
|
||||||
|
fontsize=14,
|
||||||
|
|
||||||
|
)
|
||||||
|
|
||||||
|
fig.tight_layout()
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
if cfg.run.save:
|
||||||
|
|
||||||
|
out = Path(cfg.run.save)
|
||||||
|
|
||||||
|
out.parent.mkdir(parents=True, exist_ok=True)
|
||||||
|
|
||||||
|
fig.savefig(out, dpi=150, bbox_inches="tight")
|
||||||
|
|
||||||
|
print(f"Saved to {out}", flush=True)
|
||||||
|
|
||||||
|
elif cfg.run.show:
|
||||||
|
|
||||||
|
plt.show()
|
||||||
|
|
||||||
|
else:
|
||||||
|
|
||||||
|
plt.close(fig)
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
def _print_positions(label: str, positions) -> None:
|
||||||
|
|
||||||
|
print(label, flush=True)
|
||||||
|
|
||||||
|
for i, (x, y) in enumerate(positions):
|
||||||
|
|
||||||
|
print(f" UAV {i}: ({x:.1f}, {y:.1f})", flush=True)
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
def main() -> None:
|
||||||
|
|
||||||
|
parser = argparse.ArgumentParser(description="Minimize T_max (config.toml driven)")
|
||||||
|
|
||||||
|
parser.add_argument("--config", type=str, default="config.toml", help="Path to TOML config")
|
||||||
|
|
||||||
|
args = parser.parse_args()
|
||||||
|
|
||||||
|
run(load_config(args.config))
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
|
||||||
|
try:
|
||||||
|
|
||||||
|
main()
|
||||||
|
|
||||||
|
except KeyboardInterrupt:
|
||||||
|
|
||||||
|
print("\nInterrupted.", file=sys.stderr)
|
||||||
|
|
||||||
|
sys.exit(130)
|
||||||
|
|
||||||
@@ -0,0 +1,204 @@
|
|||||||
|
#!/usr/bin/env python3
|
||||||
|
|
||||||
|
"""
|
||||||
|
|
||||||
|
Visual dashboard for multi-UAV coverage-period minimization.
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
Reads settings from config.toml (project root by default).
|
||||||
|
|
||||||
|
"""
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
import argparse
|
||||||
|
|
||||||
|
import sys
|
||||||
|
|
||||||
|
from pathlib import Path
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
import matplotlib.pyplot as plt
|
||||||
|
|
||||||
|
import numpy as np
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
from uavsearch import CoverageProblem, evaluate_deployment, load_config, optimize_deployment
|
||||||
|
|
||||||
|
from uavsearch.config import AppConfig
|
||||||
|
|
||||||
|
from uavsearch.problem import random_deployment
|
||||||
|
|
||||||
|
from uavsearch.viz import plot_coverage_dashboard
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
def run(cfg: AppConfig) -> None:
|
||||||
|
|
||||||
|
problem = cfg.problem.build_problem(cfg.objective, cfg.planner, cfg.simulation)
|
||||||
|
opt_cfg = cfg.optimizer
|
||||||
|
show_progress = cfg.simulation.show_progress
|
||||||
|
|
||||||
|
baseline_pos = random_deployment(problem, seed=cfg.problem.seed)
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
print("Evaluating baseline deployment...", flush=True)
|
||||||
|
|
||||||
|
baseline = evaluate_deployment(
|
||||||
|
|
||||||
|
problem, baseline_pos, sim_duration=cfg.simulation.duration, show_progress=show_progress
|
||||||
|
|
||||||
|
)
|
||||||
|
|
||||||
|
print(baseline.summary_line(), flush=True)
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
opt_result = None
|
||||||
|
|
||||||
|
optimized = baseline
|
||||||
|
|
||||||
|
opt_sim = cfg.simulation.effective_opt_duration()
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
if cfg.run.optimize:
|
||||||
|
|
||||||
|
method = cfg.optimizer.method
|
||||||
|
|
||||||
|
print(f"Optimizing ({method})...", flush=True)
|
||||||
|
|
||||||
|
print(
|
||||||
|
|
||||||
|
f" 搜索仿真时长: {opt_sim:.0f}s/次 (fast_eval), 最终报告: {cfg.simulation.duration:.0f}s",
|
||||||
|
|
||||||
|
flush=True,
|
||||||
|
|
||||||
|
)
|
||||||
|
|
||||||
|
opt_result = optimize_deployment(
|
||||||
|
|
||||||
|
problem,
|
||||||
|
|
||||||
|
method=method,
|
||||||
|
|
||||||
|
seed=cfg.problem.seed,
|
||||||
|
|
||||||
|
maxiter=cfg.optimizer.maxiter,
|
||||||
|
|
||||||
|
popsize=cfg.optimizer.popsize,
|
||||||
|
|
||||||
|
sim_duration=opt_sim,
|
||||||
|
|
||||||
|
initial_guess=baseline_pos,
|
||||||
|
|
||||||
|
show_progress=False,
|
||||||
|
|
||||||
|
mapso_params=cfg.optimizer.mapso,
|
||||||
|
|
||||||
|
)
|
||||||
|
|
||||||
|
optimized = opt_result.best
|
||||||
|
|
||||||
|
print(optimized.summary_line(), flush=True)
|
||||||
|
|
||||||
|
delta = baseline.objective_value - optimized.objective_value
|
||||||
|
|
||||||
|
moved = float(
|
||||||
|
|
||||||
|
np.max(np.linalg.norm(optimized.solution.initial_positions - baseline.solution.initial_positions, axis=1))
|
||||||
|
|
||||||
|
)
|
||||||
|
|
||||||
|
print(f" T_max change: {delta:+.2f}s | max depot move: {moved:.1f} m", flush=True)
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
print("Building dashboard...", flush=True)
|
||||||
|
|
||||||
|
fig = plot_coverage_dashboard(
|
||||||
|
|
||||||
|
problem,
|
||||||
|
|
||||||
|
baseline=baseline,
|
||||||
|
|
||||||
|
optimized=optimized,
|
||||||
|
|
||||||
|
opt_result=opt_result,
|
||||||
|
|
||||||
|
show_progress=show_progress,
|
||||||
|
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
out = Path(cfg.run.save)
|
||||||
|
|
||||||
|
out.parent.mkdir(parents=True, exist_ok=True)
|
||||||
|
|
||||||
|
fig.savefig(out, dpi=150, bbox_inches="tight")
|
||||||
|
|
||||||
|
print(f"Dashboard saved to {out}", flush=True)
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
if cfg.run.show:
|
||||||
|
|
||||||
|
plt.show()
|
||||||
|
|
||||||
|
else:
|
||||||
|
|
||||||
|
plt.close(fig)
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
def main() -> None:
|
||||||
|
|
||||||
|
parser = argparse.ArgumentParser(description="Coverage visualization (config.toml driven)")
|
||||||
|
|
||||||
|
parser.add_argument(
|
||||||
|
|
||||||
|
"--config",
|
||||||
|
|
||||||
|
type=str,
|
||||||
|
|
||||||
|
default="config.toml",
|
||||||
|
|
||||||
|
help="Path to TOML config (default: config.toml in cwd)",
|
||||||
|
|
||||||
|
)
|
||||||
|
|
||||||
|
args = parser.parse_args()
|
||||||
|
|
||||||
|
cfg = load_config(args.config)
|
||||||
|
|
||||||
|
run(cfg)
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
|
||||||
|
try:
|
||||||
|
|
||||||
|
main()
|
||||||
|
|
||||||
|
except KeyboardInterrupt:
|
||||||
|
|
||||||
|
print("\nInterrupted.", file=sys.stderr)
|
||||||
|
|
||||||
|
sys.exit(130)
|
||||||
|
|
||||||
|
After Width: | Height: | Size: 217 KiB |
|
After Width: | Height: | Size: 561 KiB |
|
After Width: | Height: | Size: 108 KiB |
|
After Width: | Height: | Size: 157 KiB |
|
After Width: | Height: | Size: 190 KiB |
|
After Width: | Height: | Size: 328 KiB |
|
After Width: | Height: | Size: 290 KiB |
|
After Width: | Height: | Size: 405 KiB |
@@ -0,0 +1,20 @@
|
|||||||
|
[build-system]
|
||||||
|
requires = ["setuptools>=61"]
|
||||||
|
build-backend = "setuptools.build_meta"
|
||||||
|
|
||||||
|
[project]
|
||||||
|
name = "uavsearch"
|
||||||
|
version = "0.2.0"
|
||||||
|
description = "Minimize coverage period for multi-UAV 2D region patrol (deployment + planning)"
|
||||||
|
requires-python = ">=3.10"
|
||||||
|
dependencies = [
|
||||||
|
"numpy>=1.24",
|
||||||
|
"matplotlib>=3.7",
|
||||||
|
"shapely>=2.0",
|
||||||
|
"scipy>=1.10",
|
||||||
|
"tqdm>=4.66",
|
||||||
|
"tomli>=2.0.1; python_version < '3.11'",
|
||||||
|
]
|
||||||
|
|
||||||
|
[tool.setuptools.packages.find]
|
||||||
|
where = ["src"]
|
||||||
@@ -0,0 +1,6 @@
|
|||||||
|
numpy>=1.24
|
||||||
|
matplotlib>=3.7
|
||||||
|
shapely>=2.0
|
||||||
|
scipy>=1.10
|
||||||
|
tqdm>=4.66
|
||||||
|
tomli>=2.0.1; python_version < '3.11'
|
||||||
@@ -0,0 +1,25 @@
|
|||||||
|
"""
|
||||||
|
UAVSearch — multi-UAV coverage-period minimization.
|
||||||
|
|
||||||
|
Find deployment positions and patrol plans for N UAVs over a 2D region
|
||||||
|
such that the worst-point coverage period T_max is minimized.
|
||||||
|
"""
|
||||||
|
|
||||||
|
from uavsearch.config import AppConfig, load_config
|
||||||
|
from uavsearch.optimizer import DeploymentOptimizer, OptimizationResult, optimize_deployment
|
||||||
|
from uavsearch.problem import CoverageProblem, CoverageObjective, evaluate_deployment
|
||||||
|
from uavsearch.viz import CoverageDashboard, plot_coverage_dashboard
|
||||||
|
|
||||||
|
__version__ = "0.2.0"
|
||||||
|
__all__ = [
|
||||||
|
"AppConfig",
|
||||||
|
"load_config",
|
||||||
|
"CoverageProblem",
|
||||||
|
"CoverageObjective",
|
||||||
|
"evaluate_deployment",
|
||||||
|
"DeploymentOptimizer",
|
||||||
|
"OptimizationResult",
|
||||||
|
"optimize_deployment",
|
||||||
|
"CoverageDashboard",
|
||||||
|
"plot_coverage_dashboard",
|
||||||
|
]
|
||||||
@@ -0,0 +1,275 @@
|
|||||||
|
"""Load project settings from config.toml."""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import sys
|
||||||
|
from dataclasses import dataclass, field
|
||||||
|
from pathlib import Path
|
||||||
|
from typing import Any, Literal
|
||||||
|
|
||||||
|
from uavsearch.geometry import RectRegion
|
||||||
|
from uavsearch.optimizer.mapso import MAPSOParams
|
||||||
|
from uavsearch.problem import CoverageObjective, CoverageProblem, PartitionKind, PlannerKind
|
||||||
|
|
||||||
|
StripDirection = Literal["auto", "vertical", "horizontal"]
|
||||||
|
SweepAxis = Literal["auto", "x", "y"]
|
||||||
|
ObjectiveKind = Literal["max_revisit", "max_patrol_period"]
|
||||||
|
OptimizerMethod = Literal["differential_evolution", "local", "hybrid", "mapso"]
|
||||||
|
|
||||||
|
|
||||||
|
def _load_toml(path: Path) -> dict[str, Any]:
|
||||||
|
data = path.read_bytes()
|
||||||
|
if sys.version_info >= (3, 11):
|
||||||
|
import tomllib
|
||||||
|
|
||||||
|
return tomllib.loads(data.decode("utf-8"))
|
||||||
|
import tomli
|
||||||
|
|
||||||
|
return tomli.loads(data.decode("utf-8"))
|
||||||
|
|
||||||
|
|
||||||
|
@dataclass
|
||||||
|
class BoustrophedonPlannerConfig:
|
||||||
|
"""Boustrophedon (lawn-mower) path settings."""
|
||||||
|
|
||||||
|
sweep_width_ratio: float = 2.0
|
||||||
|
sweep_axis: SweepAxis = "auto"
|
||||||
|
|
||||||
|
|
||||||
|
@dataclass
|
||||||
|
class MtspPlannerConfig:
|
||||||
|
"""mTSP grid-waypoint path settings."""
|
||||||
|
|
||||||
|
waypoint_spacing_factor: float = 1.4142135623730951
|
||||||
|
|
||||||
|
|
||||||
|
@dataclass
|
||||||
|
class PlannerConfig:
|
||||||
|
boustrophedon: BoustrophedonPlannerConfig = field(default_factory=BoustrophedonPlannerConfig)
|
||||||
|
mtsp: MtspPlannerConfig = field(default_factory=MtspPlannerConfig)
|
||||||
|
|
||||||
|
|
||||||
|
@dataclass
|
||||||
|
class ObjectiveConfig:
|
||||||
|
primary: ObjectiveKind = "max_revisit"
|
||||||
|
weight_t_max: float = 1.0
|
||||||
|
weight_coverage: float = 120.0
|
||||||
|
weight_overlap: float = 100.0
|
||||||
|
|
||||||
|
|
||||||
|
@dataclass
|
||||||
|
class ProblemConfig:
|
||||||
|
width: float = 1000.0
|
||||||
|
height: float = 800.0
|
||||||
|
uavs: int = 4
|
||||||
|
radius: float = 50.0
|
||||||
|
speed: float = 15.0
|
||||||
|
partition: PartitionKind = "lloyd"
|
||||||
|
planner: PlannerKind = "mtsp"
|
||||||
|
depot_service: float = 60.0
|
||||||
|
grid_density: float = 4.0
|
||||||
|
strip_direction: StripDirection = "auto"
|
||||||
|
lloyd_iterations: int = 6
|
||||||
|
sim_dt: float = 0.5
|
||||||
|
bounds_margin: float = 0.05
|
||||||
|
seed: int = 42
|
||||||
|
|
||||||
|
def build_region(self) -> RectRegion:
|
||||||
|
return RectRegion.from_size(self.width, self.height)
|
||||||
|
|
||||||
|
def build_problem(
|
||||||
|
self,
|
||||||
|
objective: ObjectiveConfig | None = None,
|
||||||
|
planner: PlannerConfig | None = None,
|
||||||
|
simulation: SimulationConfig | None = None,
|
||||||
|
) -> CoverageProblem:
|
||||||
|
obj = objective or ObjectiveConfig()
|
||||||
|
pl = planner or PlannerConfig()
|
||||||
|
sim = simulation or SimulationConfig()
|
||||||
|
primary = (
|
||||||
|
CoverageObjective.MAX_PATROL_PERIOD
|
||||||
|
if obj.primary == "max_patrol_period"
|
||||||
|
else CoverageObjective.MAX_REVISIT
|
||||||
|
)
|
||||||
|
return CoverageProblem(
|
||||||
|
region=self.build_region(),
|
||||||
|
n_uavs=self.uavs,
|
||||||
|
sensor_radius=self.radius,
|
||||||
|
speed=self.speed,
|
||||||
|
planner=self.planner,
|
||||||
|
partition_mode=self.partition,
|
||||||
|
strip_direction=self.strip_direction,
|
||||||
|
grid_density=self.grid_density,
|
||||||
|
sim_dt=self.sim_dt,
|
||||||
|
depot_service_time=self.depot_service,
|
||||||
|
lloyd_iterations=self.lloyd_iterations,
|
||||||
|
bounds_margin=self.bounds_margin,
|
||||||
|
objective=primary,
|
||||||
|
weight_t_max=obj.weight_t_max,
|
||||||
|
weight_coverage=obj.weight_coverage,
|
||||||
|
weight_overlap=obj.weight_overlap,
|
||||||
|
sweep_width_ratio=pl.boustrophedon.sweep_width_ratio,
|
||||||
|
sweep_axis=pl.boustrophedon.sweep_axis,
|
||||||
|
waypoint_spacing_factor=pl.mtsp.waypoint_spacing_factor,
|
||||||
|
fast_eval_max_duration=sim.fast_eval_max_duration,
|
||||||
|
fast_eval_grid_density_cap=sim.fast_eval_grid_density_cap,
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
@dataclass
|
||||||
|
class SimulationConfig:
|
||||||
|
duration: float = 200.0
|
||||||
|
opt_duration: float | None = 100.0
|
||||||
|
fast_eval_max_duration: float = 100.0
|
||||||
|
fast_eval_grid_density_cap: float = 3.0
|
||||||
|
show_progress: bool = True
|
||||||
|
|
||||||
|
def effective_opt_duration(self) -> float:
|
||||||
|
if self.opt_duration is not None:
|
||||||
|
return self.opt_duration
|
||||||
|
return min(self.duration, self.fast_eval_max_duration)
|
||||||
|
|
||||||
|
|
||||||
|
@dataclass
|
||||||
|
class DifferentialEvolutionConfig:
|
||||||
|
tol: float = 0.05
|
||||||
|
atol: float = 0.05
|
||||||
|
polish: bool = False
|
||||||
|
|
||||||
|
|
||||||
|
@dataclass
|
||||||
|
class LocalOptimizerConfig:
|
||||||
|
maxiter: int = 40
|
||||||
|
|
||||||
|
|
||||||
|
@dataclass
|
||||||
|
class OptimizerConfig:
|
||||||
|
method: OptimizerMethod = "hybrid"
|
||||||
|
maxiter: int = 25
|
||||||
|
popsize: int = 8
|
||||||
|
verbose: bool = True
|
||||||
|
min_separation_ratio: float = 0.5
|
||||||
|
mapso: MAPSOParams = field(default_factory=MAPSOParams)
|
||||||
|
differential_evolution: DifferentialEvolutionConfig = field(default_factory=DifferentialEvolutionConfig)
|
||||||
|
local: LocalOptimizerConfig = field(default_factory=LocalOptimizerConfig)
|
||||||
|
|
||||||
|
|
||||||
|
@dataclass
|
||||||
|
class RunConfig:
|
||||||
|
optimize: bool = True
|
||||||
|
save: str = "output/dashboard.png"
|
||||||
|
show: bool = False
|
||||||
|
|
||||||
|
|
||||||
|
@dataclass
|
||||||
|
class AppConfig:
|
||||||
|
problem: ProblemConfig = field(default_factory=ProblemConfig)
|
||||||
|
planner: PlannerConfig = field(default_factory=PlannerConfig)
|
||||||
|
simulation: SimulationConfig = field(default_factory=SimulationConfig)
|
||||||
|
objective: ObjectiveConfig = field(default_factory=ObjectiveConfig)
|
||||||
|
optimizer: OptimizerConfig = field(default_factory=OptimizerConfig)
|
||||||
|
run: RunConfig = field(default_factory=RunConfig)
|
||||||
|
|
||||||
|
@classmethod
|
||||||
|
def from_dict(cls, raw: dict[str, Any]) -> AppConfig:
|
||||||
|
return cls(
|
||||||
|
problem=_parse_problem(raw.get("problem", {})),
|
||||||
|
planner=_parse_planner(raw.get("planner", {})),
|
||||||
|
simulation=_parse_simulation(raw.get("simulation", {})),
|
||||||
|
objective=_parse_objective(raw.get("objective", {})),
|
||||||
|
optimizer=_parse_optimizer(raw.get("optimizer", {})),
|
||||||
|
run=_parse_run(raw.get("run", {})),
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def load_config(path: str | Path = "config.toml") -> AppConfig:
|
||||||
|
"""Load configuration from a TOML file."""
|
||||||
|
p = Path(path)
|
||||||
|
if not p.is_file():
|
||||||
|
raise FileNotFoundError(f"Config not found: {p.resolve()}")
|
||||||
|
return AppConfig.from_dict(_load_toml(p))
|
||||||
|
|
||||||
|
|
||||||
|
def _parse_problem(d: dict[str, Any]) -> ProblemConfig:
|
||||||
|
return ProblemConfig(
|
||||||
|
width=float(d.get("width", 1000.0)),
|
||||||
|
height=float(d.get("height", 800.0)),
|
||||||
|
uavs=int(d.get("uavs", 4)),
|
||||||
|
radius=float(d.get("radius", 50.0)),
|
||||||
|
speed=float(d.get("speed", 15.0)),
|
||||||
|
partition=d.get("partition", "lloyd"),
|
||||||
|
planner=d.get("planner", "mtsp"),
|
||||||
|
depot_service=float(d.get("depot_service", 60.0)),
|
||||||
|
grid_density=float(d.get("grid_density", 4.0)),
|
||||||
|
strip_direction=d.get("strip_direction", "auto"),
|
||||||
|
lloyd_iterations=int(d.get("lloyd_iterations", 6)),
|
||||||
|
sim_dt=float(d.get("sim_dt", 0.5)),
|
||||||
|
bounds_margin=float(d.get("bounds_margin", 0.05)),
|
||||||
|
seed=int(d.get("seed", 42)),
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def _parse_planner(d: dict[str, Any]) -> PlannerConfig:
|
||||||
|
bou = d.get("boustrophedon", {})
|
||||||
|
mtsp = d.get("mtsp", {})
|
||||||
|
return PlannerConfig(
|
||||||
|
boustrophedon=BoustrophedonPlannerConfig(
|
||||||
|
sweep_width_ratio=float(bou.get("sweep_width_ratio", 2.0)),
|
||||||
|
sweep_axis=bou.get("sweep_axis", "auto"),
|
||||||
|
),
|
||||||
|
mtsp=MtspPlannerConfig(
|
||||||
|
waypoint_spacing_factor=float(mtsp.get("waypoint_spacing_factor", 1.4142135623730951)),
|
||||||
|
),
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def _parse_simulation(d: dict[str, Any]) -> SimulationConfig:
|
||||||
|
return SimulationConfig(
|
||||||
|
duration=float(d.get("duration", 200.0)),
|
||||||
|
opt_duration=float(d["opt_duration"]) if "opt_duration" in d else 100.0,
|
||||||
|
fast_eval_max_duration=float(d.get("fast_eval_max_duration", 100.0)),
|
||||||
|
fast_eval_grid_density_cap=float(d.get("fast_eval_grid_density_cap", 3.0)),
|
||||||
|
show_progress=bool(d.get("show_progress", True)),
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def _parse_objective(d: dict[str, Any]) -> ObjectiveConfig:
|
||||||
|
return ObjectiveConfig(
|
||||||
|
primary=d.get("primary", "max_revisit"),
|
||||||
|
weight_t_max=float(d.get("weight_t_max", 1.0)),
|
||||||
|
weight_coverage=float(d.get("weight_coverage", 120.0)),
|
||||||
|
weight_overlap=float(d.get("weight_overlap", 100.0)),
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def _parse_optimizer(d: dict[str, Any]) -> OptimizerConfig:
|
||||||
|
mapso_raw = d.get("mapso", {})
|
||||||
|
de_raw = d.get("differential_evolution", {})
|
||||||
|
local_raw = d.get("local", {})
|
||||||
|
return OptimizerConfig(
|
||||||
|
method=d.get("method", "hybrid"),
|
||||||
|
maxiter=int(d.get("maxiter", 25)),
|
||||||
|
popsize=int(d.get("popsize", 8)),
|
||||||
|
verbose=bool(d.get("verbose", True)),
|
||||||
|
min_separation_ratio=float(d.get("min_separation_ratio", 0.5)),
|
||||||
|
mapso=MAPSOParams(
|
||||||
|
w=float(mapso_raw.get("w", 0.729)),
|
||||||
|
c1=float(mapso_raw.get("c1", 1.494)),
|
||||||
|
c2=float(mapso_raw.get("c2", 1.494)),
|
||||||
|
vmax_ratio=float(mapso_raw.get("vmax_ratio", 0.2)),
|
||||||
|
),
|
||||||
|
differential_evolution=DifferentialEvolutionConfig(
|
||||||
|
tol=float(de_raw.get("tol", 0.05)),
|
||||||
|
atol=float(de_raw.get("atol", 0.05)),
|
||||||
|
polish=bool(de_raw.get("polish", False)),
|
||||||
|
),
|
||||||
|
local=LocalOptimizerConfig(maxiter=int(local_raw.get("maxiter", 40))),
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def _parse_run(d: dict[str, Any]) -> RunConfig:
|
||||||
|
return RunConfig(
|
||||||
|
optimize=bool(d.get("optimize", True)),
|
||||||
|
save=str(d.get("save", "output/dashboard.png")),
|
||||||
|
show=bool(d.get("show", False)),
|
||||||
|
)
|
||||||
@@ -0,0 +1,3 @@
|
|||||||
|
from .region import RectRegion
|
||||||
|
|
||||||
|
__all__ = ["RectRegion"]
|
||||||
@@ -0,0 +1,57 @@
|
|||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
from dataclasses import dataclass
|
||||||
|
|
||||||
|
import numpy as np
|
||||||
|
from shapely.geometry import Point, box
|
||||||
|
|
||||||
|
|
||||||
|
@dataclass(frozen=True)
|
||||||
|
class RectRegion:
|
||||||
|
"""Axis-aligned rectangular airspace."""
|
||||||
|
|
||||||
|
xmin: float
|
||||||
|
ymin: float
|
||||||
|
xmax: float
|
||||||
|
ymax: float
|
||||||
|
|
||||||
|
def __post_init__(self) -> None:
|
||||||
|
if self.xmax <= self.xmin or self.ymax <= self.ymin:
|
||||||
|
raise ValueError("Invalid rectangle bounds")
|
||||||
|
|
||||||
|
@classmethod
|
||||||
|
def from_size(cls, width: float, height: float, origin: tuple[float, float] = (0.0, 0.0)) -> RectRegion:
|
||||||
|
ox, oy = origin
|
||||||
|
return cls(ox, oy, ox + width, oy + height)
|
||||||
|
|
||||||
|
@property
|
||||||
|
def width(self) -> float:
|
||||||
|
return self.xmax - self.xmin
|
||||||
|
|
||||||
|
@property
|
||||||
|
def height(self) -> float:
|
||||||
|
return self.ymax - self.ymin
|
||||||
|
|
||||||
|
@property
|
||||||
|
def area(self) -> float:
|
||||||
|
return self.width * self.height
|
||||||
|
|
||||||
|
@property
|
||||||
|
def centroid(self) -> tuple[float, float]:
|
||||||
|
return ((self.xmin + self.xmax) / 2, (self.ymin + self.ymax) / 2)
|
||||||
|
|
||||||
|
def to_polygon(self):
|
||||||
|
return box(self.xmin, self.ymin, self.xmax, self.ymax)
|
||||||
|
|
||||||
|
def contains_point(self, x: float, y: float) -> bool:
|
||||||
|
return self.xmin <= x <= self.xmax and self.ymin <= y <= self.ymax
|
||||||
|
|
||||||
|
def clip_point(self, x: float, y: float) -> tuple[float, float]:
|
||||||
|
return (
|
||||||
|
float(np.clip(x, self.xmin, self.xmax)),
|
||||||
|
float(np.clip(y, self.ymin, self.ymax)),
|
||||||
|
)
|
||||||
|
|
||||||
|
def distance_to_boundary(self, x: float, y: float) -> float:
|
||||||
|
point = Point(x, y)
|
||||||
|
return float(point.distance(self.to_polygon().boundary))
|
||||||
@@ -0,0 +1,3 @@
|
|||||||
|
from .revisit import CoverageGrid, RevisitMetrics, compute_revisit_metrics
|
||||||
|
|
||||||
|
__all__ = ["CoverageGrid", "RevisitMetrics", "compute_revisit_metrics"]
|
||||||
@@ -0,0 +1,173 @@
|
|||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
from dataclasses import dataclass
|
||||||
|
|
||||||
|
import numpy as np
|
||||||
|
|
||||||
|
from uavsearch.geometry import RectRegion
|
||||||
|
|
||||||
|
|
||||||
|
@dataclass
|
||||||
|
class RevisitMetrics:
|
||||||
|
mean_revisit_time: float
|
||||||
|
max_revisit_time: float
|
||||||
|
min_revisit_time: float
|
||||||
|
std_revisit_time: float
|
||||||
|
coverage_ratio: float
|
||||||
|
overlap_ratio: float
|
||||||
|
max_idle_time: float
|
||||||
|
mean_idle_time: float
|
||||||
|
|
||||||
|
def summary(self) -> str:
|
||||||
|
return (
|
||||||
|
f"mean_revisit={self.mean_revisit_time:.2f}s, "
|
||||||
|
f"max_revisit={self.max_revisit_time:.2f}s, "
|
||||||
|
f"coverage={self.coverage_ratio:.1%}, "
|
||||||
|
f"overlap={self.overlap_ratio:.1%}, "
|
||||||
|
f"max_idle={self.max_idle_time:.2f}s"
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
class CoverageGrid:
|
||||||
|
"""Track per-cell visit times for revisit analysis."""
|
||||||
|
|
||||||
|
def __init__(self, region: RectRegion, cell_size: float):
|
||||||
|
if cell_size <= 0:
|
||||||
|
raise ValueError("cell_size must be positive")
|
||||||
|
self.region = region
|
||||||
|
self.cell_size = cell_size
|
||||||
|
self.nx = max(1, int(np.ceil(region.width / cell_size)))
|
||||||
|
self.ny = max(1, int(np.ceil(region.height / cell_size)))
|
||||||
|
self.last_visit = np.full((self.nx, self.ny), np.nan)
|
||||||
|
self.visit_count = np.zeros((self.nx, self.ny), dtype=int)
|
||||||
|
self.max_idle = np.zeros((self.nx, self.ny))
|
||||||
|
self._idle_open_since = np.full((self.nx, self.ny), np.nan)
|
||||||
|
|
||||||
|
def cell_center(self, i: int, j: int) -> tuple[float, float]:
|
||||||
|
x = self.region.xmin + (i + 0.5) * self.cell_size
|
||||||
|
y = self.region.ymin + (j + 0.5) * self.cell_size
|
||||||
|
return (min(x, self.region.xmax), min(y, self.region.ymax))
|
||||||
|
|
||||||
|
def world_to_cell(self, x: float, y: float) -> tuple[int, int] | None:
|
||||||
|
if not self.region.contains_point(x, y):
|
||||||
|
return None
|
||||||
|
i = int((x - self.region.xmin) / self.cell_size)
|
||||||
|
j = int((y - self.region.ymin) / self.cell_size)
|
||||||
|
return min(i, self.nx - 1), min(j, self.ny - 1)
|
||||||
|
|
||||||
|
def mark_visit(
|
||||||
|
self,
|
||||||
|
x: float,
|
||||||
|
y: float,
|
||||||
|
t: float,
|
||||||
|
radius: float,
|
||||||
|
clip_region: RectRegion | None = None,
|
||||||
|
) -> None:
|
||||||
|
r_cells = int(np.ceil(radius / self.cell_size))
|
||||||
|
center = self.world_to_cell(x, y)
|
||||||
|
if center is None:
|
||||||
|
return
|
||||||
|
ci, cj = center
|
||||||
|
|
||||||
|
for i in range(max(0, ci - r_cells), min(self.nx, ci + r_cells + 1)):
|
||||||
|
for j in range(max(0, cj - r_cells), min(self.ny, cj + r_cells + 1)):
|
||||||
|
cx, cy = self.cell_center(i, j)
|
||||||
|
if clip_region is not None and not clip_region.contains_point(cx, cy):
|
||||||
|
continue
|
||||||
|
if (cx - x) ** 2 + (cy - y) ** 2 > radius ** 2:
|
||||||
|
continue
|
||||||
|
|
||||||
|
if not np.isnan(self.last_visit[i, j]):
|
||||||
|
idle = t - self.last_visit[i, j]
|
||||||
|
self.max_idle[i, j] = max(self.max_idle[i, j], idle)
|
||||||
|
|
||||||
|
self.last_visit[i, j] = t
|
||||||
|
self.visit_count[i, j] += 1
|
||||||
|
self._idle_open_since[i, j] = t
|
||||||
|
|
||||||
|
def finalize_idle(self, end_time: float) -> None:
|
||||||
|
for i in range(self.nx):
|
||||||
|
for j in range(self.ny):
|
||||||
|
if self.visit_count[i, j] > 0 and not np.isnan(self._idle_open_since[i, j]):
|
||||||
|
idle = end_time - self._idle_open_since[i, j]
|
||||||
|
self.max_idle[i, j] = max(self.max_idle[i, j], idle)
|
||||||
|
|
||||||
|
def idle_map(self) -> np.ndarray:
|
||||||
|
return self.max_idle.T
|
||||||
|
|
||||||
|
def visit_count_map(self) -> np.ndarray:
|
||||||
|
return self.visit_count.T
|
||||||
|
|
||||||
|
def patrol_coverage_counts(
|
||||||
|
self,
|
||||||
|
patrol_positions: list[tuple[float, float, RectRegion]],
|
||||||
|
radius: float,
|
||||||
|
) -> np.ndarray:
|
||||||
|
"""Per-cell count of UAVs simultaneously providing patrol coverage."""
|
||||||
|
counts = np.zeros((self.nx, self.ny), dtype=np.int16)
|
||||||
|
if not patrol_positions:
|
||||||
|
return counts
|
||||||
|
|
||||||
|
r_cells = int(np.ceil(radius / self.cell_size))
|
||||||
|
r2 = radius * radius
|
||||||
|
|
||||||
|
for x, y, clip_region in patrol_positions:
|
||||||
|
center = self.world_to_cell(x, y)
|
||||||
|
if center is None:
|
||||||
|
continue
|
||||||
|
ci, cj = center
|
||||||
|
for i in range(max(0, ci - r_cells), min(self.nx, ci + r_cells + 1)):
|
||||||
|
for j in range(max(0, cj - r_cells), min(self.ny, cj + r_cells + 1)):
|
||||||
|
cx, cy = self.cell_center(i, j)
|
||||||
|
if clip_region is not None and not clip_region.contains_point(cx, cy):
|
||||||
|
continue
|
||||||
|
if (cx - x) ** 2 + (cy - y) ** 2 > r2:
|
||||||
|
continue
|
||||||
|
counts[i, j] += 1
|
||||||
|
|
||||||
|
return counts
|
||||||
|
|
||||||
|
|
||||||
|
def compute_revisit_metrics(
|
||||||
|
grid: CoverageGrid,
|
||||||
|
end_time: float,
|
||||||
|
overlap_cell_steps: int = 0,
|
||||||
|
sim_steps: int = 0,
|
||||||
|
) -> RevisitMetrics:
|
||||||
|
grid.finalize_idle(end_time)
|
||||||
|
visited_mask = grid.visit_count > 0
|
||||||
|
total_cells = grid.nx * grid.ny
|
||||||
|
visited_cells = int(np.sum(visited_mask))
|
||||||
|
|
||||||
|
idle_values = grid.max_idle[visited_mask]
|
||||||
|
if len(idle_values) == 0:
|
||||||
|
return RevisitMetrics(
|
||||||
|
mean_revisit_time=float("inf"),
|
||||||
|
max_revisit_time=float("inf"),
|
||||||
|
min_revisit_time=float("inf"),
|
||||||
|
std_revisit_time=0.0,
|
||||||
|
coverage_ratio=0.0,
|
||||||
|
overlap_ratio=0.0,
|
||||||
|
max_idle_time=float("inf"),
|
||||||
|
mean_idle_time=float("inf"),
|
||||||
|
)
|
||||||
|
|
||||||
|
multi_visit = grid.visit_count > 1
|
||||||
|
if np.any(multi_visit):
|
||||||
|
revisit_values = grid.max_idle[multi_visit]
|
||||||
|
else:
|
||||||
|
revisit_values = idle_values
|
||||||
|
|
||||||
|
total_cell_steps = sim_steps * total_cells
|
||||||
|
overlap_ratio = overlap_cell_steps / total_cell_steps if total_cell_steps > 0 else 0.0
|
||||||
|
|
||||||
|
return RevisitMetrics(
|
||||||
|
mean_revisit_time=float(np.mean(revisit_values)),
|
||||||
|
max_revisit_time=float(np.max(revisit_values)),
|
||||||
|
min_revisit_time=float(np.min(revisit_values)),
|
||||||
|
std_revisit_time=float(np.std(revisit_values)),
|
||||||
|
coverage_ratio=visited_cells / total_cells,
|
||||||
|
overlap_ratio=float(overlap_ratio),
|
||||||
|
max_idle_time=float(np.max(idle_values)),
|
||||||
|
mean_idle_time=float(np.mean(idle_values)),
|
||||||
|
)
|
||||||
@@ -0,0 +1,8 @@
|
|||||||
|
from .deployment import DeploymentOptimizer, OptimizationResult, optimize_deployment
|
||||||
|
|
||||||
|
from .mapso import MAPSOParams, run_mapso
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
__all__ = ["DeploymentOptimizer", "OptimizationResult", "optimize_deployment", "MAPSOParams", "run_mapso"]
|
||||||
|
|
||||||
@@ -0,0 +1,262 @@
|
|||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import time
|
||||||
|
from dataclasses import dataclass
|
||||||
|
|
||||||
|
import numpy as np
|
||||||
|
from scipy.optimize import differential_evolution, minimize
|
||||||
|
|
||||||
|
from .mapso import MAPSOParams, run_mapso
|
||||||
|
from uavsearch.problem import (
|
||||||
|
CoverageProblem,
|
||||||
|
EvaluationResult,
|
||||||
|
evaluate_deployment,
|
||||||
|
random_deployment,
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
@dataclass
|
||||||
|
class OptimizationResult:
|
||||||
|
problem: CoverageProblem
|
||||||
|
best: EvaluationResult
|
||||||
|
history: list[EvaluationResult]
|
||||||
|
n_evaluations: int
|
||||||
|
method: str
|
||||||
|
|
||||||
|
def summary(self) -> str:
|
||||||
|
b = self.best
|
||||||
|
return (
|
||||||
|
f"T_max={b.max_revisit_time:.2f}s, coverage={b.coverage_ratio:.1%}, "
|
||||||
|
f"overlap={b.overlap_ratio:.1%}, objective={b.objective_value:.1f}"
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
class DeploymentOptimizer:
|
||||||
|
"""Search depot positions to minimize T_max."""
|
||||||
|
|
||||||
|
def __init__(
|
||||||
|
self,
|
||||||
|
problem: CoverageProblem,
|
||||||
|
seed: int = 42,
|
||||||
|
min_separation: float | None = None,
|
||||||
|
verbose: bool = True,
|
||||||
|
):
|
||||||
|
self.problem = problem
|
||||||
|
self.seed = seed
|
||||||
|
self.rng = np.random.default_rng(seed)
|
||||||
|
self.min_separation = min_separation or problem.sensor_radius * 0.5
|
||||||
|
self.verbose = verbose
|
||||||
|
self._eval_count = 0
|
||||||
|
self._history: list[EvaluationResult] = []
|
||||||
|
self._best: EvaluationResult | None = None
|
||||||
|
self._sim_duration: float | None = None
|
||||||
|
self._baseline_obj: float | None = None
|
||||||
|
|
||||||
|
def optimize(
|
||||||
|
self,
|
||||||
|
method: str = "differential_evolution",
|
||||||
|
maxiter: int = 60,
|
||||||
|
popsize: int = 10,
|
||||||
|
sim_duration: float | None = None,
|
||||||
|
initial_guess: np.ndarray | None = None,
|
||||||
|
show_progress: bool = True,
|
||||||
|
mapso_params: MAPSOParams | None = None,
|
||||||
|
) -> OptimizationResult:
|
||||||
|
self._eval_count = 0
|
||||||
|
self._history = []
|
||||||
|
self._best = None
|
||||||
|
self._sim_duration = sim_duration
|
||||||
|
self._show_progress = show_progress and self.verbose
|
||||||
|
self._baseline_obj = None
|
||||||
|
if initial_guess is not None:
|
||||||
|
self._baseline_obj = self._evaluate_baseline(initial_guess, sim_duration)
|
||||||
|
|
||||||
|
if method == "differential_evolution":
|
||||||
|
est = popsize * (maxiter + 1)
|
||||||
|
self._log(f"差分进化: maxiter={maxiter}, popsize={popsize}, 约 {est} 次评估")
|
||||||
|
self._log("优化阶段使用快速仿真(fast_eval),完成后对最优解做精评估")
|
||||||
|
self._run_de(maxiter=maxiter, popsize=popsize, sim_duration=sim_duration)
|
||||||
|
elif method == "local":
|
||||||
|
self._log("局部优化 (L-BFGS-B)")
|
||||||
|
x0 = initial_guess if initial_guess is not None else random_deployment(self.problem, self.seed)
|
||||||
|
self._run_local(x0.ravel(), sim_duration=sim_duration)
|
||||||
|
if self._best and self._baseline_obj is not None and self._best.objective_value >= self._baseline_obj - 1e-6:
|
||||||
|
self._log("局部搜索无改进,切换差分进化...")
|
||||||
|
self._run_de(maxiter=max(12, maxiter), popsize=max(6, popsize), sim_duration=sim_duration)
|
||||||
|
elif method == "hybrid":
|
||||||
|
de_iter = max(1, maxiter // 2)
|
||||||
|
est = popsize * (de_iter + 1)
|
||||||
|
self._log(f"[1/2] 差分进化: maxiter={de_iter}, popsize={popsize}, 约 {est} 次评估")
|
||||||
|
self._log("优化阶段使用快速仿真(fast_eval),完成后对最优解做精评估")
|
||||||
|
self._run_de(maxiter=de_iter, popsize=popsize, sim_duration=sim_duration)
|
||||||
|
if self._best is not None:
|
||||||
|
self._log("[2/2] 局部精修 (L-BFGS-B)")
|
||||||
|
self._run_local(self._best.solution.initial_positions.ravel(), sim_duration=sim_duration)
|
||||||
|
elif method == "mapso":
|
||||||
|
est = popsize * (maxiter + 1)
|
||||||
|
self._log(f"MAPSO: maxiter={maxiter}, popsize={popsize}, 约 {est} 次评估")
|
||||||
|
self._log("优化阶段使用快速仿真(fast_eval),完成后对最优解做精评估")
|
||||||
|
self._run_mapso(
|
||||||
|
maxiter=maxiter,
|
||||||
|
popsize=popsize,
|
||||||
|
sim_duration=sim_duration,
|
||||||
|
initial_guess=initial_guess,
|
||||||
|
mapso_params=mapso_params,
|
||||||
|
)
|
||||||
|
else:
|
||||||
|
raise ValueError(f"Unknown method: {method}")
|
||||||
|
|
||||||
|
assert self._best is not None
|
||||||
|
self._log("对最优站点做精评估 (完整仿真)...")
|
||||||
|
self._best = evaluate_deployment(
|
||||||
|
self.problem,
|
||||||
|
self._best.solution.initial_positions,
|
||||||
|
sim_duration=sim_duration,
|
||||||
|
show_progress=False,
|
||||||
|
fast_eval=False,
|
||||||
|
)
|
||||||
|
if self.verbose:
|
||||||
|
print(
|
||||||
|
f"优化完成: {self._eval_count} 次搜索评估 + 1 次精评估, "
|
||||||
|
f"最优 T_max={self._best.objective_value:.2f}s",
|
||||||
|
flush=True,
|
||||||
|
)
|
||||||
|
|
||||||
|
return OptimizationResult(
|
||||||
|
problem=self.problem,
|
||||||
|
best=self._best,
|
||||||
|
history=list(self._history),
|
||||||
|
n_evaluations=self._eval_count,
|
||||||
|
method=method,
|
||||||
|
)
|
||||||
|
|
||||||
|
def _log(self, msg: str) -> None:
|
||||||
|
if self.verbose:
|
||||||
|
print(msg, flush=True)
|
||||||
|
|
||||||
|
def _evaluate_baseline(self, positions: np.ndarray, sim_duration: float | None) -> float:
|
||||||
|
r = evaluate_deployment(
|
||||||
|
self.problem, positions, sim_duration=sim_duration, show_progress=False, fast_eval=True
|
||||||
|
)
|
||||||
|
return r.objective_value
|
||||||
|
|
||||||
|
def _objective(self, vector: np.ndarray, sim_duration: float | None) -> float:
|
||||||
|
t0 = time.perf_counter()
|
||||||
|
positions = self.problem.unpack_positions(vector)
|
||||||
|
penalty = self._separation_penalty(positions)
|
||||||
|
result = evaluate_deployment(
|
||||||
|
self.problem, positions, sim_duration=sim_duration, show_progress=False, fast_eval=True
|
||||||
|
)
|
||||||
|
elapsed = time.perf_counter() - t0
|
||||||
|
self._eval_count += 1
|
||||||
|
self._history.append(result)
|
||||||
|
if self._best is None or result.objective_value < self._best.objective_value:
|
||||||
|
self._best = result
|
||||||
|
improved = "*"
|
||||||
|
else:
|
||||||
|
improved = " "
|
||||||
|
|
||||||
|
if self.verbose:
|
||||||
|
print(
|
||||||
|
f" {improved} eval {self._eval_count:3d}: "
|
||||||
|
f"obj={result.objective_value:7.1f} T_max={result.max_revisit_time:6.1f}s "
|
||||||
|
f"cov={result.coverage_ratio:5.1%} ovl={result.overlap_ratio:5.1%} "
|
||||||
|
f"best={self._best.objective_value:7.1f} ({elapsed:5.1f}s)",
|
||||||
|
flush=True,
|
||||||
|
)
|
||||||
|
|
||||||
|
return result.objective_value + penalty
|
||||||
|
|
||||||
|
def _separation_penalty(self, positions: np.ndarray) -> float:
|
||||||
|
n = len(positions)
|
||||||
|
penalty = 0.0
|
||||||
|
for i in range(n):
|
||||||
|
for j in range(i + 1, n):
|
||||||
|
d = float(np.linalg.norm(positions[i] - positions[j]))
|
||||||
|
if d < self.min_separation:
|
||||||
|
penalty += (self.min_separation - d) * 10.0
|
||||||
|
return penalty
|
||||||
|
|
||||||
|
def _run_de(self, maxiter: int, popsize: int, sim_duration: float | None):
|
||||||
|
bounds = self.problem.bounds()
|
||||||
|
gen_done = 0
|
||||||
|
|
||||||
|
def func(x):
|
||||||
|
return self._objective(x, sim_duration)
|
||||||
|
|
||||||
|
def callback(_xk, _convergence):
|
||||||
|
nonlocal gen_done
|
||||||
|
gen_done += 1
|
||||||
|
if self.verbose and self._best is not None:
|
||||||
|
print(
|
||||||
|
f" -- DE 第 {gen_done}/{maxiter} 代完成, best T_max={self._best.objective_value:.1f}s --",
|
||||||
|
flush=True,
|
||||||
|
)
|
||||||
|
|
||||||
|
differential_evolution(
|
||||||
|
func,
|
||||||
|
bounds=bounds,
|
||||||
|
maxiter=maxiter,
|
||||||
|
popsize=popsize,
|
||||||
|
seed=self.seed,
|
||||||
|
polish=False,
|
||||||
|
tol=0.05,
|
||||||
|
atol=0.05,
|
||||||
|
callback=callback,
|
||||||
|
)
|
||||||
|
|
||||||
|
def _run_local(self, x0: np.ndarray, sim_duration: float | None):
|
||||||
|
bounds = self.problem.bounds()
|
||||||
|
|
||||||
|
def func(x):
|
||||||
|
return self._objective(x, sim_duration)
|
||||||
|
|
||||||
|
minimize(func, x0, method="L-BFGS-B", bounds=bounds, options={"maxiter": 40})
|
||||||
|
|
||||||
|
def _run_mapso(
|
||||||
|
self,
|
||||||
|
maxiter: int,
|
||||||
|
popsize: int,
|
||||||
|
sim_duration: float | None,
|
||||||
|
initial_guess: np.ndarray | None,
|
||||||
|
mapso_params: MAPSOParams | None,
|
||||||
|
):
|
||||||
|
bounds = self.problem.bounds()
|
||||||
|
|
||||||
|
def func(x):
|
||||||
|
return self._objective(x, sim_duration)
|
||||||
|
|
||||||
|
def on_generation(gen: int, total: int, best_fit: float):
|
||||||
|
if self.verbose:
|
||||||
|
print(
|
||||||
|
f" -- MAPSO 第 {gen}/{total} 代完成, best T_max={best_fit:.1f}s --",
|
||||||
|
flush=True,
|
||||||
|
)
|
||||||
|
|
||||||
|
best_vec = run_mapso(
|
||||||
|
objective=func,
|
||||||
|
bounds=bounds,
|
||||||
|
n_agents=self.problem.n_uavs,
|
||||||
|
popsize=popsize,
|
||||||
|
maxiter=maxiter,
|
||||||
|
rng=self.rng,
|
||||||
|
params=mapso_params,
|
||||||
|
initial_guess=initial_guess.ravel() if initial_guess is not None else None,
|
||||||
|
on_generation=on_generation,
|
||||||
|
)
|
||||||
|
func(best_vec)
|
||||||
|
|
||||||
|
|
||||||
|
def optimize_deployment(
|
||||||
|
problem: CoverageProblem,
|
||||||
|
method: str = "hybrid",
|
||||||
|
seed: int = 42,
|
||||||
|
maxiter: int = 60,
|
||||||
|
popsize: int = 10,
|
||||||
|
verbose: bool = True,
|
||||||
|
show_progress: bool = True,
|
||||||
|
**kwargs,
|
||||||
|
) -> OptimizationResult:
|
||||||
|
return DeploymentOptimizer(problem, seed=seed, verbose=verbose).optimize(
|
||||||
|
method=method, maxiter=maxiter, popsize=popsize, show_progress=show_progress, **kwargs
|
||||||
|
)
|
||||||
@@ -0,0 +1,101 @@
|
|||||||
|
"""Multi-Agent Particle Swarm Optimization (MAPSO) for depot deployment."""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
from dataclasses import dataclass
|
||||||
|
from typing import Callable
|
||||||
|
|
||||||
|
import numpy as np
|
||||||
|
|
||||||
|
|
||||||
|
@dataclass
|
||||||
|
class MAPSOParams:
|
||||||
|
"""Hyper-parameters for MAPSO."""
|
||||||
|
|
||||||
|
w: float = 0.729
|
||||||
|
c1: float = 1.494
|
||||||
|
c2: float = 1.494
|
||||||
|
vmax_ratio: float = 0.2
|
||||||
|
|
||||||
|
|
||||||
|
def run_mapso(
|
||||||
|
objective: Callable[[np.ndarray], float],
|
||||||
|
bounds: list[tuple[float, float]],
|
||||||
|
n_agents: int,
|
||||||
|
popsize: int,
|
||||||
|
maxiter: int,
|
||||||
|
rng: np.random.Generator,
|
||||||
|
params: MAPSOParams | None = None,
|
||||||
|
initial_guess: np.ndarray | None = None,
|
||||||
|
on_generation: Callable[[int, int, float], None] | None = None,
|
||||||
|
) -> np.ndarray:
|
||||||
|
"""
|
||||||
|
Cooperative MAPSO: each UAV is an agent with ``popsize`` particles (2D depot).
|
||||||
|
|
||||||
|
Particle index ``k`` is synchronized across agents to form one full deployment.
|
||||||
|
Returns the best position vector found (length 2 * n_agents).
|
||||||
|
"""
|
||||||
|
if params is None:
|
||||||
|
params = MAPSOParams()
|
||||||
|
|
||||||
|
low = np.array([b[0] for b in bounds], dtype=float)
|
||||||
|
high = np.array([b[1] for b in bounds], dtype=float)
|
||||||
|
span = high - low
|
||||||
|
vmax = span * params.vmax_ratio
|
||||||
|
|
||||||
|
# particles[m, agent, xy]
|
||||||
|
pos = _init_positions(n_agents, popsize, low, high, rng, initial_guess)
|
||||||
|
vel = rng.uniform(-vmax.reshape(1, n_agents, 2), vmax.reshape(1, n_agents, 2), size=(popsize, n_agents, 2))
|
||||||
|
|
||||||
|
pbest_pos = pos.copy()
|
||||||
|
pbest_fit = np.array([objective(_flatten(pos[m], n_agents)) for m in range(popsize)])
|
||||||
|
g_idx = int(np.argmin(pbest_fit))
|
||||||
|
gbest_pos = pos[g_idx].copy()
|
||||||
|
gbest_fit = float(pbest_fit[g_idx])
|
||||||
|
|
||||||
|
for gen in range(maxiter):
|
||||||
|
for m in range(popsize):
|
||||||
|
r1 = rng.random((n_agents, 2))
|
||||||
|
r2 = rng.random((n_agents, 2))
|
||||||
|
vel[m] = (
|
||||||
|
params.w * vel[m]
|
||||||
|
+ params.c1 * r1 * (pbest_pos[m] - pos[m])
|
||||||
|
+ params.c2 * r2 * (gbest_pos - pos[m])
|
||||||
|
)
|
||||||
|
vel[m] = np.clip(vel[m], -vmax.reshape(n_agents, 2), vmax.reshape(n_agents, 2))
|
||||||
|
pos[m] = np.clip(pos[m] + vel[m], low.reshape(n_agents, 2), high.reshape(n_agents, 2))
|
||||||
|
|
||||||
|
fit = objective(_flatten(pos[m], n_agents))
|
||||||
|
if fit < pbest_fit[m]:
|
||||||
|
pbest_fit[m] = fit
|
||||||
|
pbest_pos[m] = pos[m].copy()
|
||||||
|
if fit < gbest_fit:
|
||||||
|
gbest_fit = fit
|
||||||
|
gbest_pos = pos[m].copy()
|
||||||
|
|
||||||
|
if on_generation is not None:
|
||||||
|
on_generation(gen + 1, maxiter, gbest_fit)
|
||||||
|
|
||||||
|
return _flatten(gbest_pos, n_agents)
|
||||||
|
|
||||||
|
|
||||||
|
def _init_positions(
|
||||||
|
n_agents: int,
|
||||||
|
popsize: int,
|
||||||
|
low: np.ndarray,
|
||||||
|
high: np.ndarray,
|
||||||
|
rng: np.random.Generator,
|
||||||
|
initial_guess: np.ndarray | None,
|
||||||
|
) -> np.ndarray:
|
||||||
|
pos = rng.uniform(low.reshape(n_agents, 2), high.reshape(n_agents, 2), size=(popsize, n_agents, 2))
|
||||||
|
if initial_guess is not None:
|
||||||
|
center = initial_guess.reshape(n_agents, 2)
|
||||||
|
span = (high - low).reshape(n_agents, 2)
|
||||||
|
pos[0] = center
|
||||||
|
for m in range(1, popsize):
|
||||||
|
pos[m] = np.clip(center + rng.normal(0, 0.08, size=(n_agents, 2)) * span, low.reshape(n_agents, 2), high.reshape(n_agents, 2))
|
||||||
|
return pos
|
||||||
|
|
||||||
|
|
||||||
|
def _flatten(agent_positions: np.ndarray, n_agents: int) -> np.ndarray:
|
||||||
|
return agent_positions.reshape(n_agents * 2)
|
||||||
@@ -0,0 +1,30 @@
|
|||||||
|
from .assign import (
|
||||||
|
assign_uavs_by_containment,
|
||||||
|
assign_uavs_by_permutation,
|
||||||
|
assign_uavs_to_partitions,
|
||||||
|
partition_and_assign,
|
||||||
|
)
|
||||||
|
from .dispatch import build_partition, partition_lloyd, partition_workload
|
||||||
|
from .initial import generate_uneven_positions, parse_initial_positions
|
||||||
|
from .strip import StripPartitioner, partition_strips
|
||||||
|
from .uniform import UniformPartitioner, partition_uniform
|
||||||
|
from .voronoi import PartitionCell, PartitionResult, partition_voronoi
|
||||||
|
|
||||||
|
__all__ = [
|
||||||
|
"StripPartitioner",
|
||||||
|
"partition_strips",
|
||||||
|
"UniformPartitioner",
|
||||||
|
"partition_uniform",
|
||||||
|
"assign_uavs_to_partitions",
|
||||||
|
"assign_uavs_by_containment",
|
||||||
|
"assign_uavs_by_permutation",
|
||||||
|
"partition_and_assign",
|
||||||
|
"build_partition",
|
||||||
|
"partition_workload",
|
||||||
|
"partition_lloyd",
|
||||||
|
"generate_uneven_positions",
|
||||||
|
"parse_initial_positions",
|
||||||
|
"PartitionCell",
|
||||||
|
"PartitionResult",
|
||||||
|
"partition_voronoi",
|
||||||
|
]
|
||||||
@@ -0,0 +1,161 @@
|
|||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import numpy as np
|
||||||
|
from scipy.optimize import linear_sum_assignment
|
||||||
|
|
||||||
|
from uavsearch.partition.voronoi import PartitionCell, PartitionResult
|
||||||
|
|
||||||
|
|
||||||
|
def assign_uavs_by_containment(
|
||||||
|
region,
|
||||||
|
partition_cells: list[PartitionCell],
|
||||||
|
initial_positions: np.ndarray,
|
||||||
|
) -> PartitionResult:
|
||||||
|
"""
|
||||||
|
Assign each UAV to the partition cell that contains its depot.
|
||||||
|
|
||||||
|
Falls back to nearest cell by depot-to-polygon distance; resolves conflicts
|
||||||
|
with Hungarian algorithm on the remaining unassigned pairs.
|
||||||
|
"""
|
||||||
|
from shapely.geometry import Point
|
||||||
|
|
||||||
|
positions = np.asarray(initial_positions, dtype=float)
|
||||||
|
n = len(positions)
|
||||||
|
if len(partition_cells) != n:
|
||||||
|
raise ValueError("UAV count must match partition count")
|
||||||
|
|
||||||
|
assignment: list[int | None] = [None] * n
|
||||||
|
claimed: set[int] = set()
|
||||||
|
|
||||||
|
for uav_id, pos in enumerate(positions):
|
||||||
|
pt = Point(float(pos[0]), float(pos[1]))
|
||||||
|
containing = [
|
||||||
|
part_id
|
||||||
|
for part_id, cell in enumerate(partition_cells)
|
||||||
|
if part_id not in claimed and (cell.polygon.contains(pt) or cell.polygon.boundary.distance(pt) < 1e-6)
|
||||||
|
]
|
||||||
|
if len(containing) == 1:
|
||||||
|
assignment[uav_id] = containing[0]
|
||||||
|
claimed.add(containing[0])
|
||||||
|
elif len(containing) > 1:
|
||||||
|
best = min(containing, key=lambda pid: partition_cells[pid].polygon.distance(pt))
|
||||||
|
assignment[uav_id] = best
|
||||||
|
claimed.add(best)
|
||||||
|
|
||||||
|
unassigned_uavs = [i for i, a in enumerate(assignment) if a is None]
|
||||||
|
free_parts = [p for p in range(n) if p not in claimed]
|
||||||
|
|
||||||
|
if unassigned_uavs and free_parts:
|
||||||
|
cost = np.zeros((len(unassigned_uavs), len(free_parts)))
|
||||||
|
for row, uav_id in enumerate(unassigned_uavs):
|
||||||
|
pt = Point(float(positions[uav_id][0]), float(positions[uav_id][1]))
|
||||||
|
for col, part_id in enumerate(free_parts):
|
||||||
|
cost[row, col] = partition_cells[part_id].polygon.distance(pt)
|
||||||
|
rows, cols = linear_sum_assignment(cost)
|
||||||
|
for row, col in zip(rows, cols):
|
||||||
|
assignment[unassigned_uavs[row]] = free_parts[col]
|
||||||
|
|
||||||
|
for uav_id, part_id in enumerate(assignment):
|
||||||
|
if part_id is None:
|
||||||
|
pt = Point(float(positions[uav_id][0]), float(positions[uav_id][1]))
|
||||||
|
assignment[uav_id] = min(
|
||||||
|
range(n),
|
||||||
|
key=lambda pid: partition_cells[pid].polygon.distance(pt),
|
||||||
|
)
|
||||||
|
|
||||||
|
assigned: list[PartitionCell] = []
|
||||||
|
for uav_id, part_id in enumerate(assignment):
|
||||||
|
src = partition_cells[int(part_id)]
|
||||||
|
assigned.append(
|
||||||
|
PartitionCell(
|
||||||
|
uav_id=uav_id,
|
||||||
|
partition_id=int(part_id),
|
||||||
|
initial_position=(float(positions[uav_id][0]), float(positions[uav_id][1])),
|
||||||
|
polygon=src.polygon,
|
||||||
|
bounds=src.bounds,
|
||||||
|
)
|
||||||
|
)
|
||||||
|
|
||||||
|
assigned.sort(key=lambda c: c.uav_id)
|
||||||
|
return PartitionResult(region=region, initial_positions=positions, cells=assigned)
|
||||||
|
|
||||||
|
|
||||||
|
def assign_uavs_to_partitions(
|
||||||
|
region,
|
||||||
|
partition_cells: list[PartitionCell],
|
||||||
|
initial_positions: np.ndarray,
|
||||||
|
) -> PartitionResult:
|
||||||
|
"""
|
||||||
|
Match uneven initial UAV positions to uniform geographic partitions.
|
||||||
|
|
||||||
|
Uses Hungarian algorithm on distance-to-centroid cost so each UAV gets
|
||||||
|
exactly one equal-area partition and each partition has one UAV.
|
||||||
|
"""
|
||||||
|
positions = np.asarray(initial_positions, dtype=float)
|
||||||
|
n = len(partition_cells)
|
||||||
|
if len(positions) != n:
|
||||||
|
raise ValueError("UAV count must match partition count")
|
||||||
|
|
||||||
|
centroids = np.array([c.bounds.centroid for c in partition_cells])
|
||||||
|
cost = np.zeros((n, n))
|
||||||
|
for i, pos in enumerate(positions):
|
||||||
|
cost[i] = np.linalg.norm(centroids - pos, axis=1)
|
||||||
|
|
||||||
|
uav_ids, part_ids = linear_sum_assignment(cost)
|
||||||
|
|
||||||
|
assigned: list[PartitionCell] = []
|
||||||
|
for uav_id, part_id in zip(uav_ids, part_ids):
|
||||||
|
src = partition_cells[part_id]
|
||||||
|
assigned.append(
|
||||||
|
PartitionCell(
|
||||||
|
uav_id=int(uav_id),
|
||||||
|
partition_id=int(part_id),
|
||||||
|
initial_position=(float(positions[uav_id][0]), float(positions[uav_id][1])),
|
||||||
|
polygon=src.polygon,
|
||||||
|
bounds=src.bounds,
|
||||||
|
)
|
||||||
|
)
|
||||||
|
|
||||||
|
assigned.sort(key=lambda c: c.uav_id)
|
||||||
|
return PartitionResult(region=region, initial_positions=positions, cells=assigned)
|
||||||
|
|
||||||
|
|
||||||
|
def assign_uavs_by_permutation(
|
||||||
|
region,
|
||||||
|
partition_cells: list[PartitionCell],
|
||||||
|
initial_positions: np.ndarray,
|
||||||
|
permutation: tuple[int, ...],
|
||||||
|
) -> PartitionResult:
|
||||||
|
"""Assign UAV i to partition permutation[i] (discrete assignment search)."""
|
||||||
|
positions = np.asarray(initial_positions, dtype=float)
|
||||||
|
n = len(positions)
|
||||||
|
if len(permutation) != n:
|
||||||
|
raise ValueError("permutation length must match UAV count")
|
||||||
|
|
||||||
|
assigned: list[PartitionCell] = []
|
||||||
|
for uav_id in range(n):
|
||||||
|
part_id = permutation[uav_id]
|
||||||
|
src = partition_cells[part_id]
|
||||||
|
assigned.append(
|
||||||
|
PartitionCell(
|
||||||
|
uav_id=uav_id,
|
||||||
|
partition_id=part_id,
|
||||||
|
initial_position=(float(positions[uav_id][0]), float(positions[uav_id][1])),
|
||||||
|
polygon=src.polygon,
|
||||||
|
bounds=src.bounds,
|
||||||
|
)
|
||||||
|
)
|
||||||
|
assigned.sort(key=lambda c: c.uav_id)
|
||||||
|
return PartitionResult(region=region, initial_positions=positions, cells=assigned)
|
||||||
|
|
||||||
|
|
||||||
|
def partition_and_assign(
|
||||||
|
region,
|
||||||
|
n_uavs: int,
|
||||||
|
initial_positions: np.ndarray,
|
||||||
|
direction: str = "vertical",
|
||||||
|
) -> PartitionResult:
|
||||||
|
from uavsearch.partition.uniform import partition_uniform
|
||||||
|
|
||||||
|
cells = partition_uniform(region, n_uavs, direction=direction) # type: ignore[arg-type]
|
||||||
|
return assign_uavs_to_partitions(region, cells, initial_positions)
|
||||||
@@ -0,0 +1,316 @@
|
|||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
import numpy as np
|
||||||
|
|
||||||
|
from shapely.geometry import MultiPoint, Point
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
from uavsearch.geometry import RectRegion
|
||||||
|
|
||||||
|
from uavsearch.partition.assign import assign_uavs_by_containment, assign_uavs_to_partitions, partition_and_assign
|
||||||
|
|
||||||
|
from uavsearch.partition.voronoi import PartitionCell, PartitionResult, partition_voronoi
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
def _coverage_grid_points(region: RectRegion, spacing: float) -> np.ndarray:
|
||||||
|
|
||||||
|
xs = np.arange(region.xmin + spacing / 2, region.xmax, spacing)
|
||||||
|
|
||||||
|
ys = np.arange(region.ymin + spacing / 2, region.ymax, spacing)
|
||||||
|
|
||||||
|
if len(xs) == 0 or len(ys) == 0:
|
||||||
|
|
||||||
|
cx, cy = region.centroid
|
||||||
|
|
||||||
|
return np.array([[cx, cy]])
|
||||||
|
|
||||||
|
gx, gy = np.meshgrid(xs, ys)
|
||||||
|
|
||||||
|
return np.column_stack([gx.ravel(), gy.ravel()])
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
def _labels_from_seeds(points: np.ndarray, seeds: np.ndarray) -> np.ndarray:
|
||||||
|
|
||||||
|
dists = np.linalg.norm(points[:, None, :] - seeds[None, :, :], axis=2)
|
||||||
|
|
||||||
|
return np.argmin(dists, axis=1)
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
def _cells_from_labels(
|
||||||
|
|
||||||
|
region: RectRegion,
|
||||||
|
|
||||||
|
points: np.ndarray,
|
||||||
|
|
||||||
|
labels: np.ndarray,
|
||||||
|
|
||||||
|
depots: np.ndarray,
|
||||||
|
|
||||||
|
spacing: float,
|
||||||
|
|
||||||
|
) -> list[PartitionCell]:
|
||||||
|
|
||||||
|
"""Build partition cells from grid labels; depot i owns label i."""
|
||||||
|
|
||||||
|
n_uavs = len(depots)
|
||||||
|
|
||||||
|
envelope = region.to_polygon()
|
||||||
|
|
||||||
|
cells: list[PartitionCell] = []
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
for pid in range(n_uavs):
|
||||||
|
|
||||||
|
cluster_pts = points[labels == pid]
|
||||||
|
|
||||||
|
depot = np.asarray(depots[pid], dtype=float)
|
||||||
|
|
||||||
|
if len(cluster_pts) == 0:
|
||||||
|
|
||||||
|
cluster_pts = depot.reshape(1, 2)
|
||||||
|
|
||||||
|
else:
|
||||||
|
|
||||||
|
cluster_pts = np.vstack([cluster_pts, depot])
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
hull = MultiPoint([tuple(p) for p in cluster_pts]).convex_hull.intersection(envelope)
|
||||||
|
|
||||||
|
if hull.is_empty:
|
||||||
|
|
||||||
|
hull = Point(float(depot[0]), float(depot[1])).buffer(spacing)
|
||||||
|
|
||||||
|
xmin, ymin, xmax, ymax = hull.bounds
|
||||||
|
|
||||||
|
bounds = RectRegion(xmin, ymin, xmax, ymax)
|
||||||
|
|
||||||
|
cells.append(
|
||||||
|
|
||||||
|
PartitionCell(
|
||||||
|
|
||||||
|
uav_id=pid,
|
||||||
|
|
||||||
|
partition_id=pid,
|
||||||
|
|
||||||
|
initial_position=(float(depot[0]), float(depot[1])),
|
||||||
|
|
||||||
|
polygon=hull,
|
||||||
|
|
||||||
|
bounds=bounds,
|
||||||
|
|
||||||
|
)
|
||||||
|
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
return cells
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
def partition_workload(
|
||||||
|
|
||||||
|
region: RectRegion,
|
||||||
|
|
||||||
|
n_uavs: int,
|
||||||
|
|
||||||
|
sensor_radius: float,
|
||||||
|
|
||||||
|
seed_positions: np.ndarray | None = None,
|
||||||
|
|
||||||
|
seed: int = 42,
|
||||||
|
|
||||||
|
) -> list[PartitionCell]:
|
||||||
|
|
||||||
|
"""
|
||||||
|
|
||||||
|
Partition coverage grid points by nearest depot (one-shot Voronoi on grid).
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
UAV i always owns the cell built from its depot; no Hungarian reassignment.
|
||||||
|
|
||||||
|
"""
|
||||||
|
|
||||||
|
spacing = sensor_radius * np.sqrt(2)
|
||||||
|
|
||||||
|
points = _coverage_grid_points(region, spacing)
|
||||||
|
|
||||||
|
n_uavs = min(n_uavs, len(points))
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
if seed_positions is not None and len(seed_positions) >= n_uavs:
|
||||||
|
|
||||||
|
depots = np.asarray(seed_positions[:n_uavs], dtype=float)
|
||||||
|
|
||||||
|
else:
|
||||||
|
|
||||||
|
rng = np.random.default_rng(seed)
|
||||||
|
|
||||||
|
depots = points[rng.choice(len(points), size=n_uavs, replace=False)]
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
labels = _labels_from_seeds(points, depots)
|
||||||
|
|
||||||
|
return _cells_from_labels(region, points, labels, depots, spacing)
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
def partition_lloyd(
|
||||||
|
|
||||||
|
region: RectRegion,
|
||||||
|
|
||||||
|
depots: np.ndarray,
|
||||||
|
|
||||||
|
sensor_radius: float,
|
||||||
|
|
||||||
|
iterations: int = 6,
|
||||||
|
|
||||||
|
) -> list[PartitionCell]:
|
||||||
|
|
||||||
|
"""
|
||||||
|
|
||||||
|
Lloyd relaxation on the coverage grid, anchored to depot ownership.
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
Virtual seeds move to cluster centroids each iteration, but UAV i always
|
||||||
|
|
||||||
|
patrols the cell labeled i; the physical depot stays at depots[i].
|
||||||
|
|
||||||
|
"""
|
||||||
|
|
||||||
|
depots = np.asarray(depots, dtype=float)
|
||||||
|
|
||||||
|
spacing = sensor_radius * np.sqrt(2)
|
||||||
|
|
||||||
|
points = _coverage_grid_points(region, spacing)
|
||||||
|
|
||||||
|
virtual = depots.copy()
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
for _ in range(max(iterations, 1)):
|
||||||
|
|
||||||
|
labels = _labels_from_seeds(points, virtual)
|
||||||
|
|
||||||
|
new_virtual = []
|
||||||
|
|
||||||
|
for pid in range(len(depots)):
|
||||||
|
|
||||||
|
cluster = points[labels == pid]
|
||||||
|
|
||||||
|
if len(cluster) == 0:
|
||||||
|
|
||||||
|
new_virtual.append(virtual[pid])
|
||||||
|
|
||||||
|
else:
|
||||||
|
|
||||||
|
new_virtual.append(cluster.mean(axis=0))
|
||||||
|
|
||||||
|
virtual = np.array(new_virtual)
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
labels = _labels_from_seeds(points, virtual)
|
||||||
|
|
||||||
|
return _cells_from_labels(region, points, labels, depots, spacing)
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
def build_partition(
|
||||||
|
|
||||||
|
region: RectRegion,
|
||||||
|
|
||||||
|
n_uavs: int,
|
||||||
|
|
||||||
|
mode: str,
|
||||||
|
|
||||||
|
initial_positions: np.ndarray,
|
||||||
|
|
||||||
|
sensor_radius: float = 50.0,
|
||||||
|
|
||||||
|
strip_direction: str = "vertical",
|
||||||
|
|
||||||
|
lloyd_iterations: int = 6,
|
||||||
|
|
||||||
|
seed: int = 42,
|
||||||
|
|
||||||
|
) -> PartitionResult:
|
||||||
|
|
||||||
|
"""
|
||||||
|
|
||||||
|
Build geographic partition then match uneven UAV deployments to cells.
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
Modes
|
||||||
|
|
||||||
|
-----
|
||||||
|
|
||||||
|
workload : nearest-depot grid cells (depot i owns cell i)
|
||||||
|
|
||||||
|
lloyd : Lloyd-relaxed grid cells (depot i owns cell i)
|
||||||
|
|
||||||
|
voronoi : bounded Voronoi from depot positions (depot inside own cell)
|
||||||
|
|
||||||
|
uniform : equal-area strips + Hungarian match to depots
|
||||||
|
|
||||||
|
"""
|
||||||
|
|
||||||
|
positions = np.asarray(initial_positions, dtype=float)
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
if mode == "uniform":
|
||||||
|
|
||||||
|
return partition_and_assign(region, n_uavs, positions, direction=strip_direction)
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
if mode == "voronoi":
|
||||||
|
|
||||||
|
return partition_voronoi(region, positions)
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
if mode == "lloyd":
|
||||||
|
|
||||||
|
cells = partition_lloyd(region, positions, sensor_radius, iterations=lloyd_iterations)
|
||||||
|
|
||||||
|
return PartitionResult(region=region, initial_positions=positions, cells=cells)
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
if mode == "workload":
|
||||||
|
|
||||||
|
cells = partition_workload(region, n_uavs, sensor_radius, seed_positions=positions, seed=seed)
|
||||||
|
|
||||||
|
return PartitionResult(region=region, initial_positions=positions, cells=cells)
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
raise ValueError(f"Unknown partition mode: {mode}")
|
||||||
|
|
||||||
@@ -0,0 +1,49 @@
|
|||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import numpy as np
|
||||||
|
|
||||||
|
from uavsearch.geometry import RectRegion
|
||||||
|
|
||||||
|
|
||||||
|
def generate_uneven_positions(
|
||||||
|
region: RectRegion,
|
||||||
|
n_uavs: int,
|
||||||
|
seed: int = 42,
|
||||||
|
margin_ratio: float = 0.05,
|
||||||
|
) -> np.ndarray:
|
||||||
|
"""
|
||||||
|
Generate spatially uneven initial UAV positions inside the region.
|
||||||
|
|
||||||
|
Uses a U-shaped (Beta) distribution along each axis so positions cluster
|
||||||
|
toward edges/corners rather than a uniform or grid layout.
|
||||||
|
"""
|
||||||
|
if n_uavs < 1:
|
||||||
|
raise ValueError("n_uavs must be >= 1")
|
||||||
|
|
||||||
|
rng = np.random.default_rng(seed)
|
||||||
|
mx = region.width * margin_ratio
|
||||||
|
my = region.height * margin_ratio
|
||||||
|
x0, x1 = region.xmin + mx, region.xmax - mx
|
||||||
|
y0, y1 = region.ymin + my, region.ymax - my
|
||||||
|
|
||||||
|
xs = x0 + rng.beta(0.4, 0.4, n_uavs) * (x1 - x0)
|
||||||
|
ys = y0 + rng.beta(0.4, 0.4, n_uavs) * (y1 - y0)
|
||||||
|
return np.column_stack([xs, ys])
|
||||||
|
|
||||||
|
|
||||||
|
def parse_initial_positions(
|
||||||
|
region: RectRegion,
|
||||||
|
positions: np.ndarray | list[tuple[float, float]] | None,
|
||||||
|
n_uavs: int,
|
||||||
|
seed: int = 42,
|
||||||
|
) -> np.ndarray:
|
||||||
|
"""Resolve initial positions from explicit coords or auto-generate uneven layout."""
|
||||||
|
if positions is None:
|
||||||
|
return generate_uneven_positions(region, n_uavs, seed=seed)
|
||||||
|
|
||||||
|
pts = np.asarray(positions, dtype=float)
|
||||||
|
if pts.shape != (n_uavs, 2):
|
||||||
|
raise ValueError(f"Expected ({n_uavs}, 2) positions, got {pts.shape}")
|
||||||
|
|
||||||
|
clipped = np.array([region.clip_point(float(x), float(y)) for x, y in pts])
|
||||||
|
return clipped
|
||||||
@@ -0,0 +1,46 @@
|
|||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
from dataclasses import dataclass
|
||||||
|
from typing import Literal
|
||||||
|
|
||||||
|
from uavsearch.geometry import RectRegion
|
||||||
|
|
||||||
|
StripDirection = Literal["vertical", "horizontal"]
|
||||||
|
|
||||||
|
|
||||||
|
@dataclass
|
||||||
|
class StripPartitioner:
|
||||||
|
"""Divide a rectangular region into equal strips for multi-UAV assignment."""
|
||||||
|
|
||||||
|
direction: StripDirection = "vertical"
|
||||||
|
|
||||||
|
def partition(self, region: RectRegion, n_uavs: int) -> list[RectRegion]:
|
||||||
|
if n_uavs < 1:
|
||||||
|
raise ValueError("n_uavs must be >= 1")
|
||||||
|
|
||||||
|
if n_uavs == 1:
|
||||||
|
return [region]
|
||||||
|
|
||||||
|
strips: list[RectRegion] = []
|
||||||
|
if self.direction == "vertical":
|
||||||
|
step = region.width / n_uavs
|
||||||
|
for i in range(n_uavs):
|
||||||
|
x0 = region.xmin + i * step
|
||||||
|
x1 = region.xmin + (i + 1) * step
|
||||||
|
strips.append(RectRegion(x0, region.ymin, x1, region.ymax))
|
||||||
|
else:
|
||||||
|
step = region.height / n_uavs
|
||||||
|
for i in range(n_uavs):
|
||||||
|
y0 = region.ymin + i * step
|
||||||
|
y1 = region.ymin + (i + 1) * step
|
||||||
|
strips.append(RectRegion(region.xmin, y0, region.xmax, y1))
|
||||||
|
|
||||||
|
return strips
|
||||||
|
|
||||||
|
|
||||||
|
def partition_strips(
|
||||||
|
region: RectRegion,
|
||||||
|
n_uavs: int,
|
||||||
|
direction: StripDirection = "vertical",
|
||||||
|
) -> list[RectRegion]:
|
||||||
|
return StripPartitioner(direction=direction).partition(region, n_uavs)
|
||||||
@@ -0,0 +1,64 @@
|
|||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
from dataclasses import dataclass
|
||||||
|
from typing import Literal
|
||||||
|
|
||||||
|
from shapely.geometry import box
|
||||||
|
|
||||||
|
from uavsearch.geometry import RectRegion
|
||||||
|
from uavsearch.partition.voronoi import PartitionCell, PartitionResult
|
||||||
|
|
||||||
|
StripDirection = Literal["vertical", "horizontal"]
|
||||||
|
|
||||||
|
|
||||||
|
@dataclass
|
||||||
|
class UniformPartitioner:
|
||||||
|
"""Divide airspace into equal-area strips (uniform geographic partition)."""
|
||||||
|
|
||||||
|
direction: StripDirection = "vertical"
|
||||||
|
|
||||||
|
def partition(self, region: RectRegion, n_uavs: int) -> list[PartitionCell]:
|
||||||
|
if n_uavs < 1:
|
||||||
|
raise ValueError("n_uavs must be >= 1")
|
||||||
|
|
||||||
|
strips = self._equal_strips(region, n_uavs)
|
||||||
|
cells: list[PartitionCell] = []
|
||||||
|
for pid, strip in enumerate(strips):
|
||||||
|
poly = box(strip.xmin, strip.ymin, strip.xmax, strip.ymax)
|
||||||
|
cells.append(
|
||||||
|
PartitionCell(
|
||||||
|
uav_id=pid,
|
||||||
|
partition_id=pid,
|
||||||
|
initial_position=strip.centroid,
|
||||||
|
polygon=poly,
|
||||||
|
bounds=strip,
|
||||||
|
)
|
||||||
|
)
|
||||||
|
return cells
|
||||||
|
|
||||||
|
def _equal_strips(self, region: RectRegion, n_uavs: int) -> list[RectRegion]:
|
||||||
|
if n_uavs == 1:
|
||||||
|
return [region]
|
||||||
|
|
||||||
|
strips: list[RectRegion] = []
|
||||||
|
if self.direction == "vertical":
|
||||||
|
step = region.width / n_uavs
|
||||||
|
for i in range(n_uavs):
|
||||||
|
x0 = region.xmin + i * step
|
||||||
|
x1 = region.xmin + (i + 1) * step
|
||||||
|
strips.append(RectRegion(x0, region.ymin, x1, region.ymax))
|
||||||
|
else:
|
||||||
|
step = region.height / n_uavs
|
||||||
|
for i in range(n_uavs):
|
||||||
|
y0 = region.ymin + i * step
|
||||||
|
y1 = region.ymin + (i + 1) * step
|
||||||
|
strips.append(RectRegion(region.xmin, y0, region.xmax, y1))
|
||||||
|
return strips
|
||||||
|
|
||||||
|
|
||||||
|
def partition_uniform(
|
||||||
|
region: RectRegion,
|
||||||
|
n_uavs: int,
|
||||||
|
direction: StripDirection = "vertical",
|
||||||
|
) -> list[PartitionCell]:
|
||||||
|
return UniformPartitioner(direction=direction).partition(region, n_uavs)
|
||||||
@@ -0,0 +1,95 @@
|
|||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
from dataclasses import dataclass
|
||||||
|
|
||||||
|
import numpy as np
|
||||||
|
from shapely.geometry import MultiPoint, Point
|
||||||
|
from shapely.ops import voronoi_diagram
|
||||||
|
|
||||||
|
from uavsearch.geometry import RectRegion
|
||||||
|
|
||||||
|
|
||||||
|
@dataclass
|
||||||
|
class PartitionCell:
|
||||||
|
"""One UAV's assigned sub-region."""
|
||||||
|
|
||||||
|
uav_id: int
|
||||||
|
partition_id: int
|
||||||
|
initial_position: tuple[float, float]
|
||||||
|
polygon: object # shapely Polygon
|
||||||
|
bounds: RectRegion
|
||||||
|
|
||||||
|
@property
|
||||||
|
def area(self) -> float:
|
||||||
|
return float(self.polygon.area)
|
||||||
|
|
||||||
|
|
||||||
|
@dataclass
|
||||||
|
class PartitionResult:
|
||||||
|
"""Region partition outcome before patrol path planning."""
|
||||||
|
|
||||||
|
region: RectRegion
|
||||||
|
initial_positions: np.ndarray
|
||||||
|
cells: list[PartitionCell]
|
||||||
|
|
||||||
|
@property
|
||||||
|
def n_uavs(self) -> int:
|
||||||
|
return len(self.cells)
|
||||||
|
|
||||||
|
|
||||||
|
def partition_voronoi(region: RectRegion, initial_positions: np.ndarray) -> PartitionResult:
|
||||||
|
"""
|
||||||
|
Partition the airspace via bounded Voronoi diagram seeded at UAV positions.
|
||||||
|
|
||||||
|
Each UAV is assigned the cell closest to its initial position; cells are
|
||||||
|
clipped to the airspace boundary.
|
||||||
|
"""
|
||||||
|
positions = np.asarray(initial_positions, dtype=float)
|
||||||
|
if len(positions) < 1:
|
||||||
|
raise ValueError("At least one initial position required")
|
||||||
|
|
||||||
|
envelope = region.to_polygon()
|
||||||
|
seeds = MultiPoint([tuple(p) for p in positions])
|
||||||
|
diagram = voronoi_diagram(seeds, envelope=envelope)
|
||||||
|
|
||||||
|
cells: list[PartitionCell] = []
|
||||||
|
for uav_id, pos in enumerate(positions):
|
||||||
|
seed_pt = Point(float(pos[0]), float(pos[1]))
|
||||||
|
cell_poly = _find_cell_for_seed(diagram, seed_pt, envelope)
|
||||||
|
xmin, ymin, xmax, ymax = cell_poly.bounds
|
||||||
|
bounds = RectRegion(xmin, ymin, xmax, ymax)
|
||||||
|
cells.append(
|
||||||
|
PartitionCell(
|
||||||
|
uav_id=uav_id,
|
||||||
|
partition_id=uav_id,
|
||||||
|
initial_position=(float(pos[0]), float(pos[1])),
|
||||||
|
polygon=cell_poly,
|
||||||
|
bounds=bounds,
|
||||||
|
)
|
||||||
|
)
|
||||||
|
|
||||||
|
return PartitionResult(region=region, initial_positions=positions, cells=cells)
|
||||||
|
|
||||||
|
|
||||||
|
def _find_cell_for_seed(diagram, seed_pt: Point, envelope):
|
||||||
|
"""Locate the Voronoi polygon that contains the seed point."""
|
||||||
|
if hasattr(diagram, "geoms"):
|
||||||
|
candidates = list(diagram.geoms)
|
||||||
|
else:
|
||||||
|
candidates = [diagram]
|
||||||
|
|
||||||
|
best = None
|
||||||
|
best_dist = float("inf")
|
||||||
|
for geom in candidates:
|
||||||
|
if geom.is_empty:
|
||||||
|
continue
|
||||||
|
if geom.contains(seed_pt) or geom.boundary.distance(seed_pt) < 1e-6:
|
||||||
|
return geom.intersection(envelope)
|
||||||
|
dist = geom.distance(seed_pt)
|
||||||
|
if dist < best_dist:
|
||||||
|
best_dist = dist
|
||||||
|
best = geom
|
||||||
|
|
||||||
|
if best is None:
|
||||||
|
return envelope
|
||||||
|
return best.intersection(envelope)
|
||||||
@@ -0,0 +1,12 @@
|
|||||||
|
from .boustrophedon import BoustrophedonPlanner, PatrolPath
|
||||||
|
from .mtsp import MtspPlanner
|
||||||
|
from .patrol import plan_boustrophedon_patrol, plan_mtsp_patrol, plan_patrol
|
||||||
|
|
||||||
|
__all__ = [
|
||||||
|
"BoustrophedonPlanner",
|
||||||
|
"PatrolPath",
|
||||||
|
"plan_patrol",
|
||||||
|
"plan_boustrophedon_patrol",
|
||||||
|
"MtspPlanner",
|
||||||
|
"plan_mtsp_patrol",
|
||||||
|
]
|
||||||
@@ -0,0 +1,260 @@
|
|||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
from dataclasses import dataclass
|
||||||
|
|
||||||
|
import numpy as np
|
||||||
|
|
||||||
|
from uavsearch.geometry import RectRegion
|
||||||
|
|
||||||
|
|
||||||
|
@dataclass
|
||||||
|
class PatrolPath:
|
||||||
|
"""
|
||||||
|
Patrol path with depot round-trip.
|
||||||
|
|
||||||
|
Operational cycle (repeated):
|
||||||
|
depot -> patrol entry -> one patrol loop -> patrol entry -> depot -> [service]
|
||||||
|
|
||||||
|
``initial_position`` is the depot / maintenance / battery-swap station.
|
||||||
|
"""
|
||||||
|
|
||||||
|
uav_id: int
|
||||||
|
region: RectRegion
|
||||||
|
waypoints: np.ndarray # closed loop, first == last
|
||||||
|
initial_position: tuple[float, float] # depot station
|
||||||
|
entry_index: int = 0
|
||||||
|
|
||||||
|
@property
|
||||||
|
def depot_position(self) -> tuple[float, float]:
|
||||||
|
return self.initial_position
|
||||||
|
|
||||||
|
@property
|
||||||
|
def loop_length(self) -> float:
|
||||||
|
if len(self.waypoints) < 2:
|
||||||
|
return 0.0
|
||||||
|
diffs = np.diff(self.waypoints, axis=0)
|
||||||
|
return float(np.sum(np.linalg.norm(diffs, axis=1)))
|
||||||
|
|
||||||
|
@property
|
||||||
|
def length(self) -> float:
|
||||||
|
"""Patrol loop length only (legacy alias)."""
|
||||||
|
return self.loop_length
|
||||||
|
|
||||||
|
@property
|
||||||
|
def period(self) -> float:
|
||||||
|
return self.loop_length
|
||||||
|
|
||||||
|
@property
|
||||||
|
def outbound_transit_length(self) -> float:
|
||||||
|
entry = self.waypoints[self.entry_index]
|
||||||
|
depot = np.array(self.depot_position)
|
||||||
|
return float(np.linalg.norm(entry - depot))
|
||||||
|
|
||||||
|
@property
|
||||||
|
def inbound_transit_length(self) -> float:
|
||||||
|
return self.outbound_transit_length
|
||||||
|
|
||||||
|
@property
|
||||||
|
def transit_length(self) -> float:
|
||||||
|
"""Legacy: outbound transit only."""
|
||||||
|
return self.outbound_transit_length
|
||||||
|
|
||||||
|
@property
|
||||||
|
def operational_cycle_distance(self) -> float:
|
||||||
|
"""Full round-trip distance: depot -> loop -> depot."""
|
||||||
|
return self.outbound_transit_length + self.loop_length + self.inbound_transit_length
|
||||||
|
|
||||||
|
def operational_cycle_period(self, speed: float, depot_service_time: float = 0.0) -> float:
|
||||||
|
"""Wall-clock period including flight and depot service."""
|
||||||
|
if speed <= 0:
|
||||||
|
return float("inf")
|
||||||
|
return self.operational_cycle_distance / speed + depot_service_time
|
||||||
|
|
||||||
|
@property
|
||||||
|
def loop_starts_at_entry(self) -> np.ndarray:
|
||||||
|
wp = self.waypoints
|
||||||
|
if len(wp) < 2:
|
||||||
|
return wp
|
||||||
|
idx = self.entry_index
|
||||||
|
return np.vstack([wp[idx:-1], wp[: idx + 1]])
|
||||||
|
|
||||||
|
def phase_at_time(self, t: float, speed: float, depot_service_time: float) -> str:
|
||||||
|
"""Return phase name at time t within one operational cycle."""
|
||||||
|
if speed <= 0:
|
||||||
|
return "depot_service"
|
||||||
|
t_out = self.outbound_transit_length / speed
|
||||||
|
t_loop = self.loop_length / speed
|
||||||
|
t_in = self.inbound_transit_length / speed
|
||||||
|
t_cycle = t_out + t_loop + t_in + depot_service_time
|
||||||
|
t = t % max(t_cycle, 1e-9)
|
||||||
|
|
||||||
|
if t < t_out:
|
||||||
|
return "outbound"
|
||||||
|
if t < t_out + t_loop:
|
||||||
|
return "patrol"
|
||||||
|
if t < t_out + t_loop + t_in:
|
||||||
|
return "inbound"
|
||||||
|
return "depot_service"
|
||||||
|
|
||||||
|
def position_at_time(self, t: float, speed: float, depot_service_time: float) -> tuple[float, float]:
|
||||||
|
phase = self.phase_at_time(t, speed, depot_service_time)
|
||||||
|
depot = np.array(self.depot_position)
|
||||||
|
loop = self.loop_starts_at_entry
|
||||||
|
entry = loop[0] if len(loop) else depot
|
||||||
|
|
||||||
|
if speed <= 0:
|
||||||
|
return tuple(self.depot_position)
|
||||||
|
|
||||||
|
t_out = self.outbound_transit_length / speed
|
||||||
|
t_loop = self.loop_length / speed
|
||||||
|
t_in = self.inbound_transit_length / speed
|
||||||
|
t_cycle = t_out + t_loop + t_in + depot_service_time
|
||||||
|
t = t % max(t_cycle, 1e-9)
|
||||||
|
|
||||||
|
if phase == "depot_service":
|
||||||
|
return tuple(self.depot_position)
|
||||||
|
if phase == "outbound":
|
||||||
|
u = t / max(t_out, 1e-9)
|
||||||
|
p = depot + u * (entry - depot)
|
||||||
|
return float(p[0]), float(p[1])
|
||||||
|
if phase == "inbound":
|
||||||
|
u = (t - t_out - t_loop) / max(t_in, 1e-9)
|
||||||
|
p = entry + u * (depot - entry)
|
||||||
|
return float(p[0]), float(p[1])
|
||||||
|
# patrol
|
||||||
|
return self._interpolate_loop((t - t_out) * speed, loop)
|
||||||
|
|
||||||
|
def _interpolate_loop(self, dist: float, loop: np.ndarray) -> tuple[float, float]:
|
||||||
|
if len(loop) < 2:
|
||||||
|
return tuple(self.depot_position)
|
||||||
|
|
||||||
|
loop_len = max(self.loop_length, 1e-9)
|
||||||
|
dist = dist % loop_len
|
||||||
|
segments = np.linalg.norm(np.diff(loop, axis=0), axis=1)
|
||||||
|
cumulative = np.concatenate([[0.0], np.cumsum(segments)])
|
||||||
|
total = cumulative[-1]
|
||||||
|
if total <= 1e-9:
|
||||||
|
return tuple(loop[0])
|
||||||
|
|
||||||
|
dist = dist % total
|
||||||
|
idx = int(np.searchsorted(cumulative, dist, side="right") - 1)
|
||||||
|
idx = min(idx, len(segments) - 1)
|
||||||
|
seg_len = segments[idx]
|
||||||
|
if seg_len <= 1e-9:
|
||||||
|
return tuple(loop[idx])
|
||||||
|
|
||||||
|
u = (dist - cumulative[idx]) / seg_len
|
||||||
|
p0 = loop[idx]
|
||||||
|
p1 = loop[idx + 1]
|
||||||
|
pos = p0 + u * (p1 - p0)
|
||||||
|
return float(pos[0]), float(pos[1])
|
||||||
|
|
||||||
|
|
||||||
|
class BoustrophedonPlanner:
|
||||||
|
"""Generate boustrophedon (lawn-mower) closed-loop patrol paths."""
|
||||||
|
|
||||||
|
def __init__(self, sweep_width: float, sweep_axis: str = "x"):
|
||||||
|
if sweep_width <= 0:
|
||||||
|
raise ValueError("sweep_width must be positive")
|
||||||
|
self.sweep_width = sweep_width
|
||||||
|
self.sweep_axis = sweep_axis
|
||||||
|
|
||||||
|
def plan_cell(self, cell, uav_id: int = 0) -> PatrolPath:
|
||||||
|
waypoints = self._boustrophedon_closed_loop(cell.bounds)
|
||||||
|
entry_index = _nearest_waypoint_index(waypoints, cell.initial_position)
|
||||||
|
return PatrolPath(
|
||||||
|
uav_id=cell.uav_id,
|
||||||
|
region=cell.bounds,
|
||||||
|
waypoints=waypoints,
|
||||||
|
initial_position=cell.initial_position,
|
||||||
|
entry_index=entry_index,
|
||||||
|
)
|
||||||
|
|
||||||
|
def plan_from_partition(self, partition) -> list[PatrolPath]:
|
||||||
|
return [self.plan_cell(cell) for cell in partition.cells]
|
||||||
|
|
||||||
|
def _boustrophedon_closed_loop(self, strip: RectRegion) -> np.ndarray:
|
||||||
|
if self.sweep_axis == "x":
|
||||||
|
scan_path = self._zigzag_scan(strip.xmin, strip.xmax, strip.ymin, strip.ymax, along_x=True)
|
||||||
|
closed = self._close_loop_horizontal(scan_path, strip)
|
||||||
|
else:
|
||||||
|
scan_path = self._zigzag_scan(strip.ymin, strip.ymax, strip.xmin, strip.xmax, along_x=False)
|
||||||
|
closed = self._close_loop_vertical(scan_path, strip)
|
||||||
|
return np.asarray(closed, dtype=float)
|
||||||
|
|
||||||
|
def _zigzag_scan(self, a_min, a_max, b_min, b_max, along_x: bool) -> list[tuple[float, float]]:
|
||||||
|
path: list[tuple[float, float]] = []
|
||||||
|
half = self.sweep_width / 2
|
||||||
|
b = b_min + half
|
||||||
|
forward = True
|
||||||
|
while b <= b_max - half + 1e-9:
|
||||||
|
if along_x:
|
||||||
|
path.extend([(a_min, b), (a_max, b)] if forward else [(a_max, b), (a_min, b)])
|
||||||
|
else:
|
||||||
|
path.extend([(b, a_min), (b, a_max)] if forward else [(b, a_max), (b, a_min)])
|
||||||
|
b += self.sweep_width
|
||||||
|
forward = not forward
|
||||||
|
if not path:
|
||||||
|
cx, cy = (a_min + a_max) / 2, (b_min + b_max) / 2
|
||||||
|
path = [(a_min, cy), (a_max, cy)] if along_x else [(cx, b_min), (cx, b_max)]
|
||||||
|
return path
|
||||||
|
|
||||||
|
def _close_loop_horizontal(self, scan_path, strip: RectRegion):
|
||||||
|
if len(scan_path) < 2:
|
||||||
|
cx, cy = strip.centroid
|
||||||
|
return [(cx, cy), (cx, cy)]
|
||||||
|
closed = list(scan_path)
|
||||||
|
x0, y0 = closed[0]
|
||||||
|
x1, y1 = closed[-1]
|
||||||
|
if abs(x1 - x0) < 1e-9:
|
||||||
|
ext = (
|
||||||
|
[(x0, strip.ymax), (strip.xmax, strip.ymax), (strip.xmax, strip.ymin), (strip.xmin, strip.ymin)]
|
||||||
|
if y1 >= y0
|
||||||
|
else [(x0, strip.ymin), (strip.xmax, strip.ymin), (strip.xmax, strip.ymax), (strip.xmin, strip.ymax)]
|
||||||
|
)
|
||||||
|
closed.extend(ext)
|
||||||
|
elif x1 > x0:
|
||||||
|
closed.extend([(strip.xmax, y1), (strip.xmax, y0)])
|
||||||
|
else:
|
||||||
|
closed.extend([(strip.xmin, y1), (strip.xmin, y0)])
|
||||||
|
closed.append(closed[0])
|
||||||
|
return self._dedupe_consecutive(closed)
|
||||||
|
|
||||||
|
def _close_loop_vertical(self, scan_path, strip: RectRegion):
|
||||||
|
if len(scan_path) < 2:
|
||||||
|
cx, cy = strip.centroid
|
||||||
|
return [(cx, cy), (cx, cy)]
|
||||||
|
closed = list(scan_path)
|
||||||
|
x0, y0 = closed[0]
|
||||||
|
x1, y1 = closed[-1]
|
||||||
|
if abs(y1 - y0) < 1e-9:
|
||||||
|
ext = (
|
||||||
|
[(strip.xmax, y0), (strip.xmax, strip.ymax), (strip.xmin, strip.ymax), (strip.xmin, strip.ymin)]
|
||||||
|
if x1 >= x0
|
||||||
|
else [(strip.xmin, y0), (strip.xmin, strip.ymax), (strip.xmax, strip.ymax), (strip.xmax, strip.ymin)]
|
||||||
|
)
|
||||||
|
closed.extend(ext)
|
||||||
|
elif y1 > y0:
|
||||||
|
closed.extend([(x1, strip.ymax), (x0, strip.ymax)])
|
||||||
|
else:
|
||||||
|
closed.extend([(x1, strip.ymin), (x0, strip.ymin)])
|
||||||
|
closed.append(closed[0])
|
||||||
|
return self._dedupe_consecutive(closed)
|
||||||
|
|
||||||
|
@staticmethod
|
||||||
|
def _dedupe_consecutive(points: list[tuple[float, float]]) -> list[tuple[float, float]]:
|
||||||
|
if not points:
|
||||||
|
return []
|
||||||
|
out = [points[0]]
|
||||||
|
for p in points[1:]:
|
||||||
|
if abs(p[0] - out[-1][0]) > 1e-9 or abs(p[1] - out[-1][1]) > 1e-9:
|
||||||
|
out.append(p)
|
||||||
|
return out
|
||||||
|
|
||||||
|
|
||||||
|
def _nearest_waypoint_index(waypoints: np.ndarray, position: tuple[float, float]) -> int:
|
||||||
|
if len(waypoints) == 0:
|
||||||
|
return 0
|
||||||
|
pts = waypoints[:-1] if np.allclose(waypoints[0], waypoints[-1]) else waypoints
|
||||||
|
dists = np.linalg.norm(pts - np.array(position), axis=1)
|
||||||
|
return int(np.argmin(dists))
|
||||||
@@ -0,0 +1,116 @@
|
|||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
from dataclasses import dataclass
|
||||||
|
|
||||||
|
import numpy as np
|
||||||
|
|
||||||
|
from uavsearch.geometry import RectRegion
|
||||||
|
from uavsearch.partition import PartitionResult
|
||||||
|
from uavsearch.planner.boustrophedon import PatrolPath, _nearest_waypoint_index
|
||||||
|
|
||||||
|
|
||||||
|
@dataclass
|
||||||
|
class MtspPlanner:
|
||||||
|
"""Grid waypoint coverage with Voronoi partition and per-UAV TSP loops."""
|
||||||
|
|
||||||
|
sensor_radius: float
|
||||||
|
waypoint_spacing_factor: float = 1.4142135623730951
|
||||||
|
|
||||||
|
@property
|
||||||
|
def waypoint_spacing(self) -> float:
|
||||||
|
return self.sensor_radius * self.waypoint_spacing_factor
|
||||||
|
|
||||||
|
def plan_from_partition(self, partition: PartitionResult) -> list[PatrolPath]:
|
||||||
|
waypoints = self._generate_waypoints(partition.region)
|
||||||
|
paths: list[PatrolPath] = []
|
||||||
|
|
||||||
|
for cell in partition.cells:
|
||||||
|
cluster_pts = self._waypoints_in_cell(waypoints, cell.polygon)
|
||||||
|
if len(cluster_pts) == 0:
|
||||||
|
cluster_pts = np.array([cell.initial_position])
|
||||||
|
tour = self._tsp_closed_tour(cluster_pts, start_hint=np.array(cell.initial_position))
|
||||||
|
entry_index = _nearest_waypoint_index(tour, cell.initial_position)
|
||||||
|
xmin, ymin, xmax, ymax = cell.polygon.bounds
|
||||||
|
paths.append(
|
||||||
|
PatrolPath(
|
||||||
|
uav_id=cell.uav_id,
|
||||||
|
region=RectRegion(xmin, ymin, xmax, ymax),
|
||||||
|
waypoints=tour,
|
||||||
|
initial_position=cell.initial_position,
|
||||||
|
entry_index=entry_index,
|
||||||
|
)
|
||||||
|
)
|
||||||
|
|
||||||
|
return paths
|
||||||
|
|
||||||
|
def _generate_waypoints(self, region: RectRegion) -> np.ndarray:
|
||||||
|
spacing = self.waypoint_spacing
|
||||||
|
xs = np.arange(region.xmin + spacing / 2, region.xmax, spacing)
|
||||||
|
ys = np.arange(region.ymin + spacing / 2, region.ymax, spacing)
|
||||||
|
if len(xs) == 0 or len(ys) == 0:
|
||||||
|
return np.empty((0, 2))
|
||||||
|
gx, gy = np.meshgrid(xs, ys)
|
||||||
|
return np.column_stack([gx.ravel(), gy.ravel()])
|
||||||
|
|
||||||
|
def _waypoints_in_cell(self, waypoints: np.ndarray, polygon) -> np.ndarray:
|
||||||
|
if len(waypoints) == 0:
|
||||||
|
return waypoints
|
||||||
|
from shapely.geometry import Point
|
||||||
|
|
||||||
|
mask = np.array([polygon.contains(Point(x, y)) for x, y in waypoints])
|
||||||
|
return waypoints[mask]
|
||||||
|
|
||||||
|
def _tsp_closed_tour(self, points: np.ndarray, start_hint: np.ndarray | None = None) -> np.ndarray:
|
||||||
|
if len(points) == 1:
|
||||||
|
return np.vstack([points, points])
|
||||||
|
|
||||||
|
start_idx = 0
|
||||||
|
if start_hint is not None:
|
||||||
|
start_idx = int(np.argmin(np.linalg.norm(points - start_hint, axis=1)))
|
||||||
|
|
||||||
|
tour = self._nearest_neighbor_tour(points, start_idx=start_idx)
|
||||||
|
tour = self._two_opt(tour, points)
|
||||||
|
tour = np.vstack([tour, tour[0]])
|
||||||
|
return tour
|
||||||
|
|
||||||
|
def _nearest_neighbor_tour(self, points: np.ndarray, start_idx: int = 0) -> np.ndarray:
|
||||||
|
n = len(points)
|
||||||
|
unvisited = set(range(n)) - {start_idx}
|
||||||
|
tour = [start_idx]
|
||||||
|
current = start_idx
|
||||||
|
|
||||||
|
while unvisited:
|
||||||
|
nxt = min(unvisited, key=lambda j: np.linalg.norm(points[current] - points[j]))
|
||||||
|
tour.append(nxt)
|
||||||
|
unvisited.remove(nxt)
|
||||||
|
current = nxt
|
||||||
|
|
||||||
|
return points[np.array(tour)]
|
||||||
|
|
||||||
|
def _two_opt(self, tour: np.ndarray, points: np.ndarray) -> np.ndarray:
|
||||||
|
if len(tour) <= 3:
|
||||||
|
return tour
|
||||||
|
|
||||||
|
index = {tuple(p): i for i, p in enumerate(points)}
|
||||||
|
order = [index[tuple(p)] for p in tour]
|
||||||
|
improved = True
|
||||||
|
|
||||||
|
while improved:
|
||||||
|
improved = False
|
||||||
|
for i in range(1, len(order) - 2):
|
||||||
|
for j in range(i + 1, len(order)):
|
||||||
|
if j - i == 1:
|
||||||
|
continue
|
||||||
|
a, b = order[i - 1], order[i]
|
||||||
|
c, d = order[j - 1], order[j % len(order)]
|
||||||
|
before = self._dist(points[a], points[b]) + self._dist(points[c], points[d])
|
||||||
|
after = self._dist(points[a], points[c]) + self._dist(points[b], points[d])
|
||||||
|
if after < before - 1e-9:
|
||||||
|
order[i:j] = reversed(order[i:j])
|
||||||
|
improved = True
|
||||||
|
|
||||||
|
return points[np.array(order)]
|
||||||
|
|
||||||
|
@staticmethod
|
||||||
|
def _dist(a: np.ndarray, b: np.ndarray) -> float:
|
||||||
|
return float(np.linalg.norm(a - b))
|
||||||
@@ -0,0 +1,112 @@
|
|||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import numpy as np
|
||||||
|
|
||||||
|
from uavsearch.geometry import RectRegion
|
||||||
|
from uavsearch.partition import PartitionResult, build_partition, parse_initial_positions
|
||||||
|
from uavsearch.partition.voronoi import partition_voronoi
|
||||||
|
from uavsearch.planner.boustrophedon import BoustrophedonPlanner, PatrolPath
|
||||||
|
from uavsearch.planner.mtsp import MtspPlanner
|
||||||
|
|
||||||
|
|
||||||
|
def _resolve_sweep_axis(strip_direction: str, sweep_axis: str) -> str:
|
||||||
|
if sweep_axis in ("x", "y"):
|
||||||
|
return sweep_axis
|
||||||
|
if strip_direction == "horizontal":
|
||||||
|
return "y"
|
||||||
|
return "x"
|
||||||
|
|
||||||
|
|
||||||
|
def plan_patrol(
|
||||||
|
region: RectRegion,
|
||||||
|
n_uavs: int,
|
||||||
|
sensor_radius: float,
|
||||||
|
initial_positions: np.ndarray | list[tuple[float, float]] | None = None,
|
||||||
|
seed: int = 42,
|
||||||
|
partition_mode: str = "workload",
|
||||||
|
planner: str = "mtsp",
|
||||||
|
strip_direction: str | None = None,
|
||||||
|
lloyd_iterations: int = 6,
|
||||||
|
sweep_width_ratio: float = 2.0,
|
||||||
|
sweep_axis: str = "auto",
|
||||||
|
waypoint_spacing_factor: float = 1.4142135623730951,
|
||||||
|
) -> tuple[list[PatrolPath], PartitionResult]:
|
||||||
|
"""
|
||||||
|
Unified patrol planning entry.
|
||||||
|
|
||||||
|
Recommended: partition_mode='workload' + planner='mtsp'
|
||||||
|
Legacy/heuristic: partition_mode='uniform' + planner='boustrophedon'
|
||||||
|
"""
|
||||||
|
positions = parse_initial_positions(region, initial_positions, n_uavs, seed=seed)
|
||||||
|
direction = strip_direction or "vertical"
|
||||||
|
|
||||||
|
if partition_mode == "voronoi":
|
||||||
|
partition = partition_voronoi(region, positions)
|
||||||
|
else:
|
||||||
|
partition = build_partition(
|
||||||
|
region,
|
||||||
|
n_uavs,
|
||||||
|
mode=partition_mode,
|
||||||
|
initial_positions=positions,
|
||||||
|
sensor_radius=sensor_radius,
|
||||||
|
strip_direction=direction,
|
||||||
|
lloyd_iterations=lloyd_iterations,
|
||||||
|
seed=seed,
|
||||||
|
)
|
||||||
|
|
||||||
|
if planner == "boustrophedon":
|
||||||
|
sweep_width = sweep_width_ratio * sensor_radius
|
||||||
|
axis = _resolve_sweep_axis(direction, sweep_axis)
|
||||||
|
paths = BoustrophedonPlanner(sweep_width=sweep_width, sweep_axis=axis).plan_from_partition(partition)
|
||||||
|
elif planner == "mtsp":
|
||||||
|
paths = MtspPlanner(
|
||||||
|
sensor_radius=sensor_radius,
|
||||||
|
waypoint_spacing_factor=waypoint_spacing_factor,
|
||||||
|
).plan_from_partition(partition)
|
||||||
|
else:
|
||||||
|
raise ValueError(f"Unknown planner: {planner}")
|
||||||
|
|
||||||
|
return paths, partition
|
||||||
|
|
||||||
|
|
||||||
|
# Backward-compatible wrappers
|
||||||
|
def plan_boustrophedon_patrol(
|
||||||
|
region: RectRegion,
|
||||||
|
n_uavs: int,
|
||||||
|
sweep_width: float,
|
||||||
|
initial_positions: np.ndarray | list[tuple[float, float]] | None = None,
|
||||||
|
seed: int = 42,
|
||||||
|
partition_mode: str = "uniform",
|
||||||
|
strip_direction: str | None = None,
|
||||||
|
) -> tuple[list[PatrolPath], PartitionResult]:
|
||||||
|
return plan_patrol(
|
||||||
|
region,
|
||||||
|
n_uavs,
|
||||||
|
sensor_radius=sweep_width / 2,
|
||||||
|
initial_positions=initial_positions,
|
||||||
|
seed=seed,
|
||||||
|
partition_mode=partition_mode,
|
||||||
|
planner="boustrophedon",
|
||||||
|
strip_direction=strip_direction,
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def plan_mtsp_patrol(
|
||||||
|
region: RectRegion,
|
||||||
|
n_uavs: int,
|
||||||
|
sensor_radius: float,
|
||||||
|
initial_positions: np.ndarray | list[tuple[float, float]] | None = None,
|
||||||
|
seed: int = 42,
|
||||||
|
partition_mode: str = "workload",
|
||||||
|
strip_direction: str | None = None,
|
||||||
|
) -> tuple[list[PatrolPath], PartitionResult]:
|
||||||
|
return plan_patrol(
|
||||||
|
region,
|
||||||
|
n_uavs,
|
||||||
|
sensor_radius=sensor_radius,
|
||||||
|
initial_positions=initial_positions,
|
||||||
|
seed=seed,
|
||||||
|
partition_mode=partition_mode,
|
||||||
|
planner="mtsp",
|
||||||
|
strip_direction=strip_direction,
|
||||||
|
)
|
||||||
@@ -0,0 +1,295 @@
|
|||||||
|
"""
|
||||||
|
UAVSearch: multi-UAV coverage-period minimization.
|
||||||
|
|
||||||
|
Problem
|
||||||
|
-------
|
||||||
|
Deploy N UAVs over a 2D region. Each UAV operates from a **depot** (initial
|
||||||
|
position): a maintenance / battery-swap station in urban patrol.
|
||||||
|
|
||||||
|
Operational cycle (repeated):
|
||||||
|
depot --outbound--> patrol entry --loop--> patrol entry --inbound--> depot --service-->
|
||||||
|
|
||||||
|
Only the patrol loop provides coverage. Outbound, inbound, and depot service
|
||||||
|
create gaps in coverage; depot location directly affects T_max.
|
||||||
|
|
||||||
|
The optimization goal is:
|
||||||
|
|
||||||
|
min T_max = max_x T(x)
|
||||||
|
|
||||||
|
Decision variables: depot positions (2N) plus induced partition and patrol plan.
|
||||||
|
"""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
from dataclasses import dataclass, field
|
||||||
|
from enum import Enum
|
||||||
|
from typing import Literal
|
||||||
|
|
||||||
|
import numpy as np
|
||||||
|
|
||||||
|
from uavsearch.geometry import RectRegion
|
||||||
|
from uavsearch.metrics import RevisitMetrics
|
||||||
|
from uavsearch.partition import parse_initial_positions
|
||||||
|
from uavsearch.planner import PatrolPath, plan_patrol
|
||||||
|
from uavsearch.sim import PatrolSimulator
|
||||||
|
|
||||||
|
PlannerKind = Literal["mtsp", "boustrophedon"]
|
||||||
|
PartitionKind = Literal["workload", "lloyd", "voronoi", "uniform"]
|
||||||
|
|
||||||
|
|
||||||
|
class CoverageObjective(str, Enum):
|
||||||
|
"""What to minimize (all in seconds)."""
|
||||||
|
|
||||||
|
MAX_REVISIT = "max_revisit"
|
||||||
|
MAX_PATROL_PERIOD = "max_patrol_period"
|
||||||
|
|
||||||
|
|
||||||
|
@dataclass
|
||||||
|
class CoverageProblem:
|
||||||
|
"""Multi-UAV coverage-period minimization problem instance."""
|
||||||
|
|
||||||
|
region: RectRegion
|
||||||
|
n_uavs: int
|
||||||
|
sensor_radius: float
|
||||||
|
speed: float
|
||||||
|
planner: PlannerKind = "mtsp"
|
||||||
|
partition_mode: PartitionKind = "workload"
|
||||||
|
strip_direction: Literal["vertical", "horizontal", "auto"] = "auto"
|
||||||
|
grid_density: float = 4.0
|
||||||
|
sim_dt: float = 0.5
|
||||||
|
depot_service_time: float = 60.0
|
||||||
|
lloyd_iterations: int = 6
|
||||||
|
objective: CoverageObjective = CoverageObjective.MAX_REVISIT
|
||||||
|
weight_t_max: float = 1.0
|
||||||
|
weight_coverage: float = 120.0
|
||||||
|
weight_overlap: float = 100.0
|
||||||
|
bounds_margin: float = 0.05
|
||||||
|
sweep_width_ratio: float = 2.0
|
||||||
|
sweep_axis: Literal["auto", "x", "y"] = "auto"
|
||||||
|
waypoint_spacing_factor: float = 1.4142135623730951
|
||||||
|
fast_eval_max_duration: float = 100.0
|
||||||
|
fast_eval_grid_density_cap: float = 3.0
|
||||||
|
|
||||||
|
@property
|
||||||
|
def sweep_width(self) -> float:
|
||||||
|
return 2 * self.sensor_radius
|
||||||
|
|
||||||
|
@property
|
||||||
|
def n_variables(self) -> int:
|
||||||
|
return 2 * self.n_uavs
|
||||||
|
|
||||||
|
def bounds(self, margin_ratio: float | None = None) -> list[tuple[float, float]]:
|
||||||
|
mr = self.bounds_margin if margin_ratio is None else margin_ratio
|
||||||
|
mx = self.region.width * mr
|
||||||
|
my = self.region.height * mr
|
||||||
|
xb = (self.region.xmin + mx, self.region.xmax - mx)
|
||||||
|
yb = (self.region.ymin + my, self.region.ymax - my)
|
||||||
|
b: list[tuple[float, float]] = []
|
||||||
|
for _ in range(self.n_uavs):
|
||||||
|
b.extend([xb, yb])
|
||||||
|
return b
|
||||||
|
|
||||||
|
def unpack_positions(self, vector: np.ndarray) -> np.ndarray:
|
||||||
|
v = np.asarray(vector, dtype=float).reshape(self.n_uavs, 2)
|
||||||
|
clipped = np.array([self.region.clip_point(float(x), float(y)) for x, y in v])
|
||||||
|
return clipped
|
||||||
|
|
||||||
|
|
||||||
|
@dataclass
|
||||||
|
class DeploymentSolution:
|
||||||
|
initial_positions: np.ndarray
|
||||||
|
paths: list[PatrolPath]
|
||||||
|
partition: object
|
||||||
|
speed: float
|
||||||
|
metrics: RevisitMetrics | None = None
|
||||||
|
max_patrol_period: float = 0.0
|
||||||
|
objective_value: float = field(default=float("inf"))
|
||||||
|
|
||||||
|
@property
|
||||||
|
def patrol_periods(self) -> list[float]:
|
||||||
|
return [p.operational_cycle_period(self.speed, self._depot_service_time) for p in self.paths]
|
||||||
|
|
||||||
|
_depot_service_time: float = 0.0
|
||||||
|
|
||||||
|
|
||||||
|
@dataclass
|
||||||
|
class EvaluationResult:
|
||||||
|
solution: DeploymentSolution
|
||||||
|
objective_value: float
|
||||||
|
max_revisit_time: float
|
||||||
|
mean_revisit_time: float
|
||||||
|
max_patrol_period: float
|
||||||
|
coverage_ratio: float
|
||||||
|
overlap_ratio: float
|
||||||
|
load_balance: float
|
||||||
|
|
||||||
|
def summary_line(self) -> str:
|
||||||
|
return (
|
||||||
|
f"T_max={self.max_revisit_time:.2f}s, T_mean={self.mean_revisit_time:.2f}s, "
|
||||||
|
f"P_max={self.max_patrol_period:.2f}s, coverage={self.coverage_ratio:.1%}, "
|
||||||
|
f"overlap={self.overlap_ratio:.1%}, load_balance={self.load_balance:.2f}, "
|
||||||
|
f"objective={self.objective_value:.1f}"
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def plan_from_deployment(
|
||||||
|
problem: CoverageProblem,
|
||||||
|
positions: np.ndarray,
|
||||||
|
strip_direction: str | None = None,
|
||||||
|
) -> tuple[list[PatrolPath], object]:
|
||||||
|
direction = strip_direction
|
||||||
|
if direction is None and problem.strip_direction != "auto":
|
||||||
|
direction = problem.strip_direction
|
||||||
|
|
||||||
|
return plan_patrol(
|
||||||
|
problem.region,
|
||||||
|
problem.n_uavs,
|
||||||
|
problem.sensor_radius,
|
||||||
|
initial_positions=positions,
|
||||||
|
partition_mode=problem.partition_mode,
|
||||||
|
planner=problem.planner,
|
||||||
|
strip_direction=direction,
|
||||||
|
lloyd_iterations=problem.lloyd_iterations,
|
||||||
|
sweep_width_ratio=problem.sweep_width_ratio,
|
||||||
|
sweep_axis=problem.sweep_axis,
|
||||||
|
waypoint_spacing_factor=problem.waypoint_spacing_factor,
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def evaluate_deployment(
|
||||||
|
problem: CoverageProblem,
|
||||||
|
positions: np.ndarray | list[float],
|
||||||
|
sim_duration: float | None = None,
|
||||||
|
show_progress: bool = False,
|
||||||
|
fast_eval: bool = False,
|
||||||
|
) -> EvaluationResult:
|
||||||
|
if not isinstance(positions, np.ndarray) or positions.ndim != 2:
|
||||||
|
positions = problem.unpack_positions(np.asarray(positions, dtype=float))
|
||||||
|
|
||||||
|
if problem.partition_mode == "uniform" and problem.strip_direction == "auto":
|
||||||
|
candidates = [
|
||||||
|
_evaluate_single(
|
||||||
|
problem, positions, sim_duration, strip_direction=d,
|
||||||
|
show_progress=show_progress, fast_eval=fast_eval,
|
||||||
|
)
|
||||||
|
for d in ("vertical", "horizontal")
|
||||||
|
]
|
||||||
|
return min(candidates, key=lambda r: r.objective_value)
|
||||||
|
|
||||||
|
return _evaluate_single(
|
||||||
|
problem, positions, sim_duration, strip_direction=None,
|
||||||
|
show_progress=show_progress, fast_eval=fast_eval,
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def _evaluate_single(
|
||||||
|
problem: CoverageProblem,
|
||||||
|
positions: np.ndarray,
|
||||||
|
sim_duration: float | None,
|
||||||
|
strip_direction: str | None,
|
||||||
|
show_progress: bool = False,
|
||||||
|
fast_eval: bool = False,
|
||||||
|
) -> EvaluationResult:
|
||||||
|
paths, partition = plan_from_deployment(problem, positions, strip_direction=strip_direction)
|
||||||
|
outside_penalty = depot_outside_partition_penalty(positions, partition)
|
||||||
|
op_periods = [
|
||||||
|
p.operational_cycle_period(problem.speed, problem.depot_service_time) for p in paths
|
||||||
|
]
|
||||||
|
max_patrol_period = max(op_periods) if op_periods else float("inf")
|
||||||
|
|
||||||
|
if sim_duration is None:
|
||||||
|
sim_duration = max(max_patrol_period * 3.0, 180.0)
|
||||||
|
if fast_eval:
|
||||||
|
sim_duration = min(sim_duration, problem.fast_eval_max_duration)
|
||||||
|
|
||||||
|
grid_density = (
|
||||||
|
min(problem.grid_density, problem.fast_eval_grid_density_cap)
|
||||||
|
if fast_eval
|
||||||
|
else problem.grid_density
|
||||||
|
)
|
||||||
|
|
||||||
|
sim = PatrolSimulator(
|
||||||
|
problem.region,
|
||||||
|
paths,
|
||||||
|
problem.speed,
|
||||||
|
problem.sensor_radius,
|
||||||
|
depot_service_time=problem.depot_service_time,
|
||||||
|
dt=problem.sim_dt,
|
||||||
|
grid_density=grid_density,
|
||||||
|
)
|
||||||
|
metrics = sim.run(sim_duration, show_progress=show_progress)
|
||||||
|
|
||||||
|
objective_value = compute_composite_objective(
|
||||||
|
problem,
|
||||||
|
metrics=metrics,
|
||||||
|
max_patrol_period=max_patrol_period,
|
||||||
|
outside_penalty=outside_penalty,
|
||||||
|
)
|
||||||
|
|
||||||
|
solution = DeploymentSolution(
|
||||||
|
initial_positions=positions,
|
||||||
|
paths=paths,
|
||||||
|
partition=partition,
|
||||||
|
speed=problem.speed,
|
||||||
|
metrics=metrics,
|
||||||
|
max_patrol_period=max_patrol_period,
|
||||||
|
objective_value=objective_value,
|
||||||
|
_depot_service_time=problem.depot_service_time,
|
||||||
|
)
|
||||||
|
|
||||||
|
return EvaluationResult(
|
||||||
|
solution=solution,
|
||||||
|
objective_value=objective_value,
|
||||||
|
max_revisit_time=metrics.max_revisit_time,
|
||||||
|
mean_revisit_time=metrics.mean_revisit_time,
|
||||||
|
max_patrol_period=max_patrol_period,
|
||||||
|
coverage_ratio=metrics.coverage_ratio,
|
||||||
|
overlap_ratio=metrics.overlap_ratio,
|
||||||
|
load_balance=sim.load_balance_ratio(),
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def compute_composite_objective(
|
||||||
|
problem: CoverageProblem,
|
||||||
|
metrics: RevisitMetrics,
|
||||||
|
max_patrol_period: float,
|
||||||
|
outside_penalty: float = 0.0,
|
||||||
|
) -> float:
|
||||||
|
"""
|
||||||
|
Composite objective minimized by the optimizer:
|
||||||
|
|
||||||
|
w_t * T_max + w_cov * (1 - coverage) + w_ovl * overlap + penalties
|
||||||
|
|
||||||
|
coverage: fraction of grid cells ever visited during simulation (maximize).
|
||||||
|
overlap: time-averaged fraction of region with 2+ simultaneous patrol coverage (minimize).
|
||||||
|
"""
|
||||||
|
primary = (
|
||||||
|
max_patrol_period
|
||||||
|
if problem.objective == CoverageObjective.MAX_PATROL_PERIOD
|
||||||
|
else metrics.max_revisit_time
|
||||||
|
)
|
||||||
|
coverage_penalty = (1.0 - metrics.coverage_ratio) * problem.weight_coverage
|
||||||
|
overlap_penalty = metrics.overlap_ratio * problem.weight_overlap
|
||||||
|
return (
|
||||||
|
problem.weight_t_max * primary
|
||||||
|
+ coverage_penalty
|
||||||
|
+ overlap_penalty
|
||||||
|
+ outside_penalty
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def depot_outside_partition_penalty(positions: np.ndarray, partition) -> float:
|
||||||
|
"""Penalty when a depot lies outside its assigned patrol polygon."""
|
||||||
|
from shapely.geometry import Point
|
||||||
|
|
||||||
|
penalty = 0.0
|
||||||
|
for cell in partition.cells:
|
||||||
|
depot = positions[cell.uav_id]
|
||||||
|
pt = Point(float(depot[0]), float(depot[1]))
|
||||||
|
if not cell.polygon.contains(pt) and cell.polygon.boundary.distance(pt) > 1e-6:
|
||||||
|
penalty += float(cell.polygon.distance(pt)) * 50.0
|
||||||
|
return penalty
|
||||||
|
|
||||||
|
|
||||||
|
def random_deployment(problem: CoverageProblem, seed: int = 0) -> np.ndarray:
|
||||||
|
return parse_initial_positions(problem.region, None, problem.n_uavs, seed=seed)
|
||||||
@@ -0,0 +1,36 @@
|
|||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import sys
|
||||||
|
from contextlib import contextmanager
|
||||||
|
from typing import Iterator
|
||||||
|
|
||||||
|
try:
|
||||||
|
from tqdm import tqdm
|
||||||
|
except ImportError: # pragma: no cover
|
||||||
|
tqdm = None
|
||||||
|
|
||||||
|
|
||||||
|
@contextmanager
|
||||||
|
def progress_bar(
|
||||||
|
total: int | None,
|
||||||
|
desc: str,
|
||||||
|
unit: str = "it",
|
||||||
|
enabled: bool = True,
|
||||||
|
leave: bool = True,
|
||||||
|
) -> Iterator:
|
||||||
|
if not enabled or tqdm is None or total == 0:
|
||||||
|
yield None
|
||||||
|
return
|
||||||
|
bar = tqdm(
|
||||||
|
total=total,
|
||||||
|
desc=desc,
|
||||||
|
unit=unit,
|
||||||
|
leave=leave,
|
||||||
|
file=sys.stderr,
|
||||||
|
mininterval=0.3,
|
||||||
|
dynamic_ncols=True,
|
||||||
|
)
|
||||||
|
try:
|
||||||
|
yield bar
|
||||||
|
finally:
|
||||||
|
bar.close()
|
||||||
@@ -0,0 +1,4 @@
|
|||||||
|
from .engine import PatrolSimulator, UavState
|
||||||
|
from .visualizer import PatrolVisualizer, compare_planners
|
||||||
|
|
||||||
|
__all__ = ["PatrolSimulator", "UavState", "PatrolVisualizer", "compare_planners"]
|
||||||
@@ -0,0 +1,117 @@
|
|||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
from dataclasses import dataclass, field
|
||||||
|
|
||||||
|
import numpy as np
|
||||||
|
|
||||||
|
from uavsearch.geometry import RectRegion
|
||||||
|
from uavsearch.metrics import CoverageGrid, RevisitMetrics, compute_revisit_metrics
|
||||||
|
from uavsearch.planner import PatrolPath
|
||||||
|
|
||||||
|
|
||||||
|
@dataclass
|
||||||
|
class UavState:
|
||||||
|
uav_id: int
|
||||||
|
path: PatrolPath
|
||||||
|
speed: float
|
||||||
|
depot_service_time: float = 0.0
|
||||||
|
time_in_cycle: float = 0.0
|
||||||
|
|
||||||
|
@property
|
||||||
|
def operational_cycle_period(self) -> float:
|
||||||
|
return self.path.operational_cycle_period(self.speed, self.depot_service_time)
|
||||||
|
|
||||||
|
@property
|
||||||
|
def position(self) -> tuple[float, float]:
|
||||||
|
return self.path.position_at_time(self.time_in_cycle, self.speed, self.depot_service_time)
|
||||||
|
|
||||||
|
@property
|
||||||
|
def phase(self) -> str:
|
||||||
|
return self.path.phase_at_time(self.time_in_cycle, self.speed, self.depot_service_time)
|
||||||
|
|
||||||
|
@property
|
||||||
|
def is_patrolling(self) -> bool:
|
||||||
|
return self.phase == "patrol"
|
||||||
|
|
||||||
|
def advance(self, dt: float) -> tuple[float, float]:
|
||||||
|
self.time_in_cycle += dt
|
||||||
|
period = max(self.operational_cycle_period, 1e-9)
|
||||||
|
self.time_in_cycle %= period
|
||||||
|
return self.position
|
||||||
|
|
||||||
|
|
||||||
|
@dataclass
|
||||||
|
class PatrolSimulator:
|
||||||
|
region: RectRegion
|
||||||
|
paths: list[PatrolPath]
|
||||||
|
speed: float
|
||||||
|
sensor_radius: float
|
||||||
|
depot_service_time: float = 60.0
|
||||||
|
dt: float = 0.5
|
||||||
|
cell_size: float | None = None
|
||||||
|
grid_density: float = 4.0
|
||||||
|
time: float = 0.0
|
||||||
|
uavs: list[UavState] = field(init=False)
|
||||||
|
grid: CoverageGrid = field(init=False)
|
||||||
|
_overlap_cell_steps: int = field(init=False, default=0)
|
||||||
|
_sim_steps: int = field(init=False, default=0)
|
||||||
|
|
||||||
|
def __post_init__(self) -> None:
|
||||||
|
self.uavs = [
|
||||||
|
UavState(
|
||||||
|
uav_id=p.uav_id,
|
||||||
|
path=p,
|
||||||
|
speed=self.speed,
|
||||||
|
depot_service_time=self.depot_service_time,
|
||||||
|
)
|
||||||
|
for p in self.paths
|
||||||
|
]
|
||||||
|
cs = self.cell_size if self.cell_size is not None else self.sensor_radius / self.grid_density
|
||||||
|
self.grid = CoverageGrid(self.region, cell_size=cs)
|
||||||
|
|
||||||
|
def step(self) -> None:
|
||||||
|
patrol_positions: list[tuple[float, float, RectRegion]] = []
|
||||||
|
for uav in self.uavs:
|
||||||
|
x, y = uav.advance(self.dt)
|
||||||
|
if uav.is_patrolling:
|
||||||
|
patrol_positions.append((x, y, uav.path.region))
|
||||||
|
self.grid.mark_visit(
|
||||||
|
x, y, self.time, self.sensor_radius, clip_region=uav.path.region
|
||||||
|
)
|
||||||
|
|
||||||
|
if patrol_positions:
|
||||||
|
counts = self.grid.patrol_coverage_counts(patrol_positions, self.sensor_radius)
|
||||||
|
self._overlap_cell_steps += int(np.sum(counts >= 2))
|
||||||
|
|
||||||
|
self._sim_steps += 1
|
||||||
|
self.time += self.dt
|
||||||
|
|
||||||
|
def run(self, duration: float, show_progress: bool = False) -> RevisitMetrics:
|
||||||
|
from uavsearch.progress import progress_bar
|
||||||
|
|
||||||
|
self._overlap_cell_steps = 0
|
||||||
|
self._sim_steps = 0
|
||||||
|
steps = int(np.ceil(duration / self.dt))
|
||||||
|
with progress_bar(steps, desc="仿真", unit="step", enabled=show_progress, leave=False) as bar:
|
||||||
|
for _ in range(steps):
|
||||||
|
self.step()
|
||||||
|
if bar is not None:
|
||||||
|
bar.update(1)
|
||||||
|
return compute_revisit_metrics(
|
||||||
|
self.grid, self.time, overlap_cell_steps=self._overlap_cell_steps, sim_steps=self._sim_steps
|
||||||
|
)
|
||||||
|
|
||||||
|
def operational_cycle_periods(self) -> list[float]:
|
||||||
|
return [u.operational_cycle_period for u in self.uavs]
|
||||||
|
|
||||||
|
def path_lengths(self) -> list[float]:
|
||||||
|
return [u.path.loop_length for u in self.uavs]
|
||||||
|
|
||||||
|
def load_balance_ratio(self) -> float:
|
||||||
|
periods = self.operational_cycle_periods()
|
||||||
|
if not periods or min(periods) <= 1e-9:
|
||||||
|
return 1.0
|
||||||
|
return max(periods) / min(periods)
|
||||||
|
|
||||||
|
def depot_positions(self) -> list[tuple[float, float]]:
|
||||||
|
return [p.depot_position for p in self.paths]
|
||||||
@@ -0,0 +1,240 @@
|
|||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
from dataclasses import dataclass
|
||||||
|
|
||||||
|
import matplotlib.pyplot as plt
|
||||||
|
import numpy as np
|
||||||
|
from matplotlib.patches import Polygon, Rectangle
|
||||||
|
from shapely.geometry import mapping
|
||||||
|
|
||||||
|
from uavsearch.geometry import RectRegion
|
||||||
|
from uavsearch.metrics import RevisitMetrics
|
||||||
|
from uavsearch.partition import PartitionResult
|
||||||
|
from uavsearch.planner import PatrolPath
|
||||||
|
from uavsearch.sim.engine import PatrolSimulator
|
||||||
|
|
||||||
|
|
||||||
|
@dataclass
|
||||||
|
class PatrolVisualizer:
|
||||||
|
region: RectRegion
|
||||||
|
|
||||||
|
def plot_partition(
|
||||||
|
self,
|
||||||
|
partition: PartitionResult,
|
||||||
|
ax: plt.Axes | None = None,
|
||||||
|
title: str = "Equal-Area Partition",
|
||||||
|
) -> plt.Axes:
|
||||||
|
if ax is None:
|
||||||
|
_, ax = plt.subplots(figsize=(10, 8))
|
||||||
|
|
||||||
|
self._draw_region(ax)
|
||||||
|
colors = plt.cm.tab10(np.linspace(0, 1, max(partition.n_uavs, 1)))
|
||||||
|
|
||||||
|
for cell, color in zip(partition.cells, colors):
|
||||||
|
coords = np.array(mapping(cell.polygon)["coordinates"][0])
|
||||||
|
patch = Polygon(
|
||||||
|
coords,
|
||||||
|
closed=True,
|
||||||
|
facecolor=color,
|
||||||
|
edgecolor="black",
|
||||||
|
alpha=0.25,
|
||||||
|
linewidth=1.5,
|
||||||
|
)
|
||||||
|
ax.add_patch(patch)
|
||||||
|
ix, iy = cell.initial_position
|
||||||
|
ax.scatter(ix, iy, color=color, s=120, marker="^", edgecolors="black", zorder=7, label=f"UAV {cell.uav_id}")
|
||||||
|
ax.annotate(
|
||||||
|
f"P{cell.partition_id} U{cell.uav_id}",
|
||||||
|
(ix, iy),
|
||||||
|
textcoords="offset points",
|
||||||
|
xytext=(6, 6),
|
||||||
|
fontsize=8,
|
||||||
|
)
|
||||||
|
|
||||||
|
ax.set_aspect("equal")
|
||||||
|
ax.set_title(title)
|
||||||
|
ax.set_xlabel("X (m)")
|
||||||
|
ax.set_ylabel("Y (m)")
|
||||||
|
ax.legend(loc="upper right", fontsize=8)
|
||||||
|
ax.grid(True, alpha=0.3)
|
||||||
|
return ax
|
||||||
|
|
||||||
|
def plot_paths(
|
||||||
|
self,
|
||||||
|
paths: list[PatrolPath],
|
||||||
|
ax: plt.Axes | None = None,
|
||||||
|
title: str = "Patrol Paths",
|
||||||
|
partition: PartitionResult | None = None,
|
||||||
|
) -> plt.Axes:
|
||||||
|
if ax is None:
|
||||||
|
_, ax = plt.subplots(figsize=(10, 8))
|
||||||
|
|
||||||
|
if partition is not None:
|
||||||
|
self.plot_partition(partition, ax=ax, title=title)
|
||||||
|
else:
|
||||||
|
self._draw_region(ax)
|
||||||
|
|
||||||
|
colors = plt.cm.tab10(np.linspace(0, 1, max(len(paths), 1)))
|
||||||
|
|
||||||
|
for path, color in zip(paths, colors):
|
||||||
|
wp = path.waypoints
|
||||||
|
ax.plot(wp[:, 0], wp[:, 1], color=color, linewidth=1.2, alpha=0.85, label=f"UAV {path.uav_id} patrol")
|
||||||
|
ix, iy = path.initial_position
|
||||||
|
ax.scatter(ix, iy, color=color, s=120, marker="s", edgecolors="black", zorder=8, label=f"UAV {path.uav_id} depot")
|
||||||
|
entry = wp[path.entry_index]
|
||||||
|
ax.scatter(entry[0], entry[1], color=color, s=50, marker="o", zorder=6)
|
||||||
|
ax.plot([ix, entry[0]], [iy, entry[1]], color=color, linestyle="--", linewidth=1.0, alpha=0.7)
|
||||||
|
ax.plot([entry[0], ix], [entry[1], iy], color=color, linestyle=":", linewidth=1.0, alpha=0.7)
|
||||||
|
|
||||||
|
ax.set_aspect("equal")
|
||||||
|
if partition is None:
|
||||||
|
ax.set_title(title)
|
||||||
|
ax.set_xlabel("X (m)")
|
||||||
|
ax.set_ylabel("Y (m)")
|
||||||
|
ax.legend(loc="upper right", fontsize=8)
|
||||||
|
ax.grid(True, alpha=0.3)
|
||||||
|
return ax
|
||||||
|
|
||||||
|
def plot_heatmap(
|
||||||
|
self,
|
||||||
|
data: np.ndarray,
|
||||||
|
ax: plt.Axes | None = None,
|
||||||
|
title: str = "Coverage Heatmap",
|
||||||
|
cmap: str = "YlOrRd",
|
||||||
|
label: str = "Max idle time (s)",
|
||||||
|
) -> plt.Axes:
|
||||||
|
if ax is None:
|
||||||
|
_, ax = plt.subplots(figsize=(10, 8))
|
||||||
|
|
||||||
|
extent = [self.region.xmin, self.region.xmax, self.region.ymin, self.region.ymax]
|
||||||
|
im = ax.imshow(data, origin="lower", extent=extent, aspect="equal", cmap=cmap)
|
||||||
|
self._draw_region(ax, fill=False)
|
||||||
|
ax.set_title(title)
|
||||||
|
ax.set_xlabel("X (m)")
|
||||||
|
ax.set_ylabel("Y (m)")
|
||||||
|
plt.colorbar(im, ax=ax, label=label)
|
||||||
|
return ax
|
||||||
|
|
||||||
|
def plot_simulation_snapshot(
|
||||||
|
self,
|
||||||
|
simulator: PatrolSimulator,
|
||||||
|
paths: list[PatrolPath],
|
||||||
|
metrics: RevisitMetrics,
|
||||||
|
title: str = "Patrol Simulation",
|
||||||
|
partition: PartitionResult | None = None,
|
||||||
|
) -> plt.Figure:
|
||||||
|
fig, axes = plt.subplots(1, 3, figsize=(22, 7))
|
||||||
|
|
||||||
|
self.plot_partition(partition, ax=axes[0], title=f"{title} — Partition") if partition else self._draw_region(axes[0])
|
||||||
|
if partition is None:
|
||||||
|
axes[0].set_title(f"{title} — Region")
|
||||||
|
axes[0].set_aspect("equal")
|
||||||
|
|
||||||
|
self.plot_paths(paths, ax=axes[1], title=f"{title} — Paths", partition=partition)
|
||||||
|
colors = plt.cm.tab10(np.linspace(0, 1, len(simulator.uavs)))
|
||||||
|
for uav, color in zip(simulator.uavs, colors):
|
||||||
|
x, y = uav.position
|
||||||
|
axes[1].scatter(x, y, color=color, s=80, edgecolors="black", zorder=9)
|
||||||
|
|
||||||
|
idle_map = simulator.grid.idle_map()
|
||||||
|
self.plot_heatmap(
|
||||||
|
idle_map,
|
||||||
|
ax=axes[2],
|
||||||
|
title=f"{title} — Idle Time\n{metrics.summary()}",
|
||||||
|
)
|
||||||
|
|
||||||
|
fig.tight_layout()
|
||||||
|
return fig
|
||||||
|
|
||||||
|
def animate_patrol(
|
||||||
|
self,
|
||||||
|
simulator: PatrolSimulator,
|
||||||
|
paths: list[PatrolPath],
|
||||||
|
duration: float,
|
||||||
|
interval_ms: int = 50,
|
||||||
|
title: str = "Patrol Animation",
|
||||||
|
partition: PartitionResult | None = None,
|
||||||
|
):
|
||||||
|
from matplotlib.animation import FuncAnimation
|
||||||
|
|
||||||
|
fig, ax = plt.subplots(figsize=(10, 8))
|
||||||
|
self.plot_paths(paths, ax=ax, title=title, partition=partition)
|
||||||
|
colors = plt.cm.tab10(np.linspace(0, 1, len(simulator.uavs)))
|
||||||
|
scatters = [
|
||||||
|
ax.scatter([], [], color=c, s=80, edgecolors="black", zorder=9)
|
||||||
|
for c in colors
|
||||||
|
]
|
||||||
|
|
||||||
|
trail_lines = [ax.plot([], [], color=c, alpha=0.4, linewidth=1)[0] for c in colors]
|
||||||
|
trails: list[list[tuple[float, float]]] = [[] for _ in simulator.uavs]
|
||||||
|
steps = int(np.ceil(duration / simulator.dt))
|
||||||
|
|
||||||
|
def update(frame: int):
|
||||||
|
if frame > 0:
|
||||||
|
simulator.step()
|
||||||
|
for i, uav in enumerate(simulator.uavs):
|
||||||
|
pos = uav.position
|
||||||
|
scatters[i].set_offsets([pos])
|
||||||
|
trails[i].append(pos)
|
||||||
|
if len(trails[i]) > 200:
|
||||||
|
trails[i] = trails[i][-200:]
|
||||||
|
tx, ty = zip(*trails[i]) if trails[i] else ([], [])
|
||||||
|
trail_lines[i].set_data(tx, ty)
|
||||||
|
ax.set_title(f"{title} — t={simulator.time:.1f}s")
|
||||||
|
return [*scatters, *trail_lines]
|
||||||
|
|
||||||
|
return FuncAnimation(fig, update, frames=steps + 1, interval=interval_ms, blit=True)
|
||||||
|
|
||||||
|
def _draw_region(self, ax: plt.Axes, fill: bool = True) -> None:
|
||||||
|
rect = Rectangle(
|
||||||
|
(self.region.xmin, self.region.ymin),
|
||||||
|
self.region.width,
|
||||||
|
self.region.height,
|
||||||
|
linewidth=2,
|
||||||
|
edgecolor="black",
|
||||||
|
facecolor="#e8f4fc" if fill else "none",
|
||||||
|
alpha=0.5 if fill else 1.0,
|
||||||
|
)
|
||||||
|
ax.add_patch(rect)
|
||||||
|
|
||||||
|
|
||||||
|
def compare_planners(
|
||||||
|
region: RectRegion,
|
||||||
|
strip_paths: list[PatrolPath],
|
||||||
|
mtsp_paths: list[PatrolPath],
|
||||||
|
speed: float,
|
||||||
|
sensor_radius: float,
|
||||||
|
duration: float,
|
||||||
|
strip_partition: PartitionResult | None = None,
|
||||||
|
mtsp_partition: PartitionResult | None = None,
|
||||||
|
dt: float = 0.5,
|
||||||
|
) -> plt.Figure:
|
||||||
|
sim_strip = PatrolSimulator(region, strip_paths, speed, sensor_radius, dt=dt)
|
||||||
|
sim_mtsp = PatrolSimulator(region, mtsp_paths, speed, sensor_radius, dt=dt)
|
||||||
|
metrics_strip = sim_strip.run(duration)
|
||||||
|
metrics_mtsp = sim_mtsp.run(duration)
|
||||||
|
|
||||||
|
fig, axes = plt.subplots(2, 2, figsize=(16, 14))
|
||||||
|
viz = PatrolVisualizer(region)
|
||||||
|
|
||||||
|
viz.plot_paths(strip_paths, ax=axes[0, 0], title="Uniform + Boustrophedon", partition=strip_partition)
|
||||||
|
viz.plot_heatmap(
|
||||||
|
sim_strip.grid.idle_map(),
|
||||||
|
ax=axes[0, 1],
|
||||||
|
title=f"Boustrophedon idle time\n{metrics_strip.summary()}",
|
||||||
|
)
|
||||||
|
viz.plot_paths(mtsp_paths, ax=axes[1, 0], title="Uniform + mTSP", partition=mtsp_partition)
|
||||||
|
viz.plot_heatmap(
|
||||||
|
sim_mtsp.grid.idle_map(),
|
||||||
|
ax=axes[1, 1],
|
||||||
|
title=f"mTSP idle time\n{metrics_mtsp.summary()}",
|
||||||
|
)
|
||||||
|
|
||||||
|
fig.suptitle(
|
||||||
|
f"Planner Comparison ({duration:.0f}s sim) — "
|
||||||
|
f"Boustrophedon T_max/T_mean={metrics_strip.max_revisit_time / max(metrics_strip.mean_revisit_time, 1e-9):.2f}, "
|
||||||
|
f"mTSP T_max/T_mean={metrics_mtsp.max_revisit_time / max(metrics_mtsp.mean_revisit_time, 1e-9):.2f}",
|
||||||
|
fontsize=12,
|
||||||
|
)
|
||||||
|
fig.tight_layout()
|
||||||
|
return fig
|
||||||
@@ -0,0 +1,3 @@
|
|||||||
|
from .dashboard import CoverageDashboard, plot_coverage_dashboard
|
||||||
|
|
||||||
|
__all__ = ["CoverageDashboard", "plot_coverage_dashboard"]
|
||||||
@@ -0,0 +1,258 @@
|
|||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
from dataclasses import dataclass
|
||||||
|
|
||||||
|
import matplotlib.pyplot as plt
|
||||||
|
import numpy as np
|
||||||
|
from matplotlib.gridspec import GridSpec
|
||||||
|
from matplotlib.patches import FancyBboxPatch
|
||||||
|
|
||||||
|
from uavsearch.geometry import RectRegion
|
||||||
|
from uavsearch.optimizer import OptimizationResult
|
||||||
|
from uavsearch.problem import CoverageProblem, EvaluationResult
|
||||||
|
from uavsearch.sim import PatrolSimulator, PatrolVisualizer
|
||||||
|
|
||||||
|
|
||||||
|
@dataclass
|
||||||
|
class CoverageDashboard:
|
||||||
|
"""Visualization dashboard for multi-UAV coverage-period minimization."""
|
||||||
|
|
||||||
|
problem: CoverageProblem
|
||||||
|
|
||||||
|
@property
|
||||||
|
def region(self) -> RectRegion:
|
||||||
|
return self.problem.region
|
||||||
|
|
||||||
|
def plot_convergence(
|
||||||
|
self,
|
||||||
|
history: list[EvaluationResult],
|
||||||
|
ax: plt.Axes,
|
||||||
|
title: str = "Optimization convergence",
|
||||||
|
) -> plt.Axes:
|
||||||
|
if not history:
|
||||||
|
ax.text(0.5, 0.5, "No optimization history", ha="center", va="center", transform=ax.transAxes)
|
||||||
|
return ax
|
||||||
|
|
||||||
|
evals = np.arange(1, len(history) + 1)
|
||||||
|
t_max = [h.objective_value for h in history]
|
||||||
|
best_so_far = np.minimum.accumulate(t_max)
|
||||||
|
|
||||||
|
ax.plot(evals, t_max, "o", markersize=3, alpha=0.35, color="#4C72B0", label="Each evaluation")
|
||||||
|
ax.plot(evals, best_so_far, "-", linewidth=2.2, color="#C44E52", label="Best so far")
|
||||||
|
ax.set_xlabel("Evaluation #")
|
||||||
|
ax.set_ylabel("Composite objective")
|
||||||
|
ax.set_title(title)
|
||||||
|
ax.legend(loc="upper right", fontsize=8)
|
||||||
|
ax.grid(True, alpha=0.3)
|
||||||
|
ymin = min(best_so_far) * 0.95
|
||||||
|
ymax = max(t_max) * 1.05
|
||||||
|
if ymax > ymin:
|
||||||
|
ax.set_ylim(ymin, ymax)
|
||||||
|
return ax
|
||||||
|
|
||||||
|
def plot_metrics_bars(
|
||||||
|
self,
|
||||||
|
baseline: EvaluationResult,
|
||||||
|
optimized: EvaluationResult,
|
||||||
|
ax: plt.Axes,
|
||||||
|
) -> plt.Axes:
|
||||||
|
labels = ["T_max", "T_mean", "Coverage %", "Overlap %"]
|
||||||
|
b_vals = [
|
||||||
|
baseline.max_revisit_time,
|
||||||
|
baseline.mean_revisit_time,
|
||||||
|
baseline.coverage_ratio * 100.0,
|
||||||
|
baseline.overlap_ratio * 100.0,
|
||||||
|
]
|
||||||
|
o_vals = [
|
||||||
|
optimized.max_revisit_time,
|
||||||
|
optimized.mean_revisit_time,
|
||||||
|
optimized.coverage_ratio * 100.0,
|
||||||
|
optimized.overlap_ratio * 100.0,
|
||||||
|
]
|
||||||
|
x = np.arange(len(labels))
|
||||||
|
w = 0.35
|
||||||
|
|
||||||
|
ax.bar(x - w / 2, b_vals, w, label="Baseline", color="#4C72B0", alpha=0.85)
|
||||||
|
ax.bar(x + w / 2, o_vals, w, label="Optimized", color="#55A868", alpha=0.85)
|
||||||
|
ax.set_xticks(x)
|
||||||
|
ax.set_xticklabels(labels)
|
||||||
|
ax.set_ylabel("Value")
|
||||||
|
ax.set_title("Coverage metrics comparison")
|
||||||
|
ax.legend(fontsize=8)
|
||||||
|
ax.grid(True, axis="y", alpha=0.3)
|
||||||
|
|
||||||
|
for i, (bv, ov) in enumerate(zip(b_vals, o_vals)):
|
||||||
|
fmt = f"{bv:.0f}" if i < 2 else f"{bv:.1f}"
|
||||||
|
fmt_o = f"{ov:.0f}" if i < 2 else f"{ov:.1f}"
|
||||||
|
ax.text(i - w / 2, bv, fmt, ha="center", va="bottom", fontsize=7)
|
||||||
|
ax.text(i + w / 2, ov, fmt_o, ha="center", va="bottom", fontsize=7)
|
||||||
|
return ax
|
||||||
|
|
||||||
|
def plot_patrol_periods(
|
||||||
|
self,
|
||||||
|
result: EvaluationResult,
|
||||||
|
ax: plt.Axes,
|
||||||
|
title: str,
|
||||||
|
) -> plt.Axes:
|
||||||
|
periods = result.solution.patrol_periods
|
||||||
|
ids = [p.uav_id for p in result.solution.paths]
|
||||||
|
colors = plt.cm.tab10(np.linspace(0, 1, max(len(ids), 1)))
|
||||||
|
ax.bar(ids, periods, color=colors, edgecolor="black", linewidth=0.6)
|
||||||
|
ax.axhline(result.max_patrol_period, color="#C44E52", linestyle="--", linewidth=1.2, label="P_max")
|
||||||
|
ax.set_xlabel("UAV id")
|
||||||
|
ax.set_ylabel("Patrol period (s)")
|
||||||
|
ax.set_title(title)
|
||||||
|
ax.legend(fontsize=8)
|
||||||
|
ax.grid(True, axis="y", alpha=0.3)
|
||||||
|
return ax
|
||||||
|
|
||||||
|
def plot_deployment(
|
||||||
|
self,
|
||||||
|
result: EvaluationResult,
|
||||||
|
ax: plt.Axes,
|
||||||
|
title: str,
|
||||||
|
) -> plt.Axes:
|
||||||
|
patrol = PatrolVisualizer(self.region)
|
||||||
|
patrol.plot_partition(result.solution.partition, ax=ax, title=title)
|
||||||
|
for cell in result.solution.partition.cells:
|
||||||
|
cx, cy = cell.bounds.centroid
|
||||||
|
ax.scatter(cx, cy, marker="x", color="black", s=40, zorder=5)
|
||||||
|
return ax
|
||||||
|
|
||||||
|
def plot_problem_info(self, fig: plt.Figure, gs: GridSpec) -> None:
|
||||||
|
ax = fig.add_subplot(gs[0, :])
|
||||||
|
ax.axis("off")
|
||||||
|
p = self.problem
|
||||||
|
r = p.region
|
||||||
|
text = (
|
||||||
|
f"Problem: min T_max | Region {r.width:.0f} x {r.height:.0f} m | "
|
||||||
|
f"N={p.n_uavs} UAVs | r={p.sensor_radius:.0f} m | v={p.speed:.0f} m/s\n"
|
||||||
|
f"Partition: {p.partition_mode} | Planner: {p.planner} | "
|
||||||
|
f"Objective: minimize T_max = max_x T(x)\n"
|
||||||
|
f"Depot cycle: outbound -> patrol loop -> inbound -> service ({p.depot_service_time:.0f}s)\n"
|
||||||
|
f"Recommended: workload/lloyd partition + mTSP | "
|
||||||
|
f"Decision variables: depot positions (2N)"
|
||||||
|
)
|
||||||
|
box = FancyBboxPatch(
|
||||||
|
(0.02, 0.15), 0.96, 0.75,
|
||||||
|
boxstyle="round,pad=0.02",
|
||||||
|
facecolor="#f0f4f8",
|
||||||
|
edgecolor="#888888",
|
||||||
|
transform=ax.transAxes,
|
||||||
|
)
|
||||||
|
ax.add_patch(box)
|
||||||
|
ax.text(0.5, 0.52, text, ha="center", va="center", fontsize=10, transform=ax.transAxes, family="monospace")
|
||||||
|
|
||||||
|
def build(
|
||||||
|
self,
|
||||||
|
baseline: EvaluationResult,
|
||||||
|
optimized: EvaluationResult,
|
||||||
|
opt_result: OptimizationResult | None = None,
|
||||||
|
sim_duration_scale: float = 2.5,
|
||||||
|
show_progress: bool = False,
|
||||||
|
) -> plt.Figure:
|
||||||
|
"""Build the full coverage-problem dashboard figure."""
|
||||||
|
fig = plt.figure(figsize=(24, 20))
|
||||||
|
gs = GridSpec(4, 3, figure=fig, height_ratios=[0.45, 1.2, 1.2, 1.0], hspace=0.38, wspace=0.28)
|
||||||
|
|
||||||
|
self.plot_problem_info(fig, gs)
|
||||||
|
self.plot_convergence(
|
||||||
|
opt_result.history if opt_result else [],
|
||||||
|
fig.add_subplot(gs[1, 0]),
|
||||||
|
title="T_max during optimization",
|
||||||
|
)
|
||||||
|
self.plot_metrics_bars(baseline, optimized, fig.add_subplot(gs[1, 1]))
|
||||||
|
self.plot_patrol_periods(baseline, fig.add_subplot(gs[1, 2]), title="Baseline patrol periods")
|
||||||
|
|
||||||
|
patrol_viz = PatrolVisualizer(self.region)
|
||||||
|
|
||||||
|
patrol_viz.plot_paths(
|
||||||
|
baseline.solution.paths,
|
||||||
|
ax=fig.add_subplot(gs[2, 0]),
|
||||||
|
title=f"Baseline\nT_max={baseline.max_revisit_time:.1f}s",
|
||||||
|
partition=baseline.solution.partition,
|
||||||
|
)
|
||||||
|
patrol_viz.plot_paths(
|
||||||
|
optimized.solution.paths,
|
||||||
|
ax=fig.add_subplot(gs[2, 1]),
|
||||||
|
title=f"Optimized\nT_max={optimized.max_revisit_time:.1f}s",
|
||||||
|
partition=optimized.solution.partition,
|
||||||
|
)
|
||||||
|
|
||||||
|
sim_opt = PatrolSimulator(
|
||||||
|
self.region,
|
||||||
|
optimized.solution.paths,
|
||||||
|
self.problem.speed,
|
||||||
|
self.problem.sensor_radius,
|
||||||
|
grid_density=self.problem.grid_density,
|
||||||
|
dt=self.problem.sim_dt,
|
||||||
|
)
|
||||||
|
sim_opt.run(optimized.max_patrol_period * sim_duration_scale, show_progress=show_progress)
|
||||||
|
patrol_viz.plot_heatmap(
|
||||||
|
sim_opt.grid.idle_map(),
|
||||||
|
ax=fig.add_subplot(gs[2, 2]),
|
||||||
|
title=f"Optimized idle-time field\nT_max={optimized.max_revisit_time:.1f}s",
|
||||||
|
)
|
||||||
|
|
||||||
|
self.plot_patrol_periods(
|
||||||
|
optimized, fig.add_subplot(gs[3, 0]), title="Optimized patrol periods"
|
||||||
|
)
|
||||||
|
|
||||||
|
sim_base = PatrolSimulator(
|
||||||
|
self.region,
|
||||||
|
baseline.solution.paths,
|
||||||
|
self.problem.speed,
|
||||||
|
self.problem.sensor_radius,
|
||||||
|
grid_density=self.problem.grid_density,
|
||||||
|
dt=self.problem.sim_dt,
|
||||||
|
)
|
||||||
|
sim_base.run(baseline.max_patrol_period * sim_duration_scale, show_progress=show_progress)
|
||||||
|
patrol_viz.plot_heatmap(
|
||||||
|
sim_base.grid.idle_map(),
|
||||||
|
ax=fig.add_subplot(gs[3, 1]),
|
||||||
|
title=f"Baseline idle-time field\nT_max={baseline.max_revisit_time:.1f}s",
|
||||||
|
)
|
||||||
|
|
||||||
|
ax_delta = fig.add_subplot(gs[3, 2])
|
||||||
|
delta = baseline.max_revisit_time - optimized.max_revisit_time
|
||||||
|
pct = delta / max(baseline.max_revisit_time, 1e-9) * 100
|
||||||
|
ax_delta.axis("off")
|
||||||
|
summary = (
|
||||||
|
f"RESULT SUMMARY\n\n"
|
||||||
|
f"T_max: {baseline.max_revisit_time:.2f}s -> {optimized.max_revisit_time:.2f}s\n"
|
||||||
|
f"Change: {delta:+.2f}s ({pct:+.1f}%)\n\n"
|
||||||
|
f"T_mean: {baseline.mean_revisit_time:.2f}s -> {optimized.mean_revisit_time:.2f}s\n"
|
||||||
|
f"P_max: {baseline.max_patrol_period:.2f}s -> {optimized.max_patrol_period:.2f}s\n\n"
|
||||||
|
f"Coverage: {baseline.coverage_ratio:.1%} -> {optimized.coverage_ratio:.1%}\n"
|
||||||
|
f"Evaluations: {opt_result.n_evaluations if opt_result else 0}\n"
|
||||||
|
f"Method: {opt_result.method if opt_result else 'evaluate only'}"
|
||||||
|
)
|
||||||
|
ax_delta.text(
|
||||||
|
0.5, 0.5, summary, ha="center", va="center", fontsize=11,
|
||||||
|
transform=ax_delta.transAxes, family="monospace",
|
||||||
|
bbox=dict(boxstyle="round", facecolor="#e8f5e9" if delta >= 0 else "#ffebee", alpha=0.9),
|
||||||
|
)
|
||||||
|
|
||||||
|
improve = baseline.objective_value - optimized.objective_value
|
||||||
|
fig.suptitle(
|
||||||
|
f"Multi-UAV Coverage Period Minimization | "
|
||||||
|
f"T_max {baseline.objective_value:.1f}s -> {optimized.objective_value:.1f}s "
|
||||||
|
f"({improve:+.1f}s)",
|
||||||
|
fontsize=14,
|
||||||
|
y=0.98,
|
||||||
|
)
|
||||||
|
return fig
|
||||||
|
|
||||||
|
|
||||||
|
def plot_coverage_dashboard(
|
||||||
|
problem: CoverageProblem,
|
||||||
|
baseline: EvaluationResult,
|
||||||
|
optimized: EvaluationResult | None = None,
|
||||||
|
opt_result: OptimizationResult | None = None,
|
||||||
|
show_progress: bool = False,
|
||||||
|
) -> plt.Figure:
|
||||||
|
"""Convenience wrapper: if optimized is None, baseline is shown as both."""
|
||||||
|
opt_eval = optimized if optimized is not None else baseline
|
||||||
|
return CoverageDashboard(problem).build(
|
||||||
|
baseline, opt_eval, opt_result=opt_result, show_progress=show_progress
|
||||||
|
)
|
||||||
@@ -0,0 +1,72 @@
|
|||||||
|
"""Tests for config.toml loading and MAPSO optimizer."""
|
||||||
|
|
||||||
|
from pathlib import Path
|
||||||
|
|
||||||
|
import numpy as np
|
||||||
|
|
||||||
|
from uavsearch.config import AppConfig, load_config
|
||||||
|
from uavsearch.geometry import RectRegion
|
||||||
|
from uavsearch.optimizer import optimize_deployment
|
||||||
|
from uavsearch.problem import CoverageProblem, evaluate_deployment, random_deployment
|
||||||
|
|
||||||
|
|
||||||
|
def test_load_config_defaults(tmp_path):
|
||||||
|
cfg_path = tmp_path / "config.toml"
|
||||||
|
cfg_path.write_text(
|
||||||
|
"""
|
||||||
|
[problem]
|
||||||
|
width = 500.0
|
||||||
|
uavs = 3
|
||||||
|
|
||||||
|
[optimizer]
|
||||||
|
method = "mapso"
|
||||||
|
maxiter = 3
|
||||||
|
popsize = 4
|
||||||
|
""",
|
||||||
|
encoding="utf-8",
|
||||||
|
)
|
||||||
|
cfg = load_config(cfg_path)
|
||||||
|
assert cfg.problem.width == 500.0
|
||||||
|
assert cfg.problem.uavs == 3
|
||||||
|
assert cfg.optimizer.method == "mapso"
|
||||||
|
assert cfg.optimizer.mapso.w == 0.729
|
||||||
|
|
||||||
|
|
||||||
|
def test_app_config_builds_problem():
|
||||||
|
cfg = AppConfig()
|
||||||
|
problem = cfg.problem.build_problem()
|
||||||
|
assert problem.n_uavs == 4
|
||||||
|
assert problem.region.width == 1000.0
|
||||||
|
|
||||||
|
|
||||||
|
def test_mapso_optimizer_runs():
|
||||||
|
region = RectRegion.from_size(600, 500)
|
||||||
|
problem = CoverageProblem(
|
||||||
|
region=region,
|
||||||
|
n_uavs=3,
|
||||||
|
sensor_radius=30,
|
||||||
|
speed=10,
|
||||||
|
partition_mode="voronoi",
|
||||||
|
grid_density=3,
|
||||||
|
)
|
||||||
|
baseline = evaluate_deployment(problem, random_deployment(problem, seed=0), sim_duration=150)
|
||||||
|
opt = optimize_deployment(
|
||||||
|
problem,
|
||||||
|
method="mapso",
|
||||||
|
seed=0,
|
||||||
|
maxiter=2,
|
||||||
|
popsize=4,
|
||||||
|
sim_duration=80,
|
||||||
|
initial_guess=random_deployment(problem, seed=0),
|
||||||
|
verbose=False,
|
||||||
|
)
|
||||||
|
assert opt.method == "mapso"
|
||||||
|
assert opt.n_evaluations > 0
|
||||||
|
assert np.isfinite(opt.best.objective_value)
|
||||||
|
assert opt.best.objective_value <= baseline.objective_value * 1.1
|
||||||
|
|
||||||
|
|
||||||
|
def test_project_config_toml_exists():
|
||||||
|
root = Path(__file__).resolve().parents[1]
|
||||||
|
cfg = load_config(root / "config.toml")
|
||||||
|
assert cfg.optimizer.method in ("hybrid", "mapso", "local", "differential_evolution")
|
||||||
@@ -0,0 +1,64 @@
|
|||||||
|
"""Tests for composite objective with coverage and overlap."""
|
||||||
|
|
||||||
|
import numpy as np
|
||||||
|
|
||||||
|
from uavsearch.geometry import RectRegion
|
||||||
|
from uavsearch.metrics import RevisitMetrics
|
||||||
|
from uavsearch.problem import CoverageProblem, compute_composite_objective, evaluate_deployment, random_deployment
|
||||||
|
|
||||||
|
|
||||||
|
def test_overlap_ratio_in_evaluation():
|
||||||
|
region = RectRegion.from_size(600, 500)
|
||||||
|
problem = CoverageProblem(region=region, n_uavs=3, sensor_radius=30, speed=10, grid_density=3)
|
||||||
|
pos = random_deployment(problem, seed=1)
|
||||||
|
result = evaluate_deployment(problem, pos, sim_duration=120)
|
||||||
|
assert 0.0 <= result.overlap_ratio <= 1.0
|
||||||
|
assert 0.0 <= result.coverage_ratio <= 1.0
|
||||||
|
|
||||||
|
|
||||||
|
def test_composite_objective_prefers_high_coverage_low_overlap():
|
||||||
|
problem = CoverageProblem(
|
||||||
|
region=RectRegion.from_size(500, 400),
|
||||||
|
n_uavs=2,
|
||||||
|
sensor_radius=30,
|
||||||
|
speed=10,
|
||||||
|
weight_t_max=1.0,
|
||||||
|
weight_coverage=120.0,
|
||||||
|
weight_overlap=100.0,
|
||||||
|
)
|
||||||
|
good = RevisitMetrics(
|
||||||
|
mean_revisit_time=80,
|
||||||
|
max_revisit_time=100,
|
||||||
|
min_revisit_time=50,
|
||||||
|
std_revisit_time=10,
|
||||||
|
coverage_ratio=0.9,
|
||||||
|
overlap_ratio=0.05,
|
||||||
|
max_idle_time=100,
|
||||||
|
mean_idle_time=80,
|
||||||
|
)
|
||||||
|
bad = RevisitMetrics(
|
||||||
|
mean_revisit_time=80,
|
||||||
|
max_revisit_time=100,
|
||||||
|
min_revisit_time=50,
|
||||||
|
std_revisit_time=10,
|
||||||
|
coverage_ratio=0.5,
|
||||||
|
overlap_ratio=0.3,
|
||||||
|
max_idle_time=100,
|
||||||
|
mean_idle_time=80,
|
||||||
|
)
|
||||||
|
good_obj = compute_composite_objective(problem, good, max_patrol_period=200)
|
||||||
|
bad_obj = compute_composite_objective(problem, bad, max_patrol_period=200)
|
||||||
|
assert good_obj < bad_obj
|
||||||
|
|
||||||
|
|
||||||
|
def test_config_objective_weights():
|
||||||
|
from pathlib import Path
|
||||||
|
|
||||||
|
from uavsearch.config import load_config
|
||||||
|
|
||||||
|
root = Path(__file__).resolve().parents[1]
|
||||||
|
cfg = load_config(root / "config.toml")
|
||||||
|
problem = cfg.problem.build_problem(cfg.objective, cfg.planner, cfg.simulation)
|
||||||
|
assert problem.weight_coverage == cfg.objective.weight_coverage
|
||||||
|
assert problem.weight_overlap == cfg.objective.weight_overlap
|
||||||
|
assert problem.sweep_width_ratio == cfg.planner.boustrophedon.sweep_width_ratio
|
||||||
@@ -0,0 +1,39 @@
|
|||||||
|
"""Tests for coverage-period optimization."""
|
||||||
|
|
||||||
|
import numpy as np
|
||||||
|
|
||||||
|
from uavsearch.geometry import RectRegion
|
||||||
|
from uavsearch.optimizer import optimize_deployment
|
||||||
|
from uavsearch.problem import CoverageProblem, evaluate_deployment, random_deployment
|
||||||
|
|
||||||
|
|
||||||
|
def test_evaluate_deployment_returns_finite_objective():
|
||||||
|
region = RectRegion.from_size(600, 500)
|
||||||
|
problem = CoverageProblem(region=region, n_uavs=3, sensor_radius=30, speed=10)
|
||||||
|
pos = random_deployment(problem, seed=1)
|
||||||
|
result = evaluate_deployment(problem, pos, sim_duration=150)
|
||||||
|
assert np.isfinite(result.objective_value)
|
||||||
|
assert result.max_revisit_time > 0
|
||||||
|
|
||||||
|
|
||||||
|
def test_optimizer_improves_or_matches_baseline():
|
||||||
|
region = RectRegion.from_size(800, 600)
|
||||||
|
problem = CoverageProblem(
|
||||||
|
region=region,
|
||||||
|
n_uavs=3,
|
||||||
|
sensor_radius=40,
|
||||||
|
speed=12,
|
||||||
|
partition_mode="voronoi",
|
||||||
|
grid_density=3,
|
||||||
|
)
|
||||||
|
baseline = evaluate_deployment(problem, random_deployment(problem, seed=0), sim_duration=200)
|
||||||
|
opt = optimize_deployment(problem, method="local", seed=0, maxiter=5, sim_duration=200)
|
||||||
|
assert opt.best.objective_value <= baseline.objective_value * 1.05
|
||||||
|
|
||||||
|
|
||||||
|
def test_problem_unpack_positions():
|
||||||
|
region = RectRegion.from_size(100, 100)
|
||||||
|
problem = CoverageProblem(region=region, n_uavs=2, sensor_radius=10, speed=5)
|
||||||
|
vec = np.array([10, 10, 90, 90])
|
||||||
|
pos = problem.unpack_positions(vec)
|
||||||
|
assert pos.shape == (2, 2)
|
||||||
@@ -0,0 +1,54 @@
|
|||||||
|
"""Tests for depot-in-partition assignment."""
|
||||||
|
|
||||||
|
import numpy as np
|
||||||
|
from shapely.geometry import Point
|
||||||
|
|
||||||
|
from uavsearch.geometry import RectRegion
|
||||||
|
from uavsearch.partition import build_partition, partition_voronoi
|
||||||
|
from uavsearch.partition.initial import generate_uneven_positions
|
||||||
|
|
||||||
|
|
||||||
|
def _depot_inside_own_cell(region, mode: str, positions: np.ndarray, sensor_radius: float = 40.0) -> bool:
|
||||||
|
result = build_partition(region, len(positions), mode, positions, sensor_radius=sensor_radius)
|
||||||
|
for cell in result.cells:
|
||||||
|
depot = positions[cell.uav_id]
|
||||||
|
pt = Point(float(depot[0]), float(depot[1]))
|
||||||
|
if not cell.polygon.contains(pt) and cell.polygon.boundary.distance(pt) > 1e-3:
|
||||||
|
return False
|
||||||
|
return True
|
||||||
|
|
||||||
|
|
||||||
|
def test_voronoi_depot_inside_own_cell():
|
||||||
|
region = RectRegion.from_size(800, 600)
|
||||||
|
positions = generate_uneven_positions(region, 4, seed=11)
|
||||||
|
assert _depot_inside_own_cell(region, "voronoi", positions)
|
||||||
|
|
||||||
|
|
||||||
|
def test_workload_depot_inside_own_cell():
|
||||||
|
region = RectRegion.from_size(800, 600)
|
||||||
|
positions = generate_uneven_positions(region, 4, seed=11)
|
||||||
|
assert _depot_inside_own_cell(region, "workload", positions)
|
||||||
|
|
||||||
|
|
||||||
|
def test_lloyd_depot_inside_own_cell():
|
||||||
|
region = RectRegion.from_size(800, 600)
|
||||||
|
positions = generate_uneven_positions(region, 4, seed=11)
|
||||||
|
assert _depot_inside_own_cell(region, "lloyd", positions)
|
||||||
|
|
||||||
|
|
||||||
|
def test_workload_uav_id_matches_depot_index():
|
||||||
|
region = RectRegion.from_size(800, 600)
|
||||||
|
positions = generate_uneven_positions(region, 4, seed=5)
|
||||||
|
result = build_partition(region, 4, "workload", positions, sensor_radius=40)
|
||||||
|
for cell in result.cells:
|
||||||
|
assert cell.uav_id == cell.partition_id
|
||||||
|
assert np.allclose(cell.initial_position, positions[cell.uav_id])
|
||||||
|
|
||||||
|
|
||||||
|
def test_voronoi_no_hungarian_cross_assignment():
|
||||||
|
region = RectRegion.from_size(800, 600)
|
||||||
|
positions = np.array([[100, 100], [700, 100], [100, 500], [700, 500]], dtype=float)
|
||||||
|
result = partition_voronoi(region, positions)
|
||||||
|
for i, cell in enumerate(result.cells):
|
||||||
|
assert cell.uav_id == i
|
||||||
|
assert np.allclose(cell.initial_position, positions[i])
|
||||||
@@ -0,0 +1,171 @@
|
|||||||
|
"""Tests for UAVSearch patrol coverage."""
|
||||||
|
|
||||||
|
import numpy as np
|
||||||
|
|
||||||
|
from uavsearch.geometry import RectRegion
|
||||||
|
from uavsearch.partition import (
|
||||||
|
assign_uavs_to_partitions,
|
||||||
|
generate_uneven_positions,
|
||||||
|
partition_and_assign,
|
||||||
|
partition_strips,
|
||||||
|
partition_uniform,
|
||||||
|
)
|
||||||
|
from uavsearch.planner import plan_boustrophedon_patrol, plan_mtsp_patrol
|
||||||
|
from uavsearch.sim import PatrolSimulator
|
||||||
|
|
||||||
|
|
||||||
|
def test_rect_region_area():
|
||||||
|
r = RectRegion.from_size(100, 200)
|
||||||
|
assert r.area == 20000
|
||||||
|
assert r.contains_point(50, 100)
|
||||||
|
assert not r.contains_point(150, 100)
|
||||||
|
|
||||||
|
|
||||||
|
def test_strip_partition_count_and_coverage():
|
||||||
|
region = RectRegion.from_size(1000, 800)
|
||||||
|
strips = partition_strips(region, 4, direction="vertical")
|
||||||
|
assert len(strips) == 4
|
||||||
|
total_area = sum(s.area for s in strips)
|
||||||
|
assert abs(total_area - region.area) < 1e-6
|
||||||
|
|
||||||
|
|
||||||
|
def test_uniform_partition_equal_areas():
|
||||||
|
region = RectRegion.from_size(1000, 800)
|
||||||
|
cells = partition_uniform(region, 4)
|
||||||
|
areas = [c.area for c in cells]
|
||||||
|
assert len(areas) == 4
|
||||||
|
assert max(areas) - min(areas) < 1.0
|
||||||
|
|
||||||
|
|
||||||
|
def test_uneven_initial_positions_not_uniform():
|
||||||
|
region = RectRegion.from_size(1000, 800)
|
||||||
|
a = generate_uneven_positions(region, 4, seed=1)
|
||||||
|
b = generate_uneven_positions(region, 4, seed=99)
|
||||||
|
assert a.shape == (4, 2)
|
||||||
|
assert not np.allclose(a, b)
|
||||||
|
|
||||||
|
|
||||||
|
def test_assign_uavs_to_uniform_partitions():
|
||||||
|
region = RectRegion.from_size(1000, 800)
|
||||||
|
positions = generate_uneven_positions(region, 4, seed=7)
|
||||||
|
cells = partition_uniform(region, 4)
|
||||||
|
result = assign_uavs_to_partitions(region, cells, positions)
|
||||||
|
|
||||||
|
assert result.n_uavs == 4
|
||||||
|
areas = [c.area for c in result.cells]
|
||||||
|
assert max(areas) - min(areas) < 1.0
|
||||||
|
partition_ids = {c.partition_id for c in result.cells}
|
||||||
|
assert partition_ids == {0, 1, 2, 3}
|
||||||
|
for cell in result.cells:
|
||||||
|
assert abs(cell.bounds.area - region.area / 4) < 1.0
|
||||||
|
|
||||||
|
|
||||||
|
def test_partition_and_assign():
|
||||||
|
region = RectRegion.from_size(1000, 800)
|
||||||
|
positions = generate_uneven_positions(region, 4, seed=3)
|
||||||
|
result = partition_and_assign(region, 4, positions)
|
||||||
|
assert result.n_uavs == 4
|
||||||
|
areas = [c.area for c in result.cells]
|
||||||
|
assert max(areas) - min(areas) < 1.0
|
||||||
|
|
||||||
|
|
||||||
|
def test_boustrophedon_closed_loop_with_uniform_partition():
|
||||||
|
region = RectRegion.from_size(400, 300)
|
||||||
|
positions = generate_uneven_positions(region, 2, seed=3)
|
||||||
|
paths, partition = plan_boustrophedon_patrol(region, 2, sweep_width=40, initial_positions=positions)
|
||||||
|
assert len(paths) == 2
|
||||||
|
assert partition.n_uavs == 2
|
||||||
|
for p in paths:
|
||||||
|
assert p.waypoints.shape[1] == 2
|
||||||
|
assert np.allclose(p.waypoints[0], p.waypoints[-1])
|
||||||
|
assert p.length > 0
|
||||||
|
for wp in p.waypoints:
|
||||||
|
assert p.region.contains_point(float(wp[0]), float(wp[1]))
|
||||||
|
|
||||||
|
|
||||||
|
def test_mtsp_covers_region_with_uniform_partition():
|
||||||
|
region = RectRegion.from_size(500, 400)
|
||||||
|
positions = generate_uneven_positions(region, 3, seed=5)
|
||||||
|
paths, partition = plan_mtsp_patrol(region, 3, sensor_radius=30, initial_positions=positions)
|
||||||
|
assert len(paths) == 3
|
||||||
|
assert partition.n_uavs == 3
|
||||||
|
for p in paths:
|
||||||
|
assert np.allclose(p.waypoints[0], p.waypoints[-1])
|
||||||
|
assert p.length > 0
|
||||||
|
|
||||||
|
|
||||||
|
def test_simulator_starts_at_initial_position():
|
||||||
|
region = RectRegion.from_size(600, 500)
|
||||||
|
positions = generate_uneven_positions(region, 3, seed=11)
|
||||||
|
paths, _ = plan_boustrophedon_patrol(region, 3, sweep_width=60, initial_positions=positions)
|
||||||
|
sim = PatrolSimulator(region, paths, speed=10.0, sensor_radius=30.0, dt=1.0, grid_density=4)
|
||||||
|
for uav, path in zip(sim.uavs, paths):
|
||||||
|
assert np.allclose(uav.position, path.initial_position)
|
||||||
|
|
||||||
|
|
||||||
|
def test_depot_operational_cycle_includes_round_trip():
|
||||||
|
from uavsearch.planner.boustrophedon import PatrolPath
|
||||||
|
from uavsearch.geometry import RectRegion
|
||||||
|
|
||||||
|
region = RectRegion.from_size(100, 100)
|
||||||
|
wp = np.array([[10, 10], [90, 10], [90, 90], [10, 90], [10, 10]], dtype=float)
|
||||||
|
path = PatrolPath(uav_id=0, region=region, waypoints=wp, initial_position=(5.0, 5.0), entry_index=0)
|
||||||
|
assert path.outbound_transit_length > 0
|
||||||
|
assert path.operational_cycle_distance > path.loop_length
|
||||||
|
period = path.operational_cycle_period(speed=10.0, depot_service_time=60.0)
|
||||||
|
assert period > path.loop_length / 10.0 + 60.0 - 1e-6
|
||||||
|
|
||||||
|
|
||||||
|
def test_simulator_only_covers_during_patrol_phase():
|
||||||
|
region = RectRegion.from_size(600, 500)
|
||||||
|
paths, _ = plan_boustrophedon_patrol(region, 2, sweep_width=60, seed=42)
|
||||||
|
sim = PatrolSimulator(region, paths, speed=10.0, sensor_radius=30.0, dt=0.5, grid_density=4)
|
||||||
|
sim.run(duration=60.0)
|
||||||
|
visited = sim.grid.visit_count > 0
|
||||||
|
for cell in paths:
|
||||||
|
bounds = cell.region
|
||||||
|
i0 = int((bounds.xmin - region.xmin) / sim.grid.cell_size)
|
||||||
|
i1 = int((bounds.xmax - region.xmin) / sim.grid.cell_size)
|
||||||
|
j0 = int((bounds.ymin - region.ymin) / sim.grid.cell_size)
|
||||||
|
j1 = int((bounds.ymax - region.ymin) / sim.grid.cell_size)
|
||||||
|
i0 = max(0, min(i0, sim.grid.nx - 1))
|
||||||
|
i1 = max(0, min(i1, sim.grid.nx))
|
||||||
|
j0 = max(0, min(j0, sim.grid.ny - 1))
|
||||||
|
j1 = max(0, min(j1, sim.grid.ny))
|
||||||
|
assert np.any(visited[i0:i1, j0:j1])
|
||||||
|
|
||||||
|
|
||||||
|
def test_workload_partition_balances_cells():
|
||||||
|
from uavsearch.partition import build_partition, generate_uneven_positions
|
||||||
|
|
||||||
|
region = RectRegion.from_size(800, 600)
|
||||||
|
positions = generate_uneven_positions(region, 4, seed=5)
|
||||||
|
result = build_partition(region, 4, "workload", positions, sensor_radius=40)
|
||||||
|
areas = [c.area for c in result.cells]
|
||||||
|
assert len(areas) == 4
|
||||||
|
assert sum(areas) > region.area * 0.9
|
||||||
|
|
||||||
|
|
||||||
|
def test_plan_patrol_workload_mtsp():
|
||||||
|
region = RectRegion.from_size(500, 400)
|
||||||
|
from uavsearch.planner import plan_patrol
|
||||||
|
from uavsearch.partition import generate_uneven_positions
|
||||||
|
|
||||||
|
positions = generate_uneven_positions(region, 3, seed=1)
|
||||||
|
paths, partition = plan_patrol(
|
||||||
|
region, 3, sensor_radius=30, initial_positions=positions,
|
||||||
|
partition_mode="workload", planner="mtsp",
|
||||||
|
)
|
||||||
|
assert len(paths) == 3
|
||||||
|
assert partition.n_uavs == 3
|
||||||
|
|
||||||
|
|
||||||
|
def test_simulator_produces_metrics():
|
||||||
|
region = RectRegion.from_size(600, 500)
|
||||||
|
from uavsearch.planner import plan_patrol
|
||||||
|
|
||||||
|
paths, _ = plan_patrol(region, 3, sensor_radius=30, seed=42)
|
||||||
|
sim = PatrolSimulator(region, paths, speed=10.0, sensor_radius=30.0, dt=1.0, grid_density=4)
|
||||||
|
metrics = sim.run(duration=180.0)
|
||||||
|
assert metrics.coverage_ratio > 0.45
|
||||||
|
assert metrics.mean_revisit_time < float("inf")
|
||||||
@@ -0,0 +1,16 @@
|
|||||||
|
"""Tests for coverage dashboard."""
|
||||||
|
|
||||||
|
from uavsearch.geometry import RectRegion
|
||||||
|
from uavsearch.problem import CoverageProblem, evaluate_deployment, random_deployment
|
||||||
|
from uavsearch.viz import plot_coverage_dashboard
|
||||||
|
|
||||||
|
|
||||||
|
def test_dashboard_builds_without_optimize():
|
||||||
|
region = RectRegion.from_size(400, 300)
|
||||||
|
problem = CoverageProblem(region=region, n_uavs=2, sensor_radius=25, speed=10, grid_density=3)
|
||||||
|
pos = random_deployment(problem, seed=1)
|
||||||
|
result = evaluate_deployment(problem, pos, sim_duration=80.0)
|
||||||
|
fig = plot_coverage_dashboard(problem, baseline=result, optimized=result)
|
||||||
|
assert fig is not None
|
||||||
|
import matplotlib.pyplot as plt
|
||||||
|
plt.close(fig)
|
||||||