nablaengine 1.0.2__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- nablaengine/__init__.py +4 -0
- nablaengine/_fixtures/README.md +19 -0
- nablaengine/_fixtures/data/mf_s0.npz +0 -0
- nablaengine/_fixtures/mjlab/LICENSE +27 -0
- nablaengine/_fixtures/mjlab/README.md +113 -0
- nablaengine/_fixtures/mjlab/g1_meta.json +32 -0
- nablaengine/_fixtures/mjlab/g1_train.mjb +0 -0
- nablaengine/_optional.py +30 -0
- nablaengine/_paths.py +38 -0
- nablaengine/actuators/__init__.py +169 -0
- nablaengine/actuators/bam.py +306 -0
- nablaengine/actuators/bam_params/LICENSE +202 -0
- nablaengine/actuators/bam_params/xl330/m6.json +19 -0
- nablaengine/boxbox.py +259 -0
- nablaengine/ccd.py +1122 -0
- nablaengine/checks.py +376 -0
- nablaengine/cuda.py +483 -0
- nablaengine/dist_query.py +628 -0
- nablaengine/dual.py +223 -0
- nablaengine/dyn_query.py +685 -0
- nablaengine/engines.py +114 -0
- nablaengine/envs/__init__.py +24 -0
- nablaengine/envs/brax.py +165 -0
- nablaengine/envs/convert.py +771 -0
- nablaengine/envs/dmc.py +523 -0
- nablaengine/envs/env.py +233 -0
- nablaengine/envs/kin.py +371 -0
- nablaengine/envs/ops.py +134 -0
- nablaengine/envs/rewards.py +57 -0
- nablaengine/fixtures.py +243 -0
- nablaengine/forest_engine/__init__.py +0 -0
- nablaengine/forest_engine/adjoint.py +1726 -0
- nablaengine/forest_engine/adjoint_contact.py +493 -0
- nablaengine/forest_engine/bam_hooks.py +248 -0
- nablaengine/forest_engine/body_params.py +1007 -0
- nablaengine/forest_engine/capacity_diag.py +116 -0
- nablaengine/forest_engine/ccd_coop.py +250 -0
- nablaengine/forest_engine/chol_blk.py +80 -0
- nablaengine/forest_engine/contact_forces.py +142 -0
- nablaengine/forest_engine/contact_vjp.py +462 -0
- nablaengine/forest_engine/convex.py +1331 -0
- nablaengine/forest_engine/cylinder.py +73 -0
- nablaengine/forest_engine/dist_device.py +923 -0
- nablaengine/forest_engine/dyn_device.py +696 -0
- nablaengine/forest_engine/ellipsoid.py +179 -0
- nablaengine/forest_engine/elliptic.py +272 -0
- nablaengine/forest_engine/equality.py +842 -0
- nablaengine/forest_engine/floss.py +148 -0
- nablaengine/forest_engine/foot_offset.py +368 -0
- nablaengine/forest_engine/free_gyro.py +288 -0
- nablaengine/forest_engine/host.py +530 -0
- nablaengine/forest_engine/kdof64.py +127 -0
- nablaengine/forest_engine/kinematics.py +320 -0
- nablaengine/forest_engine/margin.py +167 -0
- nablaengine/forest_engine/margin_convex.py +326 -0
- nablaengine/forest_engine/midphase.py +439 -0
- nablaengine/forest_engine/model_hooks.py +913 -0
- nablaengine/forest_engine/motor_hooks.py +50 -0
- nablaengine/forest_engine/muscle.py +485 -0
- nablaengine/forest_engine/nb128.py +118 -0
- nablaengine/forest_engine/nb64.py +163 -0
- nablaengine/forest_engine/noslip.py +1124 -0
- nablaengine/forest_engine/nv128.py +1944 -0
- nablaengine/forest_engine/object_size.py +283 -0
- nablaengine/forest_engine/replay_guard.py +40 -0
- nablaengine/forest_engine/root_spread.py +126 -0
- nablaengine/forest_engine/solref.py +74 -0
- nablaengine/forest_engine/source.py +1464 -0
- nablaengine/forest_engine/sparse_pattern.py +527 -0
- nablaengine/forest_engine/spatial.py +1045 -0
- nablaengine/forest_engine/step.py +3083 -0
- nablaengine/forest_engine/surrogate.py +498 -0
- nablaengine/forest_engine/tape.py +199 -0
- nablaengine/forest_engine/tendon.py +845 -0
- nablaengine/forest_engine/terrain.py +1059 -0
- nablaengine/forest_engine/world_forces.py +166 -0
- nablaengine/forest_engine/world_params.py +230 -0
- nablaengine/g1_engine/__init__.py +0 -0
- nablaengine/g1_engine/adjoint.py +1661 -0
- nablaengine/g1_engine/adjoint_contact.py +577 -0
- nablaengine/g1_engine/bam_hooks.py +596 -0
- nablaengine/g1_engine/condim4.py +245 -0
- nablaengine/g1_engine/contact_forces.py +500 -0
- nablaengine/g1_engine/cylccd.py +1158 -0
- nablaengine/g1_engine/cylinder.py +216 -0
- nablaengine/g1_engine/elliptic.py +565 -0
- nablaengine/g1_engine/exact_replay.py +61 -0
- nablaengine/g1_engine/host.py +358 -0
- nablaengine/g1_engine/kinematics.py +320 -0
- nablaengine/g1_engine/mesh.py +305 -0
- nablaengine/g1_engine/mesh_tables.py +79 -0
- nablaengine/g1_engine/model_hooks.py +919 -0
- nablaengine/g1_engine/motor_hooks.py +70 -0
- nablaengine/g1_engine/replay_guard.py +55 -0
- nablaengine/g1_engine/source.py +1107 -0
- nablaengine/g1_engine/sphbox.py +93 -0
- nablaengine/g1_engine/step.py +3716 -0
- nablaengine/g1_engine/tape.py +173 -0
- nablaengine/g1_engine/world_params.py +447 -0
- nablaengine/identity.py +401 -0
- nablaengine/jax_ffi.py +2536 -0
- nablaengine/model/__init__.py +1 -0
- nablaengine/model/capability.py +694 -0
- nablaengine/model/fields.py +317 -0
- nablaengine/model/gravcomp.py +64 -0
- nablaengine/model/invweight.py +145 -0
- nablaengine/motor.py +143 -0
- nablaengine/object_geometry.py +609 -0
- nablaengine/params.py +258 -0
- nablaengine/provenance.py +196 -0
- nablaengine/reference/__init__.py +0 -0
- nablaengine/reference/adjoint_groups.py +226 -0
- nablaengine/reference/jax64.py +690 -0
- nablaengine/reference/warp_physics.py +262 -0
- nablaengine/sensors/__init__.py +4 -0
- nablaengine/sensors/cameras.py +285 -0
- nablaengine/sensors/data/LIVOX_MID360_LICENSE +21 -0
- nablaengine/sensors/data/livox_mid360.npz +0 -0
- nablaengine/sensors/g1.py +521 -0
- nablaengine/sensors/jax_rays.py +364 -0
- nablaengine/sensors/optix_rays.py +725 -0
- nablaengine/sensors/raycore.py +630 -0
- nablaengine/sensors/raygrad.py +374 -0
- nablaengine/sensors/raygrad_cuda.py +191 -0
- nablaengine/sensors/robot_mesh.py +273 -0
- nablaengine/sensors/torch_rays.py +275 -0
- nablaengine/terrain.py +424 -0
- nablaengine/torch_ffi.py +1328 -0
- nablaengine/workdir.py +37 -0
- nablaengine-1.0.2.dist-info/METADATA +236 -0
- nablaengine-1.0.2.dist-info/RECORD +136 -0
- nablaengine-1.0.2.dist-info/WHEEL +5 -0
- nablaengine-1.0.2.dist-info/licenses/LICENSE +202 -0
- nablaengine-1.0.2.dist-info/licenses/NOTICE +23 -0
- nablaengine-1.0.2.dist-info/licenses/THIRD_PARTY_NOTICES.md +176 -0
- nablaengine-1.0.2.dist-info/top_level.txt +1 -0
|
@@ -0,0 +1,527 @@
|
|
|
1
|
+
"""Symbolic sparsity tools for the forest engine beyond nv = 64 (the symbolic analysis; Python only, not
|
|
2
|
+
imported by any build path yet).
|
|
3
|
+
|
|
4
|
+
From a MuJoCo model and its contact pairs this module builds
|
|
5
|
+
|
|
6
|
+
- the dof tree and the tree pattern of the mass matrix M (entry (i, j) iff one dof is an ancestor of the other),
|
|
7
|
+
- the support of every contact pair (dofs on exactly one of the two bodies' root chains; the common ancestors' columns
|
|
8
|
+
cancel at a contact point, and they are cliqued with both branches by the tree pattern anyway) and its class:
|
|
9
|
+
|
|
10
|
+
world one side is the world or welded to it
|
|
11
|
+
chain one body is an ancestor of the other (the support is a chain: a clique of tree(M))
|
|
12
|
+
robot_object one side in the robot tree (the tree with the most dofs), the other in another tree ("object")
|
|
13
|
+
object_object both sides in two different object trees
|
|
14
|
+
self_cheap a robot self pair across branches whose branch group adds little fill (put in the pattern)
|
|
15
|
+
self_cross a robot self pair across branches whose group would add much fill (dynamic: handled per world)
|
|
16
|
+
same_object both sides in one object tree across its branches (treated as self pairs of that tree)
|
|
17
|
+
|
|
18
|
+
- the elimination order (robot dofs leaves first = reversed dof order, then the object trees, also leaves first),
|
|
19
|
+
- the symbolic Cholesky factor of tree(M) + the supports of the pattern pairs + the always-on constraint cliques
|
|
20
|
+
(joint / connect equalities, fixed tendons): nnz(L) (diagonal included), flops, elimination-tree height, the column
|
|
21
|
+
slot tables (column-major in elimination order), and
|
|
22
|
+
- per pair the "out of pattern" bit: its support is not a clique of the filled pattern, so a world with that pair
|
|
23
|
+
active cannot use the static sparse factor (fallback / dynamic handling, design section 3.4).
|
|
24
|
+
|
|
25
|
+
Dof sets are Python ints used as bitmasks (bit i = dof i), so nv is not limited.
|
|
26
|
+
|
|
27
|
+
python -m nablaengine.forest_engine.sparse_pattern MODEL.xml # report (JSON)
|
|
28
|
+
python -m nablaengine.forest_engine.sparse_pattern --selftest # symbolic / numeric self-tests
|
|
29
|
+
"""
|
|
30
|
+
import itertools
|
|
31
|
+
import json
|
|
32
|
+
from dataclasses import dataclass, field
|
|
33
|
+
|
|
34
|
+
import numpy as np
|
|
35
|
+
|
|
36
|
+
CLASSES = ("world", "chain", "robot_object", "object_object", "same_object", "self_cheap", "self_cross")
|
|
37
|
+
PATTERN_CLASSES = {"world", "chain", "robot_object", "object_object", "self_cheap"}
|
|
38
|
+
CHEAP_BUDGET = 64
|
|
39
|
+
|
|
40
|
+
|
|
41
|
+
def popc(x):
|
|
42
|
+
return bin(x).count("1")
|
|
43
|
+
|
|
44
|
+
|
|
45
|
+
def bits(x):
|
|
46
|
+
out, i = [], 0
|
|
47
|
+
while x:
|
|
48
|
+
if x & 1:
|
|
49
|
+
out.append(i)
|
|
50
|
+
x >>= 1
|
|
51
|
+
i += 1
|
|
52
|
+
return out
|
|
53
|
+
|
|
54
|
+
|
|
55
|
+
def mask(it):
|
|
56
|
+
v = 0
|
|
57
|
+
for i in it:
|
|
58
|
+
v |= 1 << int(i)
|
|
59
|
+
return v
|
|
60
|
+
|
|
61
|
+
|
|
62
|
+
@dataclass
|
|
63
|
+
class Factor:
|
|
64
|
+
"""Symbolic Cholesky factor of a symmetric pattern under an elimination order. Positions are elimination
|
|
65
|
+
positions (perm[k] = original dof eliminated k-th, iperm[dof] = its position); colmask[k] = the positions > k of
|
|
66
|
+
column k's below-diagonal entries; col_start[k] = the slot of column k's diagonal in the column-major storage
|
|
67
|
+
(diagonal first, then the rows in increasing position)."""
|
|
68
|
+
n: int
|
|
69
|
+
perm: list
|
|
70
|
+
iperm: list
|
|
71
|
+
colmask: list
|
|
72
|
+
col_start: list
|
|
73
|
+
etree: list
|
|
74
|
+
nnz: int
|
|
75
|
+
nnz_a: int
|
|
76
|
+
flops: int
|
|
77
|
+
height: int
|
|
78
|
+
filled: list = field(repr=False, default=None)
|
|
79
|
+
|
|
80
|
+
def has(self, i, j):
|
|
81
|
+
"""(i, j) (original dofs) is an entry of the filled pattern."""
|
|
82
|
+
return i == j or bool(self.filled[i] >> j & 1)
|
|
83
|
+
|
|
84
|
+
def slot(self, i, j):
|
|
85
|
+
"""Column-major slot of entry (i, j) of L (original dofs); KeyError if it is not in the pattern."""
|
|
86
|
+
p, q = self.iperm[i], self.iperm[j]
|
|
87
|
+
col, row = min(p, q), max(p, q)
|
|
88
|
+
if row == col:
|
|
89
|
+
return self.col_start[col]
|
|
90
|
+
if not self.colmask[col] >> row & 1:
|
|
91
|
+
raise KeyError((i, j))
|
|
92
|
+
return self.col_start[col] + 1 + popc(self.colmask[col] & ((1 << row) - 1))
|
|
93
|
+
|
|
94
|
+
def is_clique(self, s):
|
|
95
|
+
"""The dof set s (bitmask) is a clique of the filled pattern."""
|
|
96
|
+
for i in bits(s):
|
|
97
|
+
if (s & ~self.filled[i] & ~(1 << i)) != 0:
|
|
98
|
+
return False
|
|
99
|
+
return True
|
|
100
|
+
|
|
101
|
+
def summary(self):
|
|
102
|
+
dense = self.n * (self.n + 1) // 2
|
|
103
|
+
return dict(nv=self.n, nnz_a=self.nnz_a, nnz_l=self.nnz, ntri=dense, fill_frac=round(self.nnz / dense, 4),
|
|
104
|
+
flops=self.flops, dense_flops=dense_flops(self.n), height=self.height)
|
|
105
|
+
|
|
106
|
+
|
|
107
|
+
def dense_flops(n):
|
|
108
|
+
return sum(k * (k + 3) // 2 + 1 for k in range(n))
|
|
109
|
+
|
|
110
|
+
|
|
111
|
+
def symbolic(n, adj, order):
|
|
112
|
+
"""Elimination game on the symmetric pattern adj (list of n bitmasks, no diagonal bits needed) in `order`
|
|
113
|
+
(original indices, eliminated first to last). Returns a Factor."""
|
|
114
|
+
assert sorted(order) == list(range(n)), "order must be a permutation"
|
|
115
|
+
adj = [a & ~(1 << i) for i, a in enumerate(adj)]
|
|
116
|
+
for i in range(n):
|
|
117
|
+
for j in bits(adj[i]):
|
|
118
|
+
adj[j] |= 1 << i
|
|
119
|
+
nnz_a = sum(popc(a) for a in adj) // 2 + n
|
|
120
|
+
iperm = [0] * n
|
|
121
|
+
for k, v in enumerate(order):
|
|
122
|
+
iperm[v] = k
|
|
123
|
+
work = list(adj)
|
|
124
|
+
filled = [0] * n
|
|
125
|
+
elim = 0
|
|
126
|
+
colmask, nnz, flops, etree = [], 0, 0, []
|
|
127
|
+
for k, v in enumerate(order):
|
|
128
|
+
nb = work[v] & ~elim & ~(1 << v)
|
|
129
|
+
for u in bits(nb):
|
|
130
|
+
work[u] |= nb & ~(1 << u)
|
|
131
|
+
c = popc(nb)
|
|
132
|
+
nnz += c + 1
|
|
133
|
+
flops += c * (c + 3) // 2 + 1
|
|
134
|
+
cm = mask(iperm[u] for u in bits(nb))
|
|
135
|
+
colmask.append(cm)
|
|
136
|
+
etree.append((cm & -cm).bit_length() - 1 if cm else -1)
|
|
137
|
+
for u in bits(nb):
|
|
138
|
+
filled[v] |= 1 << u
|
|
139
|
+
filled[u] |= 1 << v
|
|
140
|
+
elim |= 1 << v
|
|
141
|
+
col_start, s = [], 0
|
|
142
|
+
for cm in colmask:
|
|
143
|
+
col_start.append(s)
|
|
144
|
+
s += 1 + popc(cm)
|
|
145
|
+
h = [1] * n
|
|
146
|
+
for k in range(n):
|
|
147
|
+
if etree[k] >= 0:
|
|
148
|
+
h[etree[k]] = max(h[etree[k]], h[k] + 1)
|
|
149
|
+
return Factor(n, list(order), iperm, colmask, col_start, etree, nnz, nnz_a, flops, max(h) if n else 0, filled)
|
|
150
|
+
|
|
151
|
+
|
|
152
|
+
def dense_symbolic(n, adj, order):
|
|
153
|
+
"""Reference: boolean dense right-looking elimination of the permuted pattern (O(n^3)); returns the lower
|
|
154
|
+
pattern of L in elimination positions as an (n, n) bool array."""
|
|
155
|
+
P = np.zeros((n, n), bool)
|
|
156
|
+
for i in range(n):
|
|
157
|
+
for j in bits(adj[i]):
|
|
158
|
+
P[i, j] = P[j, i] = True
|
|
159
|
+
np.fill_diagonal(P, True)
|
|
160
|
+
o = np.asarray(order)
|
|
161
|
+
A = P[np.ix_(o, o)].copy()
|
|
162
|
+
for k in range(n):
|
|
163
|
+
r = np.nonzero(A[k + 1:, k])[0] + k + 1
|
|
164
|
+
A[np.ix_(r, r)] = True
|
|
165
|
+
return np.tril(A)
|
|
166
|
+
|
|
167
|
+
|
|
168
|
+
def numeric_on_pattern(F, A):
|
|
169
|
+
"""Left-looking Cholesky of the dense symmetric A (original indices) computed only on F's slots (float64).
|
|
170
|
+
Returns the values array (column-major slots) and the dense lower L in elimination positions."""
|
|
171
|
+
n = F.n
|
|
172
|
+
o = np.asarray(F.perm)
|
|
173
|
+
Ap = A[np.ix_(o, o)]
|
|
174
|
+
val = np.zeros(F.nnz)
|
|
175
|
+
rows = [[k] + bits(F.colmask[k]) for k in range(n)]
|
|
176
|
+
L = np.zeros((n, n))
|
|
177
|
+
for k in range(n):
|
|
178
|
+
col = {r: Ap[r, k] for r in rows[k]}
|
|
179
|
+
for j in range(k):
|
|
180
|
+
if F.colmask[j] >> k & 1:
|
|
181
|
+
ljk = L[k, j]
|
|
182
|
+
for r in rows[k]:
|
|
183
|
+
if r == k or F.colmask[j] >> r & 1:
|
|
184
|
+
col[r] -= L[r, j] * ljk
|
|
185
|
+
d = np.sqrt(col[k])
|
|
186
|
+
for t, r in enumerate(rows[k]):
|
|
187
|
+
L[r, k] = d if r == k else col[r] / d
|
|
188
|
+
val[F.col_start[k] + t] = L[r, k]
|
|
189
|
+
return val, L
|
|
190
|
+
|
|
191
|
+
|
|
192
|
+
class DofTree:
|
|
193
|
+
"""Dof / body structure of a MuJoCo model: body root chains as dof masks, trees, robot vs object trees."""
|
|
194
|
+
|
|
195
|
+
def __init__(self, m):
|
|
196
|
+
self.m = m
|
|
197
|
+
self.nv, self.nbody = int(m.nv), int(m.nbody)
|
|
198
|
+
self.dof_parent = [int(x) for x in m.dof_parentid]
|
|
199
|
+
self.body_parent = [int(x) for x in m.body_parentid]
|
|
200
|
+
self.body_dofs = [mask(range(int(m.body_dofadr[b]), int(m.body_dofadr[b]) + int(m.body_dofnum[b])))
|
|
201
|
+
if m.body_dofnum[b] else 0 for b in range(self.nbody)]
|
|
202
|
+
self.chain = [0] * self.nbody
|
|
203
|
+
for b in range(1, self.nbody):
|
|
204
|
+
self.chain[b] = self.chain[self.body_parent[b]] | self.body_dofs[b]
|
|
205
|
+
self.root = [0] * self.nbody
|
|
206
|
+
for b in range(1, self.nbody):
|
|
207
|
+
p = self.body_parent[b]
|
|
208
|
+
self.root[b] = b if p == 0 else self.root[p]
|
|
209
|
+
trees = {}
|
|
210
|
+
for b in range(1, self.nbody):
|
|
211
|
+
trees.setdefault(self.root[b], 0)
|
|
212
|
+
trees[self.root[b]] |= self.body_dofs[b]
|
|
213
|
+
self.trees = {r: d for r, d in trees.items() if d}
|
|
214
|
+
self.robot_root = max(self.trees, key=lambda r: (popc(self.trees[r]), -r)) if self.trees else 0
|
|
215
|
+
self.robot = self.trees.get(self.robot_root, 0)
|
|
216
|
+
self.anc = [0] * self.nv
|
|
217
|
+
for i in range(self.nv):
|
|
218
|
+
p = self.dof_parent[i]
|
|
219
|
+
self.anc[i] = (self.anc[p] | (1 << p)) if p >= 0 else 0
|
|
220
|
+
|
|
221
|
+
def static(self, b):
|
|
222
|
+
"""Body b does not move (the world or bodies welded to it)."""
|
|
223
|
+
return self.chain[b] == 0
|
|
224
|
+
|
|
225
|
+
def tree_adj(self):
|
|
226
|
+
adj = [0] * self.nv
|
|
227
|
+
for i in range(self.nv):
|
|
228
|
+
adj[i] |= self.anc[i]
|
|
229
|
+
for a in bits(self.anc[i]):
|
|
230
|
+
adj[a] |= 1 << i
|
|
231
|
+
return adj
|
|
232
|
+
|
|
233
|
+
def order(self):
|
|
234
|
+
"""Leaves first, objects last: the robot tree's dofs in reversed dof order, then every other tree's dofs in
|
|
235
|
+
reversed dof order (trees in increasing root order)."""
|
|
236
|
+
rob = [i for i in range(self.nv) if self.robot >> i & 1][::-1]
|
|
237
|
+
objs = []
|
|
238
|
+
for r in sorted(self.trees):
|
|
239
|
+
if r != self.robot_root:
|
|
240
|
+
objs += [i for i in range(self.nv) if self.trees[r] >> i & 1][::-1]
|
|
241
|
+
rest = [i for i in range(self.nv) if i not in set(rob) | set(objs)]
|
|
242
|
+
return rob + objs + rest[::-1]
|
|
243
|
+
|
|
244
|
+
def lca(self, b1, b2):
|
|
245
|
+
a = set()
|
|
246
|
+
x = b1
|
|
247
|
+
while True:
|
|
248
|
+
a.add(x)
|
|
249
|
+
if x == 0:
|
|
250
|
+
break
|
|
251
|
+
x = self.body_parent[x]
|
|
252
|
+
x = b2
|
|
253
|
+
while x not in a:
|
|
254
|
+
x = self.body_parent[x]
|
|
255
|
+
return x
|
|
256
|
+
|
|
257
|
+
def branch(self, b, lca):
|
|
258
|
+
"""The child of lca on the path to b (b itself if its parent is lca)."""
|
|
259
|
+
while self.body_parent[b] != lca:
|
|
260
|
+
b = self.body_parent[b]
|
|
261
|
+
return b
|
|
262
|
+
|
|
263
|
+
|
|
264
|
+
@dataclass
|
|
265
|
+
class PairInfo:
|
|
266
|
+
index: int
|
|
267
|
+
geoms: tuple
|
|
268
|
+
bodies: tuple
|
|
269
|
+
cls: str
|
|
270
|
+
support: int
|
|
271
|
+
group: tuple = None
|
|
272
|
+
in_pattern: bool = None
|
|
273
|
+
|
|
274
|
+
@property
|
|
275
|
+
def nsup(self):
|
|
276
|
+
return popc(self.support)
|
|
277
|
+
|
|
278
|
+
|
|
279
|
+
def model_pairs(m, include_filter=True):
|
|
280
|
+
"""(geom1, geom2) of the explicit <pair>s, then (include_filter) the contype / conaffinity pairs MuJoCo's
|
|
281
|
+
broadphase would add (nablaengine.model.capability.filter_pairs)."""
|
|
282
|
+
out = [(int(a), int(b)) for a, b in zip(m.pair_geom1, m.pair_geom2)]
|
|
283
|
+
if include_filter:
|
|
284
|
+
from nablaengine.model.capability import filter_pairs
|
|
285
|
+
out += [(int(a), int(b)) for a, b in filter_pairs(m)]
|
|
286
|
+
return out
|
|
287
|
+
|
|
288
|
+
|
|
289
|
+
def constraint_cliques(m, t):
|
|
290
|
+
"""Dof sets that are always coupled by constraint rows: joint equalities (the two joints' dofs), connect
|
|
291
|
+
equalities (chain xor chain of the two bodies), fixed tendons (their joints' dofs). Returns [(name, mask)]."""
|
|
292
|
+
import mujoco
|
|
293
|
+
out = []
|
|
294
|
+
for e in range(int(m.neq)):
|
|
295
|
+
ty = int(m.eq_type[e])
|
|
296
|
+
o1, o2 = int(m.eq_obj1id[e]), int(m.eq_obj2id[e])
|
|
297
|
+
if ty == int(mujoco.mjtEq.mjEQ_JOINT):
|
|
298
|
+
s = mask(range(int(m.jnt_dofadr[o1]), int(m.jnt_dofadr[o1]) + 1))
|
|
299
|
+
if o2 >= 0:
|
|
300
|
+
s |= 1 << int(m.jnt_dofadr[o2])
|
|
301
|
+
elif ty in (int(mujoco.mjtEq.mjEQ_CONNECT), int(mujoco.mjtEq.mjEQ_WELD)):
|
|
302
|
+
if int(m.eq_objtype[e]) == int(mujoco.mjtObj.mjOBJ_SITE):
|
|
303
|
+
o1, o2 = int(m.site_bodyid[o1]), int(m.site_bodyid[o2])
|
|
304
|
+
s = t.chain[o1] ^ t.chain[max(o2, 0)]
|
|
305
|
+
else:
|
|
306
|
+
continue
|
|
307
|
+
out.append((f"eq{e}", s))
|
|
308
|
+
for k in range(int(m.ntendon)):
|
|
309
|
+
a, n = int(m.tendon_adr[k]), int(m.tendon_num[k])
|
|
310
|
+
s = 0
|
|
311
|
+
for w in range(a, a + n):
|
|
312
|
+
if int(m.wrap_type[w]) == int(mujoco.mjtWrap.mjWRAP_JOINT):
|
|
313
|
+
s |= 1 << int(m.jnt_dofadr[int(m.wrap_objid[w])])
|
|
314
|
+
out.append((f"tendon{k}", s))
|
|
315
|
+
return out
|
|
316
|
+
|
|
317
|
+
|
|
318
|
+
class Pattern:
|
|
319
|
+
"""The static Hessian pattern P_H of model m with the contact pairs `pairs` ((g1, g2) list; default: the explicit
|
|
320
|
+
pairs and the filter pairs) under the leaves-first / objects-last order."""
|
|
321
|
+
|
|
322
|
+
def __init__(self, m, pairs=None, cheap_budget=CHEAP_BUDGET, order=None):
|
|
323
|
+
self.m = m
|
|
324
|
+
t = self.tree = DofTree(m)
|
|
325
|
+
self.pair_list = model_pairs(m) if pairs is None else [tuple(map(int, p)) for p in pairs]
|
|
326
|
+
self.order = list(order) if order is not None else t.order()
|
|
327
|
+
self.cliques = constraint_cliques(m, t)
|
|
328
|
+
self.base_adj = t.tree_adj()
|
|
329
|
+
for _, s in self.cliques:
|
|
330
|
+
self._add(self.base_adj, s)
|
|
331
|
+
self.factor_tree = symbolic(t.nv, t.tree_adj(), self.order)
|
|
332
|
+
self.factor_m = symbolic(t.nv, self.base_adj, self.order)
|
|
333
|
+
self.pairs = [self._classify(k, g1, g2) for k, (g1, g2) in enumerate(self.pair_list)]
|
|
334
|
+
adj = list(self.base_adj)
|
|
335
|
+
for p in self.pairs:
|
|
336
|
+
if p.cls in PATTERN_CLASSES:
|
|
337
|
+
self._add(adj, p.support)
|
|
338
|
+
self.factor_noself = symbolic(t.nv, adj, self.order)
|
|
339
|
+
self.groups = {}
|
|
340
|
+
for p in self.pairs:
|
|
341
|
+
if p.group is not None:
|
|
342
|
+
g = self.groups.setdefault(p.group, dict(pairs=[], support=0))
|
|
343
|
+
g["pairs"].append(p.index)
|
|
344
|
+
g["support"] |= p.support
|
|
345
|
+
base = self.factor_noself.nnz
|
|
346
|
+
cand = []
|
|
347
|
+
for key, g in self.groups.items():
|
|
348
|
+
a2 = list(adj)
|
|
349
|
+
for i in g["pairs"]:
|
|
350
|
+
self._add(a2, self.pairs[i].support)
|
|
351
|
+
g["delta_alone"] = symbolic(t.nv, a2, self.order).nnz - base
|
|
352
|
+
cand.append((g["delta_alone"], key))
|
|
353
|
+
for _, key in sorted(cand):
|
|
354
|
+
g = self.groups[key]
|
|
355
|
+
a2 = list(adj)
|
|
356
|
+
for i in g["pairs"]:
|
|
357
|
+
self._add(a2, self.pairs[i].support)
|
|
358
|
+
nnz = symbolic(t.nv, a2, self.order).nnz
|
|
359
|
+
g["delta"] = nnz - base
|
|
360
|
+
g["cheap"] = g["delta"] <= cheap_budget
|
|
361
|
+
if g["cheap"]:
|
|
362
|
+
adj, base = a2, nnz
|
|
363
|
+
for i in g["pairs"]:
|
|
364
|
+
self.pairs[i].cls = "self_cheap" if g["cheap"] else "self_cross"
|
|
365
|
+
self.adj = adj
|
|
366
|
+
self.factor = symbolic(t.nv, adj, self.order)
|
|
367
|
+
for p in self.pairs:
|
|
368
|
+
p.in_pattern = self.factor.is_clique(p.support)
|
|
369
|
+
|
|
370
|
+
@staticmethod
|
|
371
|
+
def _add(adj, s):
|
|
372
|
+
b = bits(s)
|
|
373
|
+
for i in b:
|
|
374
|
+
adj[i] |= s & ~(1 << i)
|
|
375
|
+
|
|
376
|
+
def _classify(self, k, g1, g2):
|
|
377
|
+
m, t = self.m, self.tree
|
|
378
|
+
b1, b2 = int(m.geom_bodyid[g1]), int(m.geom_bodyid[g2])
|
|
379
|
+
sup = t.chain[b1] ^ t.chain[b2]
|
|
380
|
+
if t.static(b1) or t.static(b2):
|
|
381
|
+
return PairInfo(k, (g1, g2), (b1, b2), "world", sup)
|
|
382
|
+
r1, r2 = t.root[b1], t.root[b2]
|
|
383
|
+
if r1 != r2:
|
|
384
|
+
rob = (r1 == t.robot_root) or (r2 == t.robot_root)
|
|
385
|
+
return PairInfo(k, (g1, g2), (b1, b2), "robot_object" if rob else "object_object", sup)
|
|
386
|
+
c1, c2 = t.chain[b1], t.chain[b2]
|
|
387
|
+
if (c1 & c2) == c1 or (c1 & c2) == c2:
|
|
388
|
+
return PairInfo(k, (g1, g2), (b1, b2), "chain", sup)
|
|
389
|
+
lca = t.lca(b1, b2)
|
|
390
|
+
br = tuple(sorted((t.branch(b1, lca), t.branch(b2, lca))))
|
|
391
|
+
cls = "self_cross" if r1 == t.robot_root else "same_object"
|
|
392
|
+
return PairInfo(k, (g1, g2), (b1, b2), cls, sup, group=(lca,) + br)
|
|
393
|
+
|
|
394
|
+
def out_of_pattern(self):
|
|
395
|
+
"""Pair index -> True when the pair's support is not a clique of the static pattern."""
|
|
396
|
+
return {p.index: not p.in_pattern for p in self.pairs}
|
|
397
|
+
|
|
398
|
+
def class_counts(self):
|
|
399
|
+
out = {c: 0 for c in CLASSES}
|
|
400
|
+
for p in self.pairs:
|
|
401
|
+
out[p.cls] += 1
|
|
402
|
+
return out
|
|
403
|
+
|
|
404
|
+
def report(self, names=True):
|
|
405
|
+
import mujoco
|
|
406
|
+
m = self.m
|
|
407
|
+
bn = lambda b: mujoco.mj_id2name(m, mujoco.mjtObj.mjOBJ_BODY, b) or str(b)
|
|
408
|
+
groups = []
|
|
409
|
+
for key, g in sorted(self.groups.items(), key=lambda kv: kv[1]["delta_alone"]):
|
|
410
|
+
groups.append(dict(lca=bn(key[0]), branches=[bn(key[1]), bn(key[2])], npairs=len(g["pairs"]),
|
|
411
|
+
nsup=popc(g["support"]), delta_alone=g["delta_alone"], delta=g["delta"],
|
|
412
|
+
cheap=g["cheap"]))
|
|
413
|
+
return dict(nv=self.tree.nv, nbody=self.tree.nbody, npair=len(self.pairs),
|
|
414
|
+
trees=len(self.tree.trees), robot_dofs=popc(self.tree.robot),
|
|
415
|
+
constraint_cliques=len(self.cliques),
|
|
416
|
+
max_support=max((p.nsup for p in self.pairs), default=0),
|
|
417
|
+
classes=self.class_counts(),
|
|
418
|
+
out_of_pattern=sum(not p.in_pattern for p in self.pairs),
|
|
419
|
+
factor_tree=self.factor_tree.summary(), factor_m=self.factor_m.summary(),
|
|
420
|
+
factor_no_self=self.factor_noself.summary(), factor_h=self.factor.summary(),
|
|
421
|
+
factor_all_self=self.with_all().summary(),
|
|
422
|
+
self_groups=groups if names else len(groups))
|
|
423
|
+
|
|
424
|
+
def with_all(self):
|
|
425
|
+
"""The factor if every pair (including self_cross) were put into the pattern."""
|
|
426
|
+
adj = list(self.base_adj)
|
|
427
|
+
for p in self.pairs:
|
|
428
|
+
self._add(adj, p.support)
|
|
429
|
+
return symbolic(self.tree.nv, adj, self.order)
|
|
430
|
+
|
|
431
|
+
|
|
432
|
+
def _random_tree(rng, n, nroots):
|
|
433
|
+
par = [-1] * n
|
|
434
|
+
roots = sorted(rng.choice(np.arange(1, n), size=nroots - 1, replace=False).tolist()) if nroots > 1 else []
|
|
435
|
+
for i in range(1, n):
|
|
436
|
+
if i in roots:
|
|
437
|
+
continue
|
|
438
|
+
lo = max(0, i - int(rng.integers(1, 8)))
|
|
439
|
+
par[i] = int(rng.integers(lo, i))
|
|
440
|
+
while par[i] in roots and rng.random() < 0.3:
|
|
441
|
+
par[i] = int(rng.integers(0, i))
|
|
442
|
+
return par
|
|
443
|
+
|
|
444
|
+
|
|
445
|
+
def _anc(par):
|
|
446
|
+
anc = [0] * len(par)
|
|
447
|
+
for i, p in enumerate(par):
|
|
448
|
+
anc[i] = (anc[p] | (1 << p)) if p >= 0 else 0
|
|
449
|
+
return anc
|
|
450
|
+
|
|
451
|
+
|
|
452
|
+
def selftest(seed=0, ntests=200, verbose=False):
|
|
453
|
+
"""Symbolic factor vs the dense boolean elimination, tree(M) leaves first has no fill, numeric factor on the
|
|
454
|
+
slots vs numpy's dense Cholesky (float64), out-of-pattern bit vs a direct check. Raises AssertionError."""
|
|
455
|
+
rng = np.random.default_rng(seed)
|
|
456
|
+
worst = 0.0
|
|
457
|
+
for it in range(ntests):
|
|
458
|
+
n = int(rng.integers(2, 129 if it % 10 == 0 else 48))
|
|
459
|
+
par = _random_tree(rng, n, int(rng.integers(1, 4)))
|
|
460
|
+
anc = _anc(par)
|
|
461
|
+
adj = [0] * n
|
|
462
|
+
for i in range(n):
|
|
463
|
+
adj[i] |= anc[i]
|
|
464
|
+
for a in bits(anc[i]):
|
|
465
|
+
adj[a] |= 1 << i
|
|
466
|
+
rev = list(range(n))[::-1]
|
|
467
|
+
F0 = symbolic(n, adj, rev)
|
|
468
|
+
assert F0.nnz == F0.nnz_a, ("tree pattern leaves first must not fill", it, F0.nnz, F0.nnz_a)
|
|
469
|
+
cl = []
|
|
470
|
+
for _ in range(int(rng.integers(0, 6))):
|
|
471
|
+
x, y = int(rng.integers(0, n)), int(rng.integers(0, n))
|
|
472
|
+
cl.append((anc[x] | 1 << x) ^ (anc[y] | 1 << y))
|
|
473
|
+
a2 = list(adj)
|
|
474
|
+
for s in cl:
|
|
475
|
+
Pattern._add(a2, s)
|
|
476
|
+
order = rev if rng.random() < 0.7 else rng.permutation(n).tolist()
|
|
477
|
+
F = symbolic(n, a2, order)
|
|
478
|
+
D = dense_symbolic(n, a2, order)
|
|
479
|
+
S = np.zeros((n, n), bool)
|
|
480
|
+
for k in range(n):
|
|
481
|
+
S[k, k] = True
|
|
482
|
+
for r in bits(F.colmask[k]):
|
|
483
|
+
S[r, k] = True
|
|
484
|
+
assert np.array_equal(S, D), ("symbolic != dense symbolic", it)
|
|
485
|
+
assert F.nnz == int(D.sum())
|
|
486
|
+
sl = sorted(F.slot(F.perm[r], F.perm[k]) for k in range(n) for r in range(k, n) if S[r, k])
|
|
487
|
+
assert sl == list(range(F.nnz))
|
|
488
|
+
A = np.zeros((n, n))
|
|
489
|
+
for i in range(n):
|
|
490
|
+
for j in bits(a2[i]):
|
|
491
|
+
if j < i:
|
|
492
|
+
A[i, j] = A[j, i] = rng.normal()
|
|
493
|
+
A += np.diag(np.abs(A).sum(1) + 1.0 + rng.random(n))
|
|
494
|
+
val, L = numeric_on_pattern(F, A)
|
|
495
|
+
o = np.asarray(F.perm)
|
|
496
|
+
Lref = np.linalg.cholesky(A[np.ix_(o, o)])
|
|
497
|
+
assert np.all(np.abs(Lref[~S]) < 1e-12), ("numpy L has entries outside the pattern", it)
|
|
498
|
+
err = float(np.max(np.abs(L - Lref)))
|
|
499
|
+
res = float(np.max(np.abs(L @ L.T - A[np.ix_(o, o)])) / np.max(np.abs(A)))
|
|
500
|
+
worst = max(worst, err, res)
|
|
501
|
+
assert err < 1e-12 and res < 1e-13, (it, err, res)
|
|
502
|
+
for s in cl + [mask(rng.choice(n, size=min(n, 3), replace=False))]:
|
|
503
|
+
direct = all(F.has(i, j) for i in bits(s) for j in bits(s))
|
|
504
|
+
assert direct == F.is_clique(s)
|
|
505
|
+
if verbose and it % 50 == 0:
|
|
506
|
+
print(it, n, F.summary())
|
|
507
|
+
return dict(tests=ntests, worst_abs=worst)
|
|
508
|
+
|
|
509
|
+
|
|
510
|
+
def main(argv=None):
|
|
511
|
+
import argparse
|
|
512
|
+
ap = argparse.ArgumentParser(description=__doc__.split("\n\n")[0])
|
|
513
|
+
ap.add_argument("model", nargs="?", help="MJCF / MJB model")
|
|
514
|
+
ap.add_argument("--selftest", action="store_true")
|
|
515
|
+
ap.add_argument("--budget", type=int, default=CHEAP_BUDGET)
|
|
516
|
+
a = ap.parse_args(argv)
|
|
517
|
+
if a.selftest:
|
|
518
|
+
print(json.dumps(selftest(), indent=1))
|
|
519
|
+
if a.model:
|
|
520
|
+
import mujoco
|
|
521
|
+
m = (mujoco.MjModel.from_binary_path(a.model) if a.model.endswith(".mjb")
|
|
522
|
+
else mujoco.MjModel.from_xml_path(a.model))
|
|
523
|
+
print(json.dumps(Pattern(m, cheap_budget=a.budget).report(), indent=1))
|
|
524
|
+
|
|
525
|
+
|
|
526
|
+
if __name__ == "__main__":
|
|
527
|
+
main()
|