"""ファミレスの店の形 第3版:決まりの確かめ方とロボットの届き方を作り直した版。 codex の敵対的検証(review_result.md)を受けて直したこと - ロボットの通れる幅は機種の公表値(初期値 BellaBot 80cm)。本体の幅とは別に扱う - 「ふだん走らせる幅」(初期値 1.0m)を別に持ち、卓を3つに分ける ロボットが届く卓/狭い道なら届く卓/人が運ぶ卓(ロボットから受け取って人が運ぶ) - 届くかは、卓の「座る側(開いた側)」の前で止まれるかで判定する。背中側・壁側・仕切り越しは数えない - 幅の判定は、マス目の中心から障害物までの距離で行い、2つの細かさで同じ結果になるかを毎回確かめる - 斜めのすり抜けを禁止する。出発点が通れない場所なら止める - 待機・充電の場所は、止まっているロボットごと障害物として扱う - 決まりの確かめを全部の組み合わせに広げ、違反があれば図とデータを出さずに止める 使い方: python3 famires_v3.py (出力はサイトの中なら public/sim/layouts/、外なら variants3/) python3 famires_v3.py Servi (機種を替えて試算) """ import json import math import sys from pathlib import Path import numpy as np from scipy import ndimage, sparse from scipy.sparse.csgraph import dijkstra import matplotlib matplotlib.use("Agg") import matplotlib.pyplot as plt from matplotlib.patches import Rectangle, Circle, Polygon import famires_gen2 as gen import famires_p0 plt.rcParams["font.family"] = "Noto Sans CJK JP" HERE = Path(__file__).parent SCHEMA = "famires-layout/0.3" # 機種ごとの公表値(最小通過幅)。出典は README と同じ ROBOT_MODELS = { "BellaBot": dict(pass_width=0.80, body_width=0.50, maker="Pudu Robotics", source="https://academy.pudutech.com/en/docs/huan-le-song-chan-pin-jian-jie"), "KettyBot": dict(pass_width=0.55, body_width=0.435, maker="Pudu Robotics", source="https://academy.pudutech.com/en/docs/chan-pin-jian-jie"), "Keenbot T8": dict(pass_width=0.55, body_width=0.384, maker="KEENON", source="https://www.irisohyama.co.jp/b2b/robotics/products/keenbot-t8/"), "KEENON T10": dict(pass_width=0.585, body_width=None, maker="KEENON", source="https://meetsmore.com/products/keenon-t10"), "Servi": dict(pass_width=0.60, body_width=None, maker="Bear Robotics", source="https://innovatopia.jp/robot/robot-news/118331/"), "Servi Q": dict(pass_width=0.45, body_width=0.35, maker="Bear Robotics", source="https://innovatopia.jp/robot/robot-news/118331/"), } SETTINGS = dict( model="BellaBot", normal_width=1.0, # ふだん走らせる通路の幅(店の運用の設定) human_width=0.5, # 人が通れる幅(人が運ぶ卓の歩く距離を測るとき) res=0.025, # 計算のマス目(m)。幅 w 以上の通路は必ず通れる、w−res 未満は必ず通れない check_res=0.0125, # 確かめ用の細かいマス目(m)。2つで結果が分かれた卓は ? 印 stop_reach=0.3, # 通路の幅いっぱいから、さらに卓へ寄れる余裕(止まる位置の帯の厚み) side_end_margin=0.15, # 座る側の両端から、この長さは止まる位置に使わない toilet_min_gap=1.0, # トイレからこの距離「以内」に席を置かない(ちょうど1mも不可) toilet_door_depth=1.2, entrance_depth=1.5, # 入口から店の中へ、この奥行きは何も置かない dish_front_depth=1.2, # 料理の受け渡し口の前、この奥行きは何も置かない joint_max_depth=0.08, # 仕切りが家具に食い込んでよい深さ(背もたれの上に立つ仕切り) register_min_len=2.5, ) FURNITURE_TYPES = { "booth": dict(desc="ボックス席。向かい合うベンチ2つと間のテーブル。座る側(開いた側)は長い2辺。短い2辺はベンチの背", bench_depth=0.55, table_depth=0.75, length=1.85, bench_length={"4": 1.2, "6": 1.8}, axis={"v": "ベンチが上下(座る側は左右)", "h": "ベンチが左右(座る側は上下)"}), "t2": dict(desc="2人席。壁側がベンチ、通路側が椅子", footprint=[0.8, 1.4], table=[0.7, 0.6], bench_depth=0.45, chair_radius=0.18), "booth6L": dict(desc="L字ソファの6人席。ソファの内側の角にテーブル(約0.75m×1.2m)", sofa_depth_ratio={"band": 0.45, "column": 0.55}), "walls": dict(height_m_仮={"壁": 2.7, "仕切り": 1.2, "トイレの壁": 2.7}), } STYLE_AISLE = {"効率重視": 1.2, "ゆったり": 1.5} # ================================================================ 形の道具 def fp(t): return (t["x"], t["y"], t["x"] + t["w"], t["y"] + t["h"]) def inter(a, b): """2つの矩形の重なり(x方向の深さ, y方向の深さ)。重ならなければ None""" dx = min(a[2], b[2]) - max(a[0], b[0]) dy = min(a[3], b[3]) - max(a[1], b[1]) return (dx, dy) if dx > 1e-6 and dy > 1e-6 else None def gap(a, b): dx = max(0.0, max(a[0], b[0]) - min(a[2], b[2])) dy = max(0.0, max(a[1], b[1]) - min(a[3], b[3])) return math.hypot(dx, dy) def seg_hits(a, b, rects): """線分 a-b が矩形のどれかを通るか(1cmごとに確かめる)""" n = max(2, int(math.hypot(b[0] - a[0], b[1] - a[1]) / 0.01)) for i in range(1, n): x, y = a[0] + (b[0] - a[0]) * i / n, a[1] + (b[1] - a[1]) * i / n if any(r[0] <= x <= r[2] and r[1] <= y <= r[3] for r in rects): return True return False def entrance_zone(L, depth): e, W, D = L["entrance"], L["outer"]["w"], L["outer"]["d"] return {"bottom": (e["a0"], 0, e["a1"], depth), "top": (e["a0"], D - depth, e["a1"], D), "left": (0, e["a0"], depth, e["a1"]), "right": (W - depth, e["a0"], W, e["a1"])}[e["side"]] def table_sides(t): """座る側の候補。booth は長い2辺だけ(短い辺はベンチの背)""" x0, y0, x1, y1 = fp(t) sides = {"left": ((x0, y0), (x0, y1), (-1, 0)), "right": ((x1, y0), (x1, y1), (1, 0)), "bottom": ((x0, y0), (x1, y0), (0, -1)), "top": ((x0, y1), (x1, y1), (0, 1))} if t["type"] == "booth": keep = ("left", "right") if t["axis"] == "v" else ("bottom", "top") return {k: v for k, v in sides.items() if k in keep} return sides def all_obstacles(L, skip=None): """障害物の矩形と名前。skip は除く卓の番号""" obs = [(r["rect"], "部屋:" + r["label"]) for r in L["rooms"]] obs += [(w["rect"], "壁:" + w["label"]) for w in L["walls"]] obs += [(fp(t), f"卓:{t['id']}") for i, t in enumerate(L["tables"]) if i != skip] obs += [(L["robot_standby"]["rect"], "待機場所")] return obs def open_sides(L, i, probe=0.2): """座る側のうち、外側 probe の帯に何もない辺(壁・仕切り・ほかの卓・店の外がない辺)""" t = L["tables"][i] W, D = L["outer"]["w"], L["outer"]["d"] obs = [o for o, _ in all_obstacles(L, skip=i)] out = {} for k, ((ax, ay), (bx, by), (nx, ny)) in table_sides(t).items(): e = 0.1 if nx: # 縦の辺 band = (min(ax, ax + nx * probe), ay + e, max(ax, ax + nx * probe), by - e) else: band = (ax + e, min(ay, ay + ny * probe), bx - e, max(ay, ay + ny * probe)) outside = band[0] < -1e-6 or band[1] < -1e-6 or band[2] > W + 1e-6 or band[3] > D + 1e-6 if not outside and not any(inter(band, o) for o in obs): out[k] = ((ax, ay), (bx, by), (nx, ny)) return out # ================================================================ 決まりの確かめ def check_rules(L): S = SETTINGS W, D = L["outer"]["w"], L["outer"]["d"] v = [] # (区分, 内容) T = L["tables"] rooms, walls = L["rooms"], L["walls"] inside = lambda r: r[0] >= -1e-6 and r[1] >= -1e-6 and r[2] <= W + 1e-6 and r[3] <= D + 1e-6 # 店の外にはみ出していないか for t in T: if not inside(fp(t)): v.append(("店の外", f"{t['id']} が店の外にはみ出している")) for r in rooms + walls: if not inside(r["rect"]): v.append(("店の外", f"{r['label']} が店の外にはみ出している")) if not inside(L["robot_standby"]["rect"]): v.append(("店の外", "待機場所が店の外にはみ出している")) # 卓どうし・卓と部屋・卓と壁・卓と待機場所 for i, a in enumerate(T): A = fp(a) for b in T[i + 1:]: if inter(A, fp(b)): v.append(("重なり", f"{a['id']} と {b['id']}")) for r in rooms: if inter(A, r["rect"]): v.append(("重なり", f"{a['id']} と {r['label']}")) for w in walls: o = inter(A, w["rect"]) if o and not (w.get("joint") and a["type"] == "booth" and min(o) <= S["joint_max_depth"] + 1e-6): v.append(("重なり", f"{a['id']} と {w['label']}({min(o):.2f}m 食い込み)")) if inter(A, L["robot_standby"]["rect"]): v.append(("重なり", f"{a['id']} と 待機場所")) # 部屋どうし・部屋と待機場所 for i, a in enumerate(rooms): for b in rooms[i + 1:]: if inter(a["rect"], b["rect"]): v.append(("重なり", f"{a['label']} と {b['label']}")) if inter(a["rect"], L["robot_standby"]["rect"]): v.append(("重なり", f"{a['label']} と 待機場所")) for w in walls: if inter(w["rect"], L["robot_standby"]["rect"]): v.append(("重なり", f"{w['label']} と 待機場所")) # 入口の前・受け渡し口の前は空ける ez = entrance_zone(L, S["entrance_depth"]) for o, name in all_obstacles(L): if inter(ez, o): v.append(("入口の前", f"{name} が入口から{S['entrance_depth']}m以内にある")) for d in L["dish_up"]: x0, y0, x1, y1 = d["rect"] dz = (x0, y0 - S["dish_front_depth"], x1, y0) for o, name in all_obstacles(L): if inter(dz, o) and not name.startswith("部屋:パントリー"): v.append(("受け渡し口の前", f"{name} が受け渡し口の前{S['dish_front_depth']}m以内にある")) # トイレ toilets = [r["rect"] for r in rooms if r["label"] == "トイレ"] doors = L.get("toilet_doors", []) if len(doors) != len(toilets): v.append(("トイレ", f"トイレ{len(toilets)}か所に対して入口の情報が{len(doors)}件")) screens = [w["rect"] for w in walls if not w.get("joint")] for t in T: for tr in toilets: g = gap(fp(t), tr) if g <= S["toilet_min_gap"] + 1e-6: # 1m以内でも、席とトイレの入口の間に壁があればよい(目隠しの壁を入れる配慮) c = ((t["x"] + t["w"] / 2), (t["y"] + t["h"] / 2)) hidden = bool(doors) and all(seg_hits(c, ((d[0] + d[2]) / 2, (d[1] + d[3]) / 2), screens) for d in doors) if not hidden: v.append(("トイレ", f"{t['id']} がトイレから{g:.2f}m({S['toilet_min_gap']}m以内に置くなら、トイレの入口との間に壁が要る)")) for dz in doors: for o, name in all_obstacles(L): if name.startswith("壁:トイレの壁") or name == "部屋:トイレ": continue if inter(dz, o): v.append(("トイレ", f"{name} がトイレの入口の前をふさいでいる")) for tr in toilets: tw = [w for w in walls if w["label"] == "トイレの壁" and gap(w["rect"], tr) < 1e-6] if not tw: v.append(("トイレ", "トイレに客席側の壁がない")) for w in tw: x0, y0, x1, y1 = w["rect"] if min(x1 - x0, y1 - y0) < 0.3 - 1e-6: v.append(("トイレ", f"トイレの壁が薄い({min(x1 - x0, y1 - y0):.2f}m)")) # 入口まわり:待合・レジ labels = [r["label"] for r in rooms] if "待合" not in labels: v.append(("入口まわり", "待合がない")) for r in rooms: if r["label"] == "レジ": x0, y0, x1, y1 = r["rect"] if max(x1 - x0, y1 - y0) < S["register_min_len"] - 1e-6: v.append(("入口まわり", f"レジが短い({max(x1 - x0, y1 - y0):.2f}m)")) if r["label"] == "ドリンクバー": pass if "ドリンクバー" not in labels: v.append(("入口まわり", "ドリンクバーがない")) # 座る側が1つもない卓 for i, t in enumerate(T): if not open_sides(L, i): v.append(("座れない卓", f"{t['id']} の座る側がすべてふさがっている")) return v # ================================================================ ロボットの届き方 class Grid: def __init__(self, L, res): self.res = res W, D = L["outer"]["w"], L["outer"]["d"] self.nx, self.ny = int(math.ceil(W / res - 1e-9)), int(math.ceil(D / res - 1e-9)) xs = (np.arange(self.nx) + 0.5) * res ys = (np.arange(self.ny) + 0.5) * res self.xs, self.ys = xs, ys # 障害物までの距離を矩形から正確に出す(マス目に塗ってから測ると、縁が最大1マスずれるため) X, Y = np.meshgrid(xs, ys) clear = np.minimum(np.minimum(X, W - X), np.minimum(Y, D - Y)) # 外壁まで self.obs = [o for o, _ in all_obstacles(L)] for x0, y0, x1, y1 in self.obs: dx = np.maximum(np.maximum(x0 - X, X - x1), 0.0) dy = np.maximum(np.maximum(y0 - Y, Y - y1), 0.0) np.minimum(clear, np.hypot(dx, dy), out=clear) self.clear = clear self.occ = clear <= 1e-9 def free(self, width): # 幅 width 以上の通路は必ず通れる。width−res 未満は必ず通れない(マス目の中心が通路の真ん中に来るとは限らないため) return self.clear >= width / 2 - self.res / 2 - 1e-9 def cell(self, x, y): return int(y / self.res), int(x / self.res) def graph(self, free): ny, nx = free.shape idx = np.arange(ny * nx).reshape(ny, nx) rows, cols, wts = [], [], [] for dy, dx in ((0, 1), (1, 0), (1, 1), (1, -1)): a = free[max(0, -dy):ny - max(0, dy), max(0, -dx):nx - max(0, dx)] ys0, ys1 = max(0, -dy), ny - max(0, dy) xs0, xs1 = max(0, -dx), nx - max(0, dx) src = free[ys0:ys1, xs0:xs1] dst = free[ys0 + dy:ys1 + dy, xs0 + dx:xs1 + dx] ok = src & dst if dy and dx: # 斜めは両隣が通れるときだけ(すり抜け禁止) ok &= free[ys0:ys1, xs0 + dx:xs1 + dx] & free[ys0 + dy:ys1 + dy, xs0:xs1] s = idx[ys0:ys1, xs0:xs1][ok] d = idx[ys0 + dy:ys1 + dy, xs0 + dx:xs1 + dx][ok] w = self.res * (math.sqrt(2) if dy and dx else 1.0) rows += [s, d] cols += [d, s] wts += [np.full(len(s), w), np.full(len(s), w)] n = ny * nx return sparse.csr_matrix((np.concatenate(wts), (np.concatenate(rows), np.concatenate(cols))), shape=(n, n)) def run(self, free, sources): """sources はマス目の番号の並び。複数なら、そのどれからでも0として測る""" G = self.graph(free) n = G.shape[0] if len(sources) == 1: dist, pred = dijkstra(G, indices=sources[0], return_predecessors=True) return dist.reshape(free.shape), pred # 複数の出発点:仮の点を1つ足してつなぐ G = sparse.vstack([sparse.hstack([G, sparse.csr_matrix((n, 1))]), sparse.csr_matrix((np.full(len(sources), 1e-9), (np.zeros(len(sources), int), sources)), shape=(1, n + 1))]).tocsr() dist, pred = dijkstra(G, indices=n, return_predecessors=True) return dist[:n].reshape(free.shape), pred[:n] def stop_cells(self, side, width, reach): """座る側の前で止まれるマス目:辺から width/2 −res 〜 width/2 + reach の帯で、辺の両端を除いた所""" (ax, ay), (bx, by), (nx, ny) = side m = SETTINGS["side_end_margin"] lo, hi = width / 2 - self.res, width / 2 + reach X, Y = np.meshgrid(self.xs, self.ys) if nx: d = (X - ax) * nx along = (Y >= ay + m) & (Y <= by - m) else: d = (Y - ay) * ny along = (X >= ax + m) & (X <= bx - m) return (d >= lo) & (d <= hi) & along, d def sight(self, cy, cx, side, skip_rect): """止まる位置から辺までの線の上に、ほかの障害物がないか(1cmごとに確かめる)""" (ax, ay), (bx, by), (nx, ny) = side px, py = self.xs[cx], self.ys[cy] tx, ty = (ax, py) if nx else (px, ay) n = max(2, int(math.hypot(tx - px, ty - py) / 0.01)) for f in np.linspace(0.0, 1.0, n)[1:-1]: x, y = px + (tx - px) * f, py + (ty - py) * f for o in self.obs: if o == skip_rect: continue if o[0] < x < o[2] and o[1] < y < o[3]: return False return True def best_stop(grid, dist, sides, width, reach, skip_rect=None): best = None for k, side in sides.items(): band, _ = grid.stop_cells(side, width, reach) cand = np.where(band & np.isfinite(dist)) if not len(cand[0]): continue order = np.argsort(dist[cand]) for o in order[:200]: cy, cx = cand[0][o], cand[1][o] if grid.sight(cy, cx, side, skip_rect): if best is None or dist[cy, cx] < best[0]: best = (float(dist[cy, cx]), cy, cx, k) break return best def trace(pred, grid, cy, cx): n = grid.nx i = cy * n + cx pts = [] while i >= 0 and i < grid.nx * grid.ny: pts.append(((i % n + 0.5) * grid.res, (i // n + 0.5) * grid.res)) i = pred[i] return pts[::-1] def analyze(L, res): S = SETTINGS model = ROBOT_MODELS[S["model"]] pw, nw, hw = model["pass_width"], S["normal_width"], S["human_width"] g = Grid(L, res) sx, sy = L["start"] cy, cx = g.cell(sx, sy) errs = [] if not (0 <= cy < g.ny and 0 <= cx < g.nx): raise ValueError("出発点が店の外にある") f_pass, f_norm, f_hum = g.free(pw), g.free(nw), g.free(hw) if not f_pass[cy, cx]: raise ValueError(f"出発点(受け渡し口の前)がロボットの通れない場所にある(余裕 {g.clear[cy, cx]:.2f}m)") s0 = cy * g.nx + cx d_norm, p_norm = g.run(f_norm, [s0]) if f_norm[cy, cx] else (np.full(f_norm.shape, np.inf), None) d_pass, p_pass = g.run(f_pass, [s0]) # 待機場所から出発点まで出られるか sb = L["robot_standby"]["rect"] dock_side = {"d": ((sb[0], sb[1]), (sb[2], sb[1]), (0, -1))} if best_stop(g, d_pass, dock_side, pw, S["stop_reach"], tuple(sb)) is None: errs.append(("待機場所", "待機場所から受け渡し口の前まで出られない")) sides = [open_sides(L, i) for i in range(len(L["tables"]))] res_t = [] for i, t in enumerate(L["tables"]): r = dict(id=t["id"], seats=t["seats"], open_sides=list(sides[i])) b = best_stop(g, d_norm, sides[i], nw, S["stop_reach"], fp(t)) if p_norm is not None else None if b: r.update(category="robot", dist=round(b[0], 2), stop=[round(g.xs[b[2]], 3), round(g.ys[b[1]], 3)], side=b[3], path=trace(p_norm, g, b[1], b[2])) else: b = best_stop(g, d_pass, sides[i], pw, S["stop_reach"], fp(t)) if b: r.update(category="narrow", dist=round(b[0], 2), stop=[round(g.xs[b[2]], 3), round(g.ys[b[1]], 3)], side=b[3], path=trace(p_pass, g, b[1], b[2])) else: r.update(category="human") res_t.append(r) # 人が運ぶ卓:ふだんの道でロボットが行ける所(受け取る所)から、人が歩く距離 hum = [r for r in res_t if r["category"] == "human"] if hum: reach_cells = np.where(np.isfinite(d_norm).ravel() & f_hum.ravel())[0] if p_norm is not None else np.array([s0]) if len(reach_cells) == 0: reach_cells = np.array([s0]) d_h, p_h = g.run(f_hum, list(reach_cells)) for r in hum: i = [t["id"] for t in L["tables"]].index(r["id"]) b = best_stop(g, d_h, sides[i], hw, S["stop_reach"], fp(L["tables"][i])) if b is None: errs.append(("届かない卓", f"{r['id']} は人も運べない(通路がない)")) r.update(human_walk=None) else: r.update(human_walk=round(b[0], 2), stop=[round(g.xs[b[2]], 3), round(g.ys[b[1]], 3)], side=b[3], path=trace(p_h, g, b[1], b[2])) # 道の一番狭い所(ロボットの道の上の余裕×2) for r in res_t: if r.get("path") and r["category"] in ("robot", "narrow"): r["narrowest"] = round(min(2 * g.clear[int(y / res), int(x / res)] for x, y in r["path"]), 2) return res_t, errs def summarize(L, res_t): S, model = SETTINGS, ROBOT_MODELS[SETTINGS["model"]] cat = lambda c: [r for r in res_t if r["category"] == c] rob, nar, hum = cat("robot"), cat("narrow"), cat("human") dists = [r["dist"] for r in rob + nar] walks = [r["human_walk"] for r in hum if r.get("human_walk") is not None] return dict( name=L["name"], seats=sum(t["seats"] for t in L["tables"]), tables=len(L["tables"]), model=S["model"], pass_width=model["pass_width"], normal_width=S["normal_width"], robot_tables=len(rob), robot_seats=sum(r["seats"] for r in rob), narrow_tables=len(nar), narrow_seats=sum(r["seats"] for r in nar), human_tables=len(hum), human_seats=sum(r["seats"] for r in hum), robot_dist_mean=round(sum(dists) / len(dists), 1) if dists else None, robot_dist_max=max(dists) if dists else None, human_walk_total=round(sum(walks), 1) if walks else 0.0, human_walk_max=max(walks) if walks else None, ) # ================================================================ 描く INK, MUTED, BACK, SEAT, SOFA = gen.INK, gen.MUTED, gen.BACK, gen.SEAT, gen.SOFA ROBOT, DRINK, DISH, NG = gen.ROBOT, gen.DRINK, gen.DISH, gen.NG NARROW, HUMAN = "#b08800", "#7048e8" CAT_COLOR = {"robot": INK, "narrow": NARROW, "human": HUMAN} def draw_simple(ax, t): """記憶の店の家具:4人の角テーブル・丸テーブル・背中合わせのスツール席""" x, y, w, h = t["x"], t["y"], t["w"], t["h"] if t["type"] == "t4": ax.add_patch(Rectangle((x, y), w, h, fc=SEAT, ec=INK, lw=1.1, zorder=3)) elif t["type"] == "r4": ax.add_patch(Circle((x + w / 2, y + h / 2), w / 2, fc=SEAT, ec=INK, lw=1.1, zorder=3)) elif t["type"] == "long6": cx, cy = x + w / 2, y + h / 2 ax.add_patch(Rectangle((cx - 1.6, cy - 0.35), 3.2, 0.7, fc=SEAT, ec=INK, lw=1.1, zorder=3)) for dx in (-1.0, 0.0, 1.0): for dy in (-0.75, 0.75): ax.add_patch(Circle((cx + dx, cy + dy), 0.22, fc=SEAT, ec=INK, lw=0.9, zorder=3)) ax.text(x + w / 2, y + h / 2, str(t["seats"]), ha="center", va="center", fontsize=8, color=INK, zorder=5) def draw_lsofa_table(ax, t, ec): x, y, w, h = t["x"], t["y"], t["w"], t["h"] # 変形前の内側の角:x+0.55w〜x+w、y+0.45h〜y+h ox0, oy0, ox1, oy1 = x + 0.55 * w, y + 0.45 * h, x + w, y + h cx, cy = (ox0 + ox1) / 2, (oy0 + oy1) / 2 if t.get("flip"): cy = 2 * y + h - cy if t.get("mirror"): cx = 2 * x + w - cx ax.add_patch(Rectangle((cx - 0.375, cy - 0.6), 0.75, 1.2, fc=SEAT, ec=ec, lw=0.9, zorder=3.5)) def draw(ax, L, res_t, summ, conv): W, D = L["outer"]["w"], L["outer"]["d"] ax.set_xlim(-1.2, W + 1.2) ax.set_ylim(-2.3, D + 0.6) ax.set_aspect("equal") ax.axis("off") # 外壁と入口 e = L["entrance"] if L.get("outline"): pts = L["outline"] + [L["outline"][0]] for (xa, ya), (xb, yb) in zip(pts, pts[1:]): if e["side"] == "bottom" and ya == yb == 0: ax.plot([min(xa, xb), e["a0"]], [0, 0], color=INK, lw=3) ax.plot([e["a1"], max(xa, xb)], [0, 0], color=INK, lw=3) else: ax.plot([xa, xb], [ya, yb], color=INK, lw=3) edges = {} if L.get("outline") else {"bottom": ((0, 0), (W, 0)), "top": ((0, D), (W, D)), "left": ((0, 0), (0, D)), "right": ((W, 0), (W, D))} for side, (a, b) in edges.items(): if side != e["side"]: ax.plot([a[0], b[0]], [a[1], b[1]], color=INK, lw=3) elif side in ("bottom", "top"): ax.plot([0, e["a0"]], [a[1], a[1]], color=INK, lw=3) ax.plot([e["a1"], W], [a[1], a[1]], color=INK, lw=3) else: ax.plot([a[0], a[0]], [0, e["a0"]], color=INK, lw=3) ax.plot([a[0], a[0]], [e["a1"], D], color=INK, lw=3) m = (e["a0"] + e["a1"]) / 2 pos = {"bottom": (m, -0.5), "top": (m, D + 0.4), "left": (-0.7, m), "right": (W + 0.7, m)}[e["side"]] ax.text(*pos, "入口" if e["side"] in ("bottom", "top") else "入\n口", ha="center", va="center", fontsize=10, weight="bold") for r in L["rooms"]: if r["kind"] == "outside": continue fc = {"back": BACK, "guest": "#f8f9fa", "drink": "#d0ebff"}[r["kind"]] ec = DRINK if r["kind"] == "drink" else INK x0, y0, x1, y1 = r["rect"] ax.add_patch(Rectangle((x0, y0), x1 - x0, y1 - y0, fc=fc, ec=ec, lw=1.0, zorder=2)) tall = (y1 - y0) > (x1 - x0) * 1.6 text = "\n".join(r["label"]) if tall and len(r["label"]) <= 5 else r["label"] ax.text((x0 + x1) / 2, (y0 + y1) / 2, text, ha="center", va="center", fontsize=8 if len(r["label"]) > 5 else 9, color=DRINK if r["kind"] == "drink" else INK, zorder=5) for w in L["walls"]: x0, y0, x1, y1 = w["rect"] ax.add_patch(Rectangle((x0, y0), x1 - x0, y1 - y0, fc="#868e96", ec="#495057", lw=0.5, zorder=4)) for dz in L.get("toilet_doors", []): x0, y0, x1, y1 = dz ax.add_patch(Rectangle((x0, y0), x1 - x0, y1 - y0, fc="none", ec=MUTED, lw=0.8, ls=":", zorder=2)) for d in L["dish_up"]: x0, y0, x1, y1 = d["rect"] ax.add_patch(Rectangle((x0, y0), x1 - x0, y1 - y0, fc=DISH, ec=DISH, zorder=4)) # 道 for r in res_t: if r.get("path"): xs, ys = zip(*r["path"]) if r["category"] == "human": ax.plot(xs, ys, color=HUMAN, lw=1.0, ls=(0, (3, 2)), alpha=0.7, zorder=2.6) else: ax.plot(xs, ys, color=ROBOT if r["category"] == "robot" else NARROW, lw=0.9, alpha=0.35, zorder=2.5) for t, r in zip(L["tables"], res_t): ec = CAT_COLOR[r["category"]] if t["type"] == "booth6L": gen.draw_seat(ax, t, False, False) draw_lsofa_table(ax, t, INK) # 色は外形の枠で示す ax.add_patch(Rectangle((t["x"], t["y"]), t["w"], t["h"], fc="none", ec=ec, lw=1.6, zorder=3.6)) else: if t["type"] in ("t4", "r4", "long6"): draw_simple(ax, t) else: gen.draw_seat(ax, t, False, False) if r["category"] != "robot": ax.add_patch(Rectangle((t["x"], t["y"]), t["w"], t["h"], fc="none", ec=ec, lw=1.8, zorder=3.6)) if r.get("stop"): ax.add_patch(Circle(tuple(r["stop"]), 0.09, fc=CAT_COLOR[r["category"]] if r["category"] != "robot" else ROBOT, ec="white", lw=0.5, zorder=6)) if t["id"] in conv: ax.text(t["x"] + t["w"] - 0.1, t["y"] + t["h"] - 0.15, "?", fontsize=9, color=NG, weight="bold", zorder=7) sb = L["robot_standby"] x0, y0, x1, y1 = sb["rect"] ax.add_patch(Rectangle((x0, y0), x1 - x0, y1 - y0, fc="#fff4e6", ec=ROBOT, lw=1.4, zorder=5)) body = (ROBOT_MODELS[SETTINGS["model"]]["body_width"] or 0.5) / 2 for i in range(sb["slots"]): ax.add_patch(Circle((x0 + (x1 - x0) * (i + 0.5) / sb["slots"], (y0 + y1) / 2), body, fc=ROBOT, ec="white", lw=0.8, zorder=6)) ax.add_patch(Circle(tuple(L["start"]), 0.12, fc="white", ec=ROBOT, lw=1.5, zorder=6)) s = summ ax.text(0, -1.0, f'{L["name"]} {s["seats"]}席・{W:g}m×{D:g}m', fontsize=10.5, color=INK, va="center", weight="bold") ax.text(0, -1.45, f'機種 {s["model"]}(通れる幅 {s["pass_width"]*100:.0f}cm)・ふだん走らせる幅 {s["normal_width"]*100:.0f}cm ' f'ロボットが届く {s["robot_tables"]}卓・{s["robot_seats"]}席/狭い道なら届く {s["narrow_tables"]}卓・{s["narrow_seats"]}席/' f'人が運ぶ {s["human_tables"]}卓・{s["human_seats"]}席', fontsize=8.8, color=INK, va="center") walk = f' 人が運ぶ分の歩く距離 合計{s["human_walk_total"]}m・最長{s["human_walk_max"]}m' if s["human_tables"] else "" ok = "マス目2.5cmと1.25cmで同じ結果" if not conv else f'マス目で結果が変わる卓 {len(conv)}(?印)' ax.text(0, -1.85, f'受け渡し口の前(白丸)から止まる位置まで 平均{s["robot_dist_mean"]}m・最長{s["robot_dist_max"]}m{walk} / {ok}', fontsize=8.8, color=INK, va="center") ax.text(0, -2.2, '線:オレンジ=ロボット(ふだんの道) 黄土=ロボット(狭い道) 紫の点線=人が運ぶ道 点=止まる位置 寸法はすべて仮', fontsize=8, color=MUTED, va="center") # ================================================================ 出力 BUILDS = [("p0_memory", famires_p0.p0_memory), ("p1_efficient_corner", gen.p1_efficient_corner), ("p2_efficient_narrow", gen.p2_efficient_narrow), ("p3_relaxed_center", gen.p3_relaxed_center), ("p4_relaxed_side", gen.p4_relaxed_side), ("p5_crammed", gen.p5_crammed)] def prepare(L): for i, t in enumerate(L["tables"]): t["id"] = f"T{i + 1:02d}" d = L["dish_up"][0]["rect"] off = max(SETTINGS["normal_width"], ROBOT_MODELS[SETTINGS["model"]]["pass_width"]) / 2 + 0.05 L["start"] = [round((d[0] + d[2]) / 2, 3), round(d[1] - off, 3)] # 受け渡し口の前(通路の幅いっぱいに離れた所) return L def export(L, res_t, summ, conv, nm, out): meta = dict(schema_version=SCHEMA, units="m", coords="原点は店の外壁の内側の左下の角。x は右、y は奥(上)。Unity では x→X、y→Z、高さ→Y とする", furniture_types=FURNITURE_TYPES, robot_model=dict(name=SETTINGS["model"], **ROBOT_MODELS[SETTINGS["model"]]), settings=SETTINGS) layout = {k: v for k, v in L.items()} json.dump(dict(meta=meta, layout=layout), open(out / f"{nm}.json", "w", encoding="utf-8"), ensure_ascii=False, indent=1) slim = [{k: v for k, v in r.items() if k != "path"} | ({"path_end": r["path"][-1]} if r.get("path") else {}) for r in res_t] json.dump(dict(meta=meta, summary=summ, resolution_mismatch=conv, tables=slim), open(out / f"{nm}_analysis.json", "w", encoding="utf-8"), ensure_ascii=False, indent=1) def main(): if len(sys.argv) > 1: SETTINGS["model"] = sys.argv[1] # サイトのリポジトリの中なら public/sim/layouts/ に出す(サイトの試算が正。Unity はここを読む) base = HERE.parent.parent / "public" / "sim" / "layouts" if not base.parent.exists(): base = HERE / "variants3" out = base if SETTINGS["model"] == "BellaBot" else base / SETTINGS["model"].replace(" ", "_") out.mkdir(parents=True, exist_ok=True) allsum, failed = [], False for nm, fn in BUILDS: L = prepare(fn()) v = check_rules(L) try: res_a, err_a = analyze(L, SETTINGS["res"]) res_b, err_b = analyze(L, SETTINGS["check_res"]) except ValueError as ex: v.append(("出発点", str(ex))) res_a = err_a = err_b = None if res_a is not None: v += err_a + [e for e in err_b if e not in err_a] if v: failed = True print(f"[NG] {nm}: {L['name']}") for k, msg in v: print(f" - {k}: {msg}") allsum.append(dict(file=nm, name=L["name"], status="NG", violations=[f"{k}: {m}" for k, m in v])) continue conv = [a["id"] for a, b in zip(res_a, res_b) if a["category"] != b["category"]] summ = summarize(L, res_a) fig, ax = plt.subplots(figsize=(14, 11), dpi=120) draw(ax, L, res_a, summ, conv) fig.savefig(out / f"{nm}.png", bbox_inches="tight", facecolor="white") plt.close(fig) export(L, res_a, summ, conv, nm, out) allsum.append(dict(file=nm, status="OK", resolution_mismatch=conv, **summ)) print(f"[OK] {nm}: {summ} マス目の差: {conv}") json.dump(allsum, open(out / "summary.json", "w", encoding="utf-8"), ensure_ascii=False, indent=1) if failed: sys.exit(1) if __name__ == "__main__": main()