Download v1/scripts/probe_gpu_full_transfer.py from Travor278/DropperLab: direct link, hf CLI and curl.
- Browser
- Download file 40.1 kB
-
https://huggingface.co/datasets/Travor278/DropperLab/resolve/main/v1/scripts/probe_gpu_full_transfer.py
- Command line
-
hf download hf://datasets/Travor278/DropperLab/v1/scripts/probe_gpu_full_transfer.py
-
curl -L -o probe_gpu_full_transfer.py https://huggingface.co/datasets/Travor278/DropperLab/resolve/main/v1/scripts/probe_gpu_full_transfer.py
40.1 kB
| """Unqualified same-run 3D-water aspiration/dispense/rack motor candidate. | |
| Advancement requires actual liquid inventory. No phase-based water creation, | |
| object pose substitution, or automatic physics qualification is performed. | |
| """ | |
| from pathlib import Path | |
| import sys,argparse,json,time,math | |
| import numpy as np,mujoco,warp as wp | |
| from scipy.spatial.transform import Rotation | |
| sys.path.insert(0,str(Path(__file__).resolve().parents[1])) | |
| from dropperlab.experimental_sph.warp_dfsph import WarpDFSPH | |
| from dropperlab.experimental_sph.bulb_fem import Cavity | |
| from dropperlab.experimental_sph.bulb_integrity import BulbIntegrity | |
| from dropperlab.dual_policy import MotorController | |
| from dropperlab.assets import ROOT | |
| from dropperlab.experiment_recording import ExperimentRecorder | |
| from dropperlab.particle_inventory import CavityInventory | |
| from dropperlab.transfer_policy import TransferPolicy | |
| from dropperlab.interval_state import IntervalState | |
| from dropperlab.accepted_checkpoint import save_checkpoint,load_checkpoint | |
| from dropperlab.grasp_support import GraspSupport | |
| from dropperlab.grasp_geometry import GraspGeometry | |
| p=argparse.ArgumentParser();p.add_argument('--source',type=Path,default=ROOT/'results/coupled_gpu_seed_smoke') | |
| p.add_argument('--out',type=Path,required=True);p.add_argument('--duration',type=float,default=60.) | |
| p.add_argument('--release-duration',type=float,default=.3);p.add_argument('--sigma',type=float,default=.072) | |
| p.add_argument('--release-gap',type=float,default=.008) | |
| p.add_argument('--fluid-dt',type=float,default=.0001) | |
| p.add_argument('--adaptive-contact',action='store_true') | |
| p.add_argument('--contact-predictor-recovery',action='store_true') | |
| p.add_argument('--paired-world-contact',action='store_true') | |
| p.add_argument('--record-water-interval',type=float,default=.02) | |
| p.add_argument('--maximum-coupling-iterations',type=int,default=24) | |
| p.add_argument('--resume',type=Path) | |
| p.add_argument('--minimum-solid-dt',type=float,default=.0000125) | |
| p.add_argument('--neighbor-cache',action='store_true') | |
| p.add_argument('--kinematics-only-prediction',action='store_true') | |
| p.add_argument('--adopt-native-result',action='store_true') | |
| p.add_argument('--gas-volume-tolerance',type=float,default=1e-11) | |
| p.add_argument('--grasp-feedback',action='store_true') | |
| p.add_argument('--transport-grasp-minimum',type=float,default=.12) | |
| p.add_argument('--bulb-center-z',type=float) | |
| p.add_argument('--stem-preclose-gap',type=float,default=.014) | |
| p.add_argument('--synchronized-motion',action='store_true') | |
| p.add_argument('--recover-solid-dt',type=float,default=0.) | |
| p.add_argument('--coupling-relaxation',type=float,default=1.) | |
| p.add_argument('--coupling-tolerance',type=float,default=5e-9) | |
| p.add_argument('--ccd-tolerance',type=float) | |
| p.add_argument('--ccd-iterations',type=int) | |
| p.add_argument('--independent-grasp-geometry',action='store_true') | |
| p.add_argument('--immersion-depth',type=float,default=.005) | |
| p.add_argument('--aspiration-timeout',type=float,default=12.) | |
| p.add_argument('--stop-request',type=Path) | |
| p.add_argument('--bimanual-stem-support',action='store_true') | |
| p.add_argument('--rack-to-rack-v1',action='store_true',help='New empty-tools dual-rack initial preparation; never reinterpret an old continuation') | |
| p.add_argument('--static-world-contact',action='store_true') | |
| p.add_argument('--world-floor-z',type=float) | |
| p.add_argument('--record-port-flux',action='store_true') | |
| p.add_argument('--substep-port-flux',action='store_true') | |
| p.add_argument('--continuous-glass-wall-table',type=Path) | |
| p.add_argument('--continuous-glass-pressure-table',type=Path) | |
| p.add_argument('--dispense-force-max',type=float,default=3.) | |
| p.add_argument('--swept-water-contact',action='store_true') | |
| p.add_argument('--continuous-floor-viscosity',action='store_true') | |
| p.add_argument('--surface-model',choices=['pair','number_density_energy','number_density_implicit'],default='pair') | |
| p.add_argument('--kernel-support',type=float,default=2.) | |
| p.add_argument('--viscosity-kernel-support',type=float) | |
| p.add_argument('--viscosity-regularization',type=float,default=.01) | |
| p.add_argument('--mirror-no-slip',action='store_true') | |
| p.add_argument('--wall-velocity-model',choices=['quadratic_mirror','adaptive_mirror'],default='quadratic_mirror') | |
| p.add_argument('--pressure-complementarity',action='store_true') | |
| p.add_argument('--pressure-tolerance',type=float,default=5e-5) | |
| p.add_argument('--maximum-pressure-iterations',type=int,default=200) | |
| p.add_argument('--number-density-area-scale',type=float,default=1.) | |
| p.add_argument('--interface-kernel-support',type=float,default=3.) | |
| p.add_argument('--discrete-interface-normalization',action='store_true') | |
| p.add_argument('--interface-epsilon',type=float,default=.05) | |
| a=p.parse_args();out=a.out.resolve();out.mkdir(parents=True,exist_ok=False);started=time.perf_counter() | |
| if a.rack_to_rack_v1 and not a.bimanual_stem_support:raise ValueError('Dual-rack V1 requires bimanual support') | |
| if not .007<=a.stem_preclose_gap<=.014:raise ValueError('Stem preclose outside reviewed clearance range') | |
| if a.world_floor_z is not None and (not a.static_world_contact or not np.isfinite(a.world_floor_z)):raise ValueError('A finite world floor requires fixed-world fluid contact') | |
| if a.continuous_floor_viscosity and a.world_floor_z is None:raise ValueError('Continuous floor viscosity requires the explicit physical floor') | |
| if a.substep_port_flux and not a.record_port_flux:raise ValueError('Substep flux requires the accepted port-flux ledger') | |
| model=mujoco.MjModel.from_binary_path(str(a.source/'solid/model.mjb'));data=mujoco.MjData(model) | |
| if not 3.<=a.dispense_force_max<=4.:raise ValueError('Dispense effort must remain within the original 4N gripper rating') | |
| if any(model.actuator('left_joint'+str(i)).forcerange[1]<a.dispense_force_max for i in (7,8)):raise ValueError('Requested effort exceeds source model rating') | |
| if a.ccd_tolerance is not None: | |
| if not 0<a.ccd_tolerance<=1e-6:raise ValueError('Invalid high-precision CCD tolerance') | |
| model.opt.ccd_tolerance=a.ccd_tolerance | |
| if a.ccd_iterations is not None: | |
| if a.ccd_iterations<35:raise ValueError('CCD iteration limit may not be reduced') | |
| model.opt.ccd_iterations=a.ccd_iterations | |
| initial=np.load(a.source/'solid/initial_state.npz');data.qpos[:]=initial['qpos'];data.qvel[:]=initial['qvel'] | |
| robots=[MotorController(model,data,arm) for arm in ['left','right']] | |
| for r in robots:r.reference=data.qpos[r.qids].copy();r.target=r.reference.copy();data.ctrl[r.uids]=r.reference;data.ctrl[r.gids]=0.;r.grip_reference[:]=0.;r.grip_speed_limit=.03 | |
| if a.rack_to_rack_v1 and not a.resume: | |
| for r in robots:r.grip=.044;r.grip_reference[:]=.044;data.ctrl[r.gids]=.044 | |
| for actuator in robots[0].gids:model.actuator_forcerange[actuator]=[-3.,3.] | |
| mujoco.mj_forward(model,data);cavity=Cavity(model,data);integrity=BulbIntegrity(cavity) | |
| grasp_geometry=GraspGeometry(model,integrity) if a.independent_grasp_geometry else None | |
| names=['Beaker','Dropper','Tube'];assets=['beaker','dropper_glass','open_original_tube'];meshes=[] | |
| for asset in assets: | |
| mesh=np.load(ROOT/f'assets/generated/{asset}.npz');meshes.append((mesh['vertices'].astype(np.float32),mesh['faces'].astype(np.int32))) | |
| seed=np.load(a.source/'fluid/gpu_seed.npz');origin=seed['origin_world'];spacing=float(seed['spacing']) | |
| if a.surface_model=='number_density_energy' and a.sigma>0 and a.fluid_dt>.25*np.sqrt(998.2*spacing**3/a.sigma): | |
| raise ValueError('Explicit interface timestep exceeds the capillary stability bound') | |
| water=WarpDFSPH(seed,meshes,sigma=a.sigma,cohesion_calibration=.2074,neighbor_cache=a.neighbor_cache, | |
| surface_model=a.surface_model,kernel_support=a.kernel_support,viscosity_kernel_support=a.viscosity_kernel_support, | |
| viscosity_regularization=a.viscosity_regularization,mirror_no_slip=a.mirror_no_slip,wall_velocity_model=a.wall_velocity_model, | |
| pressure_complementarity=a.pressure_complementarity,pressure_tolerance=a.pressure_tolerance, | |
| maximum_pressure_iterations=a.maximum_pressure_iterations,number_density_area_scale=a.number_density_area_scale,interface_kernel_support=a.interface_kernel_support,discrete_interface_normalization=a.discrete_interface_normalization,interface_epsilon=a.interface_epsilon) | |
| if a.continuous_glass_wall_table: | |
| from dropperlab.experimental_sph.continuous_wall_gpu import ContinuousGlassWall | |
| water.continuous_glass_wall=ContinuousGlassWall(water,a.continuous_glass_wall_table) | |
| if a.continuous_glass_pressure_table: | |
| from dropperlab.experimental_sph.continuous_wall_pressure import ContinuousGlassPressure | |
| water.continuous_glass_pressure=ContinuousGlassPressure(water,a.continuous_glass_pressure_table) | |
| if a.swept_water_contact: | |
| from dropperlab.experimental_sph.swept_water_contact import SweptWaterAudit | |
| water.swept_water_audit=SweptWaterAudit(water) | |
| water.port_flux=None | |
| if a.record_port_flux: | |
| from dropperlab.port_flux import PortFluxLedger | |
| initial_water=np.asarray(seed['water']);beaker_local=(initial_water-seed['body_position'][0])@seed['body_rotation'][0] | |
| initial_source=(np.linalg.norm(beaker_local[:,:2],axis=1)<=.032+1e-7)&(beaker_local[:,2]>=.002-1e-7)&(beaker_local[:,2]<=.065+1e-7) | |
| if not initial_source.all():raise RuntimeError('Initial water source is not the physical beaker; source flux cannot be invented') | |
| water.port_flux=PortFluxLedger(water.nf,water.mass,initial_source,water.device,complete_history=not bool(a.resume)) | |
| static_component_names=[] | |
| if a.static_world_contact: | |
| from dropperlab.experimental_sph.static_world_contact import StaticWorldContact,scene_mesh | |
| world_vertices,world_faces,static_component_names=scene_mesh(model,data,origin) | |
| planes=None if a.world_floor_z is None else [[np.array([0.,0.,a.world_floor_z])-origin,np.array([0.,0.,1.])]] | |
| water.static_world=StaticWorldContact(water,world_vertices,world_faces,planes=planes) | |
| if a.continuous_floor_viscosity: | |
| from dropperlab.experimental_sph.plane_viscosity import PlaneViscosity | |
| water.static_world.plane_viscosity=PlaneViscosity(water.static_world) | |
| void=np.load(ROOT/'assets/generated/tube_inventory_cavity.npz') | |
| tube_inventory=CavityInventory(water,void['vertices'].astype(np.float32),void['faces'].astype(np.int32)) | |
| policy=TransferPolicy(model,data,robots,float(void['vertices'][:,2].max())) | |
| support=GraspSupport(model,data,robots) if a.grasp_feedback else None | |
| if not .12<=a.transport_grasp_minimum<=.4:raise ValueError('Transport feedback threshold outside reviewed range') | |
| if a.transport_grasp_minimum!=.12 and support is None:raise ValueError('Transport support target requires measured grasp feedback') | |
| if support is not None:support.transport_minimum=a.transport_grasp_minimum | |
| if a.bulb_center_z is not None: | |
| if support is None or not -.01<=a.bulb_center_z<=-.003:raise ValueError('Bulb recentering requires feedback and reviewed pad target') | |
| support.bulb_center_z=a.bulb_center_z | |
| for r in robots: | |
| r.synchronized_motion=a.synchronized_motion | |
| if a.synchronized_motion:r.motion_speed=.5 | |
| recorder=ExperimentRecorder(out,spacing,a.record_water_interval,model=model) | |
| for r,name in zip(robots,['Dropper','Tube']): | |
| sr=data.site(r.arm+'_tcp').xmat.reshape(3,3);sp=data.site(r.arm+'_tcp').xpos | |
| r.held=(name,sr.T@(data.body(name).xpos-sp),sr.T@data.body(name).xmat.reshape(3,3)) | |
| if a.rack_to_rack_v1 and not a.resume: | |
| for r in robots:r.held=None | |
| dry=data.body('Dropper').xpos.copy();beaker=data.body('Beaker').xpos.copy() | |
| initial_depth=water.nf*water.volume/(np.pi*.032**2) | |
| wet=np.r_[beaker[:2],beaker[2]+.002+max(3*spacing,initial_depth-a.immersion_depth)] | |
| pred=mujoco.MjData(model);integration=np.empty(mujoco.mj_stateSize(model,mujoco.mjtState.mjSTATE_INTEGRATION));previous=np.zeros((3,6)) | |
| mujoco.mj_forward(model,pred) | |
| corrected=mujoco.MjData(model);mujoco.mj_forward(model,corrected) | |
| corrected_cavity=Cavity(model,corrected);predicted_cavity=Cavity(model,pred) | |
| prediction_state=np.empty_like(integration) | |
| sealed=False;sealed_at=None;last_plan=-1.;rows=[];states=[];report={'status':'running','task_success':False,'physics_qualified':False, | |
| 'scope':'unqualified same-run 3D-water aspiration/dispense/rack candidate; initially held objects','water_particles':water.nf,'spacing_m':spacing} | |
| report['adaptive_contact_retries']=0 | |
| report['coupling_recomputations']=0 | |
| report['rejected_solid_intervals']=0 | |
| report['initial_water_ml']=water.nf*water.volume*1e6 | |
| report['immersion_depth_below_initial_surface_m']=a.immersion_depth | |
| report['wet_tip_target_m']=wet.tolist() | |
| report['neighbor_cache']=a.neighbor_cache | |
| report['kinematics_only_prediction']=a.kinematics_only_prediction | |
| report['gas_volume_tolerance_m3']=a.gas_volume_tolerance | |
| report['grasp_feedback']=a.grasp_feedback;report['synchronized_motion']=a.synchronized_motion | |
| report['recover_solid_dt_max_s']=a.recover_solid_dt | |
| if not 0.<a.coupling_relaxation<=1.:raise ValueError('Coupling relaxation must be in (0,1]') | |
| report['coupling_relaxation']=a.coupling_relaxation | |
| if not 0.<a.coupling_tolerance<=5e-8:raise ValueError('Coupling tolerance must be positive and no more than 50 nm') | |
| report['coupling_tolerance_m']=a.coupling_tolerance | |
| report['native_ccd_tolerance']=model.opt.ccd_tolerance;report['native_ccd_iterations']=model.opt.ccd_iterations | |
| report['independent_grasp_geometry']=a.independent_grasp_geometry | |
| report['static_water_world_contact']=a.static_world_contact | |
| report['static_world_collider_components']=len(static_component_names) | |
| report['record_port_flux']=a.record_port_flux | |
| report['substep_port_flux']=a.substep_port_flux | |
| report['native_commit']='copy accepted native FSI endpoint' if a.adopt_native_result else 'independent repeat integration' | |
| report['world_floor_z']=a.world_floor_z | |
| report['floor_scope']='Fixed infinite liquid support plane; native solids must remain strictly above it' if a.world_floor_z is not None else 'No ground plane' | |
| checkpoint_parameters={k:getattr(a,k) for k in ['sigma','release_duration','release_gap','fluid_dt','immersion_depth']} | |
| if a.rack_to_rack_v1:checkpoint_parameters['rack_to_rack_v1']=True | |
| if a.transport_grasp_minimum!=.12:checkpoint_parameters['transport_grasp_minimum']=a.transport_grasp_minimum | |
| if a.bulb_center_z is not None:checkpoint_parameters['bulb_center_z']=a.bulb_center_z | |
| if a.stem_preclose_gap!=.014:checkpoint_parameters['stem_preclose_gap']=a.stem_preclose_gap | |
| if a.substep_port_flux:checkpoint_parameters['substep_port_flux']=True | |
| if a.world_floor_z is not None:checkpoint_parameters['world_floor_z']=a.world_floor_z | |
| if a.dispense_force_max!=3.:checkpoint_parameters['dispense_force_max']=a.dispense_force_max | |
| if a.swept_water_contact:checkpoint_parameters['swept_water_contact']=True | |
| if a.continuous_floor_viscosity:checkpoint_parameters['continuous_floor_viscosity']=True | |
| if a.continuous_glass_wall_table: | |
| checkpoint_parameters['continuous_glass_wall_table_sha256']=water.continuous_glass_wall.sha256 | |
| report['continuous_wall_scope']='Opt-in continuous annular glass adhesion potential; all native collision facets unchanged. Wall-force model migration is explicit; not inherited physical qualification.' | |
| if a.continuous_glass_pressure_table: | |
| checkpoint_parameters['continuous_glass_pressure_table_sha256']=water.continuous_glass_pressure.sha256 | |
| report['continuous_pressure_scope']='Consistent continuous annular glass density/divergence/pressure/reaction operator. Native collision facets unchanged. Explicit numerical model migration, not inherited qualification.' | |
| advanced_defaults=dict(surface_model='pair',kernel_support=2.,viscosity_kernel_support=None,viscosity_regularization=.01, | |
| mirror_no_slip=False,wall_velocity_model='quadratic_mirror',pressure_complementarity=False, | |
| pressure_tolerance=5e-5,maximum_pressure_iterations=200,number_density_area_scale=1.,interface_kernel_support=3.,discrete_interface_normalization=False,interface_epsilon=.05) | |
| if any(getattr(a,k)!=v for k,v in advanced_defaults.items()): | |
| checkpoint_parameters.update({k:getattr(a,k) for k in advanced_defaults}) | |
| checkpoint_parameters.update(seed_spacing_m=spacing,initial_particle_count=water.nf) | |
| report['solver_parameters']=checkpoint_parameters.copy() | |
| if a.resume: | |
| previous,logic,resume_meta=load_checkpoint(a.resume,a.source/'solid/model.mjb',model,data,water,robots,cavity,policy,checkpoint_parameters, | |
| restore_numerical_options=a.ccd_tolerance is None and a.ccd_iterations is None) | |
| sealed,sealed_at,last_plan=logic;report['resumed_accepted_state']=str(a.resume.resolve()) | |
| report['resumed_physical_time']=float(data.time) | |
| if a.bimanual_stem_support: | |
| from dropperlab.bimanual_policy import BimanualPolicy | |
| if a.rack_to_rack_v1: | |
| from dropperlab.rack_to_rack_policy import RackToRackPolicy | |
| saved_policy={k:v for k,v in policy.__dict__.items() if k not in ['model','data','robots']} | |
| saved_targets=[r.target.copy() for r in robots] | |
| policy=(RackToRackPolicy if a.rack_to_rack_v1 else BimanualPolicy)(model,data,robots,float(void['vertices'][:,2].max())) | |
| if saved_policy.get('policy_kind') in ('bimanual_stem_support_v1','rack_to_rack_v1'): | |
| if a.rack_to_rack_v1 and saved_policy.get('policy_kind')!='rack_to_rack_v1':raise RuntimeError('Old held-object trajectory cannot become new cold-start V1') | |
| policy.__dict__.update(saved_policy) | |
| for r,target in zip(robots,saved_targets):r.target=target | |
| if saved_policy.get('controller_revision',1)<2: | |
| if policy.stem_secured or policy.stage not in ['await_dose','lift_after_aspiration','transfer_for_stem_support','park_above','park_seat','park_release','park_retreat']: | |
| raise RuntimeError('The reviewed grasp revision requires a checkpoint before the rigid stem grasp') | |
| # Replace an unexecuted motor approach plan only. Accepted rigid, | |
| # elastic, controller reference and water arrays remain untouched. | |
| policy.stem_rotation=np.diag([-1.,-1.,1.]).tolist();policy.stem_height=.080 | |
| policy.controller_revision=2 | |
| policy.events.append(dict(time=float(data.time),stage='reviewed_unexecuted_stem_approach_revision')) | |
| else:policy.events=saved_policy['events']+[{'time':float(data.time),'stage':'bimanual_stem_support_adaptation'}] | |
| policy.dispense_force_max=a.dispense_force_max | |
| policy.stem_preclose_gap=a.stem_preclose_gap | |
| if not a.resume and not a.rack_to_rack_v1:policy.stage='await_dose';policy.entered=float(data.time);policy.events=[] | |
| report['scope']='unqualified coupled 3D-water transfer with contact-only second-hand rigid glass support' | |
| report['bimanual_stem_support']=True | |
| if a.rack_to_rack_v1:report.update(scope='New cold-start V1: empty dropper on A, inverted empty tube on B, initially empty home hands',rack_to_rack_v1=True) | |
| recorder.capture(data,water.positions_numpy()+origin,water_velocity=water.velocities_numpy()) | |
| print(json.dumps({'stage':'gpu_coupled_initialized','particles':water.nf,'wall_seconds':time.perf_counter()-started}),flush=True) | |
| def poses(offset,length): | |
| positions=[];rotations=[];centers=[];linear=[];angular=[] | |
| for name in names: | |
| b=data.body(name);e=pred.body(name);c0=data.xipos[b.id];c1=pred.xipos[e.id] | |
| r0=b.xmat.reshape(3,3);vector=Rotation.from_matrix(e.xmat.reshape(3,3)@r0.T).as_rotvec();fraction=np.clip(offset/length,0,1) | |
| r=Rotation.from_rotvec(vector*fraction).as_matrix()@r0;c=(1-fraction)*c0+fraction*c1 | |
| positions.append(c+r@(r0.T@(b.xpos-c0))-origin);rotations.append(r);centers.append(c-origin) | |
| linear.append((c1-c0)/length);angular.append(vector/length) | |
| return np.array(positions),np.array(rotations),np.array(centers),np.array(linear),np.array(angular) | |
| def sync_current(): | |
| position=[];rotation=[];com=[];linear=[];angular=[] | |
| for name in names: | |
| body=data.body(name);velocity=np.empty(6) | |
| mujoco.mj_objectVelocity(model,data,mujoco.mjtObj.mjOBJ_BODY,body.id,velocity,0) | |
| position.append(body.xpos-origin);rotation.append(body.xmat.reshape(3,3));com.append(data.xipos[body.id]-origin) | |
| linear.append(velocity[3:]);angular.append(velocity[:3]) | |
| water.sync_bodies(position,rotation,com,linear,angular) | |
| def prediction_geometry(state): | |
| if a.kinematics_only_prediction: | |
| mujoco.mj_kinematics(model,state);mujoco.mj_comPos(model,state);mujoco.mj_flex(model,state) | |
| else:mujoco.mj_forward(model,state) | |
| def endpoint_geometry(state): | |
| if a.kinematics_only_prediction:prediction_geometry(state) | |
| else:mujoco.mj_fwdPosition(model,state) | |
| try: | |
| frame=0;next_step_recovery=float(data.time)+.005;controlled_stop=False | |
| while data.time<a.duration-1e-10: | |
| if water.port_flux is not None and not a.substep_port_flux: | |
| # Smaller numerical intervals keep every real port crossing inside | |
| # one accepted water step; no physical coefficient is changed. | |
| model.opt.timestep=min(model.opt.timestep,a.fluid_dt,a.recover_solid_dt if a.recover_solid_dt>0 else a.fluid_dt) | |
| t=float(data.time);dt=float(model.opt.timestep) | |
| previous_before=previous.copy() | |
| start=IntervalState(model,data,robots,cavity,policy) | |
| initial_logic=(sealed,sealed_at,last_plan) | |
| checkpoint=water.candidate_checkpoint() | |
| # The legacy endpoint ledger is written only after acceptance and never | |
| # needs a candidate backup. Substep measurements do need rollback. | |
| flux_snapshot=water.port_flux.snapshot() if water.port_flux is not None and a.substep_port_flux else None | |
| tip_before=data.body('Dropper').xpos.copy()-origin | |
| rotation_before=data.body('Dropper').xmat.reshape(3,3).copy() | |
| if water.port_flux is not None and not a.substep_port_flux and dt>a.fluid_dt+1e-15: | |
| raise RuntimeError('Port-flux measurement requires each accepted solid interval to contain at most one water step') | |
| sync_current() | |
| bore_ml=water.bore_volume()*1e6;tube_ml=tube_inventory.volume()*1e6 | |
| if support and a.bimanual_stem_support: | |
| support.right_object=policy.right_object;support.left_object=getattr(policy,'left_object','Dropper') | |
| grasp_ready=support.regulate(policy) if support else True | |
| vertices=data.flexvert_xpos[cavity.start:cavity.start+integrity.total_vertices] | |
| jac_start=np.linalg.det(vertices[integrity.tetrahedra[:,1:]]-vertices[integrity.tetrahedra[:,0,None]])/integrity.reference_det | |
| if policy.stage in ['dispense','supported_dispense'] or a.bimanual_stem_support: | |
| policy.regulate_dispense(float(jac_start.min()),cavity.pressure) | |
| if a.rack_to_rack_v1:policy.measured_bulb_volume_m3=cavity.volume() | |
| policy.port_colour=float(water.port_color()) | |
| active_transfer=policy.update(bore_ml,tube_ml,grasp_ready) | |
| aspiration_elapsed=t-policy.entered if a.rack_to_rack_v1 else t | |
| if not active_transfer and aspiration_elapsed>a.aspiration_timeout:raise RuntimeError('Actual 1 mL aspiration not established before timeout') | |
| if not active_transfer and t-last_plan>.02: | |
| last_plan=t;policy.command_aspiration(wet) | |
| color=water.port_color();surface=data.body('Beaker').xpos[2]+.002+water.nf*water.volume/(np.pi*.032**2) | |
| if not sealed and color>.25 and data.body('Dropper').xpos[2]<surface-spacing:sealed=True;sealed_at=t | |
| alpha=np.clip((t-((sealed_at+.03) if sealed_at is not None else float('inf')))/a.release_duration,0,1) | |
| limit=3.-2.2*alpha*alpha*(3-2*alpha) | |
| if not active_transfer: | |
| for actuator in robots[0].gids:model.actuator_forcerange[actuator]=[-limit,limit] | |
| else:limit=float(model.actuator_forcerange[robots[0].gids[0],1]) | |
| joint_fraction=None | |
| if a.bimanual_stem_support and policy.stem_secured: | |
| maximum=max(float(np.max(np.abs(r.target-r.reference))) for r in robots) | |
| joint_fraction=min(1.,.5*dt/max(maximum,1e-15)) | |
| for i,r in enumerate(robots): | |
| if not active_transfer:r.grip=min(a.release_gap*alpha*alpha*(3-2*alpha),policy.safe_grip_ceiling) if i==0 else (.044 if a.rack_to_rack_v1 else 0.) | |
| r.update(dt,joint_fraction=joint_fraction) | |
| # Empty, dry glass reconnects gas to the atmosphere. Retention/sealing | |
| # still needs a qualified multiphase interface; no success flag is granted. | |
| vented=not sealed or (active_transfer and bore_ml<.001 and color<.1) | |
| cavity.apply(dt,vented=vented,water_volume=water.bore_volume(),apply_forces=False) | |
| data.xfrc_applied[:]=0.;cavity.apply_pressure(cavity.pressure) | |
| for i,name in enumerate(names):data.xfrc_applied[model.body(name).id]+=previous[i] | |
| mujoco.mj_getState(model,data,integration,mujoco.mjtState.mjSTATE_INTEGRATION);mujoco.mj_setState(model,pred,integration,mujoco.mjtState.mjSTATE_INTEGRATION) | |
| if not a.kinematics_only_prediction:mujoco.mj_forward(model,pred) | |
| mujoco.mj_step(model,pred);endpoint_geometry(pred) | |
| volume_start=cavity.volume() | |
| water.contact_predictor_recovery=a.contact_predictor_recovery | |
| water.paired_world_contact=a.paired_world_contact | |
| if a.paired_world_contact and not hasattr(water,'paired_contact_applied'): | |
| water.paired_contact_applied=wp.zeros(1,dtype=int,device=water.device) | |
| for coupling in range(a.maximum_coupling_iterations): | |
| if coupling: | |
| water.reject_candidate_interval(checkpoint);report['coupling_recomputations']+=1 | |
| if a.substep_port_flux:water.port_flux.reject(flux_snapshot) | |
| substeps=max(1,math.ceil(dt/min(a.fluid_dt,.3*spacing/max(water.maximum_speed(),.1))));nominal_h=dt/substeps | |
| impulse=np.zeros((3,6));pressure_sum=0.;volume_end=predicted_cavity.volume() | |
| elapsed=0.;retry_limit=nominal_h;rejected_prediction=False | |
| while elapsed<dt-1e-14: | |
| h=min(retry_limit,dt-elapsed) | |
| pos,rot,com,lin,ang=poses(elapsed,dt);end_pos,end_rot,_,_,_=poses(elapsed+h,dt) | |
| water.sync_bodies(pos,rot,com,lin,ang,end_pos,end_rot) | |
| volume=volume_start+(volume_end-volume_start)*(elapsed+.5*h)/dt | |
| gas=volume+cavity.dead_volume-water.bore_volume();pressure=cavity.gas_pv/gas | |
| if gas<=1e-7 or pressure<3000:raise RuntimeError('Invalid gas state') | |
| flux_before=None | |
| if a.substep_port_flux: | |
| flux_before=wp.empty(water.nf,dtype=wp.vec3,device=water.device);wp.copy(flux_before,water.x,count=water.nf) | |
| try:liquid=water.step(h,gas_pressure=pressure-cavity.patm) | |
| except RuntimeError as e: | |
| if a.contact_predictor_recovery and 'physical CAD contact rejected' in str(e) and h<1e-6 and water.rejected_candidate_wrench is not None: | |
| # Correct only the independent solid predictor with the | |
| # rejected contact reaction. The next coupling iteration | |
| # recomputes all water/flux from the accepted checkpoint. | |
| trial_force,trial_torque=water.rejected_candidate_wrench | |
| seed_impulse=impulse.copy() | |
| for i,name in enumerate(names): | |
| actual_com=data.xipos[model.body(name).id]-origin | |
| seed_impulse[i]+=(dt-elapsed)*np.r_[trial_force[i],trial_torque[i]+np.cross(com[i]-actual_com,trial_force[i])] | |
| mujoco.mj_setState(model,corrected,integration,mujoco.mjtState.mjSTATE_INTEGRATION) | |
| prediction_geometry(corrected);corrected.xfrc_applied[:]=0. | |
| corrected_cavity.apply_pressure((pressure_sum+(dt-elapsed)*pressure)/dt) | |
| for i,name in enumerate(names):corrected.xfrc_applied[model.body(name).id]+=seed_impulse[i]/dt | |
| mujoco.mj_step(model,corrected);endpoint_geometry(corrected) | |
| mujoco.mj_getState(model,corrected,prediction_state,mujoco.mjtState.mjSTATE_INTEGRATION) | |
| mujoco.mj_setState(model,pred,prediction_state,mujoco.mjtState.mjSTATE_INTEGRATION);prediction_geometry(pred) | |
| rejected_prediction=True | |
| report['contact_predictor_retries']=report.get('contact_predictor_retries',0)+1 | |
| print(json.dumps({'stage':'rejected_contact_predictor_retry','time':t,'coupling_iteration':coupling,'rejected_water_step':h}),flush=True) | |
| break | |
| if not a.adaptive_contact or 'physical CAD contact rejected' not in str(e) or h<1e-6:raise | |
| retry_limit=h/2;report['adaptive_contact_retries']+=1 | |
| continue | |
| if a.substep_port_flux: | |
| # Trial measurements follow each actual numerical water | |
| # step and its moving CAD. They are published only after | |
| # the outer native endpoint passes the existing FSI guard. | |
| water.port_flux.advance(flux_before,water.x,pos[1],rot[1],end_pos[1],end_rot[1]) | |
| force=water.force.numpy();torque=water.torque.numpy() | |
| for i,name in enumerate(names): | |
| actual_com=data.xipos[model.body(name).id]-origin | |
| impulse[i]+=h*np.r_[force[i],torque[i]+np.cross(com[i]-actual_com,force[i])] | |
| pressure_sum+=h*pressure;elapsed+=h | |
| if rejected_prediction: | |
| endpoint_error=float('inf');volume_endpoint_error=float('inf');geometry_failures=1 | |
| continue | |
| # Compute an independently integrated corrected endpoint. The live | |
| # solid state stays at the interval start until the candidate passes. | |
| mujoco.mj_setState(model,corrected,integration,mujoco.mjtState.mjSTATE_INTEGRATION) | |
| prediction_geometry(corrected);corrected.xfrc_applied[:]=0. | |
| corrected_cavity.apply_pressure(pressure_sum/dt) | |
| for i,name in enumerate(names):corrected.xfrc_applied[model.body(name).id]+=impulse[i]/dt | |
| mujoco.mj_step(model,corrected);endpoint_geometry(corrected) | |
| endpoint_position=np.array([corrected.body(name).xpos-origin for name in names]) | |
| endpoint_rotation=np.array([corrected.body(name).xmat.reshape(3,3) for name in names]) | |
| geometry_failures=water.actual_geometry_failures(endpoint_position,endpoint_rotation) | |
| endpoint_error=max(float(np.linalg.norm(corrected.body(name).xpos-pred.body(name).xpos))+ | |
| .15*float(np.linalg.norm(corrected.body(name).xmat-pred.body(name).xmat)) for name in names) | |
| volume_endpoint_error=abs(corrected_cavity.volume()-predicted_cavity.volume()) | |
| if endpoint_error<a.coupling_tolerance and volume_endpoint_error<=a.gas_volume_tolerance and geometry_failures==0:break | |
| mujoco.mj_getState(model,corrected,prediction_state,mujoco.mjtState.mjSTATE_INTEGRATION) | |
| if a.coupling_relaxation<1.: | |
| old_qpos=pred.qpos.copy();old_qvel=pred.qvel.copy() | |
| difference=np.empty(model.nv) | |
| mujoco.mj_differentiatePos(model,difference,1.,old_qpos,corrected.qpos) | |
| mujoco.mj_setState(model,pred,prediction_state,mujoco.mjtState.mjSTATE_INTEGRATION) | |
| # Damp only the independent candidate prediction on MuJoCo's | |
| # configuration manifold. Live bodies continue native steps. | |
| pred.qpos[:]=old_qpos;mujoco.mj_integratePos(model,pred.qpos,difference,a.coupling_relaxation) | |
| pred.qvel[:]=(1-a.coupling_relaxation)*old_qvel+a.coupling_relaxation*corrected.qvel | |
| else:mujoco.mj_setState(model,pred,prediction_state,mujoco.mjtState.mjSTATE_INTEGRATION) | |
| prediction_geometry(pred) | |
| else: | |
| water.reject_candidate_interval(checkpoint) | |
| if a.substep_port_flux:water.port_flux.reject(flux_snapshot) | |
| if dt<=a.minimum_solid_dt:raise RuntimeError(f'FSI candidate did not converge at minimum solid step; error={endpoint_error:g}, gas volume error={volume_endpoint_error:g}, CAD failures={geometry_failures}') | |
| start.reject(model,data,robots,cavity,policy);sealed,sealed_at,last_plan=initial_logic | |
| model.opt.timestep=max(a.minimum_solid_dt,dt/2);report['rejected_solid_intervals']+=1 | |
| next_step_recovery=t+.020 | |
| print(json.dumps({'stage':'rejected_coupled_interval_retry','time':t,'new_solid_dt':model.opt.timestep, | |
| 'endpoint_error_m':endpoint_error,'gas_volume_error_m3':volume_endpoint_error,'actual_cad_failures':geometry_failures}),flush=True) | |
| continue | |
| data.xfrc_applied[:]=0.;cavity.apply_pressure(pressure_sum/dt) | |
| previous=impulse/dt | |
| for i,name in enumerate(names):data.xfrc_applied[model.body(name).id]+=previous[i] | |
| if a.adopt_native_result: | |
| # Commit the independently integrated, already accepted FSI result. | |
| # This is the native solver endpoint, never a prescribed object pose. | |
| mujoco.mj_copyData(data,model,corrected) | |
| else:mujoco.mj_step(model,data) | |
| mujoco.mj_fwdPosition(model,data) | |
| if np.max(np.abs(data.qpos-corrected.qpos))>1e-10:raise RuntimeError('Live solid integration differs from corrected native endpoint') | |
| if any(c.dist<-.0001 for c in data.contact):raise RuntimeError('Solid contact overlap exceeds 0.1 mm') | |
| sync_current() | |
| if water.tabletop_geometry_failures(origin):raise RuntimeError('Water/table geometry guard; stationary world-fluid contacts remain unqualified') | |
| if any(w.number for w in data.warning):raise RuntimeError('Native solid warning') | |
| if a.world_floor_z is not None: | |
| moving=(model.body_weldid[model.geom_bodyid]!=0)&(model.geom_contype!=0) | |
| if np.any(data.geom_xpos[moving,2]-model.geom_rbound[moving]<=a.world_floor_z):raise RuntimeError('Native solid approached the liquid-only ground plane; native ground collision must be modeled before continuing') | |
| vertices=data.flexvert_xpos[cavity.start:cavity.start+integrity.total_vertices] | |
| jac=np.linalg.det(vertices[integrity.tetrahedra[:,1:]]-vertices[integrity.tetrahedra[:,0,None]])/integrity.reference_det | |
| if jac.min()<.5:raise RuntimeError('FEM material guard') | |
| if water.port_flux is not None and not a.substep_port_flux: | |
| water.port_flux.advance(checkpoint[0],water.x,tip_before,rotation_before, | |
| data.body('Dropper').xpos-origin,data.body('Dropper').xmat.reshape(3,3)) | |
| if frame%33==0: | |
| geometry=integrity.check();row={'time':float(data.time),'stage':policy.stage if active_transfer else 'aspirate' if alpha>0 else 'immerse', | |
| 'bore_water_ml':water.bore_volume()*1e6,'bulb_volume_ml':cavity.volume()*1e6,'gas_pressure_pa':pressure_sum/dt, | |
| 'tube_water_ml':tube_inventory.volume()*1e6, | |
| 'velocity_max':water.maximum_speed(),'left_force_limit_n':limit,'left_grip_target_m':robots[0].grip,'port_color':color,**geometry} | |
| if grasp_geometry:row['independent_fem_jaw_overlap_m']=grasp_geometry.check(data) | |
| row.update(coupling_iterations=coupling+1,solid_endpoint_error_m=endpoint_error, | |
| gas_volume_endpoint_error_m3=volume_endpoint_error,actual_endpoint_cad_failures=geometry_failures) | |
| row.update(liquid) | |
| if water.port_flux is not None:row.update(water.port_flux.summary()) | |
| row.update(left_joint_target_rad=robots[0].target.tolist(), | |
| left_tcp_world_m=data.site('left_tcp').xpos.tolist(), | |
| dropper_world_m=data.body('Dropper').xpos.tolist(), | |
| aspiration_arm_hold=policy.aspiration_goal_set,dispense_feedback=policy.dispense_feedback) | |
| if support:row['native_grasp_normal_forces_n']=policy.contact_support | |
| if support and policy.stage in ['home','settle']: | |
| from dropperlab.seating_measurement import measured_seats | |
| row.update(measured_seats(model,support.state_view(),robots)) | |
| rows.append(row);states.append(data.qpos.copy());report['last_state']=row;report['wall_seconds']=time.perf_counter()-started | |
| if data.time-recorder.last>=a.record_water_interval-1e-10: | |
| recorder.capture(data,water.positions_numpy()+origin,water_velocity=water.velocities_numpy()) | |
| save_checkpoint(out/'accepted_checkpoint.npz',a.source/'solid/model.mjb',model,data,water,robots,cavity,policy,previous,(sealed,sealed_at,last_plan),checkpoint_parameters) | |
| (out/'progress.json').write_text(json.dumps(report,indent=2));print(json.dumps(row),flush=True) | |
| if policy.done:break | |
| if a.stop_request and a.stop_request.exists():controlled_stop=True;break | |
| if a.recover_solid_dt>0 and data.time>=next_step_recovery and coupling<4: | |
| model.opt.timestep=min(a.recover_solid_dt,2*model.opt.timestep) | |
| next_step_recovery=float(data.time)+.020 | |
| frame+=1 | |
| report['status']='completed' | |
| report['execution_complete']=policy.done | |
| if not policy.done:report.update(status='incomplete',error='Controlled stop at an accepted coupled boundary' if controlled_stop else 'Physical time limit reached before the full sequence completed') | |
| recorder.capture(data,water.positions_numpy()+origin,force=True,water_velocity=water.velocities_numpy()) | |
| save_checkpoint(out/'accepted_checkpoint.npz',a.source/'solid/model.mjb',model,data,water,robots,cavity,policy,previous,(sealed,sealed_at,last_plan),checkpoint_parameters) | |
| except Exception as e: | |
| report.update(status='failed',error=str(e));print(str(e),flush=True) | |
| if 'swept water path' in str(e) and getattr(water,'swept_water_audit',None) is not None: | |
| report['swept_failure_detail']=water.swept_water_audit.describe_failure() | |
| # An exception may occur after several liquid substeps in an unaccepted | |
| # solid interval. Persist final arrays only after rejecting that interval. | |
| if 'checkpoint' in locals(): | |
| water.reject_candidate_interval(checkpoint) | |
| if flux_snapshot is not None:water.port_flux.reject(flux_snapshot) | |
| start.reject(model,data,robots,cavity,policy);sealed,sealed_at,last_plan=initial_logic | |
| previous=previous_before | |
| report['failed_interval_rolled_back']=True | |
| sync_current() | |
| positions=np.array([data.body(name).xpos-origin for name in names]) | |
| rotations=np.array([data.body(name).xmat.reshape(3,3) for name in names]) | |
| failures=water.actual_geometry_failures(positions,rotations) | |
| report['rollback_state_cad_failures']=failures | |
| if not failures: | |
| save_checkpoint(out/'accepted_checkpoint.npz',a.source/'solid/model.mjb',model,data,water,robots,cavity,policy,previous,(sealed,sealed_at,last_plan),checkpoint_parameters) | |
| report.update(physical_seconds=float(data.time),wall_seconds=time.perf_counter()-started) | |
| report['phase_events']=policy.events | |
| if water.port_flux is not None:report.update(water.port_flux.summary()) | |
| (out/'report.json').write_text(json.dumps(report,indent=2));(out/'trajectory.json').write_text(json.dumps(rows,indent=2)) | |
| np.savez_compressed(out/'solid_states.npz',qpos=np.array(states)) | |
| np.savez_compressed(out/'final_water.npz',position=water.positions_numpy()+origin,velocity=water.velocities_numpy(),mass=water.mass) | |
| print(json.dumps({k:v for k,v in report.items() if k!='last_state'},indent=2)) | |