File size: 24,161 Bytes
2bcbba2
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ff86ab2
 
 
2bcbba2
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
#!/usr/bin/env python3
"""A task file as a LIBERO-style BDDL problem (robosuite domain).

    python tools/task_bddl.py tasks/round_peg_hole.json                 # print it
    python tools/task_bddl.py datasets/gear_mesh/meta/task.json -o x.bddl

What a BDDL reader gets, mapped from the task file:

  :language      task_text
  :regions       one init region per object on the table: the nominal xy
                 +- randomize.xy_m as LIBERO's (x_min y_min x_max y_max), in the
                 TABLE's frame (metres from its centre, as LIBERO's are), and
                 nominal yaw +- randomize.yaw_deg as :yaw_rotation in radians.
                 An object that rides on another (gear_mesh's parked gears,
                 randomize.like) gets a mount region on that object instead.
                 An insertion gets the receiving fixture's insertion_region.
                 A per-axis xy_m ([x, y], the hammer) is kept per axis.
  :fixtures      the table, and every object that does not move: welded
                 ("fixed_base": true) or kinematic ("fixed": true).
  :objects       everything else. Instance <name>_1, type = the asset.
  :init          (On <obj> <its region>).
  :goal          LIBERO's own predicates (in, on, up, open, ...) wherever one
                 fits: lift -> Up, insert -> In the insertion region,
                 joint_angle / joint_open -> Open. ONE predicate of our own:
                 a threaded insert (success.thread) -> Screwed, because In
                 is satisfied by a part pushed straight down the bore and a
                 screwing task is not. LIBERO's parser reads it; its own
                 evaluator does not ground it -- tools/bddl_eval.py does.

LIBERO's predicates are thresholds of its own (Up is z >= 1.0 m, Open is the
articulation's is_open()), so each goal is followed by a comment with the
EXACT criterion this dataset graded by, and meta/episodes.jsonl carries
`success_terms` per episode. Comments are `;` lines, which LIBERO's parser
(bddl.parsing.scan_tokens) strips; it also lowercases everything, so every
name here is lowercase already.
"""

from __future__ import annotations

import argparse
import json
import math
import os
import re
import sys

REPO = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
sys.path.insert(0, REPO)

TABLE = "main_table"


def _num(x: float) -> str:
    return f"{x:.6g}"


def _ident(s: str) -> str:
    return "".join(c if c.isalnum() else "_" for c in s.lower())


def _language(text: str) -> str:
    """The instruction as LIBERO reads it: lowercase words, and nothing its
    tokenizer would take for structure (a paren, or `;` opening a comment)."""
    return " ".join(re.sub(r"[();]", " ", text).lower().split())


def _asset_type(obj: dict) -> str:
    path = obj.get("usd") or ""
    if path:
        return _ident(os.path.basename(os.path.dirname(path)) or obj["name"])
    return _ident(obj.get("shape", obj["name"]))


def _fixed(obj: dict) -> bool:
    return bool(obj.get("fixed_base") or obj.get("fixed"))


def _joint_criterion(succ: dict) -> str:
    if succ["type"] == "joint_angle":
        return f"joint turned >= {succ['min_deg']:g} deg ({succ.get('direction', 'increase')})"
    return (f"joint travel >= {succ['fraction']:g} of its range "
            f"({succ.get('direction', 'increase')})")


def _pose_goal(succ: dict, inst: dict, target: dict, regions: list) -> tuple[str, str]:
    """(goal, criterion text) for the pose-graded criteria of 2026-09-28. LIBERO has
    no predicate for an orientation or a displacement: those goals are `(true)` and
    the exact rule is the `; success as graded` comment (bddl_eval.py grades by it)."""
    t = succ["type"]
    part = inst[succ.get("part") or (succ["of"] if isinstance(succ.get("of"), str) else target["name"])]
    if t == "separate":
        into = inst[succ["into"]]
        if f"(insertion_region\n          (:target {into})" not in "".join(regions):
            regions.append(f"      (insertion_region\n          (:target {into})\n      )")
        return (f"(Not (In {part} {into}_insertion_region))",
                f"{part} >= {succ['min_m']:g} m off its seat on {into}")
    if t == "turn":
        return ("(true)", f"{part} turned >= {float(succ['min_deg']):g} deg {succ.get('direction', 'cw')} "
                          f"about {inst[succ['into']]}'s local axis {succ.get('axis_local', [0, 0, 1])}, "
                          f"accumulated step by step in {inst[succ['into']]}'s frame and only while "
                          f"within {float(succ.get('max_offset_m', 0.003)) * 1e3:g} mm of its seat "
                          f"(no LIBERO predicate for a turn; no joint either -- it turns by contact)")
    if t == "axis_upright":
        return ("(true)", f"{part}'s local axis {succ.get('axis')} within "
                          f"{succ.get('tolerance_deg', 20)} deg of world up (no LIBERO predicate)")
    if t == "reorient_face":
        goal, tol = succ.get("up_color") or succ.get("up_face"), succ.get("tolerance_deg", 25.0)
        return ("(true)", (f"{part}'s {goal} face up within {tol:g} deg" if goal else
                           f"{part} rolled onto a face perpendicular to the one that started up, "
                           f"within {tol:g} deg (never the opposite face)")
                + (", resting again" if succ.get("require_resting", True) else "")
                + " (no LIBERO predicate)")
    if t == "pose_target":
        reg = f"{_ident(part)}_goal_region"
        if succ.get("goal_of") is not None:
            # The goal moves with a randomized object: no fixed table region.
            return ("(true)", f"{part} on {succ['goal_of']} (within "
                              f"{float(succ.get('tol_m', 0.02)) * 1e3:g} mm and "
                              f"{float(succ.get('tol_deg', 15.0)):g} deg; no LIBERO predicate) "
                              "pose_target " + json.dumps({k: v for k, v in succ.items()
                                                           if k != "hold_s"}))
        if succ.get("goal_xy") is not None:
            (gx, gy), tol = succ["goal_xy"], float(succ.get("tol_m", 0.02))
            box = (gx - tol, gy - tol, gx + tol, gy + tol)
        elif succ.get("region"):
            r = succ["region"]
            box = (r.get("x", [-0.45, 0.45])[0], r.get("y", [-0.45, 0.45])[0],
                   r.get("x", [-0.45, 0.45])[1], r.get("y", [-0.45, 0.45])[1])
        else:
            return ("(true)", f"{part} moved >= {succ['displace_m']:g} m from its start "
                              f"(no LIBERO predicate)")
        regions.append("\n".join([f"      ({reg}", f"          (:target {TABLE})",
                                   "          (:ranges (",
                                   f"              ({' '.join(_num(v) for v in box)})",
                                   "            )", "          )", "      )"]))
        return (f"(On {part} {TABLE}_{reg})",
                "pose_target " + json.dumps({k: v for k, v in succ.items() if k != "hold_s"}))
    if t == "count":
        into = inst[succ["into"]]
        if f"(:target {into})" not in "".join(regions):
            regions.append(f"      (insertion_region\n          (:target {into})\n      )")
        objs = [inst[o] for o in succ["objects"]]
        body = " ".join(f"(In {o} {into}_insertion_region)" for o in objs)
        if int(succ["need"]) >= len(objs):
            return f"(And {body})", f"all {len(objs)} in {into} ({succ.get('mode', 'insert')})"
        return "(true)", f"{succ['need']} of {objs} in {into} ({succ.get('mode', 'insert')})"
    subs = []
    for sub in succ["of"]:
        if sub["type"] == "lift":
            subs.append((f"(Up {inst[sub.get('part') or target['name']]})", "lifted"))
        elif sub["type"] == "insert":
            into = inst[sub["into"]]
            if f"(:target {into})" not in "".join(regions):
                regions.append(f"      (insertion_region\n          (:target {into})\n      )")
            subs.append((f"(In {inst[sub.get('part') or target['name']]} {into}_insertion_region)",
                         f"{sub.get('part')} in {sub['into']}"))
        else:
            subs.append(_pose_goal(sub, inst, target, regions))
    return " ".join(g for g, _ in subs), " AND ".join(c for _, c in subs)


def to_bddl(spec: dict, name: str | None = None) -> str:
    name = _ident(name or spec.get("name", "task"))
    objs = spec["objects"]
    inst = {o["name"]: f"{_ident(o['name'])}_1" for o in objs}
    succ = {k: v for k, v in spec["success"].items() if not k.startswith("_")}
    target = next(o for o in objs if o.get("role") == "target")
    hold = succ.get("hold_s")

    regions, init, notes = [], [], []
    for o in objs:
        r = o.get("randomize") or {}
        like = r.get("like")
        if like and not o.get("on_table", True):
            reg = f"{_ident(o['name'])}_mount"
            regions.append(f"      ({reg}\n          (:target {inst[like]})\n      )")
            init.append(f"(On {inst[o['name']]} {inst[like]}_{reg})")
            notes.append(f"; {inst[o['name']]} starts on {inst[like]} and moves with its draw")
            continue
        x, y = (float(v) for v in o.get("xy", (0.0, 0.0)))
        d = r.get("xy_m", 0.0)             # one half-width, or [x, y]
        dx, dy_ = (float(d), float(d)) if isinstance(d, (int, float)) else map(float, d)
        if r.get("region") == "workspace":
            # anywhere reachable on the table: the region is the table less
            # the edge margin, and the reach limit rides along as a comment
            # (LIBERO's :ranges are rectangles; a reach annulus is not one)
            from tools.task_spec import table_half  # noqa: PLC0415
            hx, hy = table_half(spec)
            e = float(r.get("edge_margin_m", 0.05))
            x, y, dx, dy_ = 0.0, 0.0, hx - e, hy - e
            notes.append(f"; {inst[o['name']]}: anywhere on the table that is also within "
                         f"reach of {'BOTH arms of ' if r.get('reach') == 'both' else ''}"
                         f"{'the ' + r['reach'] + ' arm of ' if r.get('reach') not in (None, 'any', 'both') else ''}"
                         f"{spec.get('workspace')} (tasks/workspaces/) -- the "
                         f"rectangle above is the table less {r.get('edge_margin_m', 0.05):g} m, "
                         f"and draws out of reach are rejected")
        if like:
            rel = r.get("rel_xy_m")
            notes.append(f"; {inst[o['name']]} starts at the place above RELATIVE TO {inst[like]} and "
                         f"moves with {inst[like]}'s draw"
                         + (f", varied about that place by rel_xy_m {rel} m and rel_yaw_deg "
                            f"{r.get('rel_yaw_deg', 0)} deg (nominal layout's frame); a draw whose "
                            f"outline leaves the table is drawn again" if rel or r.get("rel_yaw_deg")
                            else ""))
        yaw0 = math.radians(float(o.get("yaw_deg", 0.0)))
        dy = math.radians(float(r.get("yaw_deg", 0.0)))
        reg = f"{_ident(o['name'])}_init_region"
        lines = [f"      ({reg}",
                 f"          (:target {TABLE})",
                 "          (:ranges (",
                 f"              ({_num(x - dx)} {_num(y - dy_)} {_num(x + dx)} {_num(y + dy_)})",
                 "            )",
                 "          )",
                 "          (:yaw_rotation (",
                 f"              ({_num(yaw0 - dy)} {_num(yaw0 + dy)})",
                 "            )",
                 "          )",
                 "      )"]
        regions.append("\n".join(lines))
        init.append(f"(On {inst[o['name']]} {TABLE}_{reg})")
        if "rot_xyzw" in o:
            notes.append(f"; {inst[o['name']]}: yaw is about world z ON TOP of its authored "
                         f"rot_xyzw {o['rot_xyzw']} (meta/task.json)")
        _ov = ("; objects are drawn independently; a scene in which two objects overlap "
               "(outline and height, tools/task_spec.footprints) is drawn again -- no "
               "minimum distance")
        if _ov not in notes:
            notes.append(_ov)

    t = succ["type"]
    tgt = inst[target["name"]]
    if t == "lift" and succ.get("objects"):
        # every named object up AT ONCE (two_cubes: one per hand) -- not just the target
        ups = [inst[o] for o in succ["objects"]]
        goal = "(And " + " ".join(f"(Up {u})" for u in ups) + ")"
        crit = (f"every one of {', '.join(ups)} raised >= {succ['height_m']:g} m above its "
                f"resting height, together")
        if succ.get("max_hands_touching") is not None:
            crit += (f", with at most {succ['max_hands_touching']} hand(s) touching them on "
                     f"every step of the hold")
    elif t == "lift":
        goal = f"(Up {tgt})"
        crit = f"{tgt} raised >= {succ['height_m']:g} m above its resting height"
    elif t == "insert":
        into = inst[succ["into"]]
        regions.append(f"      (insertion_region\n          (:target {into})\n      )")
        goal = f"(In {tgt} {into}_insertion_region)"
        # into_local may be SEVERAL holes (a tabletop's four corners); any of them counts
        holes = succ.get("into_local")
        holes = ([holes] if holes is not None and not isinstance(holes[0], (list, tuple))
                 else holes)
        where = (f" -- ANY of its {len(holes)} holes, at "
                 + ", ".join(f"[{', '.join(_num(c) for c in h)}]" for h in holes)
                 + f" in {into}'s frame" if holes and len(holes) > 1 else "")
        if "thread" in succ:
            # A THREADED insert is not In: a part pushed straight down the
            # bore satisfies In and fails this. LIBERO has no predicate for
            # it, so this names its own -- Screwed -- and tools/bddl_eval.py
            # grounds it (and refuses In on a threaded task).
            th = succ["thread"]
            goal = f"(Screwed {tgt} {into}_insertion_region)"
            crit = (f"{tgt} SCREWED into {into}{where}: its head within clearance_m "
                    f"{succ['clearance_m']:g} of the hole's axis {succ['axis']} and at least "
                    f"depth_m {succ['depth_m']:g} along it (0 = seated), reached by >= "
                    f"{th['min_turns']:g} net turns of the right-hand rule about that axis "
                    f"(clockwise from above for a downward axis) while engaged (axial >= "
                    f"{th['engagement_depth_m']:g} m) and within {th['max_tilt_deg']:g} deg of "
                    f"it, the advance staying within {th['pitch_tolerance_m']:g} m of "
                    f"{th['pitch_m']:g} m per turn -- a part pushed down or spun in place "
                    f"does not count")
        elif "through" in succ:
            th = succ["through"]
            crit = (f"{tgt}'s centreline inside {into}'s bore {th['bore_m']} (m, along axis "
                    f"{succ['axis']}) for >= {th['min_engagement_m']:g} m, either end first, "
                    f"from either mouth, within clearance_m {succ['clearance_m']:g} of the axis")
        else:
            gate = (f"head inside lateral_box_m {succ['lateral_box_m']} (m, {into}'s frame, "
                    f"about into_local {succ.get('into_local', [0, 0, 0])})"
                    if succ.get("lateral_box_m") else f"clearance_m {succ['clearance_m']:g}")
            crit = (f"insert of {tgt} into {into}{where}: {gate}, "
                    f"depth_m {succ['depth_m']:g}"
                    + (f" to max_depth_m {succ['max_depth_m']:g}" if succ.get("max_depth_m") is not None else "")
                    + f" along axis {succ['axis']} "
                    f"(meta/task.json `success` defines both)")
    elif t in ("joint_angle", "joint_open"):
        of = inst[succ.get("of", target["name"])]
        goal = f"(Open {of})"
        crit = f"{of}: {_joint_criterion(succ)}"
        if succ.get("min_tool_speed_mps"):
            crit += (f", counting only travel made while {tgt} moves >= "
                     f"{succ['min_tool_speed_mps']:g} m/s")
            if succ.get("require_tool_contact"):
                crit += (f" and touches the part {of}'s joint moves (or did within "
                         f"{float(succ.get('tool_contact_window_s', 0.0)) * 1e3:g} ms) with no "
                         f"hand on it -- checked by tools/bddl_eval.py from the contact sidecars")
    elif t == "handover":
        # LIBERO has no predicate for WHICH hand holds a thing, let alone a change of hands.
        goal = "(true)"
        crit = (f"{tgt} lifted >= {succ.get('height_m', 0.08):g} m above its rest and passed from "
                f"one hand to the other ({succ.get('direction', 'any')}): with the taker = within "
                f"{succ.get('near_m', 0.06):g} m of its thumb tip and more than "
                f"{succ.get('far_m', 0.12):g} m from the giver's; set down in between starts over")
    elif t == "joint_sequence":
        # A conjunction cannot say THEN: the steps' order is the rule, so it goes in the comment.
        goal = "(true)"
        crit = (" THEN ".join(
            f"{inst[st['of']]}'s {st.get('joint', 'joint')} {st['direction']}d "
            + (f"to {st['to']:g}" if "to" in st else f"by >= {st['fraction']:g} of its range")
            for st in succ["steps"])
            + " (each step latches once met; the last one is held; no LIBERO predicate orders them)")
    elif t in ("pose_target", "count", "all", "axis_upright", "separate", "reorient_face", "turn"):
        goal, crit = _pose_goal(succ, inst, target, regions)
    else:
        raise NotImplementedError(f"success type {t!r} has no BDDL mapping yet")
    if hold:
        crit += f", held {hold:g} s continuously"
    nc = succ.get("no_carry")
    if nc:
        # A rule over the whole episode, not a state at its end: a BDDL goal
        # cannot say "never", so it is stated here and graded by the same
        # criterion (pipeline.StaySupported) that bddl_eval replays.
        who = inst[nc.get("object") or target["name"]]
        crit += (f"; AND {who} never carried: its lowest corner (box half extents "
                 f"{', '.join(f'{float(v) * 1e3:g}' for v in nc['half_extents_m'])} mm) never "
                 f"more than {float(nc['max_height_m']) * 1e3:g} mm above the table top for "
                 f"longer than {float(nc.get('max_air_s', 0.2)):g} s -- once it is, the episode "
                 f"cannot succeed (no LIBERO predicate: a goal is an end state)")

    fixtures = [f"    {TABLE} - table"] + [f"    {inst[o['name']]} - {_asset_type(o)}"
                                           for o in objs if _fixed(o)]
    movers = [f"    {inst[o['name']]} - {_asset_type(o)}" for o in objs if not _fixed(o)]
    interest = sorted({tgt} | ({inst[succ["into"]]} if t in ("insert", "separate", "count", "turn") else set())
                      | ({inst[succ["of"]]} if isinstance(succ.get("of"), str) else set())
                      | {inst[x] for sub in (succ.get("of") if t == "all" else []) or []
                         for x in (sub.get("part"), sub.get("into")) if x}
                      | {inst[x] for x in (succ.get("objects") or []) if x in inst}
                      | {inst[st["of"]] for st in (succ.get("steps") or [])})
    hands = spec.get("hands") or "both"

    out = [
        f"; {spec.get('name', name)} -- generated from the task file by tools/task_bddl.py.",
        "; LIBERO-style BDDL (robosuite domain). Positions are metres in the table's frame",
        "; (its top centre), yaw in radians. The numbers the demos were recorded against",
        "; are meta/task.json; each episode's actual draw is in meta/episodes.jsonl.",
        f"; hands: {hands} (MANO hand, VR teleoperation; not a robosuite robot)",
        f"(define (problem vrteleop_{name})",
        "  (:domain robosuite)",
        f"  (:language {_language(spec.get('task_text', name))})",
        "    (:regions",
        *regions,
        "    )",
        "",
        "  (:fixtures",
        *fixtures,
        "  )",
        "",
        "  (:objects",
        *movers,
        "  )",
        "",
        "  (:obj_of_interest",
        *[f"    {i}" for i in interest],
        "  )",
        "",
        "  (:init",
        *[f"    {s}" for s in init],
        "  )",
        *[f"  {n}" for n in notes],
        "",
        "  (:goal",
        f"    (And {goal})",
        "  )",
        f"  ; success as graded: {crit}",
        "",
        ")",
    ]
    return "\n".join(out) + "\n"


# --------------------------------------------------------------- reading ----
def scan(text: str) -> list:
    """The s-expression as LIBERO's tokenizer (bddl.parsing.scan_tokens) reads it: `;` comments
    stripped, everything lowercased, nested lists of tokens."""
    text = re.sub(r";.*$", "", text, flags=re.MULTILINE).lower()
    stack, cur = [], []
    for tok in re.findall(r"[()]|[^\s()]+", text):
        if tok == "(":
            stack.append(cur)
            cur = []
        elif tok == ")":
            if not stack:
                raise ValueError("unbalanced parentheses: an extra ')'")
            done, cur = cur, stack.pop()
            cur.append(done)
        else:
            cur.append(tok)
    if stack or len(cur) != 1:
        raise ValueError("unbalanced parentheses, or more than one top-level form")
    return cur[0]


def parse(text: str) -> dict:
    """{problem, language, fixtures, objects, regions {key: target}, init, goal} -- the fields
    LIBERO's robosuite_parse_problem returns, with region keys spelled as it spells them
    (`<target>_<region>`)."""
    tokens = scan(text)
    if tokens[0] != "define":
        raise ValueError("not a (define ...) problem")
    groups = {g[0]: g for g in tokens[1:] if isinstance(g, list) and g}

    def typed(group):
        names, out = list(group[1:]), []
        while names:
            if names[0] == "-":
                names = names[2:]
            else:
                out.append(names.pop(0))
        return out

    regions = {}
    for reg in groups.get(":regions", [None])[1:]:
        attrs = {a[0]: a for a in reg[1:]}
        regions[attrs[":target"][1] + "_" + reg[0]] = attrs[":target"][1]
    goal = groups[":goal"][1] if ":goal" in groups else ["and"]
    return {"problem": groups["problem"][1], "language": " ".join(groups[":language"][1:]),
            "fixtures": typed(groups[":fixtures"]), "objects": typed(groups[":objects"]),
            "regions": regions, "init": groups[":init"][1:], "goal": goal}


def goal_atoms(goal) -> list[list]:
    """The goal as a conjunction of literals: (And a b ...) -> [a, b, ...], nested Ands
    flattened. A literal is an atom or a NEGATED atom, kept as ["not", atom] -- a `separate`
    task's (Not (In cap_1 bottle_1_insertion_region)). Or, and Not over anything but a single
    atom, are refused: silently reading them as a conjunction would pass what fails."""
    if goal and goal[0] == "and":
        out = []
        for g in goal[1:]:
            out += goal_atoms(g)
        return out
    if (goal and goal[0] == "not" and len(goal) == 2 and isinstance(goal[1], list)
            and goal[1] and goal[1][0] not in ("and", "or", "not")):
        return [goal]
    if goal and isinstance(goal[0], str) and goal[0] not in ("or", "not"):
        return [goal]
    raise ValueError(f"goal {goal!r} is not a conjunction of literals")


def main() -> int:
    ap = argparse.ArgumentParser(description=__doc__,
                                 formatter_class=argparse.RawDescriptionHelpFormatter)
    ap.add_argument("task", help="a task file: tasks/<task>.json or <dataset>/meta/task.json")
    ap.add_argument("-o", "--out", help="write here instead of stdout")
    a = ap.parse_args()
    with open(a.task) as fh:
        spec = json.load(fh)
    text = to_bddl(spec)
    if a.out:
        with open(a.out, "w") as fh:
            fh.write(text)
    else:
        sys.stdout.write(text)
    return 0


if __name__ == "__main__":
    sys.exit(main())