diff --git a/tests/test_asset_agilent_1290infinity.py b/tests/test_asset_agilent_1290infinity.py new file mode 100644 index 0000000000000000000000000000000000000000..8eddbf90661f2a94b1f087faa2857f3948e11dc8 --- /dev/null +++ b/tests/test_asset_agilent_1290infinity.py @@ -0,0 +1,94 @@ +from pathlib import Path +import sys,unittest,copy,json,importlib.util,math +ROOT=Path(__file__).resolve().parents[1];sys.path.insert(0,str(ROOT/'scripts')) +from asset_runtime.agilent_1290infinity import * +sp=importlib.util.spec_from_file_location('asset_tool',ROOT/'skills/chemistry-lab-assets/scripts/asset_tool.py');tool=importlib.util.module_from_spec(sp);sp.loader.exec_module(tool) +OBSERVED=set() +def call(r,k,**a): + v=r.invoke(k,**a);err=tool.validate_value(v,CAPS[k][1]);assert not err,err;OBSERVED.add(k);return v +def prepared(plant=None,method=None,sample=None): + r=Agilent1290infinityRuntime();call(r,'plant.configure',**(plant or copy.deepcopy(PLANT_EXAMPLE)));call(r,'method.configure',**(method or copy.deepcopy(METHOD_EXAMPLE)));call(r,'drawer.set',position_m=.2);call(r,'sample.load',**(sample or copy.deepcopy(SAMPLE_EXAMPLE)));call(r,'drawer.set',position_m=0.);call(r,'power.set',enabled=True);call(r,'pump.set',enabled=True);r.step(10.);return r +class SEC(unittest.TestCase): + def test_metadata_and_schema(self): + r=prepared();m=r.describe() + for k,c in m['capabilities'].items(): + errors=tool.validate_value(c['example_arguments'],c['input_schema']);self.assertEqual(errors,[]) + for k,v in r.read('evaluator').items():errors=tool.validate_value(v,m['state_slots'][k]['value_schema']);self.assertEqual(errors,[]) + def test_setpoint_and_pure_queries(self): + r=Agilent1290infinityRuntime();call(r,'plant.configure',**PLANT_EXAMPLE);t=list(r.temperature);call(r,'method.configure',**METHOD_EXAMPLE);self.assertEqual(r.temperature,t);before=copy.deepcopy(r.__dict__);r.read();r.describe();call(r,'process.measure');call(r,'ledger.read');self.assertEqual(r.__dict__,before) + def test_pressure_derating_and_atomic_rejection(self): + p=copy.deepcopy(PLANT_EXAMPLE) + for c in p['columns']:c.update(resistance_pa_s_m3=1.2e15,max_pressure_pa=1.3e8) + r=Agilent1290infinityRuntime();call(r,'plant.configure',**p);before=copy.deepcopy(r.__dict__) + with self.assertRaisesRegex(ActionRejected,'PRESSURE_LIMIT'):r.invoke('method.configure',**dict(METHOD_EXAMPLE,flow_m3_s=5e-6/60)) + self.assertEqual(r.__dict__,before) + def test_invalid_nan_bool_extra(self): + r=prepared() + for a in [{'enabled':1},{'enabled':True,'extra':3}]: + with self.assertRaises(ActionRejected):r.invoke('pump.set',**a) + for dt in [True,float('nan'),-1.,float('inf')]: + before=copy.deepcopy(r.__dict__) + with self.assertRaises(ActionRejected):r.step(dt) + self.assertEqual(r.__dict__,before) + def test_all_templates_and_families(self): + r=Agilent1290infinityRuntime();self.assertEqual(len(r.templates),73);self.assertEqual(len({v['polymer_family'] for v in r.templates.values()}),3) + for sid in r.templates:t=call(r,'template.read',substance_id=sid);self.assertGreater(t['mp_kg_mol'],0);self.assertTrue(t['template_source']) + def test_configuration_and_access_motion(self): + r=prepared() + for k,a in [('door.set',{'angle_rad':1.}),('drawer.set',{'position_m':.2}),('column_cover.set',{'angle_rad':1.})]: + before=copy.deepcopy(r.__dict__) + with self.assertRaisesRegex(ActionRejected,'BUSY'):r.invoke(k,**a) + self.assertEqual(r.__dict__,before) + call(r,'pump.set',enabled=False);call(r,'door.set',angle_rad=1.);call(r,'door.set',angle_rad=0.);call(r,'column_cover.set',angle_rad=1.);call(r,'column_cover.set',angle_rad=0.) + def test_complete_conservation(self): + r=prepared();call(r,'acquisition.start') + for _ in range(120):r.step(1.) + self.assertEqual(r.phase,'succeeded');l=call(r,'ledger.read');self.assertLess(abs(l['volume_residual_m3']),1e-12);self.assertLess(abs(l['mass_residual_kg']),1e-20);self.assertGreater(l['eluted_kg'],0.);self.assertAlmostEqual(l['injected_kg'],2e-9) + def test_cancel_partial_and_other_instance(self): + r=prepared();other=prepared();before=copy.deepcopy(other.__dict__);call(r,'acquisition.start');r.step(60.);call(r,'acquisition.stop');l=r._ledger();r.step(10.);self.assertEqual(l,r._ledger());self.assertEqual(other.__dict__,before);self.assertGreater(l['column_kg'],0.);self.assertGreater(l['eluted_kg'],0.) + def test_exhaustion_failure(self): + p=copy.deepcopy(PLANT_EXAMPLE);p['reservoir_m3']=2e-7;r=prepared(p);call(r,'acquisition.start');r.step(120);self.assertEqual(r.phase,'failed');self.assertAlmostEqual(r.reservoir,0.);self.assertLess(abs(r._ledger()['volume_residual_m3']),1e-12) + def test_unload_preserves_column(self): + r=prepared();call(r,'acquisition.start');r.step(60);call(r,'acquisition.stop');x=r._ledger()['column_kg'];call(r,'drawer.set',position_m=.2);call(r,'sample.unload');self.assertEqual(r._ledger()['column_kg'],x);self.assertLess(abs(r._ledger()['volume_residual_m3']),1e-12) + def test_calibration_moments_from_signal(self): + r=prepared();call(r,'calibration.fit',**CAL_EXAMPLE);call(r,'acquisition.start') + for _ in range(1200):r.step(.1) + a=call(r,'molecular_weight.analyze');self.assertEqual(a['quality'],'estimated_relative');self.assertAlmostEqual(a['mass_kg'],2e-9,delta=1e-12) + # Independent analytic logM mixture moments from nominal source material values. + D=1.02;expected_mw=(20.+100.)/2*math.sqrt(D);expected_mn=2/(1/20.+1/100.)/math.sqrt(D) + self.assertAlmostEqual(a['mw_kg_mol']/expected_mw,1,delta=.003);self.assertAlmostEqual(a['mn_kg_mol']/expected_mn,1,delta=.003) + r.sample['solutes'][0]['concentration_kg_m3']=50.;r.sample['sample_id']='secret_changed';self.assertEqual(call(r,'molecular_weight.analyze'),a) + def test_invalid_calibration_and_outside(self): + r=prepared();before=copy.deepcopy(r.__dict__) + with self.assertRaises(ActionRejected):r.invoke('calibration.fit',**dict(CAL_EXAMPLE,points=[CAL_EXAMPLE['points'][0]]*2)) + self.assertEqual(r.__dict__,before);self.assertEqual(call(r,'molecular_weight.analyze')['quality'],'incomplete');call(r,'acquisition.start');r.step(120);self.assertEqual(call(r,'molecular_weight.analyze')['quality'],'uncalibrated') + call(r,'calibration.fit',**dict(CAL_EXAMPLE,points=[dict(elution_volume_m3=2e-7,mp_kg_mol=1e4),dict(elution_volume_m3=3e-7,mp_kg_mol=1e3)]));self.assertEqual(call(r,'molecular_weight.analyze')['quality'],'outside_calibration') + def test_saturated_signal_is_not_quantified(self): + s=copy.deepcopy(SAMPLE_EXAMPLE) + for v in s['solutes']:v['concentration_kg_m3']=100. + r=prepared(sample=s);call(r,'calibration.fit',**CAL_EXAMPLE);call(r,'acquisition.start') + for _ in range(1200):r.step(.1) + self.assertTrue(r.saturated);self.assertEqual(call(r,'molecular_weight.analyze')['quality'],'saturated') + def test_session_truth_dedup_cancel_owner(self): + r=prepared();r.register_principal('a');r.register_principal('b');r.register_principal('e','evaluator');a=r.session('a');b=r.session('b');i=r.instance_id + self.assertNotIn('sample.identity',a.read(instance_id=i)['observations']);self.assertNotIn('ledger.read',a.describe(instance_id=i)['capabilities']);denied=a.invoke(instance_id=i,capability_id='ledger.read',arguments={},request_id='d');self.assertEqual(denied['error']['code'],'ACCESS_DENIED') + v=a.invoke(instance_id=i,capability_id='acquisition.start',arguments={},request_id='one');self.assertEqual(v['status'],'accepted');self.assertEqual(v,a.invoke(instance_id=i,capability_id='acquisition.start',arguments={},request_id='one'));op=v['operation_id'] + with self.assertRaises(ActionRejected):b.poll(op) + r.step(60);self.assertEqual(a.poll(op)['status'],'running');a.cancel(op,'stop');self.assertEqual(a.poll(op)['status'],'cancelled') + def test_partition_mass_and_signal_area(self): + rs=[prepared(),prepared()] + for r in rs:call(r,'acquisition.start') + rs[0].step(120.) + for _ in range(1200):rs[1].step(.1) + for k in ['column_kg','eluted_kg','reservoir_m3','waste_m3']:self.assertAlmostEqual(rs[0]._ledger()[k],rs[1]._ledger()[k],delta=1e-12) + area=lambda r:sum(p['delta_n']*p['window_m3'] for p in r.points);self.assertAlmostEqual(area(rs[0]),area(rs[1]),delta=1e-20) + def test_eight_positions_and_temperature_bounds(self): + for i in range(8): + r=Agilent1290infinityRuntime();call(r,'plant.configure',**PLANT_EXAMPLE);call(r,'method.configure',**dict(METHOD_EXAMPLE,column_index=i));self.assertEqual(r.read()['column.selected'],i) + with self.assertRaises(ActionRejected):r.invoke('method.configure',**dict(METHOD_EXAMPLE,column_index=8)) + with self.assertRaises(ActionRejected):r.invoke('method.configure',**dict(METHOD_EXAMPLE,zone_targets_k=[273.,300.])) + def test_unsupported(self): + r=prepared() + for k in UNSUPPORTED: + with self.assertRaisesRegex(ActionRejected,'UNSUPPORTED'):r.invoke(k) +if __name__=='__main__':unittest.main() diff --git a/tests/test_asset_antonpaar_autosorb6100.py b/tests/test_asset_antonpaar_autosorb6100.py new file mode 100644 index 0000000000000000000000000000000000000000..7256b545cf4213b7064107c8c3262905c9c99fc1 --- /dev/null +++ b/tests/test_asset_antonpaar_autosorb6100.py @@ -0,0 +1,110 @@ +from pathlib import Path +import sys,math,copy,json,hashlib,unittest,importlib.util +ROOT=Path(__file__).resolve().parents[1];sys.path.insert(0,str(ROOT/'scripts'));from asset_runtime import antonpaar_autosorb6100 as r +spec=importlib.util.spec_from_file_location('autosorb_asset_tool',ROOT/'skills/chemistry-lab-assets/scripts/asset_tool.py');tool=importlib.util.module_from_spec(spec);spec.loader.exec_module(tool) +OBSERVED=set() +def call(h,k,**a): + v=h.invoke(k,**a);errors=tool.validate_value(v,r.CAPS[k][1]);assert not errors,(k,errors);OBSERVED.add(k);return v +def configured(ids=(0,),plant=None,method=None): + h=r.AntonpaarAutosorb6100Runtime();call(h,'plant.configure',**(plant or r.PLANT_EXAMPLE));call(h,'power.set',enabled=True);call(h,'guard.set',angle_rad=1.5) + for i in ids:call(h,'sample'+str(i)+'.set',drop_m=.18);call(h,'sample.load',**dict(r.SAMPLE_EXAMPLE,station=i,sample_id='private'+str(i)));call(h,'sample'+str(i)+'.set',drop_m=0.);call(h,'method.configure',**dict(method or r.METHOD_EXAMPLE,station=i));call(h,'pressure.calibrate',**dict(r.PCAL_EXAMPLE,station=i));call(h,'volume.calibrate',**dict(r.VCAL_EXAMPLE,station=i)) + call(h,'guard.set',angle_rad=0.);call(h,'coolant.fill',volume_m3=.003);call(h,'dewar.set',lift_m=.29);return h +def finish(h,limit=3600): + for _ in range(limit): + h.step(1.) + if h.phase!='running':break + return call(h,'process.measure') +def balances(h): + d=call(h,'ledger.read') + for k in ['n2_residual_mol','sample_residual_kg','ln2_residual_kg','water_residual_kg']:assert abs(d[k])<1e-10,(k,d[k]) + for k in ['manifold_energy_residual_j','degas_energy_residual_j']:assert abs(d[k])<1e-6,(k,d[k]) + return d +def point(x,q):return dict(time_s=0.,pressure_pa=x*r.P0,relative_pressure=x,loading_mol_kg=q,p0_pa=r.P0,temperature_k=77.) +class AutosorbTests(unittest.TestCase): + def test_01_source_integrity_and_real_count(self): + self.assertEqual(len(r.LIB['substances']),100) + for sid,v in r.LIB['substances'].items(): + self.assertEqual(sid,v['substance_id']);self.assertEqual(v['evidence'],'measured_literature');self.assertEqual(hashlib.sha256((ROOT/v['source']['raw_path']).read_bytes()).hexdigest(),v['source']['sha256']);self.assertIsNone(v['conditions']['branch']);x=v['runtime_equilibrium']['pressure_pa'];y=v['runtime_equilibrium']['loading_mol_kg'];self.assertTrue(all(b>a for a,b in zip(x,x[1:])));self.assertTrue(all(b>=a for a,b in zip(y,y[1:]))) + def test_02_full_pressure_inversion(self): + h=configured();call(h,'acquisition.start',stations=[0]);out=finish(h);self.assertEqual(out['phase'],'succeeded');s=h.stations[0];self.assertEqual(len(s['points']),18);d=r.LIB['substances'][r.SID]['runtime_equilibrium'] + for p in s['points']: + expected=r.interp(d['pressure_pa'],d['loading_mol_kg'],p['pressure_pa']);self.assertLess(abs(p['loading_mol_kg']/expected-1),.002) + self.assertEqual(s['bet']['status'],'conditional_branch_unspecified');self.assertGreater(s['bet']['area_m2_kg'],1e6);self.assertEqual(out['stations'][0]['psd']['status'],'not_available_branch_unspecified');self.assertIsNone(out['stations'][0]['total_pore_volume_m3_kg']);balances(h) + def test_03_three_independent_stations(self): + h=configured((0,1,2),method=dict(r.METHOD_EXAMPLE,relative_pressures=[.002,.005,.01,.02]));call(h,'acquisition.start',stations=[0,1,2]);out=finish(h);self.assertEqual(out['phase'],'succeeded');self.assertEqual([len(s['points']) for s in h.stations],[4,4,4]);balances(h) + def test_04_mass_readout_independent_truth(self): + h=configured(method=dict(r.METHOD_EXAMPLE,entered_mass_kg=.0002));call(h,'acquisition.start',stations=[0]);finish(h);p=h.stations[0]['points'][5];curve=r.LIB['substances'][r.SID]['runtime_equilibrium'];q=r.interp(curve['pressure_pa'],curve['loading_mol_kg'],p['pressure_pa']);self.assertAlmostEqual(p['loading_mol_kg']/q,.5,delta=.002);self.assertEqual(h.stations[0]['sample']['true_dry_mass_kg'],.0001);balances(h) + def test_05_free_space_two_temperature(self): + h=configured();v=call(h,'volume.calibrate',**r.VCAL_EXAMPLE);self.assertAlmostEqual(v['warm_volume_m3'],1e-5,places=14);self.assertAlmostEqual(v['cold_volume_m3'],1e-5,places=14) + before=copy.deepcopy(h.__dict__) + with self.assertRaises(r.ActionRejected):h.invoke('volume.calibrate',**dict(r.VCAL_EXAMPLE,cold_dosed_mol=r.VCAL_EXAMPLE['warm_dosed_mol'])) + self.assertEqual(h.__dict__,before) + def test_06_pressure_sensor_calibration(self): + h=configured(plant=dict(r.PLANT_EXAMPLE,pressure_gain=[1.1]*3,pressure_offset_pa=[20.]*3));p=h.pressure(0);self.assertAlmostEqual(h.indicated(0),1.1*p+20.,delta=.003);call(h,'pressure.calibrate',station=0,reference_pa=[0.,100000.],measured_pa=[20.,110020.]);self.assertAlmostEqual(h.indicated(0),p,delta=.003) + def test_07_cancel_preserves_resources(self): + h=configured();call(h,'acquisition.start',stations=[0]);h.step(220.);source=h.source;call(h,'acquisition.stop');h.step(10.);self.assertEqual(h.phase,'cancelled');self.assertEqual(h.source,source);self.assertTrue(h.stations[0]['sample']);self.assertGreater(h.pumped,0);balances(h) + def test_08_source_depletion_timeout(self): + h=configured(plant=dict(r.PLANT_EXAMPLE,source_volume_m3=.00001));call(h,'acquisition.start',stations=[0]);finish(h,3600);self.assertEqual(h.phase,'failed');self.assertEqual(h.failure,'POINT_TIMEOUT');self.assertGreaterEqual(h.source,0);balances(h) + def test_09_dewar_tube_interlocks(self): + h=configured() + for k,a in [('guard.set',{'angle_rad':1.5}),('sample0.set',{'drop_m':.18})]: + with self.assertRaises(r.ActionRejected):h.invoke(k,**a) + call(h,'acquisition.start',stations=[0]) + with self.assertRaises(r.ActionRejected):h.invoke('dewar.set',lift_m=0.) + def test_10_finite_backfill_and_unload(self): + h=configured(method=dict(r.METHOD_EXAMPLE,relative_pressures=[.002,.005,.01,.02]));call(h,'acquisition.start',stations=[0]);finish(h);call(h,'dewar.set',lift_m=0.) + with self.assertRaises(r.ActionRejected):h.invoke('sample0.set',drop_m=.18) + source=h.source;call(h,'sample.backfill',station=0);h.step(5.);self.assertLess(h.source,source);self.assertAlmostEqual(h.pressure(0),101325.,delta=15.);call(h,'guard.set',angle_rad=1.5);call(h,'sample0.set',drop_m=.18);self.assertEqual(call(h,'sample.unload',station=0)['returned_mass_kg'],.0001);balances(h) + def test_11_ln2_capacity_and_depletion(self): + h=configured() + with self.assertRaises(r.ActionRejected):h.invoke('coolant.fill',volume_m3=.001) + h.ln2=1e-8;h.ln2_added=h.ln2;call(h,'acquisition.start',stations=[0]);h.step(1.);self.assertEqual(h.phase,'failed');self.assertEqual(h.ln2,0.);balances(h) + def test_12_degas_six_samples_two_heaters(self): + h=r.AntonpaarAutosorb6100Runtime();call(h,'plant.configure',**dict(r.PLANT_EXAMPLE,degas_heat_capacity_j_k=20.,degas_power_w=500.));call(h,'power.set',enabled=True);call(h,'coolant.fill',volume_m3=.003) + for b in range(2):call(h,'heater'+str(b)+'.set',drop_m=.16) + for i in range(6):call(h,'degas.load',**dict(r.DLOAD_EXAMPLE,slot=i,water_rate_at_373_s=.1)) + for b in range(2):call(h,'heater'+str(b)+'.set',drop_m=0.) + call(h,'degas.start',**dict(r.DPROGRAM_EXAMPLE,steps=[dict(temperature_k=333.15,hold_s=220.)],ramp_k_s=5.)) + h.step(250.);self.assertEqual(h.degas_phase,'succeeded');self.assertTrue(h.read('evaluator')['degas.dry_enough']);self.assertGreater(h.trap,5e-5) + h.step(150.) + for b in range(2):call(h,'heater'+str(b)+'.set',drop_m=.16) + for i in range(6):call(h,'degas.unload',slot=i) + balances(h) + def test_13_degas_cancel_and_hot_interlock(self): + h=configured(plant=dict(r.PLANT_EXAMPLE,degas_heat_capacity_j_k=20.,degas_power_w=500.));call(h,'heater0.set',drop_m=.16);call(h,'degas.load',**r.DLOAD_EXAMPLE);call(h,'heater0.set',drop_m=0.);call(h,'degas.start',**r.DPROGRAM_EXAMPLE);h.step(40.) + with self.assertRaises(r.ActionRejected):h.invoke('heater0.set',drop_m=.16) + call(h,'degas.stop');before=h.dtemps[0];h.step(5.);self.assertLess(h.dtemps[0],before);balances(h) + def test_14_trap_capacity_failure(self): + h=configured(plant=dict(r.PLANT_EXAMPLE,trap_capacity_kg=1e-6));call(h,'heater0.set',drop_m=.16);call(h,'degas.load',**r.DLOAD_EXAMPLE);call(h,'heater0.set',drop_m=0.);call(h,'degas.start',**r.DPROGRAM_EXAMPLE);h.step(100.);self.assertEqual(h.degas_phase,'failed');self.assertAlmostEqual(h.trap,1e-6);balances(h) + def test_15_bet_independent_analytic_curve(self): + qm=4.;C=75.;pts=[point(x,qm*C*x/((1-x)*(1+(C-1)*x))) for x in [.005,.01,.02,.03,.05,.08,.10,.15,.20,.25,.3]];b=r.bet_fit(pts,branch_confirmed=True);self.assertEqual(b['status'],'valid_estimate');self.assertAlmostEqual(b['monolayer_mol_kg'],qm,places=8);self.assertAlmostEqual(b['C'],C,places=8);self.assertAlmostEqual(b['area_m2_kg'],qm*r.NA*.162e-18,places=7) + self.assertIsNone(r.bet_fit([point(.2,0.),point(.3,-1.)])['area_m2_kg']) + def test_16_bjh_formula_and_branch_guard(self): + h=configured();pts=[point(x,q) for x,q in [(.4,2.),(.6,4.),(.8,8.),(.95,12.)]];out=call(h,'analysis.bjh',points=pts,branch='desorption');self.assertTrue(out['diameter_m']);x1=.95;x2=.8;t1=.354e-9*(5/-math.log(x1))**(1/3);t2=.354e-9*(5/-math.log(x2))**(1/3);k1=-2*r.N2['surface_tension_n_m']*r.VLIQ/(r.R*77*math.log(x1));k2=-2*r.N2['surface_tension_n_m']*r.VLIQ/(r.R*77*math.log(x2));radius=(t1+t2+k1+k2)/2;expected=4*r.VLIQ*(radius/((k1+k2)/2+t1-t2))**2;self.assertAlmostEqual(out['pore_volume_m3_kg'][0],expected,places=12);self.assertEqual(call(h,'analysis.bjh',points=pts,branch='unspecified')['diameter_m'],[]) + def test_17_template_range_and_method_validation(self): + h=configured();call(h,'method.configure',**dict(r.METHOD_EXAMPLE,relative_pressures=[.002,.01,.5,.996])) + with self.assertRaises(r.ActionRejected):h.invoke('acquisition.start',stations=[0]) + for points in [[.1,.2,.15,.3],[.1]*4,[]]: + with self.assertRaises(r.ActionRejected):h.invoke('method.configure',**dict(r.METHOD_EXAMPLE,relative_pressures=points)) + for v in [True,float('nan'),float('inf'),-1.]: + with self.assertRaises(r.ActionRejected):h.step(v) + def test_18_permissions_dedup_poll_and_write(self): + h=configured();h.register_principal('agent');h.register_principal('other');agent=h.session('agent');other=h.session('other');d=agent.describe(instance_id=h.instance_id);self.assertNotIn('plant.configure',d['capabilities']);self.assertNotIn('station0.identity',agent.read(instance_id=h.instance_id)['observations']);denied=agent.invoke(instance_id=h.instance_id,capability_id='sample.load',arguments=r.SAMPLE_EXAMPLE,request_id='deny');self.assertEqual(denied['error']['code'],'ACCESS_DENIED');args=dict(instance_id=h.instance_id,capability_id='acquisition.start',arguments={'stations':[0]},request_id='start');a=agent.invoke(**args);self.assertEqual(a,agent.invoke(**args));op=a['operation_id'];self.assertEqual(agent.poll(op)['status'],'running') + with self.assertRaises(r.ActionRejected):other.poll(op) + bad=agent.invoke(**dict(args,arguments={'stations':[1]}));self.assertEqual(bad['error']['code'],'REQUEST_CONFLICT');h.step(3.);agent.cancel(op,'cancel');self.assertEqual(agent.poll(op)['status'],'cancelled');agent.write(instance_id=h.instance_id,state_id='power.enabled',value=False,request_id='off');self.assertFalse(h.powered) + def test_19_queries_atomicity_and_independent_instances(self): + h=configured();before=copy.deepcopy(h.__dict__);call(h,'process.measure');call(h,'ledger.read');call(h,'template.reference',substance_id=r.SID);h.read();self.assertEqual(h.__dict__,before);other=configured();call(h,'acquisition.start',stations=[0]);h.step(1.);self.assertEqual(other.time_s,0.);self.assertEqual(other.phase,'idle') + for k in r.UNSUPPORTED: + with self.assertRaises(r.ActionRejected):h.invoke(k) + with self.assertRaises(r.ActionRejected):h.invoke('sample0.set',drop_m=True) + def test_20_fixed_clock_partition_and_slot_schemas(self): + a=configured();b=configured();call(a,'acquisition.start',stations=[0]);call(b,'acquisition.start',stations=[0]);a.step(20.) + for _ in range(400):b.step(.05) + self.assertEqual(a.read('evaluator'),b.read('evaluator')) + for k,v in a.read('evaluator').items():self.assertFalse(tool.validate_value(v,r.SLOTS[k][0]),(k,v)) + self.assertEqual(set(a.read('evaluator')),set(r.SLOTS));balances(a) + def test_21_warmup_retained_gas_interlock(self): + h=configured();call(h,'acquisition.start',stations=[0]);h.step(400.);call(h,'acquisition.stop') + with self.assertRaises(r.ActionRejected):h.invoke('dewar.set',lift_m=0.) + h.step(600.);call(h,'dewar.set',lift_m=0.);balances(h) +if __name__=='__main__':unittest.main() diff --git a/tests/test_asset_antonpaar_litesizerdia.py b/tests/test_asset_antonpaar_litesizerdia.py new file mode 100644 index 0000000000000000000000000000000000000000..a1113dee8dda0dd489f5cc9b52e56d3628b839bf --- /dev/null +++ b/tests/test_asset_antonpaar_litesizerdia.py @@ -0,0 +1,111 @@ +import unittest,copy,pickle,math,sys +from pathlib import Path +from unittest import mock +import numpy as np,cv2 +from scripts.asset_runtime import antonpaar_litesizerdia as r +O=Path(__file__).resolve().parents[1]/'outputs/expansion_batch03/t4_measure/antonpaar_litesizerdia';sys.path.insert(0,str(O));from example_setup import build +class TestDia(unittest.TestCase): + def done(self,h,dt=6.):h.invoke('acquisition.start');h.step(dt);self.assertEqual(h.phase,'succeeded',h.error);return h + def test01_source(self): + self.assertEqual(r.LIB['coverage']['raw_binary_images'],384);self.assertEqual(r.LIB['coverage']['original_particle_records'],6000);self.assertEqual(r.LIB['coverage']['named_valid_powder_records'],97) + def test02_rectangle_feret(self): + a=np.ones((30,40),np.uint8);v=r.descriptors(a,2e-6);self.assertAlmostEqual(v['area_m2'],1200*4e-12);self.assertAlmostEqual(v['feret_min_m'],60e-6);self.assertAlmostEqual(v['feret_max_m'],100e-6);self.assertAlmostEqual(v['aspect_ratio'],.6) + def test03_circle(self): + a=np.zeros((221,221),np.uint8);cv2.circle(a,(110,110),100,1,-1);v=r.descriptors(a,1e-6);self.assertLess(abs(v['circularity']-1),.01);self.assertLess(abs(v['equivalent_diameter_m']/200e-6-1),.005) + def test04_rle_exact(self): + a=np.random.default_rng(0).integers(0,2,(18,29));self.assertTrue(np.array_equal(a,r.decode_rle(a.shape,r.rle(a)))) + def test05_real_outline_metadata(self): + ratios=[] + for sid in ['grain_capecod','grain_fijipink','grain_hawaii','grain_ottawa1220','grain_peaceriver','grain_vieques']: + for i in [0,20,40,63]: + mask,pitch,*_=r.particle(sid,i);d=r.descriptors(mask,pitch);ref=r.LIB['substances'][sid]['value']['images'][i]['metadata'];ratios.append(abs(d['feret_max_m']/ref['FERET_MAX']-1));self.assertLess(abs(d['aspect_ratio']-ref['ASPECT_RATIO']),.035) + self.assertLess(max(ratios),.04) + def test06_three_modes(self): + for mode in ['liquid','dry','freefall']: + h=self.done(build(mode));self.assertEqual(len(h.images),32);self.assertGreater(h.summary['d50_m'],0.);self.assertEqual(h.frames,880);self.assertLess(abs(h._ledger()['solid_error_kg']),1e-15) + def test07_read_pure(self): + h=build();before=pickle.dumps(h.__dict__) + for _ in range(5):h.read();h.describe();h._result() + self.assertEqual(before,pickle.dumps(h.__dict__)) + def test08_setpoint_only(self): + h=build();t=h.time_s;temp=h.temperature;h.invoke('method.configure',**dict(r.METHOD_EXAMPLE,ultrasound_w=50.));self.assertEqual(h.temperature,temp);self.assertEqual(h.time_s,t) + def test09_wet_recirculate(self): + h=self.done(build(count=8));self.assertEqual(len(h.population),8);self.assertEqual(h.waste_n,0);self.assertEqual(h.pass_index,32) + def test10_dry_finite(self): + h=self.done(build('dry',count=12));self.assertEqual(h.waste_n,12);self.assertEqual(len(h.population),0);self.assertEqual(len(h.images),12);self.assertGreater(h.air_used,0) + def test11_freefall_recover(self): + h=self.done(build('freefall',count=12));self.assertEqual(len(h.collected),12);h.invoke('power.set',enabled=False);h.invoke('lid.set',angle_rad=1.55);h.invoke('sample.recover');self.assertEqual(h.returned_n,12);self.assertAlmostEqual(h.loaded_m,h.returned_m);self.assertEqual(h.air_used,0.) + def test12_drain_mass_heat(self): + h=self.done(build(method={'ultrasound_w':50.}));self.assertGreater(h.temperature,293.15);h.invoke('liquid.drain');h.step(1.);self.assertGreater(h.waste_n,0);self.assertLess(h.waste_n,128);self.assertEqual(h._ledger()['particles_error'],0);h.step(10.);self.assertEqual(h.liquid,0);self.assertEqual(h.waste_n,128);l=h._ledger();self.assertLess(abs(l['solid_error_kg']),1e-15);self.assertLess(abs(l['heat_error_j']),1e-6) + def test13_cancel_partial(self): + h=build('dry');h.invoke('acquisition.start');h.step(.5);mass=h.waste_m;air=h.air_used;n=len(h.images);h.invoke('acquisition.stop');h.step(1.);self.assertEqual(h.waste_m,mass);self.assertEqual(h.air_used,air);self.assertEqual(len(h.images),n);self.assertGreater(n,0) + def test14_air_exhaust(self): + h=build('dry');h.air=.001;h.air_added=.001;h.invoke('acquisition.start');h.step(1.);self.assertEqual(h.phase,'failed');self.assertEqual(h.error,'AIR_EXHAUSTED');self.assertAlmostEqual(h.air,0.) + def test15_atomic_reject(self): + h=build() + for k,a in [('power.set',{'enabled':1}),('air.add',{'amount_mol':float('nan')}),('module.withdraw',{'distance_m':.3}),('method.configure',dict(r.METHOD_EXAMPLE,mode='dry'))]: + before=pickle.dumps(h.__dict__) + with self.assertRaises(r.ActionRejected):h.invoke(k,**a) + self.assertEqual(before,pickle.dumps(h.__dict__)) + def test16_access(self): + h=build();h.invoke('lid.set',angle_rad=1.55) + with self.assertRaisesRegex(r.ActionRejected,'CLOSURE'):h.invoke('acquisition.start') + h.invoke('lid.set',angle_rad=0.);h.invoke('acquisition.start') + with self.assertRaisesRegex(r.ActionRejected,'BUSY'):h.invoke('lid.set',angle_rad=1.55) + def test17_truth_and_instances(self): + h=build();g=build('freefall');self.done(h);self.assertEqual(g.phase,'idle');a=g.session();d=a.describe(instance_id=g.instance_id);self.assertNotIn('plant.configure',d['capabilities']);self.assertNotIn('truth.solid_kg',a.read(instance_id=g.instance_id)['observations']) + with self.assertRaises(r.ActionRejected):a.read(instance_id=g.instance_id,state_ids=['truth.solid_kg']) + self.assertEqual(a.invoke(instance_id=g.instance_id,capability_id='ledger.read',arguments={},request_id='x')['status'],'rejected') + def test18_principal_registration(self): + h=r.AntonpaarLitesizerdiaRuntime();h.register_principal('matterix_agent');h.register_principal('matterix_evaluator','evaluator') + with self.assertRaises(r.ActionRejected):h.register_principal('matterix_agent','evaluator') + with self.assertRaises(r.ActionRejected):h.session('unknown') + def test19_idempotent(self): + h=build();a=h.session();kw=dict(instance_id=h.instance_id,capability_id='acquisition.start',arguments={},request_id='x');first=a.invoke(**kw);h.step(.5);second=a.invoke(**kw);self.assertEqual(first,second);self.assertEqual(a.invoke(**dict(kw,capability_id='power.set',arguments={'enabled':False}))['error']['code'],'REQUEST_CONFLICT') + def test20_async_ownership(self): + h=build();h.register_principal('other');a=h.session();op=a.invoke(instance_id=h.instance_id,capability_id='acquisition.start',arguments={},request_id='x')['operation_id'];h.step(.5) + with self.assertRaises(r.ActionRejected):h.session('other').poll(op) + a.cancel(op,'cancel');self.assertEqual(a.poll(op)['status'],'cancelled');partial=len(a.poll(op)['result']['particles']);self.assertGreater(partial,0);h.invoke('acquisition.start');self.assertEqual(len(a.poll(op)['result']['particles']),partial) + def test21_external_calibration(self): + h=build(plant={'true_pixel_at_1x_m':3.3e-6});h.invoke('calibration.pixel',reference_length_m=330e-6,observed_pixels=100.);self.done(h);ref=self.done(build());self.assertLess(abs(h.summary['d50_m']/ref.summary['d50_m']-1),.01) + def test22_scale_bias_independent(self): + h=self.done(build(method={'pixel_size_m':6e-6}));ref=self.done(build());self.assertAlmostEqual(h.summary['d50_m']/ref.summary['d50_m'],2.) + def test23_high_throughput(self): + h=self.done(build('dry',method={'feed_particles_s':500.,'fps':10.,'target_images':200,'duration_s':1.},count=1000),1.);self.assertGreater(h.missed,0);self.assertLessEqual(len(h.images),10);self.assertEqual(h.waste_n,500) + def test24_resolution_clipping(self): + h=build(method={'magnification':6.,'pixel_size_m':.5e-6,'target_images':256,'duration_s':8.});h.invoke('acquisition.start');h.step(8.);self.assertGreater(h.rejected,0) + def test25_reconstruction_explicit(self): + with self.assertRaises(r.ActionRejected):build(sid='powder_001') + h=self.done(build(sid='powder_001',method={'accept_shape_reconstruction':True}));self.assertIn('synthetic_outline',h.images[0]['evidence']) + with self.assertRaises(r.ActionRejected):build(sid='powder_050',method={'accept_shape_reconstruction':True}) + with self.assertRaises(r.ActionRejected):build(method={'accept_inferred_source_scale':False}) + def test26_clock_partition(self): + h=build();g=build();h.invoke('acquisition.start');g.invoke('acquisition.start');h.step(1.23) + for dt in [.333,.121,.449,.327]:g.step(dt) + self.assertEqual(h.read(),g.read());self.assertEqual(h._result(),g._result()) + def test27_unsupported_no_fake_sensor(self): + h=build() + for k in r.UNSUPPORTED: + with self.assertRaisesRegex(r.ActionRejected,'UNSUPPORTED'):h.invoke(k) + self.assertNotIn('temperature.measured_k',h.read());self.assertNotIn('truth.temperature_k',h.read('agent')) + def test28_query_cannot_steal_operation(self): + h=build();h.register_principal('observer');a=h.session();o=h.session('observer');op=a.invoke(instance_id=h.instance_id,capability_id='acquisition.start',arguments={},request_id='owner')['operation_id'];reply=o.invoke(instance_id=h.instance_id,capability_id='acquisition.result',arguments={},request_id='read');self.assertEqual(reply['status'],'succeeded');self.assertIsNone(reply['operation_id']) + with self.assertRaises(r.ActionRejected):o.poll(op) + self.assertEqual(a.poll(op)['status'],'running') + def test29_result_source_stable(self): + h=self.done(build('freefall'));source=h._result()['template_source'];original=copy.deepcopy(h._result());h.invoke('power.set',enabled=False);h.invoke('lid.set',angle_rad=1.55);h.invoke('sample.recover');h.invoke('method.configure',**dict(r.METHOD_EXAMPLE,mode='freefall',accept_shape_reconstruction=True));h.invoke('sample.load',**dict(r.SAMPLE_EXAMPLE,substance_id='powder_001'));self.assertEqual(h._result()['template_source'],source);h.invoke('calibration.pixel',reference_length_m=600e-6,observed_pixels=100.);self.assertEqual(h._result(),original) + def test30_recovery_truth_requires_evaluator(self): + h=self.done(build('freefall',count=12));h.invoke('power.set',enabled=False);h.invoke('lid.set',angle_rad=1.55);agent=h.session();evaluator=h.session('evaluator');self.assertNotIn('sample.recover',agent.describe(instance_id=h.instance_id)['capabilities']);before=pickle.dumps(h.__dict__) + denied=agent.invoke(instance_id=h.instance_id,capability_id='sample.recover',arguments={},request_id='denied');self.assertEqual(denied['error']['code'],'ACCESS_DENIED');self.assertEqual(before,pickle.dumps(h.__dict__));recovered=evaluator.invoke(instance_id=h.instance_id,capability_id='sample.recover',arguments={},request_id='recover');self.assertEqual(recovered['status'],'succeeded');self.assertEqual(recovered['result']['particles'],12);self.assertAlmostEqual(recovered['result']['mass_kg'],h.loaded_m);self.assertLess(abs(h._ledger()['solid_error_kg']),1e-15) + def test31_metadata_covers_actual_state_changes(self): + metadata=r.export_antonpaar_litesizerdia_contract_metadata();original=r.AntonpaarLitesizerdiaRuntime.invoke;observed=set() + def audited_invoke(h,cap,**arguments): + before=h.read();result=original(h,cap,**arguments);after=h.read();changed={state for state in before if before[state]!=after[state]};declared={effect['state_id'] for effect in metadata['capabilities'][cap]['state_effects'] if effect['timing']=='immediate'} + self.assertFalse(changed-declared,(cap,changed-declared));observed.add(cap);return result + with mock.patch.object(r.AntonpaarLitesizerdiaRuntime,'invoke',audited_invoke): + h=build(method={'ultrasound_w':50.});h.invoke('acquisition.start');h.invoke('sim.step',dt_s=6.);h.invoke('liquid.drain');h.invoke('sim.step',dt_s=11.);h.invoke('lid.set',angle_rad=1.55);h.invoke('liquid.fill',volume_m3=.0003);h.invoke('calibration.pixel',reference_length_m=.000600,observed_pixels=100.);h.invoke('method.configure',**dict(h.method,magnification=6.,pixel_size_m=.5e-6,threshold=.6));h.invoke('power.set',enabled=False);h.invoke('service.set',distance_m=.16);h.invoke('service.set',distance_m=0.) + for mode in ['dry','freefall']: + d=build(mode);d.invoke('acquisition.start');d.invoke('sim.step',dt_s=.5);d.invoke('acquisition.stop');d.invoke('power.set',enabled=False);d.invoke('lid.set',angle_rad=1.55);d.invoke('sample.recover') + q=r.AntonpaarLitesizerdiaRuntime();q.invoke('plant.configure',**dict(r.PLANT_EXAMPLE,ambient_k=298.15));q.invoke('power.set',enabled=True);q.invoke('background.capture');q.invoke('power.set',enabled=False);q.invoke('latch.set',angle_rad=.65);q.invoke('module.withdraw',distance_m=.32);q.invoke('module.select',mode='dry') + self.assertTrue(set(r.IMMEDIATE_EFFECTS)<=observed) +if __name__=='__main__':unittest.main() diff --git a/tests/test_asset_antonpaar_litesizerdls.py b/tests/test_asset_antonpaar_litesizerdls.py new file mode 100644 index 0000000000000000000000000000000000000000..e8ec68b1ac4286903f3e3e01649f9d701450b62f --- /dev/null +++ b/tests/test_asset_antonpaar_litesizerdls.py @@ -0,0 +1,114 @@ +import sys,unittest,copy,math,json +from pathlib import Path +from unittest import mock +import numpy as np +R=Path(__file__).resolve().parents[1];sys.path.insert(0,str(R/'scripts'));sys.path.insert(0,str(R/'outputs/expansion_batch03/t4_measure/antonpaar_litesizerdls'));import example_setup as ex +rt=ex.rt +class TestLitesizerDls(unittest.TestCase): + def ready(self,**kw):return ex.configure(rt.AntonpaarLitesizerdlsRuntime(),**kw) + def test_01_source_integrity(self): + lib=rt.LIB['substances'];self.assertEqual(len(lib),103);self.assertEqual(len({lib['cad_'+str(i).zfill(2)]['chemical_formulation']['ionizable_lipid'] for i in range(1,97)}),96);self.assertEqual(lib['cad_85']['value']['pdi'],.16);self.assertIsNone(lib['bpd']['value']['diameter_m']);self.assertEqual(len(lib['bpd']['value']['g2']['acquisitions']),30) + def test_02_independent_stokes_einstein(self): + tau=np.geomspace(1e-7,.01,240);D=1.380649e-23*298.15/(3*math.pi*.00089*100e-9);q=4*math.pi*1.33*math.sin(math.pi/4)/658e-9;g2=1+.45*np.exp(-2*D*q*q*tau);out=rt.analyze(tau,g2,298.15,.00089,1.33,90);self.assertLess(abs(out['z_average_m']/100e-9-1),.003);self.assertLess(out['pdi'],.003);self.assertAlmostEqual(sum(out['intensity_fraction']),1.,12) + def test_03_three_angles_inversion(self): + for angle in [15,90,175]: + tau=np.geomspace(1e-7,10,280);g=rt.second_order(tau,180e-9,.2,293.15,.001002,1.333,angle,.4);v=rt.analyze(tau,g,293.15,.001002,1.333,angle);self.assertLess(abs(v['z_average_m']/180e-9-1),1e-4);self.assertAlmostEqual(v['pdi'],.2,4) + def test_04_measured_raw_protein(self): + h=self.ready(kind='quartz',reference='bpd');v=ex.run(h);self.assertEqual(v['phase'],'succeeded');self.assertTrue(5e-910e-9)&(x<40e-9)].sum(),.3);self.assertGreater(w[(x>150e-9)&(x<600e-9)].sum(),.3) + def test_06_entered_viscosity_not_truth(self): + h=self.ready();m=dict(rt.METHOD_EXAMPLE,entered_viscosity_pa_s=rt.METHOD_EXAMPLE['entered_viscosity_pa_s']*2);ex.call(h,'method.configure',**m);v=ex.run(h);self.assertLess(abs(v['dls']['z_average_m']/rt.LIB['substances'][rt.SID]['value']['diameter_m']-.5),.002) + def test_07_external_size_calibration(self): + h=self.ready();ex.call(h,'dls.calibrate',reference_m=200e-9,measured_m=100e-9);v=ex.run(h);self.assertLess(abs(v['dls']['z_average_m']/rt.LIB['substances'][rt.SID]['value']['diameter_m']-2),.002) + def test_08_zeta_phase_and_eof_rejection(self): + h=self.ready(mode='zeta');v=ex.run(h);self.assertEqual(v['phase'],'succeeded');self.assertLess(abs(v['els']['zeta_v']/rt.LIB['substances'][rt.SID]['value']['zeta_v']-1),.002);self.assertLess(v['els']['phase_residual_rad'],1e-10);self.assertGreater(max(v['els']['phase_plus_rad'])-min(v['els']['phase_plus_rad']),.01) + def test_09_external_mobility_calibration(self): + h=self.ready(mode='zeta');ex.call(h,'mobility.calibrate',reference_m2_v_s=[-1e-8,1e-8],measured_m2_v_s=[-2e-8,2e-8]);v=ex.run(h);self.assertLess(abs(v['els']['zeta_v']/rt.LIB['substances'][rt.SID]['value']['zeta_v']-.5),.002) + def test_10_finite_sample_energy_return(self): + h=self.ready();ex.run(h);ex.unload(h);v=ex.call(h,'ledger.read');self.assertEqual(v['present_liquid_kg'],0);self.assertEqual(v['loaded_particles_kg'],v['returned_particles_kg']);self.assertLess(abs(v['heat_balance_j']),1e-7);self.assertGreater(v['returned_heat_j'],0.) + def test_11_heat_setpoint_not_instant(self): + h=self.ready();t=h.temperature;ex.call(h,'method.configure',**dict(rt.METHOD_EXAMPLE,temperature_k=303.15,timeout_s=500.));self.assertEqual(h.temperature,t);h.step(100.);self.assertTrue(tb for a,b in zip(ds,ds[1:]))) + def test_28_completed_operation_survives_sample_replacement(self): + r=setup();r.register_principal('a');s=r.session('a');ans=s.invoke(instance_id=r.instance_id,capability_id='acquisition.start',arguments={},request_id='old_sample');op=ans['operation_id'] + while r.phase=='running':r.step(.1) + original=s.poll(op);self.assertEqual(len(original['result']['points']),4) + call(r,'guard0.set',angle_rad=1.4);call(r,'cell.drain');call(r,'sample.unload');call(r,'sample.load',**dict(rt.SAMPLE_EXAMPLE,sample_id='replacement')) + self.assertEqual(original,s.poll(op)) + call(r,'guard0.set',angle_rad=0.);call(r,'method.configure',**rt.METHOD_EXAMPLE) + ans=s.invoke(instance_id=r.instance_id,capability_id='acquisition.start',arguments={},request_id='new_sample');self.assertNotEqual(op,ans['operation_id']);r.step(.1);self.assertEqual(original,s.poll(op)) + returned=s.poll(op);returned['result']['points'].clear();self.assertEqual(original,s.poll(op)) + def test_29_cancelled_operation_result_is_immutable(self): + r=setup();r.register_principal('a');s=r.session('a');ans=s.invoke(instance_id=r.instance_id,capability_id='acquisition.start',arguments={},request_id='start');r.step(5.) + s.cancel(ans['operation_id'],'cancel');original=s.poll(ans['operation_id']);self.assertEqual(original['status'],'cancelled');r.step(20.);self.assertEqual(original,s.poll(ans['operation_id'])) + def test_30_failed_operation_retains_partial_result(self): + r=setup();method=copy.deepcopy(r.method);method['point_timeout_s']=1.;call(r,'method.configure',**method);r.register_principal('a');s=r.session('a');ans=s.invoke(instance_id=r.instance_id,capability_id='acquisition.start',arguments={},request_id='start') + while r.phase=='running':r.step(.1) + original=s.poll(ans['operation_id']);self.assertEqual(original['status'],'failed');self.assertEqual(r.failure,'POINT_TIMEOUT');r.step(20.);self.assertEqual(original,s.poll(ans['operation_id'])) + def test_31_metadata_covers_actual_observable_changes(self): + metadata=rt.export_antonpaar_poremaster60_contract_metadata();original=rt.AntonpaarPoremaster60Runtime.invoke;observed=set() + def audited_invoke(r,k,**arguments): + before=r.read('evaluator');result=original(r,k,**arguments);after=r.read('evaluator');changed={state for state in before if before[state]!=after[state]};declared={effect['state_id'] for effect in metadata['capabilities'][k]['state_effects'] if effect['timing']=='immediate'} + self.assertFalse(changed-declared,(k,changed-declared));observed.add(k);return result + with mock.patch.object(rt.AntonpaarPoremaster60Runtime,'invoke',audited_invoke): + r=setup();run(r);high(r);run(r);call(r,'cap.set',lift_m=.19);call(r,'guard0.set',angle_rad=1.4);call(r,'cell.transfer',destination='low0');r.step(5.);call(r,'cell.drain');call(r,'sample.unload') + # At idle, calibration changes sensor observations without advancing the process. + call(r,'pressure.calibrate',**dict(rt.PCAL_EXAMPLE,measured_pa=[0.,55*rt.PSI]));call(r,'volume.calibrate',**dict(rt.VCAL_EXAMPLE,measured_capacitance_f=[0.,10e-12]));call(r,'blank.calibrate',pressures_pa=[0.,rt.P_MAX],volumes_m3=[0.,0.]);call(r,'cell.configure',bulb_volume_m3=6.6e-6,stem_capacity_m3=2e-6) + for stop in ['acquisition.stop','emergency.stop','power.set']: + q=setup();call(q,'acquisition.start');q.step(1.);call(q,stop,**({'enabled':False} if stop=='power.set' else {})) + self.assertTrue(set(rt.IMMEDIATE_EFFECTS)<=observed) +if __name__=='__main__':unittest.main() diff --git a/tests/test_asset_antonpaar_psa1190.py b/tests/test_asset_antonpaar_psa1190.py new file mode 100644 index 0000000000000000000000000000000000000000..c0b5d190277f6b7536197f26b755370d5729e981 --- /dev/null +++ b/tests/test_asset_antonpaar_psa1190.py @@ -0,0 +1,113 @@ +import unittest,copy,pickle,sys,math +from pathlib import Path +from unittest import mock +import numpy as np +from scripts.asset_runtime import antonpaar_psa1190 as r +O=Path(__file__).resolve().parents[1]/'outputs/expansion_batch03/t4_measure/antonpaar_psa1190';sys.path.insert(0,str(O));from example_setup import build +class TestPsa1190(unittest.TestCase): + def test29_host_registration(self): + h=r.AntonpaarPsa1190Runtime();h.register_principal('matterix_agent');h.register_principal('matterix_evaluator','evaluator');self.assertNotIn('truth.solid_kg',h.session('matterix_agent').read(instance_id=h.instance_id)['observations']) + with self.assertRaises(r.ActionRejected):h.register_principal('matterix_agent','evaluator') + with self.assertRaises(r.ActionRejected):h.session('unregistered') + def done(self,h,dt=15.1):h.invoke('acquisition.start');h.step(dt);self.assertEqual(h.phase,'succeeded',h.error);return h + def test01_sources(self): + c=r.LIB['coverage'];self.assertEqual(c['total_records'],232);self.assertEqual(c['full_distribution_records'],118);self.assertEqual(c['pharmaceutical_named_valid_records'],97) + for k,v in r.LIB['substances'].items():self.assertTrue(v['source']);self.assertEqual(v['evidence'],'measured_literature') + def test02_rayleigh(self): + x=.001;m=1.5+0j;_,qe,qs=r.mie_scattering(x,m,np.array([.1,.2]));reference=8/3*x**4*abs((m*m-1)/(m*m+2))**2;self.assertAlmostEqual(qs/reference,1,places=5);self.assertAlmostEqual(qe/qs,1,places=9) + def test03_mie_energy(self): + th=np.linspace(0,np.pi,12001);I,qe,qs=r.mie_scattering(2.,1.5+0j,th);integral=2/4*np.trapz(I*np.sin(th),th);self.assertAlmostEqual(qe,qs,places=11);self.assertAlmostEqual(integral,qs,places=6);self.assertAlmostEqual(qs,1.798418163226,places=8) + def test04_mie_absorption(self): + _,qe,qs=r.mie_scattering(2.,1.5+.1j,np.array([.1]));self.assertGreater(qe,qs);self.assertGreater(qs,0) + def test05_fraunhofer_kernel(self): + K,_=r.optical_kernel(2.9,3.4,2.9,3.1,1.,'fraunhofer');j=int(np.searchsorted(r.DIAM,100e-6));d=r.DIAM[j];k=2*np.pi/830e-9;x=k*d/2;u=x*np.sin(np.deg2rad(r.THETA[0]));expected=x**4*(2*r.j1(u)/u)**2/4/k**2*6/(np.pi*d**3);self.assertAlmostEqual(K[0,j]/expected,1,places=12) + def test06_inverse_single_bin(self): + m=dict(r.METHOD_EXAMPLE,regularization=0.);K,_=r.optical_kernel(2.9,3.4,2.9,3.1,1.33,'mie_hybrid');j=int(np.searchsorted(r.DIAM,40e-6));p=r.invert(K[:,j],m);self.assertAlmostEqual(p['d50_m']/r.DIAM[j],1,places=6);self.assertGreater(p['volume_fraction'][j],.999) + def test07_source_steel(self): + h=self.done(build());self.assertLess(abs(h.psd['d50_m']/36.7e-6-1),.03);self.assertLess(h.psd['relative_fit_residual'],1e-3);self.assertEqual(h.mass_waste,0);self.assertIn('assumed',h.evidence) + def test08_soil_full_curve(self): + h=self.done(build('wet','soil_2014_111'));p,*_=r.template('soil_2014_111',False,True,'wet');d=r.quantiles(p);self.assertLess(abs(h.psd['d50_m']/d[1]-1),.06);self.assertLess(abs(sum(h.psd['volume_fraction'])-1),1e-9) + def test09_refractive_input_independent(self): + K,_=r.optical_kernel(1.543,.01,1.543,.01,1.33,'mie_hybrid');p=np.zeros(len(r.DIAM));p[np.searchsorted(r.DIAM,1.e-6)]=1;m=dict(r.METHOD_EXAMPLE,n635=1.543,k635=.01,n830=1.543,k830=.01,regularization=0.);good=r.invert(K@p,m);bad=r.invert(K@p,dict(m,n635=1.8,n830=1.8));self.assertLess(abs(good['d50_m']/r.DIAM[np.argmax(p)]-1),.01);self.assertGreater(np.linalg.norm(np.array(good['volume_fraction'])-bad['volume_fraction']),.1) + def test10_calibration(self): + h=build();h.invoke('calibration.size',reference_m=50e-6,observed_m=40e-6);self.done(h);self.assertLess(abs(h.psd['d50_m']/36.7e-6-1.25),.04) + def test11_wet_mass_and_drain_heat(self): + h=self.done(build());h.invoke('liquid.drain');h.step(23.);self.assertEqual(h.phase,'succeeded');l=h._ledger();self.assertAlmostEqual(l['solid_waste_kg'],.008,places=11);self.assertAlmostEqual(l['liquid_present_kg'],0);self.assertLess(abs(l['heat_error_j']),1e-6);self.assertLess(abs(l['solid_error_kg']),1e-12) + def test12_dry_finite_recover(self): + h=self.done(build('dry'));self.assertAlmostEqual(h.mass_waste,.006,places=10);self.assertLess(h.air,2.);h.invoke('power.set',enabled=False);h.invoke('dry_hood.set',lift_m=.2);h.invoke('sample.recover');self.assertAlmostEqual(h.mass_loaded,h.mass_waste+h.mass_returned,places=10);self.assertLess(abs(h._ledger()['air_error_mol']),1e-11) + def test13_cancel_partial(self): + h=build('dry');h.invoke('acquisition.start');h.step(3.);m=h.mass_waste;gas=h.air_used;h.invoke('acquisition.stop');h.step(2.);self.assertEqual(h.mass_waste,m);self.assertEqual(h.air_used,gas);self.assertGreater(m,0) + def test14_warmup(self): + h=r.AntonpaarPsa1190Runtime();h.invoke('plant.configure',**r.PLANT_EXAMPLE);h.invoke('power.set',enabled=True);h.step(59.9) + with self.assertRaisesRegex(r.ActionRejected,'NOT_READY'):h.invoke('background.start') + h.step(.1);self.assertEqual(h.warm,60.) + def test15_background_clock(self): + h=build();h.invoke('liquid.drain');h.step(23);h.invoke('tank_lid.set',slide_m=.17);h.invoke('liquid.fill',volume_m3=.00045);h.invoke('tank_lid.set',slide_m=0.);h.invoke('background.start');h.step(59.9);self.assertFalse(h.bg_ready);h.step(.1);self.assertTrue(h.bg_ready) + def test16_interlocks(self): + h=build();h.invoke('tank_lid.set',slide_m=.17) + with self.assertRaisesRegex(r.ActionRejected,'CLOSURE'):h.invoke('acquisition.start') + with self.assertRaisesRegex(r.ActionRejected,'POWER_INTERLOCK'):h.invoke('cover.set',angle_rad=1.2) + with self.assertRaisesRegex(r.ActionRejected,'BLANK_NOT_EMPTY'):h.invoke('tank_lid.set',slide_m=0.);h.invoke('background.start') + def test17_strict_atomic(self): + h=build() + for cap,args in [('power.set',{'enabled':1}),('method.configure',dict(r.METHOD_EXAMPLE,acquisition_s=60)),('air.add',{'amount_mol':float('nan')}),('sample.load',dict(r.SAMPLE_EXAMPLE))]: + before=pickle.dumps(h.__dict__) + with self.assertRaises(r.ActionRejected):h.invoke(cap,**args) + self.assertEqual(before,pickle.dumps(h.__dict__)) + def test18_truth_and_instances(self): + h=build();g=build('dry');a=h.session('agent');self.assertNotIn('truth.solid_kg',a.read(instance_id=h.instance_id)['observations']);self.assertNotIn('plant.configure',a.describe(instance_id=h.instance_id)['capabilities']) + with self.assertRaises(r.ActionRejected):a.read(instance_id=h.instance_id,state_ids=['truth.solid_kg']) + self.done(h);self.assertEqual(g.phase,'succeeded');self.assertIsNone(g.psd) + def test19_pure_reads_dedup(self): + h=build();a=h.session();before=pickle.dumps(h.__dict__) + for _ in range(3):h.read();a.describe(instance_id=h.instance_id);a.read(instance_id=h.instance_id) + self.assertEqual(before,pickle.dumps(h.__dict__));args=dict(instance_id=h.instance_id,capability_id='acquisition.start',arguments={},request_id='same');x=a.invoke(**args);y=a.invoke(**args);self.assertEqual(x,y);self.assertEqual(h._counter,2);z=a.invoke(**dict(args,capability_id='power.set',arguments={'enabled':False}));self.assertEqual(z['error']['code'],'REQUEST_CONFLICT') + def test20_async_record_ownership(self): + h=build();a=h.session();e=h.session('evaluator');q=a.invoke(instance_id=h.instance_id,capability_id='acquisition.start',arguments={},request_id='start');op=q['operation_id'] + with self.assertRaises(r.ActionRejected):e.poll(op) + h.step(15.1);before=a.poll(op);h.invoke('liquid.drain');h.step(23.);self.assertEqual(before,a.poll(op)) + def test21_gas_exhaustion(self): + h=build('dry');h.air=.001;h.air_loaded=.001;h.invoke('acquisition.start');h.step(2.);self.assertEqual(h.error,'GAS_EXHAUSTED');self.assertGreaterEqual(h.air,0);self.assertLess(abs(h._ledger()['air_error_mol']),1e-12) + def test22_obscuration(self): + h=build();h.wet*=10;h.mass_loaded*=10;h.invoke('acquisition.start');h.step(15.);self.assertEqual(h.error,'OBSCURATION_RANGE');self.assertIsNone(h.psd) + def test23_heat_and_cooling(self): + h=self.done(build());hot=h.temperature;self.assertGreater(hot,293.15);h.invoke('power.set',enabled=False);self.assertEqual(hot,h.temperature);h.step(100.);self.assertLess(h.temperature,hot);self.assertLess(abs(h._ledger()['heat_error_j']),1e-6) + def test24_settling_and_deaggregation(self): + h=build();h.plant['settling_factor']=1.;h.agg=.5;total=h.read()['truth.solid_kg'];h.invoke('acquisition.start');h.step(5.);self.assertGreater(h.settled.sum(),0);self.assertLess(h.agg,.5);self.assertAlmostEqual(h.read()['truth.solid_kg'],total,places=12) + def test25_clock_partition(self): + a=build();b=copy.deepcopy(a);a.invoke('acquisition.start');b.invoke('acquisition.start');a.step(2.3) + for _ in range(230):b.step(.01) + self.assertEqual(a.read(),b.read());np.testing.assert_allclose(a.wet,b.wet) + def test26_template_rejection(self): + for sid,cross,trunc in [('powder_050',True,True),('powder_057',True,True),('powder_001',False,True)]: + with self.assertRaises(r.ActionRejected):r.template(sid,cross,trunc,'wet') + v,_,e,_=r.template('powder_001',True,True,'wet');self.assertEqual(len(v),110);self.assertIn('assumed',e) + def test27_timeout_and_unsupported(self): + h=build();h.invoke('method.configure',**dict(h.method,timeout_s=1.));h.invoke('acquisition.start');h.step(2.);self.assertEqual(h.error,'TIMEOUT') + for k in r.UNSUPPORTED: + with self.assertRaisesRegex(r.ActionRejected,'UNSUPPORTED'):h.invoke(k) + def test28_no_implicit_temperature_sensor(self): + h=build();a=h.session();obs=a.read(instance_id=h.instance_id)['observations'];self.assertNotIn('truth.temperature_k',obs);self.assertFalse(any('temperature' in k for k in obs)) + def test30_result_query_cannot_take_operation_ownership(self): + h=build();h.register_principal('observer');owner=h.session();observer=h.session('observer');op=owner.invoke(instance_id=h.instance_id,capability_id='acquisition.start',arguments={},request_id='owned')['operation_id'];h.step(.1);before=h._owners.copy() + queried=observer.invoke(instance_id=h.instance_id,capability_id='acquisition.result',arguments={},request_id='query');self.assertEqual(queried['status'],'succeeded');self.assertIsNone(queried['operation_id']);self.assertEqual(queried['result']['operation_id'],op);self.assertEqual(h._owners,before) + with self.assertRaisesRegex(r.ActionRejected,'ACCESS_DENIED'):observer.cancel(op,'unauthorized') + self.assertEqual(owner.cancel(op,'owner_cancel')['status'],'succeeded');self.assertEqual(owner.poll(op)['status'],'cancelled') + def test31_result_source_belongs_to_acquisition(self): + h=self.done(build('dry'));original=h.invoke('acquisition.result');h.invoke('method.configure',**dict(h.method,regularization=.0002));self.assertEqual(original,h.invoke('acquisition.result'));h.invoke('power.set',enabled=False);h.invoke('dry_hood.set',lift_m=.2);h.invoke('sample.recover') + h.invoke('sample.load',**dict(r.SAMPLE_EXAMPLE,substance_id='powder_001',mass_kg=.03,true_density_kg_m3=1000.,accept_cross_method=True,accept_range_truncation=True));self.assertNotEqual(original['template_source'],h.source);self.assertEqual(original,h.invoke('acquisition.result')) + h.invoke('dry_hood.set',lift_m=0.);h.invoke('power.set',enabled=True);h.step(60.);h.invoke('acquisition.start');self.assertEqual(h.invoke('acquisition.result')['template_source'],h.source) + def test32_metadata_covers_actual_state_changes(self): + metadata=r.export_antonpaar_psa1190_contract_metadata();original=r.AntonpaarPsa1190Runtime.invoke;observed=set() + def audited_invoke(h,cap,**arguments): + before=h.read();result=original(h,cap,**arguments);after=h.read();changed={state for state in before if before[state]!=after[state]};declared={effect['state_id'] for effect in metadata['capabilities'][cap]['state_effects'] if effect['timing']=='immediate'} + self.assertFalse(changed-declared,(cap,changed-declared));observed.add(cap);return result + with mock.patch.object(r.AntonpaarPsa1190Runtime,'invoke',audited_invoke): + h=build();h.invoke('acquisition.start');h.invoke('sim.step',dt_s=15.1);h.invoke('calibration.size',reference_m=50e-6,observed_m=40e-6);h.invoke('liquid.drain');h.invoke('sim.step',dt_s=23.);h.invoke('tank_lid.set',slide_m=.17);h.invoke('liquid.fill',volume_m3=.00045);h.invoke('tank_lid.set',slide_m=0.);h.invoke('method.configure',**dict(h.method,medium_n=1.34));h.invoke('background.start');h.invoke('sim.step',dt_s=60.) + d=build('dry');d.invoke('acquisition.start');d.invoke('sim.step',dt_s=2.);d.invoke('acquisition.stop');d.invoke('power.set',enabled=False);d.invoke('dry_hood.set',lift_m=.2);d.invoke('sample.recover');d.invoke('sample.load',**dict(r.SAMPLE_EXAMPLE,mass_kg=.03,agglomerated_fraction=.5)) + q=r.AntonpaarPsa1190Runtime();q.invoke('plant.configure',**dict(r.PLANT_EXAMPLE,ambient_k=298.15));d.invoke('dry_hood.set',lift_m=0.);d.invoke('power.set',enabled=True);d.invoke('sim.step',dt_s=60.);d.invoke('acquisition.start');d.invoke('power.set',enabled=False) + self.assertTrue(set(r.IMMEDIATE_EFFECTS)<=observed) + def test33_recovery_mass_requires_evaluator(self): + h=build('dry');h.invoke('power.set',enabled=False);h.invoke('dry_hood.set',lift_m=.2);agent=h.session();evaluator=h.session('evaluator');self.assertNotIn('sample.recover',agent.describe(instance_id=h.instance_id)['capabilities']);before=pickle.dumps(h.__dict__) + denied=agent.invoke(instance_id=h.instance_id,capability_id='sample.recover',arguments={},request_id='deny_truth');self.assertEqual(denied['error']['code'],'ACCESS_DENIED');self.assertEqual(before,pickle.dumps(h.__dict__));recovered=evaluator.invoke(instance_id=h.instance_id,capability_id='sample.recover',arguments={},request_id='recover');self.assertEqual(recovered['status'],'succeeded');self.assertAlmostEqual(recovered['result']['returned_mass_kg'],.03);self.assertLess(abs(h._ledger()['solid_error_kg']),1e-12) +if __name__=='__main__':unittest.main() diff --git a/tests/test_asset_antonpaar_surpass3.py b/tests/test_asset_antonpaar_surpass3.py new file mode 100644 index 0000000000000000000000000000000000000000..91f658f81a3c018083eb6551be5a05874c1272cc --- /dev/null +++ b/tests/test_asset_antonpaar_surpass3.py @@ -0,0 +1,76 @@ +import unittest,copy,math,importlib.util,json +from scripts.asset_runtime import antonpaar_surpass3 as r +spec=importlib.util.spec_from_file_location('asset_tool',r.ROOT/'skills/chemistry-lab-assets/scripts/asset_tool.py');tool=importlib.util.module_from_spec(spec);spec.loader.exec_module(tool);OBSERVED=set() +def call(h,k,a=None): + v=h.invoke(k,**(a or {}));tool.validate_value(v,r.CAPS[k][1]);OBSERVED.add(k);return v +def setup(plant=None,method=None,liquid=None,sample=None): + h=r.AntonpaarSurpass3Runtime() + for k,a in [('plant.configure',dict(r.PLANT_EXAMPLE,**(plant or {}))),('method.configure',dict(r.METHOD_EXAMPLE,**(method or {}))),('lock.set',{'angle_rad':0.}),('cell.set',{'withdrawal_m':.095}),('sample.load',dict(r.SAMPLE_EXAMPLE,**(sample or {}))),('cell.set',{'withdrawal_m':0.}),('lock.set',{'angle_rad':1.2}),('gap.set',{'height_m':.0001}),('lid.set',{'lift_m':.105}),('electrolyte.load',dict(r.LIQUID_EXAMPLE,**(liquid or {}))),('lid.set',{'lift_m':0.}),('ph.calibrate',r.PHCAL_EXAMPLE),('conductivity.calibrate',r.COND_EXAMPLE),('power.set',{'enabled':True})]:call(h,k,a) + return h +def finish(h): + if h.phase!='running':call(h,'acquisition.start') + for _ in range(1800): + h.step(1.) + if h.phase!='running':break + return h +class Tests(unittest.TestCase): + def ledger(self,h): + l=call(h,'ledger.read') + for k in ['volume_residual_m3','k_residual_mol','cl_residual_mol','electroneutral_residual_mol','titrant_residual_m3','gas_mole_residual']:self.assertLess(abs(l[k]),1e-13,k) + self.assertLess(abs(l['work_residual_j']),1e-10);self.assertGreaterEqual(h.V-sum(h.chamber),-1e-15) + def test_01_original_references(self): + h=setup();self.assertEqual(len(h.library['substances']),70);self.assertAlmostEqual(call(h,'template.reference',{'substance_id':'nanomile_2'})['zeta_v'],-.00121);self.assertFalse(call(h,'template.reference',{'substance_id':'nanomile_2'})['applicable_to_surpass']);self.assertEqual(call(h,'template.reference',{'substance_id':'cotton_agcl'})['zeta_v'],-.019) + with self.assertRaisesRegex(r.ActionRejected,'PARTICLE_REFERENCE_ONLY'):setup(sample={'reference_id':'nanomile_2'}) + def test_02_complete_ols_and_iep(self): + h=finish(setup());self.assertEqual(h.phase,'succeeded');self.assertEqual(len(h.fits),16);self.assertAlmostEqual(h._iep(),4.1,places=6) + for f in h.fits: + expected=-.019-.01*(f['ph']-6);self.assertAlmostEqual(f['zeta_from_i_v'],expected,places=10);self.assertAlmostEqual(f['zeta_from_v_v'],expected,places=10);self.assertGreater(f['r2_i'],.999999) + self.ledger(h);self.assertEqual({x['direction'] for x in call(h,'process.measure')['trace']},{1,-1}) + def test_03_surface_conduction_bias(self): + h=finish(setup(plant={'surface_conductance_s':1e-6},method={'ph_targets':[6.],'cycles':1}));f=h.fits[0];self.assertAlmostEqual(f['zeta_from_i_v'],-.019,places=12);self.assertLess(abs(f['zeta_from_v_v']),abs(f['zeta_from_i_v']));self.ledger(h) + def test_04_ideal_chemistry_titration(self): + h=finish(setup(method={'ph_targets':[4.,8.,5.],'cycles':1}));self.assertEqual(h.phase,'succeeded');self.assertGreater(h.added[0],0);self.assertGreater(h.added[1],0);self.assertAlmostEqual(h.chemistry()[0],5.,places=6);self.ledger(h) + def test_05_independent_pressure_work(self): + h=setup(method={'ph_targets':[6.],'cycles':1});call(h,'acquisition.start');h.step(1.);self.assertEqual(h.stage,'ramp');self.ledger(h);p=h.plant;pv=(h.method['start_pressure_pa']+p['ambient_pa'])*p['gas_volume_m3'];expected=pv*math.log((p['gas_volume_m3']+h.moved)/p['gas_volume_m3'])-p['ambient_pa']*h.moved;self.assertAlmostEqual(h.work,expected,places=10);self.assertAlmostEqual(h.gas_n,(h.pressure+p['ambient_pa'])*(h.gas_v+h.moved)/8.314462618/p['temperature_k'],places=12) + def test_06_cancel_partial_dose_and_poweroff(self): + h=setup(method={'ph_targets':[3.],'cycles':1});call(h,'acquisition.start');h.step(30.);self.assertGreater(h.added[0],0);call(h,'acquisition.stop');before=[h.V,h.nk,h.ncl];h.step(20);self.assertEqual(before,[h.V,h.nk,h.ncl]);self.assertEqual(h.phase,'cancelled');self.ledger(h) + h=setup(method={'ph_targets':[6.],'cycles':1});call(h,'acquisition.start');h.step(1);call(h,'power.set',{'enabled':False});self.assertEqual(h.phase,'cancelled');self.assertEqual(h.pressure,0);self.ledger(h) + def test_07_stock_depletion(self): + h=finish(setup(method={'ph_targets':[3.],'cycles':1},liquid={'acid_stock_m3':1e-7}));self.assertEqual(h.failure,'TITRANT_DEPLETED');self.assertGreater(h.added[0],0);self.ledger(h) + def test_08_capacity_failure(self): + h=finish(setup(method={'ph_targets':[3.],'cycles':1},liquid={'volume_m3':.00025}));self.assertEqual(h.failure,'BEAKER_CAPACITY');self.ledger(h) + def test_09_blocked_pressure_timeout(self): + h=finish(setup(plant={'blocked_fraction':1.},method={'ph_targets':[6.],'cycles':1,'ramp_timeout_s':10.}));self.assertEqual(h.failure,'PRESSURE_TIMEOUT');self.assertEqual(h.circulated,0);self.assertTrue(all(x['streaming_a']==0 for x in h.trace));self.ledger(h) + def test_10_chamber_empty_failure(self): + h=finish(setup(plant={'gas_volume_m3':1e-4},method={'ph_targets':[6.],'cycles':1,'fill_volume_m3':2e-5}));self.assertEqual(h.failure,'CHAMBER_EMPTY');self.ledger(h) + def test_11_read_pure_isolation_partition(self): + a=setup();b=copy.deepcopy(a);call(a,'acquisition.start');call(b,'acquisition.start');a.step(7.3) + for _ in range(73):b.step(.1) + self.assertEqual(a.read('evaluator'),b.read('evaluator'));old=a.read('evaluator');call(a,'process.measure');a.describe();call(a,'ledger.read');self.assertEqual(a.read('evaluator'),old);c=setup();self.assertEqual(c.time_s,0) + def test_12_invalid_atomic_interlocks(self): + h=setup();old=h.read('evaluator') + for k,a in [('cell.set',{'withdrawal_m':.09}),('method.configure',dict(r.METHOD_EXAMPLE,start_pressure_pa=20000.,stop_pressure_pa=30000.)),('gap.set',{'height_m':.0001005}),('power.set',{'enabled':1}),('ph.calibrate',{'buffer_ph':[4.,4.],'measured_v':[-.2,-.2]})]: + with self.assertRaises(r.ActionRejected):call(h,k,a) + self.assertEqual(h.read('evaluator'),old) + call(h,'acquisition.start') + with self.assertRaisesRegex(r.ActionRejected,'BUSY'):call(h,'lid.set',{'lift_m':.1}) + def test_13_calibration_bias_correction(self): + h=setup(plant={'ph_slope_v':-.06,'ph_offset_v':.01,'conductivity_gain':1.08},method={'ph_targets':[6.],'cycles':1});call(h,'ph.calibrate',{'buffer_ph':[4.,7.],'measured_v':[-.23,-.41]});call(h,'conductivity.calibrate',{'reference_s_m':.1413,'indicated_s_m':.1413*1.08});self.assertAlmostEqual(h.indicated()[0],6.,places=8);self.assertAlmostEqual(h.indicated()[1],h.chemistry()[1],places=12);h=finish(h);self.assertAlmostEqual(h.fits[0]['zeta_from_v_v'],-.019,places=10) + def test_14_no_unbracketed_iep_and_rinse(self): + h=finish(setup(method={'ph_targets':[6.,7.],'cycles':1}));self.assertIsNone(h._iep());h=finish(setup(method={'ph_targets':[6.],'cycles':1,'mode':'rinse'}));self.assertEqual(h.phase,'succeeded');self.assertFalse(h.fits);self.assertGreater(h.circulated,0);self.ledger(h) + def test_15_drain_and_sample_unload(self): + h=finish(setup(method={'ph_targets':[6.],'cycles':1}));call(h,'lid.set',{'lift_m':.105});v=call(h,'electrolyte.drain');self.assertGreater(v['volume_m3'],0);self.assertEqual(call(h,'electrolyte.drain')['volume_m3'],0);call(h,'lock.set',{'angle_rad':0.});call(h,'cell.set',{'withdrawal_m':.095});call(h,'sample.unload');self.assertFalse(h.sample);self.ledger(h) + def test_16_electrical_limits_and_sensor_offsets(self): + h=finish(setup(plant={'voltage_gain':1.3,'current_gain':.8,'voltage_offset_v':.01,'current_offset_a':1e-7},method={'ph_targets':[6.],'cycles':1}));self.assertAlmostEqual(h.fits[0]['zeta_from_v_v'],-.019*1.3,places=10);self.assertAlmostEqual(h.fits[0]['zeta_from_i_v'],-.019*.8,places=10) + h=finish(setup(method={'ph_targets':[8.],'cycles':1},liquid={'kcl_mol_m3':.01},sample={'ph_slope_v':-.05}));self.assertEqual(h.failure,'ELECTRICAL_RANGE');self.ledger(h) + def test_17_gap_flow_and_tubing(self): + a=setup(method={'ph_targets':[6.],'cycles':1});b=setup(plant={'extra_resistance_pa_s_m3':5e10},method={'ph_targets':[6.],'cycles':1});call(a,'acquisition.start');call(b,'acquisition.start');a.step(1.);b.step(1.);self.assertGreater(a.circulated,b.circulated);self.assertLess(b.cell_pressure,b.pressure);finish(b);self.assertEqual(b.phase,'succeeded');self.assertAlmostEqual(b.fits[0]['zeta_from_i_v'],-.019,places=12) + def test_18_permissions_dedup_schema(self): + h=setup();h.register_principal('a');h.register_principal('b');h.register_principal('eval','evaluator');s=h.session('a');q=h.session('b');self.assertNotIn('sample.identity',s.read(instance_id=h.instance_id)['observations']);self.assertNotIn('sample.load',s.describe(instance_id=h.instance_id)['capabilities']);args=dict(instance_id=h.instance_id,capability_id='acquisition.start',arguments={},request_id='start');v=s.invoke(**args);self.assertEqual(v,s.invoke(**args));self.assertEqual(s.invoke(**dict(args,capability_id='acquisition.stop'))['error']['code'],'REQUEST_CONFLICT') + with self.assertRaises(r.ActionRejected):q.poll(v['operation_id']) + self.assertEqual(s.cancel(v['operation_id'],'cancel')['status'],'succeeded');self.assertEqual(s.poll(v['operation_id'])['status'],'cancelled');self.assertEqual(s.invoke(instance_id=h.instance_id,capability_id='ledger.read',arguments={},request_id='forbidden')['error']['code'],'ACCESS_DENIED') + for k in r.UNSUPPORTED: + with self.assertRaisesRegex(r.ActionRejected,'UNSUPPORTED'):h.invoke(k) + for dt in [True,-1,float('nan'),float('inf')]: + with self.assertRaises(r.ActionRejected):h.step(dt) +if __name__=='__main__':unittest.main() diff --git a/tests/test_asset_antonpaar_ultrapyc5000.py b/tests/test_asset_antonpaar_ultrapyc5000.py new file mode 100644 index 0000000000000000000000000000000000000000..49dd53f271b78b8481178597a507d27402e3dfd1 --- /dev/null +++ b/tests/test_asset_antonpaar_ultrapyc5000.py @@ -0,0 +1,113 @@ +import unittest,copy,math,importlib.util,statistics,json +from scripts.asset_runtime import antonpaar_ultrapyc5000 as r +spec=importlib.util.spec_from_file_location('asset_tool',r.ROOT/'skills/chemistry-lab-assets/scripts/asset_tool.py');tool=importlib.util.module_from_spec(spec);spec.loader.exec_module(tool);OBSERVED=set() +def call(h,k,a=None): + v=h.invoke(k,**(a or {}));tool.validate_value(v,r.CAPS[k][1]);OBSERVED.add(k);return v +def open_cup(h): + for k,a in [('seal.set',{'angle_rad':0.}),('lock.set',{'angle_rad':0.}),('lid.set',{'lift_m':.13}),('cup.set',{'lift_m':.12})]:call(h,k,a) +def close_cup(h): + for k,a in [('cup.set',{'lift_m':0.}),('lid.set',{'lift_m':0.}),('lock.set',{'angle_rad':1.1}),('seal.set',{'angle_rad':1.4})]:call(h,k,a) +def calibrate(h): + c=r.CELLS[h.method['cell']];v=8e-6 if h.method['reference']=='small' or (h.method['reference']=='auto' and c<=10e-6) else 50e-6;s=c*.2 + a=dict(blank_ratio=c/v,sphere_ratio=(c-s)/v,sphere_volume_m3=s) if h.method['direction']=='powder_protect' else dict(blank_ratio=v/c,sphere_ratio=v/(c-s),sphere_volume_m3=s);return call(h,'volume.calibrate',a) +def setup(plant=None,method=None,sample=None,load=True): + h=r.AntonpaarUltrapyc5000Runtime();call(h,'plant.configure',dict(r.PLANT_EXAMPLE,**(plant or {})));call(h,'method.configure',dict(r.METHOD_EXAMPLE,**(method or {})));calibrate(h) + if load:open_cup(h);call(h,'sample.load',dict(r.SAMPLE_EXAMPLE,**(sample or {})));call(h,'sample.set_mass',{'mass_kg':h.sample['true_mass_kg']});close_cup(h) + call(h,'power.set',{'enabled':True});return h +def finish(h,limit=1800): + if h.phase!='running':call(h,'acquisition.start') + for _ in range(limit): + h.step(1.) + if h.phase!='running':break + return h +def until(h,stage,limit=1000): + if h.phase!='running':call(h,'acquisition.start') + for _ in range(limit*10): + if h.stage==stage:return + if h.phase!='running':raise AssertionError((h.phase,h.stage,h.failure)) + h.step(.1) + raise AssertionError((stage,h.stage,h.failure)) +class Tests(unittest.TestCase): + def ledger(self,h): + x=call(h,'ledger.read');self.assertLess(max(abs(v) for v in x['species_residual_mol']),1e-12);self.assertLess(abs(x['sample_residual_kg']),1e-12);self.assertLess(abs(x['energy_residual_j']),max(1e-8,2e-11*abs(h.energy())));self.assertGreaterEqual(x['source_mol'],0.) + def test_01_real_reference_provenance(self): + h=setup();self.assertEqual(len(h.library['substances']),73);a=call(h,'template.reference',{'substance_id':'nist_al'});self.assertEqual(a['density_kg_m3'],2699.);self.assertEqual(a['evidence'],'assumption');self.assertEqual(call(h,'template.reference',{'substance_id':'measured_cu'})['evidence'],'measured_literature');self.assertEqual(call(h,'template.reference',{'substance_id':'measured_174ph'})['density_kg_m3'],7780.) + self.assertTrue(all(v['conditions']['temperature_k'] is None for v in h.library['substances'].values()));self.assertNotIn('nist_hg',h.library['substances']);self.assertNotIn('nist_at',h.library['substances']) + def test_02_both_directions_pressure_inversion(self): + for d in ['sample_first','powder_protect']: + h=finish(setup(method={'direction':d}));self.assertEqual(h.phase,'succeeded',h.failure);res=call(h,'process.measure');self.assertEqual(len(res['runs']),3);self.assertAlmostEqual(res['mean_density_kg_m3'],2699.,delta=.02);self.assertAlmostEqual(res['mean_volume_m3'],.05/2699.,delta=2e-10);self.ledger(h) + self.assertAlmostEqual(res['standard_deviation_m3'],statistics.stdev(v['volume_m3'] for v in res['runs']),places=15) + def test_03_closed_and_open_pores(self): + a=finish(setup(sample={'open_pore_m3':0.}));b=finish(setup(sample={'open_pore_m3':20e-6}));c=finish(setup(sample={'closed_pore_m3':3e-6}));self.assertAlmostEqual(a._stats()[0],b._stats()[0],places=13);self.assertAlmostEqual(c._stats()[0]-a._stats()[0],3e-6,delta=2e-10);self.assertLess(c._stats()[1],a._stats()[1]);self.ledger(c) + def test_04_entered_mass_not_truth(self): + h=setup();call(h,'sample.set_mass',{'mass_kg':.055});finish(h);self.assertEqual(h.sample['true_mass_kg'],.05);self.assertAlmostEqual(h._stats()[1],2699.*1.1,delta=.03);self.ledger(h) + def test_05_two_actual_pressure_runs_calibration(self): + for d in ['sample_first','powder_protect']: + h=setup(plant={'cell_volume_factor':1.01,'reference_volume_factor':.99},method={'mode':'calibration','direction':d,'max_runs':1,'runs_to_average':1},load=False);finish(h);blank=h.runs[0]['ratio'];h.step(20);open_cup(h);call(h,'sample.load',dict(r.SAMPLE_EXAMPLE,true_mass_kg=.02699,open_pore_m3=0.));close_cup(h);finish(h);sphere=h.runs[0]['ratio'];v=call(h,'volume.calibrate',dict(blank_ratio=blank,sphere_ratio=sphere,sphere_volume_m3=1e-5));self.assertAlmostEqual(v['cell_volume_m3'],50.5e-6,delta=2e-10);self.assertAlmostEqual(v['reference_volume_m3'],49.5e-6,delta=2e-10) + call(h,'method.configure',dict(h.method,mode='measure'));call(h,'sample.set_mass',{'mass_kg':.02699});finish(h);self.assertAlmostEqual(h._stats()[1],2699.,delta=.1);self.ledger(h) + def test_06_pressure_gain_offset_calibration(self): + h=setup(plant={'pressure_gain':[1.03,.98],'pressure_offset_pa':[100.,-70.]});call(h,'pressure.calibrate',dict(reference_pa=[101325.,201325.],sample_measured_pa=[101325.*1.03+100.,201325.*1.03+100.],reference_measured_pa=[101325.*.98-70.,201325.*.98-70.]));calibrate(h);finish(h);self.assertAlmostEqual(h._stats()[1],2699.,delta=.03);self.ledger(h) + def test_07_flow_purge_exact_residual(self): + h=setup(method={'preparation':'flow','preparation_s':60.});until(h,'flow');old=h.ns[1]+h.nr[1];total=sum(h.ns)+sum(h.nr);h.step(1.);dn=h.method['flow_m3_s']*101325./r.R/273.15;self.assertAlmostEqual(h.ns[1]+h.nr[1],old*math.exp(-dn/total),places=12);self.assertGreater(h.source_initial-h.source,0.);finish(h);self.assertEqual(h.phase,'succeeded',h.failure);self.ledger(h) + def test_08_pulse_preparation(self): + h=finish(setup(method={'preparation':'pulse','purge_pulses':3}));self.assertEqual(h.pulses,3);self.assertEqual(h.phase,'succeeded',h.failure);self.assertAlmostEqual(h._stats()[1],2699.,delta=.03);self.ledger(h) + def test_09_vacuum_and_missing_pump(self): + h=finish(setup(method={'preparation':'vacuum','preparation_s':60.}));self.assertEqual(h.phase,'succeeded',h.failure);self.assertGreater(sum(h.evacuated),0);self.ledger(h) + h=setup(plant={'pump_available':False},method={'preparation':'vacuum','preparation_s':60.});old=h.read('evaluator') + with self.assertRaisesRegex(r.ActionRejected,'PUMP_UNAVAILABLE'):call(h,'acquisition.start') + self.assertEqual(old,h.read('evaluator')) + def test_10_finite_gas_depletion(self): + h=finish(setup(plant={'source_volume_m3':1e-5}));self.assertEqual(h.phase,'failed');self.assertEqual(h.failure,'GAS_DEPLETED');self.assertGreater(h.source_initial-h.source,0);self.ledger(h) + def test_11_leak_observation_is_not_random_fault(self): + good=finish(setup(method={'mode':'leak'},load=False));bad=finish(setup(plant={'leak_conductance_mol_s_pa':1e-11},method={'mode':'leak'},load=False));self.assertEqual(good.phase,'succeeded');self.assertEqual(bad.phase,'succeeded',bad.failure);self.assertTrue(good.leak_pass);self.assertFalse(bad.leak_pass);self.assertGreater(bad.leak_rate,1.);self.ledger(bad) + def test_12_setpoint_energy_cooling_and_heating(self): + h=setup(load=False);t=h.temp;call(h,'thermal.set_temperature',{'temperature_k':276.15});self.assertEqual(h.temp,t);h.step(3600);self.assertAlmostEqual(h.temp,276.15,delta=.02);self.ledger(h);call(h,'thermal.set_temperature',{'temperature_k':323.15});h.step(7200);self.assertAlmostEqual(h.temp,323.15,delta=.02);self.ledger(h) + def test_13_partial_cancel_and_poweroff_vent(self): + h=setup();until(h,'expand');consumed=h.source_initial-h.source;peak=max(h.pressure(0),h.pressure(1));call(h,'acquisition.stop');self.assertEqual(h.phase,'cancelled');self.assertEqual(h.source_initial-h.source,consumed);self.assertGreater(peak,h.plant['ambient_pa']+1000);h.step(30.);self.assertLess(max(h.pressure(0),h.pressure(1)),peak);self.assertEqual(h.sample['true_mass_kg'],.05);self.ledger(h) + h=setup();until(h,'expand');call(h,'power.set',{'enabled':False});self.assertEqual(h.phase,'cancelled');h.step(30.);self.assertEqual(h.power_w,0);self.ledger(h) + def test_14_pure_reads_partition_and_instances(self): + a=setup();b=copy.deepcopy(a);call(a,'acquisition.start');call(b,'acquisition.start');a.step(7.3) + for _ in range(73):b.step(.1) + self.assertEqual(a.read('evaluator'),b.read('evaluator'));old=a.read('evaluator');call(a,'process.measure');call(a,'ledger.read');a.describe();self.assertEqual(a.read('evaluator'),old);self.assertEqual(setup().time_s,0.) + def test_15_atomic_mechanical_sequence(self): + h=setup();old=h.read('evaluator') + for k,a in [('lock.set',{'angle_rad':0.}),('lid.set',{'lift_m':.13}),('cup.set',{'lift_m':.12}),('power.set',{'enabled':1}),('volume.calibrate',dict(r.CAL_EXAMPLE,sphere_ratio=2.)),('method.configure',dict(r.METHOD_EXAMPLE,max_runs=1,runs_to_average=3))]: + with self.assertRaises(r.ActionRejected):call(h,k,a) + self.assertEqual(old,h.read('evaluator')) + until(h,'expand') + with self.assertRaisesRegex(r.ActionRejected,'BUSY'):call(h,'lid.set',{'lift_m':.13}) + call(h,'acquisition.stop') + with self.assertRaisesRegex(r.ActionRejected,'PRESSURE_INTERLOCK'):call(h,'seal.set',{'angle_rad':0.}) + def test_16_capacity_and_nominal_optin(self): + for sample in [{'true_mass_kg':.5},{'accept_reference_transfer':False},{'reference_id':'invalid_secret'}]: + h=setup(load=False);open_cup(h);old=copy.deepcopy(h.read('evaluator')) + with self.assertRaises(r.ActionRejected):call(h,'sample.load',dict(r.SAMPLE_EXAMPLE,**sample)) + self.assertEqual(old,h.read('evaluator'));self.ledger(h) + def test_17_six_semantic_cells_and_dual_references(self): + for key,v in r.CELLS.items(): + h=finish(setup(method={'cell':key,'max_runs':1,'runs_to_average':1},sample={'true_mass_kg':2699.*v*.4,'open_pore_m3':v*.1}));self.assertEqual(h.phase,'succeeded',(key,h.failure));self.assertAlmostEqual(h._stats()[1],2699.,delta=.05);self.assertAlmostEqual(h.ref,8e-6 if v<=10e-6 else 50e-6);self.ledger(h) + def test_18_automatic_and_declared_thermal_expansion(self): + h=setup(method={'max_runs':8,'runs_to_average':3,'automatic':True},sample={'reference_temperature_k':288.15,'volume_expansion_per_k':.0001});finish(h);self.assertEqual(len(h.runs),3);self.assertAlmostEqual(h._stats()[1],2699./1.001,delta=.06);self.ledger(h) + def test_19_permission_dedup_poll_and_schemas(self): + h=setup();h.register_principal('a');h.register_principal('b');h.register_principal('e','evaluator');s=h.session('a');q=h.session('b');self.assertNotIn('sample.identity',s.read(instance_id=h.instance_id)['observations']);self.assertNotIn('sample.load',s.describe(instance_id=h.instance_id)['capabilities']);args=dict(instance_id=h.instance_id,capability_id='acquisition.start',arguments={},request_id='start');v=s.invoke(**args);self.assertEqual(v,s.invoke(**args));self.assertEqual(s.invoke(**dict(args,capability_id='acquisition.stop'))['error']['code'],'REQUEST_CONFLICT') + with self.assertRaises(r.ActionRejected):q.poll(v['operation_id']) + self.assertEqual(s.cancel(v['operation_id'],'cancel')['status'],'succeeded');self.assertEqual(s.poll(v['operation_id'])['status'],'cancelled');self.assertEqual(s.invoke(instance_id=h.instance_id,capability_id='ledger.read',arguments={},request_id='deny')['error']['code'],'ACCESS_DENIED');self.assertNotIn('private_al_powder',json.dumps(s.poll(v['operation_id']))) + for k in r.UNSUPPORTED: + with self.assertRaisesRegex(r.ActionRejected,'UNSUPPORTED'):h.invoke(k) + for dt in [True,-1,float('nan'),float('inf')]: + with self.assertRaises(r.ActionRejected):h.step(dt) + def test_20_unload_mass_and_home_release(self): + h=finish(setup());h.step(30.);open_cup(h);self.assertEqual(call(h,'sample.unload')['returned_mass_kg'],.05);self.assertFalse(h.sample);self.ledger(h);self.assertEqual(call(h,'panel.home')['page'],'home');self.assertEqual(h.home,.0015);h.step(.1);self.assertEqual(h.home,.0015);h.step(.1);self.assertEqual(h.home,0.);call(h,'power.set',{'enabled':False});self.assertEqual(h.read()['display.pressure_text'],'') + def test_21_three_inert_gases(self): + for gas in ['He','N2','Ar']: + h=finish(setup(plant={'source_gas':gas},method={'max_runs':1,'runs_to_average':1}));self.assertEqual(h.phase,'succeeded');self.assertAlmostEqual(h._stats()[1],2699.,delta=.03);self.ledger(h) + def test_22_blocked_valve_timeout(self): + h=finish(setup(plant={'connect_conductance_mol_s_pa':1e-11},method={'stage_timeout_s':30.}));self.assertEqual(h.phase,'failed');self.assertEqual(h.failure,'STAGE_TIMEOUT');self.ledger(h) + def test_23_reconfigure_does_not_implicitly_vent(self): + h=setup();until(h,'expand');call(h,'acquisition.stop');before=[h.ns.copy(),h.nr.copy(),h.source];call(h,'method.configure',dict(h.method,direction='sample_first'));self.assertEqual(before,[h.ns,h.nr,h.source]);self.assertIsNone(h.cal_volume);self.ledger(h) + empty=setup(load=False) + with self.assertRaisesRegex(r.ActionRejected,'INSERT_ACCESS'):call(empty,'method.configure',dict(empty.method,cell='small')) + open_cup(empty);call(empty,'method.configure',dict(empty.method,cell='small'));self.assertEqual(empty.cell,10e-6);self.ledger(empty) + def test_24_completed_result_keeps_run_mass(self): + h=finish(setup());old=call(h,'process.measure')['mean_density_kg_m3'];call(h,'sample.set_mass',{'mass_kg':.07});self.assertEqual(call(h,'process.measure')['mean_density_kg_m3'],old);h.step(30.);open_cup(h);call(h,'sample.unload');self.assertEqual(call(h,'process.measure')['mean_density_kg_m3'],old) +if __name__=='__main__':unittest.main() diff --git a/tests/test_asset_applied_sx20.py b/tests/test_asset_applied_sx20.py new file mode 100644 index 0000000000000000000000000000000000000000..b693b97111d27677246ab374d8e281c8b212c2f9 --- /dev/null +++ b/tests/test_asset_applied_sx20.py @@ -0,0 +1,203 @@ +import copy,json,math,sys,unittest +from pathlib import Path +import numpy as np +from scipy.linalg import expm +ROOT=Path(__file__).resolve().parents[1];sys.path.insert(0,str(ROOT/'scripts')) +from asset_runtime.applied_sx20 import * +def ready(plant=None,sample=None,method=None): + r=AppliedSx20Runtime();r.invoke('plant.configure',**(plant or PLANT_EXAMPLE));r.invoke('sample.load',**(sample or SAMPLE_EXAMPLE));r.invoke('method.configure',**(method or METHOD_EXAMPLE)) + for k,a in [('bath.cover',{'opened':False}),('valves.set',{'drive':True}),('gas.set',{'enabled':True}),('power.set',{'enabled':True})]:r.invoke(k,**a) + return r +def flush(r): + r.invoke('gas.set',enabled=False);r.invoke('bath.cover',opened=True);r.invoke('valves.set',drive=False);r.invoke('fluid.flush');r.invoke('valves.set',drive=True);r.invoke('bath.cover',opened=False);r.invoke('gas.set',enabled=True) +class TestSx20(unittest.TestCase): + def assertReject(self,r,k,args,code): + before=r.debug_snapshot() + with self.assertRaisesRegex(ActionRejected,code):r.invoke(k,**args) + self.assertEqual(before,r.debug_snapshot()) + def test_01_references(self): + t=_templates() if '_templates' in globals() else AppliedSx20Runtime().templates + self.assertEqual(len(t),63);self.assertEqual(len({q['name'] for q in t.values()}),63) + for q in t.values():self.assertIsNone(q['kinetic_constants_s_inv']);self.assertIsNone(q['measured_time_trace']) + def test_02_guard_ack(self): + r=AppliedSx20Runtime();self.assertReject(r,'plant.configure',dict(PLANT_EXAMPLE,accept_surrogate_model=False),'EVIDENCE_ACK') + def test_03_initialization_at_nonzero_clock(self): + r=AppliedSx20Runtime();r.step(.02);r.invoke('plant.configure',**PLANT_EXAMPLE);self.assertReject(r,'plant.configure',PLANT_EXAMPLE,'INITIALIZATION') + def test_04_guard_solvent(self): + r=AppliedSx20Runtime();r.invoke('plant.configure',**PLANT_EXAMPLE);self.assertReject(r,'sample.load',dict(SAMPLE_EXAMPLE,solvent='water'),'SOLVENT') + def test_05_guard_hypothetical_ack(self): + r=AppliedSx20Runtime();r.invoke('plant.configure',**PLANT_EXAMPLE);self.assertReject(r,'sample.load',dict(SAMPLE_EXAMPLE,accept_hypothetical_kinetics=False),'EVIDENCE_ACK') + def test_06_source_coverage(self): + r=ready(method=dict(METHOD_EXAMPLE,wavelength_m=850e-9));self.assertReject(r,'acquisition.start',{},'SOURCE_COVERAGE') + def test_07_physical_mixing_ratio(self): + r=ready();self.assertReject(r,'method.configure',dict(METHOD_EXAMPLE,mix_ratio_a_b=2),'PHYSICAL_RATIO') + def test_08_asymmetric_capacity(self): + for cap in [1e-6,.5e-6,.25e-6,.1e-6]: + ratio=round(2.5e-6/cap,10);r=ready(plant=dict(PLANT_EXAMPLE,drive_b_capacity_m3=cap),method=dict(METHOD_EXAMPLE,mix_ratio_a_b=ratio));r.invoke('acquisition.start');r.step(.03) + useda=2.5e-6-r._va;usedb=cap-r._vb;self.assertAlmostEqual(useda/usedb,ratio,places=9) + def test_09_standard_path(self): + r=ready();self.assertReject(r,'method.configure',dict(METHOD_EXAMPLE,path_m=.005),'POWER_OFF') + r.invoke('power.set',enabled=False);self.assertReject(r,'method.configure',dict(METHOD_EXAMPLE,path_m=.005),'CELL_PATH') + def test_10_rapid_option(self): + r=ready(plant=dict(PLANT_EXAMPLE,rapid_cell_installed=True),method=dict(METHOD_EXAMPLE,path_m=.005,stop_volume_m3=35e-9)) + self.assertEqual(r.cell_volume,5e-9);self.assertEqual(r.stop_capacity,1e-6);r.invoke('acquisition.start');r.step(1);self.assertEqual(r.points[0]['reaction_age_s'],.0005) + def test_11_no_early_observation(self): + r=ready();r.invoke('acquisition.start');r.step(.069);self.assertEqual(r.points,[]);r.step(.001);self.assertEqual(len(r.points),1);self.assertAlmostEqual(r.points[0]['sample_time_s'],.07);self.assertEqual(r.points[0]['reaction_age_s'],.001) + def test_12_delay_not_double_clock(self): + r=ready(method=dict(METHOD_EXAMPLE,delay_s=.005));r.invoke('acquisition.start');r.step(.074);self.assertEqual(r.points,[]);r.step(.001) + self.assertAlmostEqual(r.time_s,.075);self.assertAlmostEqual(r.points[0]['sample_time_s'],.075);self.assertAlmostEqual(r.points[0]['reaction_age_s'],.006) + def test_13_partition_invariance(self): + a=ready();b=ready() + for r in [a,b]:r.invoke('acquisition.start') + a.step(.7) + for _ in range(700):b.step(.001) + self.assertEqual(len(a.points),len(b.points));np.testing.assert_allclose([[p['signal'],p['sample_time_s']] for p in a.points],[[p['signal'],p['sample_time_s']] for p in b.points],rtol=1e-10,atol=1e-12) + np.testing.assert_allclose([a._va,a._nc,a._ns],[b._va,b._nc,b._ns],rtol=1e-10,atol=1e-20) + def test_14_conservation_partial_full(self): + r=ready();r.invoke('acquisition.start') + for dt in [.013,.027,.031,.5]: + r.step(dt);d=r.invoke('product.read');self.assertLess(abs(d['volume_residual_m3']),1e-19);self.assertLess(abs(d['moiety_residual_mol']),1e-21) + def test_15_cell_washout_exact(self): + r=ready();r.invoke('acquisition.start');r.step(.035);v=.035*PLANT_EXAMPLE['flow_m3_s'];cin=SAMPLE_EXAMPLE['stock_concentration_mol_m3']/2 + self.assertAlmostEqual(r._nc/(cin*20e-9),1-math.exp(-v/20e-9),places=12) + def test_16_cancel_retains_consumption(self): + r=ready();r.invoke('acquisition.start');r.step(.03);v=r._va;r.invoke('acquisition.stop');r.step(1);self.assertEqual(r._va,v);self.assertLess(v,2.5e-6);self.assertTrue(r.needs_flush);self.assertEqual(r.points,[]) + def test_17_cover_cancel(self): + r=ready();r.invoke('acquisition.start');r.step(.09);n=len(r.points);r.invoke('bath.cover',opened=True);r.step(1);self.assertEqual(len(r.points),n);self.assertFalse(r.gas);self.assertEqual(r.phase,'cancelled') + def test_18_power_cancel(self): + r=ready();r.invoke('acquisition.start');r.step(.08);r.invoke('power.set',enabled=False);self.assertEqual(r.phase,'cancelled') + def test_19_gas_cancel(self): + r=ready();r.invoke('acquisition.start');r.step(.03);r.invoke('gas.set',enabled=False);self.assertEqual(r.phase,'cancelled') + def test_20_new_start_needs_flush(self): + r=ready();r.invoke('acquisition.start');r.step(1);self.assertReject(r,'acquisition.start',{},'EXTERNAL_FLUSH') + def test_21_flush_and_autoempty(self): + r=ready();r.invoke('acquisition.start');r.step(1);oldstop=r._vs;oldn=r._ns;flush(r) + self.assertEqual(r._vs,oldstop);self.assertEqual(r._ns,oldn);self.assertEqual(r._nc,0);r.invoke('acquisition.start');self.assertEqual(r.stage,'returning');self.assertEqual(r.read()['stop.valve_angle_rad'],math.pi) + r.step(.02);self.assertLess(r._vs,oldstop);self.assertGreater(r._nw,0);r.step(1);self.assertEqual(r.phase,'succeeded');self.assertLess(abs(r._ledger()['moiety_residual_mol']),1e-21) + def test_22_equal_rates_exponential_oracle(self): + for k1,k2 in [(20,20),(20,20.000001),(40,8),(8,40)]: + for t in [0,.001,.04,1,1e3]: + actual=AppliedSx20Runtime.fractions(t,k1,k2);expected=expm(np.array([[-k1,0,0],[k1,-k2,0],[0,k2,0]],float)*t)@np.array([1.,0,0]);np.testing.assert_allclose(actual,expected,atol=5e-9,rtol=5e-7);self.assertAlmostEqual(sum(actual),1) + def test_23_intermediate_peak(self): + r=ready();r.invoke('acquisition.start');r.step(1);signals=[p['signal'] for p in r.points];self.assertGreater(max(signals),signals[0]);self.assertLess(signals[-1],signals[0]) + def test_24_absorbance_independent(self): + r=ready();r.invoke('acquisition.start');r.step(1);t=r.templates[SAMPLE_EXAMPLE['template_id']];epsilon=np.interp(482.5e-9,t['abs_wavelength_m'],t['epsilon_m2_mol']);p=r.points[20];f=expm(np.array([[-40.,0,0],[40.,-8.,0],[0,8.,0]])*p['reaction_age_s'])@np.array([1,0,0]);expected=epsilon*.001*(1-math.exp(-7))*.01*np.dot(f,[1,2,.15]);self.assertAlmostEqual(p['signal'],expected,places=11) + def test_25_fluor_filter_independent(self): + r=ready(method=FLUOR_METHOD);r.invoke('acquisition.start');r.step(1);t=r.templates['pcad_010'];x=np.array(t['em_wavelength_m']);y=np.maximum(t['emission_relative'],0);lo=505e-9;hi=535e-9;grid=np.r_[lo,x[(x>lo)&(x0)) + def test_30_noise_deterministic_partition(self): + a=ready(plant=dict(PLANT_EXAMPLE,abs_noise_sd=.001));b=ready(plant=dict(PLANT_EXAMPLE,abs_noise_sd=.001)) + for r in [a,b]:r.invoke('acquisition.start') + a.step(1) + for _ in range(100):b.step(.01) + np.testing.assert_allclose([p['signal'] for p in a.points],[p['signal'] for p in b.points],atol=1e-12) + def test_31_fit_only_observations(self): + r=AppliedSx20Runtime();x=np.linspace(0,1,60);y=.2+.7*np.exp(-7*x);before=r.debug_snapshot();o=r.invoke('kinetics.fit',time_s=x.tolist(),signal=y.tolist());self.assertAlmostEqual(o['k_s_inv'],7,places=6);self.assertLess(o['rmse'],1e-8);self.assertEqual(before,r.debug_snapshot()) + def test_32_fit_invalid(self): + r=ready();self.assertReject(r,'kinetics.fit',dict(time_s=[0]*6,signal=[1]*6),'ANALYSIS') + def test_33_blank_caller_value(self): + r=ready();r.invoke('calibration.zero',observed_blank=.02,mode='absorbance');self.assertEqual(r._correction['absorbance'],-.02) + def test_34_readonly_deepcopy(self): + r=ready();r.invoke('acquisition.start');r.step(1);snap=r.debug_snapshot();z=r.invoke('result.read');z['points'].clear();d=r.invoke('template.read',substance_id='pcad_010');d['epsilon_m2_mol'][0]=999;self.assertEqual(snap,r.debug_snapshot());self.assertNotEqual(r.templates['pcad_010']['epsilon_m2_mol'][0],999) + def test_35_acl(self): + r=ready();s=r.session();reply=s.invoke(instance_id=r.instance_id,capability_id='product.read',arguments={},request_id='secret');self.assertEqual(reply['error']['code'],'ACCESS_DENIED');self.assertNotIn('truth.ledger',s.describe(instance_id=r.instance_id)['state_slots']) + with self.assertRaisesRegex(ActionRejected,'ACCESS_DENIED'):s.read(instance_id=r.instance_id,state_ids=['truth.ledger']) + def test_36_request_dedup(self): + r=ready();s=r.session();args=dict(instance_id=r.instance_id,capability_id='acquisition.start',arguments={},request_id='one');a=s.invoke(**args);r.step(.01);v=r._va;b=s.invoke(**args);self.assertEqual(a,b);self.assertEqual(v,r._va) + args.update(capability_id='acquisition.stop');self.assertEqual(s.invoke(**args)['error']['code'],'REQUEST_CONFLICT') + def test_37_poll_owner_cancel(self): + r=ready();r.register_principal('other');s=r.session();rep=s.invoke(instance_id=r.instance_id,capability_id='acquisition.start',arguments={},request_id='start') + with self.assertRaisesRegex(ActionRejected,'ACCESS_DENIED'):r.session('other').poll(rep['operation_id']) + self.assertEqual(s.cancel(rep['operation_id'],'cancel')['status'],'succeeded');self.assertEqual(s.poll(rep['operation_id'])['status'],'cancelled') + def test_38_schema_bool_nan_extra(self): + r=ready() + for value in [True,float('nan'),float('inf')]:self.assertReject(r,'calibration.zero',dict(observed_blank=value,mode='absorbance'),'INVALID_ARGUMENT') + self.assertReject(r,'power.set',dict(enabled=True,unexpected=3),'INVALID_ARGUMENT') + def test_39_zero_step_stability(self): + r=ready();s=r.debug_snapshot();r.step(0);self.assertEqual(s,r.debug_snapshot()) + def test_40_busy_guard_atomic(self): + r=ready();r.invoke('acquisition.start');self.assertReject(r,'method.configure',METHOD_EXAMPLE,'BUSY') + def test_41_unsupported(self): + r=ready() + for k in UNSUPPORTED:self.assertReject(r,k,CAPS[k][6],'UNSUPPORTED') + def test_42_timestamp_not_read_time(self): + r=ready();r.invoke('acquisition.start');r.step(2);rep=r.session().read(instance_id=r.instance_id,state_ids=['scan.signal']);self.assertAlmostEqual(rep['observations']['scan.signal']['sample_time_s'],.57);self.assertEqual(rep['clock']['time_s'],2.) + def test_43_all_templates_actual_output(self): + for t in AppliedSx20Runtime().templates.values(): + peak=t['derived']['emission_peak_m'];lo=max(300e-9,t['em_wavelength_m'][0],peak-10e-9);hi=min(650e-9,t['em_wavelength_m'][-1],peak+10e-9) + sample=dict(SAMPLE_EXAMPLE,template_id=t['substance_id'],solvent=t['conditions']['solvent']) + method=dict(FLUOR_METHOD,wavelength_m=t['conditions']['reference_excitation_m'],filter_low_m=lo,filter_high_m=hi,points=6,duration_s=.01) + r=ready(sample=sample,method=method);r.invoke('acquisition.start');r.step(1);self.assertEqual(r.phase,'succeeded');self.assertTrue(all(math.isfinite(p['signal']) for p in r.points));self.assertGreater(max(p['signal'] for p in r.points),0) + def test_44_no_factory_dimensions(self): + g=json.loads((ROOT/'assets/expansion_batch04/t3_analytical/applied_sx20/geometry_manifest.json').read_text());self.assertIsNone(g['documented_dimensions_m']);self.assertIsNone(g['total_mass_kg']) + def test_45_physical_unit_slots(self): + r=ready(method=FLUOR_METHOD);r.invoke('acquisition.start');r.step(1);out=r.session().read(instance_id=r.instance_id);self.assertEqual(out['observations']['scan.fluorescence_v']['unit'],'V');self.assertIsNone(out['observations']['scan.absorbance']['value']);self.assertEqual(out['observations']['scan.fluorescence_v']['value'],r.points[-1]['signal']) + def test_46_reconfigure_preserves_old_observation_unit(self): + r=ready();r.invoke('acquisition.start');r.step(1);r.invoke('power.set',enabled=False);r.invoke('method.configure',**FLUOR_METHOD) + self.assertEqual(r.read()['scan.unit'],'1');self.assertIsNone(r.read()['scan.fluorescence_v']);self.assertIsNotNone(r.read()['scan.absorbance']) + def test_47_fit_time_and_signal_scale_equivariance(self): + base=np.linspace(0,1,60);r=AppliedSx20Runtime() + for time_scale,signal_scale in [(1.,1e-20),(1.,1e200),(1e12,1.),(1e-12,1.)]: + with self.subTest(time_scale=time_scale,signal_scale=signal_scale): + before=r.debug_snapshot();out=r.invoke('kinetics.fit',time_s=(base*time_scale).tolist(),signal=((.2+.7*np.exp(-7*base))*signal_scale).tolist()) + self.assertAlmostEqual(out['k_s_inv']*time_scale,7.,places=7);self.assertAlmostEqual(out['amplitude']/signal_scale,.7,places=8);self.assertAlmostEqual(out['offset']/signal_scale,.2,places=8);self.assertLess(out['rmse']/signal_scale,1e-8) + json.dumps(out,allow_nan=False);self.assertEqual(before,r.debug_snapshot()) + def test_48_fit_unrepresentable_rate_is_clear_atomic_rejection(self): + r=AppliedSx20Runtime();x=np.linspace(0,1,60);args=dict(time_s=(x*1e-309).tolist(),signal=(.2+.7*np.exp(-7*x)).tolist());before=r.debug_snapshot() + reply=r.session().invoke(instance_id=r.instance_id,capability_id='kinetics.fit',arguments=args,request_id='too-fast-for-number') + self.assertEqual(reply['status'],'rejected');self.assertEqual(reply['error']['code'],'FIT_UNIDENTIFIABLE');self.assertEqual(before,r.debug_snapshot());json.dumps(reply,allow_nan=False) + def test_49_result_method_retained_until_next_acquisition(self): + r=ready();r.invoke('acquisition.start');r.step(1);old=r.invoke('result.read');new=dict(METHOD_EXAMPLE,duration_s=.2,delay_s=.01) + r.invoke('method.configure',**new);self.assertEqual(r.invoke('result.read'),old);self.assertEqual(json.loads(old['settings_json']),METHOD_EXAMPLE) + flush(r);r.invoke('acquisition.start');empty=r.invoke('result.read');self.assertEqual(empty['points'],[]);self.assertEqual(json.loads(empty['settings_json']),new);r.step(1) + result=r.invoke('result.read');self.assertAlmostEqual(result['points'][-1]['trigger_time_s'],.21);self.assertEqual(json.loads(result['settings_json']),new) + def test_50_depleted_stocks_nonnegative_and_conserved(self): + r=ready(method=dict(METHOD_EXAMPLE,stop_volume_m3=2.5e-6)) + for shot in range(2): + if shot:flush(r) + r.invoke('acquisition.start') + while r.phase=='running':r.step(.007) + ledger=r.invoke('product.read') + for key in ['stock_a_volume_m3','stock_b_volume_m3','cell_volume_m3','stop_volume_m3','waste_volume_m3','stock_moiety_mol','cell_moiety_mol','stop_moiety_mol','waste_moiety_mol']:self.assertGreaterEqual(ledger[key],0.) + self.assertLess(ledger['stock_a_volume_m3'],1e-18);self.assertLess(ledger['stock_b_volume_m3'],1e-18);self.assertLess(abs(ledger['volume_residual_m3']),1e-18);self.assertLess(abs(ledger['moiety_residual_mol']),1e-21) + self.assertAlmostEqual(ledger['modeled_mass_residual_kg'],ledger['volume_residual_m3']*PLANT_EXAMPLE['fluid_density_kg_m3']) + for key,value in r.read('evaluator').items():validate(SLOTS[key][0],value) + flush(r);self.assertReject(r,'acquisition.start',{},'INSUFFICIENT_REAGENT') + def test_51_historical_completion_snapshot_has_final_elapsed_and_owner(self): + r=ready();r.register_principal('other');s=r.session();op=s.invoke(instance_id=r.instance_id,capability_id='acquisition.start',arguments={},request_id='first')['operation_id'];r.step(1) + terminal=s.poll(op);self.assertEqual(terminal['status'],'succeeded');self.assertAlmostEqual(terminal['result']['elapsed_s'],.57);self.assertEqual(terminal['result']['completed_points'],101) + flush(r);s.invoke(instance_id=r.instance_id,capability_id='acquisition.start',arguments={},request_id='second');before=r.debug_snapshot();self.assertEqual(s.poll(op),terminal) + terminal['result']['completed_points']=999;self.assertEqual(s.poll(op)['result']['completed_points'],101) + self.assertNotIn(SAMPLE_EXAMPLE['sample_id'],json.dumps(s.poll(op)));self.assertNotIn(SAMPLE_EXAMPLE['template_id'],json.dumps(s.poll(op))) + with self.assertRaisesRegex(ActionRejected,'ACCESS_DENIED'):r.session('other').poll(op) + self.assertEqual(before,r.debug_snapshot()) + def test_52_cancel_historical_terminal_does_not_cancel_current(self): + r=ready();s=r.session();old=s.invoke(instance_id=r.instance_id,capability_id='acquisition.start',arguments={},request_id='old')['operation_id'];r.step(1);flush(r) + current=s.invoke(instance_id=r.instance_id,capability_id='acquisition.start',arguments={},request_id='new')['operation_id'];r.step(.02);revision=r.revision;volumes=[r._va,r._vb,r._vs,r._vw] + v=s.cancel(old,'cancel-old');self.assertEqual(v['result']['phase'],'succeeded');self.assertEqual(r.phase,'running');self.assertEqual(r.operation_id,current);self.assertEqual(r.revision,revision);self.assertEqual(volumes,[r._va,r._vb,r._vs,r._vw]);self.assertEqual(s.cancel(old,'cancel-old'),v) + with self.assertRaisesRegex(ActionRejected,'REQUEST_CONFLICT'):s.cancel(current,'cancel-old') + self.assertEqual(r.phase,'running') + def test_53_cancelled_observations_and_transferred_liquid_stay_retained(self): + r=ready();s=r.session();op=s.invoke(instance_id=r.instance_id,capability_id='acquisition.start',arguments={},request_id='partial')['operation_id'];r.step(.083);points=copy.deepcopy(r.points);volumes=[r._va,r._vb,r._vs,r._vw] + s.cancel(op,'stop-partial');terminal=s.poll(op);self.assertEqual(terminal['status'],'cancelled');self.assertEqual(terminal['result']['completed_points'],len(points));self.assertGreater(len(points),0);self.assertLess(len(points),101) + r.step(1);self.assertEqual(r.points,points);self.assertEqual([r._va,r._vb,r._vs,r._vw],volumes);self.assertTrue(r.needs_flush) + flush(r);s.invoke(instance_id=r.instance_id,capability_id='acquisition.start',arguments={},request_id='next');self.assertEqual(s.poll(op),terminal) + def test_54_metadata_tracks_actual_calibration_and_drive_timing(self): + r=ready();m=export_applied_sx20_contract_metadata();caps=m['capabilities'];before=r.read();r.invoke('calibration.zero',observed_blank=.02,mode='absorbance');after=r.read() + self.assertEqual({key for key in before if before[key]!=after[key]},{'calibration.absorbance_correction'});self.assertEqual(after['calibration.absorbance_correction'],-.02);self.assertEqual(after['calibration.fluorescence_correction_v'],0.) + self.assertEqual(m['state_slots']['calibration.absorbance_correction']['unit'],'1');self.assertEqual(m['state_slots']['calibration.fluorescence_correction_v']['unit'],'V');self.assertTrue(all(e['timing']=='immediate' for e in caps['calibration.zero']['state_effects'])) + before=r.read('evaluator');r.invoke('acquisition.start');started=r.read('evaluator');immediate={v['state_id'] for v in caps['acquisition.start']['state_effects'] if v['timing']=='immediate'};later={v['state_id'] for v in caps['acquisition.start']['state_effects'] if v['timing']=='on_step'} + self.assertLessEqual({key for key in before if before[key]!=started[key]},immediate);self.assertNotIn('drive.stroke_m',immediate);r.step(.02);advanced=r.read('evaluator');self.assertLessEqual({key for key in started if started[key]!=advanced[key]},later);self.assertGreater(advanced['drive.stroke_m'],0.) + self.assertEqual(caps['kinetics.fit']['observes'],[]);self.assertEqual(caps['power.set']['observes'],['power.enabled']) +if __name__=='__main__':unittest.main() + + diff --git a/tests/test_asset_arradiance_gemstarxt.py b/tests/test_asset_arradiance_gemstarxt.py new file mode 100644 index 0000000000000000000000000000000000000000..74c1e276760d767fb3a4d5f531b432d7c317c39f --- /dev/null +++ b/tests/test_asset_arradiance_gemstarxt.py @@ -0,0 +1,177 @@ +"""CHEM-064 independent conservation, timing, interlock and protocol checks.""" +import copy,math,sys,unittest +from pathlib import Path +sys.path.insert(0,str(Path(__file__).resolve().parents[1]/'scripts')) +from asset_runtime.arradiance_gemstarxt import * +def ready(law='alumina_tma_water',warm=True,plant=None,kinetics=None,supply=None,method=None,sample=True): + h=ArradianceGemstarxtRuntime();p=dict(WARM_EXAMPLE if warm else PLANT_EXAMPLE) + if law in ['zinc_dez_water','titania_ttip_water']:p['initial_k']=[423.15,423.15,373.15] if warm else [298.15]*3 + p.update(plant or {});h.invoke('plant.configure',**p) + su=copy.deepcopy(SUPPLY_EXAMPLE);su['bottle_species'][0]=LAWS[law]['a'];su.update(supply or {});h.invoke('gas.install',**su) + ke=dict(KINETICS_EXAMPLE,law_id=law) + if law=='zinc_dez_water':ke.update(density_kg_m3=5600.,adsorption_pa_s_inv=1.4,conversion_pa_s_inv=1.8) + if law=='titania_ttip_water':ke.update(density_kg_m3=3900.,adsorption_pa_s_inv=.7,conversion_pa_s_inv=.9) + if LAWS[law]['plasma']:ke.update(plasma_site_mol_m2=3e-6,adsorption_pa_s_inv=1.,conversion_pa_s_inv=1.) + ke.update(kinetics or {});h.invoke('kinetics.configure',**ke) + if sample:h.invoke('sample.install',**(HOT_SAMPLE_EXAMPLE if warm else SAMPLE_EXAMPLE)) + m=copy.deepcopy(METHOD_EXAMPLE) + if law in ['zinc_dez_water','titania_ttip_water']:m.update(reactor_k=423.15,door_k=423.15) + if LAWS[law]['plasma']:m.update(rf_w=150.,pulse_s=[.2,.5],exposure_s=[.5,2.]) + m.update(method or {});h.invoke('method.configure',**m) + if not warm:h.invoke('door.set',opened=False) + h.invoke('power.set',enabled=True) + if LAWS[law]['plasma']:h.invoke('rf.power_set',enabled=True) + return h +def run(law='alumina_tma_water',**kwargs): + h=ready(law,**kwargs);h.invoke('acquisition.start');h.step(100);return h +def at_stage(h,stage,limit=20000): + for _ in range(limit): + if h.stage==stage:return + h.step(.02) + raise AssertionError((h.stage,h.phase,stage)) +class TestALD(unittest.TestCase): + def conserved(self,h): + d=h._ledger();self.assertLess(max(map(abs,d['atom_residual_mol'])),1e-10);self.assertLess(abs(d['thermal_residual_j']),1e-5) + for x in [h.gas,h.exhaust,h.film,h.collected]:self.assertTrue(all(n>=0 for n in x.values())) + self.assertGreaterEqual(h.adsorbed,0);self.assertLessEqual(h.adsorbed,h.capacity+1e-14) + def rejects_unchanged(self,h,cap,**a): + old=h.debug_snapshot() + with self.assertRaises(ActionRejected):h.invoke(cap,**a) + self.assertEqual(old,h.debug_snapshot()) + def test_01_primary_three_and_curated_not_50(self): + h=ArradianceGemstarxtRuntime();self.assertEqual(len(h.templates),3);self.assertEqual(len(h.references),109) + self.assertEqual(len({r['material'] for r in h.references.values() if r['material']}),45) + self.assertTrue(all(not r['runnable'] for r in h.references.values())) + def test_02_anchors_have_distinct_precursors_conditions_sources(self): + h=ArradianceGemstarxtRuntime();self.assertEqual({r['value'] for r in h.templates.values()},{1.05e-10,1.8e-10,.5e-10}) + self.assertEqual(h.templates['titania_ttip_water']['precursor'],'TTIP') + for r in h.templates.values():self.assertEqual(r['evidence'],'measured_literature');self.assertTrue(r['source']['sha256']) + def test_03_all_net_reactions_element_balanced(self): + for law in LAWS.values(): + for i in range(8): + lhs=law['na']*ATOMS[law['a']][i]+law['nb']*ATOMS[law['b']][i] + rhs=ATOMS[law['film']][i]+sum(c*ATOMS[s][i] for s,c in law['products'].items());self.assertEqual(lhs,rhs) + def test_04_initial_warm_snapshot_explicit(self): + h=ArradianceGemstarxtRuntime();self.rejects_unchanged(h,'plant.configure',**dict(WARM_EXAMPLE,warm_snapshot=False)) + h.invoke('plant.configure',**WARM_EXAMPLE);self.assertGreater(h.thermal_initial,0);self.conserved(h);self.rejects_unchanged(h,'plant.configure',**WARM_EXAMPLE) + def test_05_cold_configuration_not_teleport(self): + h=ready(warm=False);self.assertEqual(h.temp,[298.15]*3);self.assertEqual(h.target,[523.15,523.15,373.15]);self.assertFalse(h.opened) + def test_06_hot_sample_only_same_initialization_clock(self): + h=ready(sample=False);h.step(.01);self.rejects_unchanged(h,'sample.install',**HOT_SAMPLE_EXAMPLE) + def test_07_substrate_200mm_max(self): + h=ready(sample=False);self.rejects_unchanged(h,'sample.install',**dict(HOT_SAMPLE_EXAMPLE,area_m2=math.pi*.101**2)) + def test_08_hardware_temperature_limits(self): + h=ready() + for n,t in [('reactor_k',573.16),('door_k',573.16),('manifold_k',473.16)]:self.rejects_unchanged(h,'method.configure',**dict(METHOD_EXAMPLE,**{n:t})) + def test_09_carrier_rf_hard_limits(self): + h=ready();self.rejects_unchanged(h,'method.configure',**dict(METHOD_EXAMPLE,carrier_std_m3_s=CARRIER_MAX*1.01));self.rejects_unchanged(h,'method.configure',**dict(METHOD_EXAMPLE,rf_w=300.1)) + def test_10_temperature_anchor_not_extrapolated(self): + h=ready();self.rejects_unchanged(h,'method.configure',**dict(METHOD_EXAMPLE,reactor_k=423.15)) + def test_11_plasma_not_thermal_fixed_gpc(self): + h=ready(sample=False);self.rejects_unchanged(h,'kinetics.configure',**dict(KINETICS_EXAMPLE,law_id='plasma_tma_oxygen')) + h=run('plasma_tma_oxygen');self.assertEqual(h.phase,'succeeded');self.assertGreater(h.film['Al2O3'],0);self.conserved(h) + e=h.invoke('film.estimate');self.assertFalse(e['measured']);self.assertIn('no_measured_GPC',e['template_source']) + def test_12_three_materials_complete_and_thickness_formula(self): + results=[] + for law in list(LAWS)[:3]: + h=run(law);self.assertEqual(h.phase,'succeeded');self.assertEqual(h.completed,2);self.conserved(h) + ratio=h._thickness()/(2*h.templates[law]['value']);self.assertAlmostEqual(ratio,1,delta=1e-6);results.append(h._thickness()) + self.assertEqual(len(set(round(x,14) for x in results)),3) + def test_13_finite_feed_pulse_integral(self): + h=run();self.assertAlmostEqual(.01-h.remaining[0],2*.2*2e-4,delta=1e-12);self.assertAlmostEqual(.03-h.remaining[1],2*.2*3e-4,delta=1e-12) + def test_14_substep_short_pulse_no_extra_dose(self): + h=run(method={'pulse_s':[.001,.003]});self.assertAlmostEqual(.01-h.remaining[0],2*.001*2e-4,delta=1e-12);self.assertAlmostEqual(.03-h.remaining[1],2*.003*3e-4,delta=1e-12);self.conserved(h) + def test_15_saturation_caps_growth_not_pulse_linear(self): + a=run(method={'pulse_s':[.2,.2],'cycles':1});b=run(method={'pulse_s':[2.,2.],'cycles':1}) + self.assertLessEqual(b._thickness(),b.templates['alumina_tma_water']['value']*(1+1e-12));self.assertAlmostEqual(a._thickness(),b._thickness(),delta=1e-17);self.assertGreater(.01-b.remaining[0],8*(.01-a.remaining[0])) + def test_16_underexposure_not_forced_nominal_gpc(self): + h=run(kinetics={'adsorption_pa_s_inv':1e-5,'conversion_pa_s_inv':1e-5}) + self.assertLess(h._thickness(),2*h.templates['alumina_tma_water']['value']*.01);self.assertGreater(h.adsorbed,0);self.conserved(h) + def test_17_a_half_reaction_bound_no_film(self): + h=ready();h.invoke('acquisition.start');at_stage(h,'purge_a');self.assertGreater(h.adsorbed,0);self.assertEqual(sum(h.film.values()),0.);self.conserved(h) + def test_18_cancel_preserves_adsorbate_residual(self): + h=ready();h.invoke('acquisition.start');at_stage(h,'exposure_a');before=h.adsorbed;gas=h.gas['TMA'];h.invoke('acquisition.stop') + self.assertEqual(h.phase,'cancelled');self.assertEqual(h.adsorbed,before);self.assertGreater(gas,0);h.step(1);self.assertEqual(h.adsorbed,before);self.assertLess(h.gas['TMA'],gas);self.conserved(h) + def test_19_cancel_after_b_preserves_partial_film(self): + h=ready(kinetics={'conversion_pa_s_inv':.001});h.invoke('acquisition.start');at_stage(h,'purge_b');f=h._thickness();self.assertGreater(f,0);h.invoke('acquisition.stop');h.step(1);self.assertEqual(h._thickness(),f);self.assertEqual(h.completed,0);self.conserved(h) + def test_20_purge_extends_and_clears_residual(self): + h=ready(method={'purge_s':[.001,.001],'cycles':1});h.invoke('acquisition.start');at_stage(h,'purge_a');h.step(.05);self.assertEqual(h.stage,'purge_a');at_stage(h,'pulse_b');self.assertLessEqual(h._p('TMA'),h.plant['residual_limit_pa']);self.conserved(h) + def test_21_purge_timeout_not_fake_success(self): + h=run(plant={'pump_m3_s':1e-5,'purge_timeout_s':1.},method={'purge_s':[.001,.001]});self.assertEqual(h.phase,'failed');self.assertEqual(h.warning,'PURGE_RESIDUAL_TIMEOUT');self.assertEqual(h.completed,0);self.conserved(h) + def test_22_empty_source_fail_finite(self): + h=run(supply={'bottle_mol':[1e-8,.03,0.,0.]});self.assertEqual(h.phase,'failed');self.assertEqual(h.warning,'SOURCE_EXHAUSTED');self.assertEqual(h.remaining[0],0);self.assertFalse(any(h.valves));self.conserved(h) + def test_23_shared_carrier_not_double_count(self): + h=ready('plasma_tma_oxygen',method={'cycles':1});h.invoke('acquisition.start');at_stage(h,'pulse_b');n=h.carrier;t=h.elapsed_s;h.step(.1) + expected=h.method['carrier_std_m3_s']*STD_P/(R*STD_T)*(h.elapsed_s-t);self.assertAlmostEqual(n-h.carrier,expected,delta=1e-12);self.assertGreater(h.rf,0);self.conserved(h) + def test_24_rf_independent_power_interlock(self): + h=ready('plasma_tma_oxygen');h.invoke('rf.power_set',enabled=False);self.rejects_unchanged(h,'acquisition.start') + def test_25_powerloss_closes_all_keeps_material(self): + h=ready();h.invoke('acquisition.start');at_stage(h,'exposure_a');before=h.adsorbed;h.invoke('power.set',enabled=False);self.assertEqual(h.rf,0);self.assertEqual(h.valves,[0.]*4);self.assertEqual(h.adsorbed,before);self.conserved(h) + def test_26_emo_reset_requires_both_off(self): + h=ready();h.invoke('safety.emo');self.assertTrue(h.emo);self.rejects_unchanged(h,'safety.reset');h.invoke('power.set',enabled=False);h.invoke('rf.power_set',enabled=False);h.invoke('safety.reset');self.assertFalse(h.emo) + def test_27_watchdog_failure_and_heartbeat(self): + h=ready(plant={'watchdog_s':.1});h.invoke('acquisition.start');h.step(.05);h.invoke('control.heartbeat');h.step(.05);self.assertFalse(h.emo);h.step(.1);self.assertTrue(h.emo);self.assertEqual(h.warning,'WATCHDOG_TIMEOUT');self.assertEqual(h.phase,'failed') + def test_28_hot_or_vacuum_door_rejected(self): + h=ready();self.rejects_unchanged(h,'door.set',opened=True);h.invoke('power.set',enabled=False);self.rejects_unchanged(h,'door.set',opened=True) + def test_29_cold_vent_collect_conserves(self): + h=ready(warm=False);h.invoke('power.set',enabled=False);h.invoke('door.set',opened=True);h.invoke('sample.collect',recipient_id='tray');self.assertIsNone(h.sample);self.conserved(h) + def test_30_collect_bound_and_film_after_cooling(self): + h=ready(plant={'heat_capacity_j_k':[100.]*3,'heat_loss_w_k':[10.]*3});h.invoke('acquisition.start');at_stage(h,'purge_b');h.invoke('acquisition.stop');h.invoke('power.set',enabled=False);h.step(300);h.invoke('vacuum.vent');h.step(10);h.invoke('door.set',opened=True);h.invoke('sample.collect',recipient_id='tray');self.assertGreater(sum(h.collected.values()),0);self.conserved(h) + def test_31_read_describe_stepzero_pure(self): + h=ready();old=h.debug_snapshot();h.read();h.describe();h.invoke('process.measure');h.invoke('product.read');h.invoke('film.estimate');h.step(0);self.assertEqual(old,h.debug_snapshot()) + def test_32_rejection_atomic_and_numeric_boolean(self): + h=ready() + for x in [True,float('nan'),float('inf'),-1]:self.rejects_unchanged(h,'method.configure',**dict(METHOD_EXAMPLE,carrier_std_m3_s=x)) + h.invoke('acquisition.start');self.rejects_unchanged(h,'method.configure',**METHOD_EXAMPLE) + def test_33_two_instance_independence(self): + a=ready();b=ready();old=b.debug_snapshot();a.invoke('acquisition.start');a.step(2);self.assertEqual(b.debug_snapshot(),old) + def test_34_truth_filter_and_host_only_identity(self): + h=ready();s=h.session();self.assertNotIn('truth.ledger',s.describe(instance_id=h.instance_id)['state_slots']);self.assertNotIn('product.read',s.describe(instance_id=h.instance_id)['capabilities']) + r=s.invoke(instance_id=h.instance_id,capability_id='product.read',arguments={},request_id='deny');self.assertEqual(r['error']['code'],'ACCESS_DENIED') + with self.assertRaises(ActionRejected):s.read(instance_id=h.instance_id,state_ids=['truth.ledger']) + with self.assertRaises(ActionRejected):h.session('evaluator') + def test_35_idempotency_conflict_operation_owner(self): + h=ready();s=h.session();args=dict(instance_id=h.instance_id,capability_id='acquisition.start',arguments={},request_id='a') + r=s.invoke(**args);self.assertEqual(s.invoke(**args),r);self.assertEqual(h._operation_count,1) + bad=s.invoke(instance_id=h.instance_id,capability_id='power.set',arguments={'enabled':False},request_id='a');self.assertEqual(bad['error']['code'],'REQUEST_CONFLICT') + h.register_principal('other');other=h.session('other') + with self.assertRaises(ActionRejected):other.poll(r['operation_id']) + s.cancel(r['operation_id'],'cancel');self.assertEqual(h.phase,'cancelled') + def test_36_template_reference_raw_not_runnable(self): + h=ready();r=h.invoke('reference.read',reference_id='gold_002');self.assertFalse(r['runnable']);self.assertIn('not independently',r['evidence']) + self.rejects_unchanged(h,'template.read',substance_id='gold_002') + def test_37_cold_full_cycle_actually_heats(self): + h=ready(warm=False,plant={'heat_capacity_j_k':[100.]*3},method={'cycles':1});h.invoke('acquisition.start');h.step(.1);self.assertLess(h.temp[0],310);h.step(180);self.assertEqual(h.phase,'succeeded');self.assertGreater(h._thickness(),0);self.conserved(h) + def test_38_pulse_chunking_stability(self): + a=ready(method={'pulse_s':[.003,.005]});b=ready(method={'pulse_s':[.003,.005]}) + for h in [a,b]:h.invoke('acquisition.start') + a.step(60) + for _ in range(6000):b.step(.01) + self.assertAlmostEqual(a.remaining[0],b.remaining[0],delta=1e-12);self.assertAlmostEqual(a.remaining[1],b.remaining[1],delta=1e-12);self.conserved(a);self.conserved(b) + def test_39_heater_electrical_upper_bound(self): + h=ArradianceGemstarxtRuntime();self.rejects_unchanged(h,'plant.configure',**dict(WARM_EXAMPLE,heater_max_w=[1500.,600.,400.])) + self.assertLessEqual(sum(PLANT_EXAMPLE['heater_max_w']),120*20) + def test_40_bad_step_does_not_advance(self): + h=ready() + for dt in [True,-1.,float('nan'),float('inf')]: + old=h.debug_snapshot() + with self.assertRaises(ActionRejected):h.step(dt) + self.assertEqual(old,h.debug_snapshot()) + def test_41_standard_bottles_not_four_filled(self): + self.assertEqual(sum(n>0 for n in SUPPLY_EXAMPLE['bottle_mol']),2) + h=ArradianceGemstarxtRuntime();h.invoke('plant.configure',**WARM_EXAMPLE) + self.rejects_unchanged(h,'gas.install',**dict(SUPPLY_EXAMPLE,bottle_species=['TMA','TMA','EMPTY','EMPTY'])) + def test_42_session_write_routes_to_checked_command(self): + h=ready();s=h.session();result=s.write(instance_id=h.instance_id,state_id='power.enabled',value=False,request_id='power-write');self.assertEqual(result['status'],'succeeded');self.assertFalse(h.powered) + with self.assertRaises(ActionRejected):s.write(instance_id=h.instance_id,state_id='truth.ledger',value={},request_id='private') + def test_43_power_EMO_watchdog_close_vacuum_NC(self): + for cap,a in [('power.set',{'enabled':False}),('safety.emo',{})]: + h=ready();h.invoke('acquisition.start');h.step(.1);self.assertTrue(h.pump);h.invoke(cap,**a);self.assertFalse(h.pump);self.assertEqual(h.read()['vacuum.angle_rad'],0.);self.conserved(h) + h=ready(plant={'watchdog_s':.1});h.invoke('acquisition.start');h.step(.2);self.assertFalse(h.pump);self.conserved(h) + def test_44_chemistry_change_invalidates_old_method(self): + h=ready(sample=False);self.assertTrue(h.method);h.invoke('kinetics.configure',**dict(KINETICS_EXAMPLE,law_id='zinc_dez_water'));self.assertIsNone(h.method) + self.rejects_unchanged(h,'method.configure',**METHOD_EXAMPLE) +if __name__=='__main__':unittest.main() + + + diff --git a/tests/test_asset_biolin_sigma700.py b/tests/test_asset_biolin_sigma700.py new file mode 100644 index 0000000000000000000000000000000000000000..4d753d27915463015cd3e6e9c0005787d5470e7f --- /dev/null +++ b/tests/test_asset_biolin_sigma700.py @@ -0,0 +1,118 @@ +import unittest,copy,math,json,sys +from pathlib import Path +from unittest import mock +ROOT=Path(__file__).resolve().parents[1];sys.path.insert(0,str(ROOT/'outputs/expansion_batch03/t4_measure/biolin_sigma700'));import example_setup as ex +rt=ex.rt +class Tests(unittest.TestCase): + def h(self,**kw):return ex.build(**kw) + def test_01_source(self):self.assertEqual(sum(v['kind']=='pure' for v in rt.LIB['substances'].values()),413);self.assertAlmostEqual(rt.tension('cas_64_17_5',293.15,0),.022386) + def test_02_pure_read(self): + h=self.h();s=h.session();before=copy.deepcopy(h.__dict__);s.describe(instance_id=h.instance_id);s.read(instance_id=h.instance_id);h.invoke('acquisition.result');self.assertEqual(before,h.__dict__) + def test_03_target_not_advance(self): + h=self.h();t=h.time_s;h.invoke('stage.move',position_m=.06);self.assertEqual(h.q,0.);self.assertEqual(h.time_s,t);h.step(.1);self.assertAlmostEqual(h.q,.0008) + def test_04_plate(self): + h=self.h();ex.call(h,'acquisition.start');h.step(30);r=ex.call(h,'acquisition.result');self.assertEqual(r['phase'],'succeeded');self.assertAlmostEqual(r['tension_n_m'],.022454,delta=3e-6);self.assertGreater(len(r['rows']),200);self.assertEqual(h.q,0.) + def test_05_force_buoyancy(self): + h=self.h();h.invoke('stage.move',position_m=.101);h.step(14);d=h._depth();expected=.002*rt.G+2*(.0195+.00012)*.022454-791.01243*rt.G*.0195*.00012*d;self.assertAlmostEqual(h.trueforce,expected,places=10) + def test_06_ring(self): + h=self.h(probe='ring',method={'speed_m_s':.001,'sample_interval_s':.02});h.invoke('acquisition.start');h.step(210);self.assertEqual(h.phase,'succeeded');self.assertAlmostEqual(h.peak,.022454,delta=.00010) + def test_07_ring_acceptance(self): + h=self.h(probe='ring');h.method['accept_ring_proxy']=False + with self.assertRaisesRegex(rt.ActionRejected,'RING_MODEL'):h.invoke('acquisition.start') + def test_08_two_instances(self): + a=self.h();b=self.h(sid='cas_64_17_5');a.invoke('acquisition.start');a.step(30);self.assertEqual(b.phase,'idle');self.assertNotEqual(a.gamma,b.gamma) + def test_09_atomic(self): + h=self.h();before=copy.deepcopy(h.__dict__) + with self.assertRaises(rt.ActionRejected):h.invoke('method.configure',**dict(rt.METHOD_EXAMPLE,speed_m_s=float('nan'))) + self.assertEqual(before,h.__dict__) + def test_10_busy(self): + h=self.h();h.invoke('acquisition.start');before=copy.deepcopy(h.__dict__) + with self.assertRaisesRegex(rt.ActionRejected,'BUSY'):h.invoke('door.set',angle_rad=2.35) + self.assertEqual(before,h.__dict__) + def test_11_cancel(self): + h=self.h();ex.call(h,'acquisition.start');h.step(4);q=h.q;ex.call(h,'acquisition.stop');n=len(h.rows);h.step(2);self.assertEqual(h.q,q);self.assertEqual(len(h.rows),n);self.assertEqual(h.phase,'cancelled') + def test_12_heat(self): + h=self.h();h.invoke('thermal.set_temperature',temperature_k=313.15);before=h.temperature;h.step(100);self.assertGreater(h.temperature,before);self.assertLess(h.temperature,313.15);self.assertAlmostEqual(h._ledger()['heat_error_j'],0.,delta=1e-7) + def test_13_dose(self): + h=self.h(sid='apg_fig1_2',plant={'ambient_k':298.15},temp=298.15);ex.call(h,'stock.load',volume_m3=2e-5,concentration_kg_m3=1.);ex.call(h,'dose.start',volume_m3=1e-6,flow_m3_s=1e-7);h.step(3);self.assertAlmostEqual(h.volume,30.3e-6);ex.call(h,'acquisition.stop');v=h.volume;h.step(1);self.assertEqual(h.volume,v);l=ex.call(h,'ledger.read');self.assertAlmostEqual(l['mass_error_kg'],0.,delta=1e-12);self.assertAlmostEqual(l['solute_error_kg'],0.,delta=1e-12);self.assertAlmostEqual(l['heat_error_j'],0.,delta=1e-7) + def test_14_finite_stock(self): + h=self.h();h.invoke('stock.load',volume_m3=1e-6,concentration_kg_m3=0.);h.invoke('dose.start',volume_m3=1e-6,flow_m3_s=1e-7);h.step(11);self.assertEqual(h.phase,'succeeded');self.assertAlmostEqual(h.stock,0.,delta=1e-12) + with self.assertRaisesRegex(rt.ActionRejected,'FINITE_STOCK'):h.invoke('dose.start',volume_m3=1e-6,flow_m3_s=1e-7) + def test_15_truth(self): + h=self.h();s=h.session();self.assertNotIn('truth.solute_kg',s.describe(instance_id=h.instance_id)['state_slots']);self.assertNotIn('truth.solute_kg',s.read(instance_id=h.instance_id)['observations']);self.assertEqual(s.invoke(instance_id=h.instance_id,capability_id='ledger.read',arguments={},request_id='x')['error']['code'],'ACCESS_DENIED') + def test_16_principals(self): + h=self.h() + with self.assertRaises(rt.ActionRejected):h.session('intruder') + with self.assertRaises(rt.ActionRejected):h.register_principal('agent','evaluator') + def test_17_dedupe(self): + h=self.h();s=h.session();a=dict(instance_id=h.instance_id,capability_id='stage.move',arguments={'position_m':.05},request_id='x');r=s.invoke(**a);self.assertEqual(r,s.invoke(**a));a['arguments']={'position_m':.1};self.assertEqual(s.invoke(**a)['error']['code'],'REQUEST_CONFLICT') + def test_18_ownership_query(self): + h=self.h();h.register_principal('b');a=h.session();b=h.session('b');r=a.invoke(instance_id=h.instance_id,capability_id='acquisition.start',arguments={},request_id='start');r2=b.invoke(instance_id=h.instance_id,capability_id='acquisition.result',arguments={},request_id='read');self.assertIsNone(r2['operation_id']) + with self.assertRaises(rt.ActionRejected):b.cancel(r['operation_id'],'cancel') + h.step(.5);self.assertEqual(a.poll(r['operation_id'])['status'],'running');self.assertEqual(a.cancel(r['operation_id'],'cancel')['status'],'succeeded') + def test_19_calibration_independent(self): + h=self.h(plant={'force_gain':1.02,'force_offset_n':.00002});ex.call(h,'balance.calibrate',reference_forces_n=[0.,.1],observed_raw_forces_n=[.00002,.10202]);h.step(2);h.invoke('balance.tare');h.invoke('acquisition.start');h.step(30);self.assertAlmostEqual(h.peak,.022454,delta=3e-6) + def test_20_wrong_calibration(self): + h=self.h(plant={'force_gain':1.1});h.invoke('acquisition.start');h.step(30);self.assertGreater(abs(h.peak-.022454),.001) + def test_21_cmc_real(self): + r=rt.LIB['substances']['apg_fig1_2']['values'];h=self.h();out=ex.call(h,'analysis.cmc',concentrations_kg_m3=r['concentration_kg_m3'][1:],tensions_n_m=r['tension_n_m'][1:]);self.assertTrue(.0250 for c in r.channels.values())) + def test_no_fat_measurement(self): + r=run_cycle(configured(fast=True));self.assertEqual(set(r.invoke('hydrolysis.measure')),set(MEASURE['properties']));self.assertNotIn('fat_mass_fraction',r.invoke('hydrolysis.measure')) + def test_all_ledgers(self): + r=rinse_all(filter_once(run_cycle(configured(6,True))));r.invoke('product.collect',position=1,fraction=.5,recipient_id='out') + for v in balances(r)[:4]:self.assertLess(abs(v),1e-9) + self.assertLess(abs(balances(r)[4]),1e-5) + def test_matrix_specific_release(self): + r=configured(2,True);r.channels[2]['config']['release_rate_s_inverse']=0.;b=r.channels[2]['bound'];run_cycle(r);self.assertEqual(r.channels[2]['bound'],b);self.assertLess(r.channels[1]['bound'],b) + def test_cancel_preserves_partial(self): + r=configured(fast=True);r.invoke('acquisition.start');r.step(.1);s=r._product();r.invoke('acquisition.stop');self.assertEqual(r.phase,'cancelled');self.assertEqual(s,r._product());self.assertEqual(r.mode,'off') + def test_power_interrupt(self): + r=configured(fast=True);r.invoke('acquisition.start');r.invoke('power.set',enabled=False);self.assertEqual(r.phase,'cancelled');self.assertEqual(r.mode,'off') + def test_ventilation_fault(self): + r=configured(fast=True);r.invoke('acquisition.start');r.invoke('ventilation.set',enabled=False);self.assertEqual(r.phase,'failed');self.assertFalse(r.vacuum) + def test_raise_busy(self): + r=configured(fast=True);r.invoke('acquisition.start');self.reject(r,'rack.set_raised',raised=True) + def test_vacuum_early_reject(self): + r=configured(fast=True);r.invoke('acquisition.start');self.reject(r,'vacuum.set',enabled=True) + def test_filter_requires_raise(self): + r=run_cycle(configured(fast=True));self.reject(r,'filtration.start') + def test_flow_only_step(self): + r=run_cycle(configured(fast=True));r.invoke('rack.set_raised',raised=True);r.step(1);p=r._product();r.invoke('filtration.start');self.assertEqual(p,r._product());r.step(1);self.assertGreater(r.waste_volume,0) + def test_collect_before_rinse(self): + r=filter_once(run_cycle(configured(fast=True)));self.reject(r,'product.collect',position=1,fraction=1.,recipient_id='out') + def test_water_finite(self): + r=filter_once(run_cycle(configured(fast=True)));r.water=0.;self.reject(r,'rinse.add',position=1,volume_m3=100e-6) + def test_filtered_holdup(self): + r=filter_once(run_cycle(configured(fast=True)));self.assertAlmostEqual(r.channels[1]['tube_volume'],r.plant['tube_holdup_m3']);self.assertLessEqual(r.channels[1]['tube_volume'],64e-6) + def test_cstr_wash(self): + r=filter_once(run_cycle(configured(fast=True)));a=r.channels[1]['tube_acid'];r.invoke('rinse.add',position=1,volume_m3=100e-6);r.invoke('filtration.start');r.step(100);self.assertAlmostEqual(r.channels[1]['tube_acid'],a*math.exp(-100e-6/r.plant['tube_holdup_m3']),places=12) + def test_collect_repeat_finite(self): + r=rinse_all(filter_once(run_cycle(configured(fast=True))));r.invoke('product.collect',position=1,fraction=1.,recipient_id='out');v=r.collected_fat;r.invoke('product.collect',position=1,fraction=1.,recipient_id='out');self.assertEqual(v,r.collected_fat) + def test_agent_truth_filter(self): + r=configured(fast=True);s=r.session();self.assertFalse(any(k.startswith('truth.') for k in r.read()));out=s.invoke(instance_id=r.instance_id,capability_id='product.read',arguments={},request_id='x');self.assertEqual(out['status'],'rejected');self.assertEqual(out['result'],{}) + def test_idempotent_request(self): + r=BuchiHydrolexhRuntime();s=r.session();a=dict(instance_id=r.instance_id,capability_id='power.toggle',arguments={},request_id='x');self.assertEqual(s.invoke(**a),s.invoke(**a));self.assertTrue(r.powered) + def test_unknown_instance(self): + r=BuchiHydrolexhRuntime();s=r.session();self.assertEqual(s.invoke(instance_id='other',capability_id='power.toggle',arguments={},request_id='x')['error']['code'],'UNKNOWN_INSTANCE') + def test_instance_isolation(self): + a=configured(fast=True);b=BuchiHydrolexhRuntime();a.step(1);self.assertEqual(b.time_s,0);self.assertFalse(b.powered);self.assertEqual(len(b.channels),0) + def test_step_invalid(self): + r=BuchiHydrolexhRuntime() + for v in [-1,float('nan'),float('inf'),True,7201]: + with self.assertRaises(ActionRejected):r.step(v) + def test_read_never_steps(self): + r=configured(fast=True);t=r.time_s + for _ in range(10):r.session().read(instance_id=r.instance_id) + self.assertEqual(r.time_s,t) +if __name__=='__main__':unittest.main() diff --git a/tests/test_asset_ch_chi440c.py b/tests/test_asset_ch_chi440c.py new file mode 100644 index 0000000000000000000000000000000000000000..18c75ecafddafbf39312f68430df09635a02a343 --- /dev/null +++ b/tests/test_asset_ch_chi440c.py @@ -0,0 +1,71 @@ +from pathlib import Path +import sys,unittest,copy,importlib.util,math +ROOT=Path(__file__).resolve().parents[1];sys.path.insert(0,str(ROOT/'scripts')) +from asset_runtime.ch_chi440c import * +sp=importlib.util.spec_from_file_location('asset_tool',ROOT/'skills/chemistry-lab-assets/scripts/asset_tool.py');tool=importlib.util.module_from_spec(sp);sp.loader.exec_module(tool) +OBSERVED=set() +def call(r,k,**a): + v=r.invoke(k,**a);err=tool.validate_value(v,CAPS[k][1]);assert not err,err;OBSERVED.add(k);return v +def prepared(crystal=None,method=None,sample=None): + r=ChChi440cRuntime();call(r,'crystal.configure',**(crystal or copy.deepcopy(CRYSTAL_EXAMPLE)));call(r,'lid.set',lift_m=.05);call(r,'sample.load',**(sample or copy.deepcopy(SAMPLE_EXAMPLE)));call(r,'lid.set',lift_m=0.);call(r,'method.configure',**(method or copy.deepcopy(METHOD_EXAMPLE)));call(r,'power.set',enabled=True);return r +def qcm_method(t=3.):return dict(mode='qcm_only',steps=[dict(duration_s=t,potential_v=0.,current_a=0.)],sample_interval_s=.1,reference_electrode='not driven') +class EQCM(unittest.TestCase): + def test_metadata_and_real_templates(self): + r=prepared();m=r.describe() + for c in m['capabilities'].values():self.assertEqual(tool.validate_value(c['example_arguments'],c['input_schema']),[]) + for k,v in r.read('evaluator').items():self.assertEqual(tool.validate_value(v,m['state_slots'][k]['value_schema']),[]) + self.assertEqual(len(r.templates),96) + for sid in r.templates:self.assertGreater(call(r,'template.read',substance_id=sid)['molar_mass_kg_mol'],0.) + def test_faraday_sauerbrey_independent(self): + r=prepared();call(r,'acquisition.start');r.step(3.);self.assertEqual(r.phase,'succeeded');self.assertEqual(len(r.points),30);mass=1e-5*.063546/(2*F);self.assertAlmostEqual(r.film*r.mw,mass,delta=1e-25);self.assertLess(abs(r._ledger()['mass_residual_kg']),1e-21);self.assertLess(abs(r._ledger()['charge_residual_c']),1e-18);self.assertAlmostEqual(r.inferred(),mass,delta=.025/r.sensitivity());self.assertGreater(r.points[19]['inferred_delta_mass_kg'],r.points[-1]['inferred_delta_mass_kg']) + def test_fixed_sampling_partition(self): + a=prepared();b=prepared() + for r in [a,b]:call(r,'acquisition.start') + a.step(3.) + for _ in range(1000):b.step(.003) + self.assertEqual(a.points,b.points);self.assertEqual(a._ledger(),b._ledger()) + def test_voltage_mode_bv_current_and_limits(self): + m=dict(METHOD_EXAMPLE,mode='potential',steps=[dict(duration_s=1.,potential_v=-.05,current_a=0.)]);r=prepared(method=m);call(r,'acquisition.start');r.step(1.);self.assertEqual(r.phase,'succeeded');self.assertGreater(r.current,0.);self.assertLess(abs(r.potential+.05),1e-12) + r=prepared(method=dict(m,steps=[dict(duration_s=1.,potential_v=-10.,current_a=0.)]),sample=dict(SAMPLE_EXAMPLE,series_resistance_ohm=0.));call(r,'acquisition.start');r.step(1.);self.assertEqual(r.failure,'CURRENT_LIMIT');self.assertEqual(r.charge,0.) + def test_galvanostatic_potential_limit(self): + r=prepared(sample=dict(SAMPLE_EXAMPLE,series_resistance_ohm=1e9));call(r,'acquisition.start');r.step(1.);self.assertEqual(r.failure,'POTENTIAL_LIMIT');self.assertEqual(r.film,0.) + def test_atomic_limits_sampling_and_types(self): + r=prepared() + for k,a in [('method.configure',dict(METHOD_EXAMPLE,sample_interval_s=.000999)),('method.configure',dict(METHOD_EXAMPLE,steps=[dict(duration_s=1.,potential_v=0.,current_a=.25001)])),('method.configure',dict(METHOD_EXAMPLE,mode='potential',steps=[dict(duration_s=1.,potential_v=10.01,current_a=0.)])),('method.configure',dict(METHOD_EXAMPLE,sample_interval_s=.13)),('power.set',{'enabled':1}),('lid.set',{'lift_m':float('nan')})]: + before=copy.deepcopy(r.__dict__) + with self.assertRaises(ActionRejected):r.invoke(k,**a) + self.assertEqual(r.__dict__,before) + for dt in [True,float('nan'),-1.]: + with self.assertRaises(ActionRejected):r.step(dt) + def test_maximum_1khz_boundary(self): + r=prepared(method=dict(METHOD_EXAMPLE,steps=[dict(duration_s=.010,potential_v=0.,current_a=1e-5)],sample_interval_s=.001));call(r,'acquisition.start');r.step(.01);self.assertEqual(len(r.points),10);self.assertEqual(r.phase,'succeeded') + def test_finite_exhaustion_preserves_transfers(self): + s=dict(SAMPLE_EXAMPLE,volume_m3=1e-9,concentration_mol_m3=1e-5);r=prepared(sample=s);call(r,'acquisition.start');r.step(3.);self.assertEqual(r.phase,'failed');self.assertEqual(r.failure,'FINITE_MATERIAL_EXHAUSTED');self.assertEqual(r.solution,0.);self.assertGreater(r.film,0);self.assertLess(abs(r._ledger()['mass_residual_kg']),1e-25);self.assertAlmostEqual(r.charge,2*F*1e-14,delta=1e-22) + def test_negative_current_without_film(self): + r=prepared(method=dict(METHOD_EXAMPLE,steps=[dict(duration_s=1.,potential_v=0.,current_a=-1e-5)]));call(r,'acquisition.start');r.step(1.);self.assertEqual(r.failure,'FINITE_MATERIAL_EXHAUSTED');self.assertEqual(r.charge,0.);self.assertEqual(r.film,0.) + def test_cancellation_unload_clean_ledger(self): + r=prepared();call(r,'acquisition.start');r.step(1.);call(r,'acquisition.stop');l=r._ledger();r.step(10.);self.assertEqual(l,r._ledger()) + with self.assertRaisesRegex(ActionRejected,'LID_OPEN_REQUIRED'):r.invoke('sample.unload') + call(r,'lid.set',lift_m=.05);call(r,'sample.unload');self.assertGreater(r.film,0.);call(r,'crystal.clean');self.assertEqual(r.film,0.);self.assertGreater(r.waste_mass,0.);self.assertLess(abs(r._ledger()['mass_residual_kg']),1e-21);call(r,'sample.load',**ADSORPTION_EXAMPLE);self.assertLess(abs(r._ledger()['mass_residual_kg']),1e-21) + def test_baseline_does_not_clean_or_read_truth(self): + r=prepared();r.step(.1);call(r,'baseline.zero');call(r,'acquisition.start');r.step(3.);mass=r.film*r.mw;frequency=r.frequency;call(r,'baseline.zero');self.assertEqual(r.inferred(),0.);self.assertEqual(r.film*r.mw,mass);r.film*=2.;self.assertEqual(r.frequency,frequency);self.assertEqual(r.inferred(),0.) + def test_adsorption_finite_analytic(self): + r=prepared(method=qcm_method(10.),sample=ADSORPTION_EXAMPLE);call(r,'acquisition.start');r.step(10.);self.assertGreater(r.film,0.);self.assertLess(r.film,1e-9);self.assertEqual(r.charge,0.);self.assertLess(abs(r._ledger()['mass_residual_kg']),1e-21);self.assertLess(r.points[-1]['frequency_hz'],r.points[0]['frequency_hz']) + x=0.;dt=1e-4;n=ADSORPTION_EXAMPLE['volume_m3']*ADSORPTION_EXAMPLE['concentration_mol_m3'];s=ADSORPTION_EXAMPLE + for _ in range(100000):x+=dt*(s['adsorption_on_m3_mol_s']*(n-x)*(s['site_capacity_mol']-x)/s['volume_m3']-s['desorption_off_s']*x) + self.assertAlmostEqual(r.film,x,delta=1e-14) + def test_adsorption_repeated_root_and_desorption(self): + self.assertAlmostEqual(adsorb_exact(0.,1.,1.,1.,0.,1.,1.),.5);self.assertAlmostEqual(adsorb_exact(.3,1.,1.,0.,2.,1.,.5),.3/math.e) + def test_thinfilm_domain_failure_keeps_mass(self): + r=prepared(crystal=dict(CRYSTAL_EXAMPLE,max_relative_shift=1e-6),method=dict(METHOD_EXAMPLE,steps=[dict(duration_s=1.,potential_v=0.,current_a=.001)]));call(r,'acquisition.start');r.step(1.);self.assertEqual(r.failure,'THINFILM_DOMAIN');self.assertIsNone(r.frequency);self.assertGreater(r.film,0.);self.assertIsNone(r.inferred()) + def test_session_truth_dedup_owner_and_stale(self): + r=prepared();r.register_principal('a');r.register_principal('b');a=r.session('a');b=r.session('b');i=r.instance_id;self.assertNotIn('ledger.read',a.describe(instance_id=i)['capabilities']);self.assertNotIn('sample.identity',a.read(instance_id=i)['observations']);self.assertNotIn('film.true_mass_kg',a.read(instance_id=i)['observations']);v=a.invoke(instance_id=i,capability_id='acquisition.start',arguments={},request_id='one');self.assertEqual(v,a.invoke(instance_id=i,capability_id='acquisition.start',arguments={},request_id='one')) + with self.assertRaises(ActionRejected):b.poll(v['operation_id']) + r.step(1.);a.cancel(v['operation_id'],'stop');obs=a.read(instance_id=i,state_ids=['frequency.hz'])['observations']['frequency.hz'];self.assertEqual(obs['quality'],'stale');r.step(10);self.assertEqual(obs,a.read(instance_id=i,state_ids=['frequency.hz'])['observations']['frequency.hz']) + def test_instances_busy_pure_and_unsupported(self): + r=prepared();other=prepared();before=copy.deepcopy(other.__dict__);call(r,'acquisition.start') + with self.assertRaisesRegex(ActionRejected,'BUSY'):r.invoke('lid.set',lift_m=.05) + r.step(.5);self.assertEqual(other.__dict__,before);saved=copy.deepcopy(r.__dict__);r.describe();r.read();call(r,'process.measure');call(r,'ledger.read');self.assertEqual(r.__dict__,saved) + for k in UNSUPPORTED: + with self.assertRaisesRegex(ActionRejected,'UNSUPPORTED'):r.invoke(k) +if __name__=='__main__':unittest.main() diff --git a/tests/test_asset_ch_chi920d.py b/tests/test_asset_ch_chi920d.py new file mode 100644 index 0000000000000000000000000000000000000000..5738de5681874f96acc18d0e20c8f36514f41669 --- /dev/null +++ b/tests/test_asset_ch_chi920d.py @@ -0,0 +1,76 @@ +from pathlib import Path +import sys,unittest,copy,importlib.util,math +ROOT=Path(__file__).resolve().parents[1];sys.path.insert(0,str(ROOT/'scripts')) +from asset_runtime.ch_chi920d import * +sp=importlib.util.spec_from_file_location('asset_tool',ROOT/'skills/chemistry-lab-assets/scripts/asset_tool.py');tool=importlib.util.module_from_spec(sp);sp.loader.exec_module(tool) +OBSERVED=set() +def call(r,k,**a): + v=r.invoke(k,**a);err=tool.validate_value(v,CAPS[k][1]);assert not err,err;OBSERVED.add(k);return v +def prepared(plant=None,method=None,sample=None): + r=ChChi920dRuntime();call(r,'plant.configure',**(plant or copy.deepcopy(PLANT_EXAMPLE)));call(r,'method.configure',**(method or copy.deepcopy(METHOD_EXAMPLE)));call(r,'sample.load',**(sample or copy.deepcopy(SAMPLE_EXAMPLE)));call(r,'power.set',enabled=True);return r +class SECM(unittest.TestCase): + def test_metadata_schema(self): + r=prepared();m=r.describe() + for k,c in m['capabilities'].items():self.assertEqual(tool.validate_value(c['example_arguments'],c['input_schema']),[],k) + for k,v in r.read('evaluator').items():self.assertEqual(tool.validate_value(v,m['state_slots'][k]['value_schema']),[],k) + def test_pure_queries_and_targets(self): + r=prepared();q=r.q[:];call(r,'stage.move',x_m=.01,y_m=.01,z_m=.02);self.assertEqual(r.q,q);before=copy.deepcopy(r.__dict__);r.read();r.describe();call(r,'process.measure');call(r,'ledger.read');self.assertEqual(r.__dict__,before);r.step(1.);self.assertLess(math.dist(r.q,r.target),math.dist(q,r.target)) + def test_position_quantization_and_range(self): + for fine,res in [(True,1.6e-9),(False,8e-9)]: + r=prepared(plant=dict(PLANT_EXAMPLE,fine_enabled=fine));out=call(r,'stage.move',x_m=11e-9,y_m=0,z_m=.005);self.assertAlmostEqual(out['x_m']/res,round(11e-9/res));r.step(1);self.assertAlmostEqual(r.q[0],out['x_m']) + before=copy.deepcopy(r.__dict__) + with self.assertRaises(ActionRejected):r.invoke('stage.move',x_m=.025001,y_m=0,z_m=.005) + self.assertEqual(r.__dict__,before) + def test_limits_atomic_and_bad_types(self): + r=prepared() + for k,a in [('method.configure',dict(METHOD_EXAMPLE,tip_potential_v=10.01)),('method.configure',dict(METHOD_EXAMPLE,substrate_potential_v=-10.01)),('power.set',{'enabled':1}),('stage.move',dict(x_m=0.,y_m=0.,z_m=float('nan')))]: + before=copy.deepcopy(r.__dict__) + with self.assertRaises(ActionRejected):r.invoke(k,**a) + self.assertEqual(r.__dict__,before) + for dt in [True,float('nan'),-1.,float('inf')]: + with self.assertRaises(ActionRejected):r.step(dt) + def test_all_59_templates(self): + r=prepared();self.assertEqual(len(r.templates),59) + for sid in r.templates:self.assertGreater(call(r,'template.read',substance_id=sid)['diffusion_m2_s'],0) + def test_complete_conservation_and_map(self): + r=prepared();call(r,'acquisition.start');r.step(20);self.assertEqual(r.phase,'succeeded');l=call(r,'ledger.read');self.assertLess(abs(l['total_residual_mol']),1e-19);self.assertLess(abs(l['charge_residual_c']),1e-18);self.assertEqual(len(call(r,'process.measure')['points']),25);self.assertGreater(r.reduced,0.);self.assertGreater(max(p['tip_current_a'] for p in r.points),min(p['tip_current_a'] for p in r.points)) + def test_cancel_partial_and_unload(self): + r=prepared();call(r,'acquisition.start');r.step(4.);self.assertGreater(r.tip_charge,0.);call(r,'acquisition.stop');l=r._ledger();q=r.q[:];r.step(5);self.assertEqual(l,r._ledger());self.assertEqual(q,r.q) + with self.assertRaisesRegex(ActionRejected,'RETRACT_REQUIRED'):r.invoke('sample.unload') + call(r,'stage.move',x_m=0,y_m=0,z_m=.005);r.step(5);call(r,'sample.unload');self.assertLess(abs(r._ledger()['total_residual_mol']),1e-19);self.assertGreater(r.tip_charge,0) + def test_partition_invariance(self): + rs=[prepared(),prepared()] + for r in rs:call(r,'acquisition.start') + rs[0].step(20.) + for _ in range(2000):rs[1].step(.01) + for k in ['oxidized_mol','reduced_mol','tip_charge_c','substrate_charge_c']:self.assertAlmostEqual(rs[0]._ledger()[k],rs[1]._ledger()[k],delta=1e-18) + self.assertEqual([p['tip_current_a'] for p in rs[0].points],[p['tip_current_a'] for p in rs[1].points]) + def test_approach_current_and_guard(self): + path=[dict(x_m=0,y_m=0,z_m=z) for z in [50e-6,20e-6,10e-6,5e-6,2e-6]];r=prepared(method=dict(METHOD_EXAMPLE,mode='approach',path=path));call(r,'acquisition.start');r.step(20);self.assertEqual(len(r.points),5);self.assertGreater(r.points[-1]['tip_current_a'],r.points[0]['tip_current_a']) + call(r,'method.configure',**dict(METHOD_EXAMPLE,path=[dict(x_m=0,y_m=0,z_m=0.)]));before=copy.deepcopy(r.__dict__) + with self.assertRaisesRegex(ActionRejected,'COLLISION_GUARD'):r.invoke('acquisition.start') + self.assertEqual(r.__dict__,before) + def test_negative_feedback(self): + r=prepared(sample=dict(SAMPLE_EXAMPLE,base_rate_m_s=0.,patch_rate_m_s=0.));call(r,'acquisition.start');r.step(20);self.assertTrue(all(p['substrate_current_a']==0 for p in r.points));self.assertEqual(r.sub_charge,0.) + def test_steady_dwell_and_current_limit(self): + r=prepared(method=dict(METHOD_EXAMPLE,dwell_s=.001)) + with self.assertRaisesRegex(ActionRejected,'STEADY_STATE_DWELL'):r.invoke('acquisition.start') + r=prepared(plant=dict(PLANT_EXAMPLE,current_range_a=1e-11));call(r,'acquisition.start');r.step(20);self.assertEqual(r.phase,'failed');self.assertEqual(r.failure,'CURRENT_LIMIT');self.assertEqual(r.tip_charge,0.) + def test_total_two_channel_continuous_limit(self): + p=dict(PLANT_EXAMPLE,tip_radius_m=1e-4,current_range_a=.25);m=dict(METHOD_EXAMPLE,path=[dict(x_m=0.,y_m=0.,z_m=11e-6)],dwell_s=30.);sample=dict(SAMPLE_EXAMPLE,concentration_mol_m3=5e4);r=prepared(p,m,sample);call(r,'acquisition.start');r.step(60.);self.assertEqual(r.phase,'failed');self.assertEqual(r.failure,'CURRENT_LIMIT');self.assertEqual(r.tip_charge,0.);self.assertEqual(r.reduced,0.) + def test_kinetics_uses_observed_currents(self): + r=prepared(plant=dict(PLANT_EXAMPLE,current_range_a=1e-7));call(r,'acquisition.start');r.step(20);D=r.templates[SAMPLE_EXAMPLE['substance_id']]['diffusion_m2_s'];a=call(r,'kinetics.estimate',**dict(KIN_EXAMPLE,diffusion_m2_s=D));self.assertEqual(a['quality'],'estimated_surrogate');self.assertAlmostEqual(a['rate_m_s'][12]/.001001,1.,delta=.02) + r.sample['base_rate_m_s']=.9;r.sample['patch_rate_m_s']=0;r.sample['sample_id']='changed_secret';self.assertEqual(call(r,'kinetics.estimate',**dict(KIN_EXAMPLE,diffusion_m2_s=D)),a) + def test_session_truth_owner_stale(self): + r=prepared();r.register_principal('a');r.register_principal('b');a=r.session('a');b=r.session('b');i=r.instance_id;self.assertNotIn('sample.identity',a.read(instance_id=i)['observations']);self.assertNotIn('ledger.read',a.describe(instance_id=i)['capabilities']);v=a.invoke(instance_id=i,capability_id='acquisition.start',arguments={},request_id='one');self.assertEqual(v,a.invoke(instance_id=i,capability_id='acquisition.start',arguments={},request_id='one')) + with self.assertRaises(ActionRejected):b.poll(v['operation_id']) + r.step(4);a.cancel(v['operation_id'],'stop');obs=a.read(instance_id=i,state_ids=['tip.current_a'])['observations']['tip.current_a'];self.assertEqual(obs['quality'],'stale');r.step(10);later=a.read(instance_id=i,state_ids=['tip.current_a'])['observations']['tip.current_a'];self.assertEqual(obs,later) + def test_two_instances_and_busy(self): + r=prepared();other=prepared();before=copy.deepcopy(other.__dict__);call(r,'acquisition.start') + with self.assertRaisesRegex(ActionRejected,'BUSY'):r.invoke('stage.move',x_m=0,y_m=0,z_m=.005) + r.step(10);self.assertEqual(other.__dict__,before) + def test_unsupported(self): + r=prepared() + for k in UNSUPPORTED: + with self.assertRaisesRegex(ActionRejected,'UNSUPPORTED'):r.invoke(k) +if __name__=='__main__':unittest.main() diff --git a/tests/test_asset_cytiva_nanoassemblrignite.py b/tests/test_asset_cytiva_nanoassemblrignite.py new file mode 100644 index 0000000000000000000000000000000000000000..aed21b1b1965221806f64870ed82191f76ac87be --- /dev/null +++ b/tests/test_asset_cytiva_nanoassemblrignite.py @@ -0,0 +1,151 @@ +"""CHEM-060 independent regression tests; finite material, process clock and trust boundary.""" +import copy,json,math,sys,unittest +from pathlib import Path +ROOT=Path(__file__).resolve().parents[1];sys.path.insert(0,str(ROOT/'scripts')) +from asset_runtime.cytiva_nanoassemblrignite import * +def prepared(dilution=True,method=None): + h=CytivaNanoassemblrigniteRuntime();h.invoke('plant.configure',**PLANT_EXAMPLE) + h.invoke('cartridge.install',dilution=dilution,cartridge_id='chip',accept_host_attachment=True) + for x in SYRINGE_EXAMPLES:h.invoke('syringe.load',**x) + h.invoke('tubes.install',sample_capacity_m3=50e-6,accept_host_attachment=True) + h.invoke('heating.configure',installed=True,accept_host_attachment=True) + h.invoke('method.configure',**(method or dict(METHOD_EXAMPLE,dilution_ratio=1. if dilution else 0.))) + h.invoke('block.set',opened=False);h.invoke('lid.set',opened=False);h.invoke('power.set',enabled=True);return h +class IgniteTests(unittest.TestCase): + def atomic(self,h,k,**a): + before=h.debug_snapshot() + with self.assertRaises(ActionRejected):h.invoke(k,**a) + self.assertEqual(before,h.debug_snapshot()) + def conserve(self,h): + p=h.invoke('product.read') + for suffix in ['m3','kg','solute_kg']: + for i in range(3):self.assertAlmostEqual(p['initial_'+suffix][i],sum(p[loc+'_'+suffix][i] for loc in LOCS if loc!='initial'),delta=1e-11) + self.assertAlmostEqual(p['heater_input_j'],p['thermal_loss_j']+p['sensible_j'],delta=2e-7) + def test_default_conservation(self): + h=prepared();h.invoke('acquisition.start');h.step(60);self.conserve(h);self.assertEqual(h.phase,'succeeded') + def test_exact_routing_and_holdup(self): + h=prepared();h.invoke('acquisition.start');h.step(60) + self.assertAlmostEqual(sum(h.vols['sample']),3.47e-6,delta=1e-14);self.assertAlmostEqual(sum(h.vols['waste']),.5e-6,delta=1e-14) + self.assertAlmostEqual(sum(h.vols['mixer']),20e-9,delta=1e-15);self.assertAlmostEqual(sum(h.vols['dilution']),10e-9,delta=1e-15) + def test_L_not_in_primary_mixer(self): + h=prepared();h.invoke('acquisition.start');h.step(30);self.assertEqual(h.vols['mixer'][0],0.);self.assertGreater(h.vols['dilution'][0],0.) + def test_base_chip_two_inputs(self): + h=prepared(False);h.invoke('acquisition.start');h.step(60);self.assertEqual(h.vols['syringe'][0],10e-6);self.assertEqual(sum(h.vols['dilution']),0.);self.assertAlmostEqual(sum(h.vols['sample']),1.73e-6,delta=1e-14);self.conserve(h) + def test_incorrect_chip_topology_atomic(self): + h=prepared(False,dict(METHOD_EXAMPLE));self.atomic(h,'acquisition.start') + def test_20_flow_strictly_rejected(self): + h=prepared();self.atomic(h,'method.configure',**dict(METHOD_EXAMPLE,flow_m3_s=20e-6/60)) + def test_just_below_20_accepted(self): + h=prepared();h.invoke('method.configure',**dict(METHOD_EXAMPLE,flow_m3_s=math.nextafter(20e-6/60,0.))) + def test_ignite_plus_ranges_rejected(self): + h=prepared() + for args in [dict(METHOD_EXAMPLE,volume_m3=60e-6),dict(METHOD_EXAMPLE,flow_m3_s=200e-6/60)]:self.atomic(h,'method.configure',**args) + def test_method_low_flow_high_ratio(self): + h=prepared();h.invoke('method.configure',**dict(METHOD_EXAMPLE,flow_m3_s=.1e-6/60,flow_ratio_c_r=10.,dilution_ratio=1.)) + def test_L_48_limit(self): + h=prepared();h.invoke('method.configure',**dict(METHOD_EXAMPLE,flow_m3_s=8e-6/60,dilution_ratio=6.));self.atomic(h,'method.configure',**dict(METHOD_EXAMPLE,flow_m3_s=8e-6/60,dilution_ratio=6.01)) + def test_waste_sum_rejected(self): + h=prepared();self.atomic(h,'method.configure',**dict(METHOD_EXAMPLE,start_waste_equiv_m3=2e-6)) + def test_all_waste_zero_sample(self): + h=prepared(method=dict(METHOD_EXAMPLE,start_waste_equiv_m3=2e-6,end_waste_equiv_m3=0.));h.invoke('acquisition.start');h.step(60);self.assertEqual(sum(h.vols['sample']),0.);self.conserve(h) + def test_no_waste_all_output_sample(self): + h=prepared(method=dict(METHOD_EXAMPLE,start_waste_equiv_m3=0.,end_waste_equiv_m3=0.));h.invoke('acquisition.start');h.step(60);self.assertEqual(sum(h.vols['waste']),0.) + def test_finite_empty_rejection(self): + h=prepared(method=dict(METHOD_EXAMPLE,volume_m3=10e-6));self.atomic(h,'acquisition.start');self.assertFalse(h.used) + def test_tube_capacity_preflight(self): + h=prepared(method=dict(METHOD_EXAMPLE,start_waste_equiv_m3=2e-6,end_waste_equiv_m3=0.,dilution_ratio=4.)) + h.vols['waste'][0]=10e-6 + self.atomic(h,'acquisition.start') + def test_lid_interrupts_not_rejected(self): + h=prepared();h.invoke('acquisition.start');h.step(12);h.invoke('lid.set',opened=True);v=copy.deepcopy(h.vols);h.step(10);self.assertTrue(h.lid);self.assertEqual(h.phase,'cancelled');self.assertEqual(v,h.vols);self.conserve(h) + def test_power_loss_partial(self): + h=prepared();h.invoke('acquisition.start');h.step(12);h.invoke('power.set',enabled=False);v=copy.deepcopy(h.vols);h.step(10);self.assertEqual(v,h.vols);self.assertFalse(h.heating);self.conserve(h) + def test_cancel_reset_no_refund(self): + h=prepared();h.invoke('acquisition.start');h.step(12);h.invoke('acquisition.stop');v=copy.deepcopy(h.vols);pl=[h._consumed(i) for i in range(3)] + h.invoke('cycle.reset');h.step(20);self.assertEqual(h.paddle,[0.]*3);self.assertEqual(v,h.vols);self.assertEqual(pl,[h._consumed(i) for i in range(3)]) + def test_completed_paddles_home_plungers_consumed(self): + h=prepared();h.invoke('acquisition.start');h.step(60);self.assertEqual(h.paddle,[0.]*3);self.assertGreater(h._consumed(1),0.) + def test_single_use_no_second_run(self): + h=prepared();h.invoke('acquisition.start');h.step(60);self.atomic(h,'acquisition.start') + def test_prime_6mm_not_fixed_volume(self): + h=prepared();h.invoke('cartridge.prime');h.step(40) + for i in range(3):self.assertAlmostEqual(h._consumed(i),.006,delta=1e-10) + self.assertFalse(h.used);self.assertTrue(h.primed);self.assertEqual(sum(h.vols['sample']),0.);self.conserve(h) + def test_prime_then_formulate(self): + h=prepared();h.invoke('cartridge.prime');h.step(40);h.invoke('acquisition.start');h.step(60);self.conserve(h);self.assertTrue(h.used) + def test_loaded_source_rebind_rejected(self): + h=prepared();h.invoke('lid.set',opened=True);h.invoke('block.set',opened=True);h.invoke('syringe.unload',channel=1) + self.atomic(h,'syringe.load',**dict(SYRINGE_EXAMPLES[1],density_kg_m3=900.)) + def test_syringe_stroke_limit(self): + h=CytivaNanoassemblrigniteRuntime();h.invoke('plant.configure',**PLANT_EXAMPLE);self.atomic(h,'syringe.load',**dict(SYRINGE_EXAMPLES[1],inner_diameter_m=.002)) + def test_20ml_C_heated_configuration_not_assumed(self): + h=CytivaNanoassemblrigniteRuntime();h.invoke('plant.configure',**PLANT_EXAMPLE);self.atomic(h,'syringe.load',**dict(SYRINGE_EXAMPLES[1],capacity_m3=20e-6)) + def test_invalid_solute_density_rejected(self): + h=CytivaNanoassemblrigniteRuntime();h.invoke('plant.configure',**PLANT_EXAMPLE);self.atomic(h,'syringe.load',**dict(SYRINGE_EXAMPLES[1],solute_kg_m3=900.,density_kg_m3=800.)) + def test_collect_and_dispose_conservation(self): + h=prepared();h.invoke('acquisition.start');h.step(60);h.invoke('lid.set',opened=True);h.invoke('tubes.collect',recipient_id='vial');h.invoke('block.set',opened=True);h.invoke('cartridge.remove') + for i in range(3):h.invoke('syringe.unload',channel=i) + self.conserve(h);self.assertEqual(sum(h.vols['mixer']),0.);self.assertGreater(sum(h.vols['collected_sample']),0.) + def test_heater_75_and_30_achievable(self): + h=prepared();o=h.invoke('heating.set',enabled=True,targets_k=[298.15,348.15]);self.assertEqual(h.targets,[298.15,348.15]);self.assertEqual(o['effective_targets_k'],[318.15,348.15]) + h.step(1200);self.assertAlmostEqual(h.temperature[0],318.15,places=6);self.assertAlmostEqual(h.temperature[1],348.15,places=6);self.conserve(h) + def test_heater_upper_invalid_atomic(self): + h=prepared();self.atomic(h,'heating.set',enabled=True,targets_k=[348.16,298.15]) + def test_heater_option_required(self): + h=prepared();h.invoke('lid.set',opened=True);h.invoke('heating.configure',installed=False,accept_host_attachment=True);self.atomic(h,'heating.set',enabled=True,targets_k=[303.15]*2) + def test_heat_no_fluid_size_prediction(self): + h=prepared();h.invoke('heating.set',enabled=True,targets_k=[310.,315.]);h.step(200);self.assertIn('180',h.warning);self.assertFalse(h.invoke('formulation.measure')['particle_size_mapping_available']);self.conserve(h) + def test_read_and_queries_are_pure(self): + h=prepared();before=h.debug_snapshot() + for k in ['formulation.measure','product.read']:h.invoke(k) + h.invoke('reference.lookup',substance_id='lnp_atlas_913');h.read();h.session().read(instance_id=h.instance_id);self.assertEqual(before,h.debug_snapshot()) + def test_reference_methods_distinct(self): + h=prepared();x=h.invoke('reference.lookup',substance_id='lnp_atlas_913');self.assertEqual([a['method'] for a in x['measurements']],['TDA','DLS']);self.assertAlmostEqual(x['measurements'][1]['value'],93e-9);self.assertEqual(x['evidence'],'measured_literature') + def test_unknown_reference_and_nan_atomic(self): + h=prepared();self.atomic(h,'reference.lookup',substance_id='missing');self.atomic(h,'method.configure',**dict(METHOD_EXAMPLE,volume_m3=float('nan'))) + def test_permission_truth_filter(self): + h=prepared();s=h.session();self.assertNotIn('truth.ledger',s.describe(instance_id=h.instance_id)['state_slots']) + self.assertEqual(s.invoke(instance_id=h.instance_id,capability_id='product.read',arguments={},request_id='deny')['error']['code'],'ACCESS_DENIED') + with self.assertRaises(ActionRejected):s.read(instance_id=h.instance_id,state_ids=['truth.ledger']) + def test_session_idempotency_conflict(self): + h=prepared();s=h.session();kw=dict(instance_id=h.instance_id,capability_id='acquisition.start',arguments={},request_id='once') + first=s.invoke(**kw);snap=h.debug_snapshot();self.assertEqual(first,s.invoke(**kw));self.assertEqual(snap,h.debug_snapshot()) + self.assertEqual(s.invoke(**dict(kw,capability_id='acquisition.stop'))['error']['code'],'REQUEST_CONFLICT') + def test_session_owner_poll_cancel(self): + h=prepared();a=h.session();h.register_principal('other');b=h.session('other') + op=a.invoke(instance_id=h.instance_id,capability_id='acquisition.start',arguments={},request_id='a')['operation_id'];h.step(12) + with self.assertRaises(ActionRejected):b.poll(op) + a.cancel(op,'cancel');self.assertEqual(a.poll(op)['status'],'cancelled');self.conserve(h) + def test_state_write_route(self): + h=prepared();s=h.session();s.write(instance_id=h.instance_id,state_id='lid.opened',value=True,request_id='open');self.assertTrue(h.lid) + with self.assertRaises(ActionRejected):s.write(instance_id=h.instance_id,state_id='volume.sample_m3',value=1.,request_id='bad') + def test_foreign_instance_rejected(self): + h=prepared();self.assertEqual(h.session().invoke(instance_id='foreign',capability_id='power.set',arguments={'enabled':False},request_id='x')['error']['code'],'UNKNOWN_INSTANCE');self.assertTrue(h.powered) + def test_clock_and_two_instances(self): + a=prepared();b=prepared();a.invoke('acquisition.start');a.step(20);self.assertEqual(b.time_s,0.);self.assertEqual(b.phase,'idle');self.conserve(a) + def test_time_partition_consistency(self): + a=prepared();b=prepared();a.invoke('acquisition.start');b.invoke('acquisition.start');a.step(60) + for _ in range(6000):b.step(.01) + for loc in LOCS: + for x,y in zip(a.vols[loc],b.vols[loc]):self.assertAlmostEqual(x,y,delta=1e-11) + def test_zero_dt_and_invalid_dt(self): + h=prepared();snap=h.debug_snapshot();h.step(0);self.assertEqual(snap,h.debug_snapshot()) + with self.assertRaises(ActionRejected):h.step(-1) + def test_block_open_cannot_close_lid(self): + h=prepared();h.invoke('lid.set',opened=True);h.invoke('block.set',opened=True);self.atomic(h,'lid.set',opened=False) + def test_exhaustion_exact_batch(self): + h=prepared(method=dict(METHOD_EXAMPLE,volume_m3=4e-6));h.invoke('acquisition.start');h.step(100);self.assertLess(h.vols['syringe'][1],1e-15);self.assertLess(h.vols['syringe'][2],1e-15);self.conserve(h) + def test_used_chip_identity_cannot_reset(self): + h=prepared();h.invoke('acquisition.start');h.step(60);h.invoke('lid.set',opened=True);h.invoke('block.set',opened=True);h.invoke('cartridge.remove') + self.atomic(h,'cartridge.install',dilution=True,cartridge_id='chip',accept_host_attachment=True) + h.invoke('cartridge.install',dilution=True,cartridge_id='fresh_chip',accept_host_attachment=True);self.assertFalse(h.used) + def test_full_20ml_volume_with_two_10ml_syringes(self): + h=prepared(False,dict(METHOD_EXAMPLE,flow_m3_s=19.9e-6/60,flow_ratio_c_r=1.,volume_m3=20e-6,dilution_ratio=0.)) + h.invoke('lid.set',opened=True);h.invoke('block.set',opened=True) + for i in [1,2]: + h.invoke('syringe.unload',channel=i);h.invoke('syringe.load',**dict(SYRINGE_EXAMPLES[i],capacity_m3=10e-6,volume_m3=10e-6,inner_diameter_m=.0145)) + h.invoke('block.set',opened=False);h.invoke('lid.set',opened=False);h.invoke('acquisition.start');h.step(100) + self.assertEqual(h.phase,'succeeded');self.assertAlmostEqual(h.dispensed,20e-6,delta=1e-14);self.conserve(h) +if __name__=='__main__':unittest.main() + + diff --git a/tests/test_asset_edinburgh_fls1000tcspc.py b/tests/test_asset_edinburgh_fls1000tcspc.py new file mode 100644 index 0000000000000000000000000000000000000000..cff791b27b82bb6f45afc33c7c611b0514735cb4 --- /dev/null +++ b/tests/test_asset_edinburgh_fls1000tcspc.py @@ -0,0 +1,214 @@ +"""Independent numerical, event-clock, permission and negative-control regressions.""" +import copy,hashlib,json,math,pickle,sys,unittest +from pathlib import Path +import numpy as np +from scipy.integrate import quad +ROOT=Path(__file__).resolve().parents[1];sys.path.insert(0,str(ROOT/'scripts')) +from asset_runtime.edinburgh_fls1000tcspc import * +def ready(sample=None,method=None,plant=None): + h=EdinburghFls1000tcspcRuntime() + for k,a in [('plant.configure',plant or PLANT_EXAMPLE),('sample.load',sample or SAMPLE_EXAMPLE),('method.configure',method or METHOD_EXAMPLE),('sample.cover',{'opened':False}),('power.set',{'enabled':True}),('source.arm',{'enabled':True})]:h.invoke(k,**a) + return h +def collect(sample=None,method=None): + h=ready(sample,method);h.invoke('irf.start' if (sample or SAMPLE_EXAMPLE)['kind']=='scatterer' else 'acquisition.start');h.step(3);return h +class TcspcTests(unittest.TestCase): + def rejected(self,h,k,a,code=None): + old=pickle.dumps(h.debug_snapshot()) + with self.assertRaises(ActionRejected) as c:h.invoke(k,**a) + if code:self.assertEqual(str(c.exception),code) + self.assertEqual(pickle.dumps(h.debug_snapshot()),old) + def test_01_source_templates(self): + h=EdinburghFls1000tcspcRuntime();self.assertEqual(len(h.templates),67) + for t in h.templates.values(): + f=t['source_file'];self.assertEqual(hashlib.sha256((ROOT/f['path']).read_bytes()).hexdigest(),f['sha256']);self.assertIsNone(t['measured_photon_histogram']);self.assertGreater(t['lifetime_s'],0);self.assertLess(t['emission_peak_m'],900e-9) + self.assertLess(abs(h.templates['life_row_003']['lifetime_s']/4.1e-9-1),1e-14) + def test_02_not_bool_nan(self): + h=EdinburghFls1000tcspcRuntime() + for val in [True,float('nan'),float('inf')]:self.rejected(h,'plant.configure',dict(PLANT_EXAMPLE,dark_rate_s_inv=val),'INVALID_ARGUMENT') + def test_03_initialization_once(self): + h=EdinburghFls1000tcspcRuntime();h.step(.1);h.invoke('plant.configure',**PLANT_EXAMPLE);self.rejected(h,'plant.configure',PLANT_EXAMPLE,'INITIALIZATION_ONLY') + def test_04_ack_required(self): + h=EdinburghFls1000tcspcRuntime();self.rejected(h,'plant.configure',dict(PLANT_EXAMPLE,accept_surrogate_model=False),'EVIDENCE_ACK_REQUIRED') + def test_05_external_load_guards(self): + h=ready();self.rejected(h,'sample.load',SAMPLE_EXAMPLE,'EXTERNAL_LOAD_REQUIRED') + def test_06_sample_source(self): + h=EdinburghFls1000tcspcRuntime();h.invoke('plant.configure',**PLANT_EXAMPLE) + self.rejected(h,'sample.load',dict(SAMPLE_EXAMPLE,components=[{'template_id':'invented','photon_weight':1.}]),'UNKNOWN_REFERENCE') + self.rejected(h,'sample.load',dict(SAMPLE_EXAMPLE,components=[{'template_id':'life_row_003','photon_weight':.5}]),'SAMPLE_COMPOSITION') + def test_07_source_discrete(self): + h=ready();self.rejected(h,'method.configure',dict(METHOD_EXAMPLE,excitation_wavelength_m=450e-9),'INSTALLED_SOURCE_MISMATCH') + def test_08_repetition_discrete(self): + h=ready();self.rejected(h,'method.configure',dict(METHOD_EXAMPLE,repetition_hz=15e6),'INVALID_ARGUMENT') + def test_09_wavelength_grid(self): + h=ready();self.rejected(h,'method.configure',dict(METHOD_EXAMPLE,emission_wavelength_m=519.005e-9),'WAVELENGTH_STEP') + def test_10_window_period_guard(self): + h=ready();self.rejected(h,'method.configure',dict(METHOD_EXAMPLE,time_window_s=100e-9),'PERIOD_GRID_RESOURCE') + def test_11_latent_resource_guard(self): + h=ready();self.rejected(h,'method.configure',dict(METHOD_EXAMPLE,repetition_hz=20e3,time_window_s=2.5e-9),'PERIOD_GRID_RESOURCE') + def test_12_event_resource_guard(self): + h=ready();self.rejected(h,'method.configure',dict(METHOD_EXAMPLE,max_acquisition_s=1000.),'EVENT_RESOURCE_LIMIT') + def test_13_response_not_lifetime_bound(self): + h=ready();self.assertGreater(h.irf_fwhm,600e-12);self.assertNotEqual(h.irf_fwhm,5e-12) + expected=math.sqrt((75e-12)**2+(600e-12)**2+(20e-12)**2+(30e-12)**2);self.assertAlmostEqual(h.irf_fwhm/expected,1.) + def test_14_periodic_decay_independent_integral(self): + n=50;dt=1e-9;tau=15e-9;actual=exp_bins(n,dt,tau) + expected=[sum(quad(lambda t:math.exp(-t/tau)/tau,(i+k*n)*dt,(i+1+k*n)*dt,epsabs=1e-13)[0] for k in range(15)) for i in range(n)] + np.testing.assert_allclose(actual,expected,rtol=1e-12);self.assertAlmostEqual(sum(actual),1.) + def test_15_gaussian_irf_independent_erf(self): + n=1000;dt=50e-12;f=610e-12;c=2e-9;actual=wrapped_irf(n,dt,f,c);sig=f/math.sqrt(8*math.log(2)) + expected=np.array([.5*(math.erf(((i+1)*dt-c)/(math.sqrt(2)*sig))-math.erf((i*dt-c)/(math.sqrt(2)*sig))) for i in range(n)]) + np.testing.assert_allclose(actual,expected/expected.sum(),atol=1e-14) + def test_16_circular_convolution_direct(self): + a=np.arange(1.,33);a/=a.sum();b=exp_bins(32,1e-9,30e-9) + expected=[sum(a[j]*b[(i-j)%32] for j in range(32)) for i in range(32)] + np.testing.assert_allclose(convolve(a,b),expected,atol=1e-14) + def test_17_first_photon_probability(self): + mu=np.array([.1,.2,.3]);got=first_photon(mu) + np.testing.assert_allclose(got,[(1-math.exp(-.1)),math.exp(-.1)*(1-math.exp(-.2)),math.exp(-.3)*(1-math.exp(-.3))]) + self.assertAlmostEqual(got.sum(),1-math.exp(-.6));self.assertLess(np.dot(got,np.arange(3))/got.sum(),np.dot(mu,np.arange(3))/mu.sum()) + def test_18_wraparound_long_lifetime(self): + d=exp_bins(1000,50e-12,50e-6);self.assertLess(max(d)/min(d),1.002);self.assertAlmostEqual(sum(d),1.) + def test_19_chunk_invariance(self): + a=ready();b=ready() + for h in [a,b]:h.invoke('acquisition.start') + a.step(1.) + for _ in range(200):b.step(.005) + self.assertEqual(a.histograms[0]['counts'],b.histograms[0]['counts']);self.assertEqual(a._ledger()['emitted_pulses'],b._ledger()['emitted_pulses']);self.assertAlmostEqual(a.elapsed_s,b.elapsed_s) + def test_20_finite_movement(self): + h=ready();h.invoke('acquisition.start');h.step(.04);s=h.read() + self.assertEqual(s['scan.stage'],'moving');self.assertEqual(s['scan.total_counts'],0);self.assertFalse(s['source.emitting']);self.assertAlmostEqual(s['slit.width_m'],.0006);h.step(.041);self.assertEqual(h.stage,'counting') + def test_21_exact_total_stop(self): + h=collect(method=dict(METHOD_EXAMPLE,target_count=500));self.assertEqual(h.phase,'succeeded');self.assertEqual(sum(h.histograms[0]['counts']),500) + def test_22_exact_peak_stop(self): + h=collect(method=dict(METHOD_EXAMPLE,stop_kind='peak_counts',target_count=20));self.assertEqual(h.phase,'succeeded');self.assertEqual(max(h.histograms[0]['counts']),20) + def test_23_time_stop(self): + h=collect(method=dict(METHOD_EXAMPLE,stop_kind='time',max_acquisition_s=.01));self.assertAlmostEqual(h.histograms[0]['duration_s'],.01);self.assertEqual(h.histograms[0]['pulses'],200000) + def test_24_timeout_keeps_data(self): + h=collect(method=dict(METHOD_EXAMPLE,target_count=100000,max_acquisition_s=.001));self.assertEqual(h.phase,'failed');self.assertEqual(h.warning,'COUNT_TIMEOUT');self.assertGreater(sum(h.active['counts']),0);self.assertFalse(h.active['complete']) + def test_25_cancel_keeps_photons(self): + h=ready();h.invoke('acquisition.start');h.step(.09);n=h._recorded;h.invoke('acquisition.stop');h.step(1);self.assertGreater(n,0);self.assertEqual(h._recorded,n);self.assertEqual(h.phase,'cancelled') + def test_26_open_cover_stops_source(self): + h=ready();h.invoke('acquisition.start');h.step(.09);h.invoke('sample.cover',opened=True);self.assertEqual(h.phase,'cancelled');self.assertFalse(h.armed);self.assertFalse(h.read()['source.emitting']) + def test_27_power_off_stops(self): + h=ready();h.invoke('acquisition.start');h.invoke('power.set',enabled=False);self.assertEqual(h.phase,'cancelled');self.assertFalse(h.armed) + def test_28_source_disarm_stops(self): + h=ready();h.invoke('acquisition.start');h.invoke('source.arm',enabled=False);self.assertEqual(h.phase,'cancelled') + def test_29_partial_window_discard_ledger(self): + h=collect(method=dict(METHOD_EXAMPLE,time_window_s=2.5e-9,stop_kind='time',max_acquisition_s=.005));l=h._ledger();self.assertGreater(l['out_of_window_photons'],0);self.assertEqual(l['count_residual'],0);self.assertLessEqual(l['detected_first_photons'],l['emitted_pulses']) + def test_30_intact_volume_replacement(self): + h=collect();h.invoke('power.set',enabled=False);h.invoke('sample.cover',opened=True);h.invoke('sample.load',**IRF_EXAMPLE);l=h._ledger();self.assertEqual(l['current_volume_m3'],0);self.assertEqual(l['removed_volume_m3'],1e-6);self.assertAlmostEqual(l['volume_residual_m3'],0) + def test_31_irf_real_acquisition(self): + h=collect(IRF_EXAMPLE,dict(METHOD_EXAMPLE,emission_wavelength_m=405e-9));self.assertEqual(h.phase,'succeeded');self.assertEqual(sum(h.histograms[0]['counts']),5000);self.assertEqual(h.histograms[0]['response_kind'],'IRF') + def test_32_irf_kind_guard(self): + h=ready();self.rejected(h,'irf.start',{},'REFERENCE_KIND') + def test_33_scatter_wavelength_guard(self): + h=ready(IRF_EXAMPLE);self.rejected(h,'irf.start',{},'SCATTER_WAVELENGTH') + def test_34_scan_sequential(self): + h=ready(method=dict(METHOD_EXAMPLE,target_count=500));h.invoke('scan.start',wavelengths_m=[510e-9,530e-9,550e-9]);h.step(3);self.assertEqual(h.phase,'succeeded');self.assertEqual(len(h.histograms),3) + for before,after in zip(h.histograms,h.histograms[1:]):self.assertGreaterEqual(after['start_time_s']-before['start_time_s']-before['duration_s'],.04-1e-12) + def test_35_query_clock_and_no_truth(self): + h=collect();t=h.time_s;n=h._recorded + for k in ['process.measure','result.read']:self.assertNotIn('life_row',json.dumps(h.invoke(k))) + self.assertEqual(h.time_s,t);self.assertEqual(h._recorded,n);self.assertNotIn('truth.ledger',h.read());self.assertIsNotNone(h.read('evaluator')['truth.ledger']) + def test_36_no_return_alias(self): + h=collect();r=h.invoke('result.read');r['histograms'][0]['counts'][0]=999999;self.assertNotEqual(h.histograms[0]['counts'][0],999999) + def test_37_caller_only_mono_fit(self): + h=EdinburghFls1000tcspcRuntime();r=h.invoke('lifetime.fit',**CAPS['lifetime.fit'][6]);self.assertLess(abs(r['lifetimes_s'][0]/4e-9-1),.005) + def test_38_caller_bi_fit(self): + irfh=demo_hist();n=512;dt=50e-9/n;irf=wrapped_irf(n,dt,610e-12,2e-9);mu=.004*convolve(irf,exp_bins(n,dt,.5e-9))+.006*convolve(irf,exp_bins(n,dt,4e-9))+1e-6/n;h=demo_hist(4e-9);h['counts']=np.rint(h['pulses']*first_photon(mu)).astype(int).tolist() + r=EdinburghFls1000tcspcRuntime().invoke('lifetime.fit',histogram=h,irf_histogram=irfh,initial_lifetimes_s=[.7e-9,3e-9]);np.testing.assert_allclose(r['lifetimes_s'],[.5e-9,4e-9],rtol=.03) + def test_39_das_fixed_taus(self): + h=EdinburghFls1000tcspcRuntime();r=h.invoke('das.fit',**CAPS['das.fit'][6]);self.assertEqual(len(r['wavelength_m']),2);self.assertLess(abs(r['photon_amplitudes_per_pulse'][0][0]/.01-1),.005) + def test_40_fit_rejects_partial_or_wrong_irf(self): + h=EdinburghFls1000tcspcRuntime();a=copy.deepcopy(CAPS['lifetime.fit'][6]);a['histogram']['complete']=False;self.rejected(h,'lifetime.fit',a,'ANALYSIS_INPUT') + a=copy.deepcopy(CAPS['lifetime.fit'][6]);a['irf_histogram']['response_kind']='decay';self.rejected(h,'lifetime.fit',a,'IRF_GRID_MISMATCH') + def test_41_full_period_fit_guard(self): + h=EdinburghFls1000tcspcRuntime();a=copy.deepcopy(CAPS['lifetime.fit'][6]);a['histogram']['period_s']=100e-9;self.rejected(h,'lifetime.fit',a,'FULL_PERIOD_REQUIRED') + def test_42_session_permissions(self): + h=ready();s=h.session();r=s.invoke(instance_id=h.instance_id,capability_id='product.read',arguments={},request_id='x');self.assertEqual(r['error']['code'],'ACCESS_DENIED') + with self.assertRaises(ActionRejected):s.read(instance_id=h.instance_id,state_ids=['truth.ledger']) + self.assertNotIn('sample.load',s.describe(instance_id=h.instance_id)['capabilities']) + def test_43_idempotency_cancel(self): + h=ready();s=h.session();kw=dict(instance_id=h.instance_id,capability_id='acquisition.start',arguments={},request_id='start');a=s.invoke(**kw);self.assertEqual(s.invoke(**kw),a);self.assertEqual(h._op_count,1);h.step(.09);s.cancel(a['operation_id'],'cancel');self.assertEqual(s.poll(a['operation_id'])['status'],'cancelled') + r=s.invoke(instance_id=h.instance_id,capability_id='acquisition.stop',arguments={},request_id='start');self.assertEqual(r['error']['code'],'REQUEST_CONFLICT') + def test_44_owner_only_poll(self): + h=ready();h.register_principal('b');a=h.session().invoke(instance_id=h.instance_id,capability_id='acquisition.start',arguments={},request_id='a') + with self.assertRaises(ActionRejected):h.session('b').poll(a['operation_id']) + def test_45_unsupported(self): + h=ready() + for cap in UNSUPPORTED:self.rejected(h,cap,CAPS[cap][6],'UNSUPPORTED') + def test_46_actual_measurement_fit(self): + ir=collect(IRF_EXAMPLE,dict(METHOD_EXAMPLE,emission_wavelength_m=405e-9,target_count=20000,max_acquisition_s=.3)) + signal=collect(method=dict(METHOD_EXAMPLE,target_count=20000,max_acquisition_s=.3)) + r=signal.invoke('lifetime.fit',histogram=signal.histograms[0],irf_histogram=ir.histograms[0],initial_lifetimes_s=[3e-9]);self.assertLess(abs(r['lifetimes_s'][0]/4.1e-9-1),.10) + def test_47_all_real_templates_run(self): + h=EdinburghFls1000tcspcRuntime() + for sid,t in h.templates.items(): + q=collect(dict(SAMPLE_EXAMPLE,components=[{'template_id':sid,'photon_weight':1.}]),dict(METHOD_EXAMPLE,emission_wavelength_m=t['emission_peak_m'],target_count=100)) + self.assertEqual(q.phase,'succeeded');self.assertEqual(q._ledger()['count_residual'],0) + def test_48_sample_timestamp(self): + h=collect();h.step(1);s=h.session().read(instance_id=h.instance_id,state_ids=['scan.total_counts']);o=s['observations']['scan.total_counts'];self.assertLess(o['sample_time_s'],h.time_s);self.assertEqual(o['sample_time_s'],h.histograms[-1]['last_sample_time_s']) + def test_49_empty_signal_not_invented(self): + h=ready();s=h.read();self.assertEqual(s['scan.total_counts'],0);self.assertIsNone(s['scan.mean_microtime_s']);self.assertIsNone(s['scan.last_sample_time_s']) + def test_50_irf_transfer_and_units(self): + h=ready();self.assertAlmostEqual(h.read()['method.bin_width_s']/(50e-9/1024),1.);self.assertGreater(h.irf_fwhm,h.read()['method.bin_width_s']);self.assertEqual(SLOTS['scan.mean_microtime_s'][1],'s') + def test_51_historical_method_snapshot(self): + h=collect();before=h.invoke('result.read');h.invoke('method.configure',**dict(METHOD_EXAMPLE,target_count=123,emission_wavelength_m=530e-9));self.assertEqual(h.invoke('result.read')['settings_json'],before['settings_json']) + h.invoke('acquisition.start');h.step(2);self.assertEqual(json.loads(h.invoke('result.read')['settings_json'])['target_count'],123) + def test_52_documented_tcspc_channels_not_mcs_channels(self): + h=ready() + for bins in [512,1024,2048,4096,8192]: + h.invoke('method.configure',**dict(METHOD_EXAMPLE,bins=bins));self.assertAlmostEqual(h.read()['method.bin_width_s']*bins/50e-9,1.) + for bins in [500,1000,2000,4000,8000]:self.rejected(h,'method.configure',dict(METHOD_EXAMPLE,bins=bins),'INVALID_ARGUMENT') + self.assertEqual(len(demo_hist()['counts']),512);self.assertEqual(METHOD_EXAMPLE['bins'],1024) + def test_53_zero_or_underflowed_period_rejects_with_protocol_error(self): + for cap in ['lifetime.fit','das.fit']: + for period in [0.,5e-324]: + with self.subTest(cap=cap,period=period): + h=EdinburghFls1000tcspcRuntime();a=copy.deepcopy(CAPS[cap][6]);histograms=[a['histogram']] if cap=='lifetime.fit' else a['histograms'] + for hist in [*histograms,a['irf_histogram']]:hist['period_s']=period;hist['edges_s']=[i/len(hist['counts'])*period for i in range(len(hist['counts'])+1)] + before=pickle.dumps(h.debug_snapshot());reply=h.session().invoke(instance_id=h.instance_id,capability_id=cap,arguments=a,request_id='bad-grid') + self.assertEqual(reply['status'],'rejected');self.assertEqual(reply['error']['code'],'ANALYSIS_INPUT');self.assertEqual(before,pickle.dumps(h.debug_snapshot()));json.dumps(reply,allow_nan=False) + def test_54_numerically_invisible_lifetime_does_not_return_initial_guess(self): + a=copy.deepcopy(CAPS['lifetime.fit'][6]);a['initial_lifetimes_s']=[5e-12] + for hist in [a['histogram'],a['irf_histogram']]:hist['period_s']=50e-6;hist['edges_s']=np.linspace(0,50e-6,len(hist['counts'])+1).tolist() + self.rejected(EdinburghFls1000tcspcRuntime(),'lifetime.fit',a,'FIT_UNIDENTIFIABLE') + def test_55_zero_photon_acquisition_has_real_observation_window(self): + h=ready(sample=dict(SAMPLE_EXAMPLE,mean_photons_per_pulse_at_peak=1e-8),plant=dict(PLANT_EXAMPLE,dark_rate_s_inv=0.),method=dict(METHOD_EXAMPLE,stop_kind='time',max_acquisition_s=1e-5));h.invoke('acquisition.start');h.step(.081) + hist=h.histograms[0];self.assertEqual(hist['pulses'],200);self.assertEqual(sum(hist['counts']),0);self.assertIsNone(hist['last_sample_time_s']);end=hist['start_time_s']+hist['duration_s'] + observations=h.session().read(instance_id=h.instance_id,state_ids=['scan.total_counts','scan.peak_counts','scan.mean_microtime_s'])['observations'] + for observation in observations.values():self.assertEqual(observation['sample_time_s'],end);self.assertEqual(observation['sample_window_s'],[hist['start_time_s'],end]) + self.assertEqual(observations['scan.total_counts']['value'],0);self.assertIsNone(observations['scan.mean_microtime_s']['value']);self.assertEqual(observations['scan.mean_microtime_s']['quality'],'unavailable') + def test_56_accumulated_count_window_includes_no_photon_tail(self): + h=collect(method=dict(METHOD_EXAMPLE,stop_kind='time',max_acquisition_s=.005));hist=h.histograms[0];end=hist['start_time_s']+hist['duration_s'];before=pickle.dumps(h.debug_snapshot()) + observations=h.session().read(instance_id=h.instance_id,state_ids=['scan.total_counts','scan.last_sample_time_s'])['observations'];total=observations['scan.total_counts'] + self.assertGreater(end,hist['last_sample_time_s']);self.assertEqual(total['sample_time_s'],end);self.assertEqual(total['sample_window_s'],[hist['start_time_s'],end]);self.assertEqual(observations['scan.last_sample_time_s']['value'],hist['last_sample_time_s']);self.assertEqual(before,pickle.dumps(h.debug_snapshot())) + def test_57_historical_completion_preserves_public_summary_and_window(self): + h=ready(method=dict(METHOD_EXAMPLE,stop_kind='time',max_acquisition_s=.005));h.register_principal('other');s=h.session();op=s.invoke(instance_id=h.instance_id,capability_id='acquisition.start',arguments={},request_id='first')['operation_id'];h.step(1);terminal=s.poll(op) + self.assertEqual(terminal['status'],'succeeded');self.assertAlmostEqual(terminal['result']['elapsed_s'],.085);self.assertEqual(terminal['observations']['scan.total_counts'],s.read(instance_id=h.instance_id,state_ids=['scan.total_counts'])['observations']['scan.total_counts']) + s.invoke(instance_id=h.instance_id,capability_id='acquisition.start',arguments={},request_id='second');before=pickle.dumps(h.debug_snapshot());self.assertEqual(s.poll(op),terminal);terminal['result']['total_counts']=-1;self.assertGreater(s.poll(op)['result']['total_counts'],0) + self.assertNotIn('life_row',json.dumps(s.poll(op)));self.assertNotIn(SAMPLE_EXAMPLE['sample_id'],json.dumps(s.poll(op))) + with self.assertRaisesRegex(ActionRejected,'ACCESS_DENIED'):h.session('other').poll(op) + self.assertEqual(before,pickle.dumps(h.debug_snapshot())) + def test_58_cancel_historical_terminal_does_not_stop_new_counting(self): + h=ready(method=dict(METHOD_EXAMPLE,target_count=1000));s=h.session();old=s.invoke(instance_id=h.instance_id,capability_id='acquisition.start',arguments={},request_id='old')['operation_id'];h.step(1) + current=s.invoke(instance_id=h.instance_id,capability_id='acquisition.start',arguments={},request_id='new')['operation_id'];h.step(.0001);revision=h.revision;ledger=h._ledger() + reply=s.cancel(old,'cancel-old');self.assertEqual(reply['result']['phase'],'succeeded');self.assertEqual(h.phase,'running');self.assertEqual(h.operation_id,current);self.assertEqual(h.revision,revision);self.assertEqual(h._ledger(),ledger);self.assertEqual(s.cancel(old,'cancel-old'),reply) + with self.assertRaisesRegex(ActionRejected,'REQUEST_CONFLICT'):s.cancel(current,'cancel-old') + self.assertEqual(h.phase,'running') + def test_59_failed_and_cancelled_partial_histories_survive_later_start(self): + for status in ['failed','cancelled']: + with self.subTest(status=status): + h=ready(method=dict(METHOD_EXAMPLE,target_count=100000,max_acquisition_s=.001));s=h.session();op=s.invoke(instance_id=h.instance_id,capability_id='acquisition.start',arguments={},request_id='first')['operation_id'];h.step(.0805) + if status=='cancelled':s.cancel(op,'cancel') + else:h.step(.002) + terminal=s.poll(op);self.assertEqual(terminal['status'],status);self.assertGreater(terminal['result']['total_counts'],0);self.assertFalse(h.active['complete']);counts=copy.deepcopy(h.active['counts']);ledger=h._ledger();h.step(1);self.assertEqual(h.active['counts'],counts);self.assertEqual(h._ledger(),ledger) + s.invoke(instance_id=h.instance_id,capability_id='acquisition.start',arguments={},request_id='next');self.assertEqual(s.poll(op),terminal) + def test_60_metadata_matches_method_targets_and_step_optics(self): + h=ready();m=export_edinburgh_fls1000tcspc_contract_metadata();caps=m['capabilities'];before=h.read('evaluator');h.invoke('method.configure',**dict(METHOD_EXAMPLE,time_window_s=25e-9,emission_wavelength_m=520e-9));configured=h.read('evaluator');effects=caps['method.configure']['state_effects'] + self.assertTrue(all(e['timing']=='immediate' for e in effects));self.assertLessEqual({key for key in before if before[key]!=configured[key]},{e['state_id'] for e in effects});self.assertEqual(configured['mono.wavelength_m'],before['mono.wavelength_m']);self.assertNotIn('truth.ledger',{e['state_id'] for e in effects}) + h.invoke('acquisition.start');started=h.read('evaluator');immediate={e['state_id'] for e in caps['acquisition.start']['state_effects'] if e['timing']=='immediate'};later={e['state_id'] for e in caps['acquisition.start']['state_effects'] if e['timing']=='on_step'} + self.assertLessEqual({key for key in configured if configured[key]!=started[key]},immediate);self.assertNotIn('mono.wavelength_m',immediate);h.step(.04);advanced=h.read('evaluator');self.assertLessEqual({key for key in started if started[key]!=advanced[key]},later);self.assertFalse(advanced['source.emitting']);self.assertGreater(advanced['slit.width_m'],started['slit.width_m']) + self.assertEqual(caps['lifetime.fit']['observes'],[]);self.assertEqual(caps['das.fit']['observes'],[]);self.assertEqual(m['state_slots']['scan.total_counts']['sampling']['mode'],'integral') +if __name__=='__main__':unittest.main() + diff --git a/tests/test_asset_elementar_isoprimeprecision.py b/tests/test_asset_elementar_isoprimeprecision.py new file mode 100644 index 0000000000000000000000000000000000000000..6f324e9ece28598151ff788799577bd2d185c252 --- /dev/null +++ b/tests/test_asset_elementar_isoprimeprecision.py @@ -0,0 +1,560 @@ +"""tests for CHEM-090 elementar_isoprimeprecision (Elementar isoprime precisION IRMS with centrION): python3 -m unittest tests/test_asset_elementar_isoprimeprecision.py + +Themes: contract consistency (slots, effects, errors raised vs declared); agent / evaluator truth isolation (unknown samples); idempotent request +ids; two instances isolated; step-partition independence (noise included); rejected calls leave the state unchanged; every output validated +against its schema and every success changes only declared slots; pump-down within 12 h (calibrated), power failure with the isolation valve; +magnet mass range (1-76 amu at 3 kV); continuous-flow CO2 against reference pulses (17O correction, internal precision <= 0.06 permil), +normalisation with reference materials recovering an unknown; dual inlet internal precision (<= 0.010 / 0.016 permil 2 sigma at 100 bar uL); +H2 with the H3+ factor (<= 8 ppm/nA); N2; ratio linearity; non-selected inlet vented; resistor switching and saturation; faults (helium, filament, +vacuum leak, magnet drift, empty reference gas); ledgers (sample, reference and dual-inlet moles; helium) close exactly.""" +import json +import math +import re +import sys +import unittest +from pathlib import Path + +ROOT = Path(__file__).resolve().parents[1] +sys.path.insert(0, str(ROOT / 'scripts')) +from asset_runtime import elementar_isoprimeprecision as rt # noqa: E402 + +INST = 'elementar_isoprimeprecision_01' +CHECKS = [] +SEEN_CAPS = set() +PROCESS_EVIDENCE = {} +CO2_REF = {'13C': -0.0367, '18O': 0.0251} + + +def _differ(x, y): + if isinstance(x, float) and isinstance(y, float): + return abs(x - y) > 1e-12 * max(1.0, abs(x), abs(y)) + return json.dumps(x, sort_keys=True, default=str) != json.dumps(y, sort_keys=True, default=str) + + +class Rig: + def __init__(self, seed=1, instance=INST, **plant): + self.h = rt.ElementarIsoprimeprecisionRuntime(instance) + self.h.register_principal('agent', 'agent') + self.h.register_principal('eval', 'evaluator') + self.A = self.h.session('agent') + self.E = self.h.session('eval') + self.n = 0 + self.inst = instance + self.call(self.E, 'plant.configure', **dict(rt.PLANT_EXAMPLE, noise_seed=seed, **plant)) + + def call(self, sess, cap, expect='succeeded', **args): + self.n += 1 + before, t0 = self.h.read('evaluator'), self.h.t + r = sess.invoke(instance_id=self.inst, capability_id=cap, arguments=args, request_id=f'r{self.n}') + after = self.h.read('evaluator') + changed = {k for k in after if _differ(after[k], before[k])} - {'clock.time_s'} + if expect == 'succeeded': + assert r['status'] == 'succeeded', (cap, r['error']) + rt.validate(rt.CAPS[cap]['output_schema'], r['result']) + if cap != 'sim.step': + extra = changed - set(rt.EFFECTS.get(cap, [])) + assert not extra, (cap, sorted(extra)) + assert self.h.t == t0, cap + SEEN_CAPS.add(cap) + PROCESS_EVIDENCE.setdefault(cap, []).append(dict(arguments=json.dumps(args, sort_keys=True, default=str)[:200], time_s=t0, status=r['status'])) + return r['result'] + assert r['status'] in ('rejected', 'unsupported'), (cap, r['status'], r.get('result')) + assert r['error']['code'] == expect, (cap, r['error']['code'], expect) + assert not changed, (cap, 'rejected call changed', sorted(changed)) + assert expect in [e['code'] for e in rt.export_elementar_isoprimeprecision_contract_metadata()['capabilities'][cap]['errors']], (cap, expect) + return r + + def step(self, s): + self.call(self.E, 'sim.step', dt_s=float(s)) + + def read(self, *ids, who=None): + sess = who or self.E + o = sess.read(instance_id=self.inst, state_ids=list(ids) if ids else None)['observations'] + return {k: v['value'] for k, v in o.items()} if not ids or len(ids) > 1 else o[ids[0]]['value'] + + def ready(self, species='CO2', ref=1, deltas=None): + self.call(self.A, 'power.set', on=True) + self.step(600.0) + self.call(self.A, 'source.set', filament=True) + self.call(self.A, 'magnet.set_species', species=species) + self.call(self.A, 'centrion.set', inlet=1, carrier_on=True) + self.call(self.A, 'reference.assign', gas=ref, deltas=deltas or CO2_REF) + + def peaks(self, since=0): + return self.call(self.A, 'results.read', since_peak=since)['peaks'] + + def ledger(self): + return self.call(self.E, 'ledger.read')['ledger'] + + +def _raised_codes(): + src = Path(rt.__file__).read_text() + funcs = {} + for m in re.finditer(r'\n def (\w+)\(self[^\n]*\n(.*?)(?=\n def |\n# ----|\nclass |\ndef )', src, re.S): + funcs[m.group(1)] = m.group(2) + own = {k: set(re.findall(r"ActionRejected\('([A-Z_]+)'\)", v)) for k, v in funcs.items()} + calls = {k: set(re.findall(r'self\.(_\w+)\(', v)) & set(funcs) for k, v in funcs.items()} + out = {} + for k in funcs: + if not k.startswith('_cmd_'): + continue + seen, todo, codes = set(), [k], set() + while todo: + f = todo.pop() + if f in seen: + continue + seen.add(f) + codes |= own.get(f, set()) + todo += [g for g in calls.get(f, ()) if g not in ('_cmd_sim_step', 'step', '_tick')] + out[k] = codes + name = {'_cmd_' + c.replace('.', '_'): c for c in rt.CAPS} + return {name[k]: v for k, v in out.items() if k in name} + + +def _balance(test, L): + for sp, inj in L['injected_mol'].items(): + tot = L['vented_mol'].get(sp, 0.0) + L['source_mol'].get(sp, 0.0) + L['ionised_mol'].get(sp, 0.0) + L['in_flight_mol'].get(sp, 0.0) + test.assertAlmostEqual(tot, inj, delta=1e-9 * inj, msg=sp) + for sp, inj in L['ref_injected_mol'].items(): + tot = L['ref_vented_mol'].get(sp, 0.0) + L['ref_source_mol'].get(sp, 0.0) + L['ref_ionised_mol'].get(sp, 0.0) + test.assertAlmostEqual(tot, inj, delta=1e-12 + 1e-9 * inj, msg='ref ' + sp) + test.assertAlmostEqual(L['di_consumed_mol'], L['di_source_mol'] + L['di_ionised_mol'], delta=1e-15 + 1e-9 * L['di_consumed_mol']) + test.assertAlmostEqual(L['di_loaded_mol'], L['di_consumed_mol'] + L['di_left_mol'] + L['di_evacuated_mol'], delta=1e-15 + 1e-9 * L['di_loaded_mol']) + + +def _cf_run(g, samples, pulses=3, pulse_a=None, duration=None): + pul = [dict(gas=1, start_s=20.0 + 40.0 * k, duration_s=20.0, **({'intensity_a': pulse_a[k]} if pulse_a else {})) for k in range(pulses)] + dur = duration or (40.0 * pulses + 140.0 * len(samples) + 120.0) + g.call(g.A, 'acquisition.start', duration_s=dur, reference_pulses=pul) + for k, (kw, amount) in enumerate(samples): + g.call(g.A, 'sample.inject', inlet=1, species=g.h.magnet['species'], amount_mol=amount, delay_s=40.0 * pulses + 10.0 + 140.0 * k, **kw) + g.step(dur + 1.0) + + +class Contract(unittest.TestCase): + def test_metadata_slots_effects_consistent(self): + meta = rt.export_elementar_isoprimeprecision_contract_metadata() + slots = set(meta['state_slots']) + self.assertEqual(slots, set(rt.SLOTS)) + for k, c in meta['capabilities'].items(): + for e in c['state_effects']: + self.assertIn(e['state_id'], slots, k) + self.assertTrue({'INVALID_ARGUMENT', 'REQUEST_CONFLICT', 'UNKNOWN_INSTANCE'} <= {e['code'] for e in c['errors']}, k) + for p in c['preconditions']: + for s in p['state_ids']: + self.assertIn(s, slots, k) + self.assertTrue(rt.SCENE_MIRRORED <= slots) + for name, p in meta['mechanisms']['irms_process']['parameters'].items(): + self.assertEqual(name, name.lower()) + self.assertIn(p['evidence'], ('documented', 'assumption'), name) + + def test_declared_errors_cover_raised_codes(self): + meta = rt.export_elementar_isoprimeprecision_contract_metadata() + for cap, codes in _raised_codes().items(): + declared = {e['code'] for e in meta['capabilities'][cap]['errors']} + self.assertTrue(codes <= declared, (cap, sorted(codes - declared))) + + def test_unsupported_capabilities(self): + g = Rig() + for k in rt.UNSUPPORTED: + g.call(g.A, k, expect='UNSUPPORTED') + + def test_agent_truth_isolation(self): + g = Rig() + g.ready() + g.call(g.E, 'sample.declare', sample_id='leaf_a', deltas={'13C': -0.0281}) + _cf_run(g, [(dict(sample_id='leaf_a'), 4e-6)], pulses=1) + self.assertFalse(any(k.startswith('truth.') for k in g.read(who=g.A))) + p = [q for q in g.peaks() if q['type'] == 'sample'][0] + self.assertNotIn('truth', p) + self.assertNotIn('label', p) # unknown sample: the label is not leaked + for cap, a in (('truth.inspect', {}), ('ledger.read', {}), ('sim.step', dict(dt_s=1.0)), ('sample.declare', dict(sample_id='x', deltas={})), + ('fault.inject', dict(fault='vacuum_leak', active=True))): + r = g.A.invoke(instance_id=INST, capability_id=cap, arguments=a, request_id='x' + cap) + self.assertEqual(r['error']['code'], 'ACCESS_DENIED') + g.call(g.E, 'fault.inject', fault='magnet_drift', active=True) + self.assertFalse(any(e['kind'] in ('fault', 'truth') for e in g.call(g.A, 'events.read', since_s=0.0)['events'])) + g.call(g.E, 'truth.inspect') + + def test_idempotent_request_ids(self): + g = Rig() + a = g.A.invoke(instance_id=INST, capability_id='power.set', arguments=dict(on=True), request_id='same') + b = g.A.invoke(instance_id=INST, capability_id='power.set', arguments=dict(on=True), request_id='same') + self.assertEqual(a, b) + c = g.A.invoke(instance_id=INST, capability_id='power.set', arguments=dict(on=False), request_id='same') + self.assertEqual(c['error']['code'], 'REQUEST_CONFLICT') + + def test_two_instances_isolated(self): + a, b = Rig(instance='i1'), Rig(instance='i2') + a.call(a.A, 'power.set', on=True) + self.assertFalse(b.read('power.on')) + + def test_step_partition_independence(self): + runs = [] + for parts in ([400.0], [0.3, 7.7, 92.0, 300.0], [1.0] * 40 + [360.0]): + g = Rig(seed=7) + g.ready() + g.call(g.A, 'acquisition.start', duration_s=380.0, reference_pulses=[dict(gas=1, start_s=20.0, duration_s=20.0)]) + g.call(g.A, 'sample.inject', inlet=1, species='CO2', amount_mol=3e-6, substance_id='usgs40', delay_s=60.0) + for p in parts: + g.step(p) + v = g.read() + v.pop('clock.time_s') + runs.append(json.dumps([v, g.peaks()], sort_keys=True, default=str)) + self.assertEqual(runs[0], runs[1]) + self.assertEqual(runs[0], runs[2]) + + def test_rejections_change_nothing(self): + r = rt.ElementarIsoprimeprecisionRuntime('fresh') + r.register_principal('a', 'agent') + self.assertEqual(r.session('a').invoke(instance_id='fresh', capability_id='power.set', arguments=dict(on=True), request_id='p')['error']['code'], 'PLANT_REQUIRED') + g = Rig(vented=True) + g.call(g.E, 'plant.configure', expect='SEED_FIXED', **dict(rt.PLANT_EXAMPLE, noise_seed=2)) + g.call(g.E, 'plant.configure', expect='CONFIG_FIXED', **dict(rt.PLANT_EXAMPLE, inlets=['gc', None, None, None, None])) + g.call(g.E, 'sample.declare', expect='NAME_TAKEN', sample_id='usgs40', deltas={'13C': 0.0}) + g.call(g.A, 'source.set', expect='POWER_OFF', filament=True) + g.call(g.A, 'power.set', on=True) + g.call(g.A, 'source.set', expect='VACUUM_NOT_READY', filament=True) # vented + g.call(g.A, 'magnet.peak_center', expect='NO_SPECIES') + g.call(g.A, 'magnet.set_species', expect='OUT_OF_RANGE', species='SO2', ) if g.h.source['acceleration_v'] > 3500 else None + g.call(g.A, 'source.set', acceleration_v=5000.0) + g.call(g.A, 'magnet.set_species', expect='OUT_OF_RANGE', species='SO2') # 66 u > 45.6 u at 5 kV + g.call(g.A, 'source.set', acceleration_v=3000.0) + g.call(g.A, 'centrion.set', expect='INLET_EMPTY', inlet=3) + g.call(g.A, 'sample.inject', expect='NO_CARRIER', inlet=1, species='CO2', amount_mol=1e-6, substance_id='usgs40') + g.call(g.A, 'centrion.set', inlet=1, carrier_on=True) + g.call(g.A, 'sample.inject', expect='WRONG_INLET', inlet=5, species='CO2', amount_mol=1e-6, substance_id='usgs40') + g.call(g.A, 'sample.inject', expect='UNKNOWN_SAMPLE', inlet=1, species='CO2', amount_mol=1e-6, sample_id='nothing') + g.call(g.A, 'sample.inject', expect='NO_DELTA_FOR_SPECIES', inlet=1, species='N2', amount_mol=1e-6, substance_id='usgs24') + g.call(g.A, 'sample.inject', expect='INVALID_ARGUMENT', inlet=1, species='CO2', amount_mol=1e-6) + g.call(g.A, 'acquisition.start', expect='NO_SPECIES', duration_s=60.0) + g.call(g.A, 'magnet.set_species', species='CO2') + g.call(g.A, 'acquisition.start', expect='SOURCE_OFF', duration_s=60.0) + g.call(g.A, 'reference.assign', expect='NO_REFERENCE_GAS', gas=4, deltas={'13C': 0.0}) + g.call(g.A, 'reference.assign', expect='INVALID_ARGUMENT', gas=1, deltas={'15N': 0.0}) + g.call(g.A, 'dual_inlet.start', expect='SOURCE_OFF', species='CO2', substance_id='nbs19', sample_bar_ul=100.0, reference_gas=1) + g.call(g.A, 'h3.determine', expect='NEED_H2_PULSES', run=1) + g.call(g.A, 'calibration.normalize', expect='UNKNOWN_PEAK', isotope='13C', standards=[dict(peak=1, substance_id='usgs40'), dict(peak=2, substance_id='usgs41')]) + g.call(g.A, 'amplifier.configure', expect='INVALID_ARGUMENT', mode='fixed') + g.call(g.E, 'fault.inject', expect='GAS_REQUIRED', fault='reference_gas_empty', active=True) + g.call(g.E, 'fault.inject', expect='INVALID_ARGUMENT', fault='alien', active=True) + + +class Physics(unittest.TestCase): + def test_pump_down_within_12_h_and_status(self): + g = Rig(vented=True) + self.assertEqual(g.read('vacuum.state'), 'vented') + g.call(g.A, 'power.set', on=True) + self.assertEqual(g.read('status.led'), 'amber') + self.assertEqual([g.read('indicator.led_' + k) for k in ('green', 'amber', 'red')], [k == 'amber' for k in ('green', 'amber', 'red')]) + g.call(g.A, 'vacuum.pump_down') + g.step(11.0 * 3600.0) + self.assertEqual(g.read('vacuum.state'), 'pumping') + g.step(1.05 * 3600.0) + self.assertEqual(g.read('vacuum.state'), 'ready') # brochure: within 12 h without bakeout + self.assertLessEqual(g.read('truth.process')['pressure_pa'], rt.ENG['vacuum_ready_pa']) + g.call(g.A, 'source.set', filament=True) + self.assertEqual(g.read('status.led'), 'green') + self.assertEqual([g.read('indicator.led_' + k) for k in ('green', 'amber', 'red')], [k == 'green' for k in ('green', 'amber', 'red')]) + g.call(g.A, 'vacuum.vent', expect='FILAMENT_ON') + g.call(g.A, 'source.set', filament=False) + g.call(g.A, 'vacuum.vent') + self.assertEqual(g.read('vacuum.state'), 'vented') + self.assertIsNone(g.read('vacuum.pressure_pa')) + + def test_power_failure_isolation_valve(self): + g = Rig() + g.ready() + g.call(g.E, 'fault.inject', fault='mains_outage', active=True) + self.assertEqual(g.read('vacuum.state'), 'isolated') + self.assertFalse(g.read('source.state')['filament']) + self.assertEqual(g.read('status.led'), 'off') + self.assertEqual([g.read('indicator.led_' + k) for k in ('green', 'amber', 'red')], [k == 'off' for k in ('green', 'amber', 'red')]) + g.step(600.0) + p_sealed = g.read('truth.process')['pressure_pa'] + self.assertGreater(p_sealed, 0.05) # sealed analyser: pressure rises + g.call(g.E, 'fault.inject', fault='mains_outage', active=False) + self.assertEqual(g.read('vacuum.state'), 'isolated') + g.step(rt.ENG['turbo_spinup_s'] + 1.0) + self.assertEqual(g.read('vacuum.state'), 'ready') # turbo at speed: valve reopened + self.assertIn('ISOLATION_OPEN', [e['code'] for e in g.call(g.A, 'events.read', since_s=0.0)['events']]) + g.call(g.A, 'source.set', filament=True) + + def test_magnet_mass_range(self): + self.assertLess(rt.ElementarIsoprimeprecisionRuntime()._max_mass(3000.0) - 76.0, 1e-9) + g = Rig() + g.ready() + self.assertAlmostEqual(g.read('magnet.state')['field_t'], rt.b_for(45.0, 3000.0) * (1 + 4e-4), places=12) + g.call(g.A, 'source.set', acceleration_v=4000.0) # field follows the voltage + self.assertAlmostEqual(g.read('magnet.state')['field_t'], rt.b_for(45.0, 4000.0), places=12) + g.call(g.A, 'source.set', expect='OUT_OF_RANGE', acceleration_v=5000.0) # 46 u > 45.6 u + self.assertEqual(g.read('magnet.state')['masses'], [44, 45, 46]) + + def test_cf_co2_deltas_precision_and_normalisation(self): + g = Rig() + g.ready() + g.call(g.E, 'sample.declare', sample_id='leaf_a', deltas={'13C': -0.0281}) + _cf_run(g, [(dict(substance_id='usgs40'), 4e-6), (dict(substance_id='usgs41'), 4e-6), (dict(sample_id='leaf_a'), 4e-6)], pulses=10) + peaks = g.peaks() + refs = [p for p in peaks if p['type'] == 'reference'] + smp = [p for p in peaks if p['type'] == 'sample'] + self.assertEqual((len(refs), len(smp)), (10, 3)) + # internal precision of the monitoring gas: SD of the reference pulses' 45/44 against their mean + r45 = [p['ratios']['45/44'] for p in refs] + m = sum(r45) / len(r45) + sd = math.sqrt(sum((x / m - 1) ** 2 for x in r45) / (len(r45) - 1)) * 1000.0 + self.assertLess(sd, rt.DOC['cf_precision_permil']['co2_13c']) # brochure: <= 0.06 permil 1 sigma + self.assertAlmostEqual(smp[0]['delta_ref']['13C'], rt.RM['usgs40']['values']['13C']['delta'], delta=2e-4) + self.assertAlmostEqual(smp[0]['delta_ref']['18O'], rt.PLANT_EXAMPLE['combustion_o2_delta18o'], delta=3e-4) + n = g.call(g.A, 'calibration.normalize', isotope='13C', standards=[dict(peak=smp[0]['peak'], substance_id='usgs40'), + dict(peak=smp[1]['peak'], substance_id='usgs41')]) + self.assertAlmostEqual(n['slope'], 1.0, delta=0.01) + leaf = [p for p in g.peaks() if p['type'] == 'sample'][2] + self.assertAlmostEqual(leaf['delta_normalized']['13C'], -0.0281, delta=1.5e-4) + self.assertEqual(g.read('results.count'), 13) + _balance(self, g.ledger()) + + def test_dual_inlet_precision(self): + g = Rig() + g.ready() + r = g.call(g.A, 'dual_inlet.start', species='CO2', substance_id='nbs19', sample_bar_ul=100.0, reference_gas=1, cycles=10) + self.assertEqual(g.read('acquisition.state')['mode'], 'dual_inlet') + g.step(r['ends_s'] - g.h.t + 1.0) + p = g.peaks()[-1] + self.assertEqual(p['type'], 'dual_inlet') + self.assertEqual(p['cycles'], 10) + lim = rt.DOC['di_precision_permil_2s'] + self.assertLess(2000.0 * p['internal_se']['13C'], lim['co2_13c']) # brochure: <= 0.010 permil 2 sigma + self.assertLess(2000.0 * p['internal_se']['18O'], lim['co2_18o']) + self.assertAlmostEqual(p['delta_ref']['13C'], rt.RM['nbs19']['values']['13C']['delta'], delta=3e-5) + self.assertAlmostEqual(p['delta_ref']['18O'], rt.RM['nbs19']['values']['18O']['delta'], delta=4e-5) + _balance(self, g.ledger()) + g.step(0.05) # start between two 0.1 s grid points + r = g.call(g.A, 'dual_inlet.start', species='CO2', substance_id='nbs19', sample_bar_ul=100.0, reference_gas=1, cycles=4) + self.assertAlmostEqual(r['ends_s'] - (g.h.t + 0.05), 9 * (20.0 + rt.ENG['di_switch_s']), places=9) # first block at the next grid point + g.step(r['ends_s'] - g.h.t + 1.0) + self.assertEqual(g.peaks()[-1]['cycles'], 4) + _balance(self, g.ledger()) + + def test_h2_h3_factor_and_normalisation(self): + g = Rig(reference_gases=[dict(species='H2', deltas={'2H': -0.150}), None, None, None, None, None]) + g.ready('H2', deltas={'2H': -0.150}) + _cf_run(g, [], pulses=5, pulse_a=[2e-9, 4e-9, 6e-9, 8e-9, 10e-9], duration=230.0) + k = g.call(g.A, 'h3.determine', run=1) + self.assertLess(k['factor_ppm_na'], rt.DOC['h3_factor_max_ppm_na']) # brochure: <= 8.0 ppm/nA + self.assertAlmostEqual(k['factor_ppm_na'], rt.ENG['h3_factor_ppm_na'], delta=0.3) + _cf_run(g, [(dict(substance_id='vsmow2'), 4e-6), (dict(substance_id='slap2'), 4e-6), (dict(substance_id='gisp2'), 4e-6)], pulses=1) + smp = [p for p in g.peaks() if p['type'] == 'sample'][-3:] + g.call(g.A, 'calibration.normalize', isotope='2H', standards=[dict(peak=smp[0]['peak'], substance_id='vsmow2'), dict(peak=smp[1]['peak'], substance_id='slap2')]) + gisp2 = [p for p in g.peaks() if p['type'] == 'sample'][-1] + self.assertAlmostEqual(gisp2['delta_normalized']['2H'], rt.RM['gisp2']['values']['2H']['delta'], delta=1.5e-3) + self.assertGreater(g.read('calibration.state')['h3_factor_ppm_na'], 0.0) + + def test_n2_and_linearity(self): + g = Rig() + g.ready('N2', ref=2, deltas={'15N': -0.0012}) + amps = [2e-9, 4e-9, 6e-9, 8e-9, 10e-9, 12e-9] + g.call(g.A, 'acquisition.start', duration_s=420.0, reference_pulses=[dict(gas=2, start_s=10.0 + 35.0 * k, duration_s=20.0, intensity_a=a) + for k, a in enumerate(amps)]) + g.call(g.A, 'sample.inject', inlet=1, species='N2', amount_mol=4e-6, substance_id='usgs40', delay_s=230.0) + g.step(421.0) + refs = [p for p in g.peaks() if p['type'] == 'reference'] + xs = [a * 1e9 for a in amps] + ys = [(p['ratios']['29/28'] / refs[0]['ratios']['29/28'] - 1) * 1000.0 for p in refs] + mx, my = sum(xs) / len(xs), sum(ys) / len(ys) + slope = sum((x - mx) * (y - my) for x, y in zip(xs, ys)) / sum((x - mx) ** 2 for x in xs) # permil per nA (least squares) + self.assertLess(abs(slope), rt.DOC['cf_linearity_permil_na']['n2_15n']) # brochure: <= 0.02 permil/nA + smp = [p for p in g.peaks() if p['type'] == 'sample'][0] + self.assertAlmostEqual(smp['delta_ref']['15N'], rt.RM['usgs40']['values']['15N']['delta'], delta=3e-4) + + def test_unselected_inlet_vents_and_saturation(self): + g = Rig() + g.ready() + g.call(g.A, 'acquisition.start', duration_s=300.0) + g.call(g.A, 'sample.inject', inlet=2, species='CO2', amount_mol=4e-6, substance_id='usgs40', delay_s=20.0) # inlet 1 selected + g.step(301.0) + self.assertEqual(g.peaks(), []) + L = g.ledger() + self.assertAlmostEqual(L['vented_mol']['CO2'], 4e-6, delta=1e-15) + g.call(g.A, 'acquisition.start', duration_s=300.0) + g.call(g.A, 'sample.inject', inlet=1, species='CO2', amount_mol=4e-4, substance_id='usgs40', delay_s=20.0) # 100 times larger: auto resistor step-down + g.step(301.0) + p = g.peaks()[-1] + self.assertFalse(p['saturated']) + self.assertLess(g.read('amplifier.state')['resistors_ohm']['44'], rt.ENG['default_resistors_ohm']['CO2'][0]) + g.call(g.A, 'amplifier.configure', mode='fixed', resistors_ohm=[1e11, 1e11, 1e11]) + g.call(g.A, 'acquisition.start', duration_s=300.0) + g.call(g.A, 'sample.inject', inlet=1, species='CO2', amount_mol=4e-6, substance_id='usgs40', delay_s=20.0) + g.step(301.0) + self.assertTrue(g.peaks()[-1]['saturated']) + _balance(self, g.ledger()) + + def test_faults(self): + g = Rig() + g.ready() + g.call(g.E, 'fault.inject', fault='vacuum_leak', active=True) + g.step(1.0) + self.assertFalse(g.read('source.state')['filament']) # vacuum trip + self.assertIn('VACUUM_TRIP', [e['code'] for e in g.call(g.A, 'events.read', since_s=0.0)['events']]) + g.call(g.E, 'fault.inject', fault='vacuum_leak', active=False) + g.step(60.0) + g.call(g.A, 'source.set', filament=True) + g.call(g.E, 'fault.inject', fault='magnet_drift', active=True) + g.step(5 * 86400.0) + off = g.read('truth.process')['field_offset_t'] + self.assertGreater(abs(off), 1e-4) + c = g.call(g.A, 'magnet.peak_center') + self.assertAlmostEqual(c['offset_t'], off, delta=1e-9) + g.call(g.E, 'fault.inject', fault='magnet_drift', active=False) + g.call(g.E, 'fault.inject', fault='reference_gas_empty', active=True, gas=1) + _cf_run(g, [], pulses=1, duration=60.0) + self.assertEqual([p for p in g.peaks() if p['type'] == 'reference'], []) + g.call(g.E, 'fault.inject', fault='reference_gas_empty', active=False, gas=1) + g.call(g.E, 'fault.inject', fault='he_supply_empty', active=True) + g.step(1.0) + self.assertEqual(g.read('status.led'), 'red') + self.assertEqual([g.read('indicator.led_' + k) for k in ('green', 'amber', 'red')], [k == 'red' for k in ('green', 'amber', 'red')]) + self.assertFalse(g.read('centrion.state')['carrier_on']) + g.call(g.A, 'centrion.set', expect='NO_HELIUM', carrier_on=True) + g.call(g.E, 'fault.inject', fault='he_supply_empty', active=False) + g.call(g.E, 'fault.inject', fault='filament_burnout', active=True) + self.assertFalse(g.read('source.state')['filament']) + g.call(g.E, 'fault.inject', fault='filament_burnout', active=False) + g.call(g.A, 'source.set', expect='FILAMENT_FAILED', filament=True) + g.call(g.A, 'hood.set', angle_rad=1.9) + self.assertEqual(g.read('hood.angle_rad'), 1.9) + g.call(g.A, 'acquisition.stop') + _balance(self, g.ledger()) + + def test_quiet_stepping_helium_and_power_toggle(self): + g = Rig() + g.ready() + n = g.h.tick + he0 = g.ledger()['he_used_m3'] + g.step(30 * 86400.0) # nothing measured: closed-form jump + self.assertEqual(g.h.tick - n, int(round(30 * 86400.0 / rt.DT))) + self.assertAlmostEqual(g.ledger()['he_used_m3'] - he0, rt.ENG['carrier_he_m3_s'] * 30 * 86400.0, delta=1e-9) + self.assertGreater(g.read('source.state')['filament_hours'], 700.0) + g.call(g.A, 'centrion.set', sleep=True) + g.call(g.A, 'power.toggle') + self.assertFalse(g.read('power.on')) + + +class ReviewFixes(unittest.TestCase): + """Regressions of the round-1 review (H3+ repeat, quiet-interval events, filament replacement, dual-inlet stop, auto ranging).""" + + def test_h3_repeat_is_idempotent(self): + g = Rig(reference_gases=[dict(species='H2', deltas={'2H': -0.150}), None, None, None, None, None]) + g.ready('H2', deltas={'2H': -0.150}) + _cf_run(g, [], pulses=5, pulse_a=[2e-9, 4e-9, 6e-9, 8e-9, 10e-9], duration=230.0) + k1 = g.call(g.A, 'h3.determine', run=1)['factor_ppm_na'] + k2 = g.call(g.A, 'h3.determine', run=1)['factor_ppm_na'] + self.assertAlmostEqual(k1, k2, places=12) # a repeat on the same run does not add up + _cf_run(g, [], pulses=5, pulse_a=[2e-9, 4e-9, 6e-9, 8e-9, 10e-9], duration=230.0) # a later run processed with the factor + k3 = g.call(g.A, 'h3.determine', run=2)['factor_ppm_na'] + self.assertAlmostEqual(k3, k1, delta=0.3) + self.assertLess(k3, rt.DOC['h3_factor_max_ppm_na']) + + def test_quiet_events_do_not_depend_on_the_partition(self): + out = [] + for parts in ([100.0], [0.1] * 1000, [0.05] * 2000, [7.3] * 13 + [5.1]): + g = Rig() + g.ready() + g.call(g.E, 'fault.inject', fault='vacuum_leak', active=True) + for dt in parts: + g.step(dt) + ev = [e for e in g.call(g.A, 'events.read', since_s=0.0)['events'] if e['code'] == 'VACUUM_TRIP'] + out.append((round(g.read('source.state')['filament_hours'], 12), ev[0]['time_s'])) + self.assertTrue(all(o == out[0] for o in out), out) + life = [] + for parts in ([30 * 86400.0] * 6, [86400.0] * 180): + g = Rig() + g.ready() + for dt in parts: + g.step(dt) + ev = [e for e in g.call(g.A, 'events.read', since_s=0.0)['events'] if e['code'] == 'FILAMENT_BURNT'] + life.append((ev[0]['time_s'], g.ledger()['he_used_m3'])) + self.assertAlmostEqual(life[0][0], life[1][0], places=6) + self.assertAlmostEqual(life[0][1], life[1][1], delta=1e-15) + + def test_filament_replacement_and_dual_inlet_stop(self): + g = Rig() + g.ready() + g.call(g.E, 'fault.inject', fault='filament_burnout', active=True) + g.call(g.A, 'source.replace_filament', expect='NOT_VENTED') + g.call(g.A, 'vacuum.vent') + g.call(g.A, 'source.replace_filament', expect='HOOD_CLOSED') + g.call(g.A, 'hood.set', angle_rad=1.6) + g.call(g.A, 'source.replace_filament', expect='FAULT_ACTIVE') + g.call(g.E, 'fault.inject', fault='filament_burnout', active=False) + r = g.call(g.A, 'source.replace_filament') + self.assertEqual(r['source']['filament_hours'], 0.0) + g.call(g.A, 'hood.set', angle_rad=0.0) + g.call(g.A, 'vacuum.pump_down') + g.step(12 * 3600.0) + g.call(g.A, 'source.set', filament=True) + g.call(g.A, 'dual_inlet.start', species='CO2', substance_id='nbs19', sample_bar_ul=100.0, reference_gas=1, cycles=10) + g.step(250.0) + r = g.call(g.A, 'acquisition.stop') + self.assertIsNotNone(r['run']) + self.assertEqual(g.read('acquisition.state'), {}) + p = g.peaks()[-1] + self.assertEqual(p['type'], 'dual_inlet') + self.assertLess(p['cycles'], 10) + _balance(self, g.ledger()) + + def test_drifted_beams_give_no_delta_and_no_crash(self): + g = Rig() + g.ready() + g.call(g.E, 'fault.inject', fault='magnet_drift', active=True) + g.step(4 * 86400.0) + r = g.call(g.A, 'dual_inlet.start', species='CO2', substance_id='nbs19', sample_bar_ul=100.0, reference_gas=1, cycles=4) + g.step(r['ends_s'] - g.h.t + 1.0) + p = g.peaks()[-1] + json.dumps(p) # real numbers only + self.assertTrue(p['delta_ref'] is None or all(isinstance(v, float) for v in p['delta_ref'].values())) + _balance(self, g.ledger()) + + def test_off_grid_run_end_and_helium_alarm_time(self): + res = [] + for parts in ([150.0], None, [0.07] * 2200): + g = Rig() + g.ready() + r = g.call(g.A, 'acquisition.start', duration_s=100.05, reference_pulses=[dict(gas=1, start_s=20.0, duration_s=20.0)]) + self.assertAlmostEqual(r['ends_s'] * 10.0, round(r['ends_s'] * 10.0), places=6) # end on the 0.1 s grid + for dt in (parts or [r['ends_s'] - g.h.t, 50.0]): + g.step(dt) + p = g.peaks()[0] + res.append((p['area_vs'], [e['time_s'] for e in g.call(g.A, 'events.read', since_s=0.0)['events'] if e['code'] == 'RUN_END'])) + self.assertTrue(all(x == res[0] for x in res), res) + times = [] + for parts in ([40000.0], [7.3] * 5480): + g = Rig(he_supply_gauge_pa=5.0e4) + g.ready() + for dt in parts: + g.step(dt) + times.append([e['time_s'] for e in g.call(g.A, 'events.read', since_s=0.0)['events'] if e['code'] == 'HELIUM_EMPTY']) + t_exp = 600.0 + (rt.ENG['he_supply_m3'] * 5.0e4 / 101325.0 - 0.0) / rt.ENG['carrier_he_m3_s'] + self.assertEqual(times[0], times[1]) + self.assertTrue(len(times[0]) == 1 and abs(times[0][0] - t_exp) < 1e-3, (times, t_exp)) + + def test_auto_ranging_restarts_at_each_acquisition(self): + g = Rig() + g.ready() + g.call(g.A, 'acquisition.start', duration_s=300.0) + g.call(g.A, 'sample.inject', inlet=1, species='CO2', amount_mol=4e-4, substance_id='usgs40', delay_s=20.0) + g.step(301.0) + self.assertLess(g.read('amplifier.state')['resistors_ohm']['44'], rt.ENG['default_resistors_ohm']['CO2'][0]) + g.call(g.A, 'acquisition.start', duration_s=60.0) + self.assertEqual(g.read('amplifier.state')['resistors_ohm'], {}) + + +class ZCoverage(unittest.TestCase): + def test_all_capabilities_exercised(self): + missing = set(rt.CAPS) - set(rt.UNSUPPORTED) - SEEN_CAPS + if len(SEEN_CAPS) > 5: + self.assertFalse(missing, sorted(missing)) + + +if __name__ == '__main__': + unittest.main() diff --git a/tests/test_asset_elementar_varioel.py b/tests/test_asset_elementar_varioel.py new file mode 100644 index 0000000000000000000000000000000000000000..1f29e6fb573802b40709b5a1d3e629aac2429026 --- /dev/null +++ b/tests/test_asset_elementar_varioel.py @@ -0,0 +1,199 @@ +"""Independent process, numerical and protocol regressions for CHEM-079 only.""" +import copy,json,math,sys,unittest +from pathlib import Path +import numpy as np +ROOT=Path(__file__).resolve().parents[1];sys.path.insert(0,str(ROOT/'scripts')) +from asset_runtime import elementar_varioel as r + +def finish(h,dt=.25): + for _ in range(2000): + if h.phase!='running':return + h.step(dt) + raise AssertionError('sequence failed to terminate') +def ready(plant=None,method=None,library=None,instance_id='test_varioel'): + h=r.ElementarVarioelRuntime(instance_id,library=library);h.invoke('plant.configure',**dict(dict(r.PLANT_EXAMPLE,tcd_noise_sd=0.),**(plant or {})));h.invoke('method.configure',**dict(r.METHOD_EXAMPLE,**(method or {})));h.invoke('furnace.configure',**r.FURNACE_EXAMPLE);h.invoke('power.set',enabled=True);h.step(1.5);return h +def load(h,slot=0,kind='sample',mass=2e-6,template='oem_sulfanilic_acid',**extra): + a=copy.deepcopy(r.BLANK_EXAMPLE if kind=='blank' else r.SAMPLE_EXAMPLE);a.update(slot_index=slot,kind=kind,mass_kg=0. if kind=='blank' else mass,template_id='' if kind=='blank' else template,**extra);h.invoke('sample.load',**a) +def run(h,slots):h.invoke('sequence.configure',slot_indices=slots);h.invoke('sequence.start');finish(h);return h.invoke('result.read') +def blank(h):load(h,kind='blank');run(h,[0]);return h + +def calibrated(plant=None,method=None): + h=blank(ready(plant,method));masses=[1e-6,2e-6,3e-6] + for slot,m in enumerate(masses,1):load(h,slot,'standard',m) + result=run(h,[1,2,3]) + for e in r.MODES[h.method['mode']]: + obs=[dict(reference_id='oem_sulfanilic_acid',sample_mass_kg=m,peak_area_s=q['areas_s'][e]) for m,q in zip(masses,result['completed_assays'])];h.invoke('calibration.fit',element=e,observations=obs,accept_same_method_basis=True) + return h + +class ElementarProcessTests(unittest.TestCase): + def reject_atomic(self,h,code,cap,**args): + before=repr(h.debug_snapshot()) + with self.assertRaisesRegex(r.ActionRejected,code):h.invoke(cap,**args) + self.assertEqual(before,repr(h.debug_snapshot())) + def closed(self,h): + q=h.invoke('product.read');self.assertLess(max(abs(x) for x in q['tracked_elements_kg']['residual'].values()),1e-17);self.assertLess(abs(q['unmeasured_residual_kg']),1e-17);self.assertLess(abs(q['oxygen_residual_mol']),1e-12);self.assertLess(abs(q['thermal_residual_j']),1e-7) + def test_source_measurements_are_not_calculated_values(self): + h=ready();q=json.loads(h.invoke('template.read',substance_id='oem_sulfanilic_acid')['template_json']);self.assertEqual(q['element_mass_fractions']['C'],.4168);self.assertIsNone(q['calculated_reference_percent']['C']);self.assertIsNone(q['peak_trace']) + def test_unknown_template_atomic(self): + h=ready();self.reject_atomic(h,'UNKNOWN_REFERENCE','template.read',substance_id='not-a-source') + def test_reported_source_sum_rejected_not_normalized(self): + for fractions in [{e:.4 for e in r.ELEMENTS},{'C':.5,'H':.5,'N':5e-13,'S':0.}]: + lib=r._library();lib['compounds']['oem_sulfanilic_acid']['element_mass_fractions']=fractions;h=ready(library=lib);self.reject_atomic(h,'SOURCE_COMPOSITION_RANGE','sample.load',**r.SAMPLE_EXAMPLE) + def test_source_unknown_ack_required(self): + h=ready();self.reject_atomic(h,'UNKNOWN_CONDITIONS','sample.load',**dict(r.SAMPLE_EXAMPLE,accept_unknown_conditions=False)) + def test_reported_values_cannot_be_host_overwritten(self): + h=ready();a=dict(r.SAMPLE_EXAMPLE,assumed_unreported_fractions=dict(r.SAMPLE_EXAMPLE['assumed_unreported_fractions'],C=.8),accept_assumed_missing_elements=True);self.reject_atomic(h,'REPORTED_VALUE_OVERRIDE','sample.load',**a) + def test_source_basis_mismatch(self): + h=ready();self.reject_atomic(h,'SOURCE_BASIS_MISMATCH','sample.load',**dict(r.SAMPLE_EXAMPLE,mass_basis='assumed_dry')) + def test_organic_mass_limit(self): + h=ready();self.reject_atomic(h,'SAMPLE_MASS_LIMIT','sample.load',**dict(r.SAMPLE_EXAMPLE,mass_kg=20.01e-6)) + def test_each_absolute_element_capacity(self): + for j,e in enumerate(r.ELEMENTS): + with self.subTest(element=e): + lib=r._library();lib['compounds']['oem_sulfanilic_acid']['element_mass_fractions']={z:1. if z==e else 0. for z in r.ELEMENTS};h=ready(library=lib);self.reject_atomic(h,'ELEMENT_MASS_LIMIT','sample.load',**dict(r.SAMPLE_EXAMPLE,sample_class='inorganic',mass_kg=float(r.ELEMENT_LIMITS[j]*1.01))) + def test_unknown_s_capacity_uses_remainder_bound(self): + h=ready();self.reject_atomic(h,'ELEMENT_MASS_LIMIT','sample.load',**dict(r.SAMPLE_EXAMPLE,template_id='ep0459505_compound_01',sample_class='inorganic',mass_kg=1.4e-3)) + def test_chn_missing_s_retained_as_unknown(self): + h=blank(ready(method={'mode':'CHN'}));load(h,template='ep0459505_compound_01');q=run(h,[0])['completed_assays'][0];self.assertIsNone(q['areas_s']['S']);self.assertIsNone(q['fractions']['S']);self.assertEqual(q['source_fraction_evidence']['S'],'unreported_unknown_not_zero');self.assertGreater(h._ledger()['unmeasured_retained_kg'],0);self.closed(h) + def test_chns_missing_s_rejected_before_consumption(self): + h=blank(ready());load(h,template='ep0459505_compound_01');h.invoke('sequence.configure',slot_indices=[0]);self.reject_atomic(h,'UNREPORTED_MODE_ELEMENT','sequence.start');self.assertIn(0,h.samples) + def test_explicit_missing_s_assumption_has_evidence(self): + h=blank(ready());a=dict(r.SAMPLE_EXAMPLE,template_id='ep0459505_compound_01',assumed_unreported_fractions=dict(r.SAMPLE_EXAMPLE['assumed_unreported_fractions'],S=.01));self.reject_atomic(h,'MISSING_ELEMENT_ACK_REQUIRED','sample.load',**a);a['accept_assumed_missing_elements']=True;h.invoke('sample.load',**a);q=run(h,[0])['completed_assays'][0];self.assertIn('host_assumption',q['source_fraction_evidence']['S']) + def test_zero_sample_mass_not_blank(self): + h=ready();self.reject_atomic(h,'SAMPLE_MASS_LIMIT','sample.load',**dict(r.SAMPLE_EXAMPLE,mass_kg=0.)) + def test_blank_cannot_hide_sample_mass(self): + h=ready();self.reject_atomic(h,'BLANK_COMPOSITION','sample.load',**dict(r.BLANK_EXAMPLE,mass_kg=1e-6)) + def test_top_loading_needs_no_front_door(self): + h=ready();self.assertFalse(h.opened);load(h);self.assertIn(0,h.samples) + def test_duplicate_slot_rejects_without_inventory_change(self): + h=ready();load(h);self.reject_atomic(h,'SLOT_OCCUPIED','sample.load',**r.SAMPLE_EXAMPLE) + def test_tray_unload_preserves_all_mass(self): + h=ready();load(h);q=h.invoke('sample.unload',slot_index=0,recipient_id='rack');self.assertEqual(q['mass_kg'],2e-6);self.assertFalse(h.samples);self.closed(h) + def test_thermal_exact_first_order_and_net_heat(self): + h=ready();h.invoke('power.set',enabled=False);old=h.temperature.copy();h.step(.17);expected=298.15+(old-298.15)*math.exp(-5*.17);np.testing.assert_allclose(h.temperature,expected,rtol=1e-14);self.closed(h) + def test_furnace_target_does_not_teleport_temperature(self): + h=ready();old=h.temperature.copy();h.invoke('furnace.configure',combustion_k=1473.15,reduction_k=1200.);np.testing.assert_array_equal(h.temperature,old);self.assertFalse(h._ready());h.step(.1);self.assertLess(h.temperature[0],1473.15) + def test_tin_flash_is_not_allowed_furnace_setting(self): + h=ready();self.reject_atomic(h,'INVALID_ARGUMENT','furnace.configure',combustion_k=2073.15,reduction_k=1123.15) + def test_room_temperature_cannot_run_combustion(self): + h=ready();h.invoke('furnace.configure',combustion_k=298.15,reduction_k=298.15);h.step(2);load(h,kind='blank');h.invoke('sequence.configure',slot_indices=[0]);self.reject_atomic(h,'REACTION_TEMPERATURE_LIMIT','sequence.start') + def test_hot_powered_maintenance_rejected(self): + h=ready();self.reject_atomic(h,'COLD_SERVICE_REQUIRED','furnace.extend',extension_m=.12) + def test_cold_slide_requires_door_and_return_before_closing(self): + h=ready();h.invoke('power.set',enabled=False);h.step(2);self.reject_atomic(h,'COLD_SERVICE_REQUIRED','furnace.extend',extension_m=.12);h.invoke('cover.set',opened=True);h.invoke('furnace.extend',extension_m=.12);self.reject_atomic(h,'RETRACT_FURNACE_REQUIRED','cover.set',opened=False);self.reject_atomic(h,'POWER_INTERLOCK','power.set',enabled=True);h.invoke('furnace.extend',extension_m=0.);h.invoke('cover.set',opened=False) + def test_unique_queue_consumes_once(self): + h=blank(ready());load(h);self.reject_atomic(h,'DUPLICATE_SLOT','sequence.configure',slot_indices=[0,0]);run(h,[0]);self.assertNotIn(0,h.samples);self.reject_atomic(h,'EMPTY_SLOT','sequence.start') + def test_empty_and_unblanked_queue_atomic(self): + h=ready();self.reject_atomic(h,'EMPTY_SLOT','sequence.start');load(h);h.invoke('sequence.configure',slot_indices=[0]);self.reject_atomic(h,'MATCHED_BLANK_REQUIRED','sequence.start') + def test_blank_first_with_sample_in_same_queue(self): + h=ready();load(h,kind='blank');load(h,slot=4);q=run(h,[0,4]);self.assertEqual([x['kind'] for x in q['completed_assays']],['blank','sample']);self.assertTrue(h._blank_valid());self.closed(h) + def test_sample_before_first_blank_rejected(self): + h=ready();load(h,slot=0);load(h,slot=1,kind='blank');h.invoke('sequence.configure',slot_indices=[0,1]);self.reject_atomic(h,'MATCHED_BLANK_REQUIRED','sequence.start') + def test_finite_carousel_and_ball_transfer(self): + h=blank(ready());load(h,slot=40);h.invoke('sequence.configure',slot_indices=[40]);h.invoke('sequence.start');h.step(.01);self.assertGreater(h.carousel,0);self.assertLess(h.carousel,math.pi);self.assertIn(40,h.samples) + while h.stage!='ball_open':h.step(max(1e-8,h._due())) + h.step(.005);self.assertGreater(h.ball,0);self.assertLess(h.ball,math.pi/2);self.assertIn(40,h.samples);h.step(.02);self.assertNotIn(40,h.samples);self.assertIsNotNone(h._current) + def test_apt_order_and_nonoverlapping_assigned_gates(self): + h=blank(ready());load(h);q=run(h,[0])['completed_assays'][0];groups=[] + for p in q['chromatogram']: + if p['element']!='baseline' and (not groups or groups[-1]!=p['element']):groups.append(p['element']) + self.assertEqual(groups,['N','C','H','S']);points=q['chromatogram'];self.assertTrue(all(a['time_s']<=b['sample_window_s'][0]+1e-12 for a,b in zip(points,points[1:]))) + def test_peak_area_independently_integrates_samples(self): + h=blank(ready());load(h);q=run(h,[0])['completed_assays'][0] + for e in r.ELEMENTS:self.assertAlmostEqual(q['areas_s'][e],sum(p['corrected_signal']*(p['sample_window_s'][1]-p['sample_window_s'][0]) for p in q['chromatogram'] if p['element']==e),places=14) + def test_baseline_offset_does_not_change_corrected_areas(self): + results=[] + for baseline in [.01,.7]: + h=blank(ready(plant={'tcd_baseline':baseline}));load(h);results.append(run(h,[0])['completed_assays'][0]['areas_s']) + np.testing.assert_allclose(list(results[0].values()),list(results[1].values()),atol=1e-14,rtol=0) + def test_finite_conversion_and_oxygen_stoichiometry(self): + h=blank(ready(method={'combustion_s':.001}));load(h);q=run(h,[0]);led=h._ledger();inputm=np.array([h.templates['oem_sulfanilic_acid']['element_mass_fractions'][e]*2e-6 for e in r.ELEMENTS]);converted=inputm*(-math.expm1(-.12));self.assertAlmostEqual(led['oxygen_consumed_mol'],float(converted@r.O2_PER_ELEMENT_KG),places=15);np.testing.assert_allclose(list(led['tracked_elements_kg']['retained_residue'].values()),inputm-converted,atol=1e-20);self.closed(h) + def test_oxygen_limited_conversion_preserves_unconverted_mass(self): + h=blank(ready(method={'oxygen_dose_mol':1e-9}));load(h);run(h,[0]);q=h._ledger();self.assertLessEqual(q['oxygen_consumed_mol'],1.000001e-9);self.assertGreater(sum(q['tracked_elements_kg']['retained_residue'].values()),1e-6);self.closed(h) + def test_oxygen_supply_checked_for_entire_queue(self): + h=ready(plant={'oxygen_inventory_mol':.0005});load(h,kind='blank');load(h,slot=1,kind='blank');h.invoke('sequence.configure',slot_indices=[0,1]);self.reject_atomic(h,'OXYGEN_SUPPLY_LIMIT','sequence.start') + def test_carrier_and_heated_line_interlocks(self): + for parameter in ['carrier_ready','heated_line_ready']: + h=ready(plant={parameter:False});load(h,kind='blank');h.invoke('sequence.configure',slot_indices=[0]);self.reject_atomic(h,'GAS_PATH_NOT_READY','sequence.start') + def test_prior_peak_tails_remain_real_inventory(self): + h=blank(ready(method={'baseline_threshold':.01}));load(h);run(h,[0]);q=h._ledger();self.assertGreater(sum(q['tracked_elements_kg']['tails'].values()),0);old=sum(q['tracked_elements_kg']['exhaust'].values());h.step(.1);self.assertGreater(sum(h._ledger()['tracked_elements_kg']['exhaust'].values()),old);self.closed(h) + def test_unselected_elements_have_explicit_mass_account(self): + h=blank(ready(method={'mode':'CN'}));load(h);q=run(h,[0])['completed_assays'][0];self.assertIsNone(q['areas_s']['H']);self.assertIsNone(q['areas_s']['S']);self.assertGreater(h._ledger()['tracked_elements_kg']['unselected_exhaust']['S'],0);self.closed(h) + def test_apt_timeout_keeps_partial_observations_and_mass(self): + h=blank(ready(method={'maximum_release_s':.03}));load(h);run(h,[0]);self.assertEqual(h.phase,'failed');self.assertEqual(h.warning,'APT_BASELINE_TIMEOUT');self.assertGreater(len(h._active['chromatogram']),0);self.assertIn('failed',h._active['status']);self.assertFalse(h._result()['complete']);self.closed(h) + def test_cancel_after_transfer_quarantines_and_cold_recovers(self): + h=blank(ready());load(h);h.invoke('sequence.configure',slot_indices=[0]);h.invoke('sequence.start') + while h.stage!='combustion':h.step(max(1e-8,h._due())) + h.step(.05);h.invoke('sequence.stop');self.assertEqual(h.phase,'cancelled');self.assertEqual(h.ball,0);self.assertNotIn(0,h.samples);self.reject_atomic(h,'RECOVER_CANCELLED','sequence.start');self.reject_atomic(h,'COLD_SERVICE','sample.unload',slot_index=0,recipient_id='waste');h.invoke('power.set',enabled=False);h.step(2);h.invoke('cover.set',opened=True);h.invoke('furnace.extend',extension_m=.12);amount=h.invoke('sample.unload',slot_index=0,recipient_id='waste')['mass_kg'];self.assertGreater(amount,0);self.assertLessEqual(amount,2e-6);self.assertIsNone(h._current);self.closed(h) + def test_door_interrupts_without_resurrecting_sample(self): + h=blank(ready());load(h);h.invoke('sequence.configure',slot_indices=[0]);h.invoke('sequence.start') + while h.stage!='release':h.step(max(1e-8,h._due())) + h.invoke('cover.set',opened=True);self.assertEqual(h.phase,'cancelled');self.assertEqual(h.warning,'MAINTENANCE_DOOR_OPEN');old=h.temperature.copy();h.step(.2);self.assertTrue(np.all(h.temperature0 for v in q['areas_s'].values()));self.assertEqual(q['fractions'],r._nulls()) + def test_observed_three_standard_fit_recovers_unknown(self): + h=calibrated();self.assertTrue(h.invoke('calibration.read')['ready']);load(h);q=run(h,[0])['completed_assays'][0] + for e in r.ELEMENTS:self.assertAlmostEqual(q['fractions'][e],h.templates['oem_sulfanilic_acid']['element_mass_fractions'][e],delta=2e-6) + def test_calibration_uses_observed_area_not_hidden_truth(self): + h=calibrated();h._calibration['C']['slope_s_kg']*=2;h._calibration['C']['mass_range_kg'][0]=0.;load(h);q=run(h,[0])['completed_assays'][0];self.assertAlmostEqual(q['fractions']['C'],.4168/2,delta=2e-6) + def test_calibration_rejects_degenerate_nonfinite_and_negative_slope(self): + h=blank(ready());a=copy.deepcopy(r.CALIBRATION_EXAMPLE);a['observations']=[a['observations'][0]]*3;self.reject_atomic(h,'DEGENERATE_CALIBRATION','calibration.fit',**a) + a=copy.deepcopy(r.CALIBRATION_EXAMPLE) + for p in a['observations']:p['peak_area_s']=-p['peak_area_s'] + self.reject_atomic(h,'CALIBRATION_RANGE','calibration.fit',**a);a['observations'][0]['peak_area_s']=float('inf');self.reject_atomic(h,'INVALID_ARGUMENT','calibration.fit',**a) + def test_calibration_overflow_rejects_atomically(self): + h=blank(ready());a=copy.deepcopy(r.CALIBRATION_EXAMPLE) + for p,v in zip(a['observations'],[-1e308,0,1e308]):p['peak_area_s']=v + self.reject_atomic(h,'CALIBRATION_RANGE','calibration.fit',**a) + def test_calibration_missing_source_channel_cannot_fit(self): + h=blank(ready());a=copy.deepcopy(r.CALIBRATION_EXAMPLE);a['element']='S' + for p in a['observations']:p['reference_id']='ep0459505_compound_01' + self.reject_atomic(h,'MEASURED_REFERENCE_REQUIRED','calibration.fit',**a) + def test_calibration_outside_range_returns_null(self): + h=calibrated();load(h,mass=5e-6);q=run(h,[0])['completed_assays'][0];self.assertIsNone(q['fractions']['C']);self.assertEqual(q['fraction_quality']['C'],'outside_calibrated_element_mass_range') + def test_method_invalidates_blank_and_calibration_retains_old_data(self): + h=calibrated();old=h._result();h.invoke('method.configure',**dict(r.METHOD_EXAMPLE,combustion_s=.2));self.assertFalse(h._blank_valid());self.assertFalse(h._calibration_ready());self.assertEqual(old,h._result());load(h);h.invoke('sequence.configure',slot_indices=[0]);self.reject_atomic(h,'MATCHED_BLANK_REQUIRED','sequence.start') + def test_sequence_results_reset_only_on_next_start(self): + h=calibrated();self.assertEqual(len(h.completed_assays),3);load(h);h.invoke('sequence.configure',slot_indices=[0]);self.assertEqual(len(h.completed_assays),3);h.invoke('sequence.start');self.assertEqual(h.completed_assays,[]);finish(h);self.assertEqual(len(h.completed_assays),1) + def test_partitioned_steps_preserve_observations_and_mass(self): + a=blank(ready(plant={'seed':11,'tcd_noise_sd':1e-7}));b=blank(ready(plant={'seed':11,'tcd_noise_sd':1e-7})) + for h in [a,b]:load(h);h.invoke('sequence.configure',slot_indices=[0]);h.invoke('sequence.start') + finish(a,.25);finish(b,.007);qa=a.completed_assays[0];qb=b.completed_assays[0];self.assertEqual(len(qa['chromatogram']),len(qb['chromatogram']));np.testing.assert_allclose([p['signal'] for p in qa['chromatogram']],[p['signal'] for p in qb['chromatogram']],rtol=1e-9,atol=1e-9);self.closed(a);self.closed(b) + def test_query_purity_and_export_roundtrip(self): + h=blank(ready());load(h);run(h,[0]);before=repr(h.debug_snapshot()) + for cap,args in [('process.measure',{}),('result.read',{}),('chromatogram.read',{}),('blank.read',{}),('calibration.read',{}),('product.read',{}),('template.read',{'substance_id':'oem_sulfanilic_acid'}),('result.export',{'format':'json'}),('result.export',{'format':'csv'})]:h.invoke(cap,**args) + self.assertEqual(before,repr(h.debug_snapshot()));self.assertEqual(json.loads(h.invoke('result.export',format='json')['content']),h._result());self.assertIn('mass_fraction',h.invoke('result.export',format='csv')['content']) + def test_public_access_filters_sample_truth_and_host_commands(self): + h=ready();load(h);public=h.session();desc=public.describe(instance_id=h.instance_id);self.assertNotIn('truth.ledger',desc['state_slots']);self.assertNotIn('sample.load',desc['capabilities']);reply=public.invoke(instance_id=h.instance_id,capability_id='product.read',arguments={},request_id='deny');self.assertEqual(reply['status'],'rejected');self.assertEqual(reply['error']['code'],'ACCESS_DENIED');self.assertNotIn('oem_sulfanilic_acid',json.dumps(public.read(instance_id=h.instance_id))) + def test_host_role_and_read_write_binding(self): + h=r.ElementarVarioelRuntime();h.register_principal('host','evaluator');session=h.session('host');reply=session.invoke(instance_id=h.instance_id,capability_id='plant.configure',arguments=r.PLANT_EXAMPLE,request_id='plant');self.assertEqual(reply['status'],'succeeded');self.assertIn('truth.ledger',session.read(instance_id=h.instance_id)['observations']);self.assertEqual(session.write(instance_id=h.instance_id,state_id='power.enabled',value=True,request_id='on')['status'],'succeeded') + def test_request_replay_and_conflict_are_atomic(self): + h=ready();s=h.session();args=dict(instance_id=h.instance_id,capability_id='method.configure',arguments=r.METHOD_EXAMPLE,request_id='method');first=s.invoke(**args);revision=h.revision;self.assertEqual(s.invoke(**args),first);self.assertEqual(h.revision,revision);args['arguments']=dict(r.METHOD_EXAMPLE,mode='CHN');self.assertEqual(s.invoke(**args)['error']['code'],'REQUEST_CONFLICT');self.assertEqual(h.revision,revision) + def test_history_poll_and_cancel_old_do_not_touch_new(self): + h=blank(ready());s=h.session();load(h);h.invoke('sequence.configure',slot_indices=[0]);start=s.invoke(instance_id=h.instance_id,capability_id='sequence.start',arguments={},request_id='first');op=start['operation_id'];finish(h);old=s.poll(op);load(h,slot=4);h.invoke('sequence.configure',slot_indices=[4]);new=s.invoke(instance_id=h.instance_id,capability_id='sequence.start',arguments={},request_id='second');self.assertEqual(s.poll(op),old);s.cancel(op,'cancel_old');self.assertEqual(h.phase,'running');self.assertEqual(h.operation_id,new['operation_id']);self.assertEqual(s.poll(op),old) + def test_cancelled_history_retains_partial_data_and_ownership(self): + h=blank(ready());h.register_principal('other');s=h.session();load(h);h.invoke('sequence.configure',slot_indices=[0]);op=s.invoke(instance_id=h.instance_id,capability_id='sequence.start',arguments={},request_id='start')['operation_id'];h.step(.2);s.cancel(op,'cancel');old=s.poll(op);self.assertEqual(old['status'],'cancelled');self.assertGreater(len(old['result']['active_assay']['chromatogram']),0) + with self.assertRaisesRegex(r.ActionRejected,'ACCESS_DENIED'):h.session('other').poll(op) + def test_actual_detector_windows_survive_later_idle_time(self): + h=calibrated();load(h);run(h,[0]);before=h.session().read(instance_id=h.instance_id,state_ids=['detector.tcd_signal','result.c_fraction']);h.step(1);after=h.session().read(instance_id=h.instance_id,state_ids=['detector.tcd_signal','result.c_fraction']);self.assertEqual(before['observations'],after['observations']);self.assertLess(after['observations']['result.c_fraction']['sample_window_s'][0],after['observations']['result.c_fraction']['sample_window_s'][1]) + def test_independent_instances_do_not_share_consumption(self): + a=blank(ready(instance_id='a'));b=blank(ready(instance_id='b'));load(a);load(b);before=repr(b.debug_snapshot());run(a,[0]);self.assertEqual(before,repr(b.debug_snapshot()));self.assertIn(0,b.samples) + def test_invalid_step_never_changes_state(self): + h=ready();before=repr(h.debug_snapshot()) + for dt in [-1,float('nan'),float('inf'),True]: + with self.assertRaises(r.ActionRejected):h.step(dt) + self.assertEqual(before,repr(h.debug_snapshot())) + t=h.time_s;h.step(1e-10);self.assertGreater(h.time_s,t) + def test_unsupported_options_and_metadata_query_purity(self): + h=ready() + for cap in r.UNSUPPORTED:self.reject_atomic(h,'UNSUPPORTED',cap) + meta=r.export_elementar_varioel_contract_metadata();self.assertEqual(len(meta['capabilities']),23);self.assertEqual(len(meta['state_slots']),31) + for k,c in meta['capabilities'].items(): + if c['kind']=='query' or k in r.UNSUPPORTED:self.assertEqual(c['state_effects'],[]) + self.assertEqual(meta['capabilities']['sequence.start']['execution']['mode'],'asynchronous') + def test_schema_rejects_unknown_fields_and_nonfinite(self): + h=ready();self.reject_atomic(h,'INVALID_ARGUMENT','method.configure',**dict(r.METHOD_EXAMPLE,extra=3));self.reject_atomic(h,'INVALID_ARGUMENT','sample.load',**dict(r.SAMPLE_EXAMPLE,mass_kg=float('nan'))) + def test_event_budget_rejected_before_sample_consumption(self): + h=ready(plant={'detector_period_s':.001},method={'maximum_release_s':3600.});load(h,kind='blank');h.invoke('sequence.configure',slot_indices=[0]);self.reject_atomic(h,'EVENT_RESOURCE_LIMIT','sequence.start') + +if __name__=='__main__':unittest.main() diff --git a/tests/test_asset_freeman_ft4powder.py b/tests/test_asset_freeman_ft4powder.py new file mode 100644 index 0000000000000000000000000000000000000000..2702b63f7eeb2d7b5ea9f9dd6f58883e0b0785b1 --- /dev/null +++ b/tests/test_asset_freeman_ft4powder.py @@ -0,0 +1,141 @@ +"""FT4 powder-only process, metrology schema and owner/host regression tests.""" +import copy,importlib.util,json,math,sys,unittest +from pathlib import Path +from unittest import mock +import numpy as np +ROOT=Path(__file__).resolve().parents[1];sys.path.insert(0,str(ROOT/'scripts')) +from asset_runtime import freeman_ft4powder as rt +OBSERVED=[] +def call(h,k,**a): + r=h.invoke(k,**a);OBSERVED.append((k,copy.deepcopy(a),copy.deepcopy(r)));return r +def setup(mode='dynamic',instance_id='ft4_test',plant=None,sample=None,method=None,gas=None): + h=rt.FreemanFt4powderRuntime(instance_id) + for k,a in [('plant.configure',dict(rt.PLANT_EXAMPLE,**(plant or {}))),('tool.select',{'tool_type':{'dynamic':'blade','shear':'shear','compression':'piston','permeability':'permeability'}[mode]}),('sample.load',dict(rt.SAMPLE_EXAMPLE,**(sample or {}))),('gas.load',dict(rt.GAS_EXAMPLE,**(gas or {}))),('clamp.set',{'locked':True}),('door.set',{'opened':False}),('power.set',{'enabled':True}),('method.configure',dict(rt.METHOD_EXAMPLE,mode=mode,**(method or {}))),('gas.set_flow',{'flow_m3_s':(method or {}).get('gas_flow_m3_s',rt.METHOD_EXAMPLE['gas_flow_m3_s'])})]:call(h,k,**a) + if mode=='permeability':call(h,'gas.open',enabled=True) + return h +def finish(h,seconds=300): + for _ in range(round(seconds/.1)): + h.step(.1) + if h.phase!='running':break + return call(h,'acquisition.result') +def park(h): + call(h,'spindle.set_speed',angular_speed_rad_s=0.);call(h,'gas.open',enabled=False);call(h,'axis.move',position_m=0.,speed_m_s=.03);h.step(7.);call(h,'door.set',opened=True);call(h,'clamp.set',locked=False) +class TestFT4Powder(unittest.TestCase): + def rejected(self,h,k,error='.',**a): + before=copy.deepcopy(h.__dict__) + with self.assertRaisesRegex(rt.ActionRejected,error):h.invoke(k,**a) + self.assertEqual(before,h.__dict__) + def assert_ledger(self,h): + l=call(h,'ledger.read');self.assertLess(abs(l['powder_error_kg']),1e-14);self.assertLess(abs(l['gas_error_mol']),1e-12);self.assertLess(abs(l['mass_error_kg']),1e-14);self.assertLess(abs(l['energy_error_j']),1e-7) + def test_01_dynamic_real_scalar_anchor_and_seventh_bfe(self): + h=setup();call(h,'acquisition.start');r=finish(h);self.assertEqual(r['phase'],'succeeded');self.assertLess(r['elapsed_s'],60);self.assertEqual(len(r['points']),14);self.assertEqual(r['basic_flowability_energy_j'],[p for p in r['points'] if p['kind']=='down'][6]['energy_j']);self.assertAlmostEqual(r['specific_energy_j_kg'],r['points'][-1]['energy_j']/h.method['weighed_mass_kg']);self.assertLess(abs(r['basic_flowability_energy_j']/2.107-1),.05);self.assert_ledger(h) + def test_02_single_downstroke_not_automatically_bfe(self): + for cond,cycles in [(1,1),(0,7)]: + h=setup(method={'conditioning_cycles':cond,'measurement_cycles':cycles});h.invoke('acquisition.start');r=finish(h);self.assertIsNone(r['basic_flowability_energy_j']);self.assertIsNotNone(r['specific_energy_j_kg']) + def test_03_independent_segment_work_integral(self): + h=setup();h.invoke('acquisition.start');r=finish(h) + for p in r['points']: + rows=[x for x in r['rows'] if x['segment']=='measure_'+p['kind'] and x['cycle']==p['cycle']];z=np.array([x['position_m'] for x in rows]);theta=np.array([x['rotation_rad'] for x in rows]);force=np.array([x['force_n'] for x in rows]);torque=np.array([x['torque_nm'] for x in rows]);expected=float(np.sum((force[1:]+force[:-1])/2*np.diff(z)+(torque[1:]+torque[:-1])/2*np.diff(theta)));self.assertAlmostEqual(p['energy_j'],expected,places=12) + a=rt.CAPS['analysis.energy']['example_arguments'];self.assertAlmostEqual(call(h,'analysis.energy',**a)['energy_j'],.04) + def test_04_true_seventh_work_matches_scalar_before_sensor_response(self): + h=setup(sample={'initial_history_factor':1.});h.invoke('acquisition.start') + while not (h.segment=='measure_down' and h.cycle==6):h.step(.1) + before=h.mechanical + while h.segment=='measure_down':h.step(.1) + self.assertAlmostEqual(h.mechanical-before,2.107,places=7) + def test_05_filling_history_conditioning_and_mass(self): + h=setup(sample={'mass_kg':.045,'initial_packing_ratio':.95,'initial_history_factor':2.},method={'measurement_cycles':1});mass=h.sample['mass_kg'];initial=h.packing;h.invoke('acquisition.start');finish(h);self.assertGreater(h.packing,initial);self.assertLess(abs(h.packing-1),1e-3);self.assertLess(h.history,1.001);self.assertEqual(h.sample['mass_kg'],mass);self.assert_ledger(h) + def test_06_shear_continuum_and_external_yield_fit(self): + h=setup('shear');call(h,'acquisition.start');r=finish(h);self.assertEqual(r['phase'],'succeeded');self.assertEqual(len(r['points']),3);self.assertTrue(all(p['shear_stress_pa']>0 for p in r['points']));a=rt.CAPS['analysis.shear_yield']['example_arguments'];fit=call(h,'analysis.shear_yield',**a);self.assertAlmostEqual(fit['cohesion_pa'],500.,places=7);self.assertAlmostEqual(fit['friction_angle_rad'],math.atan(.5),places=10);self.assertLess(fit['residual_pa'],1e-8);self.assert_ledger(h) + def test_07_compression_geometry_mass_and_monotonic_density(self): + h=setup('compression');height=h._height();call(h,'acquisition.start');r=finish(h);self.assertEqual(r['phase'],'succeeded');density=[p['bulk_density_kg_m3'] for p in r['points']];self.assertEqual(density,sorted(density));self.assertLess(h._height(),height);self.assertTrue(all(00 for p in r['points']));a=rt.CAPS['analysis.permeability']['example_arguments'];res=call(h,'analysis.permeability',**a);self.assertAlmostEqual(res['permeability_m2'],a['gas_viscosity_pa_s']*a['flow_m3_s']*a['bed_height_m']/a['area_m2']/a['pressure_drop_pa'],places=22);self.assert_ledger(h) + def test_09_true_setpoints_and_pure_queries(self): + h=setup();before=copy.deepcopy(h.__dict__);h.describe();h.session().read(instance_id=h.instance_id);h.invoke('acquisition.result');h.invoke('ledger.read');call(h,'reference.query',reference_id=rt.SAMPLE_EXAMPLE['reference_id']);self.assertEqual(before,h.__dict__);call(h,'axis.move',position_m=.03,speed_m_s=.03);call(h,'spindle.set_speed',angular_speed_rad_s=4.);self.assertEqual(h.position,0.);self.assertEqual(h.rotation,0.);self.assertEqual(h.time_s,0.);h.step(.1);self.assertEqual(h.position,.003);self.assertAlmostEqual(h.rotation,.4) + def test_10_host_partition_independence_and_zero_dt(self): + a=setup();b=setup();a.invoke('acquisition.start');b.invoke('acquisition.start');a.step(7.) + for _ in range(70):b.step(.1) + self.assertEqual(a.read(),b.read());self.assertEqual(a.rows,b.rows);before=copy.deepcopy(a.__dict__);a.step(0.);self.assertEqual(before,a.__dict__) + def test_11_two_instances(self): + a=setup(instance_id='a');b=setup(instance_id='b');before=copy.deepcopy(b.__dict__);a.invoke('acquisition.start');a.step(8.);self.assertEqual(before,b.__dict__) + def test_12_registered_agent_truth_and_recovery_permissions(self): + h=setup();s=h.session();d=s.describe(instance_id=h.instance_id);self.assertFalse(any(k.startswith('truth.') for k in d['state_slots']));self.assertNotIn('sample.remove',d['capabilities']);before=copy.deepcopy(h.__dict__) + for k,a in [('sample.remove',{}),('gas.unload',{}),('ledger.read',{}),('sim.step',{'dt_s':1.})]: + r=s.invoke(instance_id=h.instance_id,capability_id=k,arguments=a,request_id=k);self.assertEqual(r['error']['code'],'ACCESS_DENIED');self.assertEqual(before,h.__dict__) + with self.assertRaises(rt.ActionRejected):s.read(instance_id=h.instance_id,state_ids=['truth.powder_mass_kg']) + with self.assertRaises(rt.ActionRejected):h.register_principal('agent','evaluator') + def test_13_operation_owner_queries_poll_and_cancel(self): + h=setup();h.register_principal('other');a=h.session();b=h.session('other');op=a.invoke(instance_id=h.instance_id,capability_id='acquisition.start',arguments={},request_id='start')['operation_id'];before=copy.deepcopy(h.__dict__) + for k in ['acquisition.result','acquisition.stop']: + r=b.invoke(instance_id=h.instance_id,capability_id=k,arguments={},request_id=k);self.assertEqual(r['error']['code'],'ACCESS_DENIED');self.assertEqual(before,h.__dict__) + with self.assertRaises(rt.ActionRejected):b.poll(op) + q=a.invoke(instance_id=h.instance_id,capability_id='acquisition.result',arguments={},request_id='q');self.assertIsNone(q['operation_id']);self.assertEqual(h._owners[op],'agent');self.assertEqual(a.cancel(op,'cancel')['status'],'succeeded') + def test_14_idempotency_and_request_conflict(self): + h=setup();s=h.session();a=dict(instance_id=h.instance_id,capability_id='gas.set_flow',arguments={'flow_m3_s':1e-6},request_id='x');r=s.invoke(**a);before=copy.deepcopy(h.__dict__);self.assertEqual(r,s.invoke(**a));self.assertEqual(before,h.__dict__);a['arguments']={'flow_m3_s':2e-6};self.assertEqual(s.invoke(**a)['error']['code'],'REQUEST_CONFLICT');self.assertEqual(before,h.__dict__) + def test_15_history_source_freeze_and_return_copy(self): + h=setup(method={'measurement_cycles':1});s=h.session();op=s.invoke(instance_id=h.instance_id,capability_id='acquisition.start',arguments={},request_id='start')['operation_id'];finish(h);saved=s.poll(op);park(h);call(h,'sample.remove');call(h,'sample.load',**dict(rt.SAMPLE_EXAMPLE,reference_id='retalac_2026'));self.assertEqual(saved,s.poll(op));self.assertEqual(saved['result'],h.invoke('acquisition.result'));saved['result']['rows'][0]['force_n']=999.;self.assertNotEqual(saved,s.poll(op)) + def test_16_cancel_keeps_dissipation_packing_and_frozen_result(self): + h=setup(sample={'initial_history_factor':2.});h.invoke('acquisition.start');h.step(8.);self.assertGreater(h.mechanical,0.);history=h.history;energy=h.mechanical;call(h,'acquisition.stop');saved=h.invoke('acquisition.result');self.assertEqual(h.history,history);self.assertEqual(h.mechanical,energy);h.step(1.);self.assertEqual(saved,h.invoke('acquisition.result'));self.assertEqual(h.omega,0.);self.assert_ledger(h) + def test_17_safety_door_stops_immediately_and_close_does_not_resume(self): + h=setup();h.invoke('acquisition.start');h.step(8.);old=(h.position,h.rotation);call(h,'door.set',opened=True);self.assertEqual(h.phase,'failed');self.assertEqual(h.error,'DOOR_INTERLOCK');self.assertEqual(h.omega,0.);saved=h.invoke('acquisition.result');h.step(1.);self.assertEqual(old,(h.position,h.rotation));call(h,'door.set',opened=False);h.step(.2);self.assertEqual(saved,h.invoke('acquisition.result'));self.assertEqual(old,(h.position,h.rotation));call(h,'acquisition.start');self.assertEqual(h.phase,'running') + def test_18_tiny_finite_gas_terminal_includes_last_tick(self): + h=setup('permeability',gas={'amount_mol':1e-15});h.invoke('acquisition.start');h.step(.1);r=call(h,'acquisition.result');self.assertEqual(r['phase'],'failed');self.assertEqual(r['error_code'],'GAS_EXHAUSTED');self.assertEqual(h.gas_stock,0.);self.assertFalse(h.gas_enabled);self.assertEqual(r['elapsed_s'],.1);self.assertEqual(r['rows'][-1]['time_s'],.1);self.assert_ledger(h) + def test_19_manufacturer_speed_stroke_force_bounds_atomic(self): + h=setup() + for k,a in [('axis.move',{'position_m':.1851,'speed_m_s':.03}),('axis.move',{'position_m':.1,'speed_m_s':.03001}),('spindle.set_speed',{'angular_speed_rad_s':4*math.pi+1e-5})]:self.rejected(h,k,**a) + self.rejected(h,'method.configure','FORCE_RANGE',**dict(rt.METHOD_EXAMPLE,normal_stresses_pa=[30000.]));call(h,'spindle.set_speed',angular_speed_rad_s=4*math.pi);h.step(.1);self.assertAlmostEqual(h.omega,4*math.pi);call(h,'spindle.set_speed',angular_speed_rad_s=0.) + def test_20_invalid_engineering_unknown_source_and_overfill(self): + h=rt.FreemanFt4powderRuntime();self.rejected(h,'plant.configure','MODEL_NOT_ACCEPTED',**dict(rt.PLANT_EXAMPLE,accept_engineering=False));h.invoke('plant.configure',**rt.PLANT_EXAMPLE) + for a in [dict(accept_engineering=False),dict(reference_id='unknown'),dict(mass_kg=.5),dict(solid_density_kg_m3=100.)]:self.rejected(h,'sample.load',**dict(rt.SAMPLE_EXAMPLE,**a)) + lib=copy.deepcopy(rt.library());lib['substances'][rt.SAMPLE_EXAMPLE['reference_id']]['runtime_usable']=False + with mock.patch.object(rt,'library',return_value=lib):self.rejected(h,'sample.load','INVALID_REFERENCE',**rt.SAMPLE_EXAMPLE) + def test_21_condition_scaling_needs_explicit_acceptance(self): + h=rt.FreemanFt4powderRuntime();h.invoke('plant.configure',**rt.PLANT_EXAMPLE);h.invoke('sample.load',**dict(rt.SAMPLE_EXAMPLE,accept_condition_scaling=False));self.rejected(h,'method.configure','CONDITION_SCALING_NOT_ACCEPTED',**rt.METHOD_EXAMPLE) + def test_22_tool_access_interlocks_and_no_liquid_substitution(self): + h=setup();self.rejected(h,'tool.select','TOOL_ACCESS',tool_type='shear');self.rejected(h,'clamp.set','SAMPLE_ACCESS',locked=False);self.rejected(h,'service.set','POWER_INTERLOCK',distance_m=.06);h.invoke('door.set',opened=True);h.invoke('tool.select',tool_type='piston');h.invoke('door.set',opened=False);self.rejected(h,'acquisition.start','ATTACHMENT_REQUIRED') + for k in rt.UNSUPPORTED:self.rejected(h,k,'UNSUPPORTED') + def test_23_force_torque_resolution_and_supplied_zero_offsets(self): + h=setup();call(h,'sensor.calibrate',force_zero_n=.001,torque_zero_nm=.00001,pressure_zero_pa=2.);h.invoke('acquisition.start');h.step(8.);f,t,_=h._indications();self.assertAlmostEqual(f/1e-4,round(f/1e-4),places=7);self.assertAlmostEqual(t/2e-6,round(t/2e-6),places=7) + def test_24_force_overload_is_explicit_partial_failure(self): + h=setup(sample={'initial_history_factor':10.,'conditioning_rate_s':0.});h.invoke('acquisition.start');r=finish(h);self.assertEqual(r['phase'],'failed');self.assertEqual(r['error_code'],'FORCE_OVERLOAD');self.assertLessEqual(abs(h._indications()[0]),50);self.assertGreater(h.mechanical,0.);self.assert_ledger(h) + def test_25_stiff_compression_limited_by_axial_rate(self): + h=setup('compression',plant={'compression_tau_s':.001},sample={'compression_modulus_pa':100.},method={'normal_stresses_pa':[20000.],'hold_s':2.});h.invoke('acquisition.start');positions=[] + while h.phase=='running':positions.append(h.position);h.step(.1) + self.assertLessEqual(max(abs(b-a) for a,b in zip(positions,positions[1:])),.003+1e-12);self.assertGreater(h._height(),0.);self.assertLess(h._density(),h.sample['solid_density_kg_m3']);self.assert_ledger(h) + def test_26_pressure_range_guard(self): + h=setup('permeability',sample={'permeability_m2':1e-16});h.invoke('acquisition.start');h.step(.1);self.assertEqual(h.phase,'failed');self.assertEqual(h.error,'PRESSURE_MODEL_RANGE');self.assertFalse(h.gas_enabled);self.assert_ledger(h) + def test_27_invalid_numbers_busy_and_dt_atomic(self): + h=setup() + for value in [True,float('nan'),float('inf'),-1.]:self.rejected(h,'gas.set_flow',flow_m3_s=value) + before=copy.deepcopy(h.__dict__) + for dt in [True,float('nan'),-1.,float('inf')]: + with self.assertRaises(rt.ActionRejected):h.step(dt) + self.assertEqual(before,h.__dict__) + h.invoke('acquisition.start');self.rejected(h,'method.configure','BUSY',**rt.METHOD_EXAMPLE) + def test_28_powder_gas_recovery_conservation(self): + h=setup();h.invoke('acquisition.start');finish(h);park(h);call(h,'sample.remove');call(h,'gas.unload');call(h,'power.set',enabled=False);call(h,'service.set',distance_m=.06);self.assertEqual(h.powder_recovered,h.powder_loaded);self.assertEqual(h.gas_stock,0.);self.assert_ledger(h) + def test_29_environment_bounds_and_no_empirical_claims(self): + h=rt.FreemanFt4powderRuntime() + for t in [283.14,313.16]:self.rejected(h,'plant.configure',**dict(rt.PLANT_EXAMPLE,ambient_k=t)) + meta=rt.export_freeman_ft4powder_contract_metadata();self.assertIn('DEM',' '.join(meta['mechanisms']['powder_mechanics']['limitations']));self.assertEqual(meta['capabilities']['noise.empirical']['availability'],'unsupported') + def test_30_state_effects_cover_actual_changes(self): + meta=rt.export_freeman_ft4powder_contract_metadata();original=rt.FreemanFt4powderRuntime.invoke + def audited(h,k,**a): + before=h.read();r=original(h,k,**a);after=h.read();changed={x for x in before if before[x]!=after[x]};declared={e['state_id'] for e in meta['capabilities'][k]['state_effects'] if e['timing']=='immediate'};self.assertFalse(changed-declared,(k,changed-declared));return r + with mock.patch.object(rt.FreemanFt4powderRuntime,'invoke',audited): + h=setup();call(h,'sensor.calibrate',**rt.CAPS['sensor.calibrate']['example_arguments']);call(h,'acquisition.start');call(h,'sim.step',dt_s=8.);call(h,'acquisition.stop');park(h);call(h,'sample.remove');call(h,'gas.unload');call(h,'power.set',enabled=False);call(h,'service.set',distance_m=.06) + def test_31_source_summary_not_invented_native_trace(self): + lib=rt.library()['substances'];r=lib['tablettose_70_2026'];self.assertEqual(r['values']['basic_flowability_energy_j'],2.107);self.assertEqual(r['values']['specific_energy_j_kg'],6.41);self.assertEqual(r['conditions']['sample_volume_m3'],85e-6);self.assertIsNone(r['values']['conditioned_bulk_density_kg_m3']);self.assertNotIn('force_n',r['values']);self.assertTrue(r['runtime_usable']) + def test_31b_stiff_thermal_and_large_host_step(self): + h=setup(plant={'thermal_capacity_j_k':.01,'heat_loss_w_k':100.});call(h,'acquisition.start');h.step(70.);self.assertEqual(h.phase,'succeeded');self.assertTrue(math.isfinite(h.temperature));self.assertGreaterEqual(h.temperature,h.plant['ambient_k']);self.assertLess(h.temperature,h.plant['ambient_k']+1.);self.assert_ledger(h) + def test_31c_thermal_domain_excess_explicitly_fails(self): + h=setup(plant={'thermal_capacity_j_k':.01,'heat_loss_w_k':0.});h.invoke('acquisition.start');r=finish(h);self.assertEqual(r['phase'],'failed');self.assertEqual(r['error_code'],'THERMAL_MODEL_RANGE');self.assertGreater(h.temperature-h.plant['ambient_k'],h.plant['maximum_temperature_rise_k']);self.assertEqual(h.omega,0.);self.assert_ledger(h);self.rejected(h,'acquisition.start','THERMAL_MODEL_RANGE') + def test_32_all_actual_capability_and_state_schemas(self): + spec=importlib.util.spec_from_file_location('ft4_asset_tool',ROOT/'skills/chemistry-lab-assets/scripts/asset_tool.py');tool=importlib.util.module_from_spec(spec);spec.loader.exec_module(tool);meta=rt.export_freeman_ft4powder_contract_metadata();h=setup();call(h,'acquisition.start');call(h,'sim.step',dt_s=60.);call(h,'acquisition.result');call(h,'ledger.read') + for k,c in rt.CAPS.items(): + if k in rt.UNSUPPORTED:continue + cases=[v for v in OBSERVED if v[0]==k];self.assertTrue(cases,k) + for _,a,r in cases:self.assertEqual(tool.validate_value(a,meta['capabilities'][k]['input_schema']),[],k);self.assertEqual(tool.validate_value(r,meta['capabilities'][k]['output_schema']),[],k) + for k,v in h.read().items():self.assertEqual(tool.validate_value(v,meta['state_slots'][k]['value_schema']),[],k) +if __name__=='__main__':unittest.main() diff --git a/tests/test_asset_frontier_egapy.py b/tests/test_asset_frontier_egapy.py new file mode 100644 index 0000000000000000000000000000000000000000..67fde784d90a48402a177516366d0718a9b7d8dc --- /dev/null +++ b/tests/test_asset_frontier_egapy.py @@ -0,0 +1,76 @@ +import unittest,copy,json,math,importlib.util +from pathlib import Path +from scripts.asset_runtime import frontier_egapy as r +spec=importlib.util.spec_from_file_location('asset_tool',r.ROOT/'skills/chemistry-lab-assets/scripts/asset_tool.py');tool=importlib.util.module_from_spec(spec);spec.loader.exec_module(tool) +OBSERVED=set() +def call(h,k,a=None): + v=h.invoke(k,**(a or {}));tool.validate_value(v,r.CAPS[k][1]);OBSERVED.add(k);return v +def setup(mode='single',**method): + h=r.FrontierEgapyRuntime();call(h,'plant.configure',r.PLANT_EXAMPLE);call(h,'method.configure',dict(r.METHOD_EXAMPLE,mode=mode,**method));call(h,'sample.load',r.SAMPLE_EXAMPLE);call(h,'power.set',{'enabled':True});call(h,'gas.set',{'enabled':True});call(h,'gc.ready',{'ready':True});return h +def until(h,stage,max_s=1200): + for _ in range(max_s): + if h.stage==stage:return + h.step(1.) + raise AssertionError((stage,h.stage,h.T,h.phase,h.failure)) +def dropped(h): + call(h,'acquisition.start');until(h,'wait_drop');call(h,'cup.drop');call(h,'acquisition.confirm');return h +class Tests(unittest.TestCase): + def assertledger(self,h): + l=call(h,'ledger.read');self.assertLess(abs(l['mass_residual_kg']),1e-18);self.assertLess(abs(l['energy_residual_j']),max(1e-7,l['heater_energy_j']*1e-10));self.assertLess(abs(l['carrier_residual_mol']),1e-11);self.assertLess(abs(l['cool_residual_mol']),1e-11) + for x in l['species']:self.assertLess(abs(x['residual_kg']),1e-18) + def test_01_schema_and_real_library(self): + m=r.export_frontier_egapy_contract_metadata();self.assertEqual(len(m['capabilities']),22);h=setup();v=call(h,'template.reference',{'substance_id':'nist_pps_73'});self.assertEqual(v['name'],'Styrene');self.assertEqual(v['ri'],892.7);self.assertIn([104,999.],v['peaks']);self.assertEqual(len(h.library['substances']),164);self.assertEqual(len(h.library['polymers']),11) + def test_02_single_and_mass_energy(self): + h=dropped(setup());h.step(6.);self.assertEqual(h.stage,'cool');self.assertGreater(sum(h.generated.values()),1e-8);until(h,'cool');h.step(300.);self.assertEqual(h.phase,'succeeded');self.assertLessEqual(h.T[0],323.15);self.assertledger(h);v=call(h,'products.collect');self.assertGreater(sum(x['mass_kg'] for x in v['species']),0);self.assertFalse(call(h,'products.collect')['species']);self.assertledger(h) + def test_03_double_manual_order(self): + h=setup('double',td_end_k=373.15);call(h,'acquisition.start');until(h,'wait_insert');self.assertEqual(h.sampler,0.) + with self.assertRaises(r.ActionRejected):call(h,'acquisition.confirm') + call(h,'sampler.set',{'down_m':.08});call(h,'acquisition.confirm');until(h,'wait_retract');self.assertEqual(h.sampler,.08) + with self.assertRaises(r.ActionRejected):call(h,'acquisition.confirm') + call(h,'sampler.set',{'down_m':0.});call(h,'acquisition.confirm');until(h,'wait_drop') + with self.assertRaises(r.ActionRejected):call(h,'cup.drop') + call(h,'gc.ready',{'ready':True});call(h,'cup.drop');call(h,'acquisition.confirm');self.assertEqual(h.triggers,2);h.step(10);self.assertEqual(sum(x['gc_trigger'] for x in h.trace),2);self.assertledger(h) + def test_04_ega_requires_retract(self): + h=setup('ega',td_end_k=373.15);call(h,'acquisition.start');until(h,'wait_insert');call(h,'sampler.set',{'down_m':.08});call(h,'acquisition.confirm');until(h,'wait_retract');h.step(1);self.assertEqual(h.stage,'wait_retract');call(h,'sampler.set',{'down_m':0.});call(h,'acquisition.confirm');h.step(.1);self.assertEqual(h.stage,'cool');self.assertEqual(h.triggers,1);self.assertledger(h) + def test_05_cancel_hot_continues_chemistry(self): + h=dropped(setup(pyrolysis_s=60.));h.step(.2);call(h,'acquisition.stop');before=sum(h.generated.values());h.step(2.);self.assertEqual(h.phase,'cancelled');self.assertGreater(sum(h.generated.values()),before);self.assertledger(h) + def test_06_power_off_energy(self): + h=dropped(setup(pyrolysis_s=60.));before=h.heat;call(h,'power.set',{'enabled':False});h.step(5);self.assertEqual(h.heat,before);self.assertEqual(h.phase,'cancelled');self.assertledger(h) + def test_07_atomic_invalid(self): + h=setup();old=copy.deepcopy(h.read('evaluator')) + for k,a in [('method.configure',dict(r.METHOD_EXAMPLE,hold_s=7.)),('method.configure',dict(r.METHOD_EXAMPLE,ramp_k_s=10.1)),('guard.set',{'lift_m':float('nan')}),('power.set',{'enabled':1})]: + with self.assertRaises(r.ActionRejected):call(h,k,a) + self.assertEqual(h.read('evaluator'),old) + def test_08_fixed_step_partition(self): + a=dropped(setup());b=copy.deepcopy(a);a.step(1.7) + for _ in range(17):b.step(.1) + self.assertEqual(a.T,b.T);self.assertEqual(a.generated,b.generated);self.assertEqual(a.read('evaluator'),b.read('evaluator')) + def test_09_isolation_pure_queries(self): + a=setup();b=setup();a.T[0]=350.;before=a.read('evaluator');call(a,'process.measure');call(a,'ledger.read');self.assertEqual(before,a.read('evaluator'));self.assertEqual(b.T[0],293.15) + def test_10_capacity_and_mass_fraction(self): + h=setup();h.sample=None + for s in [dict(r.SAMPLE_EXAMPLE,channels=[dict(r.SAMPLE_EXAMPLE['channels'][0],char_fraction=.2)]),dict(r.SAMPLE_EXAMPLE,channels=[dict(r.SAMPLE_EXAMPLE['channels'][0],mass_kg=1e-4)],density_kg_m3=10.)]: + with self.assertRaises(r.ActionRejected):call(h,'sample.load',s) + def test_11_guard_and_unload(self): + h=setup();call(h,'guard.set',{'lift_m':.18}) + with self.assertRaises(r.ActionRejected):call(h,'acquisition.start') + call(h,'guard.set',{'lift_m':0.});dropped(h) + with self.assertRaises(r.ActionRejected):call(h,'guard.set',{'lift_m':.18}) + h.step(500.);self.assertLess(h.T[2],313.15);call(h,'sample.unload');self.assertFalse(h.sample);self.assertledger(h) + def test_12_species_exact_flow(self): + h=setup();h.channels=[];h.loaded=1e-8;h.generated={'nist_pps_73':1e-8};h.chamber={'nist_pps_73':1e-8};h.step(1.);self.assertAlmostEqual(h.chamber['nist_pps_73'],1e-8*math.exp(-.02),places=20);self.assertledger(h) + def test_13_depletion(self): + h=setup();h.carrier=1e-12;call(h,'acquisition.start');h.step(1);self.assertEqual(h.failure,'CARRIER_DEPLETED');self.assertGreaterEqual(h.carrier,0.) + def test_14_interface_auto(self): + h=setup(interface_auto=True);call(h,'acquisition.start');h.step(10.);self.assertLessEqual(h.T[1],h.T[0]+100.1);self.assertledger(h) + def test_15_permissions_idempotency(self): + h=setup();h.register_principal('a');h.register_principal('b');h.register_principal('eval','evaluator');s=h.session('a');b=h.session('b');v=s.describe(instance_id=h.instance_id);self.assertNotIn('sample.identity',v['state_slots']);self.assertNotIn('sample.load',v['capabilities']);self.assertNotIn('cup.temperature_k',s.read(instance_id=h.instance_id)['observations']);args=dict(instance_id=h.instance_id,capability_id='acquisition.start',arguments={},request_id='req');x=s.invoke(**args);self.assertEqual(x,s.invoke(**args));self.assertEqual(s.invoke(**dict(args,capability_id='acquisition.stop'))['error']['code'],'REQUEST_CONFLICT') + with self.assertRaises(r.ActionRejected):b.poll(x['operation_id']) + self.assertEqual(s.cancel(x['operation_id'],'cancel')['status'],'succeeded');self.assertEqual(s.poll(x['operation_id'])['status'],'cancelled');self.assertEqual(s.invoke(instance_id=h.instance_id,capability_id='ledger.read',arguments={},request_id='private')['error']['code'],'ACCESS_DENIED') + def test_16_invalid_time_and_unsupported(self): + h=setup() + for dt in [-1.,True,float('inf'),float('nan')]: + with self.assertRaises(r.ActionRejected):h.step(dt) + for cap in r.UNSUPPORTED: + with self.assertRaisesRegex(r.ActionRejected,'UNSUPPORTED'):h.invoke(cap) +if __name__=='__main__':unittest.main() diff --git a/tests/test_asset_fujifilm_dmp2850.py b/tests/test_asset_fujifilm_dmp2850.py new file mode 100644 index 0000000000000000000000000000000000000000..4b1957cd83bd2fe8282daa0fa1343899a2bc2bdb --- /dev/null +++ b/tests/test_asset_fujifilm_dmp2850.py @@ -0,0 +1,119 @@ +"""CHEM-058 runtime contract, finite ink and uncalibrated physical invariants.""" +import copy,math,unittest +from scripts.asset_runtime import fujifilm_dmp2850 as m +def ready(ink=None,method=None,sample=None,pattern=None): + r=m.FujifilmDmp2850Runtime() + for k,a in [('plant',m.PLANT_EXAMPLE),('ink',ink or m.INK_EXAMPLE),('method',method or m.METHOD_EXAMPLE),('substrate',sample or m.SAMPLE_EXAMPLE),('pattern',pattern or m.PATTERN_EXAMPLE)]:r.invoke(k+'.configure',**copy.deepcopy(a)) + r.invoke('power.set',enabled=True);r.invoke('vacuum.set',enabled=True);return r +def first_flight(r): + r.invoke('acquisition.start') + speeds=[r.plant['axis_speed_m_s']]*2+[r.plant['manual_speed_m_s'],r.plant['manual_angle_rad_s']] + t=max(abs(a-b)/v for a,b,v in zip(r.q,r.target,speeds)) + r.step(max(1e-8,t));assert r.flight is not None +class TestDmp2850(unittest.TestCase): + def assertLedger(self,r): + p=r._product() + for sp in ['solvent','solute']: + self.assertAlmostEqual(p['initial_'+sp+'_kg'],sum(p[loc+'_'+sp+'_kg'] for loc in ['cartridge','flight','deposit','waste','evaporated','collected']),delta=1e-17) + def rejected(self,r,k,**a): + before=r.debug_snapshot() + with self.assertRaises(m.ActionRejected):r.invoke(k,**a) + self.assertEqual(before,r.debug_snapshot()) + def test_specs_picoliter_and_pitch(self): + self.assertEqual(m.DROP_VOLUME,2.4e-15);self.assertAlmostEqual(m.PITCH,338.6666666667e-6) + self.assertAlmostEqual(math.degrees(math.asin(20e-6/m.PITCH)),3.3855,places=3) + def test_configuration_after_world_time(self): + r=m.FujifilmDmp2850Runtime();r.step(.02);r.invoke('plant.configure',**m.PLANT_EXAMPLE);self.assertTrue(r.read()['plant.configured']) + def test_read_and_describe_are_pure(self): + r=ready();before=r.debug_snapshot() + for _ in range(3):r.read();r.describe();r.session().read(instance_id=r.instance_id) + self.assertEqual(before,r.debug_snapshot()) + def test_set_temperature_only_target(self): + r=ready();r.invoke('thermal.set_temperature',platen_k=313.15,cartridge_k=308.15);self.assertEqual(r.temps,[298.15,298.15]);self.assertEqual(r.temp_targets,[313.15,308.15]) + def test_thermal_energy_balance_and_cooldown(self): + r=ready();r.invoke('thermal.set_temperature',platen_k=323.15,cartridge_k=318.15);r.invoke('thermal.set_enabled',enabled=True);r.step(20);self.assertGreater(r.temps[0],298.15);self.assertLess(r.temps[0],323.15) + t=r.temps[:];r.invoke('power.set',enabled=False);r.step(20);self.assertTrue(all(a=-1e-14 for loc in LOCS for v in p[loc+'_kg'])) + def test_default_conservation_and_finite_time(self): + h=prepared();h.invoke('acquisition.start');h.step(60);self.assertEqual(h.phase,'succeeded');self.assertEqual(h.elapsed_s,60.);self.conserve(h) + def test_no_fluidization_atomic_start(self): + h=prepared(method=dict(METHOD_EXAMPLE,air_normal_m3_s=1e-9));self.atomic(h,'acquisition.start');self.assertFalse(h.air) + def test_drop_air_flow_stops_with_partial_material(self): + h=prepared();h.invoke('acquisition.start');h.step(5);h.invoke('fluidization.set_flow',flow_normal_m3_s=0.);h.step(.02);self.assertEqual(h.phase,'failed');self.assertEqual(h.warning,'NOT_FLUIDIZED');self.conserve(h) + def test_total_air_includes_atomizer(self): + h=prepared();self.atomic(h,'fluidization.set_flow',flow_normal_m3_s=100/3600);h.invoke('fluidization.set_flow',flow_normal_m3_s=97/3600);h.invoke('acquisition.start');self.assertAlmostEqual(h._utility(),100/3600) + def test_power_kva_not_kw(self): + h=GlattMiniglattRuntime();self.atomic(h,'plant.configure',**dict(PLANT_EXAMPLE,heater_w=3300.)) + def test_inlet_power_limited(self): + h=prepared(plant=dict(PLANT_EXAMPLE,heater_w=30.));h.invoke('acquisition.start');self.assertLess(h.read()['thermal.inlet_k'],333.15);self.assertGreater(h.read()['thermal.inlet_k'],298.15) + def test_inlet_80_limit_atomic(self): + h=prepared();h.invoke('thermal.set_temperature',temperature_k=353.15);self.atomic(h,'thermal.set_temperature',temperature_k=353.16) + def test_temperature_target_not_bed_jump(self): + h=prepared();t=h._temperature();h.invoke('thermal.set_temperature',temperature_k=353.15);self.assertEqual(t,h._temperature()) + def test_pump_100ml_min_limit(self): + h=prepared();h.invoke('spray.set_rate',flow_m3_s=100e-6/60);self.atomic(h,'spray.set_rate',flow_m3_s=100.01e-6/60) + def test_finite_tank_exhaustion(self): + h=prepared(liquid=dict(LIQUID_EXAMPLE,volume_m3=.2e-6));h.invoke('acquisition.start');h.step(10);self.assertLess(sum(h.mass['tank']),1e-15);self.assertGreater(sum(h.mass['bed']),.08);self.conserve(h) + def test_spray_stops_after_scheduled_window(self): + h=prepared();h.invoke('acquisition.start');h.step(45);mass=copy.deepcopy(h.mass['tank']);h.step(15);self.assertEqual(mass,h.mass['tank']) + def test_standard_25g_lower_limit(self): + h=GlattMiniglattRuntime();h.invoke('plant.configure',**PLANT_EXAMPLE);self.atomic(h,'powder.load',**dict(POWDER_EXAMPLE,dry_mass_kg=.02499));h.invoke('powder.load',**dict(POWDER_EXAMPLE,dry_mass_kg=.025)) + def test_standard_375g_upper_limit(self): + h=GlattMiniglattRuntime();h.invoke('plant.configure',**PLANT_EXAMPLE);h.invoke('powder.load',**dict(POWDER_EXAMPLE,dry_mass_kg=.375)) + def test_micro_minimum_and_bottom(self): + h=prepared(micro=True,powder=dict(POWDER_EXAMPLE,dry_mass_kg=.0025,water_mass_kg=0.),method=dict(METHOD_EXAMPLE,spray_position='bottom'));h.invoke('acquisition.start');h.step(1);self.conserve(h) + def test_micro_top_rejected(self): + h=GlattMiniglattRuntime();h.invoke('plant.configure',**PLANT_EXAMPLE);h.invoke('kit.configure',micro=True,micro_maximum_kg=.025,accept_host_attachment=True);self.atomic(h,'method.configure',**METHOD_EXAMPLE) + def test_micro_unknown_max_explicit(self): + h=GlattMiniglattRuntime();h.invoke('plant.configure',**PLANT_EXAMPLE);h.invoke('kit.configure',micro=True,micro_maximum_kg=.01,accept_host_attachment=True);self.atomic(h,'powder.load',**dict(POWDER_EXAMPLE,dry_mass_kg=.02)) + def test_drying_no_spray(self): + h=prepared(method=dict(METHOD_EXAMPLE,operation='drying',spray_m3_s=0.,spray_duration_s=0.));h.invoke('acquisition.start');h.step(60);self.assertAlmostEqual(h.mass['tank'][1],.0018);self.assertAlmostEqual(h.mass['tank'][2],.0282);self.assertGreater(h.mass['vapor'][2],0.);self.conserve(h) + def test_coating_conserves_particle_count(self): + h=prepared(method=dict(METHOD_EXAMPLE,operation='coating'));n=h.n_initial;h.invoke('acquisition.start');h.step(60);self.assertAlmostEqual(sum(h.particles.values())/n,1.,places=11);self.assertGreater(h._diameter(),POWDER_EXAMPLE['seed_diameter_m']);self.conserve(h) + def test_aggregation_reduces_count(self): + h=prepared(powder=dict(POWDER_EXAMPLE,breakage_s_inv=0.,aggregation_s_inv=.2));h.invoke('acquisition.start');h.step(60);self.assertLess(sum(h.particles.values()),h.n_initial);self.assertGreater(h._diameter(),100e-6) + def test_breakage_no_mass_loss(self): + h=prepared(powder=dict(POWDER_EXAMPLE,aggregation_s_inv=0.,breakage_s_inv=.0001));h.invoke('acquisition.start');h.step(10);self.assertGreater(sum(h.particles.values()),h.n_initial);self.conserve(h) + def test_filter_clog_fails(self): + h=prepared(plant=dict(PLANT_EXAMPLE,filter_resistance_pa_per_kg=1e8,filter_trip_pa=100.));h.invoke('acquisition.start');h.step(2);self.assertEqual(h.phase,'failed');self.assertEqual(h.warning,'FILTER_CLOGGED');self.conserve(h) + def test_blowback_requires_step_and_returns_fraction(self): + h=prepared();h.invoke('acquisition.start');h.step(20);h.invoke('acquisition.stop');old=copy.deepcopy(h.mass['filter']);air=h.air_used + h.invoke('filter.clean');self.assertEqual(old,h.mass['filter']);h.step(.5) + for a,b in zip(old,h.mass['filter']):self.assertAlmostEqual(b,a*.15,delta=1e-14) + self.assertAlmostEqual(h.air_used-air,100/3600*.5,delta=1e-12);self.conserve(h) + def test_blowback_not_during_run(self): + h=prepared();h.invoke('acquisition.start');self.atomic(h,'filter.clean') + def test_open_tower_interrupts_preserves(self): + h=prepared();h.invoke('acquisition.start');h.step(10);h.invoke('tower.set',opened=True);m=copy.deepcopy(h.mass);h.step(10);self.assertEqual(m,h.mass);self.assertEqual(h.phase,'cancelled');self.conserve(h) + def test_power_loss_preserves(self): + h=prepared();h.invoke('acquisition.start');h.step(10);h.invoke('power.set',enabled=False);m=copy.deepcopy(h.mass);h.step(10);self.assertEqual(m,h.mass);self.assertFalse(h.air);self.conserve(h) + def test_collection_keeps_filter_and_heat(self): + h=prepared();h.invoke('acquisition.start');h.step(60);f=copy.deepcopy(h.mass['filter']);h.invoke('tower.set',opened=True);h.invoke('product.collect',recipient_id='receiver');self.assertEqual(f,h.mass['filter']);self.assertEqual(sum(h.mass['bed']),0.);self.conserve(h) + def test_no_rebind_powder_or_liquid(self): + h=prepared();h.invoke('tower.set',opened=True);self.atomic(h,'powder.load',**POWDER_EXAMPLE);self.atomic(h,'liquid.load',**LIQUID_EXAMPLE) + def test_heater_requires_flow(self): + h=prepared();self.atomic(h,'heating.set',enabled=True) + def test_queries_read_describe_pure(self): + h=prepared();before=h.debug_snapshot() + h.read();h.session().read(instance_id=h.instance_id);h.session().describe(instance_id=h.instance_id) + for k in ['product.read','granulation.measure']:h.invoke(k) + h.invoke('reference.lookup',substance_id='mutylo_g1');self.assertEqual(before,h.debug_snapshot()) + def test_real_sieve_not_DLS(self): + h=prepared();x=h.invoke('reference.lookup',substance_id='mutylo_g2');self.assertGreater(x['mass_fraction'][0],.5);self.assertEqual(x['median_interval_m'][0],0.);self.assertAlmostEqual(x['median_interval_m'][1],90e-6);self.assertTrue(x['last_bin_open']);self.assertEqual(x['evidence'],'measured_literature') + def test_truth_filter(self): + h=prepared();s=h.session();self.assertNotIn('truth.ledger',s.describe(instance_id=h.instance_id)['state_slots']) + self.assertEqual(s.invoke(instance_id=h.instance_id,capability_id='product.read',arguments={},request_id='x')['error']['code'],'ACCESS_DENIED') + with self.assertRaises(ActionRejected):s.read(instance_id=h.instance_id,state_ids=['truth.ledger']) + def test_session_idempotency_conflict(self): + h=prepared();s=h.session();a=dict(instance_id=h.instance_id,capability_id='acquisition.start',arguments={},request_id='once');r=s.invoke(**a);before=h.debug_snapshot();self.assertEqual(r,s.invoke(**a));self.assertEqual(before,h.debug_snapshot());self.assertEqual(s.invoke(**dict(a,capability_id='acquisition.stop'))['error']['code'],'REQUEST_CONFLICT') + def test_poll_owner_and_cancel_partial(self): + h=prepared();s=h.session();h.register_principal('other');op=s.invoke(instance_id=h.instance_id,capability_id='acquisition.start',arguments={},request_id='a')['operation_id'];h.step(3) + with self.assertRaises(ActionRejected):h.session('other').poll(op) + s.cancel(op,'cancel');self.assertEqual(s.poll(op)['status'],'cancelled');self.conserve(h) + def test_write_route(self): + h=prepared();h.session().write(instance_id=h.instance_id,state_id='thermal.target_k',value=340.,request_id='temp');self.assertEqual(h.method['temperature_k'],340.) + with self.assertRaises(ActionRejected):h.session().write(instance_id=h.instance_id,state_id='truth.ledger',value={},request_id='bad') + def test_foreign_instance(self): + h=prepared();self.assertEqual(h.session().invoke(instance_id='foreign',capability_id='power.set',arguments={'enabled':False},request_id='x')['error']['code'],'UNKNOWN_INSTANCE');self.assertTrue(h.powered) + def test_panel_toggles(self): + h=prepared();h.invoke('air.toggle');self.assertTrue(h.air);h.invoke('heating.toggle');self.assertTrue(h.heating);h.invoke('air.toggle');self.assertFalse(h.heating) + def test_panel_heat_toggle_atomic_without_air(self): + h=prepared();self.atomic(h,'heating.toggle') + def test_two_instances_isolated(self): + a=prepared();b=prepared();before=b.debug_snapshot();a.invoke('acquisition.start');a.step(10);self.assertEqual(before,b.debug_snapshot()) + def test_nan_bool_and_unknown_atomic(self): + h=prepared();self.atomic(h,'spray.set_rate',flow_m3_s=True);self.atomic(h,'fluidization.set_flow',flow_normal_m3_s=float('nan'));self.atomic(h,'reference.lookup',substance_id='missing') + def test_zero_and_invalid_time(self): + h=prepared();before=h.debug_snapshot();h.step(0);self.assertEqual(before,h.debug_snapshot()) + with self.assertRaises(ActionRejected):h.step(-1) + def test_time_partition_selected_case(self): + a=prepared();b=prepared();a.invoke('acquisition.start');b.invoke('acquisition.start');a.step(60) + for _ in range(6000):b.step(.01) + for loc in LOCS: + for x,y in zip(a.mass[loc],b.mass[loc]):self.assertAlmostEqual(x,y,delta=2e-7) + self.assertAlmostEqual(a._temperature(),b._temperature(),delta=.005);self.conserve(a);self.conserve(b) + def test_normal_flow_conversion_and_ergun_weight(self): + h=prepared();h.invoke('acquisition.start');x=h._hydraulics();q,t,_=h._gas();self.assertAlmostEqual(x['u'],q*t/273.15/PLANT_EXAMPLE['bed_area_m2']);self.assertTrue(x['fluidized']);self.assertLess(x['dp'],sum(h.mass['bed'])*9.80665/PLANT_EXAMPLE['bed_area_m2']) +if __name__=='__main__':unittest.main() diff --git a/tests/test_asset_ika_t25.py b/tests/test_asset_ika_t25.py new file mode 100644 index 0000000000000000000000000000000000000000..8fd6caa91b34b534d2c1e7c9765cbbc4167e367a --- /dev/null +++ b/tests/test_asset_ika_t25.py @@ -0,0 +1,87 @@ +import copy,math,sys,unittest +from pathlib import Path +ROOT=Path(__file__).resolve().parents[1];sys.path.insert(0,str(ROOT/'scripts')) +from asset_runtime.ika_t25 import * +def prepared(i='t25_01',plant=None,sample=None,method=None): + r=IkaT25Runtime(i);r.invoke('plant.configure',**(plant or PLANT_EXAMPLE));r.invoke('method.configure',**(method or METHOD_EXAMPLE));r.invoke('sample.configure',**(sample or example_sample()));r.invoke('mount.configure',head_locked=True,vessel_clamped=True);r.invoke('power.set',enabled=True);r.step(2);return r +class T25Test(unittest.TestCase): + def test_target_not_teleport(self): + r=prepared();r.invoke('acquisition.start');r.step(.2);w=r.speed;r.invoke('motor.set_speed',speed_rad_s=MAX_SPEED);self.assertEqual(w,r.speed);r.step(.1);self.assertGreater(r.speed,w) + def test_queries_pure(self): + r=prepared();s=r.debug_snapshot();r.describe();r.read();r.invoke('dispersion.measure');r.invoke('product.read');self.assertEqual(s,r.debug_snapshot()) + def test_rejected_atomic(self): + r=prepared();r.invoke('acquisition.start');s=r.debug_snapshot() + with self.assertRaises(ActionRejected):r.invoke('mount.set_immersion',immersion_m=.065) + self.assertEqual(s,r.debug_snapshot()) + def test_missing_mount(self): + r=prepared();r.invoke('mount.configure',head_locked=False,vessel_clamped=True) + with self.assertRaises(ActionRejected):r.invoke('acquisition.start') + def test_speed_si(self): + r=prepared() + for w in [2999*math.tau/60,25001*math.tau/60,True,float('nan'),float('inf')]: + with self.assertRaises(ActionRejected):r.invoke('motor.set_speed',speed_rad_s=w) + def test_step_invalid(self): + r=prepared() + for x in [True,-1,float('nan'),float('inf'),3601]: + with self.assertRaises(ActionRejected):r.step(x) + def test_viscosity_si(self): + s=example_sample();s['viscosity_Pa_s']=5000 + with self.assertRaises(ActionRejected):prepared(sample=s) + def test_head_not_st(self): + m=copy.deepcopy(METHOD_EXAMPLE);m['head']='s25_n18g_st' + with self.assertRaises(ActionRejected):prepared(method=m) + def test_no_timer_invention(self): + m=copy.deepcopy(METHOD_EXAMPLE);m['duration_s']=61 + with self.assertRaises(ActionRejected):prepared(method=m) + def test_bottom_clearance(self): + r=prepared();s=r.debug_snapshot() + with self.assertRaises(ActionRejected):r.invoke('mount.set_immersion',immersion_m=.10) + self.assertEqual(s,r.debug_snapshot()) + def test_lift_on_step(self): + r=prepared();r.invoke('mount.set_immersion',immersion_m=.065);self.assertEqual(r.lift,0.) + with self.assertRaises(ActionRejected):r.invoke('acquisition.start') + r.step(.2);self.assertAlmostEqual(r.lift,-.005);r.invoke('acquisition.start') + def test_too_small_vessel_volume(self): + s=example_sample();s['carrier_mass_kg']=.001;s['dispersed_mass_kg']=0. + with self.assertRaises(ActionRejected):prepared(sample=s) + def test_mass_conservation(self): + r=prepared();r.invoke('acquisition.start');r.step(8);self.assertEqual(r.mass,r.initial);r.invoke('product.collect',fraction=.3,recipient_id='vial') + for a,b,c in zip(r.initial,r.mass,r.collected):self.assertAlmostEqual(a,b+c) + def test_energy_balance(self): + r=prepared();r.invoke('acquisition.start');r.step(8);self.assertAlmostEqual(r.heat,r.storage+r.loss,places=8);self.assertLessEqual(r.heat,r.energy);self.assertGreater(r.temperature,298.15) + def test_breakup_no_mass_creation(self): + r=prepared();r.invoke('acquisition.start');r.step(8);self.assertLess(r.size,r.sample['initial_size_m']);self.assertGreaterEqual(r.size,r.plant['minimum_size_m']);self.assertEqual(r.mass,r.initial) + def test_cancel_coast_partial(self): + r=prepared();r.invoke('acquisition.start');r.step(1);e=r.energy;d=r.size;mass=r.mass.copy();r.invoke('acquisition.stop');self.assertGreater(r.speed,0);r.step(2);self.assertEqual(r.speed,0);self.assertEqual(r.phase,'cancelled');self.assertGreater(r.energy,e);self.assertLessEqual(r.size,d);self.assertEqual(mass,r.mass) + def test_completion(self): + r=prepared();r.invoke('acquisition.start');r.step(8);self.assertEqual(r.phase,'succeeded');self.assertEqual(r.speed,0);self.assertAlmostEqual(r.elapsed_s,5) + def test_power_no_restart(self): + r=prepared();r.invoke('acquisition.start');r.step(1);r.invoke('power.set',enabled=False);r.step(2);r.invoke('power.set',enabled=True);r.step(1);self.assertFalse(r.motor);self.assertEqual(r.speed,0);self.assertEqual(r.phase,'cancelled') + def test_dual_isolation(self): + a=prepared('a');b=prepared('b');snap=b.debug_snapshot();a.invoke('acquisition.start');a.step(5);self.assertEqual(snap,b.debug_snapshot()) + def test_permissions(self): + r=prepared();s=r.session();self.assertNotIn('truth.mass_kg',s.read(instance_id=r.instance_id)['observations']);self.assertNotIn('product.read',s.describe(instance_id=r.instance_id)['capabilities']);self.assertEqual(s.invoke(instance_id=r.instance_id,capability_id='product.read',arguments={},request_id='bad')['error']['code'],'ACCESS_DENIED') + def test_idempotency(self): + r=prepared();s=r.session();kw=dict(instance_id=r.instance_id,capability_id='acquisition.start',arguments={},request_id='a');a=s.invoke(**kw);snap=r.debug_snapshot();self.assertEqual(a,s.invoke(**kw));self.assertEqual(snap,r.debug_snapshot()) + def test_poll_cancel_ownership(self): + r=prepared();s=r.session();r.register_principal('second','agent');op=s.invoke(instance_id=r.instance_id,capability_id='acquisition.start',arguments={},request_id='start')['operation_id'];r.step(1) + with self.assertRaises(ActionRejected):r.session('second').poll(op) + self.assertEqual(s.cancel(op,'cancel')['status'],'cancelled');self.assertEqual(s.cancel(op,'cancel')['status'],'cancelled') + def test_external_observation(self): + r=prepared();self.assertIsNone(r.invoke('observation.read')['temperature_K']);r.invoke('observation.record',temperature_K=299.,size_m=.0001,measurement_source='external');self.assertEqual(r.invoke('observation.read')['temperature_K'],299.);self.assertEqual(r.temperature,298.15) + def test_reference_real_drives_capacity(self): + r=prepared();cp=r.invoke('reference.lookup',substance_id='water');self.assertTrue(4100