File size: 4,522 Bytes
870b85a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""Native fixed-waist, position-only checks for the actual task endpoints."""
import argparse
import json
from pathlib import Path
import sys

from .preflight import NativeReachPreflight, position_gate, sha256


def aggregate(records, *, unchanged):
    passed = (unchanged is True and len(records) == 2
              and {r['endpoint'] for r in records} == {'pick', 'place'}
              and all(r['gate']['position_reachable'] is True for r in records))
    return {'passed': passed, 'all_source_inputs_unchanged': unchanged,
            'position_only': True, 'grasp_qualified': False, 'whole_task_acceptance': False}


def run(args):
    import numpy as np
    sys.path.insert(0, str(args.sdk_root))
    from isaaclab_arena_g1.g1_whole_body_controller.wbc_policy.g1_wbc_upperbody_ik.g1_wbc_upperbody_controller import G1WBCUpperbodyController

    if args.out.exists() or not 1 <= args.iterations <= 500:
        raise ValueError('IK output must be new and iteration count bounded')
    source = args.sdk_root / 'isaaclab_arena_g1/g1_whole_body_controller/wbc_policy/g1_wbc_upperbody_ik/g1_wbc_upperbody_controller.py'
    paths = [args.task, args.urdf, source, Path(__file__), Path(__file__).with_name('preflight.py')]
    hashes = {str(p): sha256(p) for p in paths}
    task = json.loads(args.task.read_text())
    records = []
    for endpoint in ('pick', 'place'):
        native = NativeReachPreflight.from_sdk(args.urdf, args.sdk_root)
        item = task[endpoint]
        # Homie-v2 nominal standing pelvis height; this is not measured grasp posture.
        geometry = native.geometry(item['position_xyz_m'], item['approach_pose'], .75)
        record = {'endpoint': endpoint, 'geometry': geometry,
                  'gate': position_gate(geometry, None), 'trace': []}
        if geometry['inside_outer_bound']:
            robot = native.robot
            controller = G1WBCUpperbodyController(robot, body_active_joint_groups=['arms'])
            solver = controller.body_ik_solver
            solver.update_weights({native.frame: {'orientation_cost': 0.0}})
            target = np.eye(4)
            target[:3, 3] = geometry['target_pelvis_xyz_m']
            q = controller.body.reduced_to_full_configuration(solver.configuration.q)
            for step in range(args.iterations + 1):
                if step:
                    q = controller.inverse_kinematics({native.frame: target}, 0, 0)
                robot.cache_forward_kinematics(q, auto_clip=False)
                fk = robot.frame_placement(native.frame)
                internal = solver.configuration.get_transform_frame_to_world(native.frame)
                evidence = {'request_sha256': geometry['request_sha256'], 'step': step,
                    'position_error_m': float(np.linalg.norm(fk.translation - target[:3, 3])),
                    'joint_limit_violation_rad': float(max(0, np.max(robot.lower_joint_limits - q),
                                                           np.max(q - robot.upper_joint_limits))),
                    'fixed_chain_max_abs_rad': max([abs(float(q[x['index']]) - x['q0_rad'])
                        for x in native.fixed_ancestors] or [0]),
                    'returned_full_vs_internal_fk_max_abs': float(np.max(np.abs(fk.homogeneous - internal.homogeneous)))}
                record['trace'].append(evidence)
                if evidence['position_error_m'] <= .001 and step > 0:
                    break
            record.update(final=evidence, final_q=q.tolist(), final_fk_matrix=fk.homogeneous.tolist(),
                          joint_names=robot.joint_names, gate=position_gate(geometry, evidence))
        records.append(record)
    unchanged = all(sha256(p) == digest for p, digest in hashes.items())
    report = {'schema': 'rhg.native-position-ik.v1', 'task_sha256': hashes[str(args.task)],
              'input_sha256': hashes, 'runs': records, 'pelvis_height_m': .75,
              'frame': 'left_wrist_yaw_link', 'position_tolerance_m': .01,
              **aggregate(records, unchanged=unchanged)}
    args.out.write_text(json.dumps(report, indent=2, allow_nan=False) + '\n')
    return 0 if report['passed'] else 2


def main(argv=None):
    parser = argparse.ArgumentParser(description=__doc__)
    for name in ('sdk-root', 'urdf', 'task', 'out'):
        parser.add_argument('--' + name, required=True, type=Path)
    parser.add_argument('--iterations', type=int, default=150)
    return run(parser.parse_args(argv))


if __name__ == '__main__':
    raise SystemExit(main())