tarzanagh commited on
Commit
e3f79b0
·
verified ·
1 Parent(s): 073f2e4

INIT in one run (Algorithm 3 as printed): best-first over the pairs with an exact piece test and a stop at the first obstacle-free completion that passes; no budget, no known feasible curve; gridstart.start uses it; the layered form is kept as init

Browse files
globmp/gridstart/README.md CHANGED
@@ -16,8 +16,8 @@ four route classes.
16
 
17
  | file | content |
18
  |---|---|
19
- | `../init.py` | INIT (Algorithm 3), the package's one implementation: shortest path over the joints for given per-joint state sets |
20
- | `instance.py` | the instance, the chart of free control points, the cost, the exact test of one piece; `GridStates` hands INIT the grid values per joint, the piece cost and the piece test (`grid_start`); `RestStates` and `start`: the two-run start |
21
  | `plain_grid.py` | the plain grid (`plain_grid`), for comparison |
22
  | `exact_repair.py` | the exact repair step (5) as a semidefinite program (Clarabel), and GlobMP with that repair |
23
  | `run.py` | sanity checks, `E*_N`, one job per `(N, h)`, summary table |
@@ -60,25 +60,28 @@ Results go to `results/gridstart` (or `--out`, or `$GLOBMP_GRIDSTART_OUT`).
60
 
61
  Counts are deterministic; times depend on the machine.
62
 
63
- ## The start in two runs of INIT
64
 
65
- Algorithm 3 takes the candidates and an optional budget `U`, and returns the cheapest feasible candidate curve
66
- with cost at most `U`, or none. `instance.start` computes the start of Theorem 1 with two runs:
67
-
68
- 1. INIT with no budget on few candidates: joint positions on a grid (`--h0`, default 0.25) with zero velocity at
69
- the joints, so every piece is a straight move (`RestStates`).
70
- 2. GlobMP with the exact repair from that curve gives a feasible curve `z0`.
71
- 3. INIT on the grid of spacing `h` with the budget `U = f(z0)`. The start is the grid point it returns, or `z0`
72
- if it returns none.
73
 
74
  ```bash
75
- python -m globmp.gridstart.run start --N 2 3 4 --h 0.5 0.25 --procs 6 # 5 s; reference/start.json
76
  ```
77
 
78
- The start is feasible and costs no more than `z0` and no more than any feasible grid point. In the six runs
79
- above step 3 returns none (no grid point costs at most `f(z0)`) after 1 to 3,476 piece tests, and the start `z0`
80
- costs `E*_N` to 1e-9. For comparison, the grid point `z_h` alone costs 1.16 to 2.49 times `E*_N` at `h = 0.25`,
81
- and at `h = 0.5` there is no feasible grid point within `4 E*_N` for N = 4.
 
 
 
 
 
82
 
83
  ## Limits
84
 
 
16
 
17
  | file | content |
18
  |---|---|
19
+ | `../init.py` | INIT (Algorithm 3): `init_best_first`, the search as printed, and `init`, its layered form with a budget |
20
+ | `instance.py` | the instance, the chart of free control points, the cost, the exact test of one piece; `GridStates` hands INIT the grid values per joint, the piece cost and the piece test (`grid_start`); `start`: Algorithm 3 as printed |
21
  | `plain_grid.py` | the plain grid (`plain_grid`), for comparison |
22
  | `exact_repair.py` | the exact repair step (5) as a semidefinite program (Clarabel), and GlobMP with that repair |
23
  | `run.py` | sanity checks, `E*_N`, one job per `(N, h)`, summary table |
 
60
 
61
  Counts are deterministic; times depend on the machine.
62
 
63
+ ## Algorithm 3 as printed: one run, no budget
64
 
65
+ `globmp.init.init_best_first` takes the pairs of grid values at consecutive joints in increasing order of
66
+ (cost so far + piece cost + obstacle-free cost of the rest), tests a piece when its pair is taken, and, when a grid
67
+ value is reached, also tests the obstacle-free optimal completion from it. It stops at the first completion that
68
+ passes. This is A* with an exact piece test and an early stop. It needs no budget and no known feasible curve; the
69
+ curve it returns is feasible and costs no more than any feasible grid point, which is what Theorem 1 needs of its
70
+ start. `instance.start` runs it on the grid inside the box of `{f <= 4 E*_N}`.
 
 
71
 
72
  ```bash
73
+ python -m globmp.gridstart.run start --N 2 3 4 --h 0.5 0.375 0.25 --procs 9 # 4 s; reference/start.json
74
  ```
75
 
76
+ | pieces N | h | piece tests + completion pieces | layered INIT, budget 4 E*_N | start / E*_N | GlobMP from the start / E*_N |
77
+ |---|---|---|---|---|---|
78
+ | 2 | 0.25 | 5,244 + 184 | 254,288 | 1.16 | 1.0000 |
79
+ | 3 | 0.25 | 414 + 102 | 45,446 | 1.11 | 1.0000 |
80
+ | 4 | 0.25 | 194 + 198 | 10,144 | 1.48 | 1.0000 |
81
+
82
+ In the nine runs the start costs no more than the cheapest feasible grid point wherever that point is known, and
83
+ GlobMP with the exact repair reaches `E*_N` from it in seven. In the other two (N = 3 and N = 4 at `h = 0.5`) the
84
+ start lies in the other route class and GlobMP ends 16% above `E*_N`: the spacing is too coarse there.
85
 
86
  ## Limits
87
 
globmp/gridstart/instance.py CHANGED
@@ -11,7 +11,7 @@ Time scale: the package gives every piece unit duration, so cost(total duration
11
 
12
  Contents: the program (`build`), the chart, the cost as a quadratic (`Quad`), the exact test of one piece
13
  (`pieces_free`), what INIT needs (`GridStates`: the grid values per joint, the piece cost, the piece test; `grid_start`
14
- calls globmp.init), the two-run start of Algorithm 3 (`RestStates`, `start`), route classes, and the exact rational
15
  check of a whole curve.
16
  """
17
  import math
@@ -23,7 +23,7 @@ import torch
23
  from .. import Problem, DT
24
  from .. import spline as bern
25
  from ..check import block_minima
26
- from ..init import init
27
 
28
  torch.set_num_threads(1)
29
 
@@ -236,49 +236,27 @@ class GridStates:
236
 
237
  def togo(self, j): return self.q.togo(j, self.T[j])
238
 
239
-
240
- class RestStates(GridStates):
241
- """Candidates of the first run: the joint positions on the grid h0 Z^2 inside the box `lim` = (x_lo, x_hi,
242
- y_lo, y_hi), with zero velocity at every joint (a_j = Q_j, c0 = START, a_N = GOAL). Every piece is then a
243
- straight move between two joint positions. Same piece cost and piece test as GridStates."""
244
-
245
- def __init__(self, N, h0, lim=(0.0, 10.0, -3.0, 3.0)):
246
- self.q = Quad(N); self.N = self.n_pieces = N; self.root_fallback = 0; self._piece = (None,)
247
- Q = lattice([math.ceil(lim[0] / h0), math.ceil(lim[2] / h0)], [math.floor(lim[1] / h0), math.floor(lim[3] / h0)], h0)
248
- self.T = [START[None, :].copy()] + [np.concatenate([Q, Q], 1) for _ in range(N - 1)] + [GOAL[None, :].copy()]
249
-
250
-
251
- def states_to_x(g, path):
252
- N = g.N; x = np.zeros(4 * N)
253
- for j in range(N + 1): x[idx_joint(j, N)] = g.T[j][path[j]]
254
- return x
255
-
256
-
257
- def start(N, h, h0=0.25, descend=None):
258
- """The start of Theorem 1 as Algorithm 3 computes it, in two runs of INIT (globmp.init):
259
- 1. INIT on the candidates RestStates(N, h0); `descend` (GlobMP with the exact repair) from its curve gives a
260
- feasible curve z0 of cost f(z0);
261
- 2. INIT on the grid of spacing h with the budget U = f(z0): it returns the cheapest feasible grid point
262
- if one costs at most f(z0), otherwise none; the start is that grid point, or z0.
263
- descend: x (4N,) -> (x, cost) of a feasible curve no dearer than x (None: z0 is the curve of run 1 itself).
264
- Returns (x, cost, info): x is feasible and costs no more than z0 and no more than any feasible grid point."""
265
- t0 = time.time(); g0 = RestStates(N, h0); r0 = init(g0)
266
- info = dict(N=N, h=h, h0=h0, run1=dict(states=[g0.n_states(j) for j in range(N + 1)], time=r0['time'],
267
- tests=sum(l['tested'] for l in r0['layers'])))
268
- if not r0['curves']:
269
- return None, None, dict(info, fail='no feasible candidate in the first run', time=time.time() - t0)
270
- c0, path = r0['curves'][0]; x0 = states_to_x(g0, path); info['run1'].update(cost=c0, x=x0.tolist())
271
- xz, cz = (x0, c0) if descend is None else descend(x0)
272
- info['z0'] = dict(cost=float(cz), x=np.asarray(xz).tolist())
273
- g = GridStates(N, h, cz); r = init(g, float(cz))
274
- if r['curves']: cost, path = r['curves'][0]; x = states_to_x(g, path)
275
- else: cost, x = float(cz), np.asarray(xz)
276
- info['run2'] = dict(returned='grid point' if r['curves'] else 'none', start='grid point' if r['curves'] else 'z0',
277
- cost=float(cost), time=r['time'],
278
- states=[g.n_states(j) for j in range(N + 1)], tests=sum(l['tested'] for l in r['layers']),
279
- box=[(int(a), int(b)) for a, b in zip(g.lo, g.hi)])
280
- info['time'] = time.time() - t0
281
- return x, float(cost), info
282
 
283
 
284
  def grid_start(N, h, U, rule='togo', improve_only=True):
 
11
 
12
  Contents: the program (`build`), the chart, the cost as a quadratic (`Quad`), the exact test of one piece
13
  (`pieces_free`), what INIT needs (`GridStates`: the grid values per joint, the piece cost, the piece test; `grid_start`
14
+ calls the layered form, `start` Algorithm 3 as printed, both in globmp.init), route classes, and the exact rational
15
  check of a whole curve.
16
  """
17
  import math
 
23
  from .. import Problem, DT
24
  from .. import spline as bern
25
  from ..check import block_minima
26
+ from ..init import init, init_best_first
27
 
28
  torch.set_num_threads(1)
29
 
 
236
 
237
  def togo(self, j): return self.q.togo(j, self.T[j])
238
 
239
+ def completion(self, j, t):
240
+ """The obstacle-free optimal completion from state t at joint j < N (it attains togo): (all its pieces pass
241
+ the exact test, the curve x with zeros before joint j, number of pieces tested)."""
242
+ N = self.N; c, gs, Hss, gr, Hrs, Hrr_i = self.q.togo_data[j]; S = self.T[j][t]
243
+ sj = idx_joint(j, N); r = list(range(sj[-1] + 1, 4 * N)); x = np.zeros(4 * N); x[sj] = S; x[r] = -Hrr_i @ (gr + Hrs @ S)
244
+ C = ctrl(x, N)[j:]; ok, nfb = pieces_free(C); self.root_fallback += nfb
245
+ return bool(ok.all()), x, len(C)
246
+
247
+
248
+ def start(N, h, U):
249
+ """The start of Theorem 1 by ONE run of INIT (globmp.init.init_best_first) on the grid of spacing h inside the
250
+ bounding box of {f <= U}: a feasible curve that costs no more than any feasible grid point (of cost <= U).
251
+ Returns (x, cost, info), or (None, None, info) when no feasible curve of cost <= U is found."""
252
+ t0 = time.time(); g = GridStates(N, h, U); r = init_best_first(g, U * (1 + 1e-12))
253
+ info = dict(N=N, h=h, U=U, states=[g.n_states(j) for j in range(N + 1)], time=time.time() - t0)
254
+ if r is None: return None, None, dict(info, fail=True)
255
+ x = np.zeros(4 * N) if r['tail'] is None else np.array(r['tail'], float)
256
+ for j, t in enumerate(r['path']): x[idx_joint(j, N)] = g.T[j][t]
257
+ info.update(tests=r['tests'], completion_tests=r['completion_tests'], closed=r['closed'], joint=r['joint'],
258
+ ends='grid point' if r['tail'] is None else f"completion from joint {r['joint']}", time=time.time() - t0)
259
+ return x, r['cost'], info
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
260
 
261
 
262
  def grid_start(N, h, U, rule='togo', improve_only=True):
globmp/gridstart/reference/start.json CHANGED
@@ -2,91 +2,163 @@
2
  "N2_h0.25": {
3
  "N": 2,
4
  "h": 0.25,
5
- "h0": 0.25,
6
- "run1_cost": 687.0,
7
- "run1_tests": 1572,
8
- "z0_cost": 12.330473175721181,
9
- "run2_returned": "none",
10
- "run2_tests": 3476,
11
- "start": "z0",
12
- "start_cost": 12.330473175721181,
 
13
  "start_certified": true,
14
- "globmp_final": 12.330473175327825,
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
15
  "E_star": 12.33047317470573
16
  },
17
  "N2_h0.5": {
18
  "N": 2,
19
  "h": 0.5,
20
- "h0": 0.25,
21
- "run1_cost": 687.0,
22
- "run1_tests": 1572,
23
- "z0_cost": 12.330473181107209,
24
- "run2_returned": "none",
25
- "run2_tests": 57,
26
- "start": "z0",
27
- "start_cost": 12.330473181107209,
 
28
  "start_certified": true,
29
- "globmp_final": 12.330473181108118,
 
 
30
  "E_star": 12.33047317470573
31
  },
32
  "N3_h0.25": {
33
  "N": 3,
34
  "h": 0.25,
35
- "h0": 0.25,
36
- "run1_cost": 441.0,
37
- "run1_tests": 562625,
38
- "z0_cost": 3.5540533765947657,
39
- "run2_returned": "none",
40
- "run2_tests": 290,
41
- "start": "z0",
42
- "start_cost": 3.5540533765947657,
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
43
  "start_certified": true,
44
- "globmp_final": 3.554053376593629,
 
 
45
  "E_star": 3.5540533765934015
46
  },
47
  "N3_h0.5": {
48
  "N": 3,
49
  "h": 0.5,
50
- "h0": 0.25,
51
- "run1_cost": 441.0,
52
- "run1_tests": 562625,
53
- "z0_cost": 3.554053376594311,
54
- "run2_returned": "none",
55
- "run2_tests": 8,
56
- "start": "z0",
57
- "start_cost": 3.554053376594311,
 
58
  "start_certified": true,
59
- "globmp_final": 3.554053376593629,
 
 
60
  "E_star": 3.5540533765934015
61
  },
62
  "N4_h0.25": {
63
  "N": 4,
64
  "h": 0.25,
65
- "h0": 0.25,
66
- "run1_cost": 333.0,
67
- "run1_tests": 1510750,
68
- "z0_cost": 1.5046976748556062,
69
- "run2_returned": "none",
70
- "run2_tests": 44,
71
- "start": "z0",
72
- "start_cost": 1.5046976748556062,
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
73
  "start_certified": true,
74
- "globmp_final": 1.5046976746684777,
 
 
75
  "E_star": 1.504697674656427
76
  },
77
  "N4_h0.5": {
78
  "N": 4,
79
  "h": 0.5,
80
- "h0": 0.25,
81
- "run1_cost": 333.0,
82
- "run1_tests": 1510750,
83
- "z0_cost": 1.504697674620047,
84
- "run2_returned": "none",
85
- "run2_tests": 1,
86
- "start": "z0",
87
- "start_cost": 1.504697674620047,
 
88
  "start_certified": true,
89
- "globmp_final": 1.5046976746184555,
 
 
90
  "E_star": 1.504697674656427
91
  }
92
  }
 
2
  "N2_h0.25": {
3
  "N": 2,
4
  "h": 0.25,
5
+ "piece_tests": 5244,
6
+ "completion_pieces": 184,
7
+ "states_reached": 130,
8
+ "ends": "completion from joint 1",
9
+ "time_s": 2.43,
10
+ "start_cost": 14.25,
11
+ "start_over_E": 1.1556734115631437,
12
+ "cheapest_grid_point": 14.25,
13
+ "layered_tests_budget_4E": 254288,
14
  "start_certified": true,
15
+ "globmp_final": 12.330473181153593,
16
+ "globmp_over_E": 1.000000000522921,
17
+ "globmp_class": "pp",
18
+ "E_star": 12.33047317470573
19
+ },
20
+ "N2_h0.375": {
21
+ "N": 2,
22
+ "h": 0.375,
23
+ "piece_tests": 641,
24
+ "completion_pieces": 68,
25
+ "states_reached": 42,
26
+ "ends": "completion from joint 1",
27
+ "time_s": 0.18,
28
+ "start_cost": 15.9375,
29
+ "start_over_E": 1.2925294734587793,
30
+ "cheapest_grid_point": 16.5,
31
+ "layered_tests_budget_4E": 24505,
32
+ "start_certified": true,
33
+ "globmp_final": 12.330473175802126,
34
+ "globmp_over_E": 1.0000000000889175,
35
+ "globmp_class": "pp",
36
  "E_star": 12.33047317470573
37
  },
38
  "N2_h0.5": {
39
  "N": 2,
40
  "h": 0.5,
41
+ "piece_tests": 195,
42
+ "completion_pieces": 44,
43
+ "states_reached": 27,
44
+ "ends": "completion from joint 1",
45
+ "time_s": 0.05,
46
+ "start_cost": 18.75,
47
+ "start_over_E": 1.520622909951505,
48
+ "cheapest_grid_point": 21.0,
49
+ "layered_tests_budget_4E": 4307,
50
  "start_certified": true,
51
+ "globmp_final": 12.330473174664576,
52
+ "globmp_over_E": 0.9999999999966623,
53
+ "globmp_class": "pp",
54
  "E_star": 12.33047317470573
55
  },
56
  "N3_h0.25": {
57
  "N": 3,
58
  "h": 0.25,
59
+ "piece_tests": 414,
60
+ "completion_pieces": 102,
61
+ "states_reached": 39,
62
+ "ends": "completion from joint 1",
63
+ "time_s": 0.56,
64
+ "start_cost": 3.9609375,
65
+ "start_over_E": 1.1144845280282767,
66
+ "cheapest_grid_point": 4.5,
67
+ "layered_tests_budget_4E": 45446,
68
+ "start_certified": true,
69
+ "globmp_final": 3.554053376594311,
70
+ "globmp_over_E": 1.0000000000002558,
71
+ "globmp_class": "pp",
72
+ "E_star": 3.5540533765934015
73
+ },
74
+ "N3_h0.375": {
75
+ "N": 3,
76
+ "h": 0.375,
77
+ "piece_tests": 106,
78
+ "completion_pieces": 69,
79
+ "states_reached": 28,
80
+ "ends": "completion from joint 1",
81
+ "time_s": 0.09,
82
+ "start_cost": 6.10546875,
83
+ "start_over_E": 1.7178888730850064,
84
+ "cheapest_grid_point": 8.0625,
85
+ "layered_tests_budget_4E": 2988,
86
  "start_certified": true,
87
+ "globmp_final": 3.5540533773894367,
88
+ "globmp_over_E": 1.0000000002239795,
89
+ "globmp_class": "pp",
90
  "E_star": 3.5540533765934015
91
  },
92
  "N3_h0.5": {
93
  "N": 3,
94
  "h": 0.5,
95
+ "piece_tests": 52,
96
+ "completion_pieces": 54,
97
+ "states_reached": 22,
98
+ "ends": "completion from joint 1",
99
+ "time_s": 0.03,
100
+ "start_cost": 7.96875,
101
+ "start_over_E": 2.2421582220687224,
102
+ "cheapest_grid_point": 12.0,
103
+ "layered_tests_budget_4E": 367,
104
  "start_certified": true,
105
+ "globmp_final": 4.128390380190922,
106
+ "globmp_over_E": 1.1616005565307599,
107
+ "globmp_class": "mm",
108
  "E_star": 3.5540533765934015
109
  },
110
  "N4_h0.25": {
111
  "N": 4,
112
  "h": 0.25,
113
+ "piece_tests": 194,
114
+ "completion_pieces": 198,
115
+ "states_reached": 64,
116
+ "ends": "completion from joint 1",
117
+ "time_s": 1.4,
118
+ "start_cost": 2.2222222222226264,
119
+ "start_over_E": 1.4768562879118123,
120
+ "cheapest_grid_point": 3.75,
121
+ "layered_tests_budget_4E": 10144,
122
+ "start_certified": true,
123
+ "globmp_final": 1.5046976754624666,
124
+ "globmp_over_E": 1.0000000005356822,
125
+ "globmp_class": "pp",
126
+ "E_star": 1.504697674656427
127
+ },
128
+ "N4_h0.375": {
129
+ "N": 4,
130
+ "h": 0.375,
131
+ "piece_tests": 21,
132
+ "completion_pieces": 55,
133
+ "states_reached": 16,
134
+ "ends": "completion from joint 1",
135
+ "time_s": 0.06,
136
+ "start_cost": 2.3611111111115406,
137
+ "start_over_E": 1.5691598059063006,
138
+ "cheapest_grid_point": 5.8125,
139
+ "layered_tests_budget_4E": 462,
140
  "start_certified": true,
141
+ "globmp_final": 1.5046976746987184,
142
+ "globmp_over_E": 1.0000000000281064,
143
+ "globmp_class": "pp",
144
  "E_star": 1.504697674656427
145
  },
146
  "N4_h0.5": {
147
  "N": 4,
148
  "h": 0.5,
149
+ "piece_tests": 20,
150
+ "completion_pieces": 43,
151
+ "states_reached": 12,
152
+ "ends": "completion from joint 1",
153
+ "time_s": 0.03,
154
+ "start_cost": 4.4444444444450255,
155
+ "start_over_E": 2.9537125758234732,
156
+ "cheapest_grid_point": null,
157
+ "layered_tests_budget_4E": null,
158
  "start_certified": true,
159
+ "globmp_final": 1.7480567593997876,
160
+ "globmp_over_E": 1.1617328775356337,
161
+ "globmp_class": "mm",
162
  "E_star": 1.504697674656427
163
  }
164
  }
globmp/gridstart/run.py CHANGED
@@ -6,9 +6,8 @@
6
  plain grid when it is small enough, then GlobMP with the exact repair from z_h
7
  (--first-order: also the released Algorithms 1-2 from z_h)
8
  summary table of all jobs (markdown on stdout, summary.json in the output directory)
9
- start the start as Algorithm 3 computes it (instance.start): INIT on joint positions with zero velocity,
10
- GlobMP with the exact repair from its curve (z0), INIT on the grid with the budget f(z0); the start is
11
- the returned grid point, or z0 if none is returned; then GlobMP from the start
12
 
13
  python -m globmp.gridstart.run check
14
  python -m globmp.gridstart.run optimum --procs 4
@@ -177,25 +176,21 @@ def stage_summary(a):
177
 
178
 
179
  def start_job(args):
180
- N, h, h0, out = args; t0 = time.time()
181
- def descend(x):
182
- p = build(N, whiten=True); Ze, info = exact_descent(p, G_to_Z(p, x_to_G(x, N)))
183
- xz = Z_to_x(p, Ze, N); return xz, float(Quad(N).f(xz))
184
- x, cost, info = start(N, h, h0=h0, descend=descend)
185
- res = dict(info, cost=cost)
186
  if x is not None:
187
  p = build(N); Z = G_to_Z(p, x_to_G(x, N))
188
- res['start'] = {k: v for k, v in finish(p, Z).items() if k != 'x'}
189
  res['exact'] = descend_exact((N, x_to_G(x, N), False))
190
- f = os.path.join(out, 'optimum.json')
191
- if os.path.exists(f): res['E_star'] = json.load(open(f))[str(N)]['E_star']
192
  res['time_total'] = time.time() - t0
193
  json.dump(res, open(os.path.join(out, f'start_N{N}_h{h}.json'), 'w'), indent=1, default=float)
194
- r1, r2, E = res.get('run1', {}), res.get('run2', {}), res.get('E_star')
195
- print(f"N={N} h={h}: run 1 cost {r1.get('cost')} ({r1.get('tests')} tests, {r1.get('time', 0):.1f}s) | z0 {res.get('z0', {}).get('cost')} | "
196
- f"run 2 returns {r2.get('returned')} ({r2.get('tests')} tests, {r2.get('time', 0):.2f}s) | start = {r2.get('start')}, cost {cost} | "
197
- f"GlobMP from the start -> {res.get('exact', {}).get('final_cost')} {res.get('exact', {}).get('side')}"
198
- + (f" | E* {E}" if E else '') + f" | {res['time_total']:.0f}s", flush=True)
199
  return res
200
 
201
 
@@ -209,13 +204,12 @@ def main():
209
  ap.add_argument('--out', default=OUT)
210
  ap.add_argument('--first-order', action='store_true', help='also run the released Algorithms 1-2 from z_h')
211
  ap.add_argument('--T', type=int, default=6000, help='iteration cap of the first-order run')
212
- ap.add_argument('--h0', type=float, default=0.25, help='spacing of the joint positions in the first run (stage start)')
213
  a = ap.parse_args(); os.makedirs(a.out, exist_ok=True)
214
  if a.stage == 'check': stage_check(a)
215
  elif a.stage == 'optimum': stage_optimum(a)
216
  elif a.stage == 'summary': stage_summary(a)
217
  elif a.stage == 'start':
218
- with Pool(a.procs, maxtasksperchild=1) as pool: pool.map(start_job, [(N, h, a.h0, a.out) for N in a.N for h in a.h], chunksize=1)
219
  else:
220
  jobs = [(N, h, a.Ufac, a.out, a.first_order, a.T) for N in a.N for h in a.h if not os.path.exists(os.path.join(a.out, f'job_N{N}_h{h}.json'))]
221
  with Pool(a.procs, maxtasksperchild=1) as pool: pool.map(job, jobs, chunksize=1)
 
6
  plain grid when it is small enough, then GlobMP with the exact repair from z_h
7
  (--first-order: also the released Algorithms 1-2 from z_h)
8
  summary table of all jobs (markdown on stdout, summary.json in the output directory)
9
+ start Algorithm 3 as printed (instance.start, one run of globmp.init.init_best_first on the grid inside
10
+ the box of {f <= Ufac E*_N}), then GlobMP with the exact repair from the start
 
11
 
12
  python -m globmp.gridstart.run check
13
  python -m globmp.gridstart.run optimum --procs 4
 
176
 
177
 
178
  def start_job(args):
179
+ N, h, Ufac, out = args; t0 = time.time()
180
+ Es = json.load(open(os.path.join(out, 'optimum.json')))[str(N)]['E_star']; U = Ufac * Es
181
+ x, cost, info = start(N, h, U); res = dict(info, cost=cost, E_star=Es)
182
+ f = os.path.join(out, f'job_N{N}_h{h}.json')
183
+ if os.path.exists(f): res['zh_cost'] = json.load(open(f))['init_togo']['cost'] # cheapest feasible grid point
 
184
  if x is not None:
185
  p = build(N); Z = G_to_Z(p, x_to_G(x, N))
186
+ res['start'] = {k: v for k, v in finish(p, Z).items() if k != 'x'}; res['x'] = x.tolist()
187
  res['exact'] = descend_exact((N, x_to_G(x, N), False))
 
 
188
  res['time_total'] = time.time() - t0
189
  json.dump(res, open(os.path.join(out, f'start_N{N}_h{h}.json'), 'w'), indent=1, default=float)
190
+ e = res.get('exact', {})
191
+ print(f"N={N} h={h}: INIT {res.get('tests')} piece tests + {res.get('completion_tests')} completion pieces, {res.get('time', 0):.2f}s, "
192
+ f"{res.get('ends')} | start cost {cost} (grid optimum {res.get('zh_cost')}, E* {Es}) certified {res.get('start', {}).get('cert')} | "
193
+ f"GlobMP -> {e.get('final_cost')} {e.get('side')} | {res['time_total']:.0f}s", flush=True)
 
194
  return res
195
 
196
 
 
204
  ap.add_argument('--out', default=OUT)
205
  ap.add_argument('--first-order', action='store_true', help='also run the released Algorithms 1-2 from z_h')
206
  ap.add_argument('--T', type=int, default=6000, help='iteration cap of the first-order run')
 
207
  a = ap.parse_args(); os.makedirs(a.out, exist_ok=True)
208
  if a.stage == 'check': stage_check(a)
209
  elif a.stage == 'optimum': stage_optimum(a)
210
  elif a.stage == 'summary': stage_summary(a)
211
  elif a.stage == 'start':
212
+ with Pool(a.procs, maxtasksperchild=1) as pool: pool.map(start_job, [(N, h, a.Ufac, a.out) for N in a.N for h in a.h], chunksize=1)
213
  else:
214
  jobs = [(N, h, a.Ufac, a.out, a.first_order, a.T) for N in a.N for h in a.h if not os.path.exists(os.path.join(a.out, f'job_N{N}_h{h}.json'))]
215
  with Pool(a.procs, maxtasksperchild=1) as pool: pool.map(job, jobs, chunksize=1)
globmp/init.py CHANGED
@@ -9,6 +9,16 @@ cost-to-go rule the test is
9
  V(s) + w(s, s') + togo(s') > U, where togo(s') is a lower bound on the cost of the remaining pieces; it skips more
10
  pairs and returns the same curve.
11
 
 
 
 
 
 
 
 
 
 
 
12
  The instance supplies the state sets, the piece cost and the exact piece test (an object `inst`):
13
 
14
  inst.n_pieces M; the joints are 0..M
@@ -20,12 +30,15 @@ The instance supplies the state sets, the piece cost and the exact piece test (a
20
  inst.free_pairs(i, s, t) the same test for the listed pairs (s[k], t[k]) only: bool (len(s),) (for tests that
21
  cost work per pair; INIT then lists the pairs that pass the budget)
22
  inst.togo(j) cost-to-go lower bound of every state at joint j, (n_states(j),) (rule 'togo')
 
 
23
  inst.n_labels, inst.label(i, s, lab) (optional)
24
  a state can carry a label fixed by the pieces before it (e.g. the route class so far):
25
  label returns the label of the end state of every pair, int (len(s), n_states(i+1)),
26
  or (len(s), 1) on a piece that changes no label.
27
  INIT then keeps V per (label, state) and returns the cheapest curve per final label.
28
  """
 
29
  import time
30
 
31
  import numpy as np
@@ -97,3 +110,42 @@ def init(inst, U=np.inf, rule='togo', improve_only=True, ties='first', chunk=2e7
97
  if lev > 0: j = int(back[lev][2][j])
98
  curves[int(l)] = (cost, path)
99
  return dict(curves=curves, layers=layers, time=time.time() - t0)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9
  V(s) + w(s, s') + togo(s') > U, where togo(s') is a lower bound on the cost of the remaining pieces; it skips more
10
  pairs and returns the same curve.
11
 
12
+ Two forms of the same search:
13
+
14
+ init_best_first Algorithm 3 as printed. Pairs (s, s') are processed in increasing order of
15
+ V(s) + w(s, s') + togo(s'); a piece is tested when its pair is reached; when a state is reached,
16
+ the obstacle-free optimal completion from it is tested too, and the search stops at the first
17
+ completion (or last-joint state) that passes. No budget and no known feasible curve are needed.
18
+ The returned curve is feasible and costs no more than any feasible candidate curve.
19
+ init the layered form: all states of a joint at once (array operations), pieces skipped by a budget;
20
+ returns the cheapest feasible candidate curve, one per final label.
21
+
22
  The instance supplies the state sets, the piece cost and the exact piece test (an object `inst`):
23
 
24
  inst.n_pieces M; the joints are 0..M
 
30
  inst.free_pairs(i, s, t) the same test for the listed pairs (s[k], t[k]) only: bool (len(s),) (for tests that
31
  cost work per pair; INIT then lists the pairs that pass the budget)
32
  inst.togo(j) cost-to-go lower bound of every state at joint j, (n_states(j),) (rule 'togo')
33
+ inst.completion(j, t) the obstacle-free optimal completion from state t at joint j < M: (feasible, curve,
34
+ number of pieces tested); its cost is togo(j)[t] (init_best_first)
35
  inst.n_labels, inst.label(i, s, lab) (optional)
36
  a state can carry a label fixed by the pieces before it (e.g. the route class so far):
37
  label returns the label of the end state of every pair, int (len(s), n_states(i+1)),
38
  or (len(s), 1) on a piece that changes no label.
39
  INIT then keeps V per (label, state) and returns the cheapest curve per final label.
40
  """
41
+ import heapq
42
  import time
43
 
44
  import numpy as np
 
110
  if lev > 0: j = int(back[lev][2][j])
111
  curves[int(l)] = (cost, path)
112
  return dict(curves=curves, layers=layers, time=time.time() - t0)
113
+
114
+
115
+ def init_best_first(inst, U=np.inf):
116
+ """INIT, Algorithm 3: best-first over the pairs with the key V(s) + w(s, s') + togo(s'). togo is the exact
117
+ obstacle-free minimum of the remaining pieces, attained by inst.completion, so the first completion (or
118
+ last-joint state) that passes the exact test gives a feasible curve whose cost, the key, is at most the cost of
119
+ every feasible candidate curve. U: keys above U are dropped (keeps the lists short; None is returned when no
120
+ feasible curve of cost <= U is found).
121
+
122
+ Returns None or dict(cost, path, joint, tail, tests, completion_tests, closed, time): path = state index at
123
+ joints 0..joint, tail = the completion from that state (None when joint = M)."""
124
+ M = inst.n_pieces; t0 = time.time(); tg = [inst.togo(j) for j in range(M + 1)]
125
+ closed = [np.zeros(inst.n_states(j), bool) for j in range(M + 1)]; pred = {}
126
+ k0 = tg[0]; od = np.argsort(k0, kind='stable'); od = od[k0[od] <= U]
127
+ if len(od) == 0: return None
128
+ store = {(-1, 0): (od, k0[od], np.zeros(len(od)))}; heap = [(float(k0[od[0]]), -1, 0, 0)]
129
+ tests = ctests = nclosed = 0
130
+ while heap:
131
+ key, j, s, p = heapq.heappop(heap); od, keys, tots = store[(j, s)]
132
+ if p + 1 < len(od): heapq.heappush(heap, (float(keys[p + 1]), j, s, p + 1))
133
+ t = int(od[p]); jj = j + 1
134
+ if closed[jj][t]: continue
135
+ if j >= 0: # exact test of the piece (s, t)
136
+ tests += 1
137
+ if not inst.free_pairs(j, np.array([s]), np.array([t]))[0]: continue
138
+ closed[jj][t] = True; nclosed += 1; pred[(jj, t)] = s; V = float(tots[p]); tail = None
139
+ if jj < M: # obstacle-free optimal completion from t
140
+ ok, tail, n = inst.completion(jj, t); ctests += n
141
+ if jj == M or ok:
142
+ path = [t]
143
+ for lev in range(jj, 0, -1): path.append(pred[(lev, path[-1])])
144
+ return dict(cost=float(key), path=path[::-1], joint=jj, tail=tail, tests=tests, completion_tests=ctests,
145
+ closed=nclosed, time=time.time() - t0)
146
+ tot = inst.cost(jj, np.array([t]), np.array([V]))[0]; kk = tot + tg[jj + 1]
147
+ sel = np.flatnonzero(kk <= U)
148
+ if len(sel):
149
+ o = sel[np.argsort(kk[sel], kind='stable')]; store[(jj, t)] = (o, kk[o], tot[o])
150
+ heapq.heappush(heap, (float(kk[o[0]]), jj, t, 0))
151
+ return None