Download globmp/tests/test_core.py from GlobalMotionPlanning/GlobMP: direct link, hf CLI and curl.
- Browser
- Download file 8.5 kB
-
https://huggingface.co/GlobalMotionPlanning/GlobMP/resolve/main/globmp/tests/test_core.py
- Command line
-
hf download hf://GlobalMotionPlanning/GlobMP/globmp/tests/test_core.py
-
curl -L -o test_core.py https://huggingface.co/GlobalMotionPlanning/GlobMP/resolve/main/globmp/tests/test_core.py
8.5 kB
| """Fast checks of the core package (about 30 s on one CPU core). Run: python -m pytest globmp/tests | |
| or python globmp/tests/test_core.py""" | |
| import os, sys | |
| import numpy as np | |
| import torch | |
| sys.path.insert(0, os.path.join(os.path.dirname(os.path.abspath(__file__)), '..', '..')) | |
| from globmp import Problem, init_waypoints, is_feasible, block_minima, spline | |
| from globmp import cone | |
| torch.set_num_threads(1) | |
| rng = np.random.default_rng(0) | |
| def test_s_map_matches_evaluation(): | |
| d = 5; Q = torch.as_tensor(rng.normal(size=(d + 1, d + 1)), dtype=spline.DTYPE); Q = Q + Q.T | |
| s = torch.linspace(0, 1, 50, dtype=spline.DTYPE) | |
| b = spline.bernstein_basis_eval(d, s); direct = torch.einsum('is,ij,js->s', b, Q, b) | |
| via = spline.S_map(Q, d) @ spline.bernstein_basis_eval(2 * d, s) | |
| assert float((direct - via).abs().max()) < 1e-10 | |
| def test_elevation_preserves_polynomial(): | |
| c = torch.as_tensor(rng.normal(size=6), dtype=spline.DTYPE); s = torch.linspace(0, 1, 40, dtype=spline.DTYPE) | |
| lo = c @ spline.bernstein_basis_eval(5, s); hi = (spline.elev_mat(5, 11) @ c) @ spline.bernstein_basis_eval(11, s) | |
| assert float((lo - hi).abs().max()) < 1e-12 | |
| def test_cone_projection(): | |
| d = 6 | |
| for _ in range(10): | |
| g = torch.as_tensor(rng.normal(size=(2, d + 1)), dtype=spline.DTYPE) | |
| pi = spline.S_map(g.T @ g, d).unsqueeze(0) # nonnegative polynomial: in K | |
| d2, tau = cone.dist2_and_tau(pi, d) | |
| assert float(d2) < 1e-20 | |
| pn = pi - 0.5 * float(pi.abs().max()) # pushed negative: outside K | |
| d2, tau = cone.dist2_and_tau(pn, d) | |
| vals = tau @ spline.bernstein_basis_eval(2 * d, torch.linspace(0, 1, 2001, dtype=spline.DTYPE)) | |
| # inexact by design: the Frank-Wolfe inner solve stops at a relative tolerance (cone.FW_TOL = 1e-6) | |
| assert float(d2) > 0 and float(vals.min()) > -10 * cone.FW_TOL * float(pn.norm()) | |
| def _one_disc(): | |
| p = Problem(n=2, d=7, k=3, ell=3, M=2, start=[0., 0.], goal=[6., 0.], delta=0.005, whiten=True) | |
| p.add_sphere([3.0, -0.5], 1.0) | |
| return p, init_waypoints(p, np.array([[0., 0.], [3., 1.2], [6., 0.]])) | |
| def test_restoration_from_infeasible_start(): | |
| p, _ = _one_disc() | |
| Z0 = init_waypoints(p, np.array([[0., 0.], [3., 0.], [6., 0.]])) # straight line through the disc | |
| assert not is_feasible(p, Z0) | |
| Z, _, ok = p.project(Z0, p.tolvec()) | |
| assert ok and is_feasible(p, Z, tol=1e-9) | |
| def test_descent_is_monotone_and_feasible(): | |
| p, Z0 = _one_disc(); tv = p.tolvec() | |
| Z, _, ok = p.solve(Z0, tv, blocks=150) | |
| costs = [c for c, _ in p.hist] | |
| assert ok and is_feasible(p, Z, tol=1e-9) | |
| assert all(b <= a + 1e-12 for a, b in zip(costs, costs[1:])) | |
| def test_repair_is_the_nearest_point_of_the_inner_set(): | |
| """Eq. (5) on one disc. From a feasible z with Y = the obstacle-free optimum (a straight line through the disc): | |
| the repaired w is feasible on the whole interval, satisfies <Y - w, z - w> <= 0 (z lies in the inner set C(z), so | |
| this is the projection inequality), and is cheaper than z. A feasible Y comes back unchanged, and at the | |
| solution of the problem the repair returns the solution itself.""" | |
| p, Z0 = _one_disc(); tv = p.tolvec() | |
| z, _, ok = p.project(Z0, tv); assert ok and is_feasible(p, z) | |
| Y = (z - (1 / p.beta) * p.cost_grad(z)).detach(); assert not is_feasible(p, Y) | |
| w, okw = p.repair(Y, z, tv) | |
| assert okw and is_feasible(p, w) | |
| assert float(block_minima(p, w, inflated=True).min()) >= -p.repair_tol * float(tv.sqrt().max()) | |
| assert float(((Y - w) * (z - w)).sum()) <= 1e-9 and float(p.cost(w)) < float(p.cost(z)) | |
| assert float((w - Y).norm()) <= float((z - Y).norm()) | |
| w0, ok0 = p.repair(z, z, tv); assert ok0 and float((w0 - z).abs().max()) == 0.0 | |
| Zs, _, oks = p.solve(Z0, tv, blocks=150); assert oks | |
| ws, okf = p.repair((Zs - (1 / p.beta) * p.cost_grad(Zs)).detach(), Zs, tv) | |
| assert okf and float((ws - Zs).norm()) <= 1e-5 * float(Zs.norm()) | |
| assert p.repair_log['fallbacks'] == 0 | |
| def test_repair_on_every_block_family(): | |
| """Gradient projection with the repair, each block family active in turn: the result is feasible on the whole interval, | |
| the accepted costs do not rise and no repair is left unfinished.""" | |
| Cc = torch.zeros(2, 2, 8, dtype=spline.DTYPE); Cc[:, 0, :] = 3.0 | |
| Cc[0, 1, :] = torch.linspace(-0.9, -0.5, 8, dtype=spline.DTYPE); Cc[1, 1, :] = torch.linspace(-0.5, -0.9, 8, dtype=spline.DTYPE) | |
| disc = lambda q: q.add_sphere([3.0, -0.5], 1.0) | |
| cases = {'moving sphere': lambda q: q.add_moving(Cc, 1.0), | |
| 'ellipsoid': lambda q: q.add_ellipsoid([3.0, -0.5], np.diag([1 / 1.2 ** 2, 1.0])), | |
| 'super-ellipse': lambda q: q.add_superellipse([3.0, -0.5], [1.0, 1.0]), | |
| 'half-space': lambda q: (disc(q), q.add_halfspace([0.0, -1.0], -0.6)), | |
| 'box': lambda q: (disc(q), q.add_box([-1.0, -0.9], [7.0, 3.0])), | |
| 'speed limit': lambda q: (disc(q), q.add_speed(5.3))} # the unconstrained peak speed is 5.9 | |
| for name, add in cases.items(): | |
| q = Problem(n=2, d=7, k=3, ell=3, M=2, start=[0., 0.], goal=[6., 0.], delta=0.005, whiten=True); add(q) | |
| Z, _, ok = q.solve(init_waypoints(q, np.array([[0., 0.], [3., 1.2], [6., 0.]])), q.tolvec(), blocks=150) | |
| costs = [c for c, _ in q.hist] | |
| assert ok and len(costs) > 0 and is_feasible(q, Z, tol=1e-9), name | |
| assert all(b <= a + 1e-12 for a, b in zip(costs, costs[1:])), name | |
| assert q.repair_log['fallbacks'] == 0, name | |
| def test_certificate_on_one_disc(): | |
| p, Z0 = _one_disc(); tv = p.tolvec() | |
| Z, _, ok = p.solve(Z0, tv, blocks=300); Z, _ = p.polish(Z, tv, iters=20) | |
| Zf, rep = p.kkt_finish(Z) | |
| assert rep['kkt_point'] and rep['certified'] and rep['lam_min_rel'] > 0.1 | |
| assert float(block_minima(p, Zf).min()) > -1e-9 | |
| def test_init_against_enumeration(): | |
| """INIT (globmp.init) on random state sets against listing every curve, per label, for both rules.""" | |
| import itertools | |
| from globmp.init import init | |
| class Toy: | |
| n_pieces = 4; n_labels = 2 | |
| def __init__(self, seed): | |
| r = np.random.default_rng(seed); self.ns = [1, 6, 5, 6, 1] | |
| self.w = [r.integers(1, 9, size=(a, b)).astype(float) for a, b in zip(self.ns[:-1], self.ns[1:])] | |
| self.ok = [r.random((a, b)) < 0.6 for a, b in zip(self.ns[:-1], self.ns[1:])] | |
| self.flip = r.random((self.ns[2], self.ns[3])) < 0.5 # piece 2 sets the label | |
| self.tg = [np.array([min(sum(self.w[i][c[k], c[k + 1]] for k, i in enumerate(range(j, 4))) | |
| for c in itertools.product(*[[s] if q == j else range(n) for q, n in list(enumerate(self.ns))[j:]])) | |
| for s in range(self.ns[j])]) for j in range(5)] | |
| def n_states(self, j): return self.ns[j] | |
| def cost(self, i, s, V): return V[:, None] + self.w[i][s] | |
| def free(self, i, s): return self.ok[i][s] | |
| def togo(self, j): return self.tg[j] | |
| def label(self, i, s, lab): return lab[:, None] | self.flip[s] if i == 2 else lab[:, None] | |
| class ToyPairs(Toy): # the piece test given pair by pair | |
| def free_pairs(self, i, s, t): return self.ok[i][s, t] | |
| for seed in range(20): | |
| t = Toy(seed); tp = ToyPairs(seed); best = {} | |
| for c in itertools.product(*[range(n) for n in t.ns]): | |
| if all(t.ok[i][c[i], c[i + 1]] for i in range(4)): | |
| f = sum(t.w[i][c[i], c[i + 1]] for i in range(4)); l = int(t.flip[c[2], c[3]]) | |
| if l not in best or f < best[l]: best[l] = f | |
| U = min(best.values()) * 1.5 if best else 10.0 | |
| want = {l: f for l, f in best.items() if f <= U} | |
| for rule in ('togo', 'budget'): | |
| for ties, inst in (('first', t), ('state', t), ('first', tp), ('state', tp)): | |
| r = init(inst, U, rule=rule, ties=ties, chunk=7) | |
| assert {l: v[0] for l, v in r['curves'].items()} == want | |
| for l, (f, path) in r['curves'].items(): | |
| assert all(t.ok[i][path[i], path[i + 1]] for i in range(4)) and int(t.flip[path[2], path[3]]) == l | |
| assert sum(t.w[i][path[i], path[i + 1]] for i in range(4)) == f | |
| if __name__ == '__main__': | |
| for name, f in list(globals().items()): | |
| if name.startswith('test_'): | |
| f(); print('ok', name, flush=True) | |