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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
468
469
# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
# SPDX-License-Identifier: Apache-2.0

from typing import Optional

import torch
from torch import Tensor

from ardy.motion_rep.tools import compute_heading_angle
from ardy.skeleton import SkeletonBase

from .geometry import axis_angle_to_matrix, matrix_to_axis_angle


def create_pairs(tensor_A, tensor_B):
    pairs = torch.stack(
        (
            tensor_A[:, None].expand(-1, len(tensor_B)),
            tensor_B.expand(len(tensor_A), -1),
        ),
        dim=-1,
    ).reshape(-1, 2)
    return pairs


def compute_global_heading(global_joints_positions: Tensor, skeleton: SkeletonBase):
    root_heading_angle = compute_heading_angle(global_joints_positions, skeleton)
    global_root_heading = torch.stack([torch.cos(root_heading_angle), torch.sin(root_heading_angle)], dim=-1)
    return global_root_heading


class Root2DConstraintSet:
    name = "root2d"

    def __init__(
        self,
        skeleton: SkeletonBase,
        frame_indices: Tensor,
        root_2d: Tensor,
        global_root_heading: Optional[Tensor] = None,
        to_crop: bool = False,
    ) -> None:
        self.skeleton = skeleton
        if to_crop:
            root_2d = root_2d[frame_indices]
            if global_root_heading is not None:
                global_root_heading = global_root_heading[frame_indices]
        else:
            assert len(root_2d) == len(frame_indices), "The number of root 2d should be match the number of frames"
            if global_root_heading is not None:
                assert len(global_root_heading) == len(frame_indices), (
                    "The number of global root heading should match the number of frames"
                )
        self.root_2d = root_2d
        self.global_root_heading = global_root_heading
        self.frame_indices = frame_indices

    def update_constraints(self, data_dict: dict, index_dict: dict) -> None:
        data_dict["root_2d"].append(self.root_2d)
        index_dict["root_2d"].append(self.frame_indices)
        if self.global_root_heading is not None:
            # Convert heading angles to [cos, sin] format
            # self.global_root_heading contains angles in radians
            heading_cos_sin = torch.stack(
                [
                    torch.cos(self.global_root_heading),
                    torch.sin(self.global_root_heading),
                ],
                dim=-1,
            )
            data_dict["global_root_heading"].append(heading_cos_sin)
            index_dict["global_root_heading"].append(self.frame_indices)

    def crop_move(self, start: int, end: int):
        mask = (self.frame_indices >= start) & (self.frame_indices < end)
        return (
            Root2DConstraintSet(
                self.skeleton,
                self.frame_indices[mask] - start,
                self.root_2d[mask],
                self.global_root_heading[mask],
            )
            if self.global_root_heading is not None
            else Root2DConstraintSet(self.skeleton, self.frame_indices[mask] - start, self.root_2d[mask])
        )

    def get_save_info(self):
        info = {
            "type": self.name,
            "frame_indices": self.frame_indices,
            "root_2d": self.root_2d,
        }
        if self.global_root_heading is not None:
            info["global_root_heading"] = self.global_root_heading
        return info

    @classmethod
    def from_dict(cls, skeleton: SkeletonBase, dico: dict):
        device = skeleton.device
        root_2d_key = "root_2d" if "root_2d" in dico else "smooth_root_2d"
        return cls(
            skeleton,
            frame_indices=torch.tensor(dico["frame_indices"]),
            root_2d=torch.tensor(dico[root_2d_key], device=device),
            global_root_heading=torch.tensor(dico["global_root_heading"]) if "global_root_heading" in dico else None,
        )


class FullBodyConstraintSet:
    name = "fullbody"

    def __init__(
        self,
        skeleton: SkeletonBase,
        frame_indices: Tensor,
        global_joints_positions: Tensor,
        global_joints_rots: Tensor,
        root_2d: Optional[Tensor] = None,
        to_crop: bool = False,
    ):
        self.skeleton = skeleton
        self.frame_indices = frame_indices

        if to_crop:
            global_joints_positions = global_joints_positions[frame_indices]
            global_joints_rots = global_joints_rots[frame_indices]
            if root_2d is not None:
                root_2d = root_2d[frame_indices]
        else:
            assert len(global_joints_positions) == len(frame_indices), (
                "The number of global positions should be match the number of frames"
            )
            assert len(global_joints_rots) == len(frame_indices), (
                "The number of global joint rotations should be match the number of frames"
            )

            if root_2d is not None:
                assert len(root_2d) == len(frame_indices), (
                    "The number of root 2d (if specified) should be match the number of frames"
                )

        if root_2d is None:
            # substitute root 2d with the real root
            root_2d = global_joints_positions[:, skeleton.root_idx, [0, 2]]

        # root y: from smooth or pelvis is the same
        self.root_y_pos = global_joints_positions[:, skeleton.root_idx, 1]

        self.global_joints_positions = global_joints_positions
        self.global_joints_rots = global_joints_rots
        self.global_root_heading = compute_global_heading(global_joints_positions, skeleton)
        self.root_2d = root_2d

    def update_constraints(self, data_dict, index_dict):
        nbjoints = self.skeleton.nbjoints
        indices_lst = create_pairs(
            self.frame_indices,
            torch.arange(nbjoints),
        )
        data_dict["global_joints_positions"].append(
            self.global_joints_positions.reshape(-1, 3)
        )  # flatten the global positions
        index_dict["global_joints_positions"].append(indices_lst)

        # global rotations are not used here

        # also constraint root 2d to get the same full body
        # maybe keep storing the hips offset, if we smooth it ourselves
        data_dict["root_2d"].append(self.root_2d)
        index_dict["root_2d"].append(self.frame_indices)

        # constraint the y pos of the root
        data_dict["root_y_pos"].append(self.root_y_pos)
        index_dict["root_y_pos"].append(self.frame_indices)

        # constraint the global heading
        data_dict["global_root_heading"].append(self.global_root_heading)
        index_dict["global_root_heading"].append(self.frame_indices)

    def crop_move(self, start: int, end: int):
        mask = (self.frame_indices >= start) & (self.frame_indices < end)
        return FullBodyConstraintSet(
            self.skeleton,
            self.frame_indices[mask] - start,
            self.global_joints_positions[mask],
            self.global_joints_rots[mask],
            self.root_2d[mask],
        )

    def get_save_info(self):
        local_joints_rot = self.skeleton.global_rots_to_local_rots(self.global_joints_rots)
        local_joints_rot = matrix_to_axis_angle(local_joints_rot)

        root_positions = self.global_joints_positions[:, self.skeleton.root_idx]
        return {
            "type": self.name,
            "frame_indices": self.frame_indices,
            "local_joints_rot": local_joints_rot,
            "root_positions": root_positions,
            "root_2d": self.root_2d,
        }

    @classmethod
    def from_dict(cls, skeleton: SkeletonBase, dico: dict):
        frame_indices = torch.tensor(dico["frame_indices"])
        device = skeleton.device
        global_joints_rots, global_joints_positions, _ = skeleton.fk(
            axis_angle_to_matrix(torch.tensor(dico["local_joints_rot"], device=device)),
            torch.tensor(dico["root_positions"], device=device),
        )
        root_2d = None
        if "root_2d" in dico:
            root_2d = torch.tensor(dico["root_2d"], device=device)
        elif "smooth_root_2d" in dico:
            root_2d = torch.tensor(dico["smooth_root_2d"], device=device)

        return cls(
            skeleton,
            frame_indices=frame_indices,
            global_joints_positions=global_joints_positions,
            global_joints_rots=global_joints_rots,
            root_2d=root_2d,
        )


class EndEffectorConstraintSet:
    name = "end-effector"

    def __init__(
        self,
        skeleton: SkeletonBase,
        frame_indices: Tensor,
        global_joints_positions: Tensor,
        global_joints_rots: Tensor,
        root_2d: Optional[Tensor],
        *,
        joint_names: list[str],
        to_crop: bool = False,
    ) -> None:
        self.skeleton = skeleton
        self.frame_indices = frame_indices
        self.joint_names = joint_names

        # joint_names are constant for all the frames
        rot_joint_names, pos_joint_names = self.skeleton.expand_joint_names(self.joint_names)
        # indexing works for motion_rep with smooth root only (contains pelvis index)
        self.pos_indices = torch.tensor([self.skeleton.bone_index[jname] for jname in pos_joint_names])
        self.rot_indices = torch.tensor([self.skeleton.bone_index[jname] for jname in rot_joint_names])

        if to_crop:
            global_joints_positions = global_joints_positions[frame_indices]
            global_joints_rots = global_joints_rots[frame_indices]
            if root_2d is not None:
                root_2d = root_2d[frame_indices]
        else:
            assert len(global_joints_positions) == len(frame_indices), (
                "The number of global positions should be match the number of frames"
            )
            assert len(global_joints_rots) == len(frame_indices), (
                "The number of global joint rotations should be match the number of frames"
            )
            if root_2d is not None:
                assert len(root_2d) == len(frame_indices), (
                    "The number of root 2d (if specified) should be match the number of frames"
                )

        if root_2d is None:
            # substitute root 2d with the real root
            root_2d = global_joints_positions[:, skeleton.root_idx, [0, 2]]

        # root y: from smooth or pelvis is the same
        self.root_y_pos = global_joints_positions[:, skeleton.root_idx, 1]

        self.global_joints_positions = global_joints_positions
        self.global_root_heading = compute_global_heading(global_joints_positions, skeleton)
        self.global_joints_rots = global_joints_rots
        self.root_2d = root_2d

    def update_constraints(self, data_dict, index_dict):
        crop_frames_indexing = torch.arange(len(self.frame_indices))

        # constraint positions
        pos_indices_real = create_pairs(
            self.frame_indices,
            self.pos_indices,
        )
        pos_indices_crop = create_pairs(
            crop_frames_indexing,
            self.pos_indices,
        )
        data_dict["global_joints_positions"].append(self.global_joints_positions[tuple(pos_indices_crop.T)])
        index_dict["global_joints_positions"].append(pos_indices_real)

        # constraint rotations
        rot_indices_real = create_pairs(
            self.frame_indices,
            self.rot_indices,
        )
        rot_indices_crop = create_pairs(
            crop_frames_indexing,
            self.rot_indices,
        )
        data_dict["global_joints_rots"].append(self.global_joints_rots[tuple(rot_indices_crop.T)])
        index_dict["global_joints_rots"].append(rot_indices_real)

        # also constraint root 2d to get the same full body
        # maybe keep storing the hips offset, if we smooth it ourselves
        data_dict["root_2d"].append(self.root_2d)
        index_dict["root_2d"].append(self.frame_indices)

        # constraint the y pos of the root
        data_dict["root_y_pos"].append(self.root_y_pos)
        index_dict["root_y_pos"].append(self.frame_indices)

        # constraint the global heading
        data_dict["global_root_heading"].append(self.global_root_heading)
        index_dict["global_root_heading"].append(self.frame_indices)

    def crop_move(self, start: int, end: int):
        mask = (self.frame_indices >= start) & (self.frame_indices < end)

        cls = type(self)
        kwargs = {}
        if not hasattr(cls, "joint_names"):
            kwargs["joint_names"] = self.joint_names

        return cls(
            self.skeleton,
            self.frame_indices[mask] - start,
            self.global_joints_positions[mask],
            self.global_joints_rots[mask],
            self.root_2d[mask],
            **kwargs,
        )

    def get_save_info(self):
        local_joints_rot = self.skeleton.global_rots_to_local_rots(self.global_joints_rots)
        local_joints_rot = matrix_to_axis_angle(local_joints_rot)

        root_positions = self.global_joints_positions[:, self.skeleton.root_idx]
        output = {
            "type": self.name,
            "frame_indices": self.frame_indices,
            "local_joints_rot": local_joints_rot,
            "root_positions": root_positions,
            "root_2d": self.root_2d,
        }
        if not hasattr(self.__class__, "joint_names"):
            # save the joint_names for this base class
            # but not for children
            output["joint_names"] = self.joint_names
        return output

    @classmethod
    def from_dict(cls, skeleton: SkeletonBase, dico: dict):
        frame_indices = torch.tensor(dico["frame_indices"])
        device = skeleton.device
        global_joints_rots, global_joints_positions, _ = skeleton.fk(
            axis_angle_to_matrix(torch.tensor(dico["local_joints_rot"], device=device)),
            torch.tensor(dico["root_positions"], device=device),
        )
        root_2d = None
        if "root_2d" in dico:
            root_2d = torch.tensor(dico["root_2d"], device=device)
        elif "smooth_root_2d" in dico:
            root_2d = torch.tensor(dico["smooth_root_2d"], device=device)

        kwargs = {}
        if not hasattr(cls, "joint_names"):
            kwargs["joint_names"] = dico["joint_names"]

        return cls(
            skeleton,
            frame_indices=frame_indices,
            global_joints_positions=global_joints_positions,
            global_joints_rots=global_joints_rots,
            root_2d=root_2d,
            **kwargs,
        )


class LeftHandConstraintSet(EndEffectorConstraintSet):
    name = "left-hand"
    joint_names: list[str] = ["LeftHand", "Hips"]

    def __init__(self, *args, **kwargs: dict):
        super().__init__(*args, joint_names=self.joint_names, **kwargs)


class RightHandConstraintSet(EndEffectorConstraintSet):
    name = "right-hand"
    joint_names: list[str] = ["RightHand", "Hips"]

    def __init__(self, *args, **kwargs: dict):
        super().__init__(*args, joint_names=self.joint_names, **kwargs)


class LeftFootConstraintSet(EndEffectorConstraintSet):
    name = "left-foot"
    joint_names: list[str] = ["LeftFoot", "Hips"]

    def __init__(self, *args, **kwargs: dict):
        super().__init__(*args, joint_names=self.joint_names, **kwargs)


class RightFootConstraintSet(EndEffectorConstraintSet):
    name = "right-foot"
    joint_names: list[str] = ["RightFoot", "Hips"]

    def __init__(self, *args, **kwargs: dict):
        super().__init__(*args, joint_names=self.joint_names, **kwargs)


TYPE_TO_CLASS = {
    "root2d": Root2DConstraintSet,
    "fullbody": FullBodyConstraintSet,
    "left-hand": LeftHandConstraintSet,
    "right-hand": RightHandConstraintSet,
    "left-foot": LeftFootConstraintSet,
    "right-foot": RightFootConstraintSet,
    "end-effector": EndEffectorConstraintSet,
}


def load_constraints_lst(path_or_data: str | list, skeleton: SkeletonBase):
    from ardy.tools import load_json

    if isinstance(path_or_data, str):
        saved = load_json(path_or_data)
    else:
        saved = path_or_data

    constraints_lst = []
    for el in saved:
        cls = TYPE_TO_CLASS[el["type"]]
        constraints_lst.append(cls.from_dict(skeleton, el))
    return constraints_lst


def save_constraints_lst(path: str, constraints_lst):
    from ardy.tools import save_json

    if not constraints_lst:
        print("The constraints lst is empty. Skip saving")
        return

    to_save = []

    def tensor_to_list(obj):
        """Recursively convert tensors to lists for JSON serialization."""
        if isinstance(obj, Tensor):
            return obj.cpu().tolist()
        elif isinstance(obj, dict):
            return {k: tensor_to_list(v) for k, v in obj.items()}
        elif isinstance(obj, list):
            return [tensor_to_list(v) for v in obj]
        else:
            return obj

    for constraint in constraints_lst:
        constraint_info = constraint.get_save_info()
        # Convert all tensors to lists for JSON serialization
        constraint_info = tensor_to_list(constraint_info)
        to_save.append(constraint_info)

    save_json(path, to_save)
    print(f"Saved constraints to {path}")
    return to_save