File size: 11,709 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
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
"""Bounded commands and conservative checks for the v6 navigation diagnostic."""
import math


def wrap_angle(value):
    return math.atan2(math.sin(value), math.cos(value))


def yaw_wxyz(quat):
    w,x,y,z=quat
    return math.atan2(2*(w*z+x*y),1-2*(y*y+z*z))


def velocity_command(position, yaw, goal, goal_yaw=None):
    dx,dy=goal[0]-position[0],goal[1]-position[1]
    distance=math.hypot(dx,dy)
    speed=min(.22,.8*distance)
    scale=speed/distance if distance>.001 else 0.
    vx=(dx*math.cos(yaw)+dy*math.sin(yaw))*scale
    vy=(-dx*math.sin(yaw)+dy*math.cos(yaw))*scale
    heading=goal_yaw if goal_yaw is not None else math.atan2(dy,dx)
    wz=max(-.5,min(.5,1.2*wrap_angle(heading-yaw)))
    return vx,vy,wz


class RouteTracker:
    """World-frame PI feedback with bounded drift compensation per segment."""
    def __init__(self):
        self.integral=[0.,0.]
        self.heading_integral=0.
        self.goal=None

    def command(self,position,yaw,goal,segment_start,dt,goal_yaw=None,turn_first=False,heading_hold=False):
        values=[*position,*goal,*segment_start,yaw,dt]
        if (any(len(v)!=2 for v in (position,goal,segment_start))
                or not all(math.isfinite(v) for v in values) or not 0<dt<=.03
                or (goal_yaw is not None and not math.isfinite(goal_yaw))):
            raise ValueError('Invalid tracking state')
        if tuple(goal)!=self.goal:
            self.integral=[0.,0.];self.heading_integral=0.;self.goal=tuple(goal)
        dx,dy=goal[0]-segment_start[0],goal[1]-segment_start[1]
        heading=goal_yaw if goal_yaw is not None else (math.atan2(dy,dx) if dx or dy else yaw)
        angle=wrap_angle(heading-yaw)
        if heading_hold:
            proposed_heading=max(-.2,min(.2,self.heading_integral+.35*angle*dt))
            raw_heading=1.2*angle+proposed_heading
            if abs(raw_heading)<=.5 or raw_heading*angle<0:
                self.heading_integral=proposed_heading
        else:self.heading_integral=0.
        wz=max(-.5,min(.5,1.2*angle+self.heading_integral))
        if turn_first:
            if goal_yaw is None:raise ValueError('Turn gate requires a heading')
            angle=wrap_angle(goal_yaw-yaw)
            if abs(angle)>=.10:
                self.integral=[0.,0.]
                return 0.,0.,wz
        error=[goal[i]-position[i] for i in range(2)]
        proposed=[self.integral[i]+.35*error[i]*dt for i in range(2)]
        size=math.hypot(*proposed)
        if size>.12:proposed=[v*.12/size for v in proposed]
        # Freeze integration when saturation and error would push in the same direction.
        raw=[.8*error[i]+proposed[i] for i in range(2)]
        if math.hypot(*raw)<=.22 or sum(raw[i]*error[i] for i in range(2))<0:
            self.integral=proposed
        velocity=[.8*error[i]+self.integral[i] for i in range(2)]
        size=math.hypot(*velocity)
        if size>.22:velocity=[v*.22/size for v in velocity]
        vx=velocity[0]*math.cos(yaw)+velocity[1]*math.sin(yaw)
        vy=-velocity[0]*math.sin(yaw)+velocity[1]*math.cos(yaw)
        return vx,vy,wz


def approach_heading_plan(route,pick_index,pick_yaw,place_yaw,clearance_distance=.4):
    """Face the support before entering its approach, including pick retreat."""
    if (len(route)<3 or not 0<pick_index<len(route)-1 or clearance_distance<=0
            or not all(len(p)==2 and all(math.isfinite(v) for v in p) for p in route)
            or not all(math.isfinite(v) for v in (pick_yaw,place_yaw,clearance_distance))):
        raise ValueError('Invalid approach heading plan')
    def boundary(index,direction):
        distance=0.;current=index
        while distance<=clearance_distance+1.e-9 and 0<=current+direction<len(route):
            following=current+direction
            distance+=math.dist(route[current],route[following]);current=following
        return current
    pick_start=boundary(pick_index,-1);pick_end=boundary(pick_index,1)
    place_start=boundary(len(route)-1,-1)
    if pick_start<1 or pick_end>=place_start:
        raise ValueError('Approach turn regions overlap or have no safe entry segment')
    plan={i:dict(heading=pick_yaw,phase='pick_approach',turn_first=True)
          for i in range(pick_start,pick_end+1)}
    plan[pick_start]['phase']='prepare_pick'
    for i in range(place_start,len(route)):
        plan[i]=dict(heading=place_yaw,phase='place_approach',turn_first=True)
    plan[place_start]['phase']='prepare_place'
    return plan


def obstacle_meshes(meshes):
    """Exclude only saved floor slabs and rugs from foot-obstacle attribution."""
    result=[];seen=set()
    for row in meshes:
        path=row['prim_path'];name=row['name'];identifier=row['entity_id']
        if not path.startswith('/House/') or path in seen:
            raise ValueError('Invalid or duplicate saved obstacle path')
        seen.add(path)
        if identifier is None and name.startswith('floor__'):continue
        if identifier is not None and '__rug__' in identifier:continue
        result.append(row)
    if not result:raise ValueError('Missing obstacle collision meshes')
    return result


def segment_distance(point,a,b):
    dx,dy=b[0]-a[0],b[1]-a[1]
    length=dx*dx+dy*dy
    t=max(0.,min(1.,((point[0]-a[0])*dx+(point[1]-a[1])*dy)/length)) if length else 0.
    return math.dist(point[:2],(a[0]+t*dx,a[1]+t*dy))


def contact_metrics(names,vectors):
    feet=('left_ankle_roll_link','right_ankle_roll_link')
    if len(names)!=len(vectors) or not all(name in names for name in feet):
        raise ValueError('Incomplete body contact coverage')
    forces={}
    for name,vector in zip(names,vectors):
        if len(vector)!=3 or not all(math.isfinite(v) for v in vector):
            raise ValueError('Invalid measured contact force')
        forces[name]=math.sqrt(sum(v*v for v in vector))
    return dict(nonfoot_scene_contact_N=max((v for n,v in forces.items() if n not in feet),default=0.),
                left_foot_contact_N=forces[feet[0]],right_foot_contact_N=forces[feet[1]])


def filtered_contact_peak(vectors):
    if not vectors:raise ValueError('Missing filtered foot contacts')
    for vector in vectors:
        if len(vector)!=3 or not all(math.isfinite(v) for v in vector):
            raise ValueError('Nonfinite filtered foot contact')
    return max(math.sqrt(sum(v*v for v in vector)) for vector in vectors)


def summarize_navigation(rows,route,*,pick_index,pick_yaw,place_yaw,required_rugs,
                         reset_count,root_pose_write_count):
    reasons=set();next_waypoint=0;previous=None
    hold_start={'pick_hold':None,'place_hold':None}
    hold_duration={'pick_hold':0.,'place_hold':0.}
    rug_forces={identifier:0. for identifier in required_rugs}
    minimum_height=math.inf;maximum_tilt=0.;maximum_deviation=0.;maximum_contact=0.;maximum_ankle_contact=0.
    if len(route)<2 or not 0<pick_index<len(route):raise ValueError('Invalid ordered route')
    if reset_count!=1 or root_pose_write_count!=1:reasons.add('unexpected_reset_or_pose_write')
    for row in rows:
        try:
            xyz=row['root_xyz'];quat=row['root_quat_wxyz'];now=row['time_s']
            contacts=row['rug_contact_N'];body_contact=row['nonfoot_scene_contact_N']
            ankle_contact=row['maximum_ankle_obstacle_contact_N']
            values=[now,*xyz,*quat,body_contact,ankle_contact,*contacts.values()]
            if (len(xyz)!=3 or len(quat)!=4 or not all(math.isfinite(v) for v in values)
                    or ankle_contact<0):
                raise ValueError('Invalid pose/contact sample')
            norm=math.sqrt(sum(v*v for v in quat))
            if abs(norm-1)>.01:raise ValueError('Invalid quaternion')
            command=row.get('command_body_velocity',[])
            if (len(command)!=3 or not all(math.isfinite(v) for v in command)
                    or math.hypot(*command[:2])>.220001 or abs(command[2])>.500001):
                reasons.add('invalid_command')
            w,x,y,z=[v/norm for v in quat]
            tilt=math.degrees(math.acos(max(-1.,min(1.,1-2*(x*x+y*y)))))
            minimum_height=min(minimum_height,xyz[2]);maximum_tilt=max(maximum_tilt,tilt)
            maximum_contact=max(maximum_contact,body_contact)
            maximum_ankle_contact=max(maximum_ankle_contact,ankle_contact)
            if xyz[2]<.5 or xyz[2]>1.2 or tilt>40:reasons.add('fall_or_excessive_tilt')
            if body_contact>20.:reasons.add('nonfoot_scene_collision')
            if ankle_contact>20.:reasons.add('ankle_obstacle_collision')
            deviation=min(segment_distance(xyz,a,b) for a,b in zip(route,route[1:]))
            maximum_deviation=max(maximum_deviation,deviation)
            if deviation>.2:reasons.add('left_planned_route')
            while next_waypoint<len(route) and math.dist(xyz[:2],route[next_waypoint])<=.08:
                next_waypoint+=1
            for phase,goal,heading in (('pick_hold',route[pick_index],pick_yaw),
                                       ('place_hold',route[-1],place_yaw)):
                stable=(row.get('phase')==phase and math.dist(xyz[:2],goal)<=.08
                        and abs(wrap_angle(yaw_wxyz(quat)-heading))<=.12)
                continuous=previous is not None and 0<now-previous['time_s']<=.030001
                if stable:
                    if hold_start[phase] is None or not continuous:hold_start[phase]=now
                    hold_duration[phase]=max(hold_duration[phase],now-hold_start[phase])
                else:hold_start[phase]=None
            for identifier in required_rugs:
                rug_forces[identifier]=max(rug_forces[identifier],contacts.get(identifier,0.))
            if previous is not None:
                dt=now-previous['time_s'];distance=math.dist(xyz,previous['root_xyz'])
                if dt<=0:reasons.add('nonmonotonic_time')
                else:
                    if dt>.030001:reasons.add('sampling_gap')
                    if distance>.1 or distance/dt>2.:reasons.add('discontinuous_motion')
            previous=row
        except (ValueError,TypeError,KeyError,IndexError):
            reasons.add('invalid_trace')
            hold_start={'pick_hold':None,'place_hold':None};previous=None
    try:
        if not rows or rows[-1]['time_s']-rows[0]['time_s']<10.:reasons.add('insufficient_duration')
    except (KeyError,TypeError):reasons.add('invalid_trace')
    if next_waypoint!=len(route):reasons.add('incomplete_route')
    if hold_duration['pick_hold']<1.-1.e-6:reasons.add('pick_hold_not_measured')
    if hold_duration['place_hold']<2.-1.e-6:reasons.add('place_hold_not_measured')
    try:
        if not rows or math.dist(rows[-1]['root_xyz'][:2],route[-1])>.08:
            reasons.add('place_position_not_reached')
        if not rows or abs(wrap_angle(yaw_wxyz(rows[-1]['root_quat_wxyz'])-place_yaw))>.12:
            reasons.add('place_facing_not_reached')
    except (KeyError,TypeError,ValueError):reasons.add('invalid_trace')
    for identifier,force in rug_forces.items():
        if force<=1.:reasons.add('unverified_rug_contact:'+identifier)
    return dict(passed=not reasons,reasons=sorted(reasons),samples=len(rows),
        visited_waypoints=next_waypoint,total_waypoints=len(route),
        minimum_root_height_m=minimum_height if math.isfinite(minimum_height) else None,
        maximum_tilt_deg=maximum_tilt,maximum_route_deviation_m=maximum_deviation,
        maximum_nonfoot_scene_contact_N=maximum_contact,maximum_rug_contact_N=rug_forces,
        maximum_ankle_obstacle_contact_N=maximum_ankle_contact,
        measured_hold_duration_s=hold_duration,
        whole_task_acceptance=False,scope='v6_collision_only_native_controller_navigation_diagnostic')