rssr / 1500case /source /tabletop_scene.py
starry0929's picture
Add missing 1500-case scene, robot models, physical revision and IK dependencies
35f4d03 verified
Raw History Blame Contribute Delete
6.41 kB
"""Fixed synthetic table and robot-table collision checks for the S1 IK benchmark."""
import pathlib,json,copy,hashlib,xml.etree.ElementTree as ET
import numpy as np
import mujoco
TABLE={'width_m':1.2,'depth_m':.8,'height_m':.75,'thickness_m':.05,
'center_xy_world_m':[0.,-.75],'assumed_not_measured':True}
def build_scene(destination):
root=pathlib.Path('/pfs/yichen/r2r/models/trackc')
base=root/'astribot_s1_ik/astribot_s1_ik.xml'
official=root/'astribot_descriptions/mjcf/astribot_s1_mjcf'
assets_path=official/'assets/astribot_s1_asset_for_gripper.xml'
tree=ET.parse(base);xml=tree.getroot();world=xml.find('worldbody')
official_tree=ET.parse(official/'model_with_effector/astribot_s1_model_with_gripper.xml').getroot()
source_bodies={b.get('name'):b for b in official_tree.iter('body')}
source_bodies['chassis_base']=official_tree
all_meshes={x.get('name'):x for x in ET.parse(assets_path).getroot().iter('mesh')}
needed=set();attached=[]
for body in world.iter('body'):
src=source_bodies.get(body.get('name'))
if src is None:continue
for geom in list(body.findall('geom')):body.remove(geom)
for k,g in enumerate(src.findall('geom')):
if g.get('type')!='mesh':continue
attrs={k:v for k,v in g.attrib.items() if k in ['type','mesh','pos','quat','euler']}
attrs.update(name='robot_'+body.get('name')+'_'+str(k),contype='1',conaffinity='2',density='0',rgba='.62 .67 .72 1')
ET.SubElement(body,'geom',**attrs);needed.add(g.get('mesh'));attached.append(attrs['name'])
if body.get('name','').endswith('link_7') and 'arm_' in body.get('name',''):
ET.SubElement(body,'geom',name='gripper_envelope_'+body.get('name'),type='capsule',
fromto='0 -0.03 0 0 -0.15 0',size='.035',contype='1',conaffinity='2',density='0',rgba='.25 .3 .35 1')
asset=ET.SubElement(xml,'asset');mesh_files={}
for n in sorted(needed):
g=copy.deepcopy(all_meshes[n]);p=(assets_path.parent/g.get('file')).resolve();assert p.is_file(),str(p)
if p.stat().st_size<200 and p.read_bytes().startswith(b'version https://git-lfs'):
alternatives=list((root/'astribot_descriptions/urdf/astribot_s1_urdf/meshes').rglob(p.stem+'.STL'))
assert len(alternatives)==1, 'Missing actual mesh '+str(p)
p=alternatives[0]
g.set('file',str(p));asset.append(g);mesh_files[str(p)]=hashlib.sha256(p.read_bytes()).hexdigest()
x,y=TABLE['center_xy_world_m'];w=TABLE['width_m'];d=TABLE['depth_m'];h=TABLE['height_m'];t=TABLE['thickness_m']
table=ET.SubElement(world,'body',name='worktable',pos=f'{x} {y} 0')
ET.SubElement(table,'geom',name='worktable_top',type='box',pos=f'0 0 {h-t/2}',size=f'{w/2} {d/2} {t/2}',
contype='2',conaffinity='1',rgba='.43 .29 .17 1')
for i,(sx,sy) in enumerate([(-1,-1),(-1,1),(1,-1),(1,1)]):
ET.SubElement(table,'geom',name=f'worktable_leg_{i}',type='box',pos=f'{sx*(w/2-.07)} {sy*(d/2-.07)} {(h-t)/2}',
size=f'.025 .025 {(h-t)/2}',contype='2',conaffinity='1',rgba='.25 .27 .3 1')
ET.SubElement(world,'geom',name='visual_floor',type='plane',size='3 3 .01',contype='0',conaffinity='0',rgba='.16 .2 .24 1')
visual=ET.SubElement(xml,'visual');ET.SubElement(visual,'global',offwidth='960',offheight='640')
ET.SubElement(visual,'headlight',ambient='.5 .5 .5',diffuse='.6 .6 .6')
destination=pathlib.Path(destination);destination.parent.mkdir(parents=True,exist_ok=True)
tree.write(destination,encoding='unicode')
m=mujoco.MjModel.from_xml_path(str(destination));old=mujoco.MjModel.from_xml_path(str(base))
assert m.nq==old.nq==18 and np.allclose(m.body_pos[:old.nbody],old.body_pos)
info={'table':TABLE,'robot_meshes':len(needed),'robot_mesh_geoms':len(attached),'nq':m.nq,
'mesh_collision':'MuJoCo convex hulls of per-link visual meshes; conservative approximation',
'gripper_collision':'Fixed capsule envelope, no actuated finger/contact model',
'robot_self_collision_checked':False,'robot_table_collision_checked':True,
'task_object_dynamics':False,'mesh_sha256':mesh_files,'model_sha256':hashlib.sha256(destination.read_bytes()).hexdigest()}
destination.with_suffix('.json').write_text(json.dumps(info,indent=2))
return info
def contact_summary(model,data):
pairs=[];worst=0.
for i in range(data.ncon):
c=data.contact[i]
if c.dist>=-1e-5:continue
a=mujoco.mj_id2name(model,mujoco.mjtObj.mjOBJ_GEOM,c.geom1) or ''
b=mujoco.mj_id2name(model,mujoco.mjtObj.mjOBJ_GEOM,c.geom2) or ''
if a.startswith('worktable_') or b.startswith('worktable_'):
pairs.append([a,b]);worst=max(worst,-float(c.dist))
return pairs,worst
def check_trajectory(ev,left_q,right_q,up_q):
q=np.concatenate([up_q,left_q,right_q],axis=1);solver=ev._ik_solver.coupled
adr=np.concatenate([solver.upstream.qpos_adr]+[a.qpos_adr for a in solver.arms])
data=mujoco.MjData(ev._model);count=0;hits=0;worst=0.;pairs=set()
for i,end in enumerate(q):
start=q[i-1] if i else end
sub=max(1,int(np.ceil(np.max(np.abs(end-start))/.05)))
for alpha in np.arange(1,sub+1)/sub:
data.qpos[adr]=start+(end-start)*alpha;mujoco.mj_forward(ev._model,data)
contacts,penetration=contact_summary(ev._model,data);count+=1;hits+=bool(contacts);worst=max(worst,penetration)
for p in contacts:pairs.add(tuple(p))
jump=float(np.max(np.abs(np.diff(q,axis=0)))) if len(q)>1 else 0.
residual=float(max(np.max(np.abs(up_q[:,0]+up_q[:,1]+.28403)),np.max(np.abs(up_q[:,2]-.28834)),np.max(np.abs(up_q[:,3]+.00123))))
return {'table_collision_fraction':hits/max(count,1),'table_collision_checks':count,'table_penetration_max_mm':worst*1000,
'table_collision_pairs':[list(x) for x in sorted(pairs)],'waist_constraint_residual_rad':residual,
'joint_path_jump_max_rad':jump,'deployment_constraint_reject':bool(hits or residual>1e-8 or jump>.3),
'scene_version':'v14_assumed_table','collision_sampling_max_joint_step_rad':.05,
'collision_check_kind':'discrete interpolated mesh-hull robot/table; not certified continuous collision checking'}
if __name__=='__main__':
import sys
print(json.dumps(build_scene(sys.argv[1]),indent=2))