508 lines
22 KiB
Python
508 lines
22 KiB
Python
#!/usr/bin/env python3
|
|
"""World mo phong tu MOT ban do that (DB RTAB-Map cua vslam_cpp): tuong + mat dat.
|
|
|
|
De chay lai test doc (--slope-test) tren chinh con doc that khi khong dua duoc
|
|
robot ra hien truong. Moi thu lay tu DB:
|
|
|
|
* mat dat = z do cua tung node (userData, ghi khi slope.enabled), noi suy
|
|
Gauss quanh node (SIGMA, xa node thi rong dan) thanh luoi tam giac TRES
|
|
phu CA khung ban do -- o sim khong co dia hinh la san z = 0, de ho thi
|
|
mep vung da biet thanh mot bac dung;
|
|
* tuong = o BI CHIEM cua luoi 2D (log-odds tu luoi cuc bo tung node + pose
|
|
toi uu, cung GridGlobal/* voi slam.yaml), dung cao WALL_H tu mat dat. Bo
|
|
hai loai tuong GIA:
|
|
- tia LiDAR cham MAT DAT: o ma mat dat nho cao hon mat phang duoi robot
|
|
(cua node nhin thay o do) qua LIDAR_H - GROUND_TOL -- chan doc nhin tu
|
|
duoi, chan doc nhin tu tren khi dang xuong;
|
|
- o trong vong ROBOT_R + 5 cm quanh duong robot DA DI (chac chan trong);
|
|
* goi y diem dat robot: dinh doan doc lon nhat, theo pose node that.
|
|
|
|
Frame world = frame ban do, nen sai so so voi ground truth cua sim co nghia.
|
|
Sim chay tren BAN SAO cua DB trong thu muc ra (localization co the ghi DB).
|
|
|
|
Gioi han: anh camera sim khong giong anh that -> dinh vi lai bang LiDAR (KHONG
|
|
--slam-reloc-vpr); khong co nguoi / do vat di dong; vat thap duoi tam LiDAR
|
|
khong co; mat dat chi dung doc theo duong robot da di (ngang ra thi keo dai).
|
|
|
|
Chay tu goc repo (in ra lenh sim day du):
|
|
|
|
python3 tools/gen_world_from_db.py resources/maps/real_YYYYMMDD_HHMMSS.db \\
|
|
--preview logs/real_YYYYMMDD_HHMMSS_world.png
|
|
"""
|
|
import argparse
|
|
import math
|
|
import os
|
|
import re
|
|
import shutil
|
|
import sqlite3
|
|
import struct
|
|
import zlib
|
|
|
|
import numpy as np
|
|
|
|
import gen_slope_world as base
|
|
|
|
RES = 0.05 # o luoi 2D, bang Grid/CellSize
|
|
TRES = 0.20 # o luoi mat dat
|
|
SIGMA = 0.5 # noi suy z: do rong Gauss quanh node gan nhat, m
|
|
WALL_H = 2.0 # tuong cao bao nhieu tren mat dat
|
|
LIDAR_H = 0.2165 # tam LiDAR tren san: robot.yaml laser_link z 0.13 + wheel_radius 0.0865
|
|
GROUND_TOL = 0.08 # dat nho hon mat phang robot >= LIDAR_H - cai nay: tia cham DAT
|
|
ROBOT_R = 0.24 # robot.yaml robot_radius
|
|
SLOPE_DEG = 3.0 # mat dat doc hon cai nay la doc
|
|
PAD = 1.0 # le quanh khung ban do, m
|
|
MAX_GAP = 1.0 # hai node lien tiep xa hon (RGBD/LinearUpdate 0.1) = dut duong
|
|
|
|
|
|
def mat(blob):
|
|
"""Blob nen cua RTAB-Map: zlib + 12 byte (rows, cols, type) -> (bytes, so kenh)."""
|
|
typ = struct.unpack('3i', blob[-12:])[2]
|
|
return zlib.decompress(blob[:-12]), (typ >> 3) + 1
|
|
|
|
|
|
def grid_params(root):
|
|
"""GridGlobal/* cua slam.yaml (thieu thi mac dinh RTAB-Map)."""
|
|
p = {'ProbHit': 0.7, 'ProbMiss': 0.4, 'ProbClampingMin': 0.1192, 'ProbClampingMax': 0.971}
|
|
path = os.path.join(root, 'configuration_files', 'slam.yaml')
|
|
text = open(path).read() if os.path.exists(path) else ''
|
|
for k in p:
|
|
m = re.search(r'GridGlobal/%s:\s*"?([0-9.]+)' % k, text)
|
|
if m:
|
|
p[k] = float(m.group(1))
|
|
return p
|
|
|
|
|
|
def logit(p):
|
|
return math.log(p / (1.0 - p))
|
|
|
|
|
|
def connect(db):
|
|
return sqlite3.connect('file:%s?mode=ro' % db, uri=True).cursor()
|
|
|
|
|
|
def load(db):
|
|
"""-> ids tang dan, pose {id: 3x4}, do {id: (z, roll, pitch)}, nguon pose."""
|
|
c = connect(db)
|
|
row = c.execute('select opt_ids, opt_poses from Admin').fetchone()
|
|
if row is not None and row[0] is not None and row[1] is not None:
|
|
ids = np.frombuffer(mat(row[0])[0], dtype=np.int32)
|
|
P = np.frombuffer(mat(row[1])[0], dtype=np.float32).reshape(-1, 3, 4)
|
|
pose = {int(i): P[k].astype(np.float64) for k, i in enumerate(ids)}
|
|
src = 'pose toi uu (Admin)'
|
|
else:
|
|
pose = {int(i): np.frombuffer(b, dtype=np.float32).reshape(3, 4).astype(np.float64)
|
|
for i, b in c.execute('select id, pose from Node where pose is not null')}
|
|
src = 'pose ODOM (bang Node) -- DB chua co pose toi uu: node bi tat ngang?'
|
|
tilt = {}
|
|
for nid, ud in c.execute('select id, user_data from Data where user_data is not null'):
|
|
if nid not in pose:
|
|
continue
|
|
try:
|
|
raw, _ = mat(ud)
|
|
except (zlib.error, struct.error):
|
|
continue
|
|
if len(raw) >= 24:
|
|
tilt[nid] = struct.unpack_from('3d', raw)
|
|
return sorted(pose), pose, tilt, src
|
|
|
|
|
|
def cells(db, pose):
|
|
"""Luoi cuc bo tung node, theo id (= theo thoi gian, nhu RTAB-Map ghep):
|
|
-> (id, o trong xy, o chiem xy) trong frame ban do. Doc dan, khong giu
|
|
het trong RAM -- ban do lon co hang chuc trieu o trong."""
|
|
for nid, em, ob in connect(db).execute(
|
|
'select id, empty_cells, obstacle_cells from Data order by id'):
|
|
if nid not in pose or (em is None and ob is None):
|
|
continue
|
|
T = pose[nid]
|
|
out = []
|
|
for blob in (em, ob):
|
|
if blob is None:
|
|
out.append(np.zeros((0, 2)))
|
|
continue
|
|
raw, ch = mat(blob)
|
|
q = np.frombuffer(raw, dtype=np.float32).reshape(-1, ch)[:, :2].astype(np.float64)
|
|
out.append(q @ T[:2, :2].T + T[:2, 3])
|
|
yield nid, out[0], out[1]
|
|
|
|
|
|
def bilinear(G, x0, y0, step):
|
|
"""Ham lay mau song tuyen luoi G (goc (x0, y0), buoc step) tai (x, y)."""
|
|
TH, TW = G.shape
|
|
|
|
def f(x, y):
|
|
fx = np.clip((np.asarray(x, float) - x0) / step, 0, TW - 1 - 1e-9)
|
|
fy = np.clip((np.asarray(y, float) - y0) / step, 0, TH - 1 - 1e-9)
|
|
i, j = fx.astype(int), fy.astype(int)
|
|
ax, ay = fx - i, fy - j
|
|
return ((1 - ay) * ((1 - ax) * G[j, i] + ax * G[j, i + 1])
|
|
+ ay * ((1 - ax) * G[j + 1, i] + ax * G[j + 1, i + 1]))
|
|
return f
|
|
|
|
|
|
def dilate(mask, r):
|
|
"""O True lan thanh hinh tron ban kinh r o (khong vong qua mep nhu np.roll)."""
|
|
H, W = mask.shape
|
|
out = mask.copy()
|
|
for dy in range(-r, r + 1):
|
|
for dx in range(-r, r + 1):
|
|
if dx * dx + dy * dy > r * r:
|
|
continue
|
|
out[max(dy, 0):H + min(dy, 0), max(dx, 0):W + min(dx, 0)] |= \
|
|
mask[max(-dy, 0):H - max(dy, 0), max(-dx, 0):W - max(dx, 0)]
|
|
return out
|
|
|
|
|
|
def path_mask(xy, keep, x0, y0, H, W):
|
|
"""O luoi duong robot di qua: noi cac node lien tiep cung `keep`, cach < MAX_GAP."""
|
|
pts = [xy[keep]]
|
|
for k in range(len(xy) - 1):
|
|
if not (keep[k] and keep[k + 1]):
|
|
continue
|
|
a, b = xy[k], xy[k + 1]
|
|
d = math.hypot(*(b - a))
|
|
if RES / 2 < d < MAX_GAP:
|
|
t = np.linspace(0.0, 1.0, int(d / (RES / 2)) + 2)[1:-1, None]
|
|
pts.append(a + t * (b - a))
|
|
p = np.concatenate(pts)
|
|
m = np.zeros((H, W), bool)
|
|
m[((p[:, 1] - y0) / RES).astype(int).clip(0, H - 1),
|
|
((p[:, 0] - x0) / RES).astype(int).clip(0, W - 1)] = True
|
|
return m
|
|
|
|
|
|
def terrain_obj(header, gx, gy, Z):
|
|
"""Luoi do cao -> OBJ dung chung dinh (nho hon nhieu so voi Obj.quad)."""
|
|
TH, TW = Z.shape
|
|
lines = ['# ' + l for l in header.splitlines()]
|
|
for j in range(TH):
|
|
lines.extend('v %.3f %.3f %.4f' % (gx[i], gy[j], Z[j, i]) for i in range(TW))
|
|
for j in range(TH - 1):
|
|
for i in range(TW - 1):
|
|
a = j * TW + i + 1 # nguoc kim dong ho nhin tu tren: mat huong LEN
|
|
lines.append('f %d %d %d' % (a, a + 1, a + TW + 1))
|
|
lines.append('f %d %d %d' % (a, a + TW + 1, a + TW))
|
|
return '\n'.join(lines) + '\n'
|
|
|
|
|
|
def fill_gaps(occ):
|
|
"""Lap khe <= 2 o (10 cm) giua hai doan tuong thang hang (ngang, doc, cheo).
|
|
Luoi 'lan nhin moi nhat thang' xoa o tuong ma tia sau suot qua, nen tuong
|
|
that thanh net dut -- trong sim tia LiDAR lot qua khe. Chi lap o nam GIUA
|
|
hai o chiem, khong noi rong dam (nguoi da roi di khong quay lai)."""
|
|
H, W = occ.shape
|
|
|
|
def shift(m, dy, dx): # out[y, x] = m[y - dy, x - dx], ngoai mep = False
|
|
out = np.zeros_like(m)
|
|
out[max(dy, 0):H + min(dy, 0), max(dx, 0):W + min(dx, 0)] = \
|
|
m[max(-dy, 0):H - max(dy, 0), max(-dx, 0):W - max(dx, 0)]
|
|
return out
|
|
fill = np.zeros_like(occ)
|
|
for dy, dx in ((0, 1), (1, 0), (1, 1), (1, -1)):
|
|
a1, a2 = shift(occ, dy, dx), shift(occ, 2 * dy, 2 * dx)
|
|
b1, b2 = shift(occ, -dy, -dx), shift(occ, -2 * dy, -2 * dx)
|
|
fill |= (a1 & b1) | (a1 & b2) | (a2 & b1)
|
|
return occ | fill
|
|
|
|
|
|
def local_rtabmap_version(root):
|
|
"""Ban RTAB-Map ma build may nay link: build/CMakeCache.txt -> RTABMapConfigVersion.cmake."""
|
|
try:
|
|
cache = open(os.path.join(root, 'build', 'CMakeCache.txt')).read()
|
|
d = re.search(r'^RTABMap_DIR:PATH=(.+)$', cache, re.M).group(1).strip()
|
|
cfg = open(os.path.join(d, 'RTABMapConfigVersion.cmake')).read()
|
|
return re.search(r'set\(PACKAGE_VERSION "([0-9.]+)"\)', cfg).group(1)
|
|
except (OSError, AttributeError):
|
|
return None
|
|
|
|
|
|
def vtuple(v):
|
|
return tuple(int(x) for x in re.findall(r'\d+', v))
|
|
|
|
|
|
def wall_rects(occ):
|
|
"""Gop o chiem thanh hinh chu nhat: doan lien tiep tren hang, keo dai xuong
|
|
cac hang co dung doan do. -> [(i0, j0, i1, j1)] (bao gom hai dau)."""
|
|
H = occ.shape[0]
|
|
rects, opened = [], {}
|
|
for j in range(H + 1):
|
|
cur = set()
|
|
if j < H:
|
|
d = np.diff(np.concatenate(([0], occ[j].astype(np.int8), [0])))
|
|
cur = set(zip(np.nonzero(d == 1)[0].tolist(), (np.nonzero(d == -1)[0] - 1).tolist()))
|
|
for key in [k for k in opened if k not in cur]:
|
|
rects.append((key[0], opened.pop(key), key[1], j - 1))
|
|
for key in cur:
|
|
opened.setdefault(key, j)
|
|
return rects
|
|
|
|
|
|
def slope_runs(xy, zz, steep):
|
|
"""Doan doc tren quy dao: node lien tiep cung doc, chenh z >= 0.2 m.
|
|
-> [(k dau, k cuoi, chenh z, dai)]."""
|
|
runs, k = [], 0
|
|
while k < len(xy):
|
|
if not steep[k]:
|
|
k += 1
|
|
continue
|
|
e = k
|
|
while e + 1 < len(xy) and steep[e + 1] and math.hypot(*(xy[e + 1] - xy[e])) < MAX_GAP:
|
|
e += 1
|
|
dz = float(zz[k:e + 1].max() - zz[k:e + 1].min())
|
|
length = float(np.hypot(*np.diff(xy[k:e + 1], axis=0).T).sum()) if e > k else 0.0
|
|
if dz >= 0.2:
|
|
runs.append((k, e, dz, length))
|
|
k = e + 1
|
|
return runs
|
|
|
|
|
|
def walk_out(xy, k, step, dist):
|
|
"""Tu node k di theo quy dao (step = +1 / -1) toi khi duoc `dist` m hoac dut."""
|
|
s = 0.0
|
|
while 0 <= k + step < len(xy):
|
|
d = math.hypot(*(xy[k + step] - xy[k]))
|
|
if d >= MAX_GAP:
|
|
break
|
|
s += d
|
|
k += step
|
|
if s >= dist:
|
|
break
|
|
return k
|
|
|
|
|
|
def preview(path, occ, seen, ground, cleared, xy, zz, runs, spawn, x0, y0):
|
|
import cv2
|
|
H, W = occ.shape
|
|
img = np.full((H, W, 3), 128, np.uint8)
|
|
img[seen] = (255, 255, 255)
|
|
img[ground] = (0, 140, 255) # cam: tia cham dat (bo)
|
|
img[cleared] = (255, 200, 0) # xanh: tren duong da di (bo)
|
|
img[occ] = (0, 0, 0)
|
|
span = max(float(zz.max() - zz.min()), 1e-3)
|
|
col = cv2.applyColorMap(((zz - zz.min()) / span * 255).astype(np.uint8).reshape(-1, 1),
|
|
cv2.COLORMAP_JET).reshape(-1, 3)
|
|
px = ((xy - (x0, y0)) / RES).astype(int)
|
|
for (u, v), c in zip(px, col):
|
|
cv2.circle(img, (int(u), int(v)), 2, tuple(int(t) for t in c), -1)
|
|
for k, e, _, _ in runs:
|
|
cv2.polylines(img, [px[k:e + 1].reshape(-1, 1, 2).astype(np.int32)], False, (0, 0, 255), 1)
|
|
if spawn is not None:
|
|
sx, sy, syaw = spawn
|
|
u, v = int((sx - x0) / RES), int((sy - y0) / RES)
|
|
cv2.circle(img, (u, v), 8, (0, 200, 0), 2)
|
|
cv2.line(img, (u, v), (int(u + 16 * math.cos(syaw)), int(v + 16 * math.sin(syaw))), (0, 200, 0), 2)
|
|
cv2.imwrite(path, img[::-1]) # y len tren
|
|
print('anh xem truoc:', path, '(den = tuong, cam = tia cham dat da bo, xanh = bo tren duong '
|
|
'da di, cham = node theo z xanh->do, do = doan doc, vong xanh la = diem dat)')
|
|
|
|
|
|
def main():
|
|
here = os.path.dirname(os.path.abspath(__file__))
|
|
ap = argparse.ArgumentParser(description=__doc__.splitlines()[0])
|
|
ap.add_argument('db', help='DB ban do that, vd resources/maps/real_YYYYMMDD_HHMMSS.db')
|
|
ap.add_argument('--name', help='ten world (mac dinh: ten DB)')
|
|
ap.add_argument('--out', help='thu muc ra (mac dinh: <thu muc DB>/sim_<ten> -- da gitignore)')
|
|
ap.add_argument('--root', default=os.path.dirname(here), help='goc repo (doc slam.yaml)')
|
|
ap.add_argument('--preview', help='ghi anh PNG xem truoc tuong / mat dat / doc')
|
|
a = ap.parse_args()
|
|
name = a.name or os.path.splitext(os.path.basename(a.db))[0]
|
|
out = os.path.abspath(a.out or os.path.join(os.path.dirname(os.path.abspath(a.db)), 'sim_' + name))
|
|
terrain, walls = 'vslam_terrain_' + name, 'vslam_walls_' + name
|
|
|
|
ids, pose, tilt, src = load(a.db)
|
|
if not ids:
|
|
raise SystemExit('DB khong co node nao')
|
|
xy = np.array([pose[i][:2, 3] for i in ids])
|
|
yaw = np.array([math.atan2(pose[i][1, 0], pose[i][0, 0]) for i in ids])
|
|
zz = np.array([tilt[i][0] if i in tilt else 0.0 for i in ids])
|
|
print('%d node, %s; %d node co z do (userData), z %.2f .. %.2f m'
|
|
% (len(ids), src, len(tilt), zz.min(), zz.max()))
|
|
if not tilt:
|
|
print(' !! khong node nao co z (slope.enabled tat luc quet?) -> mat dat PHANG')
|
|
|
|
# z hai LUOT qua cung mot cho (cach >= 30 node): lech = troi z cua ban do.
|
|
lech = []
|
|
idx = np.arange(len(ids))
|
|
for k in range(len(ids)):
|
|
m = (np.hypot(xy[:, 0] - xy[k, 0], xy[:, 1] - xy[k, 1]) < 0.3) & (np.abs(idx - k) > 30)
|
|
if m.any():
|
|
lech.append(float(np.abs(zz[m] - zz[k]).max()))
|
|
if lech:
|
|
print(' z giua cac luot qua cung cho (%d node): trung vi %.1f cm, 95%% %.1f cm, max %.1f cm'
|
|
% (len(lech), 100 * np.median(lech), 100 * np.percentile(lech, 95), 100 * max(lech)))
|
|
|
|
# Luot 1 qua DB: khung ban do (node + moi o da thay).
|
|
lo_xy, hi_xy = xy.min(0), xy.max(0)
|
|
n_grids = 0
|
|
for _, em, ob in cells(a.db, pose):
|
|
n_grids += 1
|
|
for p in (em, ob):
|
|
if len(p):
|
|
lo_xy, hi_xy = np.minimum(lo_xy, p.min(0)), np.maximum(hi_xy, p.max(0))
|
|
if not n_grids:
|
|
raise SystemExit('DB khong co luoi cuc bo nao (obstacle_cells / empty_cells)')
|
|
x0, y0 = lo_xy - PAD
|
|
x1, y1 = hi_xy + PAD
|
|
|
|
# ---------------- Mat dat: Gauss quanh node, phu ca khung ----------------
|
|
TW = int(math.ceil((x1 - x0) / TRES)) + 1
|
|
TH = int(math.ceil((y1 - y0) / TRES)) + 1
|
|
gx = x0 + np.arange(TW) * TRES
|
|
gy = y0 + np.arange(TH) * TRES
|
|
Z = np.empty((TH, TW))
|
|
for j in range(TH): # tung hang: (TW x so node) -- vua bo nho
|
|
d2 = (gx[:, None] - xy[None, :, 0]) ** 2 + (gy[j] - xy[None, :, 1]) ** 2
|
|
dmin = d2.min(1, keepdims=True)
|
|
# Rong SIGMA sat node, rong dan khi xa (sigma^2 + (d/2)^2): xa duong di
|
|
# khong thanh bac o duong chia giua hai node khac z.
|
|
w = np.exp(-(d2 - dmin) / (2.0 * SIGMA ** 2 + 0.5 * dmin))
|
|
Z[j] = (w @ zz) / w.sum(1)
|
|
zt = bilinear(Z, x0, y0, TRES)
|
|
dzy, dzx = np.gradient(Z, TRES)
|
|
zn = zt(xy[:, 0], xy[:, 1])
|
|
gxn = bilinear(dzx, x0, y0, TRES)(xy[:, 0], xy[:, 1])
|
|
gyn = bilinear(dzy, x0, y0, TRES)(xy[:, 0], xy[:, 1])
|
|
steep = np.degrees(np.arctan(np.hypot(gxn, gyn))) > SLOPE_DEG
|
|
print('mat dat %dx%d o %.1f m, z %.2f .. %.2f m; %d node tren doc > %.0f do'
|
|
% (TW, TH, TRES, Z.min(), Z.max(), int(steep.sum()), SLOPE_DEG))
|
|
|
|
# ---------------- Luoi 2D: log-odds nhu slam.yaml, bo tia cham dat ----------------
|
|
gp = grid_params(a.root)
|
|
lh, lm = logit(gp['ProbHit']), logit(gp['ProbMiss'])
|
|
lo, hi = logit(gp['ProbClampingMin']), logit(gp['ProbClampingMax'])
|
|
W = int(math.ceil((x1 - x0) / RES))
|
|
H = int(math.ceil((y1 - y0) / RES))
|
|
L = np.zeros((H, W))
|
|
seen = np.zeros((H, W), bool)
|
|
ground = np.zeros((H, W), bool)
|
|
k_of = {nid: k for k, nid in enumerate(ids)}
|
|
n_obs = n_ground = 0
|
|
for nid, em, ob in cells(a.db, pose): # luot 2 qua DB
|
|
k = k_of[nid]
|
|
if len(ob):
|
|
# Tia ngang song song mat dat duoi robot, cao LIDAR_H: o nao mat dat
|
|
# nho len gan toi do la tia cham DAT, khong phai tuong.
|
|
plane = zn[k] + gxn[k] * (ob[:, 0] - xy[k, 0]) + gyn[k] * (ob[:, 1] - xy[k, 1])
|
|
g = zt(ob[:, 0], ob[:, 1]) - plane > LIDAR_H - GROUND_TOL
|
|
n_obs += len(ob)
|
|
if g.any():
|
|
n_ground += int(g.sum())
|
|
ground[((ob[g, 1] - y0) / RES).astype(int).clip(0, H - 1),
|
|
((ob[g, 0] - x0) / RES).astype(int).clip(0, W - 1)] = True
|
|
ob = ob[~g]
|
|
for pts, d in ((em, lm), (ob, lh)):
|
|
if not len(pts):
|
|
continue
|
|
flat = np.unique(((pts[:, 1] - y0) / RES).astype(int).clip(0, H - 1) * W
|
|
+ ((pts[:, 0] - x0) / RES).astype(int).clip(0, W - 1))
|
|
L.flat[flat] = np.clip(L.flat[flat] + d, lo, hi)
|
|
seen.flat[flat] = True
|
|
occ = seen & (L > 0)
|
|
ground &= ~occ # o con chiem nho node khac nhin thay that
|
|
n_log = int(occ.sum())
|
|
occ |= fill_gaps(occ) & ~ground
|
|
|
|
near = dilate(path_mask(xy, np.ones(len(xy), bool), x0, y0, H, W),
|
|
int(math.ceil((ROBOT_R + 0.05) / RES)))
|
|
cleared = occ & near
|
|
occ &= ~near
|
|
print('luoi %dx%d o %.2f m: %d o tuong (log-odds %d + lap khe %d - tren duong da di %d); '
|
|
'bo %d/%d lan thay la tia cham dat'
|
|
% (W, H, RES, int(occ.sum()), n_log, int((occ | cleared).sum()) - n_log,
|
|
int(cleared.sum()), n_ground, n_obs))
|
|
if steep.any():
|
|
sl = dilate(path_mask(xy, steep, x0, y0, H, W), int(round(0.6 / RES)))
|
|
print(' con %d o tuong cach duong DOC <= 0.6 m (tuong / lan can that, hoac tuong gia sot)'
|
|
% int((occ & sl).sum()))
|
|
|
|
# ---------------- Doan doc + diem dat robot ----------------
|
|
runs = slope_runs(xy, zz, steep)
|
|
for n, (k, e, dz, length) in enumerate(runs):
|
|
print('doc #%d: node %d..%d, dai %.1f m, z %.2f -> %.2f (chenh %.2f m, ~%.1f do)'
|
|
% (n, ids[k], ids[e], length, zz[k], zz[e], dz,
|
|
math.degrees(math.atan2(dz, max(length, 1e-6)))))
|
|
spawn = None
|
|
if runs:
|
|
k, e, _, _ = max(runs, key=lambda r: r[2])
|
|
top, step = (e, +1) if zz[e] > zz[k] else (k, -1)
|
|
s = walk_out(xy, top, step, 1.0) # lui ~1 m ra mat bang tren
|
|
spawn = (float(xy[s, 0]), float(xy[s, 1]), float(yaw[s]))
|
|
print('dat robot o DINH doc lon nhat (node %d, z %.2f m): --x %.2f --y %.2f --yaw %.3f'
|
|
% (ids[s], zz[s], spawn[0], spawn[1], spawn[2]))
|
|
else:
|
|
print('!! khong thay doan doc nao (chenh >= 0.2 m) -- --slope-test se bao khong co doc')
|
|
|
|
# ---------------- Ghi model + world + ban sao DB ----------------
|
|
tag = 'tu %s. Sinh boi tools/gen_world_from_db.py -- dung sua tay.' % os.path.basename(a.db)
|
|
w = base.Obj('Tuong (o chiem luoi 2D), cao %.1f m tren mat dat, %s Z-UP, met.' % (WALL_H, tag))
|
|
rects = wall_rects(occ)
|
|
for i0, j0, i1, j1 in rects:
|
|
bx0, bx1 = x0 + i0 * RES, x0 + (i1 + 1) * RES
|
|
by0, by1 = y0 + j0 * RES, y0 + (j1 + 1) * RES
|
|
f = zt(*np.meshgrid(np.linspace(bx0, bx1, max(2, int((bx1 - bx0) / TRES) + 2)),
|
|
np.linspace(by0, by1, max(2, int((by1 - by0) / TRES) + 2))))
|
|
w.box(bx0, by0, float(f.min()) - 0.05, bx1, by1, float(f.max()) + WALL_H)
|
|
print('tuong: %d hop' % len(rects))
|
|
|
|
models = os.path.join(out, 'models')
|
|
for mname, mesh, text, desc in (
|
|
(terrain, 'terrain.obj', terrain_obj('Mat dat (z node) %s Z-UP, met.' % tag, gx, gy, Z),
|
|
'Mat dat tu z node ban do that.'),
|
|
(walls, 'walls.obj', w.text(), 'Tuong tu luoi 2D ban do that.')):
|
|
base.write(os.path.join(models, mname, 'meshes', mesh), text)
|
|
base.write(os.path.join(models, mname, 'model.sdf'), base.SDF.format(name=mname, mesh=mesh))
|
|
base.write(os.path.join(models, mname, 'model.config'),
|
|
base.CONFIG.format(name=mname, desc=desc).replace('gen_slope_world', 'gen_world_from_db'))
|
|
hint = ('--x %.2f --y %.2f --yaw %.3f' % spawn) if spawn else '(khong co doc)'
|
|
world_path = os.path.join(out, name + '.world')
|
|
base.write(world_path, ''.join([
|
|
'<?xml version="1.0" ?>\n',
|
|
'<!-- World %s\n Frame world = frame ban do. Dinh doc lon nhat: %s -->\n' % (tag, hint),
|
|
'<sdf version="1.6">\n <world name="%s">\n' % name,
|
|
' <include><uri>model://ground_plane</uri></include>\n',
|
|
' <include><uri>model://sun</uri></include>\n',
|
|
base.include(terrain + '_1', terrain, 0, 0, 0, 0),
|
|
base.include(walls + '_1', walls, 0, 0, 0, 0),
|
|
' </world>\n</sdf>\n']))
|
|
|
|
# Ban sao DB: localization co the ghi vao DB, giu ban that nguyen ven. Chep
|
|
# lai moi khi ban sao khac ban goc (ca sau mot lan sim da ghi vao no).
|
|
db_copy = os.path.join(out, name + '.db')
|
|
st = os.stat(a.db)
|
|
if (not os.path.exists(db_copy) or os.stat(db_copy).st_size != st.st_size
|
|
or int(os.stat(db_copy).st_mtime) != int(st.st_mtime)):
|
|
shutil.copy2(a.db, db_copy)
|
|
print('chep DB ->', db_copy)
|
|
# DB tu Jetson (RTAB-Map 0.23) ma may nay link ban cu hon (0.21) thi RTAB-Map
|
|
# tu choi mo ("Opened database version ... is more recent"). Schema 0.23 =
|
|
# 0.21 + hai cot 0.21 khong doc (Admin.dictionary_index, Data.depth_confidence),
|
|
# nen ha chuoi version cua BAN SAO la du -- 08/10: rtabmap-info + vslam_node
|
|
# 0.21.13 nap va dinh vi lai binh thuong tren DB 0.23.12.
|
|
local = local_rtabmap_version(a.root)
|
|
con = sqlite3.connect(db_copy)
|
|
ver = con.execute('select version from Admin').fetchone()[0]
|
|
if local and vtuple(ver) > vtuple(local):
|
|
con.execute('update Admin set version = ?', (local,))
|
|
con.commit()
|
|
print('ban sao DB: version %s -> %s (RTAB-Map cua build nay)' % (ver, local))
|
|
con.close()
|
|
|
|
if a.preview:
|
|
preview(a.preview, occ, seen, ground, cleared, xy, zz, runs, spawn, x0, y0)
|
|
|
|
root = os.path.abspath(a.root)
|
|
rel = lambda p: os.path.relpath(p, root) if p.startswith(root + os.sep) else p
|
|
maps = os.path.join(root, 'resources', 'maps')
|
|
db_arg = os.path.relpath(db_copy, maps) if db_copy.startswith(maps + os.sep) else db_copy
|
|
mp = rel(models) if os.path.isabs(rel(models)) else '$PWD/' + rel(models)
|
|
print('\nChay sim (tu goc repo; dinh vi lai CHI bang LiDAR -- anh sim khac anh that):\n'
|
|
' export GAZEBO_MODEL_PATH=$PWD/resources/models:%s\n'
|
|
' ./build/app/vslam_node --sim --sim-gl --world %s %s --token t --port 8092 \\\n'
|
|
' --slam --slam-db %s --slam-mode localization --slam-reloc --slam-reloc-auto \\\n'
|
|
' --slope-test 2>&1 | tee logs/sim_%s.log'
|
|
% (mp, rel(world_path), hint, db_arg, name))
|
|
|
|
|
|
if __name__ == '__main__':
|
|
main()
|