File size: 5,632 Bytes
9ffd3e8
33c14d6
 
 
 
9ffd3e8
 
 
 
33c14d6
 
 
9ffd3e8
 
 
33c14d6
 
 
 
 
 
9ffd3e8
33c14d6
 
 
 
 
 
 
 
 
 
9ffd3e8
33c14d6
 
9ffd3e8
 
 
 
 
33c14d6
 
 
 
 
 
 
 
 
 
 
9ffd3e8
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
33c14d6
9ffd3e8
 
33c14d6
fad6045
 
9ffd3e8
 
33c14d6
9ffd3e8
33c14d6
 
 
9ffd3e8
 
33c14d6
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9ffd3e8
 
 
33c14d6
9ffd3e8
 
 
 
 
 
 
 
 
 
33c14d6
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""Chess-set and board variants compiled from the generated scene.

Each set scales the reference Staunton meshes per piece type: one width scale and
one height scale, so height, foot, neck height and neck width all change together
within the ranges in phase2_config.toml. Mass and inertia follow the new volume.
A set also carries its board and tray geometry (make_scene.Layout: square size,
border, board thickness, tray size); pieces scale with the square, as real sets do.
The scene file itself is never edited: a variant's layout is generated to a
temporary file, and the pieces are scaled with MjSpec before compiling.
"""
from __future__ import annotations

import itertools
import os
from dataclasses import asdict, dataclass, field
from pathlib import Path

import mujoco
import numpy as np

from chess_world import KINDS
from make_scene import NOMINAL, PIECES, SQUARE, Layout, build_scene

HERE = Path(__file__).resolve().parent
SCENE = HERE / "chess_scene.xml"


@dataclass
class PieceSet:
    name: str
    width: dict = field(default_factory=lambda: {k: 1.0 for k in KINDS})
    height: dict = field(default_factory=lambda: {k: 1.0 for k in KINDS})
    layout: Layout = NOMINAL

    def describe(self) -> dict:
        out = {k: dict(height_mm=round(PIECES[k]["height_m"] * self.height[k] * 1000, 1),
                       foot_mm=round(foot_mm(k) * self.width[k], 1)) for k in KINDS}
        out["layout"] = {k: (round(v * 1000, 1) if isinstance(v, float) else [round(x * 1000, 1) for x in v])
                         for k, v in asdict(self.layout).items()}     # millimetres
        return out


def foot_mm(kind: str) -> float:
    lo, hi = np.array(PIECES[kind]["bounds_m"])
    return float(np.max(hi[:2] - lo[:2]) * 1000)


def reference_set() -> PieceSet:
    return PieceSet("reference")


PAN_X = 0.0388      # shoulder pan axis in front of the arm base, from the arm model


def sample_layout(rng: np.random.Generator, cfg: dict) -> Layout:
    """A random board and tray. Boards the arm cannot serve even square and flush
    against the deck (a 25 mm board with a wide border puts the far corners out of
    reach) are redrawn; the per-episode board pose then has some room left to move."""
    import scene_environment as env

    c, b = cfg["layout"], cfg["board"]
    mm = lambda key: rng.uniform(*c[key]) / 1000
    for _ in range(1000):
        layout = Layout(square=mm("square_mm"), board_t=mm("board_thickness_mm"), border=mm("border_mm"),
                        tray_half=(mm("tray_half_x_mm"), mm("tray_half_y_mm")), tray_rim=mm("tray_rim_mm"))
        centre = env.DECK_FRONT + b["deck_gap_m"] + 4 * layout.square + layout.border
        far = np.hypot(centre + 3.5 * layout.square - PAN_X, 3.5 * layout.square)
        if far <= b["reach_m"] - c["min_slack_m"]:
            return layout
    raise RuntimeError("no layout within reach")


def sample_piece_set(rng: np.random.Generator, cfg: dict, name: str) -> PieceSet:
    """A random piece set on a random board and tray (the [layout] ranges), or on the
    nominal board if the config has no [layout]. Piece sizes follow the square size."""
    c = cfg["piece_sets"]
    if c.get("fixed"):
        return PieceSet(name)                 # reference set on the nominal board and tray
    layout = sample_layout(rng, cfg) if "layout" in cfg else NOMINAL
    k_sq = layout.square / SQUARE
    for _ in range(100):
        scale = rng.uniform(*c["scale"]) * k_sq
        stretch = rng.uniform(*c["height_stretch"])
        width = {k: scale for k in KINDS}
        height = {k: scale * stretch * rng.uniform(*c["per_kind_height"]) for k in KINDS}
        if all(foot_mm(k) * width[k] <= c["max_foot_mm"] * k_sq for k in KINDS):
            return PieceSet(name, width, height, layout)
    raise RuntimeError("no piece set satisfies max_foot_mm")


def _second_moments(inertia):
    """Per-body second moments of mass about the COM from MuJoCo fullinertia."""
    ixx, iyy, izz, ixy, ixz, iyz = inertia
    return np.array([[(iyy + izz - ixx) / 2, -ixy, -ixz],
                     [-ixy, (ixx + izz - iyy) / 2, -iyz],
                     [-ixz, -iyz, (ixx + iyy - izz) / 2]])


def _fullinertia(S):
    return [S[1, 1] + S[2, 2], S[0, 0] + S[2, 2], S[0, 0] + S[1, 1], -S[0, 1], -S[0, 2], -S[1, 2]]


_variant_ids = itertools.count()


def compile_scene(piece_set: PieceSet, scene: Path = SCENE) -> mujoco.MjModel:
    if piece_set.layout == NOMINAL:
        spec = mujoco.MjSpec.from_file(str(scene))
    else:
        # Next to the scene file so its relative includes and mesh paths resolve.
        tmp = scene.parent / f".variant_{os.getpid()}_{next(_variant_ids)}.xml"
        tmp.write_text(build_scene(piece_set.layout))
        try:
            spec = mujoco.MjSpec.from_file(str(tmp))
        finally:
            tmp.unlink()
    for mesh in spec.meshes:
        if mesh.name.startswith("chess_"):
            kind = mesh.name.split("_")[1]
            w, h = piece_set.width[kind], piece_set.height[kind]
            mesh.scale = [w, w, h]
    for body in spec.bodies:
        if not body.name.startswith(("w_", "b_")):
            continue
        kind = body.name.split("_")[1]
        p = PIECES[kind]
        w, h = piece_set.width[kind], piece_set.height[kind]
        k = np.diag([w, w, h])
        S = k @ _second_moments(p["fullinertia_kg_m2"]) @ k * (w * w * h)
        body.mass = p["mass_kg"] * w * w * h
        body.ipos = np.array(p["center_of_mass_m"]) * [w, w, h]
        body.fullinertia = _fullinertia(S)
        for site in body.sites:
            site.pos = [0, 0, p["grasp_z_m"] * h]
    return spec.compile()