Add files using upload-large-folder tool
Browse filesThis view is limited to 50 files because it contains too many changes. See raw diff
- tests/test_asset_agilent_1290infinity.py +94 -0
- tests/test_asset_antonpaar_autosorb6100.py +110 -0
- tests/test_asset_antonpaar_litesizerdia.py +111 -0
- tests/test_asset_antonpaar_litesizerdls.py +114 -0
- tests/test_asset_antonpaar_poremaster60.py +148 -0
- tests/test_asset_antonpaar_psa1190.py +113 -0
- tests/test_asset_antonpaar_surpass3.py +76 -0
- tests/test_asset_antonpaar_ultrapyc5000.py +113 -0
- tests/test_asset_applied_sx20.py +203 -0
- tests/test_asset_arradiance_gemstarxt.py +177 -0
- tests/test_asset_biolin_sigma700.py +118 -0
- tests/test_asset_biolin_thetaflex.py +139 -0
- tests/test_asset_biotage_selekt.py +88 -0
- tests/test_asset_bruker_magnettechesr5000.py +186 -0
- tests/test_asset_bruker_minispecmq20.py +127 -0
- tests/test_asset_buchi_encapsulatorb.py +89 -0
- tests/test_asset_buchi_hydrolexh.py +106 -0
- tests/test_asset_ch_chi440c.py +71 -0
- tests/test_asset_ch_chi920d.py +76 -0
- tests/test_asset_cytiva_nanoassemblrignite.py +151 -0
- tests/test_asset_edinburgh_fls1000tcspc.py +214 -0
- tests/test_asset_elementar_isoprimeprecision.py +560 -0
- tests/test_asset_elementar_varioel.py +199 -0
- tests/test_asset_freeman_ft4powder.py +141 -0
- tests/test_asset_frontier_egapy.py +76 -0
- tests/test_asset_fujifilm_dmp2850.py +119 -0
- tests/test_asset_gas_flavourspec25gc.py +88 -0
- tests/test_asset_glatt_miniglatt.py +121 -0
- tests/test_asset_ika_t25.py +87 -0
- tests/test_asset_jasco_cpl300.py +213 -0
- tests/test_asset_jasco_fp8350.py +199 -0
- tests/test_asset_jasco_fvs6000.py +219 -0
- tests/test_asset_jasco_j1500.py +177 -0
- tests/test_asset_jasco_nrs5500.py +210 -0
- tests/test_asset_jasco_p4200.py +213 -0
- tests/test_asset_jena_contraa800.py +245 -0
- tests/test_asset_jena_multix.py +212 -0
- tests/test_asset_knauer_k7400s.py +86 -0
- tests/test_asset_laboao_cvdltf12p50.py +184 -0
- tests/test_asset_leco_onh836.py +172 -0
- tests/test_asset_linari_rtadvanced.py +125 -0
- tests/test_asset_malvern_leneo.py +101 -0
- tests/test_asset_markes_unityxr.py +85 -0
- tests/test_asset_metrohm_909uv.py +83 -0
- tests/test_asset_micromeritics_autochemiii.py +160 -0
- tests/test_asset_milestone_dma80.py +223 -0
- tests/test_asset_ossila_dipcoater.py +107 -0
- tests/test_asset_ossila_doctorblade.py +117 -0
- tests/test_asset_ossila_slotdie.py +123 -0
- tests/test_asset_ossila_spincoater.py +146 -0
tests/test_asset_agilent_1290infinity.py
ADDED
|
@@ -0,0 +1,94 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from pathlib import Path
|
| 2 |
+
import sys,unittest,copy,json,importlib.util,math
|
| 3 |
+
ROOT=Path(__file__).resolve().parents[1];sys.path.insert(0,str(ROOT/'scripts'))
|
| 4 |
+
from asset_runtime.agilent_1290infinity import *
|
| 5 |
+
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)
|
| 6 |
+
OBSERVED=set()
|
| 7 |
+
def call(r,k,**a):
|
| 8 |
+
v=r.invoke(k,**a);err=tool.validate_value(v,CAPS[k][1]);assert not err,err;OBSERVED.add(k);return v
|
| 9 |
+
def prepared(plant=None,method=None,sample=None):
|
| 10 |
+
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
|
| 11 |
+
class SEC(unittest.TestCase):
|
| 12 |
+
def test_metadata_and_schema(self):
|
| 13 |
+
r=prepared();m=r.describe()
|
| 14 |
+
for k,c in m['capabilities'].items():
|
| 15 |
+
errors=tool.validate_value(c['example_arguments'],c['input_schema']);self.assertEqual(errors,[])
|
| 16 |
+
for k,v in r.read('evaluator').items():errors=tool.validate_value(v,m['state_slots'][k]['value_schema']);self.assertEqual(errors,[])
|
| 17 |
+
def test_setpoint_and_pure_queries(self):
|
| 18 |
+
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)
|
| 19 |
+
def test_pressure_derating_and_atomic_rejection(self):
|
| 20 |
+
p=copy.deepcopy(PLANT_EXAMPLE)
|
| 21 |
+
for c in p['columns']:c.update(resistance_pa_s_m3=1.2e15,max_pressure_pa=1.3e8)
|
| 22 |
+
r=Agilent1290infinityRuntime();call(r,'plant.configure',**p);before=copy.deepcopy(r.__dict__)
|
| 23 |
+
with self.assertRaisesRegex(ActionRejected,'PRESSURE_LIMIT'):r.invoke('method.configure',**dict(METHOD_EXAMPLE,flow_m3_s=5e-6/60))
|
| 24 |
+
self.assertEqual(r.__dict__,before)
|
| 25 |
+
def test_invalid_nan_bool_extra(self):
|
| 26 |
+
r=prepared()
|
| 27 |
+
for a in [{'enabled':1},{'enabled':True,'extra':3}]:
|
| 28 |
+
with self.assertRaises(ActionRejected):r.invoke('pump.set',**a)
|
| 29 |
+
for dt in [True,float('nan'),-1.,float('inf')]:
|
| 30 |
+
before=copy.deepcopy(r.__dict__)
|
| 31 |
+
with self.assertRaises(ActionRejected):r.step(dt)
|
| 32 |
+
self.assertEqual(r.__dict__,before)
|
| 33 |
+
def test_all_templates_and_families(self):
|
| 34 |
+
r=Agilent1290infinityRuntime();self.assertEqual(len(r.templates),73);self.assertEqual(len({v['polymer_family'] for v in r.templates.values()}),3)
|
| 35 |
+
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'])
|
| 36 |
+
def test_configuration_and_access_motion(self):
|
| 37 |
+
r=prepared()
|
| 38 |
+
for k,a in [('door.set',{'angle_rad':1.}),('drawer.set',{'position_m':.2}),('column_cover.set',{'angle_rad':1.})]:
|
| 39 |
+
before=copy.deepcopy(r.__dict__)
|
| 40 |
+
with self.assertRaisesRegex(ActionRejected,'BUSY'):r.invoke(k,**a)
|
| 41 |
+
self.assertEqual(r.__dict__,before)
|
| 42 |
+
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.)
|
| 43 |
+
def test_complete_conservation(self):
|
| 44 |
+
r=prepared();call(r,'acquisition.start')
|
| 45 |
+
for _ in range(120):r.step(1.)
|
| 46 |
+
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)
|
| 47 |
+
def test_cancel_partial_and_other_instance(self):
|
| 48 |
+
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.)
|
| 49 |
+
def test_exhaustion_failure(self):
|
| 50 |
+
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)
|
| 51 |
+
def test_unload_preserves_column(self):
|
| 52 |
+
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)
|
| 53 |
+
def test_calibration_moments_from_signal(self):
|
| 54 |
+
r=prepared();call(r,'calibration.fit',**CAL_EXAMPLE);call(r,'acquisition.start')
|
| 55 |
+
for _ in range(1200):r.step(.1)
|
| 56 |
+
a=call(r,'molecular_weight.analyze');self.assertEqual(a['quality'],'estimated_relative');self.assertAlmostEqual(a['mass_kg'],2e-9,delta=1e-12)
|
| 57 |
+
# Independent analytic logM mixture moments from nominal source material values.
|
| 58 |
+
D=1.02;expected_mw=(20.+100.)/2*math.sqrt(D);expected_mn=2/(1/20.+1/100.)/math.sqrt(D)
|
| 59 |
+
self.assertAlmostEqual(a['mw_kg_mol']/expected_mw,1,delta=.003);self.assertAlmostEqual(a['mn_kg_mol']/expected_mn,1,delta=.003)
|
| 60 |
+
r.sample['solutes'][0]['concentration_kg_m3']=50.;r.sample['sample_id']='secret_changed';self.assertEqual(call(r,'molecular_weight.analyze'),a)
|
| 61 |
+
def test_invalid_calibration_and_outside(self):
|
| 62 |
+
r=prepared();before=copy.deepcopy(r.__dict__)
|
| 63 |
+
with self.assertRaises(ActionRejected):r.invoke('calibration.fit',**dict(CAL_EXAMPLE,points=[CAL_EXAMPLE['points'][0]]*2))
|
| 64 |
+
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')
|
| 65 |
+
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')
|
| 66 |
+
def test_saturated_signal_is_not_quantified(self):
|
| 67 |
+
s=copy.deepcopy(SAMPLE_EXAMPLE)
|
| 68 |
+
for v in s['solutes']:v['concentration_kg_m3']=100.
|
| 69 |
+
r=prepared(sample=s);call(r,'calibration.fit',**CAL_EXAMPLE);call(r,'acquisition.start')
|
| 70 |
+
for _ in range(1200):r.step(.1)
|
| 71 |
+
self.assertTrue(r.saturated);self.assertEqual(call(r,'molecular_weight.analyze')['quality'],'saturated')
|
| 72 |
+
def test_session_truth_dedup_cancel_owner(self):
|
| 73 |
+
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
|
| 74 |
+
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')
|
| 75 |
+
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']
|
| 76 |
+
with self.assertRaises(ActionRejected):b.poll(op)
|
| 77 |
+
r.step(60);self.assertEqual(a.poll(op)['status'],'running');a.cancel(op,'stop');self.assertEqual(a.poll(op)['status'],'cancelled')
|
| 78 |
+
def test_partition_mass_and_signal_area(self):
|
| 79 |
+
rs=[prepared(),prepared()]
|
| 80 |
+
for r in rs:call(r,'acquisition.start')
|
| 81 |
+
rs[0].step(120.)
|
| 82 |
+
for _ in range(1200):rs[1].step(.1)
|
| 83 |
+
for k in ['column_kg','eluted_kg','reservoir_m3','waste_m3']:self.assertAlmostEqual(rs[0]._ledger()[k],rs[1]._ledger()[k],delta=1e-12)
|
| 84 |
+
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)
|
| 85 |
+
def test_eight_positions_and_temperature_bounds(self):
|
| 86 |
+
for i in range(8):
|
| 87 |
+
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)
|
| 88 |
+
with self.assertRaises(ActionRejected):r.invoke('method.configure',**dict(METHOD_EXAMPLE,column_index=8))
|
| 89 |
+
with self.assertRaises(ActionRejected):r.invoke('method.configure',**dict(METHOD_EXAMPLE,zone_targets_k=[273.,300.]))
|
| 90 |
+
def test_unsupported(self):
|
| 91 |
+
r=prepared()
|
| 92 |
+
for k in UNSUPPORTED:
|
| 93 |
+
with self.assertRaisesRegex(ActionRejected,'UNSUPPORTED'):r.invoke(k)
|
| 94 |
+
if __name__=='__main__':unittest.main()
|
tests/test_asset_antonpaar_autosorb6100.py
ADDED
|
@@ -0,0 +1,110 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from pathlib import Path
|
| 2 |
+
import sys,math,copy,json,hashlib,unittest,importlib.util
|
| 3 |
+
ROOT=Path(__file__).resolve().parents[1];sys.path.insert(0,str(ROOT/'scripts'));from asset_runtime import antonpaar_autosorb6100 as r
|
| 4 |
+
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)
|
| 5 |
+
OBSERVED=set()
|
| 6 |
+
def call(h,k,**a):
|
| 7 |
+
v=h.invoke(k,**a);errors=tool.validate_value(v,r.CAPS[k][1]);assert not errors,(k,errors);OBSERVED.add(k);return v
|
| 8 |
+
def configured(ids=(0,),plant=None,method=None):
|
| 9 |
+
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)
|
| 10 |
+
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))
|
| 11 |
+
call(h,'guard.set',angle_rad=0.);call(h,'coolant.fill',volume_m3=.003);call(h,'dewar.set',lift_m=.29);return h
|
| 12 |
+
def finish(h,limit=3600):
|
| 13 |
+
for _ in range(limit):
|
| 14 |
+
h.step(1.)
|
| 15 |
+
if h.phase!='running':break
|
| 16 |
+
return call(h,'process.measure')
|
| 17 |
+
def balances(h):
|
| 18 |
+
d=call(h,'ledger.read')
|
| 19 |
+
for k in ['n2_residual_mol','sample_residual_kg','ln2_residual_kg','water_residual_kg']:assert abs(d[k])<1e-10,(k,d[k])
|
| 20 |
+
for k in ['manifold_energy_residual_j','degas_energy_residual_j']:assert abs(d[k])<1e-6,(k,d[k])
|
| 21 |
+
return d
|
| 22 |
+
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.)
|
| 23 |
+
class AutosorbTests(unittest.TestCase):
|
| 24 |
+
def test_01_source_integrity_and_real_count(self):
|
| 25 |
+
self.assertEqual(len(r.LIB['substances']),100)
|
| 26 |
+
for sid,v in r.LIB['substances'].items():
|
| 27 |
+
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:])))
|
| 28 |
+
def test_02_full_pressure_inversion(self):
|
| 29 |
+
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']
|
| 30 |
+
for p in s['points']:
|
| 31 |
+
expected=r.interp(d['pressure_pa'],d['loading_mol_kg'],p['pressure_pa']);self.assertLess(abs(p['loading_mol_kg']/expected-1),.002)
|
| 32 |
+
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)
|
| 33 |
+
def test_03_three_independent_stations(self):
|
| 34 |
+
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)
|
| 35 |
+
def test_04_mass_readout_independent_truth(self):
|
| 36 |
+
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)
|
| 37 |
+
def test_05_free_space_two_temperature(self):
|
| 38 |
+
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)
|
| 39 |
+
before=copy.deepcopy(h.__dict__)
|
| 40 |
+
with self.assertRaises(r.ActionRejected):h.invoke('volume.calibrate',**dict(r.VCAL_EXAMPLE,cold_dosed_mol=r.VCAL_EXAMPLE['warm_dosed_mol']))
|
| 41 |
+
self.assertEqual(h.__dict__,before)
|
| 42 |
+
def test_06_pressure_sensor_calibration(self):
|
| 43 |
+
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)
|
| 44 |
+
def test_07_cancel_preserves_resources(self):
|
| 45 |
+
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)
|
| 46 |
+
def test_08_source_depletion_timeout(self):
|
| 47 |
+
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)
|
| 48 |
+
def test_09_dewar_tube_interlocks(self):
|
| 49 |
+
h=configured()
|
| 50 |
+
for k,a in [('guard.set',{'angle_rad':1.5}),('sample0.set',{'drop_m':.18})]:
|
| 51 |
+
with self.assertRaises(r.ActionRejected):h.invoke(k,**a)
|
| 52 |
+
call(h,'acquisition.start',stations=[0])
|
| 53 |
+
with self.assertRaises(r.ActionRejected):h.invoke('dewar.set',lift_m=0.)
|
| 54 |
+
def test_10_finite_backfill_and_unload(self):
|
| 55 |
+
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.)
|
| 56 |
+
with self.assertRaises(r.ActionRejected):h.invoke('sample0.set',drop_m=.18)
|
| 57 |
+
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)
|
| 58 |
+
def test_11_ln2_capacity_and_depletion(self):
|
| 59 |
+
h=configured()
|
| 60 |
+
with self.assertRaises(r.ActionRejected):h.invoke('coolant.fill',volume_m3=.001)
|
| 61 |
+
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)
|
| 62 |
+
def test_12_degas_six_samples_two_heaters(self):
|
| 63 |
+
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)
|
| 64 |
+
for b in range(2):call(h,'heater'+str(b)+'.set',drop_m=.16)
|
| 65 |
+
for i in range(6):call(h,'degas.load',**dict(r.DLOAD_EXAMPLE,slot=i,water_rate_at_373_s=.1))
|
| 66 |
+
for b in range(2):call(h,'heater'+str(b)+'.set',drop_m=0.)
|
| 67 |
+
call(h,'degas.start',**dict(r.DPROGRAM_EXAMPLE,steps=[dict(temperature_k=333.15,hold_s=220.)],ramp_k_s=5.))
|
| 68 |
+
h.step(250.);self.assertEqual(h.degas_phase,'succeeded');self.assertTrue(h.read('evaluator')['degas.dry_enough']);self.assertGreater(h.trap,5e-5)
|
| 69 |
+
h.step(150.)
|
| 70 |
+
for b in range(2):call(h,'heater'+str(b)+'.set',drop_m=.16)
|
| 71 |
+
for i in range(6):call(h,'degas.unload',slot=i)
|
| 72 |
+
balances(h)
|
| 73 |
+
def test_13_degas_cancel_and_hot_interlock(self):
|
| 74 |
+
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.)
|
| 75 |
+
with self.assertRaises(r.ActionRejected):h.invoke('heater0.set',drop_m=.16)
|
| 76 |
+
call(h,'degas.stop');before=h.dtemps[0];h.step(5.);self.assertLess(h.dtemps[0],before);balances(h)
|
| 77 |
+
def test_14_trap_capacity_failure(self):
|
| 78 |
+
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)
|
| 79 |
+
def test_15_bet_independent_analytic_curve(self):
|
| 80 |
+
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)
|
| 81 |
+
self.assertIsNone(r.bet_fit([point(.2,0.),point(.3,-1.)])['area_m2_kg'])
|
| 82 |
+
def test_16_bjh_formula_and_branch_guard(self):
|
| 83 |
+
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'],[])
|
| 84 |
+
def test_17_template_range_and_method_validation(self):
|
| 85 |
+
h=configured();call(h,'method.configure',**dict(r.METHOD_EXAMPLE,relative_pressures=[.002,.01,.5,.996]))
|
| 86 |
+
with self.assertRaises(r.ActionRejected):h.invoke('acquisition.start',stations=[0])
|
| 87 |
+
for points in [[.1,.2,.15,.3],[.1]*4,[]]:
|
| 88 |
+
with self.assertRaises(r.ActionRejected):h.invoke('method.configure',**dict(r.METHOD_EXAMPLE,relative_pressures=points))
|
| 89 |
+
for v in [True,float('nan'),float('inf'),-1.]:
|
| 90 |
+
with self.assertRaises(r.ActionRejected):h.step(v)
|
| 91 |
+
def test_18_permissions_dedup_poll_and_write(self):
|
| 92 |
+
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')
|
| 93 |
+
with self.assertRaises(r.ActionRejected):other.poll(op)
|
| 94 |
+
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)
|
| 95 |
+
def test_19_queries_atomicity_and_independent_instances(self):
|
| 96 |
+
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')
|
| 97 |
+
for k in r.UNSUPPORTED:
|
| 98 |
+
with self.assertRaises(r.ActionRejected):h.invoke(k)
|
| 99 |
+
with self.assertRaises(r.ActionRejected):h.invoke('sample0.set',drop_m=True)
|
| 100 |
+
def test_20_fixed_clock_partition_and_slot_schemas(self):
|
| 101 |
+
a=configured();b=configured();call(a,'acquisition.start',stations=[0]);call(b,'acquisition.start',stations=[0]);a.step(20.)
|
| 102 |
+
for _ in range(400):b.step(.05)
|
| 103 |
+
self.assertEqual(a.read('evaluator'),b.read('evaluator'))
|
| 104 |
+
for k,v in a.read('evaluator').items():self.assertFalse(tool.validate_value(v,r.SLOTS[k][0]),(k,v))
|
| 105 |
+
self.assertEqual(set(a.read('evaluator')),set(r.SLOTS));balances(a)
|
| 106 |
+
def test_21_warmup_retained_gas_interlock(self):
|
| 107 |
+
h=configured();call(h,'acquisition.start',stations=[0]);h.step(400.);call(h,'acquisition.stop')
|
| 108 |
+
with self.assertRaises(r.ActionRejected):h.invoke('dewar.set',lift_m=0.)
|
| 109 |
+
h.step(600.);call(h,'dewar.set',lift_m=0.);balances(h)
|
| 110 |
+
if __name__=='__main__':unittest.main()
|
tests/test_asset_antonpaar_litesizerdia.py
ADDED
|
@@ -0,0 +1,111 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import unittest,copy,pickle,math,sys
|
| 2 |
+
from pathlib import Path
|
| 3 |
+
from unittest import mock
|
| 4 |
+
import numpy as np,cv2
|
| 5 |
+
from scripts.asset_runtime import antonpaar_litesizerdia as r
|
| 6 |
+
O=Path(__file__).resolve().parents[1]/'outputs/expansion_batch03/t4_measure/antonpaar_litesizerdia';sys.path.insert(0,str(O));from example_setup import build
|
| 7 |
+
class TestDia(unittest.TestCase):
|
| 8 |
+
def done(self,h,dt=6.):h.invoke('acquisition.start');h.step(dt);self.assertEqual(h.phase,'succeeded',h.error);return h
|
| 9 |
+
def test01_source(self):
|
| 10 |
+
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)
|
| 11 |
+
def test02_rectangle_feret(self):
|
| 12 |
+
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)
|
| 13 |
+
def test03_circle(self):
|
| 14 |
+
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)
|
| 15 |
+
def test04_rle_exact(self):
|
| 16 |
+
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))))
|
| 17 |
+
def test05_real_outline_metadata(self):
|
| 18 |
+
ratios=[]
|
| 19 |
+
for sid in ['grain_capecod','grain_fijipink','grain_hawaii','grain_ottawa1220','grain_peaceriver','grain_vieques']:
|
| 20 |
+
for i in [0,20,40,63]:
|
| 21 |
+
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)
|
| 22 |
+
self.assertLess(max(ratios),.04)
|
| 23 |
+
def test06_three_modes(self):
|
| 24 |
+
for mode in ['liquid','dry','freefall']:
|
| 25 |
+
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)
|
| 26 |
+
def test07_read_pure(self):
|
| 27 |
+
h=build();before=pickle.dumps(h.__dict__)
|
| 28 |
+
for _ in range(5):h.read();h.describe();h._result()
|
| 29 |
+
self.assertEqual(before,pickle.dumps(h.__dict__))
|
| 30 |
+
def test08_setpoint_only(self):
|
| 31 |
+
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)
|
| 32 |
+
def test09_wet_recirculate(self):
|
| 33 |
+
h=self.done(build(count=8));self.assertEqual(len(h.population),8);self.assertEqual(h.waste_n,0);self.assertEqual(h.pass_index,32)
|
| 34 |
+
def test10_dry_finite(self):
|
| 35 |
+
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)
|
| 36 |
+
def test11_freefall_recover(self):
|
| 37 |
+
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.)
|
| 38 |
+
def test12_drain_mass_heat(self):
|
| 39 |
+
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)
|
| 40 |
+
def test13_cancel_partial(self):
|
| 41 |
+
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)
|
| 42 |
+
def test14_air_exhaust(self):
|
| 43 |
+
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.)
|
| 44 |
+
def test15_atomic_reject(self):
|
| 45 |
+
h=build()
|
| 46 |
+
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'))]:
|
| 47 |
+
before=pickle.dumps(h.__dict__)
|
| 48 |
+
with self.assertRaises(r.ActionRejected):h.invoke(k,**a)
|
| 49 |
+
self.assertEqual(before,pickle.dumps(h.__dict__))
|
| 50 |
+
def test16_access(self):
|
| 51 |
+
h=build();h.invoke('lid.set',angle_rad=1.55)
|
| 52 |
+
with self.assertRaisesRegex(r.ActionRejected,'CLOSURE'):h.invoke('acquisition.start')
|
| 53 |
+
h.invoke('lid.set',angle_rad=0.);h.invoke('acquisition.start')
|
| 54 |
+
with self.assertRaisesRegex(r.ActionRejected,'BUSY'):h.invoke('lid.set',angle_rad=1.55)
|
| 55 |
+
def test17_truth_and_instances(self):
|
| 56 |
+
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'])
|
| 57 |
+
with self.assertRaises(r.ActionRejected):a.read(instance_id=g.instance_id,state_ids=['truth.solid_kg'])
|
| 58 |
+
self.assertEqual(a.invoke(instance_id=g.instance_id,capability_id='ledger.read',arguments={},request_id='x')['status'],'rejected')
|
| 59 |
+
def test18_principal_registration(self):
|
| 60 |
+
h=r.AntonpaarLitesizerdiaRuntime();h.register_principal('matterix_agent');h.register_principal('matterix_evaluator','evaluator')
|
| 61 |
+
with self.assertRaises(r.ActionRejected):h.register_principal('matterix_agent','evaluator')
|
| 62 |
+
with self.assertRaises(r.ActionRejected):h.session('unknown')
|
| 63 |
+
def test19_idempotent(self):
|
| 64 |
+
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')
|
| 65 |
+
def test20_async_ownership(self):
|
| 66 |
+
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)
|
| 67 |
+
with self.assertRaises(r.ActionRejected):h.session('other').poll(op)
|
| 68 |
+
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)
|
| 69 |
+
def test21_external_calibration(self):
|
| 70 |
+
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)
|
| 71 |
+
def test22_scale_bias_independent(self):
|
| 72 |
+
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.)
|
| 73 |
+
def test23_high_throughput(self):
|
| 74 |
+
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)
|
| 75 |
+
def test24_resolution_clipping(self):
|
| 76 |
+
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)
|
| 77 |
+
def test25_reconstruction_explicit(self):
|
| 78 |
+
with self.assertRaises(r.ActionRejected):build(sid='powder_001')
|
| 79 |
+
h=self.done(build(sid='powder_001',method={'accept_shape_reconstruction':True}));self.assertIn('synthetic_outline',h.images[0]['evidence'])
|
| 80 |
+
with self.assertRaises(r.ActionRejected):build(sid='powder_050',method={'accept_shape_reconstruction':True})
|
| 81 |
+
with self.assertRaises(r.ActionRejected):build(method={'accept_inferred_source_scale':False})
|
| 82 |
+
def test26_clock_partition(self):
|
| 83 |
+
h=build();g=build();h.invoke('acquisition.start');g.invoke('acquisition.start');h.step(1.23)
|
| 84 |
+
for dt in [.333,.121,.449,.327]:g.step(dt)
|
| 85 |
+
self.assertEqual(h.read(),g.read());self.assertEqual(h._result(),g._result())
|
| 86 |
+
def test27_unsupported_no_fake_sensor(self):
|
| 87 |
+
h=build()
|
| 88 |
+
for k in r.UNSUPPORTED:
|
| 89 |
+
with self.assertRaisesRegex(r.ActionRejected,'UNSUPPORTED'):h.invoke(k)
|
| 90 |
+
self.assertNotIn('temperature.measured_k',h.read());self.assertNotIn('truth.temperature_k',h.read('agent'))
|
| 91 |
+
def test28_query_cannot_steal_operation(self):
|
| 92 |
+
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'])
|
| 93 |
+
with self.assertRaises(r.ActionRejected):o.poll(op)
|
| 94 |
+
self.assertEqual(a.poll(op)['status'],'running')
|
| 95 |
+
def test29_result_source_stable(self):
|
| 96 |
+
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)
|
| 97 |
+
def test30_recovery_truth_requires_evaluator(self):
|
| 98 |
+
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__)
|
| 99 |
+
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)
|
| 100 |
+
def test31_metadata_covers_actual_state_changes(self):
|
| 101 |
+
metadata=r.export_antonpaar_litesizerdia_contract_metadata();original=r.AntonpaarLitesizerdiaRuntime.invoke;observed=set()
|
| 102 |
+
def audited_invoke(h,cap,**arguments):
|
| 103 |
+
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'}
|
| 104 |
+
self.assertFalse(changed-declared,(cap,changed-declared));observed.add(cap);return result
|
| 105 |
+
with mock.patch.object(r.AntonpaarLitesizerdiaRuntime,'invoke',audited_invoke):
|
| 106 |
+
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.)
|
| 107 |
+
for mode in ['dry','freefall']:
|
| 108 |
+
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')
|
| 109 |
+
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')
|
| 110 |
+
self.assertTrue(set(r.IMMEDIATE_EFFECTS)<=observed)
|
| 111 |
+
if __name__=='__main__':unittest.main()
|
tests/test_asset_antonpaar_litesizerdls.py
ADDED
|
@@ -0,0 +1,114 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import sys,unittest,copy,math,json
|
| 2 |
+
from pathlib import Path
|
| 3 |
+
from unittest import mock
|
| 4 |
+
import numpy as np
|
| 5 |
+
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
|
| 6 |
+
rt=ex.rt
|
| 7 |
+
class TestLitesizerDls(unittest.TestCase):
|
| 8 |
+
def ready(self,**kw):return ex.configure(rt.AntonpaarLitesizerdlsRuntime(),**kw)
|
| 9 |
+
def test_01_source_integrity(self):
|
| 10 |
+
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)
|
| 11 |
+
def test_02_independent_stokes_einstein(self):
|
| 12 |
+
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)
|
| 13 |
+
def test_03_three_angles_inversion(self):
|
| 14 |
+
for angle in [15,90,175]:
|
| 15 |
+
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)
|
| 16 |
+
def test_04_measured_raw_protein(self):
|
| 17 |
+
h=self.ready(kind='quartz',reference='bpd');v=ex.run(h);self.assertEqual(v['phase'],'succeeded');self.assertTrue(5e-9<v['dls']['z_average_m']<12e-9,v['dls']['z_average_m']);self.assertIn('measured_literature raw_g2',v['evidence']);self.assertEqual(len(v['g2']),len(rt.LIB['substances']['bpd']['value']['g2']['lag_s']))
|
| 18 |
+
def test_05_bimodal_nnls(self):
|
| 19 |
+
tau=np.geomspace(1e-7,.1,400);d=np.array([20e-9,300e-9]);q=4*math.pi*1.333*math.sin(math.pi/4)/658e-9;rates=q*q*1.380649e-23*293.15/(3*math.pi*.001002*d);g1=(np.exp(-rates[0]*tau)+np.exp(-rates[1]*tau))/2;out=rt.analyze(tau,1+.4*g1*g1,293.15,.001002,1.333,90,regularization=.0001);x=np.array(out['diameter_m']);w=np.array(out['intensity_fraction']);self.assertGreater(w[(x>10e-9)&(x<40e-9)].sum(),.3);self.assertGreater(w[(x>150e-9)&(x<600e-9)].sum(),.3)
|
| 20 |
+
def test_06_entered_viscosity_not_truth(self):
|
| 21 |
+
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)
|
| 22 |
+
def test_07_external_size_calibration(self):
|
| 23 |
+
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)
|
| 24 |
+
def test_08_zeta_phase_and_eof_rejection(self):
|
| 25 |
+
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)
|
| 26 |
+
def test_09_external_mobility_calibration(self):
|
| 27 |
+
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)
|
| 28 |
+
def test_10_finite_sample_energy_return(self):
|
| 29 |
+
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.)
|
| 30 |
+
def test_11_heat_setpoint_not_instant(self):
|
| 31 |
+
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(t<h.temperature<303.16);self.assertLess(abs(h._ledger()['heat_balance_j']),1e-7)
|
| 32 |
+
def test_12_poweroff_cancel_retains_heat(self):
|
| 33 |
+
h=self.ready(mode='zeta');ex.call(h,'acquisition.start');h.step(2.);self.assertGreater(h.field(),0);t=h.temperature;ex.call(h,'power.set',enabled=False);self.assertEqual(h.phase,'cancelled');self.assertEqual(h.field(),0);self.assertEqual(h.temperature,t);h.step(1);self.assertLess(abs(h._ledger()['heat_balance_j']),1e-7)
|
| 34 |
+
def test_13_warmup_360(self):
|
| 35 |
+
h=self.ready();ex.call(h,'power.set',enabled=False);ex.call(h,'power.set',enabled=True);h.step(359.9)
|
| 36 |
+
with self.assertRaisesRegex(rt.ActionRejected,'NOT_READY'):h.invoke('acquisition.start')
|
| 37 |
+
h.step(.1);ex.run(h);self.assertEqual(h.phase,'succeeded')
|
| 38 |
+
def test_14_cell_and_lid_interlocks(self):
|
| 39 |
+
h=self.ready()
|
| 40 |
+
with self.assertRaisesRegex(rt.ActionRejected,'SAMPLE_ACCESS'):h.invoke('cuvette.set',lift_m=.12)
|
| 41 |
+
with self.assertRaisesRegex(rt.ActionRejected,'LID_NOT_RELEASED'):h.invoke('lid.set',angle_rad=1.7)
|
| 42 |
+
ex.call(h,'acquisition.start')
|
| 43 |
+
with self.assertRaisesRegex(rt.ActionRejected,'BUSY'):h.invoke('lid.release')
|
| 44 |
+
ex.call(h,'acquisition.stop');self.assertEqual(h.phase,'cancelled')
|
| 45 |
+
def test_15_quartz_volume_omega_solvent(self):
|
| 46 |
+
h=self.ready();ex.unload(h)
|
| 47 |
+
with self.assertRaisesRegex(rt.ActionRejected,'CELL_COMPATIBILITY'):h.invoke('sample.load',**dict(rt.SAMPLE_EXAMPLE,aqueous=False))
|
| 48 |
+
ex.call(h,'cell.configure',kind='quartz')
|
| 49 |
+
with self.assertRaisesRegex(rt.ActionRejected,'CELL_VOLUME'):h.invoke('sample.load',**rt.SAMPLE_EXAMPLE)
|
| 50 |
+
def test_16_bubbles_and_unknown_reference(self):
|
| 51 |
+
h=self.ready();ex.unload(h)
|
| 52 |
+
for arg,code in [({'bubble_free':False},'BUBBLES'),({'reference_id':'missing'},'UNKNOWN_REFERENCE'),({'accept_cross_instrument_transfer':False},'TRANSFER_NOT_ACCEPTED')]:
|
| 53 |
+
with self.assertRaisesRegex(rt.ActionRejected,code):h.invoke('sample.load',**dict(rt.SAMPLE_EXAMPLE,**arg))
|
| 54 |
+
def test_17_els_angle_and_missing_zeta(self):
|
| 55 |
+
h=self.ready(kind='quartz',reference='bsa')
|
| 56 |
+
with self.assertRaisesRegex(rt.ActionRejected,'ELS_ANGLE'):h.invoke('method.configure',**dict(rt.METHOD_EXAMPLE,mode='zeta'))
|
| 57 |
+
ex.call(h,'method.configure',**dict(rt.METHOD_EXAMPLE,mode='zeta',angle_deg=15))
|
| 58 |
+
with self.assertRaisesRegex(rt.ActionRejected,'CELL_COMPATIBILITY'):h.invoke('acquisition.start')
|
| 59 |
+
def test_18_temperature_calibration_independent(self):
|
| 60 |
+
h=rt.AntonpaarLitesizerdlsRuntime();ex.call(h,'plant.configure',**dict(rt.PLANT_EXAMPLE,temperature_gain=1.01,temperature_offset_k=2.));self.assertNotAlmostEqual(h.indicated(),h.block);ex.call(h,'temperature.calibrate',reference_k=[293.15,313.15],measured_k=[293.15*1.01+2,313.15*1.01+2]);self.assertAlmostEqual(h.indicated(),293.15,9)
|
| 61 |
+
def test_19_finite_purge(self):
|
| 62 |
+
h=self.ready();ex.call(h,'method.configure',**dict(rt.METHOD_EXAMPLE,temperature_k=278.15))
|
| 63 |
+
with self.assertRaisesRegex(rt.ActionRejected,'PURGE_REQUIRED'):h.invoke('acquisition.start')
|
| 64 |
+
ex.call(h,'purge.fill',moles=1e-6);ex.call(h,'purge.set',enabled=True);ex.call(h,'acquisition.start');h.step(.1);self.assertEqual(h.failure,'GAS_EXHAUSTED');self.assertLess(abs(h._ledger()['gas_residual_mol']),1e-14)
|
| 65 |
+
def test_20_liquid_phase_boundary(self):
|
| 66 |
+
h=self.ready()
|
| 67 |
+
with self.assertRaisesRegex(rt.ActionRejected,'LIQUID_PHASE'):h.invoke('method.configure',**dict(rt.METHOD_EXAMPLE,temperature_k=393.15))
|
| 68 |
+
def test_21_strict_atomic_rejections(self):
|
| 69 |
+
h=self.ready();before=copy.deepcopy(h.__dict__)
|
| 70 |
+
for k,a in [('power.set',{'enabled':1}),('method.configure',dict(rt.METHOD_EXAMPLE,temperature_k=float('nan'))),('lid.set',{'angle_rad':True}),('dls.calibrate',{'reference_m':1e-6,'measured_m':1e-9})]:
|
| 71 |
+
with self.assertRaises(rt.ActionRejected):h.invoke(k,**a)
|
| 72 |
+
self.assertEqual(h.__dict__,before)
|
| 73 |
+
def test_22_pure_reads_and_request_dedup(self):
|
| 74 |
+
h=self.ready();h.register_principal('agent');s=h.session('agent');v=copy.deepcopy(h.__dict__);s.read(instance_id=h.instance_id);h.invoke('process.measure');self.assertEqual(h.__dict__,v);a=dict(instance_id=h.instance_id,capability_id='power.set',arguments={'enabled':True},request_id='same');r=s.invoke(**a);self.assertEqual(r,s.invoke(**a));self.assertEqual(s.invoke(**dict(a,arguments={'enabled':False}))['error']['code'],'REQUEST_CONFLICT')
|
| 75 |
+
def test_23_truth_permissions(self):
|
| 76 |
+
h=self.ready();h.register_principal('agent');s=h.session('agent');self.assertNotIn('sample.identity',s.read(instance_id=h.instance_id)['observations']);r=s.invoke(instance_id=h.instance_id,capability_id='ledger.read',arguments={},request_id='bad');self.assertEqual(r['error']['code'],'ACCESS_DENIED')
|
| 77 |
+
def test_24_async_ownership_and_terminal_record(self):
|
| 78 |
+
h=self.ready();h.register_principal('a');h.register_principal('b');a=h.session('a');b=h.session('b');op=a.invoke(instance_id=h.instance_id,capability_id='acquisition.start',arguments={},request_id='run')['operation_id']
|
| 79 |
+
with self.assertRaisesRegex(rt.ActionRejected,'ACCESS_DENIED'):b.poll(op)
|
| 80 |
+
a.cancel(op,'cancel');frozen=a.poll(op);ex.call(h,'method.configure',**dict(rt.METHOD_EXAMPLE,mode='zeta',angle_deg=15));self.assertEqual(a.poll(op),frozen)
|
| 81 |
+
def test_25_clock_chunking(self):
|
| 82 |
+
a=self.ready();b=copy.deepcopy(a);ex.call(a,'acquisition.start');ex.call(b,'acquisition.start');a.step(7.)
|
| 83 |
+
for _ in range(100):b.step(.07)
|
| 84 |
+
self.assertEqual(a.read('evaluator'),b.read('evaluator'));self.assertEqual(a._result(),b._result())
|
| 85 |
+
def test_26_unsupported_and_template(self):
|
| 86 |
+
h=self.ready();ex.call(h,'template.reference',substance_id=rt.SID)
|
| 87 |
+
for k in rt.UNSUPPORTED:
|
| 88 |
+
with self.assertRaisesRegex(rt.ActionRejected,'UNSUPPORTED'):h.invoke(k)
|
| 89 |
+
def test_27_noise_not_measured_and_timeout(self):
|
| 90 |
+
h=self.ready();ex.call(h,'method.configure',**dict(rt.METHOD_EXAMPLE,temperature_k=323.15,timeout_s=10.));ex.call(h,'acquisition.start');h.step(11.);self.assertEqual(h.phase,'failed');self.assertEqual(h.failure,'ACQUISITION_TIMEOUT');self.assertTrue(h.read()['lamp.status_red'])
|
| 91 |
+
def test_28_completed_result_keeps_its_acquisition_mode(self):
|
| 92 |
+
h=self.ready();original=ex.run(h);self.assertEqual(original['mode'],'dls');ex.call(h,'method.configure',**dict(rt.METHOD_EXAMPLE,mode='zeta',angle_deg=15));self.assertEqual(h.invoke('process.measure'),original)
|
| 93 |
+
new=ex.run(h);self.assertEqual(new['mode'],'zeta');self.assertIsNone(new['dls']);self.assertIsNotNone(new['els'])
|
| 94 |
+
ex.call(h,'method.configure',**rt.METHOD_EXAMPLE);self.assertEqual(h.invoke('process.measure'),new)
|
| 95 |
+
def test_29_metadata_covers_actual_observable_effects(self):
|
| 96 |
+
metadata=rt.export_antonpaar_litesizerdls_contract_metadata();original=rt.AntonpaarLitesizerdlsRuntime.invoke;observed=set()
|
| 97 |
+
def audited_invoke(h,k,**arguments):
|
| 98 |
+
before=h.read('evaluator');result=original(h,k,**arguments);after=h.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'}
|
| 99 |
+
self.assertFalse(changed-declared,(k,changed-declared));observed.add(k);return result
|
| 100 |
+
with mock.patch.object(rt.AntonpaarLitesizerdlsRuntime,'invoke',audited_invoke):
|
| 101 |
+
h=self.ready();ex.run(h);ex.call(h,'method.configure',**dict(rt.METHOD_EXAMPLE,mode='zeta',angle_deg=15));ex.run(h);ex.unload(h)
|
| 102 |
+
ex.call(h,'sample.load',**dict(rt.SAMPLE_EXAMPLE,sample_id='warmer_sample',initial_temperature_k=298.15));ex.call(h,'temperature.calibrate',reference_k=[293.15,313.15],measured_k=[294.15,314.15]);ex.call(h,'purge.fill',moles=.01);ex.call(h,'purge.set',enabled=True);ex.call(h,'method.configure',**dict(rt.METHOD_EXAMPLE,temperature_k=303.15))
|
| 103 |
+
other=rt.AntonpaarLitesizerdlsRuntime();ex.call(other,'plant.configure',**dict(rt.PLANT_EXAMPLE,ambient_k=298.15))
|
| 104 |
+
for stop in ['acquisition.stop','power.set']:
|
| 105 |
+
q=self.ready(mode='zeta');ex.call(q,'acquisition.start');q.step(2.);ex.call(q,stop,**({'enabled':False} if stop=='power.set' else {}))
|
| 106 |
+
self.assertTrue(set(rt.IMMEDIATE_EFFECTS)<=observed)
|
| 107 |
+
def test_30_terminal_ownership_survives_new_sample_and_failure(self):
|
| 108 |
+
h=self.ready();h.register_principal('a');h.register_principal('b');s=h.session('a');op=s.invoke(instance_id=h.instance_id,capability_id='acquisition.start',arguments={},request_id='first')['operation_id']
|
| 109 |
+
while h.phase=='running':h.step(.1)
|
| 110 |
+
frozen=s.poll(op);self.assertEqual(frozen['status'],'succeeded');ex.unload(h);ex.call(h,'sample.load',**dict(rt.SAMPLE_EXAMPLE,sample_id='replacement'));ex.call(h,'cell_cap.set',lift_m=0.);ex.call(h,'cuvette.set',lift_m=0.);ex.call(h,'lid.set',angle_rad=0.)
|
| 111 |
+
ex.call(h,'method.configure',**dict(rt.METHOD_EXAMPLE,temperature_k=323.15,timeout_s=10.));new_op=s.invoke(instance_id=h.instance_id,capability_id='acquisition.start',arguments={},request_id='second')['operation_id'];h.step(11.);failed=s.poll(new_op);self.assertEqual(failed['status'],'failed');h.step(1.);self.assertEqual(failed,s.poll(new_op));self.assertEqual(frozen,s.poll(op))
|
| 112 |
+
with self.assertRaisesRegex(rt.ActionRejected,'ACCESS_DENIED'):h.session('b').poll(op)
|
| 113 |
+
copied=s.poll(op);copied['result']['g2'].clear();self.assertEqual(frozen,s.poll(op))
|
| 114 |
+
if __name__=='__main__':unittest.main()
|
tests/test_asset_antonpaar_poremaster60.py
ADDED
|
@@ -0,0 +1,148 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import unittest,sys,copy,math,json,hashlib,zipfile
|
| 2 |
+
from pathlib import Path
|
| 3 |
+
from unittest import mock
|
| 4 |
+
ROOT=Path(__file__).resolve().parents[1];OUT=ROOT/'outputs/expansion_batch03/t4_measure/antonpaar_poremaster60';sys.path.insert(0,str(OUT));from example_setup import rt,setup,run,high,call,OBSERVED
|
| 5 |
+
class PorosimetryTests(unittest.TestCase):
|
| 6 |
+
def test_01_si_washburn_and_mass_normalized_measurement(self):
|
| 7 |
+
r=setup();out=run(r)
|
| 8 |
+
self.assertEqual(len(out['points']),4)
|
| 9 |
+
for p in out['points']:
|
| 10 |
+
self.assertAlmostEqual(p['diameter_m']*p['pressure_pa'],-4*.48*math.cos(math.radians(140)),places=12)
|
| 11 |
+
xs,ys=rt.CURVES[(rt.SID,'intrusion')];expected=rt.interp(xs,ys,p['pressure_pa']);self.assertLess(abs(p['specific_volume_m3_kg']-expected),2e-6)
|
| 12 |
+
def test_02_real_cycle_energy_and_ledgers(self):
|
| 13 |
+
r=setup();run(r);high(r);out=run(r);l=call(r,'ledger.read');self.assertEqual(len(out['points']),13);self.assertEqual(sum(p['branch']=='extrusion' for p in out['points']),4);self.assertGreater(out['max_pore_volume_m3_kg'],.0025)
|
| 14 |
+
for k in ['hg_residual_kg','solid_residual_kg','gas_residual_mol','oil_residual_m3']:self.assertLess(abs(l[k]),1e-12)
|
| 15 |
+
self.assertGreater(l['hydraulic_pump_work_j'],4000);self.assertLess(abs(l['work_balance_error_j']),.01);self.assertGreater(l['capillary_work_j'],0);self.assertGreater(l['hg_intruded_kg'],0)
|
| 16 |
+
def test_03_fibre_missing_sparse_columns_recovered(self):
|
| 17 |
+
d=rt.LIB['substances']['hemp_fibre'];xs,_=rt.CURVES[('hemp_fibre','intrusion')];self.assertGreater(len(xs),800);self.assertAlmostEqual(max(xs),400911800.);r=setup(ref='hemp_fibre');run(r);high(r);out=run(r);self.assertEqual(out['phase'],'succeeded')
|
| 18 |
+
def test_04_no_fabricated_rock_extrusion(self):
|
| 19 |
+
r=setup(ref='dggs_09BG010-38.5b',mass=.0002);run(r);high(r,cycle=False)
|
| 20 |
+
m=copy.deepcopy(r.method);m['pressures_pa']+=[1e8]
|
| 21 |
+
with self.assertRaisesRegex(rt.ActionRejected,'EXTRUSION_UNAVAILABLE'):r.invoke('method.configure',**m)
|
| 22 |
+
def test_05_no_partial_source_peak_hysteresis(self):
|
| 23 |
+
r=setup();run(r);high(r);m=copy.deepcopy(r.method);m['pressures_pa']=[50*rt.PSI,1e6,1e8,1e6]
|
| 24 |
+
with self.assertRaisesRegex(rt.ActionRejected,'SOURCE_PEAK_REQUIRED'):r.invoke('method.configure',**m)
|
| 25 |
+
def test_06_no_template_extrapolation(self):
|
| 26 |
+
r=setup();m=copy.deepcopy(r.method);m['pressures_pa']=[.2*rt.PSI,10*rt.PSI]
|
| 27 |
+
with self.assertRaisesRegex(rt.ActionRejected,'TEMPLATE_RANGE'):r.invoke('method.configure',**m)
|
| 28 |
+
def test_07_wrong_entered_mass_changes_reading(self):
|
| 29 |
+
a=setup();b=setup(entered_mass=rt.SAMPLE_EXAMPLE['true_dry_mass_kg']*2);ra=run(a);rb=run(b)
|
| 30 |
+
self.assertAlmostEqual(a.v,b.v,places=14)
|
| 31 |
+
for x,y in zip(ra['points'],rb['points']):self.assertAlmostEqual(x['specific_volume_m3_kg'],y['specific_volume_m3_kg']*2,places=13)
|
| 32 |
+
def test_08_sensor_calibration_is_independent(self):
|
| 33 |
+
r=setup(plant={'pressure_gain':[1.1,1.05,.95],'pressure_offset_pa':[20.,100.,10000.],'capacitance_volume_factor_m3_f':31000.,'capacitance_offset_f':7e-12});out=run(r)
|
| 34 |
+
point=out['points'][-1];xs,ys=rt.CURVES[(rt.SID,'intrusion')];self.assertLess(abs(point['specific_volume_m3_kg']-rt.interp(xs,ys,point['pressure_pa'])),2e-6)
|
| 35 |
+
def test_09_blank_correction_is_observable(self):
|
| 36 |
+
good=setup();bad=setup();call(bad,'blank.calibrate',pressures_pa=[0.,rt.P_MAX],volumes_m3=[0.,0.]);run(good);run(bad);high(good);high(bad);a=run(good);b=run(bad);self.assertGreater(b['max_pore_volume_m3_kg']-a['max_pore_volume_m3_kg'],.0004)
|
| 37 |
+
def test_10_mercury_is_finite(self):
|
| 38 |
+
r=setup();r.hg_added=r.hg_stock=.001;call(r,'acquisition.start')
|
| 39 |
+
for _ in range(500):
|
| 40 |
+
r.step(.1)
|
| 41 |
+
if r.phase!='running':break
|
| 42 |
+
self.assertEqual(r.failure,'MERCURY_EXHAUSTED');self.assertAlmostEqual(r._ledger()['hg_residual_kg'],0,places=12);self.assertGreater(r.hg_cell,0)
|
| 43 |
+
def test_11_oil_is_finite(self):
|
| 44 |
+
r=setup(plant={'oil_volume_m3':1e-6});run(r);high(r);call(r,'acquisition.start')
|
| 45 |
+
for _ in range(10000):
|
| 46 |
+
r.step(.1)
|
| 47 |
+
if r.phase!='running':break
|
| 48 |
+
self.assertEqual(r.failure,'OIL_EXHAUSTED');self.assertAlmostEqual(r._ledger()['oil_residual_m3'],0,places=14)
|
| 49 |
+
def test_12_gas_supply_is_finite(self):
|
| 50 |
+
r=setup(plant={'source_volume_m3':1e-5,'source_pressure_pa':50*rt.PSI});call(r,'acquisition.start')
|
| 51 |
+
for _ in range(10000):
|
| 52 |
+
r.step(.1)
|
| 53 |
+
if r.phase!='running':break
|
| 54 |
+
self.assertEqual(r.failure,'GAS_EXHAUSTED');self.assertAlmostEqual(r._ledger()['gas_residual_mol'],0,places=12)
|
| 55 |
+
def test_13_cancel_retains_pressure_and_samples(self):
|
| 56 |
+
r=setup();run(r);high(r);call(r,'acquisition.start')
|
| 57 |
+
while r.p<1e7:r.step(.1)
|
| 58 |
+
before=(r.p,r.hg_cell,r.sample.copy(),r.oil);call(r,'acquisition.stop');self.assertEqual(before,(r.p,r.hg_cell,r.sample.copy(),r.oil))
|
| 59 |
+
with self.assertRaisesRegex(rt.ActionRejected,'PRESSURE_ACCESS_INTERLOCK'):r.invoke('cap.set',lift_m=.19)
|
| 60 |
+
with self.assertRaisesRegex(rt.ActionRejected,'NOT_READY'):r.invoke('acquisition.start')
|
| 61 |
+
r.step(40.);self.assertLess(abs(r.p-rt.AMBIENT),1);self.assertEqual(r.phase,'cancelled')
|
| 62 |
+
def test_14_emergency_and_power_stop(self):
|
| 63 |
+
r=setup();call(r,'acquisition.start');r.step(2.);call(r,'emergency.stop');self.assertEqual(r.phase,'cancelled');call(r,'power.set',enabled=False);self.assertEqual(r.read()['lamp.power'],False);r.step(10.);self.assertLess(abs(r.p-rt.AMBIENT),1)
|
| 64 |
+
def test_15_unload_retains_hg_in_sample(self):
|
| 65 |
+
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');out=call(r,'sample.unload');self.assertGreater(out['retained_hg_kg'],.002);self.assertAlmostEqual(out['returned_dry_mass_kg'],.0000655);l=call(r,'ledger.read');self.assertLess(abs(l['hg_residual_kg']),1e-12);self.assertLess(abs(l['solid_residual_kg']),1e-12)
|
| 66 |
+
def test_16_second_low_port_and_cumulative_xyz(self):
|
| 67 |
+
r=setup(low1=True);self.assertEqual(r.read()['cell.x_m'],.328);run(r);high(r);self.assertEqual([r.read()['cell.'+a+'_m'] for a in ['x','y','z']],[.164,.185,.265])
|
| 68 |
+
def test_17_motion_interlocks(self):
|
| 69 |
+
r=setup()
|
| 70 |
+
with self.assertRaisesRegex(rt.ActionRejected,'TRANSFER_INTERLOCK'):r.invoke('cell.transfer',destination='high')
|
| 71 |
+
call(r,'guard0.set',angle_rad=1.4)
|
| 72 |
+
with self.assertRaisesRegex(rt.ActionRejected,'POSITION_INTERLOCK'):r.invoke('acquisition.start')
|
| 73 |
+
def test_18_sample_capacity_atomicity(self):
|
| 74 |
+
r=rt.AntonpaarPoremaster60Runtime();call(r,'plant.configure',**rt.PLANT_EXAMPLE);call(r,'guard0.set',angle_rad=1.4);before=copy.deepcopy(r.__dict__)
|
| 75 |
+
with self.assertRaisesRegex(rt.ActionRejected,'CAPACITY'):r.invoke('sample.load',**dict(rt.SAMPLE_EXAMPLE,true_dry_mass_kg=.1))
|
| 76 |
+
self.assertEqual(before,r.__dict__)
|
| 77 |
+
def test_19_inputs_strict_nan_bool_unknown(self):
|
| 78 |
+
r=setup();before=copy.deepcopy(r.__dict__)
|
| 79 |
+
for a in [{'enabled':1},{'enabled':True,'oops':1}]:
|
| 80 |
+
with self.assertRaises(rt.ActionRejected):r.invoke('power.set',**a)
|
| 81 |
+
with self.assertRaises(rt.ActionRejected):r.invoke('cap.set',lift_m=float('nan'))
|
| 82 |
+
with self.assertRaises(rt.ActionRejected):r.step(True)
|
| 83 |
+
self.assertEqual(before,r.__dict__)
|
| 84 |
+
def test_20_fixed_clock_partition_invariance(self):
|
| 85 |
+
a=setup();b=setup();call(a,'acquisition.start');call(b,'acquisition.start');a.step(20.)
|
| 86 |
+
for _ in range(400):b.step(.05)
|
| 87 |
+
self.assertEqual(a.read('evaluator'),b.read('evaluator'));self.assertEqual(a._ledger(),b._ledger())
|
| 88 |
+
def test_21_read_purity(self):
|
| 89 |
+
r=setup();call(r,'acquisition.start');r.step(5.);before=copy.deepcopy(r.__dict__)
|
| 90 |
+
for _ in range(5):call(r,'process.measure');call(r,'ledger.read');call(r,'template.reference',substance_id=rt.SID);r.read('evaluator')
|
| 91 |
+
self.assertEqual(before,r.__dict__)
|
| 92 |
+
def test_22_session_visibility(self):
|
| 93 |
+
r=setup();r.register_principal('a');r.register_principal('e','evaluator');a=r.session('a');e=r.session('e');self.assertNotIn('sample.identity',a.read(instance_id=r.instance_id)['observations']);self.assertIn('sample.identity',e.read(instance_id=r.instance_id)['observations']);ans=a.invoke(instance_id=r.instance_id,capability_id='ledger.read',arguments={},request_id='deny');self.assertEqual(ans['error']['code'],'ACCESS_DENIED')
|
| 94 |
+
with self.assertRaises(rt.ActionRejected):a.read(instance_id=r.instance_id,state_ids=['sample.mass_kg'])
|
| 95 |
+
def test_23_idempotency_and_async_ownership(self):
|
| 96 |
+
r=setup();r.register_principal('a');r.register_principal('b');a=r.session('a');b=r.session('b');kwargs=dict(instance_id=r.instance_id,capability_id='acquisition.start',arguments={},request_id='start');x=a.invoke(**kwargs);y=a.invoke(**kwargs);self.assertEqual(x,y);self.assertEqual(r.serial,1)
|
| 97 |
+
with self.assertRaises(rt.ActionRejected):b.poll(x['operation_id'])
|
| 98 |
+
res=a.invoke(instance_id=r.instance_id,capability_id='power.set',arguments={'enabled':False},request_id='start');self.assertEqual(res['error']['code'],'REQUEST_CONFLICT');self.assertEqual(a.cancel(x['operation_id'],'cancel')['status'],'succeeded');self.assertEqual(a.poll(x['operation_id'])['status'],'cancelled')
|
| 99 |
+
def test_24_unsupported_not_faked(self):
|
| 100 |
+
r=setup()
|
| 101 |
+
for k in rt.UNSUPPORTED:
|
| 102 |
+
with self.assertRaisesRegex(rt.ActionRejected,'UNSUPPORTED'):r.invoke(k)
|
| 103 |
+
def test_25_library_identity_and_units(self):
|
| 104 |
+
original_ids=set('dggs_09BG010-38.5b dggs_13A017-12.7b dggs_13A017-6.0b dggs_13A017-6.15b dggs_13A017-6.8b dggs_13A017-8.2b dggs_13A017-8.3b dggs_13A027-0.5c dggs_13A027-1.9b dggs_13A027-100.5c dggs_13A027-113.1c dggs_13A027-122.8c dggs_13A027-14.5c dggs_13A027-143.0c dggs_13A027-151.0c dggs_13A027-157.7b dggs_13A027-160.0c dggs_13A027-169.4c dggs_13A027-180.5c dggs_13A027-190.8c dggs_13A027-198.8c dggs_13A027-209.9c dggs_13A027-220.2c dggs_13A027-23.6c dggs_13A027-231.4c dggs_13A027-238.8c dggs_13A027-250.2c dggs_13A027-259.4c dggs_13A027-270.0c dggs_13A027-282.0c dggs_13A027-292.4c dggs_13A027-300.2c dggs_13A027-315.2c dggs_13A027-320.8c dggs_13A027-323.2b dggs_13A027-323.8b dggs_13A027-326.8b dggs_13A027-329.5b dggs_13A027-332.2b dggs_13A027-336.0b dggs_13A027-338.1b dggs_13A027-339.8c dggs_13A027-39.0c dggs_13A027-48.6c dggs_13A027-56.8c dggs_13A027-68.0c dggs_13A027-74.2b dggs_13A027-8.4b dggs_13A027-80.1b dggs_13A027-81.0c dggs_13A027-9.5b dggs_13A027-9.6b dggs_13A027-94.5c dggs_13A027-99.5c limestone_indiana limestone_st_maximin_sml limestone_majella_m limestone_thala_th22a limestone_purbeck_p21 limestone_leitha_ua_31_ limestone_leitha_ul4_26_ limestone_leitha_ub17_21_ hemp_shiv hemp_fibre'.split());self.assertTrue(original_ids<=rt.LIB['substances'].keys());self.assertGreaterEqual(len(rt.LIB['substances']),64);self.assertGreaterEqual(len(set(v['material_group'] for v in rt.LIB['substances'].values())),13)
|
| 105 |
+
source_hashes={}
|
| 106 |
+
for k,v in rt.LIB['substances'].items():
|
| 107 |
+
if k in original_ids:
|
| 108 |
+
source=v['source'];path=OUT/source['file']
|
| 109 |
+
if path not in source_hashes:source_hashes[path]=hashlib.sha256(path.read_bytes()).hexdigest()
|
| 110 |
+
self.assertEqual(source_hashes[path],source['sha256']);self.assertTrue(source['url']);self.assertEqual(v['evidence'],'measured_literature')
|
| 111 |
+
if 'raw_member_sha256' in source:
|
| 112 |
+
with zipfile.ZipFile(path) as archive:self.assertEqual(hashlib.sha256(archive.read(source['locator'].split(' / ')[0])).hexdigest(),source['raw_member_sha256'])
|
| 113 |
+
if rt.CURVES[(k,'extrusion')][0]:
|
| 114 |
+
self.assertIn(v['evidence'],['measured','measured_literature']);self.assertEqual(v['conditions']['extrusion_status'],'experimental_descent_from_source_peak');self.assertTrue(v['source']['url']);self.assertTrue(v['source']['sha256'])
|
| 115 |
+
d=rt.LIB['substances']['dggs_09BG010-38.5b'];p=d['value'][0];self.assertAlmostEqual(p['pressure_pa'],1.64*rt.PSI);self.assertAlmostEqual(p['volume_m3_kg'],7.07868e-8);self.assertAlmostEqual(d['conditions']['closure_m3_kg'],.0025669119*.001)
|
| 116 |
+
def test_26_metadata_exposes_real_contract(self):
|
| 117 |
+
d=rt.export_antonpaar_poremaster60_contract_metadata();self.assertEqual(set(d['state_slots']),set(rt.SLOTS));self.assertEqual(len(d['capabilities']),28);self.assertEqual(sum(c['availability']=='implemented' for c in d['capabilities'].values()),21)
|
| 118 |
+
def test_27_overlap_not_a_resolved_pore_bin(self):
|
| 119 |
+
r=setup();run(r);high(r);out=run(r);self.assertEqual(len(out['distribution']['diameter_m']),7);ds=out['distribution']['diameter_m'];self.assertTrue(all(a>b for a,b in zip(ds,ds[1:])))
|
| 120 |
+
def test_28_completed_operation_survives_sample_replacement(self):
|
| 121 |
+
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']
|
| 122 |
+
while r.phase=='running':r.step(.1)
|
| 123 |
+
original=s.poll(op);self.assertEqual(len(original['result']['points']),4)
|
| 124 |
+
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'))
|
| 125 |
+
self.assertEqual(original,s.poll(op))
|
| 126 |
+
call(r,'guard0.set',angle_rad=0.);call(r,'method.configure',**rt.METHOD_EXAMPLE)
|
| 127 |
+
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))
|
| 128 |
+
returned=s.poll(op);returned['result']['points'].clear();self.assertEqual(original,s.poll(op))
|
| 129 |
+
def test_29_cancelled_operation_result_is_immutable(self):
|
| 130 |
+
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.)
|
| 131 |
+
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']))
|
| 132 |
+
def test_30_failed_operation_retains_partial_result(self):
|
| 133 |
+
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')
|
| 134 |
+
while r.phase=='running':r.step(.1)
|
| 135 |
+
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']))
|
| 136 |
+
def test_31_metadata_covers_actual_observable_changes(self):
|
| 137 |
+
metadata=rt.export_antonpaar_poremaster60_contract_metadata();original=rt.AntonpaarPoremaster60Runtime.invoke;observed=set()
|
| 138 |
+
def audited_invoke(r,k,**arguments):
|
| 139 |
+
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'}
|
| 140 |
+
self.assertFalse(changed-declared,(k,changed-declared));observed.add(k);return result
|
| 141 |
+
with mock.patch.object(rt.AntonpaarPoremaster60Runtime,'invoke',audited_invoke):
|
| 142 |
+
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')
|
| 143 |
+
# At idle, calibration changes sensor observations without advancing the process.
|
| 144 |
+
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)
|
| 145 |
+
for stop in ['acquisition.stop','emergency.stop','power.set']:
|
| 146 |
+
q=setup();call(q,'acquisition.start');q.step(1.);call(q,stop,**({'enabled':False} if stop=='power.set' else {}))
|
| 147 |
+
self.assertTrue(set(rt.IMMEDIATE_EFFECTS)<=observed)
|
| 148 |
+
if __name__=='__main__':unittest.main()
|
tests/test_asset_antonpaar_psa1190.py
ADDED
|
@@ -0,0 +1,113 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import unittest,copy,pickle,sys,math
|
| 2 |
+
from pathlib import Path
|
| 3 |
+
from unittest import mock
|
| 4 |
+
import numpy as np
|
| 5 |
+
from scripts.asset_runtime import antonpaar_psa1190 as r
|
| 6 |
+
O=Path(__file__).resolve().parents[1]/'outputs/expansion_batch03/t4_measure/antonpaar_psa1190';sys.path.insert(0,str(O));from example_setup import build
|
| 7 |
+
class TestPsa1190(unittest.TestCase):
|
| 8 |
+
def test29_host_registration(self):
|
| 9 |
+
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'])
|
| 10 |
+
with self.assertRaises(r.ActionRejected):h.register_principal('matterix_agent','evaluator')
|
| 11 |
+
with self.assertRaises(r.ActionRejected):h.session('unregistered')
|
| 12 |
+
def done(self,h,dt=15.1):h.invoke('acquisition.start');h.step(dt);self.assertEqual(h.phase,'succeeded',h.error);return h
|
| 13 |
+
def test01_sources(self):
|
| 14 |
+
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)
|
| 15 |
+
for k,v in r.LIB['substances'].items():self.assertTrue(v['source']);self.assertEqual(v['evidence'],'measured_literature')
|
| 16 |
+
def test02_rayleigh(self):
|
| 17 |
+
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)
|
| 18 |
+
def test03_mie_energy(self):
|
| 19 |
+
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)
|
| 20 |
+
def test04_mie_absorption(self):
|
| 21 |
+
_,qe,qs=r.mie_scattering(2.,1.5+.1j,np.array([.1]));self.assertGreater(qe,qs);self.assertGreater(qs,0)
|
| 22 |
+
def test05_fraunhofer_kernel(self):
|
| 23 |
+
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)
|
| 24 |
+
def test06_inverse_single_bin(self):
|
| 25 |
+
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)
|
| 26 |
+
def test07_source_steel(self):
|
| 27 |
+
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)
|
| 28 |
+
def test08_soil_full_curve(self):
|
| 29 |
+
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)
|
| 30 |
+
def test09_refractive_input_independent(self):
|
| 31 |
+
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)
|
| 32 |
+
def test10_calibration(self):
|
| 33 |
+
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)
|
| 34 |
+
def test11_wet_mass_and_drain_heat(self):
|
| 35 |
+
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)
|
| 36 |
+
def test12_dry_finite_recover(self):
|
| 37 |
+
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)
|
| 38 |
+
def test13_cancel_partial(self):
|
| 39 |
+
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)
|
| 40 |
+
def test14_warmup(self):
|
| 41 |
+
h=r.AntonpaarPsa1190Runtime();h.invoke('plant.configure',**r.PLANT_EXAMPLE);h.invoke('power.set',enabled=True);h.step(59.9)
|
| 42 |
+
with self.assertRaisesRegex(r.ActionRejected,'NOT_READY'):h.invoke('background.start')
|
| 43 |
+
h.step(.1);self.assertEqual(h.warm,60.)
|
| 44 |
+
def test15_background_clock(self):
|
| 45 |
+
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)
|
| 46 |
+
def test16_interlocks(self):
|
| 47 |
+
h=build();h.invoke('tank_lid.set',slide_m=.17)
|
| 48 |
+
with self.assertRaisesRegex(r.ActionRejected,'CLOSURE'):h.invoke('acquisition.start')
|
| 49 |
+
with self.assertRaisesRegex(r.ActionRejected,'POWER_INTERLOCK'):h.invoke('cover.set',angle_rad=1.2)
|
| 50 |
+
with self.assertRaisesRegex(r.ActionRejected,'BLANK_NOT_EMPTY'):h.invoke('tank_lid.set',slide_m=0.);h.invoke('background.start')
|
| 51 |
+
def test17_strict_atomic(self):
|
| 52 |
+
h=build()
|
| 53 |
+
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))]:
|
| 54 |
+
before=pickle.dumps(h.__dict__)
|
| 55 |
+
with self.assertRaises(r.ActionRejected):h.invoke(cap,**args)
|
| 56 |
+
self.assertEqual(before,pickle.dumps(h.__dict__))
|
| 57 |
+
def test18_truth_and_instances(self):
|
| 58 |
+
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'])
|
| 59 |
+
with self.assertRaises(r.ActionRejected):a.read(instance_id=h.instance_id,state_ids=['truth.solid_kg'])
|
| 60 |
+
self.done(h);self.assertEqual(g.phase,'succeeded');self.assertIsNone(g.psd)
|
| 61 |
+
def test19_pure_reads_dedup(self):
|
| 62 |
+
h=build();a=h.session();before=pickle.dumps(h.__dict__)
|
| 63 |
+
for _ in range(3):h.read();a.describe(instance_id=h.instance_id);a.read(instance_id=h.instance_id)
|
| 64 |
+
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')
|
| 65 |
+
def test20_async_record_ownership(self):
|
| 66 |
+
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']
|
| 67 |
+
with self.assertRaises(r.ActionRejected):e.poll(op)
|
| 68 |
+
h.step(15.1);before=a.poll(op);h.invoke('liquid.drain');h.step(23.);self.assertEqual(before,a.poll(op))
|
| 69 |
+
def test21_gas_exhaustion(self):
|
| 70 |
+
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)
|
| 71 |
+
def test22_obscuration(self):
|
| 72 |
+
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)
|
| 73 |
+
def test23_heat_and_cooling(self):
|
| 74 |
+
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)
|
| 75 |
+
def test24_settling_and_deaggregation(self):
|
| 76 |
+
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)
|
| 77 |
+
def test25_clock_partition(self):
|
| 78 |
+
a=build();b=copy.deepcopy(a);a.invoke('acquisition.start');b.invoke('acquisition.start');a.step(2.3)
|
| 79 |
+
for _ in range(230):b.step(.01)
|
| 80 |
+
self.assertEqual(a.read(),b.read());np.testing.assert_allclose(a.wet,b.wet)
|
| 81 |
+
def test26_template_rejection(self):
|
| 82 |
+
for sid,cross,trunc in [('powder_050',True,True),('powder_057',True,True),('powder_001',False,True)]:
|
| 83 |
+
with self.assertRaises(r.ActionRejected):r.template(sid,cross,trunc,'wet')
|
| 84 |
+
v,_,e,_=r.template('powder_001',True,True,'wet');self.assertEqual(len(v),110);self.assertIn('assumed',e)
|
| 85 |
+
def test27_timeout_and_unsupported(self):
|
| 86 |
+
h=build();h.invoke('method.configure',**dict(h.method,timeout_s=1.));h.invoke('acquisition.start');h.step(2.);self.assertEqual(h.error,'TIMEOUT')
|
| 87 |
+
for k in r.UNSUPPORTED:
|
| 88 |
+
with self.assertRaisesRegex(r.ActionRejected,'UNSUPPORTED'):h.invoke(k)
|
| 89 |
+
def test28_no_implicit_temperature_sensor(self):
|
| 90 |
+
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))
|
| 91 |
+
def test30_result_query_cannot_take_operation_ownership(self):
|
| 92 |
+
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()
|
| 93 |
+
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)
|
| 94 |
+
with self.assertRaisesRegex(r.ActionRejected,'ACCESS_DENIED'):observer.cancel(op,'unauthorized')
|
| 95 |
+
self.assertEqual(owner.cancel(op,'owner_cancel')['status'],'succeeded');self.assertEqual(owner.poll(op)['status'],'cancelled')
|
| 96 |
+
def test31_result_source_belongs_to_acquisition(self):
|
| 97 |
+
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')
|
| 98 |
+
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'))
|
| 99 |
+
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)
|
| 100 |
+
def test32_metadata_covers_actual_state_changes(self):
|
| 101 |
+
metadata=r.export_antonpaar_psa1190_contract_metadata();original=r.AntonpaarPsa1190Runtime.invoke;observed=set()
|
| 102 |
+
def audited_invoke(h,cap,**arguments):
|
| 103 |
+
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'}
|
| 104 |
+
self.assertFalse(changed-declared,(cap,changed-declared));observed.add(cap);return result
|
| 105 |
+
with mock.patch.object(r.AntonpaarPsa1190Runtime,'invoke',audited_invoke):
|
| 106 |
+
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.)
|
| 107 |
+
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))
|
| 108 |
+
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)
|
| 109 |
+
self.assertTrue(set(r.IMMEDIATE_EFFECTS)<=observed)
|
| 110 |
+
def test33_recovery_mass_requires_evaluator(self):
|
| 111 |
+
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__)
|
| 112 |
+
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)
|
| 113 |
+
if __name__=='__main__':unittest.main()
|
tests/test_asset_antonpaar_surpass3.py
ADDED
|
@@ -0,0 +1,76 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import unittest,copy,math,importlib.util,json
|
| 2 |
+
from scripts.asset_runtime import antonpaar_surpass3 as r
|
| 3 |
+
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()
|
| 4 |
+
def call(h,k,a=None):
|
| 5 |
+
v=h.invoke(k,**(a or {}));tool.validate_value(v,r.CAPS[k][1]);OBSERVED.add(k);return v
|
| 6 |
+
def setup(plant=None,method=None,liquid=None,sample=None):
|
| 7 |
+
h=r.AntonpaarSurpass3Runtime()
|
| 8 |
+
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)
|
| 9 |
+
return h
|
| 10 |
+
def finish(h):
|
| 11 |
+
if h.phase!='running':call(h,'acquisition.start')
|
| 12 |
+
for _ in range(1800):
|
| 13 |
+
h.step(1.)
|
| 14 |
+
if h.phase!='running':break
|
| 15 |
+
return h
|
| 16 |
+
class Tests(unittest.TestCase):
|
| 17 |
+
def ledger(self,h):
|
| 18 |
+
l=call(h,'ledger.read')
|
| 19 |
+
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)
|
| 20 |
+
self.assertLess(abs(l['work_residual_j']),1e-10);self.assertGreaterEqual(h.V-sum(h.chamber),-1e-15)
|
| 21 |
+
def test_01_original_references(self):
|
| 22 |
+
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)
|
| 23 |
+
with self.assertRaisesRegex(r.ActionRejected,'PARTICLE_REFERENCE_ONLY'):setup(sample={'reference_id':'nanomile_2'})
|
| 24 |
+
def test_02_complete_ols_and_iep(self):
|
| 25 |
+
h=finish(setup());self.assertEqual(h.phase,'succeeded');self.assertEqual(len(h.fits),16);self.assertAlmostEqual(h._iep(),4.1,places=6)
|
| 26 |
+
for f in h.fits:
|
| 27 |
+
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)
|
| 28 |
+
self.ledger(h);self.assertEqual({x['direction'] for x in call(h,'process.measure')['trace']},{1,-1})
|
| 29 |
+
def test_03_surface_conduction_bias(self):
|
| 30 |
+
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)
|
| 31 |
+
def test_04_ideal_chemistry_titration(self):
|
| 32 |
+
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)
|
| 33 |
+
def test_05_independent_pressure_work(self):
|
| 34 |
+
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)
|
| 35 |
+
def test_06_cancel_partial_dose_and_poweroff(self):
|
| 36 |
+
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)
|
| 37 |
+
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)
|
| 38 |
+
def test_07_stock_depletion(self):
|
| 39 |
+
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)
|
| 40 |
+
def test_08_capacity_failure(self):
|
| 41 |
+
h=finish(setup(method={'ph_targets':[3.],'cycles':1},liquid={'volume_m3':.00025}));self.assertEqual(h.failure,'BEAKER_CAPACITY');self.ledger(h)
|
| 42 |
+
def test_09_blocked_pressure_timeout(self):
|
| 43 |
+
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)
|
| 44 |
+
def test_10_chamber_empty_failure(self):
|
| 45 |
+
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)
|
| 46 |
+
def test_11_read_pure_isolation_partition(self):
|
| 47 |
+
a=setup();b=copy.deepcopy(a);call(a,'acquisition.start');call(b,'acquisition.start');a.step(7.3)
|
| 48 |
+
for _ in range(73):b.step(.1)
|
| 49 |
+
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)
|
| 50 |
+
def test_12_invalid_atomic_interlocks(self):
|
| 51 |
+
h=setup();old=h.read('evaluator')
|
| 52 |
+
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]})]:
|
| 53 |
+
with self.assertRaises(r.ActionRejected):call(h,k,a)
|
| 54 |
+
self.assertEqual(h.read('evaluator'),old)
|
| 55 |
+
call(h,'acquisition.start')
|
| 56 |
+
with self.assertRaisesRegex(r.ActionRejected,'BUSY'):call(h,'lid.set',{'lift_m':.1})
|
| 57 |
+
def test_13_calibration_bias_correction(self):
|
| 58 |
+
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)
|
| 59 |
+
def test_14_no_unbracketed_iep_and_rinse(self):
|
| 60 |
+
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)
|
| 61 |
+
def test_15_drain_and_sample_unload(self):
|
| 62 |
+
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)
|
| 63 |
+
def test_16_electrical_limits_and_sensor_offsets(self):
|
| 64 |
+
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)
|
| 65 |
+
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)
|
| 66 |
+
def test_17_gap_flow_and_tubing(self):
|
| 67 |
+
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)
|
| 68 |
+
def test_18_permissions_dedup_schema(self):
|
| 69 |
+
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')
|
| 70 |
+
with self.assertRaises(r.ActionRejected):q.poll(v['operation_id'])
|
| 71 |
+
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')
|
| 72 |
+
for k in r.UNSUPPORTED:
|
| 73 |
+
with self.assertRaisesRegex(r.ActionRejected,'UNSUPPORTED'):h.invoke(k)
|
| 74 |
+
for dt in [True,-1,float('nan'),float('inf')]:
|
| 75 |
+
with self.assertRaises(r.ActionRejected):h.step(dt)
|
| 76 |
+
if __name__=='__main__':unittest.main()
|
tests/test_asset_antonpaar_ultrapyc5000.py
ADDED
|
@@ -0,0 +1,113 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import unittest,copy,math,importlib.util,statistics,json
|
| 2 |
+
from scripts.asset_runtime import antonpaar_ultrapyc5000 as r
|
| 3 |
+
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()
|
| 4 |
+
def call(h,k,a=None):
|
| 5 |
+
v=h.invoke(k,**(a or {}));tool.validate_value(v,r.CAPS[k][1]);OBSERVED.add(k);return v
|
| 6 |
+
def open_cup(h):
|
| 7 |
+
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)
|
| 8 |
+
def close_cup(h):
|
| 9 |
+
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)
|
| 10 |
+
def calibrate(h):
|
| 11 |
+
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
|
| 12 |
+
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)
|
| 13 |
+
def setup(plant=None,method=None,sample=None,load=True):
|
| 14 |
+
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)
|
| 15 |
+
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)
|
| 16 |
+
call(h,'power.set',{'enabled':True});return h
|
| 17 |
+
def finish(h,limit=1800):
|
| 18 |
+
if h.phase!='running':call(h,'acquisition.start')
|
| 19 |
+
for _ in range(limit):
|
| 20 |
+
h.step(1.)
|
| 21 |
+
if h.phase!='running':break
|
| 22 |
+
return h
|
| 23 |
+
def until(h,stage,limit=1000):
|
| 24 |
+
if h.phase!='running':call(h,'acquisition.start')
|
| 25 |
+
for _ in range(limit*10):
|
| 26 |
+
if h.stage==stage:return
|
| 27 |
+
if h.phase!='running':raise AssertionError((h.phase,h.stage,h.failure))
|
| 28 |
+
h.step(.1)
|
| 29 |
+
raise AssertionError((stage,h.stage,h.failure))
|
| 30 |
+
class Tests(unittest.TestCase):
|
| 31 |
+
def ledger(self,h):
|
| 32 |
+
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.)
|
| 33 |
+
def test_01_real_reference_provenance(self):
|
| 34 |
+
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.)
|
| 35 |
+
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'])
|
| 36 |
+
def test_02_both_directions_pressure_inversion(self):
|
| 37 |
+
for d in ['sample_first','powder_protect']:
|
| 38 |
+
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)
|
| 39 |
+
self.assertAlmostEqual(res['standard_deviation_m3'],statistics.stdev(v['volume_m3'] for v in res['runs']),places=15)
|
| 40 |
+
def test_03_closed_and_open_pores(self):
|
| 41 |
+
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)
|
| 42 |
+
def test_04_entered_mass_not_truth(self):
|
| 43 |
+
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)
|
| 44 |
+
def test_05_two_actual_pressure_runs_calibration(self):
|
| 45 |
+
for d in ['sample_first','powder_protect']:
|
| 46 |
+
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)
|
| 47 |
+
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)
|
| 48 |
+
def test_06_pressure_gain_offset_calibration(self):
|
| 49 |
+
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)
|
| 50 |
+
def test_07_flow_purge_exact_residual(self):
|
| 51 |
+
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)
|
| 52 |
+
def test_08_pulse_preparation(self):
|
| 53 |
+
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)
|
| 54 |
+
def test_09_vacuum_and_missing_pump(self):
|
| 55 |
+
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)
|
| 56 |
+
h=setup(plant={'pump_available':False},method={'preparation':'vacuum','preparation_s':60.});old=h.read('evaluator')
|
| 57 |
+
with self.assertRaisesRegex(r.ActionRejected,'PUMP_UNAVAILABLE'):call(h,'acquisition.start')
|
| 58 |
+
self.assertEqual(old,h.read('evaluator'))
|
| 59 |
+
def test_10_finite_gas_depletion(self):
|
| 60 |
+
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)
|
| 61 |
+
def test_11_leak_observation_is_not_random_fault(self):
|
| 62 |
+
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)
|
| 63 |
+
def test_12_setpoint_energy_cooling_and_heating(self):
|
| 64 |
+
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)
|
| 65 |
+
def test_13_partial_cancel_and_poweroff_vent(self):
|
| 66 |
+
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)
|
| 67 |
+
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)
|
| 68 |
+
def test_14_pure_reads_partition_and_instances(self):
|
| 69 |
+
a=setup();b=copy.deepcopy(a);call(a,'acquisition.start');call(b,'acquisition.start');a.step(7.3)
|
| 70 |
+
for _ in range(73):b.step(.1)
|
| 71 |
+
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.)
|
| 72 |
+
def test_15_atomic_mechanical_sequence(self):
|
| 73 |
+
h=setup();old=h.read('evaluator')
|
| 74 |
+
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))]:
|
| 75 |
+
with self.assertRaises(r.ActionRejected):call(h,k,a)
|
| 76 |
+
self.assertEqual(old,h.read('evaluator'))
|
| 77 |
+
until(h,'expand')
|
| 78 |
+
with self.assertRaisesRegex(r.ActionRejected,'BUSY'):call(h,'lid.set',{'lift_m':.13})
|
| 79 |
+
call(h,'acquisition.stop')
|
| 80 |
+
with self.assertRaisesRegex(r.ActionRejected,'PRESSURE_INTERLOCK'):call(h,'seal.set',{'angle_rad':0.})
|
| 81 |
+
def test_16_capacity_and_nominal_optin(self):
|
| 82 |
+
for sample in [{'true_mass_kg':.5},{'accept_reference_transfer':False},{'reference_id':'invalid_secret'}]:
|
| 83 |
+
h=setup(load=False);open_cup(h);old=copy.deepcopy(h.read('evaluator'))
|
| 84 |
+
with self.assertRaises(r.ActionRejected):call(h,'sample.load',dict(r.SAMPLE_EXAMPLE,**sample))
|
| 85 |
+
self.assertEqual(old,h.read('evaluator'));self.ledger(h)
|
| 86 |
+
def test_17_six_semantic_cells_and_dual_references(self):
|
| 87 |
+
for key,v in r.CELLS.items():
|
| 88 |
+
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)
|
| 89 |
+
def test_18_automatic_and_declared_thermal_expansion(self):
|
| 90 |
+
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)
|
| 91 |
+
def test_19_permission_dedup_poll_and_schemas(self):
|
| 92 |
+
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')
|
| 93 |
+
with self.assertRaises(r.ActionRejected):q.poll(v['operation_id'])
|
| 94 |
+
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'])))
|
| 95 |
+
for k in r.UNSUPPORTED:
|
| 96 |
+
with self.assertRaisesRegex(r.ActionRejected,'UNSUPPORTED'):h.invoke(k)
|
| 97 |
+
for dt in [True,-1,float('nan'),float('inf')]:
|
| 98 |
+
with self.assertRaises(r.ActionRejected):h.step(dt)
|
| 99 |
+
def test_20_unload_mass_and_home_release(self):
|
| 100 |
+
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'],'')
|
| 101 |
+
def test_21_three_inert_gases(self):
|
| 102 |
+
for gas in ['He','N2','Ar']:
|
| 103 |
+
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)
|
| 104 |
+
def test_22_blocked_valve_timeout(self):
|
| 105 |
+
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)
|
| 106 |
+
def test_23_reconfigure_does_not_implicitly_vent(self):
|
| 107 |
+
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)
|
| 108 |
+
empty=setup(load=False)
|
| 109 |
+
with self.assertRaisesRegex(r.ActionRejected,'INSERT_ACCESS'):call(empty,'method.configure',dict(empty.method,cell='small'))
|
| 110 |
+
open_cup(empty);call(empty,'method.configure',dict(empty.method,cell='small'));self.assertEqual(empty.cell,10e-6);self.ledger(empty)
|
| 111 |
+
def test_24_completed_result_keeps_run_mass(self):
|
| 112 |
+
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)
|
| 113 |
+
if __name__=='__main__':unittest.main()
|
tests/test_asset_applied_sx20.py
ADDED
|
@@ -0,0 +1,203 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import copy,json,math,sys,unittest
|
| 2 |
+
from pathlib import Path
|
| 3 |
+
import numpy as np
|
| 4 |
+
from scipy.linalg import expm
|
| 5 |
+
ROOT=Path(__file__).resolve().parents[1];sys.path.insert(0,str(ROOT/'scripts'))
|
| 6 |
+
from asset_runtime.applied_sx20 import *
|
| 7 |
+
def ready(plant=None,sample=None,method=None):
|
| 8 |
+
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))
|
| 9 |
+
for k,a in [('bath.cover',{'opened':False}),('valves.set',{'drive':True}),('gas.set',{'enabled':True}),('power.set',{'enabled':True})]:r.invoke(k,**a)
|
| 10 |
+
return r
|
| 11 |
+
def flush(r):
|
| 12 |
+
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)
|
| 13 |
+
class TestSx20(unittest.TestCase):
|
| 14 |
+
def assertReject(self,r,k,args,code):
|
| 15 |
+
before=r.debug_snapshot()
|
| 16 |
+
with self.assertRaisesRegex(ActionRejected,code):r.invoke(k,**args)
|
| 17 |
+
self.assertEqual(before,r.debug_snapshot())
|
| 18 |
+
def test_01_references(self):
|
| 19 |
+
t=_templates() if '_templates' in globals() else AppliedSx20Runtime().templates
|
| 20 |
+
self.assertEqual(len(t),63);self.assertEqual(len({q['name'] for q in t.values()}),63)
|
| 21 |
+
for q in t.values():self.assertIsNone(q['kinetic_constants_s_inv']);self.assertIsNone(q['measured_time_trace'])
|
| 22 |
+
def test_02_guard_ack(self):
|
| 23 |
+
r=AppliedSx20Runtime();self.assertReject(r,'plant.configure',dict(PLANT_EXAMPLE,accept_surrogate_model=False),'EVIDENCE_ACK')
|
| 24 |
+
def test_03_initialization_at_nonzero_clock(self):
|
| 25 |
+
r=AppliedSx20Runtime();r.step(.02);r.invoke('plant.configure',**PLANT_EXAMPLE);self.assertReject(r,'plant.configure',PLANT_EXAMPLE,'INITIALIZATION')
|
| 26 |
+
def test_04_guard_solvent(self):
|
| 27 |
+
r=AppliedSx20Runtime();r.invoke('plant.configure',**PLANT_EXAMPLE);self.assertReject(r,'sample.load',dict(SAMPLE_EXAMPLE,solvent='water'),'SOLVENT')
|
| 28 |
+
def test_05_guard_hypothetical_ack(self):
|
| 29 |
+
r=AppliedSx20Runtime();r.invoke('plant.configure',**PLANT_EXAMPLE);self.assertReject(r,'sample.load',dict(SAMPLE_EXAMPLE,accept_hypothetical_kinetics=False),'EVIDENCE_ACK')
|
| 30 |
+
def test_06_source_coverage(self):
|
| 31 |
+
r=ready(method=dict(METHOD_EXAMPLE,wavelength_m=850e-9));self.assertReject(r,'acquisition.start',{},'SOURCE_COVERAGE')
|
| 32 |
+
def test_07_physical_mixing_ratio(self):
|
| 33 |
+
r=ready();self.assertReject(r,'method.configure',dict(METHOD_EXAMPLE,mix_ratio_a_b=2),'PHYSICAL_RATIO')
|
| 34 |
+
def test_08_asymmetric_capacity(self):
|
| 35 |
+
for cap in [1e-6,.5e-6,.25e-6,.1e-6]:
|
| 36 |
+
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)
|
| 37 |
+
useda=2.5e-6-r._va;usedb=cap-r._vb;self.assertAlmostEqual(useda/usedb,ratio,places=9)
|
| 38 |
+
def test_09_standard_path(self):
|
| 39 |
+
r=ready();self.assertReject(r,'method.configure',dict(METHOD_EXAMPLE,path_m=.005),'POWER_OFF')
|
| 40 |
+
r.invoke('power.set',enabled=False);self.assertReject(r,'method.configure',dict(METHOD_EXAMPLE,path_m=.005),'CELL_PATH')
|
| 41 |
+
def test_10_rapid_option(self):
|
| 42 |
+
r=ready(plant=dict(PLANT_EXAMPLE,rapid_cell_installed=True),method=dict(METHOD_EXAMPLE,path_m=.005,stop_volume_m3=35e-9))
|
| 43 |
+
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)
|
| 44 |
+
def test_11_no_early_observation(self):
|
| 45 |
+
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)
|
| 46 |
+
def test_12_delay_not_double_clock(self):
|
| 47 |
+
r=ready(method=dict(METHOD_EXAMPLE,delay_s=.005));r.invoke('acquisition.start');r.step(.074);self.assertEqual(r.points,[]);r.step(.001)
|
| 48 |
+
self.assertAlmostEqual(r.time_s,.075);self.assertAlmostEqual(r.points[0]['sample_time_s'],.075);self.assertAlmostEqual(r.points[0]['reaction_age_s'],.006)
|
| 49 |
+
def test_13_partition_invariance(self):
|
| 50 |
+
a=ready();b=ready()
|
| 51 |
+
for r in [a,b]:r.invoke('acquisition.start')
|
| 52 |
+
a.step(.7)
|
| 53 |
+
for _ in range(700):b.step(.001)
|
| 54 |
+
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)
|
| 55 |
+
np.testing.assert_allclose([a._va,a._nc,a._ns],[b._va,b._nc,b._ns],rtol=1e-10,atol=1e-20)
|
| 56 |
+
def test_14_conservation_partial_full(self):
|
| 57 |
+
r=ready();r.invoke('acquisition.start')
|
| 58 |
+
for dt in [.013,.027,.031,.5]:
|
| 59 |
+
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)
|
| 60 |
+
def test_15_cell_washout_exact(self):
|
| 61 |
+
r=ready();r.invoke('acquisition.start');r.step(.035);v=.035*PLANT_EXAMPLE['flow_m3_s'];cin=SAMPLE_EXAMPLE['stock_concentration_mol_m3']/2
|
| 62 |
+
self.assertAlmostEqual(r._nc/(cin*20e-9),1-math.exp(-v/20e-9),places=12)
|
| 63 |
+
def test_16_cancel_retains_consumption(self):
|
| 64 |
+
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,[])
|
| 65 |
+
def test_17_cover_cancel(self):
|
| 66 |
+
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')
|
| 67 |
+
def test_18_power_cancel(self):
|
| 68 |
+
r=ready();r.invoke('acquisition.start');r.step(.08);r.invoke('power.set',enabled=False);self.assertEqual(r.phase,'cancelled')
|
| 69 |
+
def test_19_gas_cancel(self):
|
| 70 |
+
r=ready();r.invoke('acquisition.start');r.step(.03);r.invoke('gas.set',enabled=False);self.assertEqual(r.phase,'cancelled')
|
| 71 |
+
def test_20_new_start_needs_flush(self):
|
| 72 |
+
r=ready();r.invoke('acquisition.start');r.step(1);self.assertReject(r,'acquisition.start',{},'EXTERNAL_FLUSH')
|
| 73 |
+
def test_21_flush_and_autoempty(self):
|
| 74 |
+
r=ready();r.invoke('acquisition.start');r.step(1);oldstop=r._vs;oldn=r._ns;flush(r)
|
| 75 |
+
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)
|
| 76 |
+
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)
|
| 77 |
+
def test_22_equal_rates_exponential_oracle(self):
|
| 78 |
+
for k1,k2 in [(20,20),(20,20.000001),(40,8),(8,40)]:
|
| 79 |
+
for t in [0,.001,.04,1,1e3]:
|
| 80 |
+
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)
|
| 81 |
+
def test_23_intermediate_peak(self):
|
| 82 |
+
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])
|
| 83 |
+
def test_24_absorbance_independent(self):
|
| 84 |
+
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)
|
| 85 |
+
def test_25_fluor_filter_independent(self):
|
| 86 |
+
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)&(x<hi)],hi]
|
| 87 |
+
fraction=np.trapezoid(np.interp(grid,x,y),grid)/np.trapezoid(y,x);eps=np.interp(425e-9,t['abs_wavelength_m'],t['epsilon_m2_mol']);f=AppliedSx20Runtime.fractions(.001,40,8)
|
| 88 |
+
expected=10*(1-10**(-eps*.001*(1-math.exp(-7))*.002))*.79*fraction*np.dot(f,[1,2,.15]);self.assertAlmostEqual(r.points[0]['signal'],expected,places=11);self.assertEqual(r.points[0]['unit'],'V')
|
| 89 |
+
def test_26_fluor_excitation_guard(self):
|
| 90 |
+
r=ready(method=dict(FLUOR_METHOD,wavelength_m=430e-9));self.assertReject(r,'acquisition.start',{},'EXCITATION_REFERENCE')
|
| 91 |
+
def test_27_fluor_rapid_path(self):
|
| 92 |
+
r=ready(plant=dict(PLANT_EXAMPLE,rapid_cell_installed=True),method=dict(FLUOR_METHOD,path_m=.005));r.invoke('acquisition.start');r.step(1);self.assertTrue(r.points)
|
| 93 |
+
def test_28_fluor_path_reject(self):
|
| 94 |
+
r=ready();r.invoke('power.set',enabled=False);self.assertReject(r,'method.configure',dict(FLUOR_METHOD,path_m=.01),'FLUOR_EXCITATION')
|
| 95 |
+
def test_29_log_schedule(self):
|
| 96 |
+
r=ready(method=dict(METHOD_EXAMPLE,timebase='log'));r.invoke('acquisition.start');r.step(1);times=np.array([p['trigger_time_s'] for p in r.points]);self.assertEqual(len(times),101);self.assertEqual(times[0],0);self.assertAlmostEqual(times[-1],.5);self.assertTrue(np.all(np.diff(times)>0))
|
| 97 |
+
def test_30_noise_deterministic_partition(self):
|
| 98 |
+
a=ready(plant=dict(PLANT_EXAMPLE,abs_noise_sd=.001));b=ready(plant=dict(PLANT_EXAMPLE,abs_noise_sd=.001))
|
| 99 |
+
for r in [a,b]:r.invoke('acquisition.start')
|
| 100 |
+
a.step(1)
|
| 101 |
+
for _ in range(100):b.step(.01)
|
| 102 |
+
np.testing.assert_allclose([p['signal'] for p in a.points],[p['signal'] for p in b.points],atol=1e-12)
|
| 103 |
+
def test_31_fit_only_observations(self):
|
| 104 |
+
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())
|
| 105 |
+
def test_32_fit_invalid(self):
|
| 106 |
+
r=ready();self.assertReject(r,'kinetics.fit',dict(time_s=[0]*6,signal=[1]*6),'ANALYSIS')
|
| 107 |
+
def test_33_blank_caller_value(self):
|
| 108 |
+
r=ready();r.invoke('calibration.zero',observed_blank=.02,mode='absorbance');self.assertEqual(r._correction['absorbance'],-.02)
|
| 109 |
+
def test_34_readonly_deepcopy(self):
|
| 110 |
+
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)
|
| 111 |
+
def test_35_acl(self):
|
| 112 |
+
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'])
|
| 113 |
+
with self.assertRaisesRegex(ActionRejected,'ACCESS_DENIED'):s.read(instance_id=r.instance_id,state_ids=['truth.ledger'])
|
| 114 |
+
def test_36_request_dedup(self):
|
| 115 |
+
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)
|
| 116 |
+
args.update(capability_id='acquisition.stop');self.assertEqual(s.invoke(**args)['error']['code'],'REQUEST_CONFLICT')
|
| 117 |
+
def test_37_poll_owner_cancel(self):
|
| 118 |
+
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')
|
| 119 |
+
with self.assertRaisesRegex(ActionRejected,'ACCESS_DENIED'):r.session('other').poll(rep['operation_id'])
|
| 120 |
+
self.assertEqual(s.cancel(rep['operation_id'],'cancel')['status'],'succeeded');self.assertEqual(s.poll(rep['operation_id'])['status'],'cancelled')
|
| 121 |
+
def test_38_schema_bool_nan_extra(self):
|
| 122 |
+
r=ready()
|
| 123 |
+
for value in [True,float('nan'),float('inf')]:self.assertReject(r,'calibration.zero',dict(observed_blank=value,mode='absorbance'),'INVALID_ARGUMENT')
|
| 124 |
+
self.assertReject(r,'power.set',dict(enabled=True,unexpected=3),'INVALID_ARGUMENT')
|
| 125 |
+
def test_39_zero_step_stability(self):
|
| 126 |
+
r=ready();s=r.debug_snapshot();r.step(0);self.assertEqual(s,r.debug_snapshot())
|
| 127 |
+
def test_40_busy_guard_atomic(self):
|
| 128 |
+
r=ready();r.invoke('acquisition.start');self.assertReject(r,'method.configure',METHOD_EXAMPLE,'BUSY')
|
| 129 |
+
def test_41_unsupported(self):
|
| 130 |
+
r=ready()
|
| 131 |
+
for k in UNSUPPORTED:self.assertReject(r,k,CAPS[k][6],'UNSUPPORTED')
|
| 132 |
+
def test_42_timestamp_not_read_time(self):
|
| 133 |
+
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.)
|
| 134 |
+
def test_43_all_templates_actual_output(self):
|
| 135 |
+
for t in AppliedSx20Runtime().templates.values():
|
| 136 |
+
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)
|
| 137 |
+
sample=dict(SAMPLE_EXAMPLE,template_id=t['substance_id'],solvent=t['conditions']['solvent'])
|
| 138 |
+
method=dict(FLUOR_METHOD,wavelength_m=t['conditions']['reference_excitation_m'],filter_low_m=lo,filter_high_m=hi,points=6,duration_s=.01)
|
| 139 |
+
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)
|
| 140 |
+
def test_44_no_factory_dimensions(self):
|
| 141 |
+
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'])
|
| 142 |
+
def test_45_physical_unit_slots(self):
|
| 143 |
+
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'])
|
| 144 |
+
def test_46_reconfigure_preserves_old_observation_unit(self):
|
| 145 |
+
r=ready();r.invoke('acquisition.start');r.step(1);r.invoke('power.set',enabled=False);r.invoke('method.configure',**FLUOR_METHOD)
|
| 146 |
+
self.assertEqual(r.read()['scan.unit'],'1');self.assertIsNone(r.read()['scan.fluorescence_v']);self.assertIsNotNone(r.read()['scan.absorbance'])
|
| 147 |
+
def test_47_fit_time_and_signal_scale_equivariance(self):
|
| 148 |
+
base=np.linspace(0,1,60);r=AppliedSx20Runtime()
|
| 149 |
+
for time_scale,signal_scale in [(1.,1e-20),(1.,1e200),(1e12,1.),(1e-12,1.)]:
|
| 150 |
+
with self.subTest(time_scale=time_scale,signal_scale=signal_scale):
|
| 151 |
+
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())
|
| 152 |
+
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)
|
| 153 |
+
json.dumps(out,allow_nan=False);self.assertEqual(before,r.debug_snapshot())
|
| 154 |
+
def test_48_fit_unrepresentable_rate_is_clear_atomic_rejection(self):
|
| 155 |
+
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()
|
| 156 |
+
reply=r.session().invoke(instance_id=r.instance_id,capability_id='kinetics.fit',arguments=args,request_id='too-fast-for-number')
|
| 157 |
+
self.assertEqual(reply['status'],'rejected');self.assertEqual(reply['error']['code'],'FIT_UNIDENTIFIABLE');self.assertEqual(before,r.debug_snapshot());json.dumps(reply,allow_nan=False)
|
| 158 |
+
def test_49_result_method_retained_until_next_acquisition(self):
|
| 159 |
+
r=ready();r.invoke('acquisition.start');r.step(1);old=r.invoke('result.read');new=dict(METHOD_EXAMPLE,duration_s=.2,delay_s=.01)
|
| 160 |
+
r.invoke('method.configure',**new);self.assertEqual(r.invoke('result.read'),old);self.assertEqual(json.loads(old['settings_json']),METHOD_EXAMPLE)
|
| 161 |
+
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)
|
| 162 |
+
result=r.invoke('result.read');self.assertAlmostEqual(result['points'][-1]['trigger_time_s'],.21);self.assertEqual(json.loads(result['settings_json']),new)
|
| 163 |
+
def test_50_depleted_stocks_nonnegative_and_conserved(self):
|
| 164 |
+
r=ready(method=dict(METHOD_EXAMPLE,stop_volume_m3=2.5e-6))
|
| 165 |
+
for shot in range(2):
|
| 166 |
+
if shot:flush(r)
|
| 167 |
+
r.invoke('acquisition.start')
|
| 168 |
+
while r.phase=='running':r.step(.007)
|
| 169 |
+
ledger=r.invoke('product.read')
|
| 170 |
+
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.)
|
| 171 |
+
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)
|
| 172 |
+
self.assertAlmostEqual(ledger['modeled_mass_residual_kg'],ledger['volume_residual_m3']*PLANT_EXAMPLE['fluid_density_kg_m3'])
|
| 173 |
+
for key,value in r.read('evaluator').items():validate(SLOTS[key][0],value)
|
| 174 |
+
flush(r);self.assertReject(r,'acquisition.start',{},'INSUFFICIENT_REAGENT')
|
| 175 |
+
def test_51_historical_completion_snapshot_has_final_elapsed_and_owner(self):
|
| 176 |
+
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)
|
| 177 |
+
terminal=s.poll(op);self.assertEqual(terminal['status'],'succeeded');self.assertAlmostEqual(terminal['result']['elapsed_s'],.57);self.assertEqual(terminal['result']['completed_points'],101)
|
| 178 |
+
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)
|
| 179 |
+
terminal['result']['completed_points']=999;self.assertEqual(s.poll(op)['result']['completed_points'],101)
|
| 180 |
+
self.assertNotIn(SAMPLE_EXAMPLE['sample_id'],json.dumps(s.poll(op)));self.assertNotIn(SAMPLE_EXAMPLE['template_id'],json.dumps(s.poll(op)))
|
| 181 |
+
with self.assertRaisesRegex(ActionRejected,'ACCESS_DENIED'):r.session('other').poll(op)
|
| 182 |
+
self.assertEqual(before,r.debug_snapshot())
|
| 183 |
+
def test_52_cancel_historical_terminal_does_not_cancel_current(self):
|
| 184 |
+
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)
|
| 185 |
+
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]
|
| 186 |
+
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)
|
| 187 |
+
with self.assertRaisesRegex(ActionRejected,'REQUEST_CONFLICT'):s.cancel(current,'cancel-old')
|
| 188 |
+
self.assertEqual(r.phase,'running')
|
| 189 |
+
def test_53_cancelled_observations_and_transferred_liquid_stay_retained(self):
|
| 190 |
+
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]
|
| 191 |
+
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)
|
| 192 |
+
r.step(1);self.assertEqual(r.points,points);self.assertEqual([r._va,r._vb,r._vs,r._vw],volumes);self.assertTrue(r.needs_flush)
|
| 193 |
+
flush(r);s.invoke(instance_id=r.instance_id,capability_id='acquisition.start',arguments={},request_id='next');self.assertEqual(s.poll(op),terminal)
|
| 194 |
+
def test_54_metadata_tracks_actual_calibration_and_drive_timing(self):
|
| 195 |
+
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()
|
| 196 |
+
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.)
|
| 197 |
+
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']))
|
| 198 |
+
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'}
|
| 199 |
+
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.)
|
| 200 |
+
self.assertEqual(caps['kinetics.fit']['observes'],[]);self.assertEqual(caps['power.set']['observes'],['power.enabled'])
|
| 201 |
+
if __name__=='__main__':unittest.main()
|
| 202 |
+
|
| 203 |
+
|
tests/test_asset_arradiance_gemstarxt.py
ADDED
|
@@ -0,0 +1,177 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""CHEM-064 independent conservation, timing, interlock and protocol checks."""
|
| 2 |
+
import copy,math,sys,unittest
|
| 3 |
+
from pathlib import Path
|
| 4 |
+
sys.path.insert(0,str(Path(__file__).resolve().parents[1]/'scripts'))
|
| 5 |
+
from asset_runtime.arradiance_gemstarxt import *
|
| 6 |
+
def ready(law='alumina_tma_water',warm=True,plant=None,kinetics=None,supply=None,method=None,sample=True):
|
| 7 |
+
h=ArradianceGemstarxtRuntime();p=dict(WARM_EXAMPLE if warm else PLANT_EXAMPLE)
|
| 8 |
+
if law in ['zinc_dez_water','titania_ttip_water']:p['initial_k']=[423.15,423.15,373.15] if warm else [298.15]*3
|
| 9 |
+
p.update(plant or {});h.invoke('plant.configure',**p)
|
| 10 |
+
su=copy.deepcopy(SUPPLY_EXAMPLE);su['bottle_species'][0]=LAWS[law]['a'];su.update(supply or {});h.invoke('gas.install',**su)
|
| 11 |
+
ke=dict(KINETICS_EXAMPLE,law_id=law)
|
| 12 |
+
if law=='zinc_dez_water':ke.update(density_kg_m3=5600.,adsorption_pa_s_inv=1.4,conversion_pa_s_inv=1.8)
|
| 13 |
+
if law=='titania_ttip_water':ke.update(density_kg_m3=3900.,adsorption_pa_s_inv=.7,conversion_pa_s_inv=.9)
|
| 14 |
+
if LAWS[law]['plasma']:ke.update(plasma_site_mol_m2=3e-6,adsorption_pa_s_inv=1.,conversion_pa_s_inv=1.)
|
| 15 |
+
ke.update(kinetics or {});h.invoke('kinetics.configure',**ke)
|
| 16 |
+
if sample:h.invoke('sample.install',**(HOT_SAMPLE_EXAMPLE if warm else SAMPLE_EXAMPLE))
|
| 17 |
+
m=copy.deepcopy(METHOD_EXAMPLE)
|
| 18 |
+
if law in ['zinc_dez_water','titania_ttip_water']:m.update(reactor_k=423.15,door_k=423.15)
|
| 19 |
+
if LAWS[law]['plasma']:m.update(rf_w=150.,pulse_s=[.2,.5],exposure_s=[.5,2.])
|
| 20 |
+
m.update(method or {});h.invoke('method.configure',**m)
|
| 21 |
+
if not warm:h.invoke('door.set',opened=False)
|
| 22 |
+
h.invoke('power.set',enabled=True)
|
| 23 |
+
if LAWS[law]['plasma']:h.invoke('rf.power_set',enabled=True)
|
| 24 |
+
return h
|
| 25 |
+
def run(law='alumina_tma_water',**kwargs):
|
| 26 |
+
h=ready(law,**kwargs);h.invoke('acquisition.start');h.step(100);return h
|
| 27 |
+
def at_stage(h,stage,limit=20000):
|
| 28 |
+
for _ in range(limit):
|
| 29 |
+
if h.stage==stage:return
|
| 30 |
+
h.step(.02)
|
| 31 |
+
raise AssertionError((h.stage,h.phase,stage))
|
| 32 |
+
class TestALD(unittest.TestCase):
|
| 33 |
+
def conserved(self,h):
|
| 34 |
+
d=h._ledger();self.assertLess(max(map(abs,d['atom_residual_mol'])),1e-10);self.assertLess(abs(d['thermal_residual_j']),1e-5)
|
| 35 |
+
for x in [h.gas,h.exhaust,h.film,h.collected]:self.assertTrue(all(n>=0 for n in x.values()))
|
| 36 |
+
self.assertGreaterEqual(h.adsorbed,0);self.assertLessEqual(h.adsorbed,h.capacity+1e-14)
|
| 37 |
+
def rejects_unchanged(self,h,cap,**a):
|
| 38 |
+
old=h.debug_snapshot()
|
| 39 |
+
with self.assertRaises(ActionRejected):h.invoke(cap,**a)
|
| 40 |
+
self.assertEqual(old,h.debug_snapshot())
|
| 41 |
+
def test_01_primary_three_and_curated_not_50(self):
|
| 42 |
+
h=ArradianceGemstarxtRuntime();self.assertEqual(len(h.templates),3);self.assertEqual(len(h.references),109)
|
| 43 |
+
self.assertEqual(len({r['material'] for r in h.references.values() if r['material']}),45)
|
| 44 |
+
self.assertTrue(all(not r['runnable'] for r in h.references.values()))
|
| 45 |
+
def test_02_anchors_have_distinct_precursors_conditions_sources(self):
|
| 46 |
+
h=ArradianceGemstarxtRuntime();self.assertEqual({r['value'] for r in h.templates.values()},{1.05e-10,1.8e-10,.5e-10})
|
| 47 |
+
self.assertEqual(h.templates['titania_ttip_water']['precursor'],'TTIP')
|
| 48 |
+
for r in h.templates.values():self.assertEqual(r['evidence'],'measured_literature');self.assertTrue(r['source']['sha256'])
|
| 49 |
+
def test_03_all_net_reactions_element_balanced(self):
|
| 50 |
+
for law in LAWS.values():
|
| 51 |
+
for i in range(8):
|
| 52 |
+
lhs=law['na']*ATOMS[law['a']][i]+law['nb']*ATOMS[law['b']][i]
|
| 53 |
+
rhs=ATOMS[law['film']][i]+sum(c*ATOMS[s][i] for s,c in law['products'].items());self.assertEqual(lhs,rhs)
|
| 54 |
+
def test_04_initial_warm_snapshot_explicit(self):
|
| 55 |
+
h=ArradianceGemstarxtRuntime();self.rejects_unchanged(h,'plant.configure',**dict(WARM_EXAMPLE,warm_snapshot=False))
|
| 56 |
+
h.invoke('plant.configure',**WARM_EXAMPLE);self.assertGreater(h.thermal_initial,0);self.conserved(h);self.rejects_unchanged(h,'plant.configure',**WARM_EXAMPLE)
|
| 57 |
+
def test_05_cold_configuration_not_teleport(self):
|
| 58 |
+
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)
|
| 59 |
+
def test_06_hot_sample_only_same_initialization_clock(self):
|
| 60 |
+
h=ready(sample=False);h.step(.01);self.rejects_unchanged(h,'sample.install',**HOT_SAMPLE_EXAMPLE)
|
| 61 |
+
def test_07_substrate_200mm_max(self):
|
| 62 |
+
h=ready(sample=False);self.rejects_unchanged(h,'sample.install',**dict(HOT_SAMPLE_EXAMPLE,area_m2=math.pi*.101**2))
|
| 63 |
+
def test_08_hardware_temperature_limits(self):
|
| 64 |
+
h=ready()
|
| 65 |
+
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}))
|
| 66 |
+
def test_09_carrier_rf_hard_limits(self):
|
| 67 |
+
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))
|
| 68 |
+
def test_10_temperature_anchor_not_extrapolated(self):
|
| 69 |
+
h=ready();self.rejects_unchanged(h,'method.configure',**dict(METHOD_EXAMPLE,reactor_k=423.15))
|
| 70 |
+
def test_11_plasma_not_thermal_fixed_gpc(self):
|
| 71 |
+
h=ready(sample=False);self.rejects_unchanged(h,'kinetics.configure',**dict(KINETICS_EXAMPLE,law_id='plasma_tma_oxygen'))
|
| 72 |
+
h=run('plasma_tma_oxygen');self.assertEqual(h.phase,'succeeded');self.assertGreater(h.film['Al2O3'],0);self.conserved(h)
|
| 73 |
+
e=h.invoke('film.estimate');self.assertFalse(e['measured']);self.assertIn('no_measured_GPC',e['template_source'])
|
| 74 |
+
def test_12_three_materials_complete_and_thickness_formula(self):
|
| 75 |
+
results=[]
|
| 76 |
+
for law in list(LAWS)[:3]:
|
| 77 |
+
h=run(law);self.assertEqual(h.phase,'succeeded');self.assertEqual(h.completed,2);self.conserved(h)
|
| 78 |
+
ratio=h._thickness()/(2*h.templates[law]['value']);self.assertAlmostEqual(ratio,1,delta=1e-6);results.append(h._thickness())
|
| 79 |
+
self.assertEqual(len(set(round(x,14) for x in results)),3)
|
| 80 |
+
def test_13_finite_feed_pulse_integral(self):
|
| 81 |
+
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)
|
| 82 |
+
def test_14_substep_short_pulse_no_extra_dose(self):
|
| 83 |
+
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)
|
| 84 |
+
def test_15_saturation_caps_growth_not_pulse_linear(self):
|
| 85 |
+
a=run(method={'pulse_s':[.2,.2],'cycles':1});b=run(method={'pulse_s':[2.,2.],'cycles':1})
|
| 86 |
+
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]))
|
| 87 |
+
def test_16_underexposure_not_forced_nominal_gpc(self):
|
| 88 |
+
h=run(kinetics={'adsorption_pa_s_inv':1e-5,'conversion_pa_s_inv':1e-5})
|
| 89 |
+
self.assertLess(h._thickness(),2*h.templates['alumina_tma_water']['value']*.01);self.assertGreater(h.adsorbed,0);self.conserved(h)
|
| 90 |
+
def test_17_a_half_reaction_bound_no_film(self):
|
| 91 |
+
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)
|
| 92 |
+
def test_18_cancel_preserves_adsorbate_residual(self):
|
| 93 |
+
h=ready();h.invoke('acquisition.start');at_stage(h,'exposure_a');before=h.adsorbed;gas=h.gas['TMA'];h.invoke('acquisition.stop')
|
| 94 |
+
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)
|
| 95 |
+
def test_19_cancel_after_b_preserves_partial_film(self):
|
| 96 |
+
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)
|
| 97 |
+
def test_20_purge_extends_and_clears_residual(self):
|
| 98 |
+
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)
|
| 99 |
+
def test_21_purge_timeout_not_fake_success(self):
|
| 100 |
+
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)
|
| 101 |
+
def test_22_empty_source_fail_finite(self):
|
| 102 |
+
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)
|
| 103 |
+
def test_23_shared_carrier_not_double_count(self):
|
| 104 |
+
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)
|
| 105 |
+
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)
|
| 106 |
+
def test_24_rf_independent_power_interlock(self):
|
| 107 |
+
h=ready('plasma_tma_oxygen');h.invoke('rf.power_set',enabled=False);self.rejects_unchanged(h,'acquisition.start')
|
| 108 |
+
def test_25_powerloss_closes_all_keeps_material(self):
|
| 109 |
+
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)
|
| 110 |
+
def test_26_emo_reset_requires_both_off(self):
|
| 111 |
+
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)
|
| 112 |
+
def test_27_watchdog_failure_and_heartbeat(self):
|
| 113 |
+
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')
|
| 114 |
+
def test_28_hot_or_vacuum_door_rejected(self):
|
| 115 |
+
h=ready();self.rejects_unchanged(h,'door.set',opened=True);h.invoke('power.set',enabled=False);self.rejects_unchanged(h,'door.set',opened=True)
|
| 116 |
+
def test_29_cold_vent_collect_conserves(self):
|
| 117 |
+
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)
|
| 118 |
+
def test_30_collect_bound_and_film_after_cooling(self):
|
| 119 |
+
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)
|
| 120 |
+
def test_31_read_describe_stepzero_pure(self):
|
| 121 |
+
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())
|
| 122 |
+
def test_32_rejection_atomic_and_numeric_boolean(self):
|
| 123 |
+
h=ready()
|
| 124 |
+
for x in [True,float('nan'),float('inf'),-1]:self.rejects_unchanged(h,'method.configure',**dict(METHOD_EXAMPLE,carrier_std_m3_s=x))
|
| 125 |
+
h.invoke('acquisition.start');self.rejects_unchanged(h,'method.configure',**METHOD_EXAMPLE)
|
| 126 |
+
def test_33_two_instance_independence(self):
|
| 127 |
+
a=ready();b=ready();old=b.debug_snapshot();a.invoke('acquisition.start');a.step(2);self.assertEqual(b.debug_snapshot(),old)
|
| 128 |
+
def test_34_truth_filter_and_host_only_identity(self):
|
| 129 |
+
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'])
|
| 130 |
+
r=s.invoke(instance_id=h.instance_id,capability_id='product.read',arguments={},request_id='deny');self.assertEqual(r['error']['code'],'ACCESS_DENIED')
|
| 131 |
+
with self.assertRaises(ActionRejected):s.read(instance_id=h.instance_id,state_ids=['truth.ledger'])
|
| 132 |
+
with self.assertRaises(ActionRejected):h.session('evaluator')
|
| 133 |
+
def test_35_idempotency_conflict_operation_owner(self):
|
| 134 |
+
h=ready();s=h.session();args=dict(instance_id=h.instance_id,capability_id='acquisition.start',arguments={},request_id='a')
|
| 135 |
+
r=s.invoke(**args);self.assertEqual(s.invoke(**args),r);self.assertEqual(h._operation_count,1)
|
| 136 |
+
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')
|
| 137 |
+
h.register_principal('other');other=h.session('other')
|
| 138 |
+
with self.assertRaises(ActionRejected):other.poll(r['operation_id'])
|
| 139 |
+
s.cancel(r['operation_id'],'cancel');self.assertEqual(h.phase,'cancelled')
|
| 140 |
+
def test_36_template_reference_raw_not_runnable(self):
|
| 141 |
+
h=ready();r=h.invoke('reference.read',reference_id='gold_002');self.assertFalse(r['runnable']);self.assertIn('not independently',r['evidence'])
|
| 142 |
+
self.rejects_unchanged(h,'template.read',substance_id='gold_002')
|
| 143 |
+
def test_37_cold_full_cycle_actually_heats(self):
|
| 144 |
+
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)
|
| 145 |
+
def test_38_pulse_chunking_stability(self):
|
| 146 |
+
a=ready(method={'pulse_s':[.003,.005]});b=ready(method={'pulse_s':[.003,.005]})
|
| 147 |
+
for h in [a,b]:h.invoke('acquisition.start')
|
| 148 |
+
a.step(60)
|
| 149 |
+
for _ in range(6000):b.step(.01)
|
| 150 |
+
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)
|
| 151 |
+
def test_39_heater_electrical_upper_bound(self):
|
| 152 |
+
h=ArradianceGemstarxtRuntime();self.rejects_unchanged(h,'plant.configure',**dict(WARM_EXAMPLE,heater_max_w=[1500.,600.,400.]))
|
| 153 |
+
self.assertLessEqual(sum(PLANT_EXAMPLE['heater_max_w']),120*20)
|
| 154 |
+
def test_40_bad_step_does_not_advance(self):
|
| 155 |
+
h=ready()
|
| 156 |
+
for dt in [True,-1.,float('nan'),float('inf')]:
|
| 157 |
+
old=h.debug_snapshot()
|
| 158 |
+
with self.assertRaises(ActionRejected):h.step(dt)
|
| 159 |
+
self.assertEqual(old,h.debug_snapshot())
|
| 160 |
+
def test_41_standard_bottles_not_four_filled(self):
|
| 161 |
+
self.assertEqual(sum(n>0 for n in SUPPLY_EXAMPLE['bottle_mol']),2)
|
| 162 |
+
h=ArradianceGemstarxtRuntime();h.invoke('plant.configure',**WARM_EXAMPLE)
|
| 163 |
+
self.rejects_unchanged(h,'gas.install',**dict(SUPPLY_EXAMPLE,bottle_species=['TMA','TMA','EMPTY','EMPTY']))
|
| 164 |
+
def test_42_session_write_routes_to_checked_command(self):
|
| 165 |
+
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)
|
| 166 |
+
with self.assertRaises(ActionRejected):s.write(instance_id=h.instance_id,state_id='truth.ledger',value={},request_id='private')
|
| 167 |
+
def test_43_power_EMO_watchdog_close_vacuum_NC(self):
|
| 168 |
+
for cap,a in [('power.set',{'enabled':False}),('safety.emo',{})]:
|
| 169 |
+
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)
|
| 170 |
+
h=ready(plant={'watchdog_s':.1});h.invoke('acquisition.start');h.step(.2);self.assertFalse(h.pump);self.conserved(h)
|
| 171 |
+
def test_44_chemistry_change_invalidates_old_method(self):
|
| 172 |
+
h=ready(sample=False);self.assertTrue(h.method);h.invoke('kinetics.configure',**dict(KINETICS_EXAMPLE,law_id='zinc_dez_water'));self.assertIsNone(h.method)
|
| 173 |
+
self.rejects_unchanged(h,'method.configure',**METHOD_EXAMPLE)
|
| 174 |
+
if __name__=='__main__':unittest.main()
|
| 175 |
+
|
| 176 |
+
|
| 177 |
+
|
tests/test_asset_biolin_sigma700.py
ADDED
|
@@ -0,0 +1,118 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import unittest,copy,math,json,sys
|
| 2 |
+
from pathlib import Path
|
| 3 |
+
from unittest import mock
|
| 4 |
+
ROOT=Path(__file__).resolve().parents[1];sys.path.insert(0,str(ROOT/'outputs/expansion_batch03/t4_measure/biolin_sigma700'));import example_setup as ex
|
| 5 |
+
rt=ex.rt
|
| 6 |
+
class Tests(unittest.TestCase):
|
| 7 |
+
def h(self,**kw):return ex.build(**kw)
|
| 8 |
+
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)
|
| 9 |
+
def test_02_pure_read(self):
|
| 10 |
+
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__)
|
| 11 |
+
def test_03_target_not_advance(self):
|
| 12 |
+
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)
|
| 13 |
+
def test_04_plate(self):
|
| 14 |
+
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.)
|
| 15 |
+
def test_05_force_buoyancy(self):
|
| 16 |
+
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)
|
| 17 |
+
def test_06_ring(self):
|
| 18 |
+
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)
|
| 19 |
+
def test_07_ring_acceptance(self):
|
| 20 |
+
h=self.h(probe='ring');h.method['accept_ring_proxy']=False
|
| 21 |
+
with self.assertRaisesRegex(rt.ActionRejected,'RING_MODEL'):h.invoke('acquisition.start')
|
| 22 |
+
def test_08_two_instances(self):
|
| 23 |
+
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)
|
| 24 |
+
def test_09_atomic(self):
|
| 25 |
+
h=self.h();before=copy.deepcopy(h.__dict__)
|
| 26 |
+
with self.assertRaises(rt.ActionRejected):h.invoke('method.configure',**dict(rt.METHOD_EXAMPLE,speed_m_s=float('nan')))
|
| 27 |
+
self.assertEqual(before,h.__dict__)
|
| 28 |
+
def test_10_busy(self):
|
| 29 |
+
h=self.h();h.invoke('acquisition.start');before=copy.deepcopy(h.__dict__)
|
| 30 |
+
with self.assertRaisesRegex(rt.ActionRejected,'BUSY'):h.invoke('door.set',angle_rad=2.35)
|
| 31 |
+
self.assertEqual(before,h.__dict__)
|
| 32 |
+
def test_11_cancel(self):
|
| 33 |
+
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')
|
| 34 |
+
def test_12_heat(self):
|
| 35 |
+
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)
|
| 36 |
+
def test_13_dose(self):
|
| 37 |
+
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)
|
| 38 |
+
def test_14_finite_stock(self):
|
| 39 |
+
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)
|
| 40 |
+
with self.assertRaisesRegex(rt.ActionRejected,'FINITE_STOCK'):h.invoke('dose.start',volume_m3=1e-6,flow_m3_s=1e-7)
|
| 41 |
+
def test_15_truth(self):
|
| 42 |
+
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')
|
| 43 |
+
def test_16_principals(self):
|
| 44 |
+
h=self.h()
|
| 45 |
+
with self.assertRaises(rt.ActionRejected):h.session('intruder')
|
| 46 |
+
with self.assertRaises(rt.ActionRejected):h.register_principal('agent','evaluator')
|
| 47 |
+
def test_17_dedupe(self):
|
| 48 |
+
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')
|
| 49 |
+
def test_18_ownership_query(self):
|
| 50 |
+
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'])
|
| 51 |
+
with self.assertRaises(rt.ActionRejected):b.cancel(r['operation_id'],'cancel')
|
| 52 |
+
h.step(.5);self.assertEqual(a.poll(r['operation_id'])['status'],'running');self.assertEqual(a.cancel(r['operation_id'],'cancel')['status'],'succeeded')
|
| 53 |
+
def test_19_calibration_independent(self):
|
| 54 |
+
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)
|
| 55 |
+
def test_20_wrong_calibration(self):
|
| 56 |
+
h=self.h(plant={'force_gain':1.1});h.invoke('acquisition.start');h.step(30);self.assertGreater(abs(h.peak-.022454),.001)
|
| 57 |
+
def test_21_cmc_real(self):
|
| 58 |
+
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(.025<out['cmc_kg_m3']<.09)
|
| 59 |
+
def test_22_no_false_cmc(self):
|
| 60 |
+
cs=[.001,.002,.004,.008,.016,.032,.064,.128]
|
| 61 |
+
with self.assertRaisesRegex(rt.ActionRejected,'NO_BREAKPOINT'):rt.fit_cmc(cs,[.05-.002*math.log(x) for x in cs])
|
| 62 |
+
def test_23_no_extrapolation(self):
|
| 63 |
+
with self.assertRaisesRegex(rt.ActionRejected,'TEMPERATURE_RANGE'):rt.tension('cas_64_17_5',400,0)
|
| 64 |
+
with self.assertRaisesRegex(rt.ActionRejected,'CONCENTRATION_RANGE'):rt.tension('apg_fig1_2',298.15,2.)
|
| 65 |
+
with self.assertRaisesRegex(rt.ActionRejected,'UNKNOWN_CONDITIONS'):rt.tension('sds_silica_hexane',293.15,.01)
|
| 66 |
+
def test_24_dt_partition(self):
|
| 67 |
+
a=self.h();b=self.h();a.invoke('acquisition.start');b.invoke('acquisition.start');a.step(4)
|
| 68 |
+
for _ in range(40):b.step(.1)
|
| 69 |
+
self.assertEqual(a.read(),b.read());self.assertEqual(a.rows,b.rows)
|
| 70 |
+
def test_25_removal_mass(self):
|
| 71 |
+
h=self.h();h.invoke('thermal.set_temperature',temperature_k=310);h.step(50);h.invoke('door.set',angle_rad=2.35);ex.call(h,'sample.remove');self.assertAlmostEqual(h._ledger()['mass_error_kg'],0.,delta=1e-12);self.assertAlmostEqual(h._ledger()['heat_error_j'],0.,delta=1e-7)
|
| 72 |
+
def test_26_bool_unknown(self):
|
| 73 |
+
h=self.h()
|
| 74 |
+
for args in [{'angle_rad':True},{'angle_rad':0.,'hidden':1}]:
|
| 75 |
+
with self.assertRaises(rt.ActionRejected):h.invoke('door.set',**args)
|
| 76 |
+
def test_27_all_unsupported(self):
|
| 77 |
+
h=self.h()
|
| 78 |
+
for k in rt.UNSUPPORTED:
|
| 79 |
+
with self.assertRaisesRegex(rt.ActionRejected,'UNSUPPORTED'):h.invoke(k)
|
| 80 |
+
def test_28_result_provenance(self):
|
| 81 |
+
h=self.h();h.invoke('acquisition.start');h.step(30);source=h._result()['template_source'];h.invoke('door.set',angle_rad=2.35);h.invoke('sample.remove');h.invoke('sample.load',**dict(rt.SAMPLE_EXAMPLE,substance_id='cas_67_56_1'));self.assertEqual(source,h._result()['template_source'])
|
| 82 |
+
def test_29_overimmersion(self):
|
| 83 |
+
h=self.h();h.invoke('door.set',angle_rad=2.35);h.invoke('sample.remove');h.invoke('sample.load',**dict(rt.SAMPLE_EXAMPLE,volume_m3=5e-5));h.invoke('door.set',angle_rad=0.);before=copy.deepcopy(h.__dict__)
|
| 84 |
+
with self.assertRaisesRegex(rt.ActionRejected,'OVERIMMERSION'):h.invoke('stage.move',position_m=rt.STAGE_MAX_M)
|
| 85 |
+
self.assertEqual(before,h.__dict__)
|
| 86 |
+
def test_30_direct_stop_owner(self):
|
| 87 |
+
h=self.h();h.register_principal('b');a=h.session();b=h.session('b');a.invoke(instance_id=h.instance_id,capability_id='stage.move',arguments={'position_m':.05},request_id='start');r=b.invoke(instance_id=h.instance_id,capability_id='acquisition.stop',arguments={},request_id='stop');self.assertEqual(r['error']['code'],'ACCESS_DENIED');self.assertEqual(h.phase,'running')
|
| 88 |
+
def test_31_dose_shortage_rejected_atomically(self):
|
| 89 |
+
h=self.h();h.invoke('stock.load',volume_m3=1e-6,concentration_kg_m3=0.);before=copy.deepcopy(h.__dict__)
|
| 90 |
+
with self.assertRaisesRegex(rt.ActionRejected,'FINITE_STOCK_OR_CAPACITY'):h.invoke('dose.start',volume_m3=1.0000005e-6,flow_m3_s=1e-7)
|
| 91 |
+
self.assertEqual(before,h.__dict__);self.assertAlmostEqual(h._ledger()['mass_error_kg'],0.,delta=1e-12)
|
| 92 |
+
def test_32_stock_exhaustion_retains_partial_transfer(self):
|
| 93 |
+
h=self.h(sid='apg_fig1_2',plant={'ambient_k':298.15},temp=298.15);h.invoke('stock.load',volume_m3=1e-6,concentration_kg_m3=1.);s=h.session();op=s.invoke(instance_id=h.instance_id,capability_id='dose.start',arguments={'volume_m3':1e-6,'flow_m3_s':1e-7},request_id='dose')['operation_id']
|
| 94 |
+
# Host fault injection: account for lost stock in waste, preserving all ledgers.
|
| 95 |
+
lost=5e-7;h.stock-=lost;h.waste+=lost*h.plant['liquid_density_kg_m3'];h.solute_waste+=lost*h.stock_c;h.step(20.);self.assertEqual(h.phase,'failed');self.assertEqual(h.error,'STOCK_EXHAUSTED');self.assertAlmostEqual(h.volume,30.5e-6,delta=1e-14);self.assertEqual(h.stock,0.)
|
| 96 |
+
frozen=s.poll(op);volume=h.volume;h.step(20.);self.assertEqual(h.volume,volume);self.assertEqual(frozen,s.poll(op))
|
| 97 |
+
for key in ['mass_error_kg','solute_error_kg','heat_error_j']:self.assertAlmostEqual(h._ledger()[key],0.,delta=1e-7 if key=='heat_error_j' else 1e-12)
|
| 98 |
+
def test_33_stage_scene_envelope_and_reachability(self):
|
| 99 |
+
h=self.h();before=copy.deepcopy(h.__dict__)
|
| 100 |
+
for position in [.110,.125]:
|
| 101 |
+
with self.assertRaisesRegex(rt.ActionRejected,'INVALID_ARGUMENT'):h.invoke('stage.move',position_m=position)
|
| 102 |
+
self.assertEqual(before,h.__dict__)
|
| 103 |
+
h.invoke('stage.move',position_m=rt.STAGE_MAX_M);h.step(14.);self.assertEqual(h.q,rt.STAGE_MAX_M);self.assertEqual(h.phase,'succeeded');h.invoke('stage.move',position_m=0.);h.step(14.)
|
| 104 |
+
h.invoke('door.set',angle_rad=2.35);h.invoke('sample.remove');h.invoke('sample.load',**dict(rt.SAMPLE_EXAMPLE,volume_m3=1e-6));h.invoke('door.set',angle_rad=0.);before=copy.deepcopy(h.__dict__)
|
| 105 |
+
with self.assertRaisesRegex(rt.ActionRejected,'STAGE_RANGE'):h.invoke('acquisition.start')
|
| 106 |
+
self.assertEqual(before,h.__dict__)
|
| 107 |
+
metadata=rt.export_biolin_sigma700_contract_metadata();self.assertEqual(metadata['capabilities']['stage.move']['input_schema']['properties']['position_m']['maximum'],.109)
|
| 108 |
+
for slot in ['stage.position_m','stage.target_m']:self.assertEqual(metadata['state_slots'][slot]['value_schema']['maximum'],.109)
|
| 109 |
+
def test_34_metadata_covers_actual_state_changes(self):
|
| 110 |
+
metadata=rt.export_biolin_sigma700_contract_metadata();original=rt.BiolinSigma700Runtime.invoke;observed=set()
|
| 111 |
+
def audited_invoke(h,cap,**arguments):
|
| 112 |
+
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'}
|
| 113 |
+
self.assertFalse(changed-declared,(cap,changed-declared));observed.add(cap);return result
|
| 114 |
+
with mock.patch.object(rt.BiolinSigma700Runtime,'invoke',audited_invoke):
|
| 115 |
+
h=self.h();h.invoke('balance.calibrate',reference_forces_n=[0.,.1],observed_raw_forces_n=[0.,.1]);h.invoke('balance.tare');h.invoke('stage.move',position_m=.005);h.invoke('sim.step',dt_s=1.);h.invoke('stage.move',position_m=0.);h.invoke('sim.step',dt_s=1.);h.invoke('stirrer.set_speed',speed_rad_s=20.);h.invoke('thermal.set_temperature',temperature_k=295.15);h.invoke('acquisition.start');h.invoke('sim.step',dt_s=30.);h.invoke('door.set',angle_rad=2.35);h.invoke('probe.select',probe='ring');h.invoke('sample.remove');h.invoke('power.set',enabled=False);h.invoke('service.set',distance_m=.1)
|
| 116 |
+
d=self.h(sid='apg_fig1_2',plant={'ambient_k':298.15},temp=298.15);d.invoke('stock.load',volume_m3=2e-5,concentration_kg_m3=1.);d.invoke('dose.start',volume_m3=1e-6,flow_m3_s=1e-7);d.invoke('sim.step',dt_s=3.);d.invoke('acquisition.stop');d.invoke('door.set',angle_rad=2.35);d.invoke('sample.remove')
|
| 117 |
+
self.assertTrue(set(rt.IMMEDIATE_EFFECTS)<=observed)
|
| 118 |
+
if __name__=='__main__':unittest.main()
|
tests/test_asset_biolin_thetaflex.py
ADDED
|
@@ -0,0 +1,139 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import unittest,sys,math,json,copy,base64,io
|
| 2 |
+
from pathlib import Path
|
| 3 |
+
from unittest import mock
|
| 4 |
+
import numpy as np,cv2
|
| 5 |
+
from PIL import Image
|
| 6 |
+
O=Path(__file__).resolve().parents[1]/'outputs/expansion_batch03/t4_measure/biolin_thetaflex';sys.path.insert(0,str(O));import example_setup as ex
|
| 7 |
+
rt=ex.rt
|
| 8 |
+
class TestThetaFlex(unittest.TestCase):
|
| 9 |
+
def test_library_real_counts(self):
|
| 10 |
+
l=rt.LIB;self.assertEqual(len(l['substances']),168);self.assertEqual(len(l['experimental_images']),127);self.assertEqual(len(l['excluded_rows']),8);self.assertFalse(l['coverage']['distinct_chemical_species_ge50']);self.assertTrue(all(v['source'] and v['evidence'] for v in l['substances'].values()))
|
| 11 |
+
def test_replicate_units(self):
|
| 12 |
+
a=rt.LIB['substances']['al_ctab_a_row7'];self.assertAlmostEqual(math.degrees(a['values']['contact_angle_rad']),40.18);self.assertEqual(a['conditions']['concentration_mol_m3'],11.2);self.assertEqual(a['values']['advancing_rad'],None)
|
| 13 |
+
def test_young_laplace_zero_gravity(self):
|
| 14 |
+
v=2e-10;t=1.2;x,z,r=rt.profile(v,t,0.,.0728);expected=rt.cap_radius(v,t);self.assertAlmostEqual(r/expected,1,places=5);self.assertAlmostEqual(z[0]/(expected*(1-math.cos(t))),1,places=5)
|
| 15 |
+
def test_young_laplace_volume(self):
|
| 16 |
+
v=3e-9;x,z,r=rt.profile(v,1.8,998.2,.04);measured=-math.pi*np.trapz(x*x,z);self.assertLess(abs(measured/v-1),3e-5)
|
| 17 |
+
def test_gravity_flattens(self):
|
| 18 |
+
v=3e-9;t=1.3;x,z,r=rt.profile(v,t,0.,.04);xx,zz,rr=rt.profile(v,t,998.2,.04);self.assertLess(zz[0],z[0]);self.assertGreater(xx[-1],x[-1])
|
| 19 |
+
def test_independent_circle_pixels(self):
|
| 20 |
+
for deg in [30,60,90,110,140]:
|
| 21 |
+
theta=math.radians(deg);a=np.full((1264,1984),230,np.uint8);b=1000;R=500;cy=round(b+R*math.cos(theta));cv2.circle(a,(992,cy),R,20,-1);buf=io.BytesIO();Image.fromarray(a).save(buf,format='PNG');q=rt.image_fit(base64.b64encode(buf.getvalue()).decode(),b,2e-6,'circle');expected=math.acos((cy-b)/R);self.assertLess(abs(q['mean_rad']-expected),math.radians(.25))
|
| 22 |
+
def test_static_from_pixels(self):
|
| 23 |
+
h,r=ex.static_example();self.assertEqual(len(r['rows']),5);self.assertLess(abs(r['rows'][-1]['mean_rad']-h.theta),math.radians(1.5));self.assertNotEqual(r['rows'][-1]['mean_rad'],h.theta);self.assertLess(abs(r['rows'][-1]['observed_volume_m3']/h.volume-1),.02)
|
| 24 |
+
def test_pixel_scale_independent(self):
|
| 25 |
+
h,r=ex.static_example();c=ex.call(h,'image.capture');a=rt.image_fit(c['image_png_base64'],c['baseline_px'],c['pixel_pitch_m'],'circle');b=rt.image_fit(c['image_png_base64'],c['baseline_px'],c['pixel_pitch_m']*2,'circle');self.assertAlmostEqual(a['mean_rad'],b['mean_rad']);self.assertAlmostEqual(b['volume_m3']/a['volume_m3'],8.)
|
| 26 |
+
def test_fov_invalidates_calibration(self):
|
| 27 |
+
h=ex.setup();m=copy.deepcopy(h.method);m['field_width_m']=.005;h.invoke('method.configure',**m);self.assertIsNone(h.pitch)
|
| 28 |
+
def test_fov_crop_rejected(self):
|
| 29 |
+
with self.assertRaisesRegex(rt.ActionRejected,'FIELD_OF_VIEW'):rt.render_drop(1e-8,1.5,1000.,.072,.00144,.006,.8)
|
| 30 |
+
def test_invalid_image(self):
|
| 31 |
+
with self.assertRaisesRegex(rt.ActionRejected,'INVALID_IMAGE'):rt.image_fit('notpng',1000,1e-6)
|
| 32 |
+
def test_dynamic_pin_and_hysteresis(self):
|
| 33 |
+
h,a,b,d=ex.dynamic_example();self.assertGreater(d['hysteresis_rad'],.8);self.assertLess(abs(d['advancing_rad']-h.plant['advancing_rad']),.03);self.assertLess(abs(d['receding_rad']-h.plant['receding_rad']),.06);self.assertAlmostEqual(h._ledger()['volume_error_m3'],0,places=18)
|
| 34 |
+
def test_dynamic_bond_limit(self):
|
| 35 |
+
h=ex.setup();m=copy.deepcopy(h.method);m['mode']='dynamic';h.invoke('method.configure',**m);h.invoke('dispenser.move',position_m=.024);ex.finish(h)
|
| 36 |
+
with self.assertRaisesRegex(rt.ActionRejected,'DYNAMIC_BOND_LIMIT'):h.invoke('liquid.transfer',volume_m3=1e-8)
|
| 37 |
+
def test_no_automatic_hysteresis_from_static(self):
|
| 38 |
+
p=copy.deepcopy(rt.PLANT_EXAMPLE);p.update(advancing_rad=None,receding_rad=None,accept_dynamic_proxy=False);h=ex.setup(plant=p);m=copy.deepcopy(h.method);m['mode']='dynamic'
|
| 39 |
+
with self.assertRaisesRegex(rt.ActionRejected,'DYNAMIC_INPUTS_REQUIRED'):h.invoke('method.configure',**m)
|
| 40 |
+
def test_finite_stock(self):
|
| 41 |
+
h=ex.setup();h.invoke('dispenser.move',position_m=.02);ex.finish(h);h.stock=5e-11;h.loaded=h.stock
|
| 42 |
+
before=h.read()
|
| 43 |
+
with self.assertRaisesRegex(rt.ActionRejected,'FINITE_INVENTORY'):h.invoke('liquid.transfer',volume_m3=1e-10)
|
| 44 |
+
self.assertEqual(before,h.read())
|
| 45 |
+
def test_partial_transfer_cancel_conserves(self):
|
| 46 |
+
h=ex.setup();h.invoke('dispenser.move',position_m=.02);ex.finish(h);h.invoke('liquid.transfer',volume_m3=2e-10);h.step(.31);self.assertGreater(h.volume,0);v=h.volume;h.invoke('acquisition.stop');h.step(2.);self.assertEqual(v,h.volume);self.assertAlmostEqual(h._ledger()['mass_error_kg'],0,places=16)
|
| 47 |
+
def test_clean_and_unload_conserves(self):
|
| 48 |
+
h,r=ex.static_example();h.invoke('drop.clean');h.invoke('stock.unload');h.invoke('sample.remove');l=h._ledger();self.assertAlmostEqual(l['waste_m3'],l['loaded_m3']);self.assertAlmostEqual(l['volume_error_m3'],0,places=18)
|
| 49 |
+
def test_motion_rate_and_cancel(self):
|
| 50 |
+
h=rt.BiolinThetaFlexRuntime();h.invoke('plant.configure',**rt.PLANT_EXAMPLE);h.invoke('power.set',enabled=True);h.invoke('stage.move',x_m=.04,y_m=.02,z_m=.025);h.step(1.);self.assertAlmostEqual(h.q[0],.004);h.invoke('acquisition.stop');v=h.q[:];h.step(1.);self.assertEqual(v,h.q)
|
| 51 |
+
def test_partition_independence(self):
|
| 52 |
+
a=ex.setup();b=ex.setup();a.invoke('stage.move',x_m=.07,y_m=.03,z_m=.04);b.invoke('stage.move',x_m=.07,y_m=.03,z_m=.04);a.step(.37)
|
| 53 |
+
for _ in range(37):b.step(.01)
|
| 54 |
+
self.assertEqual(a.read(),b.read())
|
| 55 |
+
def test_schema_atomic_bool_nan(self):
|
| 56 |
+
h=ex.setup();before=h.read()
|
| 57 |
+
for a in [{'x_m':True,'y_m':0.,'z_m':0.},{'x_m':float('nan'),'y_m':0.,'z_m':0.},{'x_m':0.,'y_m':0.,'z_m':0.,'extra':0}]:
|
| 58 |
+
with self.assertRaises(rt.ActionRejected):h.invoke('stage.move',**a)
|
| 59 |
+
self.assertEqual(before,h.read())
|
| 60 |
+
def test_power_service_interlock(self):
|
| 61 |
+
h=ex.setup()
|
| 62 |
+
with self.assertRaisesRegex(rt.ActionRejected,'POWER_INTERLOCK'):h.invoke('service.set',distance_m=.09)
|
| 63 |
+
h.invoke('power.set',enabled=False);h.invoke('service.set',distance_m=.09)
|
| 64 |
+
with self.assertRaisesRegex(rt.ActionRejected,'NOT_READY'):h.invoke('power.set',enabled=True)
|
| 65 |
+
def test_needle_collision_interlock(self):
|
| 66 |
+
h=ex.setup()
|
| 67 |
+
with self.assertRaisesRegex(rt.ActionRejected,'NEEDLE_COLLISION'):h.invoke('dispenser.move',position_m=.035)
|
| 68 |
+
h.invoke('dispenser.move',position_m=.020);ex.finish(h)
|
| 69 |
+
with self.assertRaisesRegex(rt.ActionRejected,'NEEDLE_INTERLOCK'):h.invoke('stage.move',x_m=.0,y_m=.0,z_m=.0)
|
| 70 |
+
def test_unknown_conditions(self):
|
| 71 |
+
h=rt.BiolinThetaFlexRuntime()
|
| 72 |
+
with self.assertRaisesRegex(rt.ActionRejected,'UNKNOWN_CONDITIONS'):h.invoke('sample.load',reference_id=rt.SAMPLE_EXAMPLE['reference_id'],accept_unknown_conditions=False)
|
| 73 |
+
def test_complete_wetting_not_cap(self):
|
| 74 |
+
sid=next(k for k,v in rt.LIB['substances'].items() if v['values']['contact_angle_rad']==0)
|
| 75 |
+
with self.assertRaisesRegex(rt.ActionRejected,'COMPLETE_WETTING_UNSUPPORTED'):rt.BiolinThetaFlexRuntime().invoke('sample.load',reference_id=sid,accept_unknown_conditions=True)
|
| 76 |
+
def test_owrk_independent_observations(self):
|
| 77 |
+
probes=[(.0218,.051),(.0508,0),(.029,.019)];gd=.021;gp=.008;obs=[dict(angle_rad=math.acos(2*(math.sqrt(gd*a)+math.sqrt(gp*b))/(a+b)-1),liquid_dispersive_j_m2=a,liquid_polar_j_m2=b) for a,b in probes];o=rt.surface_energy(obs);self.assertAlmostEqual(o['dispersive_j_m2'],gd);self.assertAlmostEqual(o['polar_j_m2'],gp)
|
| 78 |
+
def test_degenerate_owrk(self):
|
| 79 |
+
with self.assertRaisesRegex(rt.ActionRejected,'DEGENERATE_PROBES'):rt.surface_energy([dict(angle_rad=1.,liquid_dispersive_j_m2=.03,liquid_polar_j_m2=0.)]*2)
|
| 80 |
+
def test_session_truth_and_ownership(self):
|
| 81 |
+
h=ex.setup();a=h.session('agent');h.register_principal('other');b=h.session('other');d=a.describe(instance_id=h.instance_id);self.assertNotIn('truth.drop_m3',d['state_slots']);self.assertNotIn('plant.configure',d['capabilities']);r=a.invoke(instance_id=h.instance_id,capability_id='stage.move',arguments=dict(x_m=.06,y_m=.02,z_m=.025),request_id='1');op=r['operation_id'];b.invoke(instance_id=h.instance_id,capability_id='acquisition.result',arguments={},request_id='2')
|
| 82 |
+
with self.assertRaisesRegex(rt.ActionRejected,'ACCESS_DENIED'):b.poll(op)
|
| 83 |
+
self.assertEqual(b.invoke(instance_id=h.instance_id,capability_id='acquisition.stop',arguments={},request_id='3')['error']['code'],'ACCESS_DENIED');self.assertEqual(a.cancel(op,'4')['status'],'succeeded')
|
| 84 |
+
def test_idempotence_conflict(self):
|
| 85 |
+
h=ex.setup();a=h.session('agent');kw=dict(instance_id=h.instance_id,capability_id='focus.set',arguments={'position_m':.006},request_id='x');one=a.invoke(**kw);self.assertEqual(one,a.invoke(**kw));kw['arguments']={'position_m':.01};self.assertEqual(a.invoke(**kw)['error']['code'],'REQUEST_CONFLICT')
|
| 86 |
+
def test_pure_read_and_time_stamp(self):
|
| 87 |
+
h,r=ex.static_example();state=copy.deepcopy(h.__dict__);h.read();h.invoke('acquisition.result');h.invoke('image.capture');self.assertEqual(state,h.__dict__);stamp=h.last_fit_time;h.step(1.);a=h.session('agent').read(instance_id=h.instance_id,state_ids=['angle.indicated_rad']);self.assertEqual(a['observations']['angle.indicated_rad']['sample_time_s'],stamp)
|
| 88 |
+
def test_unsupported_explicit(self):
|
| 89 |
+
h=ex.setup()
|
| 90 |
+
for k in rt.UNSUPPORTED:
|
| 91 |
+
with self.assertRaisesRegex(rt.ActionRejected,'UNSUPPORTED'):h.invoke(k)
|
| 92 |
+
def test_tiny_capture_has_finite_terminal_state(self):
|
| 93 |
+
for volume,expected in [(1e-12,'succeeded'),(1e-14,'failed')]:
|
| 94 |
+
h=ex.setup();ex.put_drop(h,volume);h.invoke('acquisition.start');h.step(1.2);self.assertEqual(h.phase,expected)
|
| 95 |
+
if expected=='succeeded':self.assertEqual(len(h.rows),h.method['frames'])
|
| 96 |
+
else:self.assertEqual(h.error,'BASELINE_OR_EDGE')
|
| 97 |
+
def test_terminal_result_survives_cleanup_and_reconfiguration(self):
|
| 98 |
+
h=ex.setup();ex.put_drop(h);s=h.session();op=s.invoke(instance_id=h.instance_id,capability_id='acquisition.start',arguments={},request_id='capture')['operation_id'];h.step(1.2);snapshot=h.invoke('acquisition.result');self.assertEqual(snapshot['phase'],'succeeded');frozen=s.poll(op)
|
| 99 |
+
h.invoke('drop.clean');h.invoke('stock.unload');h.invoke('sample.remove');h.invoke('method.configure',**dict(h.method,field_width_m=.005));self.assertEqual(snapshot,h.invoke('acquisition.result'));self.assertEqual(frozen,s.poll(op))
|
| 100 |
+
snapshot['rows'][0]['mean_rad']=-1;self.assertNotEqual(snapshot,h.invoke('acquisition.result'));h.invoke('stage.move',x_m=0.,y_m=0.,z_m=0.);h.step(11.);self.assertEqual(frozen,s.poll(op))
|
| 101 |
+
def test_exact_finite_inventory_rejects_atomically(self):
|
| 102 |
+
h=ex.setup();h.invoke('stock.unload');h.invoke('stock.load',reference_id=h.sid,volume_m3=1e-10);ex.put_drop(h,9e-11);h.invoke('method.configure',**dict(h.method,mode='dynamic',flow_m3_s=1e-8));h.invoke('dispenser.move',position_m=.024);ex.finish(h)
|
| 103 |
+
for volume in [h.stock+5e-19,-(h.volume+5e-19)]:
|
| 104 |
+
before=copy.deepcopy(h.__dict__)
|
| 105 |
+
with self.assertRaisesRegex(rt.ActionRejected,'FINITE_INVENTORY'):h.invoke('liquid.transfer',volume_m3=volume)
|
| 106 |
+
self.assertEqual(before,h.__dict__)
|
| 107 |
+
self.assertGreaterEqual(h.stock,0.);self.assertLessEqual(h.read()['plunger.position_m'],.04)
|
| 108 |
+
def test_stock_exhaustion_is_terminal_and_conserves(self):
|
| 109 |
+
h=ex.setup();h.invoke('stock.unload');h.invoke('stock.load',reference_id=h.sid,volume_m3=1e-10);h.invoke('dispenser.move',position_m=.02);ex.finish(h);s=h.session();op=s.invoke(instance_id=h.instance_id,capability_id='liquid.transfer',arguments={'volume_m3':9e-11},request_id='transfer')['operation_id'];h.step(.1)
|
| 110 |
+
# Explicit host fault injection; lost stock enters waste, preserving loaded material.
|
| 111 |
+
lost=8e-11;h.stock-=lost;h.waste+=lost;h.step(2.);self.assertEqual(h.phase,'failed');self.assertEqual(h.error,'INVENTORY_EXHAUSTED');self.assertEqual(h.stock,0.);self.assertAlmostEqual(h.volume,2e-11,delta=1e-24);self.assertLessEqual(h.read()['plunger.position_m'],.04)
|
| 112 |
+
self.assertAlmostEqual(h._ledger()['volume_error_m3'],0.,delta=1e-22);self.assertAlmostEqual(h._ledger()['mass_error_kg'],0.,delta=1e-19);record=s.poll(op);volume=h.volume;h.step(3.);self.assertEqual(record,s.poll(op));self.assertEqual(volume,h.volume)
|
| 113 |
+
def test_stage_needle_clearance_envelope(self):
|
| 114 |
+
h=ex.setup();before=copy.deepcopy(h.__dict__)
|
| 115 |
+
for cap,args,error in [('stage.move',dict(x_m=.04,y_m=.02,z_m=.0491),'INVALID_ARGUMENT'),('dispenser.move',dict(position_m=.02405),'NEEDLE_COLLISION')]:
|
| 116 |
+
with self.assertRaisesRegex(rt.ActionRejected,error):h.invoke(cap,**args)
|
| 117 |
+
self.assertEqual(before,h.__dict__)
|
| 118 |
+
h.invoke('dispenser.move',position_m=.007);ex.finish(h);before=copy.deepcopy(h.__dict__)
|
| 119 |
+
with self.assertRaisesRegex(rt.ActionRejected,'NEEDLE_COLLISION'):h.invoke('stage.move',x_m=.04,y_m=.02,z_m=.043)
|
| 120 |
+
self.assertEqual(before,h.__dict__);h.invoke('stage.move',x_m=.04,y_m=.02,z_m=.042)
|
| 121 |
+
while h.phase=='running':h.step(.01);self.assertLessEqual(h.q[2]+h.dispenser,rt.STAGE_Z_MAX_M+1e-12)
|
| 122 |
+
self.assertEqual(h.q[2],.042);h.invoke('dispenser.move',position_m=0.);ex.finish(h);h.invoke('stage.move',x_m=.04,y_m=.02,z_m=.049);ex.finish(h);self.assertEqual(h.q[2],.049)
|
| 123 |
+
metadata=rt.export_biolin_thetaflex_contract_metadata();self.assertEqual(metadata['capabilities']['stage.move']['input_schema']['properties']['z_m']['maximum'],.049)
|
| 124 |
+
for slot in ['stage.z_m','stage.target_z_m']:self.assertEqual(metadata['state_slots'][slot]['value_schema']['maximum'],.049)
|
| 125 |
+
def test_instances_and_evaluator_transfer_boundaries(self):
|
| 126 |
+
a=ex.setup('a');b=ex.setup('b');before=copy.deepcopy(b.__dict__);ex.put_drop(a);self.assertEqual(before,b.__dict__);s=a.session();state=copy.deepcopy(a.__dict__);s.describe(instance_id=a.instance_id);s.read(instance_id=a.instance_id);self.assertEqual(state,a.__dict__)
|
| 127 |
+
for cap,args in [('stock.unload',{}),('drop.clean',{}),('sample.remove',{}),('ledger.read',{}),('sim.step',{'dt_s':1.})]:
|
| 128 |
+
r=s.invoke(instance_id=a.instance_id,capability_id=cap,arguments=args,request_id=cap);self.assertEqual(r['error']['code'],'ACCESS_DENIED');self.assertEqual(state,a.__dict__)
|
| 129 |
+
with self.assertRaisesRegex(rt.ActionRejected,'ACCESS_DENIED'):s.read(instance_id=a.instance_id,state_ids=['truth.drop_m3'])
|
| 130 |
+
def test_metadata_covers_actual_state_changes(self):
|
| 131 |
+
metadata=rt.export_biolin_thetaflex_contract_metadata();original=rt.BiolinThetaFlexRuntime.invoke;original_step=rt.BiolinThetaFlexRuntime.step;observed=set();stepped=set()
|
| 132 |
+
def invoke(h,cap,**arguments):
|
| 133 |
+
before=h.read();result=original(h,cap,**arguments);after=h.read();changed={key for key in before if before[key]!=after[key]};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
|
| 134 |
+
def step(h,dt_s):
|
| 135 |
+
cap={'move':'stage.move','dispenser':'dispenser.move','advance':'liquid.transfer','recede':'liquid.transfer','capture':'acquisition.start'}.get(h.stage) if h.phase=='running' else None;before=h.read();result=original_step(h,dt_s);after=h.read();changed={key for key in before if before[key]!=after[key]};declared={'clock.time_s'}|set(rt.STEP_EFFECTS.get(cap,[]));self.assertFalse(changed-declared,(cap,changed-declared));stepped.add(cap);return result
|
| 136 |
+
with mock.patch.object(rt.BiolinThetaFlexRuntime,'invoke',invoke),mock.patch.object(rt.BiolinThetaFlexRuntime,'step',step):
|
| 137 |
+
h,r=ex.static_example();h.invoke('power.set',enabled=False);h.invoke('power.set',enabled=True);h.invoke('method.configure',**dict(h.method,field_width_m=.005));h.invoke('drop.clean');h.invoke('stock.unload');h.invoke('sample.remove');h.invoke('stage.move',x_m=0.,y_m=0.,z_m=0.);h.invoke('sim.step',dt_s=.1);h.invoke('acquisition.stop');h.invoke('power.set',enabled=False);h.invoke('service.set',distance_m=.09);d,a,b,c=ex.dynamic_example();d.invoke('drop.clean')
|
| 138 |
+
self.assertTrue(set(rt.IMMEDIATE_EFFECTS)<=observed);self.assertTrue(set(rt.STEP_EFFECTS)<=stepped)
|
| 139 |
+
if __name__=='__main__':unittest.main()
|
tests/test_asset_biotage_selekt.py
ADDED
|
@@ -0,0 +1,88 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import copy,math,sys,unittest
|
| 2 |
+
from pathlib import Path
|
| 3 |
+
sys.path.insert(0,str(Path(__file__).resolve().parents[1]/'scripts'))
|
| 4 |
+
from asset_runtime.biotage_selekt import *
|
| 5 |
+
def configured(plant=None,column=None,sample=None,method=None,rack=None,second=False):
|
| 6 |
+
h=BiotageSelektRuntime();h.invoke('plant.configure',**dict(EXAMPLE,**(plant or {})));h.invoke('tray.set_extension',extension_m=.12);h.invoke('rack.configure',**dict(dict(positions=144,vessel_volume_m3=9e-6),**(rack or {})));h.invoke('tray.set_extension',extension_m=0.)
|
| 7 |
+
for i in range(2 if second else 1):
|
| 8 |
+
h.invoke('column.configure',**dict(COLUMN_EXAMPLE,**dict(column or {},channel=i)));h.invoke('sample.configure',**dict(SAMPLE_EXAMPLE,**dict(sample or {},channel=i)))
|
| 9 |
+
for i in range(2 if second else 1):h.invoke('method.configure',**dict(METHOD_EXAMPLE,**dict(method or {},channel=i)))
|
| 10 |
+
h.invoke('power.set',enabled=True);return h
|
| 11 |
+
def finish(h,dt=1.):
|
| 12 |
+
h.invoke('acquisition.start')
|
| 13 |
+
for _ in range(10000):
|
| 14 |
+
h.step(dt)
|
| 15 |
+
if h.phase!='running':return h
|
| 16 |
+
raise AssertionError((h.phase,h.stage))
|
| 17 |
+
class TestSelekt(unittest.TestCase):
|
| 18 |
+
def ledger(self,h):
|
| 19 |
+
np.testing.assert_allclose(h.initialmol,h.colmol.sum(axis=(0,2))+h.detmol+h.fractionmol.sum(axis=0)+h.wastemol,rtol=0,atol=1e-15)
|
| 20 |
+
np.testing.assert_allclose(h.initialfluid,h.reservoir+h.mixer+h.colfluid.sum(axis=(0,2))+h.detfluid+h.fractionfluid.sum(axis=0)+h.wastefluid,rtol=0,atol=1e-14)
|
| 21 |
+
for a in [h.reservoir,h.mixer,h.colfluid,h.detfluid,h.colmol,h.detmol,h.fractionmol,h.wastemol]:self.assertGreaterEqual(float(a.min()),-1e-20)
|
| 22 |
+
def test_01_real60_spectral_interpolation(self):
|
| 23 |
+
h=BiotageSelektRuntime();self.assertEqual(len(h.templates),60)
|
| 24 |
+
for sid,r in h.templates.items():
|
| 25 |
+
x=r['values']['wavelength_m'];y=r['values']['molar_decadic_absorptivity_m2_mol'];j=len(x)//2;v=h.invoke('reference.lookup',substance_id=sid,wavelength_m=x[j]);self.assertEqual(v['epsilon_m2_mol'],y[j])
|
| 26 |
+
def test_02_full_cycle(self):
|
| 27 |
+
h=finish(configured());self.assertEqual(h.phase,'succeeded');self.assertEqual(h.pressure[0],0.);self.assertGreater(h.fractionmol.sum(),0.);self.assertGreater(h.wastemol.sum(),0.);self.assertAlmostEqual(h.gradient_s[0],240.,delta=1e-8);self.assertGreater(h.colmol.sum()+h.detmol.sum(),0.);self.ledger(h)
|
| 28 |
+
def test_03_increments_rejected_atomic(self):
|
| 29 |
+
h=configured();old=h.debug_snapshot()
|
| 30 |
+
with self.assertRaises(ActionRejected):h.invoke('method.configure',**dict(METHOD_EXAMPLE,flow_m3_s=1.5e-6/60))
|
| 31 |
+
self.assertEqual(old,h.debug_snapshot())
|
| 32 |
+
for cap,arguments in [('channel.select',{'channel':v}) for v in [True,.5,-1,2]]+[('rack.configure',dict(positions=v,vessel_volume_m3=9e-6)) for v in [True,1.5,0,145]]+[('column.configure',dict(COLUMN_EXAMPLE,solvent_pair=[0,1.5]))]:
|
| 33 |
+
with self.assertRaises(ActionRejected):h.invoke(cap,**arguments)
|
| 34 |
+
self.assertEqual(old,h.debug_snapshot())
|
| 35 |
+
def test_04_only_targets_until_step(self):
|
| 36 |
+
h=configured();self.assertEqual(h.flow,0.);self.assertEqual(h.pressure[0],0.);m=h.colmol.copy();h.invoke('acquisition.start');np.testing.assert_array_equal(m,h.colmol);self.assertEqual(h.flow,0.);h.step(.1);self.assertGreater(h.flow,0.)
|
| 37 |
+
def test_05_read_pure_and_schema(self):
|
| 38 |
+
h=configured();old=h.debug_snapshot();h.read();h.describe();h.invoke('chromatography.measure');h.invoke('product.read');self.assertEqual(old,h.debug_snapshot())
|
| 39 |
+
for bad in [True,float('nan'),0,4000]:
|
| 40 |
+
with self.assertRaises(ActionRejected):h.step(bad)
|
| 41 |
+
self.assertEqual(old,h.debug_snapshot())
|
| 42 |
+
def test_06_cancel_retains_pressure_and_mol(self):
|
| 43 |
+
h=configured();h.invoke('acquisition.start');h.step(45);old=h.colmol.copy();p=h.pressure.copy();h.invoke('acquisition.stop');h.step(10);np.testing.assert_array_equal(old,h.colmol);np.testing.assert_array_equal(p,h.pressure);h=finish(h);self.assertEqual(h.phase,'succeeded');self.ledger(h)
|
| 44 |
+
def test_07_poweroff_residual(self):
|
| 45 |
+
h=configured();h.invoke('acquisition.start');h.step(40);old=h._products();p=h.pressure.copy();h.invoke('power.set',enabled=False);h.step(100);self.assertEqual(h.phase,'cancelled');self.assertEqual(old,h._products());np.testing.assert_array_equal(p,h.pressure);self.ledger(h)
|
| 46 |
+
def test_08_two_channels_sequential_shared(self):
|
| 47 |
+
h=configured(second=True);h.invoke('acquisition.start');h.step(30);old=h.debug_snapshot()
|
| 48 |
+
with self.assertRaises(ActionRejected):h.invoke('channel.select',channel=1)
|
| 49 |
+
self.assertEqual(old,h.debug_snapshot());self.assertEqual(h.gradient_s[1],0.);self.assertEqual(h.colmol[1].sum(),3e-6);h.step(300);self.assertTrue(h.done[0]);h.invoke('channel.select',channel=1);h=finish(h);self.assertEqual(h.phase,'succeeded');self.assertTrue(all(h.done));self.ledger(h)
|
| 50 |
+
def test_09_finite_solvent(self):
|
| 51 |
+
h=finish(configured(plant={'solvent_volumes_m3':[3e-6,.002,.002,.002]}));self.assertEqual(h.fault,'SOLVENT_EMPTY');self.assertLess(h.gradient_s[0],10.);self.ledger(h)
|
| 52 |
+
def test_10_finite_waste(self):
|
| 53 |
+
h=finish(configured(plant={'waste_capacity_m3':2e-6},method={'threshold_absorbance':6.4}));self.assertEqual(h.fault,'WASTE_FULL');self.assertAlmostEqual(h.wastefluid.sum(),2e-6,delta=1e-15);self.ledger(h)
|
| 54 |
+
def test_11_finite_144_rack_subset(self):
|
| 55 |
+
h=finish(configured(rack={'positions':1},method={'collection_mode':'all','fraction_volume_m3':1e-6}));self.assertEqual(h.fault,'COLLECTION_FULL');self.assertAlmostEqual(h.fractionfluid[0].sum(),1e-6,delta=1e-15);self.ledger(h)
|
| 56 |
+
def test_12_pressure_limit_partial(self):
|
| 57 |
+
h=finish(configured(column={'pressure_limit_pa':5e5}));self.assertEqual(h.fault,'OVERPRESSURE');self.assertEqual(h.gradient_s[0],0.);self.assertEqual(h.colmol.sum(),3e-6);self.assertGreater(h.pressure[0],5e5);self.ledger(h)
|
| 58 |
+
def test_13_tray_pressure_guards(self):
|
| 59 |
+
h=configured();h.invoke('acquisition.start');h.step(1);h.invoke('acquisition.stop');old=h.debug_snapshot()
|
| 60 |
+
with self.assertRaises(ActionRejected):h.invoke('tray.set_extension',extension_m=.12)
|
| 61 |
+
self.assertEqual(old,h.debug_snapshot());h.invoke('pressure.release');h.step(50);h.invoke('tray.set_extension',extension_m=.12);self.assertEqual(h.tray,.12);self.ledger(h)
|
| 62 |
+
def test_14_reference_no_extrapolation(self):
|
| 63 |
+
h=configured();old=h.debug_snapshot()
|
| 64 |
+
with self.assertRaises(ActionRejected):h.invoke('method.configure',**dict(METHOD_EXAMPLE,wavelengths_m=[200e-9,350e-9]))
|
| 65 |
+
self.assertEqual(old,h.debug_snapshot())
|
| 66 |
+
def test_15_identity_async_dedupe(self):
|
| 67 |
+
h=configured();h.register_principal('eval','evaluator');a=h.session();e=h.session('eval');self.assertNotIn('sample.configure',a.describe(instance_id=h.instance_id)['capabilities']);self.assertFalse(any(k.startswith('truth.') for k in a.read(instance_id=h.instance_id)['observations']));r=a.invoke(instance_id=h.instance_id,capability_id='acquisition.start',arguments={},request_id='one');self.assertEqual(r['status'],'accepted');self.assertEqual(r,a.invoke(instance_id=h.instance_id,capability_id='acquisition.start',arguments={},request_id='one'));self.assertEqual(a.invoke(instance_id=h.instance_id,capability_id='chromatography.measure',arguments={},request_id='one')['error']['code'],'REQUEST_CONFLICT')
|
| 68 |
+
with self.assertRaises(ActionRejected):e.poll(r['operation_id'])
|
| 69 |
+
h.step(300);self.assertEqual(a.poll(r['operation_id'])['status'],'succeeded');self.assertEqual(a.invoke(instance_id=h.instance_id,capability_id='product.read',arguments={},request_id='deny')['status'],'rejected')
|
| 70 |
+
def test_16_native_cancel(self):
|
| 71 |
+
h=configured();a=h.session();r=a.invoke(instance_id=h.instance_id,capability_id='acquisition.start',arguments={},request_id='s');h.step(30);v=h._products();self.assertEqual(a.cancel(r['operation_id'],'c')['status'],'cancelled');h.step(10);self.assertEqual(v,h._products())
|
| 72 |
+
def test_17_instances(self):
|
| 73 |
+
a=configured();b=configured();a.invoke('acquisition.start');a.step(20);self.assertEqual(b.time_s,0.);self.assertEqual(b.pressure[0],0.);self.assertFalse(np.array_equal(a.colmol,b.colmol))
|
| 74 |
+
def test_18_no_method_rack_or_plant_start(self):
|
| 75 |
+
h=BiotageSelektRuntime();old=h.debug_snapshot()
|
| 76 |
+
with self.assertRaises(ActionRejected):h.invoke('acquisition.start')
|
| 77 |
+
self.assertEqual(old,h.debug_snapshot())
|
| 78 |
+
def test_19_gradient_delay(self):
|
| 79 |
+
h=configured(method={'gradient':[dict(time_s=0.,strong_fraction=1.),dict(time_s=10.,strong_fraction=1.)]});h.invoke('acquisition.start');self.assertEqual(h._values()['gradient.mixer_fraction'],0.);h.step(.1);self.assertGreater(h._values()['gradient.mixer_fraction'],0.);self.assertLess(h._values()['gradient.mixer_fraction'],1.);self.ledger(h)
|
| 80 |
+
def test_20_sample_load_limit_atomic(self):
|
| 81 |
+
h=BiotageSelektRuntime();h.invoke('plant.configure',**EXAMPLE);h.invoke('column.configure',**dict(COLUMN_EXAMPLE,max_sample_amount_mol=1e-6));old=h.debug_snapshot()
|
| 82 |
+
with self.assertRaises(ActionRejected):h.invoke('sample.configure',**SAMPLE_EXAMPLE)
|
| 83 |
+
self.assertEqual(old,h.debug_snapshot())
|
| 84 |
+
def test_21_xy_fraction_assignment(self):
|
| 85 |
+
h=configured(method={'collection_mode':'all','fraction_volume_m3':1e-6});h.invoke('acquisition.start');h.step(30);self.assertGreater(h.tube,5);self.assertTrue(np.all(h.fractionfluid.sum(axis=1)<=1e-6+1e-15));self.assertGreater(h.wastefluid.sum(),0.);self.ledger(h)
|
| 86 |
+
def test_22_step_subdivision(self):
|
| 87 |
+
a=finish(configured(),1.);b=finish(configured(),.1);np.testing.assert_allclose(a.fractionmol,b.fractionmol,rtol=1e-7,atol=1e-13);np.testing.assert_allclose(a.colmol,b.colmol,rtol=1e-7,atol=1e-13);self.ledger(a);self.ledger(b)
|
| 88 |
+
if __name__=='__main__':unittest.main()
|
tests/test_asset_bruker_magnettechesr5000.py
ADDED
|
@@ -0,0 +1,186 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Independent numerical, lifecycle, protocol and all60 template-path regression tests."""
|
| 2 |
+
import copy,json,math,sys,unittest
|
| 3 |
+
from pathlib import Path
|
| 4 |
+
import numpy as np
|
| 5 |
+
ROOT=Path(__file__).resolve().parents[1];sys.path.insert(0,str(ROOT/'scripts'))
|
| 6 |
+
from asset_runtime.bruker_magnettechesr5000 import *
|
| 7 |
+
def configured(plant=None,method=None,sample=None,blank=True):
|
| 8 |
+
r=BrukerMagnettechesr5000Runtime();p=copy.deepcopy(plant or PLANT_EXAMPLE);m=copy.deepcopy(method or METHOD_EXAMPLE);s=copy.deepcopy(sample or SAMPLE_EXAMPLE)
|
| 9 |
+
r.invoke('plant.configure',**p);r.invoke('method.configure',**m);r.invoke('power.set',enabled=True)
|
| 10 |
+
if blank:
|
| 11 |
+
b=dict(s,sample_id='blank_01',kind='blank',template_id='',concentration_mol_m3=0.,solid_spin_count=0.,mass_kg=0.)
|
| 12 |
+
r.invoke('sample.register',**b);r.invoke('sample.load',sample_id=b['sample_id']);r.invoke('lid.set',opened=False);r.invoke('microwave.set',enabled=True);r.invoke('acquisition.start',kind='blank');r.step(m['points']*m['dwell_s'])
|
| 13 |
+
r.invoke('lid.set',opened=True);r.invoke('sample.unload',recipient_id='rack')
|
| 14 |
+
r.invoke('sample.register',**s);r.invoke('sample.load',sample_id=s['sample_id']);r.invoke('lid.set',opened=False);r.invoke('microwave.set',enabled=True);return r
|
| 15 |
+
def measured(**kw):
|
| 16 |
+
r=configured(**kw);r.invoke('acquisition.start',kind='sample');r.step(r.method['points']*r.method['dwell_s']);return r
|
| 17 |
+
def trace(r):return dict(field_t=[p['field_t'] for p in r.points],intensity=[p['intensity'] for p in r.points])
|
| 18 |
+
class TestEPR(unittest.TestCase):
|
| 19 |
+
def test_real_templates(self):
|
| 20 |
+
r=BrukerMagnettechesr5000Runtime();self.assertEqual(len(r.templates),60);self.assertEqual(sum(x['g_iso'] is not None for x in r.templates.values()),11)
|
| 21 |
+
for t in r.templates.values():self.assertEqual(t['hyperfine_t'],[float(t['source']['raw_record']['AN'])*1e-4,float(t['source']['raw_record']['AH'])*1e-4]);self.assertIsNone(t['raw_signal']);self.assertIsNone(t['source_linewidth_pp_t'])
|
| 22 |
+
def test_blank_sample_complete(self):
|
| 23 |
+
r=measured();self.assertEqual(r.phase,'succeeded');self.assertEqual(len(r.points),129);self.assertFalse(r.microwave);self.assertGreater(np.ptp([p['intensity'] for p in r.points]),1e-4)
|
| 24 |
+
def test_all60_real_template_acquisitions(self):
|
| 25 |
+
for t in BrukerMagnettechesr5000Runtime().templates.values():
|
| 26 |
+
with self.subTest(id=t['substance_id']):
|
| 27 |
+
s=dict(SAMPLE_EXAMPLE,template_id=t['substance_id'],solvent_code=t['conditions']['solvent_code'],g_assumed=None if t['g_iso'] is not None else 2.0055)
|
| 28 |
+
r=measured(sample=s);self.assertEqual(r.phase,'succeeded');self.assertTrue(np.isfinite([p['intensity'] for p in r.points]).all());self.assertGreater(np.ptp([p['intensity'] for p in r.points]),0)
|
| 29 |
+
def test_resonance_formula(self):
|
| 30 |
+
self.assertAlmostEqual(H_PLANCK*9.5e9/(MU_B*2.0055),.3384420,places=5)
|
| 31 |
+
def test_lorentz_derivative_oracle(self):
|
| 32 |
+
s=dict(SAMPLE_EXAMPLE,material_phase='solid',template_id='',solvent_code='',volume_m3=0.,mass_kg=.001,concentration_mol_m3=0.,solid_spin_count=1e12,g_assumed=2.0055,accept_synthetic_solid=True,saturation_power_w=100.)
|
| 33 |
+
m=dict(METHOD_EXAMPLE,modulation_pp_t=1e-7);r=configured(sample=s,method=m);b=r._grid();center=m['field_center_t'];sat=m['microwave_power_w']/s['saturation_power_w'];gamma=math.sqrt(3)*s['linewidth_pp_t']/2*math.sqrt(1+sat);x=b-center
|
| 34 |
+
expected=-2*gamma*x/(math.pi*(x*x+gamma*gamma)**2)*1/math.sqrt(1+sat)*PLANT_EXAMPLE['shape_scale_t2'];np.testing.assert_allclose(r._profile(b),expected,rtol=4e-7,atol=1e-10)
|
| 35 |
+
def test_six_stick_first_order_oracle(self):
|
| 36 |
+
r=configured(method=dict(METHOD_EXAMPLE,modulation_pp_t=1e-7));b=r._grid();s=r._sample();an,ah=r.templates[s['template_id']]['hyperfine_t'];gamma=math.sqrt(3)*s['linewidth_pp_t']/2*math.sqrt(1+.001/.1);expected=np.zeros(len(b))
|
| 37 |
+
for mn in [-1,0,1]:
|
| 38 |
+
for mh in [-.5,.5]:
|
| 39 |
+
x=b-(r.method['field_center_t']-mn*an-mh*ah);expected+=-2*gamma*x/(math.pi*(x*x+gamma*gamma)**2)/6
|
| 40 |
+
expected*=r._spins(s)/r.plant['reference_spin_count']/math.sqrt(1.01)*r.plant['shape_scale_t2'];np.testing.assert_allclose(r._profile(b),expected,rtol=1e-6,atol=1e-10)
|
| 41 |
+
def test_finite_modulation_converges(self):
|
| 42 |
+
r=configured(method=dict(METHOD_EXAMPLE,modulation_pp_t=.001));a=r._profile(r._grid(),256);b=r._profile(r._grid(),1024);np.testing.assert_allclose(a,b,rtol=1e-9,atol=1e-10)
|
| 43 |
+
def test_modulation_pp_not_peak(self):
|
| 44 |
+
r=configured(method=dict(METHOD_EXAMPLE,modulation_pp_t=.0005));a=r._profile(r._grid());r.method['modulation_pp_t']=.001;b=r._profile(r._grid());self.assertGreater(float(np.max(np.abs(a-b))),1e-4)
|
| 45 |
+
def test_concentration_doubles_observation(self):
|
| 46 |
+
a=measured();b=measured(sample=dict(SAMPLE_EXAMPLE,concentration_mol_m3=.0002));np.testing.assert_allclose(trace(b)['intensity'],2*np.array(trace(a)['intensity']),rtol=1e-11,atol=1e-13)
|
| 47 |
+
def test_relative_from_observations_only(self):
|
| 48 |
+
r=measured();a=trace(r);b=dict(field_t=a['field_t'],intensity=[2*x for x in a['intensity']]);ans=r.invoke('quantify.relative',reference=a,sample=b,reference_volume_m3=1e-7,sample_volume_m3=2e-7,same_settings_confirmed=True);self.assertAlmostEqual(ans['relative_spin_number'],2);self.assertAlmostEqual(ans['relative_spin_concentration'],1)
|
| 49 |
+
def test_g_centroid_and_multiplet_width_null(self):
|
| 50 |
+
r=measured();v=r.invoke('spectrum.analyze',trace=trace(r),microwave_frequency_hz=9.5e9,isolated_line_assertion=False);self.assertAlmostEqual(v['g_apparent'],2.0055,places=7);self.assertIsNone(v['linewidth_pp_t'])
|
| 51 |
+
def test_solid_explicit_isotropic_linewidth(self):
|
| 52 |
+
s=dict(SAMPLE_EXAMPLE,material_phase='solid',template_id='',solvent_code='',volume_m3=0.,mass_kg=.001,concentration_mol_m3=0.,solid_spin_count=1e12,g_assumed=2.0055,accept_synthetic_solid=True,saturation_power_w=100.)
|
| 53 |
+
m=dict(METHOD_EXAMPLE,points=1025,modulation_pp_t=1e-7);r=measured(sample=s,method=m);v=r.invoke('spectrum.analyze',trace=trace(r),microwave_frequency_hz=9.5e9,isolated_line_assertion=True);self.assertAlmostEqual(v['linewidth_pp_t'],s['linewidth_pp_t'],delta=m['sweep_width_t']/(m['points']-1)*2);self.assertEqual(r.invoke('product.read')['registered_solid_kg'],.001)
|
| 54 |
+
def test_substep_clock_and_noise_equivalence(self):
|
| 55 |
+
p=dict(PLANT_EXAMPLE,noise_density_sqrt_s=.001);m=dict(METHOD_EXAMPLE,lockin_time_constant_s=.013);a=configured(plant=p,method=m);b=configured(plant=p,method=m)
|
| 56 |
+
for r in [a,b]:r.invoke('acquisition.start',kind='sample')
|
| 57 |
+
a.step(1.29)
|
| 58 |
+
for _ in range(1290):b.step(.001)
|
| 59 |
+
np.testing.assert_allclose(trace(a)['intensity'],trace(b)['intensity'],rtol=1e-10,atol=1e-10);self.assertAlmostEqual(a.time_s,b.time_s,places=10)
|
| 60 |
+
def test_lockin_interval_mean(self):
|
| 61 |
+
r=configured(method=dict(METHOD_EXAMPLE,lockin_time_constant_s=.02));r.invoke('acquisition.start',kind='sample');target=r._schedule[0]['target'];r.step(.01);self.assertAlmostEqual(r.points[0]['raw_intensity'],target*(1-.02/.01*(1-math.exp(-.01/.02))),places=12)
|
| 62 |
+
def test_pp_saturation_reduces_area(self):
|
| 63 |
+
r=configured();b=np.linspace(.2,.5,4096);low=r._profile(b);r.method['microwave_power_w']=.1;high=r._profile(b)
|
| 64 |
+
self.assertLess(np.max(np.abs(high))/np.max(np.abs(low)),math.sqrt(100))
|
| 65 |
+
def test_thermal_energy_and_partition(self):
|
| 66 |
+
a=BrukerMagnettechesr5000Runtime();b=BrukerMagnettechesr5000Runtime()
|
| 67 |
+
for r in [a,b]:r.invoke('plant.configure',**PLANT_EXAMPLE);r.invoke('power.set',enabled=True);r.invoke('thermal.set_temperature',temperature_k=308.)
|
| 68 |
+
a.step(20)
|
| 69 |
+
for _ in range(2000):b.step(.01)
|
| 70 |
+
self.assertAlmostEqual(a.temperature_k,b.temperature_k,places=9);self.assertAlmostEqual(a._ledger()['thermal_residual_j'],0,places=8);self.assertGreater(a.temperature_k,298.15)
|
| 71 |
+
def test_material_ledger_unload_conserves(self):
|
| 72 |
+
r=measured();before=r._ledger();r.invoke('lid.set',opened=True);r.invoke('sample.unload',recipient_id='rack');after=r._ledger()
|
| 73 |
+
for k in ['registered_volume_m3','registered_solute_mol','registered_spins']:self.assertEqual(before[k],after[k])
|
| 74 |
+
for k in ['volume_residual_m3','solute_residual_mol','mass_residual_kg','spin_residual']:self.assertEqual(after[k],0)
|
| 75 |
+
def test_cancel_partial_then_pure_read(self):
|
| 76 |
+
r=configured();r.invoke('acquisition.start',kind='sample');r.step(.035);r.invoke('acquisition.stop');self.assertEqual(len(r.points),3);self.assertEqual(r.phase,'cancelled');old=r.debug_snapshot()
|
| 77 |
+
for _ in range(3):r.invoke('process.measure');r.invoke('spectrum.read');r.read()
|
| 78 |
+
self.assertEqual(old,r.debug_snapshot())
|
| 79 |
+
def test_opening_interrupts_without_faking_complete(self):
|
| 80 |
+
r=configured();r.invoke('acquisition.start',kind='sample');r.step(.025);r.invoke('lid.set',opened=True);self.assertFalse(r.microwave);self.assertEqual(r.phase,'cancelled');self.assertEqual(len(r.points),2)
|
| 81 |
+
def test_power_off_interrupts(self):
|
| 82 |
+
r=configured();r.invoke('acquisition.start',kind='sample');r.step(.025);r.invoke('power.set',enabled=False);self.assertFalse(r.microwave);self.assertFalse(r._blank_ok())
|
| 83 |
+
def test_busy_rejection_atomic(self):
|
| 84 |
+
r=configured();r.invoke('acquisition.start',kind='sample');before=r.debug_snapshot()
|
| 85 |
+
with self.assertRaisesRegex(ActionRejected,'BUSY'):r.invoke('method.configure',**METHOD_EXAMPLE)
|
| 86 |
+
self.assertEqual(before,r.debug_snapshot())
|
| 87 |
+
def test_schema_bool_nan_unknown_rejected(self):
|
| 88 |
+
r=configured()
|
| 89 |
+
for args in [dict(METHOD_EXAMPLE,points=True),dict(METHOD_EXAMPLE,microwave_power_w=float('nan')),dict(METHOD_EXAMPLE,alien=1),dict(METHOD_EXAMPLE,modulation_frequency_hz=20000.)]:
|
| 90 |
+
old=r.debug_snapshot()
|
| 91 |
+
with self.assertRaises(ActionRejected):r.invoke('method.configure',**args)
|
| 92 |
+
self.assertEqual(old,r.debug_snapshot())
|
| 93 |
+
def test_field_extents_and_factory_limits(self):
|
| 94 |
+
r=configured()
|
| 95 |
+
for args in [dict(METHOD_EXAMPLE,field_center_t=.65),dict(METHOD_EXAMPLE,microwave_power_w=.10001),dict(METHOD_EXAMPLE,microwave_power_w=0),dict(METHOD_EXAMPLE,points=250000)]:
|
| 96 |
+
with self.assertRaises(ActionRejected):r.invoke('method.configure',**args)
|
| 97 |
+
r.invoke('method.configure',**dict(METHOD_EXAMPLE,field_center_t=.32,sweep_width_t=.66))
|
| 98 |
+
def test_missing_blank(self):
|
| 99 |
+
r=configured(blank=False)
|
| 100 |
+
with self.assertRaisesRegex(ActionRejected,'BLANK_REQUIRED'):r.invoke('acquisition.start',kind='sample')
|
| 101 |
+
def test_changed_method_invalidates_blank(self):
|
| 102 |
+
r=configured();r.invoke('method.configure',**dict(METHOD_EXAMPLE,gain=2.));self.assertFalse(r._blank_ok())
|
| 103 |
+
def test_solvent_and_g_guards(self):
|
| 104 |
+
for change,msg in [({'solvent_code':'WRONG'},'SOURCE_SOLVENT_MISMATCH'),({'g_assumed':None},'MISSING_G_ASSUMPTION'),({'template_id':'niehs_122','solvent_code':'AQ08P5','g_assumed':2.0023},'SOURCE_G_CONFLICT')]:
|
| 105 |
+
with self.assertRaisesRegex(ActionRejected,msg):configured(sample=dict(SAMPLE_EXAMPLE,**change))
|
| 106 |
+
def test_source_g_kept_without_assumed_override(self):
|
| 107 |
+
t=BrukerMagnettechesr5000Runtime().templates['niehs_122'];r=measured(sample=dict(SAMPLE_EXAMPLE,template_id='niehs_122',solvent_code=t['conditions']['solvent_code'],g_assumed=None));self.assertEqual(r.phase,'succeeded')
|
| 108 |
+
def test_solid_requires_explicit_ack(self):
|
| 109 |
+
with self.assertRaisesRegex(ActionRejected,'SYNTHETIC_SOLID_ACK_REQUIRED'):configured(sample=dict(SAMPLE_EXAMPLE,material_phase='solid'),blank=False)
|
| 110 |
+
def test_missing_temperature_accessory(self):
|
| 111 |
+
r=configured(plant=dict(PLANT_EXAMPLE,temperature_accessory=False))
|
| 112 |
+
with self.assertRaisesRegex(ActionRejected,'ACCESSORY_NOT_INSTALLED'):r.invoke('thermal.set_temperature',temperature_k=298.15)
|
| 113 |
+
def test_template_temperature_guard(self):
|
| 114 |
+
r=configured();r.invoke('thermal.set_temperature',temperature_k=310.);r.step(100)
|
| 115 |
+
with self.assertRaisesRegex(ActionRejected,'REFERENCE_TEMPERATURE_MISMATCH'):r.invoke('acquisition.start',kind='sample')
|
| 116 |
+
def test_initialization_once_after_clock_advance(self):
|
| 117 |
+
r=BrukerMagnettechesr5000Runtime();r.step(5);r.invoke('plant.configure',**PLANT_EXAMPLE)
|
| 118 |
+
with self.assertRaisesRegex(ActionRejected,'INITIALIZATION_ONLY'):r.invoke('plant.configure',**PLANT_EXAMPLE)
|
| 119 |
+
def test_no_return_aliases(self):
|
| 120 |
+
r=measured();d=r.invoke('spectrum.read');d['points'][0]['intensity']=999;self.assertNotEqual(r.points[0]['intensity'],999);x=r.read('evaluator');x['truth.ledger']['registered_spins']=0;self.assertGreater(r._ledger()['registered_spins'],0)
|
| 121 |
+
def test_no_input_aliases(self):
|
| 122 |
+
r=BrukerMagnettechesr5000Runtime();p=copy.deepcopy(PLANT_EXAMPLE);r.invoke('plant.configure',**p);p['ambient_k']=300;self.assertEqual(r.plant['ambient_k'],298.15)
|
| 123 |
+
def test_session_acl_and_no_identity_leak(self):
|
| 124 |
+
r=configured();s=r.session();d=s.describe(instance_id=r.instance_id);self.assertNotIn('sample.register',d['capabilities']);self.assertNotIn('truth.ledger',d['state_slots'])
|
| 125 |
+
denied=s.invoke(instance_id=r.instance_id,capability_id='sample.register',arguments=SAMPLE_EXAMPLE,request_id='private');self.assertEqual(denied['error']['code'],'ACCESS_DENIED')
|
| 126 |
+
self.assertNotIn('niehs_109',json.dumps(s.read(instance_id=r.instance_id)))
|
| 127 |
+
def test_request_dedup_and_conflict(self):
|
| 128 |
+
r=configured();s=r.session();kw=dict(instance_id=r.instance_id,capability_id='acquisition.start',arguments={'kind':'sample'},request_id='a');a=s.invoke(**kw);b=s.invoke(**kw);self.assertEqual(a,b);self.assertEqual(r._op_count,2)
|
| 129 |
+
c=s.invoke(**dict(kw,arguments={'kind':'blank'}));self.assertEqual(c['error']['code'],'REQUEST_CONFLICT')
|
| 130 |
+
def test_operation_ownership_and_cancel(self):
|
| 131 |
+
r=configured();r.register_principal('other');s=r.session();a=s.invoke(instance_id=r.instance_id,capability_id='acquisition.start',arguments={'kind':'sample'},request_id='a')
|
| 132 |
+
with self.assertRaisesRegex(ActionRejected,'ACCESS_DENIED'):r.session('other').poll(a['operation_id'])
|
| 133 |
+
s.cancel(a['operation_id'],'cancel');self.assertEqual(s.poll(a['operation_id'])['status'],'cancelled')
|
| 134 |
+
def test_session_observation_window_and_null(self):
|
| 135 |
+
r=BrukerMagnettechesr5000Runtime();s=r.session();v=s.read(instance_id=r.instance_id)['observations']['scan.intensity'];self.assertIsNone(v['value']);self.assertEqual(v['quality'],'unavailable')
|
| 136 |
+
r=configured();r.invoke('acquisition.start',kind='sample');r.step(.025);v=r.session().read(instance_id=r.instance_id)['observations']['scan.intensity'];self.assertAlmostEqual(v['sample_time_s'],r.points[-1]['sample_time_s']);self.assertAlmostEqual(v['sample_window_s'][1]-v['sample_window_s'][0],.01)
|
| 137 |
+
def test_unsupported_envelope_and_layers(self):
|
| 138 |
+
r=configured();meta=export_bruker_magnettechesr5000_contract_metadata()
|
| 139 |
+
for c in UNSUPPORTED:self.assertEqual(r.session().invoke(instance_id=r.instance_id,capability_id=c,arguments={},request_id=c)['status'],'unsupported');self.assertTrue(all(v=='absent' for v in meta['capabilities'][c]['implementation'].values()));self.assertIsNone(meta['capabilities'][c]['binding'])
|
| 140 |
+
def test_analysis_zero_and_reference_rejections(self):
|
| 141 |
+
r=configured();zero=dict(field_t=np.linspace(.3,.4,16).tolist(),intensity=[0.]*16);v=r.invoke('spectrum.analyze',trace=zero,microwave_frequency_hz=9.5e9,isolated_line_assertion=True);self.assertIsNone(v['g_apparent']);self.assertIsNone(v['linewidth_pp_t'])
|
| 142 |
+
with self.assertRaises(ActionRejected):r.invoke('quantify.relative',reference=zero,sample=zero,reference_volume_m3=1e-7,sample_volume_m3=1e-7,same_settings_confirmed=True)
|
| 143 |
+
def test_public_write_only_setpoint(self):
|
| 144 |
+
r=configured();s=r.session()
|
| 145 |
+
with self.assertRaisesRegex(ActionRejected,'ACCESS_DENIED'):s.write(instance_id=r.instance_id,state_id='scan.intensity',value=1.,request_id='bad')
|
| 146 |
+
a=s.write(instance_id=r.instance_id,state_id='lid.opened',value=True,request_id='open');self.assertEqual(a['status'],'succeeded');self.assertTrue(r.opened)
|
| 147 |
+
def test_nonuniform_field_linear_background_has_no_resonance(self):
|
| 148 |
+
r=BrukerMagnettechesr5000Runtime();b=.3+.1*np.linspace(0,1,16)**2
|
| 149 |
+
result=r.invoke('spectrum.analyze',trace=dict(field_t=b.tolist(),intensity=(3*b+.2).tolist()),microwave_frequency_hz=9.5e9,isolated_line_assertion=True)
|
| 150 |
+
self.assertEqual(result['double_integral_t2'],0.);self.assertIsNone(result['g_apparent']);self.assertIsNone(result['linewidth_pp_t'])
|
| 151 |
+
def test_nonuniform_trace_baseline_does_not_change_integral(self):
|
| 152 |
+
r=BrukerMagnettechesr5000Runtime();b=.33+.02*np.linspace(0,1,257)**1.3;x=(b-.34)/.002;y=-x*np.exp(-x*x)
|
| 153 |
+
clean=r.invoke('spectrum.analyze',trace=dict(field_t=b.tolist(),intensity=y.tolist()),microwave_frequency_hz=9.5e9,isolated_line_assertion=False)
|
| 154 |
+
shifted=r.invoke('spectrum.analyze',trace=dict(field_t=b.tolist(),intensity=(y+3*b+.2).tolist()),microwave_frequency_hz=9.5e9,isolated_line_assertion=False)
|
| 155 |
+
self.assertAlmostEqual(clean['double_integral_t2'],shifted['double_integral_t2'],places=16);self.assertAlmostEqual(clean['g_apparent'],shifted['g_apparent'],places=12)
|
| 156 |
+
def test_relative_overflow_is_rejected_without_effects(self):
|
| 157 |
+
r=BrukerMagnettechesr5000Runtime();ref=dict(field_t=DEMO_TRACE['field_t'],intensity=[v*1e-18 for v in DEMO_TRACE['intensity']]);sample=dict(field_t=DEMO_TRACE['field_t'],intensity=[v*1e308 for v in DEMO_TRACE['intensity']]);before=r.debug_snapshot()
|
| 158 |
+
result=r.session().invoke(instance_id=r.instance_id,capability_id='quantify.relative',arguments=dict(reference=ref,sample=sample,reference_volume_m3=1e-3,sample_volume_m3=1e-12,same_settings_confirmed=True),request_id='overflow')
|
| 159 |
+
self.assertEqual(result['status'],'rejected');self.assertEqual(result['error']['code'],'INVALID_REFERENCE_INTEGRAL');self.assertEqual(before,r.debug_snapshot());json.dumps(result,allow_nan=False)
|
| 160 |
+
def test_analysis_unrepresentable_area_is_rejected(self):
|
| 161 |
+
r=BrukerMagnettechesr5000Runtime();trace=dict(field_t=np.linspace(1.,1e200,33).tolist(),intensity=DEMO_TRACE['intensity']);before=r.debug_snapshot()
|
| 162 |
+
result=r.session().invoke(instance_id=r.instance_id,capability_id='spectrum.analyze',arguments=dict(trace=trace,microwave_frequency_hz=9.5e9,isolated_line_assertion=True),request_id='area_overflow')
|
| 163 |
+
self.assertEqual(result['status'],'rejected');self.assertEqual(result['error']['code'],'ANALYSIS_INPUT');self.assertEqual(before,r.debug_snapshot());json.dumps(result,allow_nan=False)
|
| 164 |
+
def test_completed_operation_survives_later_scan_with_ownership(self):
|
| 165 |
+
r=configured();s=r.session();start=lambda rid:s.invoke(instance_id=r.instance_id,capability_id='acquisition.start',arguments={'kind':'sample'},request_id=rid)
|
| 166 |
+
old=start('first')['operation_id'];r.step(2);completed=s.poll(old);r.invoke('microwave.set',enabled=True);start('second');before=r.debug_snapshot()
|
| 167 |
+
self.assertEqual(s.poll(old),completed);self.assertEqual(before,r.debug_snapshot());self.assertEqual(completed['status'],'succeeded');self.assertEqual(completed['result']['completed_points'],129)
|
| 168 |
+
completed['result']['intensity']=-999;self.assertNotEqual(s.poll(old)['result']['intensity'],-999);r.register_principal('other')
|
| 169 |
+
with self.assertRaisesRegex(ActionRejected,'ACCESS_DENIED'):r.session('other').poll(old)
|
| 170 |
+
self.assertNotIn('niehs_',json.dumps(s.poll(old)));self.assertNotIn('truth.',json.dumps(s.poll(old)))
|
| 171 |
+
def test_cancel_old_operation_preserves_active_scan_and_dedup(self):
|
| 172 |
+
r=configured();s=r.session();start=lambda rid:s.invoke(instance_id=r.instance_id,capability_id='acquisition.start',arguments={'kind':'sample'},request_id=rid)
|
| 173 |
+
old=start('first')['operation_id'];r.step(2);r.invoke('microwave.set',enabled=True);current=start('second')['operation_id'];revision=r.revision
|
| 174 |
+
result=s.cancel(old,'cancel_old');self.assertEqual(result['result']['phase'],'succeeded');self.assertEqual(r.phase,'running');self.assertTrue(r.microwave);self.assertEqual(r.operation_id,current);self.assertEqual(r.revision,revision)
|
| 175 |
+
r.step(.02);self.assertEqual(s.cancel(old,'cancel_old'),result)
|
| 176 |
+
with self.assertRaisesRegex(ActionRejected,'REQUEST_CONFLICT'):s.cancel(current,'cancel_old')
|
| 177 |
+
self.assertEqual(r.phase,'running')
|
| 178 |
+
def test_cancelled_operation_survives_invalidation(self):
|
| 179 |
+
r=configured();s=r.session();op=s.invoke(instance_id=r.instance_id,capability_id='acquisition.start',arguments={'kind':'sample'},request_id='first')['operation_id'];r.step(.035);s.cancel(op,'stop');frozen=s.poll(op)
|
| 180 |
+
r.invoke('lid.set',opened=True);r.invoke('method.configure',**METHOD_EXAMPLE);self.assertEqual(s.poll(op),frozen);self.assertEqual(frozen['result']['completed_points'],3);self.assertEqual(frozen['result']['warning'],'CANCELLED')
|
| 181 |
+
def test_temperature_metadata_separates_setting_from_process(self):
|
| 182 |
+
r=configured();meta=export_bruker_magnettechesr5000_contract_metadata();cap=meta['capabilities']['thermal.set_temperature'];immediate={e['state_id'] for e in cap['state_effects'] if e['timing']=='immediate'};later={e['state_id'] for e in cap['state_effects'] if e['timing']=='on_step'}
|
| 183 |
+
before=r.read('evaluator');r.invoke('thermal.set_temperature',temperature_k=303.15);after=r.read('evaluator');self.assertLessEqual({k for k in before if before[k]!=after[k]},immediate);self.assertNotIn('thermal.temperature_k',immediate);self.assertNotIn('power.enabled',immediate);self.assertNotIn('lid.opened',immediate)
|
| 184 |
+
self.assertEqual(before['thermal.temperature_k'],after['thermal.temperature_k']);r.step(.1);self.assertNotEqual(r.temperature_k,before['thermal.temperature_k']);self.assertIn('thermal.temperature_k',later);self.assertIn('scan.intensity',meta['capabilities']['process.measure']['observes']);self.assertEqual(meta['capabilities']['process.measure']['state_effects'],[])
|
| 185 |
+
if __name__=='__main__':unittest.main()
|
| 186 |
+
|
tests/test_asset_bruker_minispecmq20.py
ADDED
|
@@ -0,0 +1,127 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""CHEM-066 real entry, Bloch, event timing, evidence and protocol regressions."""
|
| 2 |
+
import copy,json,math,unittest
|
| 3 |
+
import numpy as np
|
| 4 |
+
from scripts.asset_runtime.bruker_minispecmq20 import *
|
| 5 |
+
def ready(method=None,plant=None,sample=None):
|
| 6 |
+
h=BrukerMinispecMq20Runtime();h.invoke('plant.configure',**dict(FAST_PLANT,**(plant or {})))
|
| 7 |
+
h.invoke('solution.register',**dict(SAMPLE_EXAMPLE,**(sample or {})));h.invoke('sample.load',sample_id=(sample or {}).get('sample_id','sample_01'));h.invoke('method.configure',**dict(METHOD_EXAMPLE,**(method or {})));h.invoke('power.set',enabled=True);h.invoke('lid.set',opened=False);return h
|
| 8 |
+
def run(h,dt=100.):
|
| 9 |
+
h.invoke('acquisition.start');h.step(dt);return h
|
| 10 |
+
class TestMq20(unittest.TestCase):
|
| 11 |
+
def reject(self,h,k,**a):
|
| 12 |
+
b=h.debug_snapshot()
|
| 13 |
+
with self.assertRaises(ActionRejected):h.invoke(k,**a)
|
| 14 |
+
self.assertEqual(b,h.debug_snapshot())
|
| 15 |
+
def test_library55_measured_pair26(self):
|
| 16 |
+
h=BrukerMinispecMq20Runtime();self.assertEqual(len(h.templates),55);self.assertEqual(sum(v['r2_m3_mol_s'] is not None for v in h.templates.values()),26)
|
| 17 |
+
for r in h.templates.values():self.assertEqual(r['conditions']['frequency_hz'],20e6);self.assertEqual(r['evidence'],'measured_literature')
|
| 18 |
+
def test_no_false_r2_default(self):
|
| 19 |
+
h=ready();s=dict(SAMPLE_EXAMPLE,sample_id='extra',template_id='pmc4095929_gd3_dotalap',medium_id='pbs',accept_unvalidated_concentration=True)
|
| 20 |
+
self.reject(h,'solution.register',**s);h.invoke('solution.register',**dict(s,missing_r2_m3_mol_s=8.))
|
| 21 |
+
def test_bloch_rate_consistency(self):
|
| 22 |
+
self.reject(ready(),'solution.register',**dict(SAMPLE_EXAMPLE,sample_id='bad',baseline_r1_s_inv=100.,baseline_r2_s_inv=.01))
|
| 23 |
+
def test_no_measured_override(self):self.reject(ready(),'solution.register',**dict(SAMPLE_EXAMPLE,sample_id='x',missing_r2_m3_mol_s=9.))
|
| 24 |
+
def test_medium_condition(self):self.reject(ready(),'solution.register',**dict(SAMPLE_EXAMPLE,sample_id='x',medium_id='plasma'))
|
| 25 |
+
def test_concentration_range(self):self.reject(ready(),'solution.register',**dict(SAMPLE_EXAMPLE,sample_id='x',metal_concentration_mol_m3=.2))
|
| 26 |
+
def test_explicit_unknowns(self):self.reject(ready(),'solution.register',**dict(SAMPLE_EXAMPLE,sample_id='x',accept_incomplete_source_conditions=False))
|
| 27 |
+
def test_baseline_explicit(self):self.reject(ready(),'solution.register',**dict(SAMPLE_EXAMPLE,sample_id='x',accept_synthetic_baselines=False))
|
| 28 |
+
def test_tube_envelope(self):self.reject(ready(),'solution.register',**dict(SAMPLE_EXAMPLE,sample_id='x',tube_od_m=.018))
|
| 29 |
+
def test_nullable_not_garbage(self):self.reject(ready(),'solution.register',**dict(SAMPLE_EXAMPLE,sample_id='x',pH='7'))
|
| 30 |
+
def test_numeric_invalid_atomic(self):
|
| 31 |
+
for v in [True,float('nan'),float('inf'),-1,301.]:self.reject(ready(),'method.configure',**dict(METHOD_EXAMPLE,rf_power_w=v))
|
| 32 |
+
def test_unknown_argument(self):self.reject(ready(),'power.set',enabled=True,unexpected=1)
|
| 33 |
+
def test_negative_step(self):
|
| 34 |
+
h=ready();b=h.debug_snapshot()
|
| 35 |
+
with self.assertRaises(ActionRejected):h.step(-1)
|
| 36 |
+
self.assertEqual(b,h.debug_snapshot())
|
| 37 |
+
def test_dt_zero_pure(self):
|
| 38 |
+
h=ready();b=h.debug_snapshot();h.step(0);self.assertEqual(b,h.debug_snapshot())
|
| 39 |
+
def test_config_at_existing_clock(self):
|
| 40 |
+
h=BrukerMinispecMq20Runtime();h.step(1);h.invoke('plant.configure',**FAST_PLANT);self.assertEqual(h.time_s,1)
|
| 41 |
+
def test_reconfigure_blocked(self):self.reject(ready(),'plant.configure',**FAST_PLANT)
|
| 42 |
+
def test_settings_no_time(self):
|
| 43 |
+
h=ready();t=h.time_s;h.invoke('method.configure',**CPMG_METHOD);self.assertEqual(t,h.time_s)
|
| 44 |
+
def test_pure_read_describe_query(self):
|
| 45 |
+
h=run(ready());b=h.debug_snapshot();h.read();h.describe();h.invoke('relaxation.fit');h.invoke('process.measure');h.invoke('signal.read');h.session().read(instance_id=h.instance_id);self.assertEqual(b,h.debug_snapshot())
|
| 46 |
+
def test_fixed_magnet_when_off(self):
|
| 47 |
+
h=ready();h.invoke('power.set',enabled=False);self.assertEqual(h.read()['magnet.field_t'],.47);self.reject(h,'magnet.set_frequency',frequency_hz=60e6)
|
| 48 |
+
def test_diffusion_unsupported(self):self.reject(ready(),'diffusion.measure')
|
| 49 |
+
def test_vt_required(self):self.reject(ready(plant={'vt_installed':False}),'thermal.set_temperature',temperature_k=298.15)
|
| 50 |
+
def test_vt_not_instant_and_energy(self):
|
| 51 |
+
h=ready();h.invoke('thermal.set_temperature',temperature_k=300.);self.assertEqual(h.temperature,310.15);h.step(1);self.assertAlmostEqual(h.temperature,300+10.15/math.e);self.assertAlmostEqual(h._ledger()['thermal_residual_j'],0)
|
| 52 |
+
def test_vt_range(self):self.reject(ready(),'thermal.set_temperature',temperature_k=338.16)
|
| 53 |
+
def test_temperature_matching(self):
|
| 54 |
+
h=ready();h.invoke('thermal.set_temperature',temperature_k=298.15);h.step(20);self.reject(h,'acquisition.start')
|
| 55 |
+
def test_timing20ns(self):self.reject(ready(),'method.configure',**dict(METHOD_EXAMPLE,pulse90_s=50.01e-6))
|
| 56 |
+
def test_receiver_dead_time_grid(self):
|
| 57 |
+
h=BrukerMinispecMq20Runtime();self.reject(h,'plant.configure',**dict(FAST_PLANT,receiver_dead_s=10.01e-6))
|
| 58 |
+
def test_cpmg_half_delay_grid(self):self.reject(ready(),'method.configure',**dict(CPMG_METHOD,echo_spacing_s=.00500002))
|
| 59 |
+
def test_delay_grid(self):self.reject(ready(),'method.configure',**dict(METHOD_EXAMPLE,points=7))
|
| 60 |
+
def test_cpmg_overlap(self):self.reject(ready(),'method.configure',**dict(CPMG_METHOD,echo_spacing_s=20e-6))
|
| 61 |
+
def test_t1_observed_fit(self):
|
| 62 |
+
h=run(ready());f=h.invoke('relaxation.fit');self.assertEqual(f['quantity'],'T1');self.assertAlmostEqual(f['rate_s_inv'],4.2,delta=.015);self.assertGreater(f['r_squared'],.999)
|
| 63 |
+
def test_t2_observed_fit(self):
|
| 64 |
+
h=run(ready(method=CPMG_METHOD));f=h.invoke('relaxation.fit');self.assertEqual(f['quantity'],'T2');self.assertAlmostEqual(f['rate_s_inv'],5.,delta=.02)
|
| 65 |
+
def test_fitter_does_not_read_hidden_rate(self):
|
| 66 |
+
h=run(ready());a=h.invoke('relaxation.fit');h.samples[h.active]['baseline_r1_s_inv']=999;self.assertEqual(a,h.invoke('relaxation.fit'))
|
| 67 |
+
def test_no_points_at_start(self):
|
| 68 |
+
h=ready();h.invoke('acquisition.start');self.assertEqual(h.points,[]);self.assertEqual(h.phase,'running')
|
| 69 |
+
def test_partial_cancel(self):
|
| 70 |
+
h=ready(method=CPMG_METHOD);h.invoke('acquisition.start');h.step(2.13);n=len(h.points);self.assertGreater(n,0);h.invoke('acquisition.stop');h.step(1);self.assertEqual(len(h.points),n);self.assertEqual(h.phase,'cancelled');self.reject(h,'relaxation.fit')
|
| 71 |
+
def test_open_cancels(self):
|
| 72 |
+
h=ready();h.invoke('acquisition.start');h.invoke('lid.set',opened=True);self.assertEqual(h.phase,'cancelled');self.assertEqual(h.rf,0)
|
| 73 |
+
def test_off_cancels(self):
|
| 74 |
+
h=ready();h.invoke('acquisition.start');h.invoke('power.set',enabled=False);self.assertEqual(h.phase,'cancelled');self.assertEqual(h.rf,0)
|
| 75 |
+
def test_busy_atomic(self):
|
| 76 |
+
h=ready();h.invoke('acquisition.start');self.reject(h,'method.configure',**METHOD_EXAMPLE);self.reject(h,'thermal.set_temperature',temperature_k=310.15)
|
| 77 |
+
def test_rf_budget_exhaustion(self):
|
| 78 |
+
h=run(ready(plant={'rf_budget_j':.003}));self.assertEqual(h.phase,'failed');self.assertEqual(h.warning,'RF_BUDGET_EXHAUSTED');self.assertAlmostEqual(h.rf_delivered,.003);self.assertAlmostEqual(h._ledger()['rf_residual_j'],0)
|
| 79 |
+
def test_finite_pulse_energy(self):
|
| 80 |
+
h=run(ready(method=CPMG_METHOD));want=100*(50e-6+80*100e-6);self.assertAlmostEqual(h.rf_delivered,want,places=9)
|
| 81 |
+
def test_exact_bloch_free_recovery(self):
|
| 82 |
+
h=ready();h.mag[:]=[.4,.3,-.2];h.step(.1);np.testing.assert_allclose(h.mag[0],[.4*math.exp(-.5),.3*math.exp(-.5),1-1.2*math.exp(-.42)],atol=1e-12)
|
| 83 |
+
def test_finite_rf_rotation(self):
|
| 84 |
+
h=ready();h.rf=100;h.axis='x';h._advance(50e-6);self.assertAlmostEqual(-h.mag[0,1],1,delta=.001);self.assertAlmostEqual(h.rf_delivered,.005)
|
| 85 |
+
def test_phase_refocus_static_offsets(self):
|
| 86 |
+
h=run(ready(method=CPMG_METHOD,plant={'offset_hz':50}));f=h.invoke('relaxation.fit');self.assertAlmostEqual(f['rate_s_inv'],5,delta=.03)
|
| 87 |
+
def test_rf_amplitude_affects_observed_signal(self):
|
| 88 |
+
a=run(ready(method=CPMG_METHOD));b=run(ready(method=dict(CPMG_METHOD,rf_power_w=25)));self.assertNotEqual(a.points[0]['signal'],b.points[0]['signal'])
|
| 89 |
+
def test_chunk_invariance(self):
|
| 90 |
+
a=ready(method=CPMG_METHOD);b=ready(method=CPMG_METHOD);a.invoke('acquisition.start');b.invoke('acquisition.start');a.step(3)
|
| 91 |
+
for _ in range(300):b.step(.01)
|
| 92 |
+
self.assertEqual([p['signal'] for p in a.points],[p['signal'] for p in b.points]);np.testing.assert_allclose(a.mag,b.mag,atol=1e-10);self.assertAlmostEqual(a.rf_delivered,b.rf_delivered,places=9)
|
| 93 |
+
def test_two_instances(self):
|
| 94 |
+
a=ready();b=ready();s=b.debug_snapshot();a.invoke('acquisition.start');a.step(10);self.assertEqual(s,b.debug_snapshot())
|
| 95 |
+
def test_input_alias(self):
|
| 96 |
+
h=ready();method=copy.deepcopy(METHOD_EXAMPLE);h.invoke('method.configure',**method);method['delays_s'][0]=999;self.assertEqual(h.method['delays_s'][0],.001)
|
| 97 |
+
def test_output_alias(self):
|
| 98 |
+
h=run(ready());x=h.invoke('signal.read');x['points'][0]['signal']=999;self.assertNotEqual(h.points[0]['signal'],999)
|
| 99 |
+
def test_volume_ledger_unload(self):
|
| 100 |
+
h=ready();h.invoke('lid.set',opened=True);h.invoke('sample.unload',recipient_id='rack');r=h._ledger();self.assertEqual(r['attached_volume_m3'],0);self.assertEqual(r['external_volume_m3'],5e-7);self.assertEqual(r['volume_residual_m3'],0)
|
| 101 |
+
def test_agent_isolation(self):
|
| 102 |
+
h=ready();s=h.session();self.assertNotIn('truth.ledger',s.read(instance_id=h.instance_id)['observations']);self.assertNotIn('solution.register',s.describe(instance_id=h.instance_id)['capabilities'])
|
| 103 |
+
x=s.invoke(instance_id=h.instance_id,capability_id='product.read',arguments={},request_id='forbidden');self.assertEqual(x['error']['code'],'ACCESS_DENIED');self.assertNotIn(SAMPLE_EXAMPLE['template_id'],json.dumps(x))
|
| 104 |
+
def test_idempotency_conflict(self):
|
| 105 |
+
h=ready();s=h.session();a=dict(instance_id=h.instance_id,capability_id='acquisition.start',arguments={},request_id='req');x=s.invoke(**a);h.step(.1);self.assertEqual(s.invoke(**a),x);a['capability_id']='acquisition.stop';self.assertEqual(s.invoke(**a)['error']['code'],'REQUEST_CONFLICT')
|
| 106 |
+
def test_operation_ownership(self):
|
| 107 |
+
h=ready();s=h.session();h.register_principal('other');x=s.invoke(instance_id=h.instance_id,capability_id='acquisition.start',arguments={},request_id='start')
|
| 108 |
+
with self.assertRaises(ActionRejected):h.session('other').poll(x['operation_id'])
|
| 109 |
+
s.cancel(x['operation_id'],'cancel');self.assertEqual(h.phase,'cancelled')
|
| 110 |
+
def test_wrong_instance(self):
|
| 111 |
+
h=ready()
|
| 112 |
+
with self.assertRaises(ActionRejected):h.session().read(instance_id='wrong')
|
| 113 |
+
def test_unsupported_protocol(self):
|
| 114 |
+
h=ready();s=h.session()
|
| 115 |
+
for k in UNSUPPORTED:self.assertEqual(s.invoke(instance_id=h.instance_id,capability_id=k,arguments=CAPS[k][6],request_id=k)['status'],'unsupported')
|
| 116 |
+
def test_write_routes(self):
|
| 117 |
+
h=ready();x=h.session().write(instance_id=h.instance_id,state_id='lid.opened',value=True,request_id='lid');self.assertEqual(x['status'],'succeeded');self.assertTrue(h.opened)
|
| 118 |
+
def test_no_truth_write(self):
|
| 119 |
+
h=ready()
|
| 120 |
+
with self.assertRaises(ActionRejected):h.session().write(instance_id=h.instance_id,state_id='truth.ledger',value={},request_id='bad')
|
| 121 |
+
def test_receiver_overflow(self):
|
| 122 |
+
h=run(ready(plant={'receiver_gain':10.}));self.assertEqual(h.phase,'failed');self.assertEqual(h.warning,'RECEIVER_OVERFLOW')
|
| 123 |
+
def test_schema_layers_unsupported(self):
|
| 124 |
+
m=export_bruker_minispecmq20_contract_metadata()
|
| 125 |
+
for k in UNSUPPORTED:self.assertTrue(all(v=='absent' for v in m['capabilities'][k]['implementation'].values()))
|
| 126 |
+
if __name__=='__main__':unittest.main()
|
| 127 |
+
|
tests/test_asset_buchi_encapsulatorb.py
ADDED
|
@@ -0,0 +1,89 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import copy,math,sys,unittest
|
| 2 |
+
from pathlib import Path
|
| 3 |
+
ROOT=Path(__file__).resolve().parents[1];sys.path.insert(0,str(ROOT/'scripts'))
|
| 4 |
+
from asset_runtime.buchi_encapsulatorb import *
|
| 5 |
+
def configured(fast=True,**sample):
|
| 6 |
+
r=BuchiEncapsulatorbRuntime()
|
| 7 |
+
for n,e in [('plant',PLANT_EXAMPLE),('method',dict(METHOD_EXAMPLE,target_volume_m3=.5e-6 if fast else 5e-6)),('sample',dict(SAMPLE_EXAMPLE,**sample)),('bath',BATH_EXAMPLE),('air',GAS_EXAMPLE)]:r.invoke(n+'.configure',**e)
|
| 8 |
+
r.invoke('power.set',enabled=True);r.invoke('vibration.toggle');r.invoke('electrostatic.toggle');r.invoke('air.set_pressure',gauge_pa=40000.);r.step(4);return r
|
| 9 |
+
def run_batch(r=None):
|
| 10 |
+
r=r or configured();r.invoke('acquisition.start');r.invoke('valve.set_opening',fraction=1.)
|
| 11 |
+
for _ in range(1000):
|
| 12 |
+
r.step(.1)
|
| 13 |
+
if r.phase!='running':break
|
| 14 |
+
r.invoke('valve.set_opening',fraction=0.);r.step(.3);return r
|
| 15 |
+
def balances(r):
|
| 16 |
+
p=r._product();v=[]
|
| 17 |
+
for n in ['polymer','payload','water']:v.append(p['initial_'+n+'_kg']-sum(p[k+'_'+n+'_kg'] for k in ['feed','bead','bath','collected']))
|
| 18 |
+
v += [p['initial_ca_mol']-p['free_ca_mol']-p['bead_ca_mol']-p['collected_ca_mol'],p['initial_gas_mol']-p['supply_gas_mol']-p['bottle_gas_mol']-p['vented_gas_mol'],(r.sample['volume_m3'] if r.sample else 0.)-r.feed_volume-r.emitted,p['thermal_residual_j']];return v
|
| 19 |
+
class B390Tests(unittest.TestCase):
|
| 20 |
+
def test_standard_no_syringe_or_sterile(self):self.assertFalse(any('syringe' in k or 'sterile' in k for k in CAPS))
|
| 21 |
+
def test_setup_required(self):
|
| 22 |
+
with self.assertRaises(ActionRejected):BuchiEncapsulatorbRuntime().invoke('acquisition.start')
|
| 23 |
+
def test_heater_target_only(self):
|
| 24 |
+
r=configured();r.invoke('thermal.set_temperature',temperature_k=333.15);self.assertEqual(r.h_temp,298.15)
|
| 25 |
+
def test_heater_actual_lag_and_energy(self):
|
| 26 |
+
r=configured();r.invoke('thermal.toggle');r.step(20);self.assertGreater(r.h_temp,r.n_temp);self.assertGreater(r.n_temp,298.15);self.assertLess(r.h_temp,313.15);self.assertLess(abs(balances(r)[-1]),1e-7)
|
| 27 |
+
def test_no_active_cooling(self):
|
| 28 |
+
r=configured();r.invoke('thermal.set_temperature',temperature_k=283.15);r.invoke('thermal.toggle');r.step(10);self.assertEqual(r.h_temp,298.15)
|
| 29 |
+
def test_heating_delay(self):
|
| 30 |
+
r=BuchiEncapsulatorbRuntime();r.invoke('plant.configure',**dict(PLANT_EXAMPLE,heater_delay_s=120.));r.invoke('power.set',enabled=True);r.invoke('thermal.toggle');r.step(20);self.assertEqual(r.h_temp,298.15)
|
| 31 |
+
def test_pressure_target_only(self):
|
| 32 |
+
r=configured();p=r.pressure;r.invoke('air.set_pressure',gauge_pa=80000.);self.assertEqual(r.pressure,p);r.step(.1);self.assertLess(r.pressure,80000)
|
| 33 |
+
def test_start_no_auto_flow(self):
|
| 34 |
+
r=configured();r.invoke('acquisition.start');r.step(3);self.assertEqual(r.flow,0);self.assertEqual(r.emitted,0)
|
| 35 |
+
def test_valve_target_only(self):
|
| 36 |
+
r=configured();r.invoke('valve.set_opening',fraction=1.);self.assertEqual(r.valve_angle,0);self.assertEqual(r.emitted,0)
|
| 37 |
+
def test_no_false_flow_sensor(self):self.assertNotIn('truth.flow_m3_s',configured().read())
|
| 38 |
+
def test_weber_stable(self):
|
| 39 |
+
r=run_batch();self.assertEqual(r.phase,'succeeded');self.assertGreater(len(r.packets),0);self.assertTrue(.0005<r._product()['mean_bead_diameter_m']<.0008)
|
| 40 |
+
def test_particle_volume_identity(self):
|
| 41 |
+
r=run_batch();self.assertTrue(all(abs(x['count']*math.pi*x['d']**3/6-x['volume'])<1e-16 for x in r.packets))
|
| 42 |
+
def test_material_gas_ca_balances(self):self.assertTrue(all(abs(v)<1e-9 for v in balances(run_batch())))
|
| 43 |
+
def test_higher_frequency_smaller_drops(self):
|
| 44 |
+
a=run_batch();b=configured();b.invoke('vibration.set_frequency',frequency_hz=950.);b=run_batch(b);self.assertLess(b._product()['mean_bead_diameter_m'],a._product()['mean_bead_diameter_m'])
|
| 45 |
+
def test_unstable_jet_not_fake_beads(self):
|
| 46 |
+
r=configured();r.invoke('vibration.set_frequency',frequency_hz=40.);r.invoke('valve.set_opening',fraction=1.);r.step(1);n=len(r.packets);m=r.bath_material[0];r.step(2);self.assertEqual(len(r.packets),n);self.assertGreater(r.ratio,1.3);self.assertGreater(r.bath_material[0],m)
|
| 47 |
+
def test_poweroff_does_not_close_manual_flow(self):
|
| 48 |
+
r=configured();r.invoke('valve.set_opening',fraction=1.);r.step(1);r.invoke('power.set',enabled=False);v=r.emitted;r.step(1);self.assertGreater(r.emitted,v);self.assertEqual(r.frequency,0);self.assertEqual(r.voltage,0)
|
| 49 |
+
def test_cancel_keeps_flow_and_material(self):
|
| 50 |
+
r=configured();r.invoke('acquisition.start');r.invoke('valve.set_opening',fraction=1.);r.step(1);v=r.emitted;r.invoke('acquisition.stop');self.assertEqual(r.emitted,v);r.step(.5);self.assertGreater(r.emitted,v);self.assertEqual(r.phase,'cancelled')
|
| 51 |
+
def test_success_keeps_flow(self):
|
| 52 |
+
r=configured();r.invoke('acquisition.start');r.invoke('valve.set_opening',fraction=1.);r.step(7);self.assertEqual(r.phase,'succeeded');v=r.emitted;r.step(.2);self.assertGreater(r.emitted,v)
|
| 53 |
+
def test_gelation_ca_limited(self):
|
| 54 |
+
r=configured();r.ca_initial=r.ca_free=0.;r=run_batch(r);r.step(20);self.assertTrue(all(x['gel']==0 for x in r.packets))
|
| 55 |
+
def test_cure_and_leak(self):
|
| 56 |
+
r=run_batch();b=r._product();r.step(30);a=r._product();self.assertGreater(a['mature_bead_count'],b['mature_bead_count']);self.assertLess(a['bead_payload_kg'],b['bead_payload_kg']);self.assertGreater(a['bath_payload_kg'],b['bath_payload_kg'])
|
| 57 |
+
def test_electrostatic_requires_ground(self):
|
| 58 |
+
r=BuchiEncapsulatorbRuntime();r.invoke('bath.configure',**dict(BATH_EXAMPLE,grounded=False))
|
| 59 |
+
with self.assertRaises(ActionRejected):r.invoke('electrostatic.toggle')
|
| 60 |
+
def test_gap_no_live_adjustment(self):
|
| 61 |
+
with self.assertRaises(ActionRejected):configured().invoke('electrode.set_gap',gap_m=.006)
|
| 62 |
+
def test_electrode_target_motion(self):
|
| 63 |
+
r=configured();r.invoke('electrostatic.toggle');r.invoke('electrode.set_gap',gap_m=.008);self.assertEqual(r.gap,.003);r.step(.2);self.assertAlmostEqual(r.gap,.005)
|
| 64 |
+
def test_collect_requires_hv_off(self):
|
| 65 |
+
r=run_batch();r.step(20)
|
| 66 |
+
with self.assertRaises(ActionRejected):r.invoke('product.collect',**CAPS['product.collect'][6])
|
| 67 |
+
def test_collect_finite(self):
|
| 68 |
+
r=run_batch();r.step(20);r.invoke('electrostatic.toggle');r.invoke('product.collect',**CAPS['product.collect'][6]);self.assertGreater(r.collected[1],0);self.assertTrue(all(abs(v)<1e-9 for v in balances(r)))
|
| 69 |
+
def test_dead_volume(self):
|
| 70 |
+
r=configured(volume_m3=5e-6,payload_diffusion_m2_s=0.);r.invoke('vibration.toggle');r.invoke('valve.set_opening',fraction=1.);r.step(70);self.assertAlmostEqual(r.feed_volume,2e-6,13);self.assertTrue(all(abs(v)<1e-9 for v in balances(r)))
|
| 71 |
+
def test_finite_gas(self):
|
| 72 |
+
r=configured();r.gas_initial-=r.gas_supply;r.gas_supply=0.;r.invoke('air.set_pressure',gauge_pa=100000.);r.invoke('valve.set_opening',fraction=1.);r.step(2);self.assertEqual(r.gas_supply,0);self.assertTrue(all(abs(v)<1e-9 for v in balances(r)))
|
| 73 |
+
def test_identity_library50(self):
|
| 74 |
+
r=configured();self.assertEqual(len(r.templates),50);self.assertEqual(r.invoke('reference.lookup',substance_id='caffeine')['evidence'],'derived')
|
| 75 |
+
def test_no_false_payload_transport_reference(self):self.assertTrue(all(x['diffusivity_m2_s'] is None and x['encapsulation_efficiency'] is None for x in configured().templates.values()))
|
| 76 |
+
def test_pure_queries(self):
|
| 77 |
+
r=configured();b=r.debug_snapshot();r.read();r.describe();r.invoke('encapsulation.measure');self.assertEqual(b,r.debug_snapshot())
|
| 78 |
+
def test_rejection_atomic(self):
|
| 79 |
+
r=configured();b=r.debug_snapshot()
|
| 80 |
+
with self.assertRaises(ActionRejected):r.invoke('nozzle.configure',diameter_m=.002)
|
| 81 |
+
self.assertEqual(b,r.debug_snapshot())
|
| 82 |
+
def test_instances(self):
|
| 83 |
+
a=configured();b=configured();a.invoke('valve.set_opening',fraction=1.);a.step(1);self.assertEqual(b.emitted,0)
|
| 84 |
+
def test_bad_step(self):
|
| 85 |
+
for x in [True,-1,float('nan'),float('inf')]:
|
| 86 |
+
with self.assertRaises(ActionRejected):configured().step(x)
|
| 87 |
+
def test_zero_step(self):
|
| 88 |
+
r=configured();b=r.debug_snapshot();r.step(0);self.assertEqual(b,r.debug_snapshot())
|
| 89 |
+
if __name__=='__main__':unittest.main()
|
tests/test_asset_buchi_hydrolexh.py
ADDED
|
@@ -0,0 +1,106 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import copy,math,sys,unittest
|
| 2 |
+
from pathlib import Path
|
| 3 |
+
ROOT=Path(__file__).resolve().parents[1];sys.path.insert(0,str(ROOT/'scripts'))
|
| 4 |
+
from asset_runtime.buchi_hydrolexh import *
|
| 5 |
+
def configured(n=1,fast=False):
|
| 6 |
+
r=BuchiHydrolexhRuntime();p=copy.deepcopy(PLANT_EXAMPLE)
|
| 7 |
+
if fast:p.update(heater_capacity_J_K=100.,sample_capacity_J_K=10.,plate_UA_W_K=0.,sample_UA_W_K=0.,contact_UA_W_K=1.,filter_rate_m3_s=10e-6)
|
| 8 |
+
r.invoke('plant.configure',**p);m=copy.deepcopy(METHOD_EXAMPLE)
|
| 9 |
+
if fast:m['hydrolysis_s']=2.
|
| 10 |
+
r.invoke('method.configure',**m);r.invoke('water.configure',volume_m3=.005);r.invoke('ventilation.set',enabled=True)
|
| 11 |
+
for i in range(1,n+1):r.invoke('sample.configure',**example_sample(i));r.invoke('valve.set',position=i,open=True)
|
| 12 |
+
r.invoke('power.set',enabled=True);r.invoke('thermal.set_mode',mode='preheat');r.step(600);r.invoke('rack.set_raised',raised=False);r.step(1);return r
|
| 13 |
+
def run_cycle(r):
|
| 14 |
+
r.invoke('acquisition.start')
|
| 15 |
+
for _ in range(120):
|
| 16 |
+
r.step(30.)
|
| 17 |
+
if r.phase!='running':break
|
| 18 |
+
assert r.phase=='succeeded',(r.phase,r.elapsed_s,r.heater)
|
| 19 |
+
return r
|
| 20 |
+
def filter_once(r):
|
| 21 |
+
r.invoke('rack.set_raised',raised=True);r.step(1);r.invoke('vacuum.set',enabled=True);r.invoke('filtration.start');r.step(100);assert r.stage=='filtered';return r
|
| 22 |
+
def rinse_all(r):
|
| 23 |
+
for _ in range(4):
|
| 24 |
+
for i in r.channels:r.invoke('rinse.add',position=i,volume_m3=100e-6)
|
| 25 |
+
r.invoke('filtration.start');r.step(100)
|
| 26 |
+
return r
|
| 27 |
+
def balances(r):
|
| 28 |
+
p=r.invoke('product.read');return [p['initial_fat_kg']-sum(p[k] for k in ['bound_in_vessels_kg','free_in_vessels_kg','retained_bound_kg','retained_extractable_kg','waste_fat_kg','collected_fat_kg']),p['initial_acid_mol']-p['remaining_acid_mol']-p['waste_acid_mol']-p['collected_acid_mol'],p['initial_volume_m3']-p['remaining_volume_m3']-p['waste_volume_m3']-p['collected_volume_m3'],p['initial_dry_solid_kg']-p['remaining_dry_solid_kg']-p['collected_dry_solid_kg'],p['electrical_J']+p['rinse_sensible_J']-p['storage_J']-p['loss_J']-p['boiling_J']]
|
| 29 |
+
class TestBuchiHydrolexh(unittest.TestCase):
|
| 30 |
+
def reject(self,r,cap,**a):
|
| 31 |
+
before=r.debug_snapshot()
|
| 32 |
+
with self.assertRaises(ActionRejected):r.invoke(cap,**a)
|
| 33 |
+
self.assertEqual(before,r.debug_snapshot())
|
| 34 |
+
def test_schema_counts(self):self.assertEqual(len(CAPS),19);self.assertEqual(len(SLOTS),25)
|
| 35 |
+
def test_real_library(self):
|
| 36 |
+
r=BuchiHydrolexhRuntime();self.assertEqual(len(r.templates),54);self.assertAlmostEqual(r.invoke('reference.lookup',substance_id='buchi_milk_powder')['fat_mass_fraction'],.2427)
|
| 37 |
+
def test_config_required(self):self.reject(BuchiHydrolexhRuntime(),'acquisition.start')
|
| 38 |
+
def test_plant_assumption_consent(self):
|
| 39 |
+
a=dict(PLANT_EXAMPLE,accept_uncalibrated_model=False);self.reject(BuchiHydrolexhRuntime(),'plant.configure',**a)
|
| 40 |
+
def test_temperature_target_not_invented(self):self.reject(BuchiHydrolexhRuntime(),'thermal.set_temperature',temperature_K=500.)
|
| 41 |
+
def test_settings_no_time(self):
|
| 42 |
+
r=BuchiHydrolexhRuntime();r.invoke('plant.configure',**PLANT_EXAMPLE);self.assertEqual(r.time_s,0);self.assertEqual(r.heater,PLANT_EXAMPLE['ambient_K'])
|
| 43 |
+
def test_samples_range(self):
|
| 44 |
+
r=BuchiHydrolexhRuntime();r.invoke('plant.configure',**PLANT_EXAMPLE)
|
| 45 |
+
for a in [dict(example_sample(),position=7),dict(example_sample(),sample_mass_kg=.011),dict(example_sample(),sample_liquid_m3=51e-6),dict(example_sample(),position=True)]:self.reject(r,'sample.configure',**a)
|
| 46 |
+
def test_duplicate_load(self):
|
| 47 |
+
r=BuchiHydrolexhRuntime();r.invoke('plant.configure',**PLANT_EXAMPLE);r.invoke('sample.configure',**example_sample());self.reject(r,'sample.configure',**example_sample())
|
| 48 |
+
def test_unknown_reference(self):
|
| 49 |
+
r=BuchiHydrolexhRuntime();r.invoke('plant.configure',**PLANT_EXAMPLE);self.reject(r,'sample.configure',**dict(example_sample(),substance_id='fake'))
|
| 50 |
+
def test_preheat_guard(self):
|
| 51 |
+
r=configured(fast=True);r.preheat=599.;self.reject(r,'acquisition.start')
|
| 52 |
+
def test_unused_valve_guard(self):
|
| 53 |
+
r=configured(fast=True);r.invoke('valve.set',position=6,open=True);self.reject(r,'acquisition.start')
|
| 54 |
+
def test_joint_only_step(self):
|
| 55 |
+
r=BuchiHydrolexhRuntime();r.invoke('rack.set_raised',raised=False);self.assertEqual(r.rack_fraction,1);r.step(.1);self.assertAlmostEqual(r.rack_fraction,.8)
|
| 56 |
+
def test_six_position_default_cycle(self):
|
| 57 |
+
r=run_cycle(configured(6));self.assertAlmostEqual(r.elapsed_s,1800.,places=6);self.assertLess(r.time_s,3500);self.assertEqual(r.mode,'off');self.assertTrue(all(c['free']>0 for c in r.channels.values()))
|
| 58 |
+
def test_no_fat_measurement(self):
|
| 59 |
+
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'))
|
| 60 |
+
def test_all_ledgers(self):
|
| 61 |
+
r=rinse_all(filter_once(run_cycle(configured(6,True))));r.invoke('product.collect',position=1,fraction=.5,recipient_id='out')
|
| 62 |
+
for v in balances(r)[:4]:self.assertLess(abs(v),1e-9)
|
| 63 |
+
self.assertLess(abs(balances(r)[4]),1e-5)
|
| 64 |
+
def test_matrix_specific_release(self):
|
| 65 |
+
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)
|
| 66 |
+
def test_cancel_preserves_partial(self):
|
| 67 |
+
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')
|
| 68 |
+
def test_power_interrupt(self):
|
| 69 |
+
r=configured(fast=True);r.invoke('acquisition.start');r.invoke('power.set',enabled=False);self.assertEqual(r.phase,'cancelled');self.assertEqual(r.mode,'off')
|
| 70 |
+
def test_ventilation_fault(self):
|
| 71 |
+
r=configured(fast=True);r.invoke('acquisition.start');r.invoke('ventilation.set',enabled=False);self.assertEqual(r.phase,'failed');self.assertFalse(r.vacuum)
|
| 72 |
+
def test_raise_busy(self):
|
| 73 |
+
r=configured(fast=True);r.invoke('acquisition.start');self.reject(r,'rack.set_raised',raised=True)
|
| 74 |
+
def test_vacuum_early_reject(self):
|
| 75 |
+
r=configured(fast=True);r.invoke('acquisition.start');self.reject(r,'vacuum.set',enabled=True)
|
| 76 |
+
def test_filter_requires_raise(self):
|
| 77 |
+
r=run_cycle(configured(fast=True));self.reject(r,'filtration.start')
|
| 78 |
+
def test_flow_only_step(self):
|
| 79 |
+
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)
|
| 80 |
+
def test_collect_before_rinse(self):
|
| 81 |
+
r=filter_once(run_cycle(configured(fast=True)));self.reject(r,'product.collect',position=1,fraction=1.,recipient_id='out')
|
| 82 |
+
def test_water_finite(self):
|
| 83 |
+
r=filter_once(run_cycle(configured(fast=True)));r.water=0.;self.reject(r,'rinse.add',position=1,volume_m3=100e-6)
|
| 84 |
+
def test_filtered_holdup(self):
|
| 85 |
+
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)
|
| 86 |
+
def test_cstr_wash(self):
|
| 87 |
+
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)
|
| 88 |
+
def test_collect_repeat_finite(self):
|
| 89 |
+
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)
|
| 90 |
+
def test_agent_truth_filter(self):
|
| 91 |
+
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'],{})
|
| 92 |
+
def test_idempotent_request(self):
|
| 93 |
+
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)
|
| 94 |
+
def test_unknown_instance(self):
|
| 95 |
+
r=BuchiHydrolexhRuntime();s=r.session();self.assertEqual(s.invoke(instance_id='other',capability_id='power.toggle',arguments={},request_id='x')['error']['code'],'UNKNOWN_INSTANCE')
|
| 96 |
+
def test_instance_isolation(self):
|
| 97 |
+
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)
|
| 98 |
+
def test_step_invalid(self):
|
| 99 |
+
r=BuchiHydrolexhRuntime()
|
| 100 |
+
for v in [-1,float('nan'),float('inf'),True,7201]:
|
| 101 |
+
with self.assertRaises(ActionRejected):r.step(v)
|
| 102 |
+
def test_read_never_steps(self):
|
| 103 |
+
r=configured(fast=True);t=r.time_s
|
| 104 |
+
for _ in range(10):r.session().read(instance_id=r.instance_id)
|
| 105 |
+
self.assertEqual(r.time_s,t)
|
| 106 |
+
if __name__=='__main__':unittest.main()
|
tests/test_asset_ch_chi440c.py
ADDED
|
@@ -0,0 +1,71 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from pathlib import Path
|
| 2 |
+
import sys,unittest,copy,importlib.util,math
|
| 3 |
+
ROOT=Path(__file__).resolve().parents[1];sys.path.insert(0,str(ROOT/'scripts'))
|
| 4 |
+
from asset_runtime.ch_chi440c import *
|
| 5 |
+
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)
|
| 6 |
+
OBSERVED=set()
|
| 7 |
+
def call(r,k,**a):
|
| 8 |
+
v=r.invoke(k,**a);err=tool.validate_value(v,CAPS[k][1]);assert not err,err;OBSERVED.add(k);return v
|
| 9 |
+
def prepared(crystal=None,method=None,sample=None):
|
| 10 |
+
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
|
| 11 |
+
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')
|
| 12 |
+
class EQCM(unittest.TestCase):
|
| 13 |
+
def test_metadata_and_real_templates(self):
|
| 14 |
+
r=prepared();m=r.describe()
|
| 15 |
+
for c in m['capabilities'].values():self.assertEqual(tool.validate_value(c['example_arguments'],c['input_schema']),[])
|
| 16 |
+
for k,v in r.read('evaluator').items():self.assertEqual(tool.validate_value(v,m['state_slots'][k]['value_schema']),[])
|
| 17 |
+
self.assertEqual(len(r.templates),96)
|
| 18 |
+
for sid in r.templates:self.assertGreater(call(r,'template.read',substance_id=sid)['molar_mass_kg_mol'],0.)
|
| 19 |
+
def test_faraday_sauerbrey_independent(self):
|
| 20 |
+
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'])
|
| 21 |
+
def test_fixed_sampling_partition(self):
|
| 22 |
+
a=prepared();b=prepared()
|
| 23 |
+
for r in [a,b]:call(r,'acquisition.start')
|
| 24 |
+
a.step(3.)
|
| 25 |
+
for _ in range(1000):b.step(.003)
|
| 26 |
+
self.assertEqual(a.points,b.points);self.assertEqual(a._ledger(),b._ledger())
|
| 27 |
+
def test_voltage_mode_bv_current_and_limits(self):
|
| 28 |
+
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)
|
| 29 |
+
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.)
|
| 30 |
+
def test_galvanostatic_potential_limit(self):
|
| 31 |
+
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.)
|
| 32 |
+
def test_atomic_limits_sampling_and_types(self):
|
| 33 |
+
r=prepared()
|
| 34 |
+
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')})]:
|
| 35 |
+
before=copy.deepcopy(r.__dict__)
|
| 36 |
+
with self.assertRaises(ActionRejected):r.invoke(k,**a)
|
| 37 |
+
self.assertEqual(r.__dict__,before)
|
| 38 |
+
for dt in [True,float('nan'),-1.]:
|
| 39 |
+
with self.assertRaises(ActionRejected):r.step(dt)
|
| 40 |
+
def test_maximum_1khz_boundary(self):
|
| 41 |
+
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')
|
| 42 |
+
def test_finite_exhaustion_preserves_transfers(self):
|
| 43 |
+
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)
|
| 44 |
+
def test_negative_current_without_film(self):
|
| 45 |
+
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.)
|
| 46 |
+
def test_cancellation_unload_clean_ledger(self):
|
| 47 |
+
r=prepared();call(r,'acquisition.start');r.step(1.);call(r,'acquisition.stop');l=r._ledger();r.step(10.);self.assertEqual(l,r._ledger())
|
| 48 |
+
with self.assertRaisesRegex(ActionRejected,'LID_OPEN_REQUIRED'):r.invoke('sample.unload')
|
| 49 |
+
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)
|
| 50 |
+
def test_baseline_does_not_clean_or_read_truth(self):
|
| 51 |
+
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.)
|
| 52 |
+
def test_adsorption_finite_analytic(self):
|
| 53 |
+
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'])
|
| 54 |
+
x=0.;dt=1e-4;n=ADSORPTION_EXAMPLE['volume_m3']*ADSORPTION_EXAMPLE['concentration_mol_m3'];s=ADSORPTION_EXAMPLE
|
| 55 |
+
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)
|
| 56 |
+
self.assertAlmostEqual(r.film,x,delta=1e-14)
|
| 57 |
+
def test_adsorption_repeated_root_and_desorption(self):
|
| 58 |
+
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)
|
| 59 |
+
def test_thinfilm_domain_failure_keeps_mass(self):
|
| 60 |
+
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())
|
| 61 |
+
def test_session_truth_dedup_owner_and_stale(self):
|
| 62 |
+
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'))
|
| 63 |
+
with self.assertRaises(ActionRejected):b.poll(v['operation_id'])
|
| 64 |
+
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'])
|
| 65 |
+
def test_instances_busy_pure_and_unsupported(self):
|
| 66 |
+
r=prepared();other=prepared();before=copy.deepcopy(other.__dict__);call(r,'acquisition.start')
|
| 67 |
+
with self.assertRaisesRegex(ActionRejected,'BUSY'):r.invoke('lid.set',lift_m=.05)
|
| 68 |
+
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)
|
| 69 |
+
for k in UNSUPPORTED:
|
| 70 |
+
with self.assertRaisesRegex(ActionRejected,'UNSUPPORTED'):r.invoke(k)
|
| 71 |
+
if __name__=='__main__':unittest.main()
|
tests/test_asset_ch_chi920d.py
ADDED
|
@@ -0,0 +1,76 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from pathlib import Path
|
| 2 |
+
import sys,unittest,copy,importlib.util,math
|
| 3 |
+
ROOT=Path(__file__).resolve().parents[1];sys.path.insert(0,str(ROOT/'scripts'))
|
| 4 |
+
from asset_runtime.ch_chi920d import *
|
| 5 |
+
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)
|
| 6 |
+
OBSERVED=set()
|
| 7 |
+
def call(r,k,**a):
|
| 8 |
+
v=r.invoke(k,**a);err=tool.validate_value(v,CAPS[k][1]);assert not err,err;OBSERVED.add(k);return v
|
| 9 |
+
def prepared(plant=None,method=None,sample=None):
|
| 10 |
+
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
|
| 11 |
+
class SECM(unittest.TestCase):
|
| 12 |
+
def test_metadata_schema(self):
|
| 13 |
+
r=prepared();m=r.describe()
|
| 14 |
+
for k,c in m['capabilities'].items():self.assertEqual(tool.validate_value(c['example_arguments'],c['input_schema']),[],k)
|
| 15 |
+
for k,v in r.read('evaluator').items():self.assertEqual(tool.validate_value(v,m['state_slots'][k]['value_schema']),[],k)
|
| 16 |
+
def test_pure_queries_and_targets(self):
|
| 17 |
+
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))
|
| 18 |
+
def test_position_quantization_and_range(self):
|
| 19 |
+
for fine,res in [(True,1.6e-9),(False,8e-9)]:
|
| 20 |
+
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'])
|
| 21 |
+
before=copy.deepcopy(r.__dict__)
|
| 22 |
+
with self.assertRaises(ActionRejected):r.invoke('stage.move',x_m=.025001,y_m=0,z_m=.005)
|
| 23 |
+
self.assertEqual(r.__dict__,before)
|
| 24 |
+
def test_limits_atomic_and_bad_types(self):
|
| 25 |
+
r=prepared()
|
| 26 |
+
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')))]:
|
| 27 |
+
before=copy.deepcopy(r.__dict__)
|
| 28 |
+
with self.assertRaises(ActionRejected):r.invoke(k,**a)
|
| 29 |
+
self.assertEqual(r.__dict__,before)
|
| 30 |
+
for dt in [True,float('nan'),-1.,float('inf')]:
|
| 31 |
+
with self.assertRaises(ActionRejected):r.step(dt)
|
| 32 |
+
def test_all_59_templates(self):
|
| 33 |
+
r=prepared();self.assertEqual(len(r.templates),59)
|
| 34 |
+
for sid in r.templates:self.assertGreater(call(r,'template.read',substance_id=sid)['diffusion_m2_s'],0)
|
| 35 |
+
def test_complete_conservation_and_map(self):
|
| 36 |
+
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))
|
| 37 |
+
def test_cancel_partial_and_unload(self):
|
| 38 |
+
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)
|
| 39 |
+
with self.assertRaisesRegex(ActionRejected,'RETRACT_REQUIRED'):r.invoke('sample.unload')
|
| 40 |
+
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)
|
| 41 |
+
def test_partition_invariance(self):
|
| 42 |
+
rs=[prepared(),prepared()]
|
| 43 |
+
for r in rs:call(r,'acquisition.start')
|
| 44 |
+
rs[0].step(20.)
|
| 45 |
+
for _ in range(2000):rs[1].step(.01)
|
| 46 |
+
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)
|
| 47 |
+
self.assertEqual([p['tip_current_a'] for p in rs[0].points],[p['tip_current_a'] for p in rs[1].points])
|
| 48 |
+
def test_approach_current_and_guard(self):
|
| 49 |
+
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'])
|
| 50 |
+
call(r,'method.configure',**dict(METHOD_EXAMPLE,path=[dict(x_m=0,y_m=0,z_m=0.)]));before=copy.deepcopy(r.__dict__)
|
| 51 |
+
with self.assertRaisesRegex(ActionRejected,'COLLISION_GUARD'):r.invoke('acquisition.start')
|
| 52 |
+
self.assertEqual(r.__dict__,before)
|
| 53 |
+
def test_negative_feedback(self):
|
| 54 |
+
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.)
|
| 55 |
+
def test_steady_dwell_and_current_limit(self):
|
| 56 |
+
r=prepared(method=dict(METHOD_EXAMPLE,dwell_s=.001))
|
| 57 |
+
with self.assertRaisesRegex(ActionRejected,'STEADY_STATE_DWELL'):r.invoke('acquisition.start')
|
| 58 |
+
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.)
|
| 59 |
+
def test_total_two_channel_continuous_limit(self):
|
| 60 |
+
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.)
|
| 61 |
+
def test_kinetics_uses_observed_currents(self):
|
| 62 |
+
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)
|
| 63 |
+
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)
|
| 64 |
+
def test_session_truth_owner_stale(self):
|
| 65 |
+
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'))
|
| 66 |
+
with self.assertRaises(ActionRejected):b.poll(v['operation_id'])
|
| 67 |
+
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)
|
| 68 |
+
def test_two_instances_and_busy(self):
|
| 69 |
+
r=prepared();other=prepared();before=copy.deepcopy(other.__dict__);call(r,'acquisition.start')
|
| 70 |
+
with self.assertRaisesRegex(ActionRejected,'BUSY'):r.invoke('stage.move',x_m=0,y_m=0,z_m=.005)
|
| 71 |
+
r.step(10);self.assertEqual(other.__dict__,before)
|
| 72 |
+
def test_unsupported(self):
|
| 73 |
+
r=prepared()
|
| 74 |
+
for k in UNSUPPORTED:
|
| 75 |
+
with self.assertRaisesRegex(ActionRejected,'UNSUPPORTED'):r.invoke(k)
|
| 76 |
+
if __name__=='__main__':unittest.main()
|
tests/test_asset_cytiva_nanoassemblrignite.py
ADDED
|
@@ -0,0 +1,151 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""CHEM-060 independent regression tests; finite material, process clock and trust boundary."""
|
| 2 |
+
import copy,json,math,sys,unittest
|
| 3 |
+
from pathlib import Path
|
| 4 |
+
ROOT=Path(__file__).resolve().parents[1];sys.path.insert(0,str(ROOT/'scripts'))
|
| 5 |
+
from asset_runtime.cytiva_nanoassemblrignite import *
|
| 6 |
+
def prepared(dilution=True,method=None):
|
| 7 |
+
h=CytivaNanoassemblrigniteRuntime();h.invoke('plant.configure',**PLANT_EXAMPLE)
|
| 8 |
+
h.invoke('cartridge.install',dilution=dilution,cartridge_id='chip',accept_host_attachment=True)
|
| 9 |
+
for x in SYRINGE_EXAMPLES:h.invoke('syringe.load',**x)
|
| 10 |
+
h.invoke('tubes.install',sample_capacity_m3=50e-6,accept_host_attachment=True)
|
| 11 |
+
h.invoke('heating.configure',installed=True,accept_host_attachment=True)
|
| 12 |
+
h.invoke('method.configure',**(method or dict(METHOD_EXAMPLE,dilution_ratio=1. if dilution else 0.)))
|
| 13 |
+
h.invoke('block.set',opened=False);h.invoke('lid.set',opened=False);h.invoke('power.set',enabled=True);return h
|
| 14 |
+
class IgniteTests(unittest.TestCase):
|
| 15 |
+
def atomic(self,h,k,**a):
|
| 16 |
+
before=h.debug_snapshot()
|
| 17 |
+
with self.assertRaises(ActionRejected):h.invoke(k,**a)
|
| 18 |
+
self.assertEqual(before,h.debug_snapshot())
|
| 19 |
+
def conserve(self,h):
|
| 20 |
+
p=h.invoke('product.read')
|
| 21 |
+
for suffix in ['m3','kg','solute_kg']:
|
| 22 |
+
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)
|
| 23 |
+
self.assertAlmostEqual(p['heater_input_j'],p['thermal_loss_j']+p['sensible_j'],delta=2e-7)
|
| 24 |
+
def test_default_conservation(self):
|
| 25 |
+
h=prepared();h.invoke('acquisition.start');h.step(60);self.conserve(h);self.assertEqual(h.phase,'succeeded')
|
| 26 |
+
def test_exact_routing_and_holdup(self):
|
| 27 |
+
h=prepared();h.invoke('acquisition.start');h.step(60)
|
| 28 |
+
self.assertAlmostEqual(sum(h.vols['sample']),3.47e-6,delta=1e-14);self.assertAlmostEqual(sum(h.vols['waste']),.5e-6,delta=1e-14)
|
| 29 |
+
self.assertAlmostEqual(sum(h.vols['mixer']),20e-9,delta=1e-15);self.assertAlmostEqual(sum(h.vols['dilution']),10e-9,delta=1e-15)
|
| 30 |
+
def test_L_not_in_primary_mixer(self):
|
| 31 |
+
h=prepared();h.invoke('acquisition.start');h.step(30);self.assertEqual(h.vols['mixer'][0],0.);self.assertGreater(h.vols['dilution'][0],0.)
|
| 32 |
+
def test_base_chip_two_inputs(self):
|
| 33 |
+
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)
|
| 34 |
+
def test_incorrect_chip_topology_atomic(self):
|
| 35 |
+
h=prepared(False,dict(METHOD_EXAMPLE));self.atomic(h,'acquisition.start')
|
| 36 |
+
def test_20_flow_strictly_rejected(self):
|
| 37 |
+
h=prepared();self.atomic(h,'method.configure',**dict(METHOD_EXAMPLE,flow_m3_s=20e-6/60))
|
| 38 |
+
def test_just_below_20_accepted(self):
|
| 39 |
+
h=prepared();h.invoke('method.configure',**dict(METHOD_EXAMPLE,flow_m3_s=math.nextafter(20e-6/60,0.)))
|
| 40 |
+
def test_ignite_plus_ranges_rejected(self):
|
| 41 |
+
h=prepared()
|
| 42 |
+
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)
|
| 43 |
+
def test_method_low_flow_high_ratio(self):
|
| 44 |
+
h=prepared();h.invoke('method.configure',**dict(METHOD_EXAMPLE,flow_m3_s=.1e-6/60,flow_ratio_c_r=10.,dilution_ratio=1.))
|
| 45 |
+
def test_L_48_limit(self):
|
| 46 |
+
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))
|
| 47 |
+
def test_waste_sum_rejected(self):
|
| 48 |
+
h=prepared();self.atomic(h,'method.configure',**dict(METHOD_EXAMPLE,start_waste_equiv_m3=2e-6))
|
| 49 |
+
def test_all_waste_zero_sample(self):
|
| 50 |
+
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)
|
| 51 |
+
def test_no_waste_all_output_sample(self):
|
| 52 |
+
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.)
|
| 53 |
+
def test_finite_empty_rejection(self):
|
| 54 |
+
h=prepared(method=dict(METHOD_EXAMPLE,volume_m3=10e-6));self.atomic(h,'acquisition.start');self.assertFalse(h.used)
|
| 55 |
+
def test_tube_capacity_preflight(self):
|
| 56 |
+
h=prepared(method=dict(METHOD_EXAMPLE,start_waste_equiv_m3=2e-6,end_waste_equiv_m3=0.,dilution_ratio=4.))
|
| 57 |
+
h.vols['waste'][0]=10e-6
|
| 58 |
+
self.atomic(h,'acquisition.start')
|
| 59 |
+
def test_lid_interrupts_not_rejected(self):
|
| 60 |
+
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)
|
| 61 |
+
def test_power_loss_partial(self):
|
| 62 |
+
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)
|
| 63 |
+
def test_cancel_reset_no_refund(self):
|
| 64 |
+
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)]
|
| 65 |
+
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)])
|
| 66 |
+
def test_completed_paddles_home_plungers_consumed(self):
|
| 67 |
+
h=prepared();h.invoke('acquisition.start');h.step(60);self.assertEqual(h.paddle,[0.]*3);self.assertGreater(h._consumed(1),0.)
|
| 68 |
+
def test_single_use_no_second_run(self):
|
| 69 |
+
h=prepared();h.invoke('acquisition.start');h.step(60);self.atomic(h,'acquisition.start')
|
| 70 |
+
def test_prime_6mm_not_fixed_volume(self):
|
| 71 |
+
h=prepared();h.invoke('cartridge.prime');h.step(40)
|
| 72 |
+
for i in range(3):self.assertAlmostEqual(h._consumed(i),.006,delta=1e-10)
|
| 73 |
+
self.assertFalse(h.used);self.assertTrue(h.primed);self.assertEqual(sum(h.vols['sample']),0.);self.conserve(h)
|
| 74 |
+
def test_prime_then_formulate(self):
|
| 75 |
+
h=prepared();h.invoke('cartridge.prime');h.step(40);h.invoke('acquisition.start');h.step(60);self.conserve(h);self.assertTrue(h.used)
|
| 76 |
+
def test_loaded_source_rebind_rejected(self):
|
| 77 |
+
h=prepared();h.invoke('lid.set',opened=True);h.invoke('block.set',opened=True);h.invoke('syringe.unload',channel=1)
|
| 78 |
+
self.atomic(h,'syringe.load',**dict(SYRINGE_EXAMPLES[1],density_kg_m3=900.))
|
| 79 |
+
def test_syringe_stroke_limit(self):
|
| 80 |
+
h=CytivaNanoassemblrigniteRuntime();h.invoke('plant.configure',**PLANT_EXAMPLE);self.atomic(h,'syringe.load',**dict(SYRINGE_EXAMPLES[1],inner_diameter_m=.002))
|
| 81 |
+
def test_20ml_C_heated_configuration_not_assumed(self):
|
| 82 |
+
h=CytivaNanoassemblrigniteRuntime();h.invoke('plant.configure',**PLANT_EXAMPLE);self.atomic(h,'syringe.load',**dict(SYRINGE_EXAMPLES[1],capacity_m3=20e-6))
|
| 83 |
+
def test_invalid_solute_density_rejected(self):
|
| 84 |
+
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.))
|
| 85 |
+
def test_collect_and_dispose_conservation(self):
|
| 86 |
+
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')
|
| 87 |
+
for i in range(3):h.invoke('syringe.unload',channel=i)
|
| 88 |
+
self.conserve(h);self.assertEqual(sum(h.vols['mixer']),0.);self.assertGreater(sum(h.vols['collected_sample']),0.)
|
| 89 |
+
def test_heater_75_and_30_achievable(self):
|
| 90 |
+
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])
|
| 91 |
+
h.step(1200);self.assertAlmostEqual(h.temperature[0],318.15,places=6);self.assertAlmostEqual(h.temperature[1],348.15,places=6);self.conserve(h)
|
| 92 |
+
def test_heater_upper_invalid_atomic(self):
|
| 93 |
+
h=prepared();self.atomic(h,'heating.set',enabled=True,targets_k=[348.16,298.15])
|
| 94 |
+
def test_heater_option_required(self):
|
| 95 |
+
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)
|
| 96 |
+
def test_heat_no_fluid_size_prediction(self):
|
| 97 |
+
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)
|
| 98 |
+
def test_read_and_queries_are_pure(self):
|
| 99 |
+
h=prepared();before=h.debug_snapshot()
|
| 100 |
+
for k in ['formulation.measure','product.read']:h.invoke(k)
|
| 101 |
+
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())
|
| 102 |
+
def test_reference_methods_distinct(self):
|
| 103 |
+
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')
|
| 104 |
+
def test_unknown_reference_and_nan_atomic(self):
|
| 105 |
+
h=prepared();self.atomic(h,'reference.lookup',substance_id='missing');self.atomic(h,'method.configure',**dict(METHOD_EXAMPLE,volume_m3=float('nan')))
|
| 106 |
+
def test_permission_truth_filter(self):
|
| 107 |
+
h=prepared();s=h.session();self.assertNotIn('truth.ledger',s.describe(instance_id=h.instance_id)['state_slots'])
|
| 108 |
+
self.assertEqual(s.invoke(instance_id=h.instance_id,capability_id='product.read',arguments={},request_id='deny')['error']['code'],'ACCESS_DENIED')
|
| 109 |
+
with self.assertRaises(ActionRejected):s.read(instance_id=h.instance_id,state_ids=['truth.ledger'])
|
| 110 |
+
def test_session_idempotency_conflict(self):
|
| 111 |
+
h=prepared();s=h.session();kw=dict(instance_id=h.instance_id,capability_id='acquisition.start',arguments={},request_id='once')
|
| 112 |
+
first=s.invoke(**kw);snap=h.debug_snapshot();self.assertEqual(first,s.invoke(**kw));self.assertEqual(snap,h.debug_snapshot())
|
| 113 |
+
self.assertEqual(s.invoke(**dict(kw,capability_id='acquisition.stop'))['error']['code'],'REQUEST_CONFLICT')
|
| 114 |
+
def test_session_owner_poll_cancel(self):
|
| 115 |
+
h=prepared();a=h.session();h.register_principal('other');b=h.session('other')
|
| 116 |
+
op=a.invoke(instance_id=h.instance_id,capability_id='acquisition.start',arguments={},request_id='a')['operation_id'];h.step(12)
|
| 117 |
+
with self.assertRaises(ActionRejected):b.poll(op)
|
| 118 |
+
a.cancel(op,'cancel');self.assertEqual(a.poll(op)['status'],'cancelled');self.conserve(h)
|
| 119 |
+
def test_state_write_route(self):
|
| 120 |
+
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)
|
| 121 |
+
with self.assertRaises(ActionRejected):s.write(instance_id=h.instance_id,state_id='volume.sample_m3',value=1.,request_id='bad')
|
| 122 |
+
def test_foreign_instance_rejected(self):
|
| 123 |
+
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)
|
| 124 |
+
def test_clock_and_two_instances(self):
|
| 125 |
+
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)
|
| 126 |
+
def test_time_partition_consistency(self):
|
| 127 |
+
a=prepared();b=prepared();a.invoke('acquisition.start');b.invoke('acquisition.start');a.step(60)
|
| 128 |
+
for _ in range(6000):b.step(.01)
|
| 129 |
+
for loc in LOCS:
|
| 130 |
+
for x,y in zip(a.vols[loc],b.vols[loc]):self.assertAlmostEqual(x,y,delta=1e-11)
|
| 131 |
+
def test_zero_dt_and_invalid_dt(self):
|
| 132 |
+
h=prepared();snap=h.debug_snapshot();h.step(0);self.assertEqual(snap,h.debug_snapshot())
|
| 133 |
+
with self.assertRaises(ActionRejected):h.step(-1)
|
| 134 |
+
def test_block_open_cannot_close_lid(self):
|
| 135 |
+
h=prepared();h.invoke('lid.set',opened=True);h.invoke('block.set',opened=True);self.atomic(h,'lid.set',opened=False)
|
| 136 |
+
def test_exhaustion_exact_batch(self):
|
| 137 |
+
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)
|
| 138 |
+
def test_used_chip_identity_cannot_reset(self):
|
| 139 |
+
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')
|
| 140 |
+
self.atomic(h,'cartridge.install',dilution=True,cartridge_id='chip',accept_host_attachment=True)
|
| 141 |
+
h.invoke('cartridge.install',dilution=True,cartridge_id='fresh_chip',accept_host_attachment=True);self.assertFalse(h.used)
|
| 142 |
+
def test_full_20ml_volume_with_two_10ml_syringes(self):
|
| 143 |
+
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.))
|
| 144 |
+
h.invoke('lid.set',opened=True);h.invoke('block.set',opened=True)
|
| 145 |
+
for i in [1,2]:
|
| 146 |
+
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))
|
| 147 |
+
h.invoke('block.set',opened=False);h.invoke('lid.set',opened=False);h.invoke('acquisition.start');h.step(100)
|
| 148 |
+
self.assertEqual(h.phase,'succeeded');self.assertAlmostEqual(h.dispensed,20e-6,delta=1e-14);self.conserve(h)
|
| 149 |
+
if __name__=='__main__':unittest.main()
|
| 150 |
+
|
| 151 |
+
|
tests/test_asset_edinburgh_fls1000tcspc.py
ADDED
|
@@ -0,0 +1,214 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Independent numerical, event-clock, permission and negative-control regressions."""
|
| 2 |
+
import copy,hashlib,json,math,pickle,sys,unittest
|
| 3 |
+
from pathlib import Path
|
| 4 |
+
import numpy as np
|
| 5 |
+
from scipy.integrate import quad
|
| 6 |
+
ROOT=Path(__file__).resolve().parents[1];sys.path.insert(0,str(ROOT/'scripts'))
|
| 7 |
+
from asset_runtime.edinburgh_fls1000tcspc import *
|
| 8 |
+
def ready(sample=None,method=None,plant=None):
|
| 9 |
+
h=EdinburghFls1000tcspcRuntime()
|
| 10 |
+
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)
|
| 11 |
+
return h
|
| 12 |
+
def collect(sample=None,method=None):
|
| 13 |
+
h=ready(sample,method);h.invoke('irf.start' if (sample or SAMPLE_EXAMPLE)['kind']=='scatterer' else 'acquisition.start');h.step(3);return h
|
| 14 |
+
class TcspcTests(unittest.TestCase):
|
| 15 |
+
def rejected(self,h,k,a,code=None):
|
| 16 |
+
old=pickle.dumps(h.debug_snapshot())
|
| 17 |
+
with self.assertRaises(ActionRejected) as c:h.invoke(k,**a)
|
| 18 |
+
if code:self.assertEqual(str(c.exception),code)
|
| 19 |
+
self.assertEqual(pickle.dumps(h.debug_snapshot()),old)
|
| 20 |
+
def test_01_source_templates(self):
|
| 21 |
+
h=EdinburghFls1000tcspcRuntime();self.assertEqual(len(h.templates),67)
|
| 22 |
+
for t in h.templates.values():
|
| 23 |
+
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)
|
| 24 |
+
self.assertLess(abs(h.templates['life_row_003']['lifetime_s']/4.1e-9-1),1e-14)
|
| 25 |
+
def test_02_not_bool_nan(self):
|
| 26 |
+
h=EdinburghFls1000tcspcRuntime()
|
| 27 |
+
for val in [True,float('nan'),float('inf')]:self.rejected(h,'plant.configure',dict(PLANT_EXAMPLE,dark_rate_s_inv=val),'INVALID_ARGUMENT')
|
| 28 |
+
def test_03_initialization_once(self):
|
| 29 |
+
h=EdinburghFls1000tcspcRuntime();h.step(.1);h.invoke('plant.configure',**PLANT_EXAMPLE);self.rejected(h,'plant.configure',PLANT_EXAMPLE,'INITIALIZATION_ONLY')
|
| 30 |
+
def test_04_ack_required(self):
|
| 31 |
+
h=EdinburghFls1000tcspcRuntime();self.rejected(h,'plant.configure',dict(PLANT_EXAMPLE,accept_surrogate_model=False),'EVIDENCE_ACK_REQUIRED')
|
| 32 |
+
def test_05_external_load_guards(self):
|
| 33 |
+
h=ready();self.rejected(h,'sample.load',SAMPLE_EXAMPLE,'EXTERNAL_LOAD_REQUIRED')
|
| 34 |
+
def test_06_sample_source(self):
|
| 35 |
+
h=EdinburghFls1000tcspcRuntime();h.invoke('plant.configure',**PLANT_EXAMPLE)
|
| 36 |
+
self.rejected(h,'sample.load',dict(SAMPLE_EXAMPLE,components=[{'template_id':'invented','photon_weight':1.}]),'UNKNOWN_REFERENCE')
|
| 37 |
+
self.rejected(h,'sample.load',dict(SAMPLE_EXAMPLE,components=[{'template_id':'life_row_003','photon_weight':.5}]),'SAMPLE_COMPOSITION')
|
| 38 |
+
def test_07_source_discrete(self):
|
| 39 |
+
h=ready();self.rejected(h,'method.configure',dict(METHOD_EXAMPLE,excitation_wavelength_m=450e-9),'INSTALLED_SOURCE_MISMATCH')
|
| 40 |
+
def test_08_repetition_discrete(self):
|
| 41 |
+
h=ready();self.rejected(h,'method.configure',dict(METHOD_EXAMPLE,repetition_hz=15e6),'INVALID_ARGUMENT')
|
| 42 |
+
def test_09_wavelength_grid(self):
|
| 43 |
+
h=ready();self.rejected(h,'method.configure',dict(METHOD_EXAMPLE,emission_wavelength_m=519.005e-9),'WAVELENGTH_STEP')
|
| 44 |
+
def test_10_window_period_guard(self):
|
| 45 |
+
h=ready();self.rejected(h,'method.configure',dict(METHOD_EXAMPLE,time_window_s=100e-9),'PERIOD_GRID_RESOURCE')
|
| 46 |
+
def test_11_latent_resource_guard(self):
|
| 47 |
+
h=ready();self.rejected(h,'method.configure',dict(METHOD_EXAMPLE,repetition_hz=20e3,time_window_s=2.5e-9),'PERIOD_GRID_RESOURCE')
|
| 48 |
+
def test_12_event_resource_guard(self):
|
| 49 |
+
h=ready();self.rejected(h,'method.configure',dict(METHOD_EXAMPLE,max_acquisition_s=1000.),'EVENT_RESOURCE_LIMIT')
|
| 50 |
+
def test_13_response_not_lifetime_bound(self):
|
| 51 |
+
h=ready();self.assertGreater(h.irf_fwhm,600e-12);self.assertNotEqual(h.irf_fwhm,5e-12)
|
| 52 |
+
expected=math.sqrt((75e-12)**2+(600e-12)**2+(20e-12)**2+(30e-12)**2);self.assertAlmostEqual(h.irf_fwhm/expected,1.)
|
| 53 |
+
def test_14_periodic_decay_independent_integral(self):
|
| 54 |
+
n=50;dt=1e-9;tau=15e-9;actual=exp_bins(n,dt,tau)
|
| 55 |
+
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)]
|
| 56 |
+
np.testing.assert_allclose(actual,expected,rtol=1e-12);self.assertAlmostEqual(sum(actual),1.)
|
| 57 |
+
def test_15_gaussian_irf_independent_erf(self):
|
| 58 |
+
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))
|
| 59 |
+
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)])
|
| 60 |
+
np.testing.assert_allclose(actual,expected/expected.sum(),atol=1e-14)
|
| 61 |
+
def test_16_circular_convolution_direct(self):
|
| 62 |
+
a=np.arange(1.,33);a/=a.sum();b=exp_bins(32,1e-9,30e-9)
|
| 63 |
+
expected=[sum(a[j]*b[(i-j)%32] for j in range(32)) for i in range(32)]
|
| 64 |
+
np.testing.assert_allclose(convolve(a,b),expected,atol=1e-14)
|
| 65 |
+
def test_17_first_photon_probability(self):
|
| 66 |
+
mu=np.array([.1,.2,.3]);got=first_photon(mu)
|
| 67 |
+
np.testing.assert_allclose(got,[(1-math.exp(-.1)),math.exp(-.1)*(1-math.exp(-.2)),math.exp(-.3)*(1-math.exp(-.3))])
|
| 68 |
+
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())
|
| 69 |
+
def test_18_wraparound_long_lifetime(self):
|
| 70 |
+
d=exp_bins(1000,50e-12,50e-6);self.assertLess(max(d)/min(d),1.002);self.assertAlmostEqual(sum(d),1.)
|
| 71 |
+
def test_19_chunk_invariance(self):
|
| 72 |
+
a=ready();b=ready()
|
| 73 |
+
for h in [a,b]:h.invoke('acquisition.start')
|
| 74 |
+
a.step(1.)
|
| 75 |
+
for _ in range(200):b.step(.005)
|
| 76 |
+
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)
|
| 77 |
+
def test_20_finite_movement(self):
|
| 78 |
+
h=ready();h.invoke('acquisition.start');h.step(.04);s=h.read()
|
| 79 |
+
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')
|
| 80 |
+
def test_21_exact_total_stop(self):
|
| 81 |
+
h=collect(method=dict(METHOD_EXAMPLE,target_count=500));self.assertEqual(h.phase,'succeeded');self.assertEqual(sum(h.histograms[0]['counts']),500)
|
| 82 |
+
def test_22_exact_peak_stop(self):
|
| 83 |
+
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)
|
| 84 |
+
def test_23_time_stop(self):
|
| 85 |
+
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)
|
| 86 |
+
def test_24_timeout_keeps_data(self):
|
| 87 |
+
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'])
|
| 88 |
+
def test_25_cancel_keeps_photons(self):
|
| 89 |
+
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')
|
| 90 |
+
def test_26_open_cover_stops_source(self):
|
| 91 |
+
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'])
|
| 92 |
+
def test_27_power_off_stops(self):
|
| 93 |
+
h=ready();h.invoke('acquisition.start');h.invoke('power.set',enabled=False);self.assertEqual(h.phase,'cancelled');self.assertFalse(h.armed)
|
| 94 |
+
def test_28_source_disarm_stops(self):
|
| 95 |
+
h=ready();h.invoke('acquisition.start');h.invoke('source.arm',enabled=False);self.assertEqual(h.phase,'cancelled')
|
| 96 |
+
def test_29_partial_window_discard_ledger(self):
|
| 97 |
+
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'])
|
| 98 |
+
def test_30_intact_volume_replacement(self):
|
| 99 |
+
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)
|
| 100 |
+
def test_31_irf_real_acquisition(self):
|
| 101 |
+
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')
|
| 102 |
+
def test_32_irf_kind_guard(self):
|
| 103 |
+
h=ready();self.rejected(h,'irf.start',{},'REFERENCE_KIND')
|
| 104 |
+
def test_33_scatter_wavelength_guard(self):
|
| 105 |
+
h=ready(IRF_EXAMPLE);self.rejected(h,'irf.start',{},'SCATTER_WAVELENGTH')
|
| 106 |
+
def test_34_scan_sequential(self):
|
| 107 |
+
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)
|
| 108 |
+
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)
|
| 109 |
+
def test_35_query_clock_and_no_truth(self):
|
| 110 |
+
h=collect();t=h.time_s;n=h._recorded
|
| 111 |
+
for k in ['process.measure','result.read']:self.assertNotIn('life_row',json.dumps(h.invoke(k)))
|
| 112 |
+
self.assertEqual(h.time_s,t);self.assertEqual(h._recorded,n);self.assertNotIn('truth.ledger',h.read());self.assertIsNotNone(h.read('evaluator')['truth.ledger'])
|
| 113 |
+
def test_36_no_return_alias(self):
|
| 114 |
+
h=collect();r=h.invoke('result.read');r['histograms'][0]['counts'][0]=999999;self.assertNotEqual(h.histograms[0]['counts'][0],999999)
|
| 115 |
+
def test_37_caller_only_mono_fit(self):
|
| 116 |
+
h=EdinburghFls1000tcspcRuntime();r=h.invoke('lifetime.fit',**CAPS['lifetime.fit'][6]);self.assertLess(abs(r['lifetimes_s'][0]/4e-9-1),.005)
|
| 117 |
+
def test_38_caller_bi_fit(self):
|
| 118 |
+
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()
|
| 119 |
+
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)
|
| 120 |
+
def test_39_das_fixed_taus(self):
|
| 121 |
+
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)
|
| 122 |
+
def test_40_fit_rejects_partial_or_wrong_irf(self):
|
| 123 |
+
h=EdinburghFls1000tcspcRuntime();a=copy.deepcopy(CAPS['lifetime.fit'][6]);a['histogram']['complete']=False;self.rejected(h,'lifetime.fit',a,'ANALYSIS_INPUT')
|
| 124 |
+
a=copy.deepcopy(CAPS['lifetime.fit'][6]);a['irf_histogram']['response_kind']='decay';self.rejected(h,'lifetime.fit',a,'IRF_GRID_MISMATCH')
|
| 125 |
+
def test_41_full_period_fit_guard(self):
|
| 126 |
+
h=EdinburghFls1000tcspcRuntime();a=copy.deepcopy(CAPS['lifetime.fit'][6]);a['histogram']['period_s']=100e-9;self.rejected(h,'lifetime.fit',a,'FULL_PERIOD_REQUIRED')
|
| 127 |
+
def test_42_session_permissions(self):
|
| 128 |
+
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')
|
| 129 |
+
with self.assertRaises(ActionRejected):s.read(instance_id=h.instance_id,state_ids=['truth.ledger'])
|
| 130 |
+
self.assertNotIn('sample.load',s.describe(instance_id=h.instance_id)['capabilities'])
|
| 131 |
+
def test_43_idempotency_cancel(self):
|
| 132 |
+
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')
|
| 133 |
+
r=s.invoke(instance_id=h.instance_id,capability_id='acquisition.stop',arguments={},request_id='start');self.assertEqual(r['error']['code'],'REQUEST_CONFLICT')
|
| 134 |
+
def test_44_owner_only_poll(self):
|
| 135 |
+
h=ready();h.register_principal('b');a=h.session().invoke(instance_id=h.instance_id,capability_id='acquisition.start',arguments={},request_id='a')
|
| 136 |
+
with self.assertRaises(ActionRejected):h.session('b').poll(a['operation_id'])
|
| 137 |
+
def test_45_unsupported(self):
|
| 138 |
+
h=ready()
|
| 139 |
+
for cap in UNSUPPORTED:self.rejected(h,cap,CAPS[cap][6],'UNSUPPORTED')
|
| 140 |
+
def test_46_actual_measurement_fit(self):
|
| 141 |
+
ir=collect(IRF_EXAMPLE,dict(METHOD_EXAMPLE,emission_wavelength_m=405e-9,target_count=20000,max_acquisition_s=.3))
|
| 142 |
+
signal=collect(method=dict(METHOD_EXAMPLE,target_count=20000,max_acquisition_s=.3))
|
| 143 |
+
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)
|
| 144 |
+
def test_47_all_real_templates_run(self):
|
| 145 |
+
h=EdinburghFls1000tcspcRuntime()
|
| 146 |
+
for sid,t in h.templates.items():
|
| 147 |
+
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))
|
| 148 |
+
self.assertEqual(q.phase,'succeeded');self.assertEqual(q._ledger()['count_residual'],0)
|
| 149 |
+
def test_48_sample_timestamp(self):
|
| 150 |
+
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'])
|
| 151 |
+
def test_49_empty_signal_not_invented(self):
|
| 152 |
+
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'])
|
| 153 |
+
def test_50_irf_transfer_and_units(self):
|
| 154 |
+
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')
|
| 155 |
+
def test_51_historical_method_snapshot(self):
|
| 156 |
+
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'])
|
| 157 |
+
h.invoke('acquisition.start');h.step(2);self.assertEqual(json.loads(h.invoke('result.read')['settings_json'])['target_count'],123)
|
| 158 |
+
def test_52_documented_tcspc_channels_not_mcs_channels(self):
|
| 159 |
+
h=ready()
|
| 160 |
+
for bins in [512,1024,2048,4096,8192]:
|
| 161 |
+
h.invoke('method.configure',**dict(METHOD_EXAMPLE,bins=bins));self.assertAlmostEqual(h.read()['method.bin_width_s']*bins/50e-9,1.)
|
| 162 |
+
for bins in [500,1000,2000,4000,8000]:self.rejected(h,'method.configure',dict(METHOD_EXAMPLE,bins=bins),'INVALID_ARGUMENT')
|
| 163 |
+
self.assertEqual(len(demo_hist()['counts']),512);self.assertEqual(METHOD_EXAMPLE['bins'],1024)
|
| 164 |
+
def test_53_zero_or_underflowed_period_rejects_with_protocol_error(self):
|
| 165 |
+
for cap in ['lifetime.fit','das.fit']:
|
| 166 |
+
for period in [0.,5e-324]:
|
| 167 |
+
with self.subTest(cap=cap,period=period):
|
| 168 |
+
h=EdinburghFls1000tcspcRuntime();a=copy.deepcopy(CAPS[cap][6]);histograms=[a['histogram']] if cap=='lifetime.fit' else a['histograms']
|
| 169 |
+
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)]
|
| 170 |
+
before=pickle.dumps(h.debug_snapshot());reply=h.session().invoke(instance_id=h.instance_id,capability_id=cap,arguments=a,request_id='bad-grid')
|
| 171 |
+
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)
|
| 172 |
+
def test_54_numerically_invisible_lifetime_does_not_return_initial_guess(self):
|
| 173 |
+
a=copy.deepcopy(CAPS['lifetime.fit'][6]);a['initial_lifetimes_s']=[5e-12]
|
| 174 |
+
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()
|
| 175 |
+
self.rejected(EdinburghFls1000tcspcRuntime(),'lifetime.fit',a,'FIT_UNIDENTIFIABLE')
|
| 176 |
+
def test_55_zero_photon_acquisition_has_real_observation_window(self):
|
| 177 |
+
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)
|
| 178 |
+
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']
|
| 179 |
+
observations=h.session().read(instance_id=h.instance_id,state_ids=['scan.total_counts','scan.peak_counts','scan.mean_microtime_s'])['observations']
|
| 180 |
+
for observation in observations.values():self.assertEqual(observation['sample_time_s'],end);self.assertEqual(observation['sample_window_s'],[hist['start_time_s'],end])
|
| 181 |
+
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')
|
| 182 |
+
def test_56_accumulated_count_window_includes_no_photon_tail(self):
|
| 183 |
+
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())
|
| 184 |
+
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']
|
| 185 |
+
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()))
|
| 186 |
+
def test_57_historical_completion_preserves_public_summary_and_window(self):
|
| 187 |
+
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)
|
| 188 |
+
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'])
|
| 189 |
+
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)
|
| 190 |
+
self.assertNotIn('life_row',json.dumps(s.poll(op)));self.assertNotIn(SAMPLE_EXAMPLE['sample_id'],json.dumps(s.poll(op)))
|
| 191 |
+
with self.assertRaisesRegex(ActionRejected,'ACCESS_DENIED'):h.session('other').poll(op)
|
| 192 |
+
self.assertEqual(before,pickle.dumps(h.debug_snapshot()))
|
| 193 |
+
def test_58_cancel_historical_terminal_does_not_stop_new_counting(self):
|
| 194 |
+
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)
|
| 195 |
+
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()
|
| 196 |
+
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)
|
| 197 |
+
with self.assertRaisesRegex(ActionRejected,'REQUEST_CONFLICT'):s.cancel(current,'cancel-old')
|
| 198 |
+
self.assertEqual(h.phase,'running')
|
| 199 |
+
def test_59_failed_and_cancelled_partial_histories_survive_later_start(self):
|
| 200 |
+
for status in ['failed','cancelled']:
|
| 201 |
+
with self.subTest(status=status):
|
| 202 |
+
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)
|
| 203 |
+
if status=='cancelled':s.cancel(op,'cancel')
|
| 204 |
+
else:h.step(.002)
|
| 205 |
+
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)
|
| 206 |
+
s.invoke(instance_id=h.instance_id,capability_id='acquisition.start',arguments={},request_id='next');self.assertEqual(s.poll(op),terminal)
|
| 207 |
+
def test_60_metadata_matches_method_targets_and_step_optics(self):
|
| 208 |
+
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']
|
| 209 |
+
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})
|
| 210 |
+
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'}
|
| 211 |
+
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'])
|
| 212 |
+
self.assertEqual(caps['lifetime.fit']['observes'],[]);self.assertEqual(caps['das.fit']['observes'],[]);self.assertEqual(m['state_slots']['scan.total_counts']['sampling']['mode'],'integral')
|
| 213 |
+
if __name__=='__main__':unittest.main()
|
| 214 |
+
|
tests/test_asset_elementar_isoprimeprecision.py
ADDED
|
@@ -0,0 +1,560 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""tests for CHEM-090 elementar_isoprimeprecision (Elementar isoprime precisION IRMS with centrION): python3 -m unittest tests/test_asset_elementar_isoprimeprecision.py
|
| 2 |
+
|
| 3 |
+
Themes: contract consistency (slots, effects, errors raised vs declared); agent / evaluator truth isolation (unknown samples); idempotent request
|
| 4 |
+
ids; two instances isolated; step-partition independence (noise included); rejected calls leave the state unchanged; every output validated
|
| 5 |
+
against its schema and every success changes only declared slots; pump-down within 12 h (calibrated), power failure with the isolation valve;
|
| 6 |
+
magnet mass range (1-76 amu at 3 kV); continuous-flow CO2 against reference pulses (17O correction, internal precision <= 0.06 permil),
|
| 7 |
+
normalisation with reference materials recovering an unknown; dual inlet internal precision (<= 0.010 / 0.016 permil 2 sigma at 100 bar uL);
|
| 8 |
+
H2 with the H3+ factor (<= 8 ppm/nA); N2; ratio linearity; non-selected inlet vented; resistor switching and saturation; faults (helium, filament,
|
| 9 |
+
vacuum leak, magnet drift, empty reference gas); ledgers (sample, reference and dual-inlet moles; helium) close exactly."""
|
| 10 |
+
import json
|
| 11 |
+
import math
|
| 12 |
+
import re
|
| 13 |
+
import sys
|
| 14 |
+
import unittest
|
| 15 |
+
from pathlib import Path
|
| 16 |
+
|
| 17 |
+
ROOT = Path(__file__).resolve().parents[1]
|
| 18 |
+
sys.path.insert(0, str(ROOT / 'scripts'))
|
| 19 |
+
from asset_runtime import elementar_isoprimeprecision as rt # noqa: E402
|
| 20 |
+
|
| 21 |
+
INST = 'elementar_isoprimeprecision_01'
|
| 22 |
+
CHECKS = []
|
| 23 |
+
SEEN_CAPS = set()
|
| 24 |
+
PROCESS_EVIDENCE = {}
|
| 25 |
+
CO2_REF = {'13C': -0.0367, '18O': 0.0251}
|
| 26 |
+
|
| 27 |
+
|
| 28 |
+
def _differ(x, y):
|
| 29 |
+
if isinstance(x, float) and isinstance(y, float):
|
| 30 |
+
return abs(x - y) > 1e-12 * max(1.0, abs(x), abs(y))
|
| 31 |
+
return json.dumps(x, sort_keys=True, default=str) != json.dumps(y, sort_keys=True, default=str)
|
| 32 |
+
|
| 33 |
+
|
| 34 |
+
class Rig:
|
| 35 |
+
def __init__(self, seed=1, instance=INST, **plant):
|
| 36 |
+
self.h = rt.ElementarIsoprimeprecisionRuntime(instance)
|
| 37 |
+
self.h.register_principal('agent', 'agent')
|
| 38 |
+
self.h.register_principal('eval', 'evaluator')
|
| 39 |
+
self.A = self.h.session('agent')
|
| 40 |
+
self.E = self.h.session('eval')
|
| 41 |
+
self.n = 0
|
| 42 |
+
self.inst = instance
|
| 43 |
+
self.call(self.E, 'plant.configure', **dict(rt.PLANT_EXAMPLE, noise_seed=seed, **plant))
|
| 44 |
+
|
| 45 |
+
def call(self, sess, cap, expect='succeeded', **args):
|
| 46 |
+
self.n += 1
|
| 47 |
+
before, t0 = self.h.read('evaluator'), self.h.t
|
| 48 |
+
r = sess.invoke(instance_id=self.inst, capability_id=cap, arguments=args, request_id=f'r{self.n}')
|
| 49 |
+
after = self.h.read('evaluator')
|
| 50 |
+
changed = {k for k in after if _differ(after[k], before[k])} - {'clock.time_s'}
|
| 51 |
+
if expect == 'succeeded':
|
| 52 |
+
assert r['status'] == 'succeeded', (cap, r['error'])
|
| 53 |
+
rt.validate(rt.CAPS[cap]['output_schema'], r['result'])
|
| 54 |
+
if cap != 'sim.step':
|
| 55 |
+
extra = changed - set(rt.EFFECTS.get(cap, []))
|
| 56 |
+
assert not extra, (cap, sorted(extra))
|
| 57 |
+
assert self.h.t == t0, cap
|
| 58 |
+
SEEN_CAPS.add(cap)
|
| 59 |
+
PROCESS_EVIDENCE.setdefault(cap, []).append(dict(arguments=json.dumps(args, sort_keys=True, default=str)[:200], time_s=t0, status=r['status']))
|
| 60 |
+
return r['result']
|
| 61 |
+
assert r['status'] in ('rejected', 'unsupported'), (cap, r['status'], r.get('result'))
|
| 62 |
+
assert r['error']['code'] == expect, (cap, r['error']['code'], expect)
|
| 63 |
+
assert not changed, (cap, 'rejected call changed', sorted(changed))
|
| 64 |
+
assert expect in [e['code'] for e in rt.export_elementar_isoprimeprecision_contract_metadata()['capabilities'][cap]['errors']], (cap, expect)
|
| 65 |
+
return r
|
| 66 |
+
|
| 67 |
+
def step(self, s):
|
| 68 |
+
self.call(self.E, 'sim.step', dt_s=float(s))
|
| 69 |
+
|
| 70 |
+
def read(self, *ids, who=None):
|
| 71 |
+
sess = who or self.E
|
| 72 |
+
o = sess.read(instance_id=self.inst, state_ids=list(ids) if ids else None)['observations']
|
| 73 |
+
return {k: v['value'] for k, v in o.items()} if not ids or len(ids) > 1 else o[ids[0]]['value']
|
| 74 |
+
|
| 75 |
+
def ready(self, species='CO2', ref=1, deltas=None):
|
| 76 |
+
self.call(self.A, 'power.set', on=True)
|
| 77 |
+
self.step(600.0)
|
| 78 |
+
self.call(self.A, 'source.set', filament=True)
|
| 79 |
+
self.call(self.A, 'magnet.set_species', species=species)
|
| 80 |
+
self.call(self.A, 'centrion.set', inlet=1, carrier_on=True)
|
| 81 |
+
self.call(self.A, 'reference.assign', gas=ref, deltas=deltas or CO2_REF)
|
| 82 |
+
|
| 83 |
+
def peaks(self, since=0):
|
| 84 |
+
return self.call(self.A, 'results.read', since_peak=since)['peaks']
|
| 85 |
+
|
| 86 |
+
def ledger(self):
|
| 87 |
+
return self.call(self.E, 'ledger.read')['ledger']
|
| 88 |
+
|
| 89 |
+
|
| 90 |
+
def _raised_codes():
|
| 91 |
+
src = Path(rt.__file__).read_text()
|
| 92 |
+
funcs = {}
|
| 93 |
+
for m in re.finditer(r'\n def (\w+)\(self[^\n]*\n(.*?)(?=\n def |\n# ----|\nclass |\ndef )', src, re.S):
|
| 94 |
+
funcs[m.group(1)] = m.group(2)
|
| 95 |
+
own = {k: set(re.findall(r"ActionRejected\('([A-Z_]+)'\)", v)) for k, v in funcs.items()}
|
| 96 |
+
calls = {k: set(re.findall(r'self\.(_\w+)\(', v)) & set(funcs) for k, v in funcs.items()}
|
| 97 |
+
out = {}
|
| 98 |
+
for k in funcs:
|
| 99 |
+
if not k.startswith('_cmd_'):
|
| 100 |
+
continue
|
| 101 |
+
seen, todo, codes = set(), [k], set()
|
| 102 |
+
while todo:
|
| 103 |
+
f = todo.pop()
|
| 104 |
+
if f in seen:
|
| 105 |
+
continue
|
| 106 |
+
seen.add(f)
|
| 107 |
+
codes |= own.get(f, set())
|
| 108 |
+
todo += [g for g in calls.get(f, ()) if g not in ('_cmd_sim_step', 'step', '_tick')]
|
| 109 |
+
out[k] = codes
|
| 110 |
+
name = {'_cmd_' + c.replace('.', '_'): c for c in rt.CAPS}
|
| 111 |
+
return {name[k]: v for k, v in out.items() if k in name}
|
| 112 |
+
|
| 113 |
+
|
| 114 |
+
def _balance(test, L):
|
| 115 |
+
for sp, inj in L['injected_mol'].items():
|
| 116 |
+
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)
|
| 117 |
+
test.assertAlmostEqual(tot, inj, delta=1e-9 * inj, msg=sp)
|
| 118 |
+
for sp, inj in L['ref_injected_mol'].items():
|
| 119 |
+
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)
|
| 120 |
+
test.assertAlmostEqual(tot, inj, delta=1e-12 + 1e-9 * inj, msg='ref ' + sp)
|
| 121 |
+
test.assertAlmostEqual(L['di_consumed_mol'], L['di_source_mol'] + L['di_ionised_mol'], delta=1e-15 + 1e-9 * L['di_consumed_mol'])
|
| 122 |
+
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'])
|
| 123 |
+
|
| 124 |
+
|
| 125 |
+
def _cf_run(g, samples, pulses=3, pulse_a=None, duration=None):
|
| 126 |
+
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)]
|
| 127 |
+
dur = duration or (40.0 * pulses + 140.0 * len(samples) + 120.0)
|
| 128 |
+
g.call(g.A, 'acquisition.start', duration_s=dur, reference_pulses=pul)
|
| 129 |
+
for k, (kw, amount) in enumerate(samples):
|
| 130 |
+
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)
|
| 131 |
+
g.step(dur + 1.0)
|
| 132 |
+
|
| 133 |
+
|
| 134 |
+
class Contract(unittest.TestCase):
|
| 135 |
+
def test_metadata_slots_effects_consistent(self):
|
| 136 |
+
meta = rt.export_elementar_isoprimeprecision_contract_metadata()
|
| 137 |
+
slots = set(meta['state_slots'])
|
| 138 |
+
self.assertEqual(slots, set(rt.SLOTS))
|
| 139 |
+
for k, c in meta['capabilities'].items():
|
| 140 |
+
for e in c['state_effects']:
|
| 141 |
+
self.assertIn(e['state_id'], slots, k)
|
| 142 |
+
self.assertTrue({'INVALID_ARGUMENT', 'REQUEST_CONFLICT', 'UNKNOWN_INSTANCE'} <= {e['code'] for e in c['errors']}, k)
|
| 143 |
+
for p in c['preconditions']:
|
| 144 |
+
for s in p['state_ids']:
|
| 145 |
+
self.assertIn(s, slots, k)
|
| 146 |
+
self.assertTrue(rt.SCENE_MIRRORED <= slots)
|
| 147 |
+
for name, p in meta['mechanisms']['irms_process']['parameters'].items():
|
| 148 |
+
self.assertEqual(name, name.lower())
|
| 149 |
+
self.assertIn(p['evidence'], ('documented', 'assumption'), name)
|
| 150 |
+
|
| 151 |
+
def test_declared_errors_cover_raised_codes(self):
|
| 152 |
+
meta = rt.export_elementar_isoprimeprecision_contract_metadata()
|
| 153 |
+
for cap, codes in _raised_codes().items():
|
| 154 |
+
declared = {e['code'] for e in meta['capabilities'][cap]['errors']}
|
| 155 |
+
self.assertTrue(codes <= declared, (cap, sorted(codes - declared)))
|
| 156 |
+
|
| 157 |
+
def test_unsupported_capabilities(self):
|
| 158 |
+
g = Rig()
|
| 159 |
+
for k in rt.UNSUPPORTED:
|
| 160 |
+
g.call(g.A, k, expect='UNSUPPORTED')
|
| 161 |
+
|
| 162 |
+
def test_agent_truth_isolation(self):
|
| 163 |
+
g = Rig()
|
| 164 |
+
g.ready()
|
| 165 |
+
g.call(g.E, 'sample.declare', sample_id='leaf_a', deltas={'13C': -0.0281})
|
| 166 |
+
_cf_run(g, [(dict(sample_id='leaf_a'), 4e-6)], pulses=1)
|
| 167 |
+
self.assertFalse(any(k.startswith('truth.') for k in g.read(who=g.A)))
|
| 168 |
+
p = [q for q in g.peaks() if q['type'] == 'sample'][0]
|
| 169 |
+
self.assertNotIn('truth', p)
|
| 170 |
+
self.assertNotIn('label', p) # unknown sample: the label is not leaked
|
| 171 |
+
for cap, a in (('truth.inspect', {}), ('ledger.read', {}), ('sim.step', dict(dt_s=1.0)), ('sample.declare', dict(sample_id='x', deltas={})),
|
| 172 |
+
('fault.inject', dict(fault='vacuum_leak', active=True))):
|
| 173 |
+
r = g.A.invoke(instance_id=INST, capability_id=cap, arguments=a, request_id='x' + cap)
|
| 174 |
+
self.assertEqual(r['error']['code'], 'ACCESS_DENIED')
|
| 175 |
+
g.call(g.E, 'fault.inject', fault='magnet_drift', active=True)
|
| 176 |
+
self.assertFalse(any(e['kind'] in ('fault', 'truth') for e in g.call(g.A, 'events.read', since_s=0.0)['events']))
|
| 177 |
+
g.call(g.E, 'truth.inspect')
|
| 178 |
+
|
| 179 |
+
def test_idempotent_request_ids(self):
|
| 180 |
+
g = Rig()
|
| 181 |
+
a = g.A.invoke(instance_id=INST, capability_id='power.set', arguments=dict(on=True), request_id='same')
|
| 182 |
+
b = g.A.invoke(instance_id=INST, capability_id='power.set', arguments=dict(on=True), request_id='same')
|
| 183 |
+
self.assertEqual(a, b)
|
| 184 |
+
c = g.A.invoke(instance_id=INST, capability_id='power.set', arguments=dict(on=False), request_id='same')
|
| 185 |
+
self.assertEqual(c['error']['code'], 'REQUEST_CONFLICT')
|
| 186 |
+
|
| 187 |
+
def test_two_instances_isolated(self):
|
| 188 |
+
a, b = Rig(instance='i1'), Rig(instance='i2')
|
| 189 |
+
a.call(a.A, 'power.set', on=True)
|
| 190 |
+
self.assertFalse(b.read('power.on'))
|
| 191 |
+
|
| 192 |
+
def test_step_partition_independence(self):
|
| 193 |
+
runs = []
|
| 194 |
+
for parts in ([400.0], [0.3, 7.7, 92.0, 300.0], [1.0] * 40 + [360.0]):
|
| 195 |
+
g = Rig(seed=7)
|
| 196 |
+
g.ready()
|
| 197 |
+
g.call(g.A, 'acquisition.start', duration_s=380.0, reference_pulses=[dict(gas=1, start_s=20.0, duration_s=20.0)])
|
| 198 |
+
g.call(g.A, 'sample.inject', inlet=1, species='CO2', amount_mol=3e-6, substance_id='usgs40', delay_s=60.0)
|
| 199 |
+
for p in parts:
|
| 200 |
+
g.step(p)
|
| 201 |
+
v = g.read()
|
| 202 |
+
v.pop('clock.time_s')
|
| 203 |
+
runs.append(json.dumps([v, g.peaks()], sort_keys=True, default=str))
|
| 204 |
+
self.assertEqual(runs[0], runs[1])
|
| 205 |
+
self.assertEqual(runs[0], runs[2])
|
| 206 |
+
|
| 207 |
+
def test_rejections_change_nothing(self):
|
| 208 |
+
r = rt.ElementarIsoprimeprecisionRuntime('fresh')
|
| 209 |
+
r.register_principal('a', 'agent')
|
| 210 |
+
self.assertEqual(r.session('a').invoke(instance_id='fresh', capability_id='power.set', arguments=dict(on=True), request_id='p')['error']['code'], 'PLANT_REQUIRED')
|
| 211 |
+
g = Rig(vented=True)
|
| 212 |
+
g.call(g.E, 'plant.configure', expect='SEED_FIXED', **dict(rt.PLANT_EXAMPLE, noise_seed=2))
|
| 213 |
+
g.call(g.E, 'plant.configure', expect='CONFIG_FIXED', **dict(rt.PLANT_EXAMPLE, inlets=['gc', None, None, None, None]))
|
| 214 |
+
g.call(g.E, 'sample.declare', expect='NAME_TAKEN', sample_id='usgs40', deltas={'13C': 0.0})
|
| 215 |
+
g.call(g.A, 'source.set', expect='POWER_OFF', filament=True)
|
| 216 |
+
g.call(g.A, 'power.set', on=True)
|
| 217 |
+
g.call(g.A, 'source.set', expect='VACUUM_NOT_READY', filament=True) # vented
|
| 218 |
+
g.call(g.A, 'magnet.peak_center', expect='NO_SPECIES')
|
| 219 |
+
g.call(g.A, 'magnet.set_species', expect='OUT_OF_RANGE', species='SO2', ) if g.h.source['acceleration_v'] > 3500 else None
|
| 220 |
+
g.call(g.A, 'source.set', acceleration_v=5000.0)
|
| 221 |
+
g.call(g.A, 'magnet.set_species', expect='OUT_OF_RANGE', species='SO2') # 66 u > 45.6 u at 5 kV
|
| 222 |
+
g.call(g.A, 'source.set', acceleration_v=3000.0)
|
| 223 |
+
g.call(g.A, 'centrion.set', expect='INLET_EMPTY', inlet=3)
|
| 224 |
+
g.call(g.A, 'sample.inject', expect='NO_CARRIER', inlet=1, species='CO2', amount_mol=1e-6, substance_id='usgs40')
|
| 225 |
+
g.call(g.A, 'centrion.set', inlet=1, carrier_on=True)
|
| 226 |
+
g.call(g.A, 'sample.inject', expect='WRONG_INLET', inlet=5, species='CO2', amount_mol=1e-6, substance_id='usgs40')
|
| 227 |
+
g.call(g.A, 'sample.inject', expect='UNKNOWN_SAMPLE', inlet=1, species='CO2', amount_mol=1e-6, sample_id='nothing')
|
| 228 |
+
g.call(g.A, 'sample.inject', expect='NO_DELTA_FOR_SPECIES', inlet=1, species='N2', amount_mol=1e-6, substance_id='usgs24')
|
| 229 |
+
g.call(g.A, 'sample.inject', expect='INVALID_ARGUMENT', inlet=1, species='CO2', amount_mol=1e-6)
|
| 230 |
+
g.call(g.A, 'acquisition.start', expect='NO_SPECIES', duration_s=60.0)
|
| 231 |
+
g.call(g.A, 'magnet.set_species', species='CO2')
|
| 232 |
+
g.call(g.A, 'acquisition.start', expect='SOURCE_OFF', duration_s=60.0)
|
| 233 |
+
g.call(g.A, 'reference.assign', expect='NO_REFERENCE_GAS', gas=4, deltas={'13C': 0.0})
|
| 234 |
+
g.call(g.A, 'reference.assign', expect='INVALID_ARGUMENT', gas=1, deltas={'15N': 0.0})
|
| 235 |
+
g.call(g.A, 'dual_inlet.start', expect='SOURCE_OFF', species='CO2', substance_id='nbs19', sample_bar_ul=100.0, reference_gas=1)
|
| 236 |
+
g.call(g.A, 'h3.determine', expect='NEED_H2_PULSES', run=1)
|
| 237 |
+
g.call(g.A, 'calibration.normalize', expect='UNKNOWN_PEAK', isotope='13C', standards=[dict(peak=1, substance_id='usgs40'), dict(peak=2, substance_id='usgs41')])
|
| 238 |
+
g.call(g.A, 'amplifier.configure', expect='INVALID_ARGUMENT', mode='fixed')
|
| 239 |
+
g.call(g.E, 'fault.inject', expect='GAS_REQUIRED', fault='reference_gas_empty', active=True)
|
| 240 |
+
g.call(g.E, 'fault.inject', expect='INVALID_ARGUMENT', fault='alien', active=True)
|
| 241 |
+
|
| 242 |
+
|
| 243 |
+
class Physics(unittest.TestCase):
|
| 244 |
+
def test_pump_down_within_12_h_and_status(self):
|
| 245 |
+
g = Rig(vented=True)
|
| 246 |
+
self.assertEqual(g.read('vacuum.state'), 'vented')
|
| 247 |
+
g.call(g.A, 'power.set', on=True)
|
| 248 |
+
self.assertEqual(g.read('status.led'), 'amber')
|
| 249 |
+
self.assertEqual([g.read('indicator.led_' + k) for k in ('green', 'amber', 'red')], [k == 'amber' for k in ('green', 'amber', 'red')])
|
| 250 |
+
g.call(g.A, 'vacuum.pump_down')
|
| 251 |
+
g.step(11.0 * 3600.0)
|
| 252 |
+
self.assertEqual(g.read('vacuum.state'), 'pumping')
|
| 253 |
+
g.step(1.05 * 3600.0)
|
| 254 |
+
self.assertEqual(g.read('vacuum.state'), 'ready') # brochure: within 12 h without bakeout
|
| 255 |
+
self.assertLessEqual(g.read('truth.process')['pressure_pa'], rt.ENG['vacuum_ready_pa'])
|
| 256 |
+
g.call(g.A, 'source.set', filament=True)
|
| 257 |
+
self.assertEqual(g.read('status.led'), 'green')
|
| 258 |
+
self.assertEqual([g.read('indicator.led_' + k) for k in ('green', 'amber', 'red')], [k == 'green' for k in ('green', 'amber', 'red')])
|
| 259 |
+
g.call(g.A, 'vacuum.vent', expect='FILAMENT_ON')
|
| 260 |
+
g.call(g.A, 'source.set', filament=False)
|
| 261 |
+
g.call(g.A, 'vacuum.vent')
|
| 262 |
+
self.assertEqual(g.read('vacuum.state'), 'vented')
|
| 263 |
+
self.assertIsNone(g.read('vacuum.pressure_pa'))
|
| 264 |
+
|
| 265 |
+
def test_power_failure_isolation_valve(self):
|
| 266 |
+
g = Rig()
|
| 267 |
+
g.ready()
|
| 268 |
+
g.call(g.E, 'fault.inject', fault='mains_outage', active=True)
|
| 269 |
+
self.assertEqual(g.read('vacuum.state'), 'isolated')
|
| 270 |
+
self.assertFalse(g.read('source.state')['filament'])
|
| 271 |
+
self.assertEqual(g.read('status.led'), 'off')
|
| 272 |
+
self.assertEqual([g.read('indicator.led_' + k) for k in ('green', 'amber', 'red')], [k == 'off' for k in ('green', 'amber', 'red')])
|
| 273 |
+
g.step(600.0)
|
| 274 |
+
p_sealed = g.read('truth.process')['pressure_pa']
|
| 275 |
+
self.assertGreater(p_sealed, 0.05) # sealed analyser: pressure rises
|
| 276 |
+
g.call(g.E, 'fault.inject', fault='mains_outage', active=False)
|
| 277 |
+
self.assertEqual(g.read('vacuum.state'), 'isolated')
|
| 278 |
+
g.step(rt.ENG['turbo_spinup_s'] + 1.0)
|
| 279 |
+
self.assertEqual(g.read('vacuum.state'), 'ready') # turbo at speed: valve reopened
|
| 280 |
+
self.assertIn('ISOLATION_OPEN', [e['code'] for e in g.call(g.A, 'events.read', since_s=0.0)['events']])
|
| 281 |
+
g.call(g.A, 'source.set', filament=True)
|
| 282 |
+
|
| 283 |
+
def test_magnet_mass_range(self):
|
| 284 |
+
self.assertLess(rt.ElementarIsoprimeprecisionRuntime()._max_mass(3000.0) - 76.0, 1e-9)
|
| 285 |
+
g = Rig()
|
| 286 |
+
g.ready()
|
| 287 |
+
self.assertAlmostEqual(g.read('magnet.state')['field_t'], rt.b_for(45.0, 3000.0) * (1 + 4e-4), places=12)
|
| 288 |
+
g.call(g.A, 'source.set', acceleration_v=4000.0) # field follows the voltage
|
| 289 |
+
self.assertAlmostEqual(g.read('magnet.state')['field_t'], rt.b_for(45.0, 4000.0), places=12)
|
| 290 |
+
g.call(g.A, 'source.set', expect='OUT_OF_RANGE', acceleration_v=5000.0) # 46 u > 45.6 u
|
| 291 |
+
self.assertEqual(g.read('magnet.state')['masses'], [44, 45, 46])
|
| 292 |
+
|
| 293 |
+
def test_cf_co2_deltas_precision_and_normalisation(self):
|
| 294 |
+
g = Rig()
|
| 295 |
+
g.ready()
|
| 296 |
+
g.call(g.E, 'sample.declare', sample_id='leaf_a', deltas={'13C': -0.0281})
|
| 297 |
+
_cf_run(g, [(dict(substance_id='usgs40'), 4e-6), (dict(substance_id='usgs41'), 4e-6), (dict(sample_id='leaf_a'), 4e-6)], pulses=10)
|
| 298 |
+
peaks = g.peaks()
|
| 299 |
+
refs = [p for p in peaks if p['type'] == 'reference']
|
| 300 |
+
smp = [p for p in peaks if p['type'] == 'sample']
|
| 301 |
+
self.assertEqual((len(refs), len(smp)), (10, 3))
|
| 302 |
+
# internal precision of the monitoring gas: SD of the reference pulses' 45/44 against their mean
|
| 303 |
+
r45 = [p['ratios']['45/44'] for p in refs]
|
| 304 |
+
m = sum(r45) / len(r45)
|
| 305 |
+
sd = math.sqrt(sum((x / m - 1) ** 2 for x in r45) / (len(r45) - 1)) * 1000.0
|
| 306 |
+
self.assertLess(sd, rt.DOC['cf_precision_permil']['co2_13c']) # brochure: <= 0.06 permil 1 sigma
|
| 307 |
+
self.assertAlmostEqual(smp[0]['delta_ref']['13C'], rt.RM['usgs40']['values']['13C']['delta'], delta=2e-4)
|
| 308 |
+
self.assertAlmostEqual(smp[0]['delta_ref']['18O'], rt.PLANT_EXAMPLE['combustion_o2_delta18o'], delta=3e-4)
|
| 309 |
+
n = g.call(g.A, 'calibration.normalize', isotope='13C', standards=[dict(peak=smp[0]['peak'], substance_id='usgs40'),
|
| 310 |
+
dict(peak=smp[1]['peak'], substance_id='usgs41')])
|
| 311 |
+
self.assertAlmostEqual(n['slope'], 1.0, delta=0.01)
|
| 312 |
+
leaf = [p for p in g.peaks() if p['type'] == 'sample'][2]
|
| 313 |
+
self.assertAlmostEqual(leaf['delta_normalized']['13C'], -0.0281, delta=1.5e-4)
|
| 314 |
+
self.assertEqual(g.read('results.count'), 13)
|
| 315 |
+
_balance(self, g.ledger())
|
| 316 |
+
|
| 317 |
+
def test_dual_inlet_precision(self):
|
| 318 |
+
g = Rig()
|
| 319 |
+
g.ready()
|
| 320 |
+
r = g.call(g.A, 'dual_inlet.start', species='CO2', substance_id='nbs19', sample_bar_ul=100.0, reference_gas=1, cycles=10)
|
| 321 |
+
self.assertEqual(g.read('acquisition.state')['mode'], 'dual_inlet')
|
| 322 |
+
g.step(r['ends_s'] - g.h.t + 1.0)
|
| 323 |
+
p = g.peaks()[-1]
|
| 324 |
+
self.assertEqual(p['type'], 'dual_inlet')
|
| 325 |
+
self.assertEqual(p['cycles'], 10)
|
| 326 |
+
lim = rt.DOC['di_precision_permil_2s']
|
| 327 |
+
self.assertLess(2000.0 * p['internal_se']['13C'], lim['co2_13c']) # brochure: <= 0.010 permil 2 sigma
|
| 328 |
+
self.assertLess(2000.0 * p['internal_se']['18O'], lim['co2_18o'])
|
| 329 |
+
self.assertAlmostEqual(p['delta_ref']['13C'], rt.RM['nbs19']['values']['13C']['delta'], delta=3e-5)
|
| 330 |
+
self.assertAlmostEqual(p['delta_ref']['18O'], rt.RM['nbs19']['values']['18O']['delta'], delta=4e-5)
|
| 331 |
+
_balance(self, g.ledger())
|
| 332 |
+
g.step(0.05) # start between two 0.1 s grid points
|
| 333 |
+
r = g.call(g.A, 'dual_inlet.start', species='CO2', substance_id='nbs19', sample_bar_ul=100.0, reference_gas=1, cycles=4)
|
| 334 |
+
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
|
| 335 |
+
g.step(r['ends_s'] - g.h.t + 1.0)
|
| 336 |
+
self.assertEqual(g.peaks()[-1]['cycles'], 4)
|
| 337 |
+
_balance(self, g.ledger())
|
| 338 |
+
|
| 339 |
+
def test_h2_h3_factor_and_normalisation(self):
|
| 340 |
+
g = Rig(reference_gases=[dict(species='H2', deltas={'2H': -0.150}), None, None, None, None, None])
|
| 341 |
+
g.ready('H2', deltas={'2H': -0.150})
|
| 342 |
+
_cf_run(g, [], pulses=5, pulse_a=[2e-9, 4e-9, 6e-9, 8e-9, 10e-9], duration=230.0)
|
| 343 |
+
k = g.call(g.A, 'h3.determine', run=1)
|
| 344 |
+
self.assertLess(k['factor_ppm_na'], rt.DOC['h3_factor_max_ppm_na']) # brochure: <= 8.0 ppm/nA
|
| 345 |
+
self.assertAlmostEqual(k['factor_ppm_na'], rt.ENG['h3_factor_ppm_na'], delta=0.3)
|
| 346 |
+
_cf_run(g, [(dict(substance_id='vsmow2'), 4e-6), (dict(substance_id='slap2'), 4e-6), (dict(substance_id='gisp2'), 4e-6)], pulses=1)
|
| 347 |
+
smp = [p for p in g.peaks() if p['type'] == 'sample'][-3:]
|
| 348 |
+
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')])
|
| 349 |
+
gisp2 = [p for p in g.peaks() if p['type'] == 'sample'][-1]
|
| 350 |
+
self.assertAlmostEqual(gisp2['delta_normalized']['2H'], rt.RM['gisp2']['values']['2H']['delta'], delta=1.5e-3)
|
| 351 |
+
self.assertGreater(g.read('calibration.state')['h3_factor_ppm_na'], 0.0)
|
| 352 |
+
|
| 353 |
+
def test_n2_and_linearity(self):
|
| 354 |
+
g = Rig()
|
| 355 |
+
g.ready('N2', ref=2, deltas={'15N': -0.0012})
|
| 356 |
+
amps = [2e-9, 4e-9, 6e-9, 8e-9, 10e-9, 12e-9]
|
| 357 |
+
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)
|
| 358 |
+
for k, a in enumerate(amps)])
|
| 359 |
+
g.call(g.A, 'sample.inject', inlet=1, species='N2', amount_mol=4e-6, substance_id='usgs40', delay_s=230.0)
|
| 360 |
+
g.step(421.0)
|
| 361 |
+
refs = [p for p in g.peaks() if p['type'] == 'reference']
|
| 362 |
+
xs = [a * 1e9 for a in amps]
|
| 363 |
+
ys = [(p['ratios']['29/28'] / refs[0]['ratios']['29/28'] - 1) * 1000.0 for p in refs]
|
| 364 |
+
mx, my = sum(xs) / len(xs), sum(ys) / len(ys)
|
| 365 |
+
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)
|
| 366 |
+
self.assertLess(abs(slope), rt.DOC['cf_linearity_permil_na']['n2_15n']) # brochure: <= 0.02 permil/nA
|
| 367 |
+
smp = [p for p in g.peaks() if p['type'] == 'sample'][0]
|
| 368 |
+
self.assertAlmostEqual(smp['delta_ref']['15N'], rt.RM['usgs40']['values']['15N']['delta'], delta=3e-4)
|
| 369 |
+
|
| 370 |
+
def test_unselected_inlet_vents_and_saturation(self):
|
| 371 |
+
g = Rig()
|
| 372 |
+
g.ready()
|
| 373 |
+
g.call(g.A, 'acquisition.start', duration_s=300.0)
|
| 374 |
+
g.call(g.A, 'sample.inject', inlet=2, species='CO2', amount_mol=4e-6, substance_id='usgs40', delay_s=20.0) # inlet 1 selected
|
| 375 |
+
g.step(301.0)
|
| 376 |
+
self.assertEqual(g.peaks(), [])
|
| 377 |
+
L = g.ledger()
|
| 378 |
+
self.assertAlmostEqual(L['vented_mol']['CO2'], 4e-6, delta=1e-15)
|
| 379 |
+
g.call(g.A, 'acquisition.start', duration_s=300.0)
|
| 380 |
+
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
|
| 381 |
+
g.step(301.0)
|
| 382 |
+
p = g.peaks()[-1]
|
| 383 |
+
self.assertFalse(p['saturated'])
|
| 384 |
+
self.assertLess(g.read('amplifier.state')['resistors_ohm']['44'], rt.ENG['default_resistors_ohm']['CO2'][0])
|
| 385 |
+
g.call(g.A, 'amplifier.configure', mode='fixed', resistors_ohm=[1e11, 1e11, 1e11])
|
| 386 |
+
g.call(g.A, 'acquisition.start', duration_s=300.0)
|
| 387 |
+
g.call(g.A, 'sample.inject', inlet=1, species='CO2', amount_mol=4e-6, substance_id='usgs40', delay_s=20.0)
|
| 388 |
+
g.step(301.0)
|
| 389 |
+
self.assertTrue(g.peaks()[-1]['saturated'])
|
| 390 |
+
_balance(self, g.ledger())
|
| 391 |
+
|
| 392 |
+
def test_faults(self):
|
| 393 |
+
g = Rig()
|
| 394 |
+
g.ready()
|
| 395 |
+
g.call(g.E, 'fault.inject', fault='vacuum_leak', active=True)
|
| 396 |
+
g.step(1.0)
|
| 397 |
+
self.assertFalse(g.read('source.state')['filament']) # vacuum trip
|
| 398 |
+
self.assertIn('VACUUM_TRIP', [e['code'] for e in g.call(g.A, 'events.read', since_s=0.0)['events']])
|
| 399 |
+
g.call(g.E, 'fault.inject', fault='vacuum_leak', active=False)
|
| 400 |
+
g.step(60.0)
|
| 401 |
+
g.call(g.A, 'source.set', filament=True)
|
| 402 |
+
g.call(g.E, 'fault.inject', fault='magnet_drift', active=True)
|
| 403 |
+
g.step(5 * 86400.0)
|
| 404 |
+
off = g.read('truth.process')['field_offset_t']
|
| 405 |
+
self.assertGreater(abs(off), 1e-4)
|
| 406 |
+
c = g.call(g.A, 'magnet.peak_center')
|
| 407 |
+
self.assertAlmostEqual(c['offset_t'], off, delta=1e-9)
|
| 408 |
+
g.call(g.E, 'fault.inject', fault='magnet_drift', active=False)
|
| 409 |
+
g.call(g.E, 'fault.inject', fault='reference_gas_empty', active=True, gas=1)
|
| 410 |
+
_cf_run(g, [], pulses=1, duration=60.0)
|
| 411 |
+
self.assertEqual([p for p in g.peaks() if p['type'] == 'reference'], [])
|
| 412 |
+
g.call(g.E, 'fault.inject', fault='reference_gas_empty', active=False, gas=1)
|
| 413 |
+
g.call(g.E, 'fault.inject', fault='he_supply_empty', active=True)
|
| 414 |
+
g.step(1.0)
|
| 415 |
+
self.assertEqual(g.read('status.led'), 'red')
|
| 416 |
+
self.assertEqual([g.read('indicator.led_' + k) for k in ('green', 'amber', 'red')], [k == 'red' for k in ('green', 'amber', 'red')])
|
| 417 |
+
self.assertFalse(g.read('centrion.state')['carrier_on'])
|
| 418 |
+
g.call(g.A, 'centrion.set', expect='NO_HELIUM', carrier_on=True)
|
| 419 |
+
g.call(g.E, 'fault.inject', fault='he_supply_empty', active=False)
|
| 420 |
+
g.call(g.E, 'fault.inject', fault='filament_burnout', active=True)
|
| 421 |
+
self.assertFalse(g.read('source.state')['filament'])
|
| 422 |
+
g.call(g.E, 'fault.inject', fault='filament_burnout', active=False)
|
| 423 |
+
g.call(g.A, 'source.set', expect='FILAMENT_FAILED', filament=True)
|
| 424 |
+
g.call(g.A, 'hood.set', angle_rad=1.9)
|
| 425 |
+
self.assertEqual(g.read('hood.angle_rad'), 1.9)
|
| 426 |
+
g.call(g.A, 'acquisition.stop')
|
| 427 |
+
_balance(self, g.ledger())
|
| 428 |
+
|
| 429 |
+
def test_quiet_stepping_helium_and_power_toggle(self):
|
| 430 |
+
g = Rig()
|
| 431 |
+
g.ready()
|
| 432 |
+
n = g.h.tick
|
| 433 |
+
he0 = g.ledger()['he_used_m3']
|
| 434 |
+
g.step(30 * 86400.0) # nothing measured: closed-form jump
|
| 435 |
+
self.assertEqual(g.h.tick - n, int(round(30 * 86400.0 / rt.DT)))
|
| 436 |
+
self.assertAlmostEqual(g.ledger()['he_used_m3'] - he0, rt.ENG['carrier_he_m3_s'] * 30 * 86400.0, delta=1e-9)
|
| 437 |
+
self.assertGreater(g.read('source.state')['filament_hours'], 700.0)
|
| 438 |
+
g.call(g.A, 'centrion.set', sleep=True)
|
| 439 |
+
g.call(g.A, 'power.toggle')
|
| 440 |
+
self.assertFalse(g.read('power.on'))
|
| 441 |
+
|
| 442 |
+
|
| 443 |
+
class ReviewFixes(unittest.TestCase):
|
| 444 |
+
"""Regressions of the round-1 review (H3+ repeat, quiet-interval events, filament replacement, dual-inlet stop, auto ranging)."""
|
| 445 |
+
|
| 446 |
+
def test_h3_repeat_is_idempotent(self):
|
| 447 |
+
g = Rig(reference_gases=[dict(species='H2', deltas={'2H': -0.150}), None, None, None, None, None])
|
| 448 |
+
g.ready('H2', deltas={'2H': -0.150})
|
| 449 |
+
_cf_run(g, [], pulses=5, pulse_a=[2e-9, 4e-9, 6e-9, 8e-9, 10e-9], duration=230.0)
|
| 450 |
+
k1 = g.call(g.A, 'h3.determine', run=1)['factor_ppm_na']
|
| 451 |
+
k2 = g.call(g.A, 'h3.determine', run=1)['factor_ppm_na']
|
| 452 |
+
self.assertAlmostEqual(k1, k2, places=12) # a repeat on the same run does not add up
|
| 453 |
+
_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
|
| 454 |
+
k3 = g.call(g.A, 'h3.determine', run=2)['factor_ppm_na']
|
| 455 |
+
self.assertAlmostEqual(k3, k1, delta=0.3)
|
| 456 |
+
self.assertLess(k3, rt.DOC['h3_factor_max_ppm_na'])
|
| 457 |
+
|
| 458 |
+
def test_quiet_events_do_not_depend_on_the_partition(self):
|
| 459 |
+
out = []
|
| 460 |
+
for parts in ([100.0], [0.1] * 1000, [0.05] * 2000, [7.3] * 13 + [5.1]):
|
| 461 |
+
g = Rig()
|
| 462 |
+
g.ready()
|
| 463 |
+
g.call(g.E, 'fault.inject', fault='vacuum_leak', active=True)
|
| 464 |
+
for dt in parts:
|
| 465 |
+
g.step(dt)
|
| 466 |
+
ev = [e for e in g.call(g.A, 'events.read', since_s=0.0)['events'] if e['code'] == 'VACUUM_TRIP']
|
| 467 |
+
out.append((round(g.read('source.state')['filament_hours'], 12), ev[0]['time_s']))
|
| 468 |
+
self.assertTrue(all(o == out[0] for o in out), out)
|
| 469 |
+
life = []
|
| 470 |
+
for parts in ([30 * 86400.0] * 6, [86400.0] * 180):
|
| 471 |
+
g = Rig()
|
| 472 |
+
g.ready()
|
| 473 |
+
for dt in parts:
|
| 474 |
+
g.step(dt)
|
| 475 |
+
ev = [e for e in g.call(g.A, 'events.read', since_s=0.0)['events'] if e['code'] == 'FILAMENT_BURNT']
|
| 476 |
+
life.append((ev[0]['time_s'], g.ledger()['he_used_m3']))
|
| 477 |
+
self.assertAlmostEqual(life[0][0], life[1][0], places=6)
|
| 478 |
+
self.assertAlmostEqual(life[0][1], life[1][1], delta=1e-15)
|
| 479 |
+
|
| 480 |
+
def test_filament_replacement_and_dual_inlet_stop(self):
|
| 481 |
+
g = Rig()
|
| 482 |
+
g.ready()
|
| 483 |
+
g.call(g.E, 'fault.inject', fault='filament_burnout', active=True)
|
| 484 |
+
g.call(g.A, 'source.replace_filament', expect='NOT_VENTED')
|
| 485 |
+
g.call(g.A, 'vacuum.vent')
|
| 486 |
+
g.call(g.A, 'source.replace_filament', expect='HOOD_CLOSED')
|
| 487 |
+
g.call(g.A, 'hood.set', angle_rad=1.6)
|
| 488 |
+
g.call(g.A, 'source.replace_filament', expect='FAULT_ACTIVE')
|
| 489 |
+
g.call(g.E, 'fault.inject', fault='filament_burnout', active=False)
|
| 490 |
+
r = g.call(g.A, 'source.replace_filament')
|
| 491 |
+
self.assertEqual(r['source']['filament_hours'], 0.0)
|
| 492 |
+
g.call(g.A, 'hood.set', angle_rad=0.0)
|
| 493 |
+
g.call(g.A, 'vacuum.pump_down')
|
| 494 |
+
g.step(12 * 3600.0)
|
| 495 |
+
g.call(g.A, 'source.set', filament=True)
|
| 496 |
+
g.call(g.A, 'dual_inlet.start', species='CO2', substance_id='nbs19', sample_bar_ul=100.0, reference_gas=1, cycles=10)
|
| 497 |
+
g.step(250.0)
|
| 498 |
+
r = g.call(g.A, 'acquisition.stop')
|
| 499 |
+
self.assertIsNotNone(r['run'])
|
| 500 |
+
self.assertEqual(g.read('acquisition.state'), {})
|
| 501 |
+
p = g.peaks()[-1]
|
| 502 |
+
self.assertEqual(p['type'], 'dual_inlet')
|
| 503 |
+
self.assertLess(p['cycles'], 10)
|
| 504 |
+
_balance(self, g.ledger())
|
| 505 |
+
|
| 506 |
+
def test_drifted_beams_give_no_delta_and_no_crash(self):
|
| 507 |
+
g = Rig()
|
| 508 |
+
g.ready()
|
| 509 |
+
g.call(g.E, 'fault.inject', fault='magnet_drift', active=True)
|
| 510 |
+
g.step(4 * 86400.0)
|
| 511 |
+
r = g.call(g.A, 'dual_inlet.start', species='CO2', substance_id='nbs19', sample_bar_ul=100.0, reference_gas=1, cycles=4)
|
| 512 |
+
g.step(r['ends_s'] - g.h.t + 1.0)
|
| 513 |
+
p = g.peaks()[-1]
|
| 514 |
+
json.dumps(p) # real numbers only
|
| 515 |
+
self.assertTrue(p['delta_ref'] is None or all(isinstance(v, float) for v in p['delta_ref'].values()))
|
| 516 |
+
_balance(self, g.ledger())
|
| 517 |
+
|
| 518 |
+
def test_off_grid_run_end_and_helium_alarm_time(self):
|
| 519 |
+
res = []
|
| 520 |
+
for parts in ([150.0], None, [0.07] * 2200):
|
| 521 |
+
g = Rig()
|
| 522 |
+
g.ready()
|
| 523 |
+
r = g.call(g.A, 'acquisition.start', duration_s=100.05, reference_pulses=[dict(gas=1, start_s=20.0, duration_s=20.0)])
|
| 524 |
+
self.assertAlmostEqual(r['ends_s'] * 10.0, round(r['ends_s'] * 10.0), places=6) # end on the 0.1 s grid
|
| 525 |
+
for dt in (parts or [r['ends_s'] - g.h.t, 50.0]):
|
| 526 |
+
g.step(dt)
|
| 527 |
+
p = g.peaks()[0]
|
| 528 |
+
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']))
|
| 529 |
+
self.assertTrue(all(x == res[0] for x in res), res)
|
| 530 |
+
times = []
|
| 531 |
+
for parts in ([40000.0], [7.3] * 5480):
|
| 532 |
+
g = Rig(he_supply_gauge_pa=5.0e4)
|
| 533 |
+
g.ready()
|
| 534 |
+
for dt in parts:
|
| 535 |
+
g.step(dt)
|
| 536 |
+
times.append([e['time_s'] for e in g.call(g.A, 'events.read', since_s=0.0)['events'] if e['code'] == 'HELIUM_EMPTY'])
|
| 537 |
+
t_exp = 600.0 + (rt.ENG['he_supply_m3'] * 5.0e4 / 101325.0 - 0.0) / rt.ENG['carrier_he_m3_s']
|
| 538 |
+
self.assertEqual(times[0], times[1])
|
| 539 |
+
self.assertTrue(len(times[0]) == 1 and abs(times[0][0] - t_exp) < 1e-3, (times, t_exp))
|
| 540 |
+
|
| 541 |
+
def test_auto_ranging_restarts_at_each_acquisition(self):
|
| 542 |
+
g = Rig()
|
| 543 |
+
g.ready()
|
| 544 |
+
g.call(g.A, 'acquisition.start', duration_s=300.0)
|
| 545 |
+
g.call(g.A, 'sample.inject', inlet=1, species='CO2', amount_mol=4e-4, substance_id='usgs40', delay_s=20.0)
|
| 546 |
+
g.step(301.0)
|
| 547 |
+
self.assertLess(g.read('amplifier.state')['resistors_ohm']['44'], rt.ENG['default_resistors_ohm']['CO2'][0])
|
| 548 |
+
g.call(g.A, 'acquisition.start', duration_s=60.0)
|
| 549 |
+
self.assertEqual(g.read('amplifier.state')['resistors_ohm'], {})
|
| 550 |
+
|
| 551 |
+
|
| 552 |
+
class ZCoverage(unittest.TestCase):
|
| 553 |
+
def test_all_capabilities_exercised(self):
|
| 554 |
+
missing = set(rt.CAPS) - set(rt.UNSUPPORTED) - SEEN_CAPS
|
| 555 |
+
if len(SEEN_CAPS) > 5:
|
| 556 |
+
self.assertFalse(missing, sorted(missing))
|
| 557 |
+
|
| 558 |
+
|
| 559 |
+
if __name__ == '__main__':
|
| 560 |
+
unittest.main()
|
tests/test_asset_elementar_varioel.py
ADDED
|
@@ -0,0 +1,199 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Independent process, numerical and protocol regressions for CHEM-079 only."""
|
| 2 |
+
import copy,json,math,sys,unittest
|
| 3 |
+
from pathlib import Path
|
| 4 |
+
import numpy as np
|
| 5 |
+
ROOT=Path(__file__).resolve().parents[1];sys.path.insert(0,str(ROOT/'scripts'))
|
| 6 |
+
from asset_runtime import elementar_varioel as r
|
| 7 |
+
|
| 8 |
+
def finish(h,dt=.25):
|
| 9 |
+
for _ in range(2000):
|
| 10 |
+
if h.phase!='running':return
|
| 11 |
+
h.step(dt)
|
| 12 |
+
raise AssertionError('sequence failed to terminate')
|
| 13 |
+
def ready(plant=None,method=None,library=None,instance_id='test_varioel'):
|
| 14 |
+
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
|
| 15 |
+
def load(h,slot=0,kind='sample',mass=2e-6,template='oem_sulfanilic_acid',**extra):
|
| 16 |
+
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)
|
| 17 |
+
def run(h,slots):h.invoke('sequence.configure',slot_indices=slots);h.invoke('sequence.start');finish(h);return h.invoke('result.read')
|
| 18 |
+
def blank(h):load(h,kind='blank');run(h,[0]);return h
|
| 19 |
+
|
| 20 |
+
def calibrated(plant=None,method=None):
|
| 21 |
+
h=blank(ready(plant,method));masses=[1e-6,2e-6,3e-6]
|
| 22 |
+
for slot,m in enumerate(masses,1):load(h,slot,'standard',m)
|
| 23 |
+
result=run(h,[1,2,3])
|
| 24 |
+
for e in r.MODES[h.method['mode']]:
|
| 25 |
+
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)
|
| 26 |
+
return h
|
| 27 |
+
|
| 28 |
+
class ElementarProcessTests(unittest.TestCase):
|
| 29 |
+
def reject_atomic(self,h,code,cap,**args):
|
| 30 |
+
before=repr(h.debug_snapshot())
|
| 31 |
+
with self.assertRaisesRegex(r.ActionRejected,code):h.invoke(cap,**args)
|
| 32 |
+
self.assertEqual(before,repr(h.debug_snapshot()))
|
| 33 |
+
def closed(self,h):
|
| 34 |
+
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)
|
| 35 |
+
def test_source_measurements_are_not_calculated_values(self):
|
| 36 |
+
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'])
|
| 37 |
+
def test_unknown_template_atomic(self):
|
| 38 |
+
h=ready();self.reject_atomic(h,'UNKNOWN_REFERENCE','template.read',substance_id='not-a-source')
|
| 39 |
+
def test_reported_source_sum_rejected_not_normalized(self):
|
| 40 |
+
for fractions in [{e:.4 for e in r.ELEMENTS},{'C':.5,'H':.5,'N':5e-13,'S':0.}]:
|
| 41 |
+
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)
|
| 42 |
+
def test_source_unknown_ack_required(self):
|
| 43 |
+
h=ready();self.reject_atomic(h,'UNKNOWN_CONDITIONS','sample.load',**dict(r.SAMPLE_EXAMPLE,accept_unknown_conditions=False))
|
| 44 |
+
def test_reported_values_cannot_be_host_overwritten(self):
|
| 45 |
+
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)
|
| 46 |
+
def test_source_basis_mismatch(self):
|
| 47 |
+
h=ready();self.reject_atomic(h,'SOURCE_BASIS_MISMATCH','sample.load',**dict(r.SAMPLE_EXAMPLE,mass_basis='assumed_dry'))
|
| 48 |
+
def test_organic_mass_limit(self):
|
| 49 |
+
h=ready();self.reject_atomic(h,'SAMPLE_MASS_LIMIT','sample.load',**dict(r.SAMPLE_EXAMPLE,mass_kg=20.01e-6))
|
| 50 |
+
def test_each_absolute_element_capacity(self):
|
| 51 |
+
for j,e in enumerate(r.ELEMENTS):
|
| 52 |
+
with self.subTest(element=e):
|
| 53 |
+
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)))
|
| 54 |
+
def test_unknown_s_capacity_uses_remainder_bound(self):
|
| 55 |
+
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))
|
| 56 |
+
def test_chn_missing_s_retained_as_unknown(self):
|
| 57 |
+
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)
|
| 58 |
+
def test_chns_missing_s_rejected_before_consumption(self):
|
| 59 |
+
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)
|
| 60 |
+
def test_explicit_missing_s_assumption_has_evidence(self):
|
| 61 |
+
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'])
|
| 62 |
+
def test_zero_sample_mass_not_blank(self):
|
| 63 |
+
h=ready();self.reject_atomic(h,'SAMPLE_MASS_LIMIT','sample.load',**dict(r.SAMPLE_EXAMPLE,mass_kg=0.))
|
| 64 |
+
def test_blank_cannot_hide_sample_mass(self):
|
| 65 |
+
h=ready();self.reject_atomic(h,'BLANK_COMPOSITION','sample.load',**dict(r.BLANK_EXAMPLE,mass_kg=1e-6))
|
| 66 |
+
def test_top_loading_needs_no_front_door(self):
|
| 67 |
+
h=ready();self.assertFalse(h.opened);load(h);self.assertIn(0,h.samples)
|
| 68 |
+
def test_duplicate_slot_rejects_without_inventory_change(self):
|
| 69 |
+
h=ready();load(h);self.reject_atomic(h,'SLOT_OCCUPIED','sample.load',**r.SAMPLE_EXAMPLE)
|
| 70 |
+
def test_tray_unload_preserves_all_mass(self):
|
| 71 |
+
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)
|
| 72 |
+
def test_thermal_exact_first_order_and_net_heat(self):
|
| 73 |
+
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)
|
| 74 |
+
def test_furnace_target_does_not_teleport_temperature(self):
|
| 75 |
+
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)
|
| 76 |
+
def test_tin_flash_is_not_allowed_furnace_setting(self):
|
| 77 |
+
h=ready();self.reject_atomic(h,'INVALID_ARGUMENT','furnace.configure',combustion_k=2073.15,reduction_k=1123.15)
|
| 78 |
+
def test_room_temperature_cannot_run_combustion(self):
|
| 79 |
+
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')
|
| 80 |
+
def test_hot_powered_maintenance_rejected(self):
|
| 81 |
+
h=ready();self.reject_atomic(h,'COLD_SERVICE_REQUIRED','furnace.extend',extension_m=.12)
|
| 82 |
+
def test_cold_slide_requires_door_and_return_before_closing(self):
|
| 83 |
+
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)
|
| 84 |
+
def test_unique_queue_consumes_once(self):
|
| 85 |
+
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')
|
| 86 |
+
def test_empty_and_unblanked_queue_atomic(self):
|
| 87 |
+
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')
|
| 88 |
+
def test_blank_first_with_sample_in_same_queue(self):
|
| 89 |
+
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)
|
| 90 |
+
def test_sample_before_first_blank_rejected(self):
|
| 91 |
+
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')
|
| 92 |
+
def test_finite_carousel_and_ball_transfer(self):
|
| 93 |
+
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)
|
| 94 |
+
while h.stage!='ball_open':h.step(max(1e-8,h._due()))
|
| 95 |
+
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)
|
| 96 |
+
def test_apt_order_and_nonoverlapping_assigned_gates(self):
|
| 97 |
+
h=blank(ready());load(h);q=run(h,[0])['completed_assays'][0];groups=[]
|
| 98 |
+
for p in q['chromatogram']:
|
| 99 |
+
if p['element']!='baseline' and (not groups or groups[-1]!=p['element']):groups.append(p['element'])
|
| 100 |
+
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:])))
|
| 101 |
+
def test_peak_area_independently_integrates_samples(self):
|
| 102 |
+
h=blank(ready());load(h);q=run(h,[0])['completed_assays'][0]
|
| 103 |
+
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)
|
| 104 |
+
def test_baseline_offset_does_not_change_corrected_areas(self):
|
| 105 |
+
results=[]
|
| 106 |
+
for baseline in [.01,.7]:
|
| 107 |
+
h=blank(ready(plant={'tcd_baseline':baseline}));load(h);results.append(run(h,[0])['completed_assays'][0]['areas_s'])
|
| 108 |
+
np.testing.assert_allclose(list(results[0].values()),list(results[1].values()),atol=1e-14,rtol=0)
|
| 109 |
+
def test_finite_conversion_and_oxygen_stoichiometry(self):
|
| 110 |
+
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)
|
| 111 |
+
def test_oxygen_limited_conversion_preserves_unconverted_mass(self):
|
| 112 |
+
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)
|
| 113 |
+
def test_oxygen_supply_checked_for_entire_queue(self):
|
| 114 |
+
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')
|
| 115 |
+
def test_carrier_and_heated_line_interlocks(self):
|
| 116 |
+
for parameter in ['carrier_ready','heated_line_ready']:
|
| 117 |
+
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')
|
| 118 |
+
def test_prior_peak_tails_remain_real_inventory(self):
|
| 119 |
+
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)
|
| 120 |
+
def test_unselected_elements_have_explicit_mass_account(self):
|
| 121 |
+
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)
|
| 122 |
+
def test_apt_timeout_keeps_partial_observations_and_mass(self):
|
| 123 |
+
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)
|
| 124 |
+
def test_cancel_after_transfer_quarantines_and_cold_recovers(self):
|
| 125 |
+
h=blank(ready());load(h);h.invoke('sequence.configure',slot_indices=[0]);h.invoke('sequence.start')
|
| 126 |
+
while h.stage!='combustion':h.step(max(1e-8,h._due()))
|
| 127 |
+
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)
|
| 128 |
+
def test_door_interrupts_without_resurrecting_sample(self):
|
| 129 |
+
h=blank(ready());load(h);h.invoke('sequence.configure',slot_indices=[0]);h.invoke('sequence.start')
|
| 130 |
+
while h.stage!='release':h.step(max(1e-8,h._due()))
|
| 131 |
+
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.temperature<old));self.closed(h)
|
| 132 |
+
def test_uncalibrated_sample_has_areas_but_no_fake_fractions(self):
|
| 133 |
+
h=blank(ready());load(h);q=run(h,[0])['completed_assays'][0];self.assertTrue(all(v>0 for v in q['areas_s'].values()));self.assertEqual(q['fractions'],r._nulls())
|
| 134 |
+
def test_observed_three_standard_fit_recovers_unknown(self):
|
| 135 |
+
h=calibrated();self.assertTrue(h.invoke('calibration.read')['ready']);load(h);q=run(h,[0])['completed_assays'][0]
|
| 136 |
+
for e in r.ELEMENTS:self.assertAlmostEqual(q['fractions'][e],h.templates['oem_sulfanilic_acid']['element_mass_fractions'][e],delta=2e-6)
|
| 137 |
+
def test_calibration_uses_observed_area_not_hidden_truth(self):
|
| 138 |
+
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)
|
| 139 |
+
def test_calibration_rejects_degenerate_nonfinite_and_negative_slope(self):
|
| 140 |
+
h=blank(ready());a=copy.deepcopy(r.CALIBRATION_EXAMPLE);a['observations']=[a['observations'][0]]*3;self.reject_atomic(h,'DEGENERATE_CALIBRATION','calibration.fit',**a)
|
| 141 |
+
a=copy.deepcopy(r.CALIBRATION_EXAMPLE)
|
| 142 |
+
for p in a['observations']:p['peak_area_s']=-p['peak_area_s']
|
| 143 |
+
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)
|
| 144 |
+
def test_calibration_overflow_rejects_atomically(self):
|
| 145 |
+
h=blank(ready());a=copy.deepcopy(r.CALIBRATION_EXAMPLE)
|
| 146 |
+
for p,v in zip(a['observations'],[-1e308,0,1e308]):p['peak_area_s']=v
|
| 147 |
+
self.reject_atomic(h,'CALIBRATION_RANGE','calibration.fit',**a)
|
| 148 |
+
def test_calibration_missing_source_channel_cannot_fit(self):
|
| 149 |
+
h=blank(ready());a=copy.deepcopy(r.CALIBRATION_EXAMPLE);a['element']='S'
|
| 150 |
+
for p in a['observations']:p['reference_id']='ep0459505_compound_01'
|
| 151 |
+
self.reject_atomic(h,'MEASURED_REFERENCE_REQUIRED','calibration.fit',**a)
|
| 152 |
+
def test_calibration_outside_range_returns_null(self):
|
| 153 |
+
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')
|
| 154 |
+
def test_method_invalidates_blank_and_calibration_retains_old_data(self):
|
| 155 |
+
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')
|
| 156 |
+
def test_sequence_results_reset_only_on_next_start(self):
|
| 157 |
+
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)
|
| 158 |
+
def test_partitioned_steps_preserve_observations_and_mass(self):
|
| 159 |
+
a=blank(ready(plant={'seed':11,'tcd_noise_sd':1e-7}));b=blank(ready(plant={'seed':11,'tcd_noise_sd':1e-7}))
|
| 160 |
+
for h in [a,b]:load(h);h.invoke('sequence.configure',slot_indices=[0]);h.invoke('sequence.start')
|
| 161 |
+
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)
|
| 162 |
+
def test_query_purity_and_export_roundtrip(self):
|
| 163 |
+
h=blank(ready());load(h);run(h,[0]);before=repr(h.debug_snapshot())
|
| 164 |
+
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)
|
| 165 |
+
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'])
|
| 166 |
+
def test_public_access_filters_sample_truth_and_host_commands(self):
|
| 167 |
+
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)))
|
| 168 |
+
def test_host_role_and_read_write_binding(self):
|
| 169 |
+
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')
|
| 170 |
+
def test_request_replay_and_conflict_are_atomic(self):
|
| 171 |
+
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)
|
| 172 |
+
def test_history_poll_and_cancel_old_do_not_touch_new(self):
|
| 173 |
+
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)
|
| 174 |
+
def test_cancelled_history_retains_partial_data_and_ownership(self):
|
| 175 |
+
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)
|
| 176 |
+
with self.assertRaisesRegex(r.ActionRejected,'ACCESS_DENIED'):h.session('other').poll(op)
|
| 177 |
+
def test_actual_detector_windows_survive_later_idle_time(self):
|
| 178 |
+
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])
|
| 179 |
+
def test_independent_instances_do_not_share_consumption(self):
|
| 180 |
+
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)
|
| 181 |
+
def test_invalid_step_never_changes_state(self):
|
| 182 |
+
h=ready();before=repr(h.debug_snapshot())
|
| 183 |
+
for dt in [-1,float('nan'),float('inf'),True]:
|
| 184 |
+
with self.assertRaises(r.ActionRejected):h.step(dt)
|
| 185 |
+
self.assertEqual(before,repr(h.debug_snapshot()))
|
| 186 |
+
t=h.time_s;h.step(1e-10);self.assertGreater(h.time_s,t)
|
| 187 |
+
def test_unsupported_options_and_metadata_query_purity(self):
|
| 188 |
+
h=ready()
|
| 189 |
+
for cap in r.UNSUPPORTED:self.reject_atomic(h,'UNSUPPORTED',cap)
|
| 190 |
+
meta=r.export_elementar_varioel_contract_metadata();self.assertEqual(len(meta['capabilities']),23);self.assertEqual(len(meta['state_slots']),31)
|
| 191 |
+
for k,c in meta['capabilities'].items():
|
| 192 |
+
if c['kind']=='query' or k in r.UNSUPPORTED:self.assertEqual(c['state_effects'],[])
|
| 193 |
+
self.assertEqual(meta['capabilities']['sequence.start']['execution']['mode'],'asynchronous')
|
| 194 |
+
def test_schema_rejects_unknown_fields_and_nonfinite(self):
|
| 195 |
+
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')))
|
| 196 |
+
def test_event_budget_rejected_before_sample_consumption(self):
|
| 197 |
+
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')
|
| 198 |
+
|
| 199 |
+
if __name__=='__main__':unittest.main()
|
tests/test_asset_freeman_ft4powder.py
ADDED
|
@@ -0,0 +1,141 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""FT4 powder-only process, metrology schema and owner/host regression tests."""
|
| 2 |
+
import copy,importlib.util,json,math,sys,unittest
|
| 3 |
+
from pathlib import Path
|
| 4 |
+
from unittest import mock
|
| 5 |
+
import numpy as np
|
| 6 |
+
ROOT=Path(__file__).resolve().parents[1];sys.path.insert(0,str(ROOT/'scripts'))
|
| 7 |
+
from asset_runtime import freeman_ft4powder as rt
|
| 8 |
+
OBSERVED=[]
|
| 9 |
+
def call(h,k,**a):
|
| 10 |
+
r=h.invoke(k,**a);OBSERVED.append((k,copy.deepcopy(a),copy.deepcopy(r)));return r
|
| 11 |
+
def setup(mode='dynamic',instance_id='ft4_test',plant=None,sample=None,method=None,gas=None):
|
| 12 |
+
h=rt.FreemanFt4powderRuntime(instance_id)
|
| 13 |
+
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)
|
| 14 |
+
if mode=='permeability':call(h,'gas.open',enabled=True)
|
| 15 |
+
return h
|
| 16 |
+
def finish(h,seconds=300):
|
| 17 |
+
for _ in range(round(seconds/.1)):
|
| 18 |
+
h.step(.1)
|
| 19 |
+
if h.phase!='running':break
|
| 20 |
+
return call(h,'acquisition.result')
|
| 21 |
+
def park(h):
|
| 22 |
+
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)
|
| 23 |
+
class TestFT4Powder(unittest.TestCase):
|
| 24 |
+
def rejected(self,h,k,error='.',**a):
|
| 25 |
+
before=copy.deepcopy(h.__dict__)
|
| 26 |
+
with self.assertRaisesRegex(rt.ActionRejected,error):h.invoke(k,**a)
|
| 27 |
+
self.assertEqual(before,h.__dict__)
|
| 28 |
+
def assert_ledger(self,h):
|
| 29 |
+
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)
|
| 30 |
+
def test_01_dynamic_real_scalar_anchor_and_seventh_bfe(self):
|
| 31 |
+
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)
|
| 32 |
+
def test_02_single_downstroke_not_automatically_bfe(self):
|
| 33 |
+
for cond,cycles in [(1,1),(0,7)]:
|
| 34 |
+
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'])
|
| 35 |
+
def test_03_independent_segment_work_integral(self):
|
| 36 |
+
h=setup();h.invoke('acquisition.start');r=finish(h)
|
| 37 |
+
for p in r['points']:
|
| 38 |
+
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)
|
| 39 |
+
a=rt.CAPS['analysis.energy']['example_arguments'];self.assertAlmostEqual(call(h,'analysis.energy',**a)['energy_j'],.04)
|
| 40 |
+
def test_04_true_seventh_work_matches_scalar_before_sensor_response(self):
|
| 41 |
+
h=setup(sample={'initial_history_factor':1.});h.invoke('acquisition.start')
|
| 42 |
+
while not (h.segment=='measure_down' and h.cycle==6):h.step(.1)
|
| 43 |
+
before=h.mechanical
|
| 44 |
+
while h.segment=='measure_down':h.step(.1)
|
| 45 |
+
self.assertAlmostEqual(h.mechanical-before,2.107,places=7)
|
| 46 |
+
def test_05_filling_history_conditioning_and_mass(self):
|
| 47 |
+
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)
|
| 48 |
+
def test_06_shear_continuum_and_external_yield_fit(self):
|
| 49 |
+
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)
|
| 50 |
+
def test_07_compression_geometry_mass_and_monotonic_density(self):
|
| 51 |
+
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(0<p['compressibility_fraction']<1 for p in r['points']));self.assert_ledger(h)
|
| 52 |
+
def test_08_permeability_darcy_finite_gas_and_external_check(self):
|
| 53 |
+
h=setup('permeability');before=h.gas_stock;call(h,'acquisition.start');r=finish(h);self.assertEqual(r['phase'],'succeeded');self.assertLess(h.gas_stock,before);self.assertGreater(h.pressure,0);self.assertTrue(all(p['permeability_m2']>0 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)
|
| 54 |
+
def test_09_true_setpoints_and_pure_queries(self):
|
| 55 |
+
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)
|
| 56 |
+
def test_10_host_partition_independence_and_zero_dt(self):
|
| 57 |
+
a=setup();b=setup();a.invoke('acquisition.start');b.invoke('acquisition.start');a.step(7.)
|
| 58 |
+
for _ in range(70):b.step(.1)
|
| 59 |
+
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__)
|
| 60 |
+
def test_11_two_instances(self):
|
| 61 |
+
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__)
|
| 62 |
+
def test_12_registered_agent_truth_and_recovery_permissions(self):
|
| 63 |
+
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__)
|
| 64 |
+
for k,a in [('sample.remove',{}),('gas.unload',{}),('ledger.read',{}),('sim.step',{'dt_s':1.})]:
|
| 65 |
+
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__)
|
| 66 |
+
with self.assertRaises(rt.ActionRejected):s.read(instance_id=h.instance_id,state_ids=['truth.powder_mass_kg'])
|
| 67 |
+
with self.assertRaises(rt.ActionRejected):h.register_principal('agent','evaluator')
|
| 68 |
+
def test_13_operation_owner_queries_poll_and_cancel(self):
|
| 69 |
+
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__)
|
| 70 |
+
for k in ['acquisition.result','acquisition.stop']:
|
| 71 |
+
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__)
|
| 72 |
+
with self.assertRaises(rt.ActionRejected):b.poll(op)
|
| 73 |
+
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')
|
| 74 |
+
def test_14_idempotency_and_request_conflict(self):
|
| 75 |
+
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__)
|
| 76 |
+
def test_15_history_source_freeze_and_return_copy(self):
|
| 77 |
+
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))
|
| 78 |
+
def test_16_cancel_keeps_dissipation_packing_and_frozen_result(self):
|
| 79 |
+
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)
|
| 80 |
+
def test_17_safety_door_stops_immediately_and_close_does_not_resume(self):
|
| 81 |
+
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')
|
| 82 |
+
def test_18_tiny_finite_gas_terminal_includes_last_tick(self):
|
| 83 |
+
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)
|
| 84 |
+
def test_19_manufacturer_speed_stroke_force_bounds_atomic(self):
|
| 85 |
+
h=setup()
|
| 86 |
+
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)
|
| 87 |
+
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.)
|
| 88 |
+
def test_20_invalid_engineering_unknown_source_and_overfill(self):
|
| 89 |
+
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)
|
| 90 |
+
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))
|
| 91 |
+
lib=copy.deepcopy(rt.library());lib['substances'][rt.SAMPLE_EXAMPLE['reference_id']]['runtime_usable']=False
|
| 92 |
+
with mock.patch.object(rt,'library',return_value=lib):self.rejected(h,'sample.load','INVALID_REFERENCE',**rt.SAMPLE_EXAMPLE)
|
| 93 |
+
def test_21_condition_scaling_needs_explicit_acceptance(self):
|
| 94 |
+
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)
|
| 95 |
+
def test_22_tool_access_interlocks_and_no_liquid_substitution(self):
|
| 96 |
+
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')
|
| 97 |
+
for k in rt.UNSUPPORTED:self.rejected(h,k,'UNSUPPORTED')
|
| 98 |
+
def test_23_force_torque_resolution_and_supplied_zero_offsets(self):
|
| 99 |
+
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)
|
| 100 |
+
def test_24_force_overload_is_explicit_partial_failure(self):
|
| 101 |
+
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)
|
| 102 |
+
def test_25_stiff_compression_limited_by_axial_rate(self):
|
| 103 |
+
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=[]
|
| 104 |
+
while h.phase=='running':positions.append(h.position);h.step(.1)
|
| 105 |
+
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)
|
| 106 |
+
def test_26_pressure_range_guard(self):
|
| 107 |
+
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)
|
| 108 |
+
def test_27_invalid_numbers_busy_and_dt_atomic(self):
|
| 109 |
+
h=setup()
|
| 110 |
+
for value in [True,float('nan'),float('inf'),-1.]:self.rejected(h,'gas.set_flow',flow_m3_s=value)
|
| 111 |
+
before=copy.deepcopy(h.__dict__)
|
| 112 |
+
for dt in [True,float('nan'),-1.,float('inf')]:
|
| 113 |
+
with self.assertRaises(rt.ActionRejected):h.step(dt)
|
| 114 |
+
self.assertEqual(before,h.__dict__)
|
| 115 |
+
h.invoke('acquisition.start');self.rejected(h,'method.configure','BUSY',**rt.METHOD_EXAMPLE)
|
| 116 |
+
def test_28_powder_gas_recovery_conservation(self):
|
| 117 |
+
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)
|
| 118 |
+
def test_29_environment_bounds_and_no_empirical_claims(self):
|
| 119 |
+
h=rt.FreemanFt4powderRuntime()
|
| 120 |
+
for t in [283.14,313.16]:self.rejected(h,'plant.configure',**dict(rt.PLANT_EXAMPLE,ambient_k=t))
|
| 121 |
+
meta=rt.export_freeman_ft4powder_contract_metadata();self.assertIn('DEM',' '.join(meta['mechanisms']['powder_mechanics']['limitations']));self.assertEqual(meta['capabilities']['noise.empirical']['availability'],'unsupported')
|
| 122 |
+
def test_30_state_effects_cover_actual_changes(self):
|
| 123 |
+
meta=rt.export_freeman_ft4powder_contract_metadata();original=rt.FreemanFt4powderRuntime.invoke
|
| 124 |
+
def audited(h,k,**a):
|
| 125 |
+
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
|
| 126 |
+
with mock.patch.object(rt.FreemanFt4powderRuntime,'invoke',audited):
|
| 127 |
+
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)
|
| 128 |
+
def test_31_source_summary_not_invented_native_trace(self):
|
| 129 |
+
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'])
|
| 130 |
+
def test_31b_stiff_thermal_and_large_host_step(self):
|
| 131 |
+
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)
|
| 132 |
+
def test_31c_thermal_domain_excess_explicitly_fails(self):
|
| 133 |
+
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')
|
| 134 |
+
def test_32_all_actual_capability_and_state_schemas(self):
|
| 135 |
+
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')
|
| 136 |
+
for k,c in rt.CAPS.items():
|
| 137 |
+
if k in rt.UNSUPPORTED:continue
|
| 138 |
+
cases=[v for v in OBSERVED if v[0]==k];self.assertTrue(cases,k)
|
| 139 |
+
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)
|
| 140 |
+
for k,v in h.read().items():self.assertEqual(tool.validate_value(v,meta['state_slots'][k]['value_schema']),[],k)
|
| 141 |
+
if __name__=='__main__':unittest.main()
|
tests/test_asset_frontier_egapy.py
ADDED
|
@@ -0,0 +1,76 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import unittest,copy,json,math,importlib.util
|
| 2 |
+
from pathlib import Path
|
| 3 |
+
from scripts.asset_runtime import frontier_egapy as r
|
| 4 |
+
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)
|
| 5 |
+
OBSERVED=set()
|
| 6 |
+
def call(h,k,a=None):
|
| 7 |
+
v=h.invoke(k,**(a or {}));tool.validate_value(v,r.CAPS[k][1]);OBSERVED.add(k);return v
|
| 8 |
+
def setup(mode='single',**method):
|
| 9 |
+
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
|
| 10 |
+
def until(h,stage,max_s=1200):
|
| 11 |
+
for _ in range(max_s):
|
| 12 |
+
if h.stage==stage:return
|
| 13 |
+
h.step(1.)
|
| 14 |
+
raise AssertionError((stage,h.stage,h.T,h.phase,h.failure))
|
| 15 |
+
def dropped(h):
|
| 16 |
+
call(h,'acquisition.start');until(h,'wait_drop');call(h,'cup.drop');call(h,'acquisition.confirm');return h
|
| 17 |
+
class Tests(unittest.TestCase):
|
| 18 |
+
def assertledger(self,h):
|
| 19 |
+
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)
|
| 20 |
+
for x in l['species']:self.assertLess(abs(x['residual_kg']),1e-18)
|
| 21 |
+
def test_01_schema_and_real_library(self):
|
| 22 |
+
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)
|
| 23 |
+
def test_02_single_and_mass_energy(self):
|
| 24 |
+
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)
|
| 25 |
+
def test_03_double_manual_order(self):
|
| 26 |
+
h=setup('double',td_end_k=373.15);call(h,'acquisition.start');until(h,'wait_insert');self.assertEqual(h.sampler,0.)
|
| 27 |
+
with self.assertRaises(r.ActionRejected):call(h,'acquisition.confirm')
|
| 28 |
+
call(h,'sampler.set',{'down_m':.08});call(h,'acquisition.confirm');until(h,'wait_retract');self.assertEqual(h.sampler,.08)
|
| 29 |
+
with self.assertRaises(r.ActionRejected):call(h,'acquisition.confirm')
|
| 30 |
+
call(h,'sampler.set',{'down_m':0.});call(h,'acquisition.confirm');until(h,'wait_drop')
|
| 31 |
+
with self.assertRaises(r.ActionRejected):call(h,'cup.drop')
|
| 32 |
+
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)
|
| 33 |
+
def test_04_ega_requires_retract(self):
|
| 34 |
+
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)
|
| 35 |
+
def test_05_cancel_hot_continues_chemistry(self):
|
| 36 |
+
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)
|
| 37 |
+
def test_06_power_off_energy(self):
|
| 38 |
+
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)
|
| 39 |
+
def test_07_atomic_invalid(self):
|
| 40 |
+
h=setup();old=copy.deepcopy(h.read('evaluator'))
|
| 41 |
+
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})]:
|
| 42 |
+
with self.assertRaises(r.ActionRejected):call(h,k,a)
|
| 43 |
+
self.assertEqual(h.read('evaluator'),old)
|
| 44 |
+
def test_08_fixed_step_partition(self):
|
| 45 |
+
a=dropped(setup());b=copy.deepcopy(a);a.step(1.7)
|
| 46 |
+
for _ in range(17):b.step(.1)
|
| 47 |
+
self.assertEqual(a.T,b.T);self.assertEqual(a.generated,b.generated);self.assertEqual(a.read('evaluator'),b.read('evaluator'))
|
| 48 |
+
def test_09_isolation_pure_queries(self):
|
| 49 |
+
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)
|
| 50 |
+
def test_10_capacity_and_mass_fraction(self):
|
| 51 |
+
h=setup();h.sample=None
|
| 52 |
+
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.)]:
|
| 53 |
+
with self.assertRaises(r.ActionRejected):call(h,'sample.load',s)
|
| 54 |
+
def test_11_guard_and_unload(self):
|
| 55 |
+
h=setup();call(h,'guard.set',{'lift_m':.18})
|
| 56 |
+
with self.assertRaises(r.ActionRejected):call(h,'acquisition.start')
|
| 57 |
+
call(h,'guard.set',{'lift_m':0.});dropped(h)
|
| 58 |
+
with self.assertRaises(r.ActionRejected):call(h,'guard.set',{'lift_m':.18})
|
| 59 |
+
h.step(500.);self.assertLess(h.T[2],313.15);call(h,'sample.unload');self.assertFalse(h.sample);self.assertledger(h)
|
| 60 |
+
def test_12_species_exact_flow(self):
|
| 61 |
+
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)
|
| 62 |
+
def test_13_depletion(self):
|
| 63 |
+
h=setup();h.carrier=1e-12;call(h,'acquisition.start');h.step(1);self.assertEqual(h.failure,'CARRIER_DEPLETED');self.assertGreaterEqual(h.carrier,0.)
|
| 64 |
+
def test_14_interface_auto(self):
|
| 65 |
+
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)
|
| 66 |
+
def test_15_permissions_idempotency(self):
|
| 67 |
+
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')
|
| 68 |
+
with self.assertRaises(r.ActionRejected):b.poll(x['operation_id'])
|
| 69 |
+
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')
|
| 70 |
+
def test_16_invalid_time_and_unsupported(self):
|
| 71 |
+
h=setup()
|
| 72 |
+
for dt in [-1.,True,float('inf'),float('nan')]:
|
| 73 |
+
with self.assertRaises(r.ActionRejected):h.step(dt)
|
| 74 |
+
for cap in r.UNSUPPORTED:
|
| 75 |
+
with self.assertRaisesRegex(r.ActionRejected,'UNSUPPORTED'):h.invoke(cap)
|
| 76 |
+
if __name__=='__main__':unittest.main()
|
tests/test_asset_fujifilm_dmp2850.py
ADDED
|
@@ -0,0 +1,119 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""CHEM-058 runtime contract, finite ink and uncalibrated physical invariants."""
|
| 2 |
+
import copy,math,unittest
|
| 3 |
+
from scripts.asset_runtime import fujifilm_dmp2850 as m
|
| 4 |
+
def ready(ink=None,method=None,sample=None,pattern=None):
|
| 5 |
+
r=m.FujifilmDmp2850Runtime()
|
| 6 |
+
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))
|
| 7 |
+
r.invoke('power.set',enabled=True);r.invoke('vacuum.set',enabled=True);return r
|
| 8 |
+
def first_flight(r):
|
| 9 |
+
r.invoke('acquisition.start')
|
| 10 |
+
speeds=[r.plant['axis_speed_m_s']]*2+[r.plant['manual_speed_m_s'],r.plant['manual_angle_rad_s']]
|
| 11 |
+
t=max(abs(a-b)/v for a,b,v in zip(r.q,r.target,speeds))
|
| 12 |
+
r.step(max(1e-8,t));assert r.flight is not None
|
| 13 |
+
class TestDmp2850(unittest.TestCase):
|
| 14 |
+
def assertLedger(self,r):
|
| 15 |
+
p=r._product()
|
| 16 |
+
for sp in ['solvent','solute']:
|
| 17 |
+
self.assertAlmostEqual(p['initial_'+sp+'_kg'],sum(p[loc+'_'+sp+'_kg'] for loc in ['cartridge','flight','deposit','waste','evaporated','collected']),delta=1e-17)
|
| 18 |
+
def rejected(self,r,k,**a):
|
| 19 |
+
before=r.debug_snapshot()
|
| 20 |
+
with self.assertRaises(m.ActionRejected):r.invoke(k,**a)
|
| 21 |
+
self.assertEqual(before,r.debug_snapshot())
|
| 22 |
+
def test_specs_picoliter_and_pitch(self):
|
| 23 |
+
self.assertEqual(m.DROP_VOLUME,2.4e-15);self.assertAlmostEqual(m.PITCH,338.6666666667e-6)
|
| 24 |
+
self.assertAlmostEqual(math.degrees(math.asin(20e-6/m.PITCH)),3.3855,places=3)
|
| 25 |
+
def test_configuration_after_world_time(self):
|
| 26 |
+
r=m.FujifilmDmp2850Runtime();r.step(.02);r.invoke('plant.configure',**m.PLANT_EXAMPLE);self.assertTrue(r.read()['plant.configured'])
|
| 27 |
+
def test_read_and_describe_are_pure(self):
|
| 28 |
+
r=ready();before=r.debug_snapshot()
|
| 29 |
+
for _ in range(3):r.read();r.describe();r.session().read(instance_id=r.instance_id)
|
| 30 |
+
self.assertEqual(before,r.debug_snapshot())
|
| 31 |
+
def test_set_temperature_only_target(self):
|
| 32 |
+
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])
|
| 33 |
+
def test_thermal_energy_balance_and_cooldown(self):
|
| 34 |
+
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)
|
| 35 |
+
t=r.temps[:];r.invoke('power.set',enabled=False);r.step(20);self.assertTrue(all(a<b for a,b in zip(r.temps,t)))
|
| 36 |
+
p=r._product();self.assertAlmostEqual(p['heater_input_j'],p['thermal_loss_j']+p['sensible_j'],delta=1e-8)
|
| 37 |
+
def test_temperature_limits_atomic(self):
|
| 38 |
+
r=ready()
|
| 39 |
+
for t in [280.,333.16,float('nan'),True]:self.rejected(r,'thermal.set_temperature',platen_k=t,cartridge_k=298.15)
|
| 40 |
+
def test_invalid_step_atomic(self):
|
| 41 |
+
r=ready()
|
| 42 |
+
for t in [0,-1,float('nan'),float('inf'),True]:
|
| 43 |
+
before=r.debug_snapshot()
|
| 44 |
+
with self.assertRaises(m.ActionRejected):r.step(t)
|
| 45 |
+
self.assertEqual(before,r.debug_snapshot())
|
| 46 |
+
def test_invalid_arguments_atomic(self):
|
| 47 |
+
r=ready()
|
| 48 |
+
for k,a in [('power.set',{'enabled':1}),('power.set',{'enabled':True,'junk':4}),('pattern.configure',dict(m.PATTERN_EXAMPLE,rows=['12'])),('method.configure',dict(m.METHOD_EXAMPLE,nozzles=[1,1]))]:self.rejected(r,k,**a)
|
| 49 |
+
def test_capacity_limited(self):
|
| 50 |
+
r=m.FujifilmDmp2850Runtime();r.invoke('plant.configure',**m.PLANT_EXAMPLE);self.rejected(r,'ink.configure',**dict(m.INK_EXAMPLE,solvent_kg=.002))
|
| 51 |
+
def test_explicit_model_acceptance(self):
|
| 52 |
+
r=m.FujifilmDmp2850Runtime();self.rejected(r,'plant.configure',**dict(m.PLANT_EXAMPLE,accept_uncalibrated_model=False))
|
| 53 |
+
def test_no_refill_single_charge(self):
|
| 54 |
+
r=ready();r.invoke('ink.drain');self.rejected(r,'ink.configure',**m.INK_EXAMPLE);self.assertLedger(r)
|
| 55 |
+
def test_print_area_thickness_boundary(self):
|
| 56 |
+
for h,L in [(.000499,.308),(.0005,.253),(.025,.253)]:
|
| 57 |
+
r=m.FujifilmDmp2850Runtime();r.invoke('plant.configure',**m.PLANT_EXAMPLE);r.invoke('substrate.configure',**dict(m.SAMPLE_EXAMPLE,thickness_m=h,length_m=L))
|
| 58 |
+
r=m.FujifilmDmp2850Runtime();r.invoke('plant.configure',**m.PLANT_EXAMPLE);self.rejected(r,'substrate.configure',**dict(m.SAMPLE_EXAMPLE,thickness_m=.0005,length_m=.254))
|
| 59 |
+
def test_pattern_validation(self):
|
| 60 |
+
r=ready()
|
| 61 |
+
for rows in [['00'],['1','11'],['x'],['1'*17]]:self.rejected(r,'pattern.configure',**dict(m.PATTERN_EXAMPLE,rows=rows))
|
| 62 |
+
self.rejected(r,'pattern.configure',**dict(m.PATTERN_EXAMPLE,x_m=.101))
|
| 63 |
+
def test_waveform_period_and_factor(self):
|
| 64 |
+
r=ready();self.rejected(r,'method.configure',**dict(m.METHOD_EXAMPLE,frequency_hz=15000,dwell_s=.001));self.rejected(r,'method.configure',**dict(m.METHOD_EXAMPLE,voltage_v=1.))
|
| 65 |
+
def test_no_vacuum_no_print(self):
|
| 66 |
+
r=ready();r.invoke('vacuum.set',enabled=False);self.rejected(r,'acquisition.start')
|
| 67 |
+
def test_motion_is_asynchronous(self):
|
| 68 |
+
r=ready();old=r.q[:];r.invoke('axis.move_to',x_m=.05,y_m=-.03,z_m=.003);self.assertEqual(r.q,old);r.step(1);self.assertEqual(r.phase,'succeeded');self.assertEqual(r.q[:3],[.05,-.03,.003])
|
| 69 |
+
def test_manual_angle_target(self):
|
| 70 |
+
r=ready();r.invoke('cartridge.set_angle',angle_rad=.7);self.assertEqual(r.q[3],0.);r.step(1);self.assertEqual(r.q[3],.7)
|
| 71 |
+
def test_nozzle_pattern_offset_compensation(self):
|
| 72 |
+
r=ready();first_flight(r);x,y,n=r.points[0];delta=(n-5.5)*m.PITCH;a=r.q[3]
|
| 73 |
+
self.assertAlmostEqual(r.q[0]+delta*math.cos(a),x-.104)
|
| 74 |
+
self.assertAlmostEqual(-r.q[1]+y-.154,delta*math.sin(a))
|
| 75 |
+
self.assertAlmostEqual(r.q[2]-r.sample['thickness_m'],r.method['gap_m'])
|
| 76 |
+
def test_complete_print_and_mass(self):
|
| 77 |
+
r=ready();r.invoke('acquisition.start');r.step(3);self.assertEqual(r.phase,'succeeded');self.assertEqual(r.drop_count,5);self.assertEqual(len(r.spots),5);self.assertEqual({s['n'] for s in r.spots},{0,5,11});self.assertLedger(r)
|
| 78 |
+
def test_cancel_preserves_inflight_and_partial_product(self):
|
| 79 |
+
r=ready();first_flight(r);self.assertEqual(r.drop_count,1);self.assertFalse(r.spots);r.invoke('acquisition.stop');self.assertIsNotNone(r.flight);r.step(.01);self.assertIsNone(r.flight);self.assertEqual(len(r.spots),1);self.assertEqual(r.phase,'cancelled');self.assertLedger(r)
|
| 80 |
+
def test_power_loss_releases_vacuum_not_material(self):
|
| 81 |
+
r=ready();first_flight(r);r.invoke('power.set',enabled=False);r.step(.01);self.assertFalse(r.vacuum);self.assertEqual(len(r.spots),1);self.assertLedger(r)
|
| 82 |
+
def test_periodic_cleaning_consumes_finite_ink(self):
|
| 83 |
+
r=ready(method=dict(m.METHOD_EXAMPLE,clean_every_drops=2));r.invoke('acquisition.start');r.step(20);self.assertEqual(r.phase,'succeeded');self.assertEqual(r.cleanings,2);self.assertGreater(r.waste[0],0);self.assertLedger(r)
|
| 84 |
+
def test_cancel_cleaning_keeps_waste(self):
|
| 85 |
+
r=ready();r.invoke('axis.move_to',x_m=0,y_m=0,z_m=.003);r.step(1);r.invoke('cleaning.start');r.step(2.02);r.invoke('acquisition.stop');self.assertGreater(r.waste[0],0);self.assertLess(r.waste[0],m.PLANT_EXAMPLE['cleaning_flow_m3_s']*.05*m.INK_EXAMPLE['solvent_density_kg_m3']);self.assertLedger(r)
|
| 86 |
+
def test_empty_cartridge_stops_without_negative_mass(self):
|
| 87 |
+
r=ready(ink=dict(m.INK_EXAMPLE,solvent_kg=789*m.DROP_VOLUME*2.5,solute_kg=0.));r.invoke('acquisition.start');r.step(3);self.assertEqual(r.phase,'failed');self.assertEqual(r.drop_count,2);self.assertEqual(r.fault,'INK_EMPTY');self.assertLedger(r)
|
| 88 |
+
def test_drying_evaporates_only_solvent(self):
|
| 89 |
+
r=ready();r.invoke('acquisition.start');r.step(3);solute=sum(s['m'][1] for s in r.spots);before=r.evaporated[0];r.step(100);self.assertGreater(r.evaporated[0],before);self.assertEqual(sum(s['m'][1] for s in r.spots),solute);self.assertLedger(r)
|
| 90 |
+
def test_dropwatch_uses_fired_drop_and_no_time_advance(self):
|
| 91 |
+
r=ready();r.invoke('axis.move_to',x_m=0,y_m=0,z_m=.003);r.step(1);r.invoke('dropwatch.start');r.step(3);self.assertEqual(r.drop_count,1);self.assertGreater(r.waste[0],0);before=r.debug_snapshot();c=r.invoke('dropwatch.observe',delay_s=.0001);self.assertEqual(before,r.debug_snapshot());self.assertEqual(len(c['pixels']),4096);self.assertIn(32,c['pixels']);self.assertAlmostEqual(c['drop_diameter_m'],(6*m.DROP_VOLUME/math.pi)**(1/3));self.assertLedger(r)
|
| 92 |
+
def test_camera_after_impact_blank_and_uncalibrated(self):
|
| 93 |
+
r=ready();self.rejected(r,'dropwatch.observe',delay_s=.0001);first_flight(r);c=r.invoke('dropwatch.observe',delay_s=.01);self.assertEqual(set(c['pixels']),{240});self.assertIn('synthetic',c['evidence'])
|
| 94 |
+
def test_collection_and_drain(self):
|
| 95 |
+
r=ready();r.invoke('acquisition.start');r.step(3);r.invoke('product.collect',recipient_id='slide');self.assertFalse(r.sample_present);self.assertFalse(r.spots);self.assertGreater(r.collected[1],0);r.invoke('ink.drain');self.assertEqual(r.cartridge,[0,0]);self.assertLedger(r)
|
| 96 |
+
def test_busy_and_inflight_attachment_rejected(self):
|
| 97 |
+
r=ready();first_flight(r);self.rejected(r,'method.configure',**m.METHOD_EXAMPLE);r.invoke('acquisition.stop');self.rejected(r,'product.collect',recipient_id='x')
|
| 98 |
+
def test_independent_instances(self):
|
| 99 |
+
a,b=ready(),ready();before=b.debug_snapshot();a.invoke('acquisition.start');a.step(3);self.assertEqual(before,b.debug_snapshot())
|
| 100 |
+
def test_reference_no_extrapolation(self):
|
| 101 |
+
r=ready();self.assertGreater(r.invoke('reference.lookup',substance_id='ethanol',temperature_k=298.15)['vapor_pressure_pa'],1000);self.rejected(r,'reference.lookup',substance_id='ethanol',temperature_k=100.);self.rejected(r,'reference.lookup',substance_id='no_such_ink',temperature_k=298.15)
|
| 102 |
+
def test_session_truth_and_role_isolation(self):
|
| 103 |
+
r=ready();s=r.session();self.assertNotIn('truth.ledger',s.describe(instance_id=r.instance_id)['state_slots'])
|
| 104 |
+
for cap in ['product.read','ink.drain','vacuum.set']:
|
| 105 |
+
out=s.invoke(instance_id=r.instance_id,capability_id=cap,arguments={'enabled':False} if cap=='vacuum.set' else {},request_id=cap);self.assertEqual(out['error']['code'],'ACCESS_DENIED');self.assertEqual(out['result'],{})
|
| 106 |
+
with self.assertRaises(m.ActionRejected):s.read(instance_id=r.instance_id,state_ids=['truth.ledger'])
|
| 107 |
+
def test_session_idempotency_and_conflict(self):
|
| 108 |
+
r=ready();s=r.session();args=dict(instance_id=r.instance_id,capability_id='power.set',arguments={'enabled':True},request_id='one');a=s.invoke(**args);rev=r.revision;self.assertEqual(s.invoke(**args),a);self.assertEqual(r.revision,rev);args['arguments']={'enabled':False};self.assertEqual(s.invoke(**args)['error']['code'],'REQUEST_CONFLICT');self.assertTrue(r.powered)
|
| 109 |
+
def test_session_poll_cancel_owner_and_write(self):
|
| 110 |
+
r=ready();r.register_principal('second');s=r.session();out=s.invoke(instance_id=r.instance_id,capability_id='acquisition.start',arguments={},request_id='p');op=out['operation_id'];self.assertEqual(out['status'],'accepted')
|
| 111 |
+
before=r.debug_snapshot();s.poll(op);self.assertEqual(before,r.debug_snapshot())
|
| 112 |
+
with self.assertRaises(m.ActionRejected):r.session('second').poll(op)
|
| 113 |
+
s.cancel(op,'c');self.assertEqual(r.phase,'cancelled');s.write(instance_id=r.instance_id,state_id='thermal.enabled',value=True,request_id='heat');self.assertTrue(r.heating)
|
| 114 |
+
def test_step_partition_mass_positions(self):
|
| 115 |
+
a,b=ready(),ready();a.invoke('acquisition.start');b.invoke('acquisition.start');a.step(3)
|
| 116 |
+
for _ in range(300):b.step(.01)
|
| 117 |
+
self.assertEqual(a.q,b.q);self.assertEqual(a.drop_count,b.drop_count);self.assertEqual(a.phase,b.phase);self.assertLedger(a);self.assertLedger(b)
|
| 118 |
+
self.assertAlmostEqual(a.evaporated[0],b.evaporated[0],delta=1e-16)
|
| 119 |
+
if __name__=='__main__':unittest.main()
|
tests/test_asset_gas_flavourspec25gc.py
ADDED
|
@@ -0,0 +1,88 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from pathlib import Path
|
| 2 |
+
import sys,unittest,copy,json,importlib.util,math
|
| 3 |
+
ROOT=Path(__file__).resolve().parents[1];sys.path.insert(0,str(ROOT/'scripts'))
|
| 4 |
+
from asset_runtime.gas_flavourspec25gc import *
|
| 5 |
+
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)
|
| 6 |
+
OBSERVED=set()
|
| 7 |
+
def call(r,k,**a):
|
| 8 |
+
v=r.invoke(k,**a);err=tool.validate_value(v,CAPS[k][1]);assert not err,err;OBSERVED.add(k);return v
|
| 9 |
+
def prepared(plant=None,method=None,sample=None):
|
| 10 |
+
r=GasFlavourspec25gcRuntime();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);r.step(20.);call(r,'gas.set',enabled=True);return r
|
| 11 |
+
class GCIMS(unittest.TestCase):
|
| 12 |
+
def test_metadata_schema(self):
|
| 13 |
+
r=prepared();m=r.describe()
|
| 14 |
+
for k,c in m['capabilities'].items():self.assertEqual(tool.validate_value(c['example_arguments'],c['input_schema']),[],k)
|
| 15 |
+
for k,v in r.read('evaluator').items():self.assertEqual(tool.validate_value(v,m['state_slots'][k]['value_schema']),[],k)
|
| 16 |
+
def test_pure_queries_and_targets(self):
|
| 17 |
+
r=GasFlavourspec25gcRuntime();call(r,'plant.configure',**PLANT_EXAMPLE);t=copy.deepcopy(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)
|
| 18 |
+
def test_manufacturer_bounds_atomic(self):
|
| 19 |
+
r=GasFlavourspec25gcRuntime();call(r,'plant.configure',**PLANT_EXAMPLE)
|
| 20 |
+
for field,value in [('gc_k',373.16),('ims_k',373.16),('injector_k',473.16),('column_length_m',60.01),('accept_method_transfer',False)]:
|
| 21 |
+
before=copy.deepcopy(r.__dict__)
|
| 22 |
+
with self.assertRaises(ActionRejected):r.invoke('method.configure',**dict(METHOD_EXAMPLE,**{field:value}))
|
| 23 |
+
self.assertEqual(r.__dict__,before)
|
| 24 |
+
def test_invalid_inputs(self):
|
| 25 |
+
r=prepared()
|
| 26 |
+
for a in [{'enabled':1},{'enabled':True,'extra':3}]:
|
| 27 |
+
with self.assertRaises(ActionRejected):r.invoke('gas.set',**a)
|
| 28 |
+
for dt in [True,float('nan'),-1,float('inf')]:
|
| 29 |
+
before=copy.deepcopy(r.__dict__)
|
| 30 |
+
with self.assertRaises(ActionRejected):r.step(dt)
|
| 31 |
+
self.assertEqual(r.__dict__,before)
|
| 32 |
+
def test_all_templates_77_unique_80_channels(self):
|
| 33 |
+
r=GasFlavourspec25gcRuntime();self.assertEqual(len(r.templates),77);self.assertEqual(sum(len(t['channels']) for t in r.templates.values()),80)
|
| 34 |
+
for sid in r.templates:
|
| 35 |
+
t=call(r,'template.read',substance_id=sid);self.assertGreater(min(t['retention_times_s']),0);self.assertGreater(min(t['drift_ratios']),.5)
|
| 36 |
+
def test_sixty_positions_and_bad_sample(self):
|
| 37 |
+
self.assertEqual(len({tuple(vial_target(i)) for i in range(60)}),60)
|
| 38 |
+
for idx in [0,9,50,59]:
|
| 39 |
+
r=prepared(sample=dict(SAMPLE_EXAMPLE,vial_index=idx));call(r,'acquisition.start');r.step(11);self.assertEqual(r.q,vial_target(idx))
|
| 40 |
+
r=GasFlavourspec25gcRuntime();call(r,'plant.configure',**PLANT_EXAMPLE)
|
| 41 |
+
for s in [dict(SAMPLE_EXAMPLE,vial_index=60),dict(SAMPLE_EXAMPLE,headspace_m3=15e-6,vial_m3='10mL'),dict(SAMPLE_EXAMPLE,solutes=[dict(substance_id='fake',mole_fraction=.2)])]:
|
| 42 |
+
before=copy.deepcopy(r.__dict__)
|
| 43 |
+
with self.assertRaises(ActionRejected):r.invoke('sample.load',**s)
|
| 44 |
+
self.assertEqual(r.__dict__,before)
|
| 45 |
+
def test_ready_interlock_and_motion(self):
|
| 46 |
+
r=prepared();call(r,'gas.set',enabled=False);call(r,'cover.set',angle_rad=1.)
|
| 47 |
+
with self.assertRaises(ActionRejected):r.invoke('gas.set',enabled=True)
|
| 48 |
+
call(r,'cover.set',angle_rad=0);call(r,'gantry.move',x_m=.1,y_m=.2,z_m=.1);self.assertEqual(r.q,[.1,.2,.1]);call(r,'gas.set',enabled=True);call(r,'acquisition.start')
|
| 49 |
+
for k,a in [('cover.set',dict(angle_rad=1.)),('gantry.move',dict(x_m=0.,y_m=0.,z_m=0.)),('sample.unload',{})]:
|
| 50 |
+
with self.assertRaisesRegex(ActionRejected,'BUSY'):r.invoke(k,**a)
|
| 51 |
+
def test_complete_moles_and_signal(self):
|
| 52 |
+
r=prepared();call(r,'acquisition.start')
|
| 53 |
+
for _ in range(198):r.step(1.)
|
| 54 |
+
self.assertEqual(r.phase,'succeeded');l=call(r,'ledger.read');self.assertLess(abs(l['total_residual_mol']),1e-12);self.assertLess(abs(l['analyte_residual_mol']),1e-20);self.assertEqual(l['syringe_mol'],0.);self.assertGreater(l['exhaust_mol'],0.);area=call(r,'signal.integrate',**ROI_EXAMPLE)['area_s'];expected=sum(b['eluted'] for b in r.bands)*r.plant['gain_s_per_mol'];self.assertAlmostEqual(area,expected,delta=1e-6);self.assertTrue(call(r,'process.measure')['complete'])
|
| 55 |
+
def test_cancel_preserves_syringe_and_purge(self):
|
| 56 |
+
r=prepared();call(r,'acquisition.start');r.step(13.);self.assertIsNotNone(r.syringe);call(r,'acquisition.stop');l=r._ledger();r.step(100);self.assertEqual(l,r._ledger());call(r,'sample.unload');self.assertEqual(r._ledger()['syringe_mol'],l['syringe_mol']);call(r,'syringe.purge');self.assertEqual(r._ledger()['syringe_mol'],0.);self.assertLess(abs(r._ledger()['total_residual_mol']),1e-12)
|
| 57 |
+
def test_cancel_after_injection_preserves_column(self):
|
| 58 |
+
r=prepared();call(r,'acquisition.start');r.step(50);call(r,'acquisition.stop');l=r._ledger();self.assertGreater(l['column_mol'],0);r.step(30);self.assertEqual(l,r._ledger());call(r,'sample.unload');self.assertEqual(r._ledger()['column_mol'],l['column_mol']);self.assertLess(abs(r._ledger()['total_residual_mol']),1e-12)
|
| 59 |
+
def test_finite_gas_failure(self):
|
| 60 |
+
r=prepared(plant=dict(PLANT_EXAMPLE,gas_supply_mol=1e-4));call(r,'acquisition.start');r.step(500);self.assertEqual(r.phase,'failed');self.assertLess(r.supply,1e-15);self.assertLess(abs(r._ledger()['total_residual_mol']),1e-12)
|
| 61 |
+
def test_partition_invariance(self):
|
| 62 |
+
rs=[prepared(),prepared()]
|
| 63 |
+
for r in rs:call(r,'acquisition.start')
|
| 64 |
+
rs[0].step(198)
|
| 65 |
+
for _ in range(1980):rs[1].step(.1)
|
| 66 |
+
for k in ['column_mol','exhaust_mol','sample_remaining_mol','gas_remaining_mol']:self.assertAlmostEqual(rs[0]._ledger()[k],rs[1]._ledger()[k],delta=1e-11)
|
| 67 |
+
self.assertAlmostEqual(call(rs[0],'signal.integrate',**ROI_EXAMPLE)['area_s'],call(rs[1],'signal.integrate',**ROI_EXAMPLE)['area_s'],delta=1e-7)
|
| 68 |
+
def test_observed_calibration_and_fingerprint(self):
|
| 69 |
+
r=prepared();call(r,'calibration.fit',**CAL_EXAMPLE);call(r,'acquisition.start')
|
| 70 |
+
for _ in range(198):r.step(1.)
|
| 71 |
+
a=call(r,'concentration.analyze');area=call(r,'signal.integrate',**ROI_EXAMPLE)['area_s'];self.assertEqual(a['quality'],'estimated');self.assertAlmostEqual(a['concentration_mol_m3'],area/500.)
|
| 72 |
+
r.sample['sample_id']='hidden';r.sample['species']={};self.assertEqual(call(r,'concentration.analyze'),a)
|
| 73 |
+
features=call(r,'fingerprint.compare',reference=[0.]*1920)['features'];self.assertAlmostEqual(call(r,'fingerprint.compare',reference=features)['cosine_similarity'],1.)
|
| 74 |
+
def test_invalid_calibration_and_incomplete(self):
|
| 75 |
+
r=prepared();self.assertEqual(call(r,'concentration.analyze')['quality'],'incomplete');before=copy.deepcopy(r.__dict__)
|
| 76 |
+
with self.assertRaises(ActionRejected):r.invoke('calibration.fit',**dict(CAL_EXAMPLE,standards=[CAL_EXAMPLE['standards'][0]]*2))
|
| 77 |
+
self.assertEqual(r.__dict__,before)
|
| 78 |
+
def test_session_owner_dedup_and_isolation(self):
|
| 79 |
+
r=prepared();other=prepared();before=copy.deepcopy(other.__dict__);r.register_principal('a');r.register_principal('b');a=r.session('a');b=r.session('b');i=r.instance_id
|
| 80 |
+
self.assertNotIn('sample.identity',a.read(instance_id=i)['observations']);self.assertNotIn('ledger.read',a.describe(instance_id=i)['capabilities']);self.assertEqual(a.invoke(instance_id=i,capability_id='ledger.read',arguments={},request_id='d')['error']['code'],'ACCESS_DENIED')
|
| 81 |
+
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']
|
| 82 |
+
with self.assertRaises(ActionRejected):b.poll(op)
|
| 83 |
+
r.step(13);a.cancel(op,'stop');self.assertEqual(a.poll(op)['status'],'cancelled');self.assertEqual(other.__dict__,before)
|
| 84 |
+
def test_unsupported(self):
|
| 85 |
+
r=prepared()
|
| 86 |
+
for k in UNSUPPORTED:
|
| 87 |
+
with self.assertRaisesRegex(ActionRejected,'UNSUPPORTED'):r.invoke(k)
|
| 88 |
+
if __name__=='__main__':unittest.main()
|
tests/test_asset_glatt_miniglatt.py
ADDED
|
@@ -0,0 +1,121 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Mini-Glatt2012 actual numerical/contract boundary regression tests."""
|
| 2 |
+
import copy,json,math,sys,unittest
|
| 3 |
+
from pathlib import Path
|
| 4 |
+
ROOT=Path(__file__).resolve().parents[1];sys.path.insert(0,str(ROOT/'scripts'))
|
| 5 |
+
from asset_runtime.glatt_miniglatt import *
|
| 6 |
+
def prepared(method=None,plant=None,powder=None,liquid=None,micro=False):
|
| 7 |
+
h=GlattMiniglattRuntime();h.invoke('plant.configure',**(plant or PLANT_EXAMPLE))
|
| 8 |
+
h.invoke('kit.configure',micro=micro,micro_maximum_kg=.025,accept_host_attachment=True)
|
| 9 |
+
h.invoke('powder.load',**(powder or POWDER_EXAMPLE));h.invoke('liquid.load',**(liquid or LIQUID_EXAMPLE))
|
| 10 |
+
h.invoke('method.configure',**(method or METHOD_EXAMPLE));h.invoke('tower.set',opened=False);h.invoke('power.set',enabled=True);return h
|
| 11 |
+
class GlattTests(unittest.TestCase):
|
| 12 |
+
def atomic(self,h,k,**a):
|
| 13 |
+
before=h.debug_snapshot()
|
| 14 |
+
with self.assertRaises(ActionRejected):h.invoke(k,**a)
|
| 15 |
+
self.assertEqual(before,h.debug_snapshot())
|
| 16 |
+
def conserve(self,h):
|
| 17 |
+
p=h.invoke('product.read')
|
| 18 |
+
for i in range(3):self.assertAlmostEqual(p['initial_kg'][i],sum(p[x+'_kg'][i] for x in LOCS if x!='initial'),delta=1e-11)
|
| 19 |
+
self.assertAlmostEqual(p['heater_input_j'],sum(p[k] for k in ['exhaust_sensible_j','loss_j','latent_j','vapor_sensible_j','bed_sensible_j','filter_sensible_j','collected_sensible_j']),delta=2e-6)
|
| 20 |
+
self.assertTrue(all(v>=-1e-14 for loc in LOCS for v in p[loc+'_kg']))
|
| 21 |
+
def test_default_conservation_and_finite_time(self):
|
| 22 |
+
h=prepared();h.invoke('acquisition.start');h.step(60);self.assertEqual(h.phase,'succeeded');self.assertEqual(h.elapsed_s,60.);self.conserve(h)
|
| 23 |
+
def test_no_fluidization_atomic_start(self):
|
| 24 |
+
h=prepared(method=dict(METHOD_EXAMPLE,air_normal_m3_s=1e-9));self.atomic(h,'acquisition.start');self.assertFalse(h.air)
|
| 25 |
+
def test_drop_air_flow_stops_with_partial_material(self):
|
| 26 |
+
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)
|
| 27 |
+
def test_total_air_includes_atomizer(self):
|
| 28 |
+
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)
|
| 29 |
+
def test_power_kva_not_kw(self):
|
| 30 |
+
h=GlattMiniglattRuntime();self.atomic(h,'plant.configure',**dict(PLANT_EXAMPLE,heater_w=3300.))
|
| 31 |
+
def test_inlet_power_limited(self):
|
| 32 |
+
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)
|
| 33 |
+
def test_inlet_80_limit_atomic(self):
|
| 34 |
+
h=prepared();h.invoke('thermal.set_temperature',temperature_k=353.15);self.atomic(h,'thermal.set_temperature',temperature_k=353.16)
|
| 35 |
+
def test_temperature_target_not_bed_jump(self):
|
| 36 |
+
h=prepared();t=h._temperature();h.invoke('thermal.set_temperature',temperature_k=353.15);self.assertEqual(t,h._temperature())
|
| 37 |
+
def test_pump_100ml_min_limit(self):
|
| 38 |
+
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)
|
| 39 |
+
def test_finite_tank_exhaustion(self):
|
| 40 |
+
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)
|
| 41 |
+
def test_spray_stops_after_scheduled_window(self):
|
| 42 |
+
h=prepared();h.invoke('acquisition.start');h.step(45);mass=copy.deepcopy(h.mass['tank']);h.step(15);self.assertEqual(mass,h.mass['tank'])
|
| 43 |
+
def test_standard_25g_lower_limit(self):
|
| 44 |
+
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))
|
| 45 |
+
def test_standard_375g_upper_limit(self):
|
| 46 |
+
h=GlattMiniglattRuntime();h.invoke('plant.configure',**PLANT_EXAMPLE);h.invoke('powder.load',**dict(POWDER_EXAMPLE,dry_mass_kg=.375))
|
| 47 |
+
def test_micro_minimum_and_bottom(self):
|
| 48 |
+
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)
|
| 49 |
+
def test_micro_top_rejected(self):
|
| 50 |
+
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)
|
| 51 |
+
def test_micro_unknown_max_explicit(self):
|
| 52 |
+
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))
|
| 53 |
+
def test_drying_no_spray(self):
|
| 54 |
+
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)
|
| 55 |
+
def test_coating_conserves_particle_count(self):
|
| 56 |
+
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)
|
| 57 |
+
def test_aggregation_reduces_count(self):
|
| 58 |
+
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)
|
| 59 |
+
def test_breakage_no_mass_loss(self):
|
| 60 |
+
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)
|
| 61 |
+
def test_filter_clog_fails(self):
|
| 62 |
+
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)
|
| 63 |
+
def test_blowback_requires_step_and_returns_fraction(self):
|
| 64 |
+
h=prepared();h.invoke('acquisition.start');h.step(20);h.invoke('acquisition.stop');old=copy.deepcopy(h.mass['filter']);air=h.air_used
|
| 65 |
+
h.invoke('filter.clean');self.assertEqual(old,h.mass['filter']);h.step(.5)
|
| 66 |
+
for a,b in zip(old,h.mass['filter']):self.assertAlmostEqual(b,a*.15,delta=1e-14)
|
| 67 |
+
self.assertAlmostEqual(h.air_used-air,100/3600*.5,delta=1e-12);self.conserve(h)
|
| 68 |
+
def test_blowback_not_during_run(self):
|
| 69 |
+
h=prepared();h.invoke('acquisition.start');self.atomic(h,'filter.clean')
|
| 70 |
+
def test_open_tower_interrupts_preserves(self):
|
| 71 |
+
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)
|
| 72 |
+
def test_power_loss_preserves(self):
|
| 73 |
+
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)
|
| 74 |
+
def test_collection_keeps_filter_and_heat(self):
|
| 75 |
+
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)
|
| 76 |
+
def test_no_rebind_powder_or_liquid(self):
|
| 77 |
+
h=prepared();h.invoke('tower.set',opened=True);self.atomic(h,'powder.load',**POWDER_EXAMPLE);self.atomic(h,'liquid.load',**LIQUID_EXAMPLE)
|
| 78 |
+
def test_heater_requires_flow(self):
|
| 79 |
+
h=prepared();self.atomic(h,'heating.set',enabled=True)
|
| 80 |
+
def test_queries_read_describe_pure(self):
|
| 81 |
+
h=prepared();before=h.debug_snapshot()
|
| 82 |
+
h.read();h.session().read(instance_id=h.instance_id);h.session().describe(instance_id=h.instance_id)
|
| 83 |
+
for k in ['product.read','granulation.measure']:h.invoke(k)
|
| 84 |
+
h.invoke('reference.lookup',substance_id='mutylo_g1');self.assertEqual(before,h.debug_snapshot())
|
| 85 |
+
def test_real_sieve_not_DLS(self):
|
| 86 |
+
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')
|
| 87 |
+
def test_truth_filter(self):
|
| 88 |
+
h=prepared();s=h.session();self.assertNotIn('truth.ledger',s.describe(instance_id=h.instance_id)['state_slots'])
|
| 89 |
+
self.assertEqual(s.invoke(instance_id=h.instance_id,capability_id='product.read',arguments={},request_id='x')['error']['code'],'ACCESS_DENIED')
|
| 90 |
+
with self.assertRaises(ActionRejected):s.read(instance_id=h.instance_id,state_ids=['truth.ledger'])
|
| 91 |
+
def test_session_idempotency_conflict(self):
|
| 92 |
+
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')
|
| 93 |
+
def test_poll_owner_and_cancel_partial(self):
|
| 94 |
+
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)
|
| 95 |
+
with self.assertRaises(ActionRejected):h.session('other').poll(op)
|
| 96 |
+
s.cancel(op,'cancel');self.assertEqual(s.poll(op)['status'],'cancelled');self.conserve(h)
|
| 97 |
+
def test_write_route(self):
|
| 98 |
+
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.)
|
| 99 |
+
with self.assertRaises(ActionRejected):h.session().write(instance_id=h.instance_id,state_id='truth.ledger',value={},request_id='bad')
|
| 100 |
+
def test_foreign_instance(self):
|
| 101 |
+
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)
|
| 102 |
+
def test_panel_toggles(self):
|
| 103 |
+
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)
|
| 104 |
+
def test_panel_heat_toggle_atomic_without_air(self):
|
| 105 |
+
h=prepared();self.atomic(h,'heating.toggle')
|
| 106 |
+
def test_two_instances_isolated(self):
|
| 107 |
+
a=prepared();b=prepared();before=b.debug_snapshot();a.invoke('acquisition.start');a.step(10);self.assertEqual(before,b.debug_snapshot())
|
| 108 |
+
def test_nan_bool_and_unknown_atomic(self):
|
| 109 |
+
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')
|
| 110 |
+
def test_zero_and_invalid_time(self):
|
| 111 |
+
h=prepared();before=h.debug_snapshot();h.step(0);self.assertEqual(before,h.debug_snapshot())
|
| 112 |
+
with self.assertRaises(ActionRejected):h.step(-1)
|
| 113 |
+
def test_time_partition_selected_case(self):
|
| 114 |
+
a=prepared();b=prepared();a.invoke('acquisition.start');b.invoke('acquisition.start');a.step(60)
|
| 115 |
+
for _ in range(6000):b.step(.01)
|
| 116 |
+
for loc in LOCS:
|
| 117 |
+
for x,y in zip(a.mass[loc],b.mass[loc]):self.assertAlmostEqual(x,y,delta=2e-7)
|
| 118 |
+
self.assertAlmostEqual(a._temperature(),b._temperature(),delta=.005);self.conserve(a);self.conserve(b)
|
| 119 |
+
def test_normal_flow_conversion_and_ergun_weight(self):
|
| 120 |
+
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'])
|
| 121 |
+
if __name__=='__main__':unittest.main()
|
tests/test_asset_ika_t25.py
ADDED
|
@@ -0,0 +1,87 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import copy,math,sys,unittest
|
| 2 |
+
from pathlib import Path
|
| 3 |
+
ROOT=Path(__file__).resolve().parents[1];sys.path.insert(0,str(ROOT/'scripts'))
|
| 4 |
+
from asset_runtime.ika_t25 import *
|
| 5 |
+
def prepared(i='t25_01',plant=None,sample=None,method=None):
|
| 6 |
+
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
|
| 7 |
+
class T25Test(unittest.TestCase):
|
| 8 |
+
def test_target_not_teleport(self):
|
| 9 |
+
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)
|
| 10 |
+
def test_queries_pure(self):
|
| 11 |
+
r=prepared();s=r.debug_snapshot();r.describe();r.read();r.invoke('dispersion.measure');r.invoke('product.read');self.assertEqual(s,r.debug_snapshot())
|
| 12 |
+
def test_rejected_atomic(self):
|
| 13 |
+
r=prepared();r.invoke('acquisition.start');s=r.debug_snapshot()
|
| 14 |
+
with self.assertRaises(ActionRejected):r.invoke('mount.set_immersion',immersion_m=.065)
|
| 15 |
+
self.assertEqual(s,r.debug_snapshot())
|
| 16 |
+
def test_missing_mount(self):
|
| 17 |
+
r=prepared();r.invoke('mount.configure',head_locked=False,vessel_clamped=True)
|
| 18 |
+
with self.assertRaises(ActionRejected):r.invoke('acquisition.start')
|
| 19 |
+
def test_speed_si(self):
|
| 20 |
+
r=prepared()
|
| 21 |
+
for w in [2999*math.tau/60,25001*math.tau/60,True,float('nan'),float('inf')]:
|
| 22 |
+
with self.assertRaises(ActionRejected):r.invoke('motor.set_speed',speed_rad_s=w)
|
| 23 |
+
def test_step_invalid(self):
|
| 24 |
+
r=prepared()
|
| 25 |
+
for x in [True,-1,float('nan'),float('inf'),3601]:
|
| 26 |
+
with self.assertRaises(ActionRejected):r.step(x)
|
| 27 |
+
def test_viscosity_si(self):
|
| 28 |
+
s=example_sample();s['viscosity_Pa_s']=5000
|
| 29 |
+
with self.assertRaises(ActionRejected):prepared(sample=s)
|
| 30 |
+
def test_head_not_st(self):
|
| 31 |
+
m=copy.deepcopy(METHOD_EXAMPLE);m['head']='s25_n18g_st'
|
| 32 |
+
with self.assertRaises(ActionRejected):prepared(method=m)
|
| 33 |
+
def test_no_timer_invention(self):
|
| 34 |
+
m=copy.deepcopy(METHOD_EXAMPLE);m['duration_s']=61
|
| 35 |
+
with self.assertRaises(ActionRejected):prepared(method=m)
|
| 36 |
+
def test_bottom_clearance(self):
|
| 37 |
+
r=prepared();s=r.debug_snapshot()
|
| 38 |
+
with self.assertRaises(ActionRejected):r.invoke('mount.set_immersion',immersion_m=.10)
|
| 39 |
+
self.assertEqual(s,r.debug_snapshot())
|
| 40 |
+
def test_lift_on_step(self):
|
| 41 |
+
r=prepared();r.invoke('mount.set_immersion',immersion_m=.065);self.assertEqual(r.lift,0.)
|
| 42 |
+
with self.assertRaises(ActionRejected):r.invoke('acquisition.start')
|
| 43 |
+
r.step(.2);self.assertAlmostEqual(r.lift,-.005);r.invoke('acquisition.start')
|
| 44 |
+
def test_too_small_vessel_volume(self):
|
| 45 |
+
s=example_sample();s['carrier_mass_kg']=.001;s['dispersed_mass_kg']=0.
|
| 46 |
+
with self.assertRaises(ActionRejected):prepared(sample=s)
|
| 47 |
+
def test_mass_conservation(self):
|
| 48 |
+
r=prepared();r.invoke('acquisition.start');r.step(8);self.assertEqual(r.mass,r.initial);r.invoke('product.collect',fraction=.3,recipient_id='vial')
|
| 49 |
+
for a,b,c in zip(r.initial,r.mass,r.collected):self.assertAlmostEqual(a,b+c)
|
| 50 |
+
def test_energy_balance(self):
|
| 51 |
+
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)
|
| 52 |
+
def test_breakup_no_mass_creation(self):
|
| 53 |
+
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)
|
| 54 |
+
def test_cancel_coast_partial(self):
|
| 55 |
+
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)
|
| 56 |
+
def test_completion(self):
|
| 57 |
+
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)
|
| 58 |
+
def test_power_no_restart(self):
|
| 59 |
+
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')
|
| 60 |
+
def test_dual_isolation(self):
|
| 61 |
+
a=prepared('a');b=prepared('b');snap=b.debug_snapshot();a.invoke('acquisition.start');a.step(5);self.assertEqual(snap,b.debug_snapshot())
|
| 62 |
+
def test_permissions(self):
|
| 63 |
+
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')
|
| 64 |
+
def test_idempotency(self):
|
| 65 |
+
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())
|
| 66 |
+
def test_poll_cancel_ownership(self):
|
| 67 |
+
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)
|
| 68 |
+
with self.assertRaises(ActionRejected):r.session('second').poll(op)
|
| 69 |
+
self.assertEqual(s.cancel(op,'cancel')['status'],'cancelled');self.assertEqual(s.cancel(op,'cancel')['status'],'cancelled')
|
| 70 |
+
def test_external_observation(self):
|
| 71 |
+
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)
|
| 72 |
+
def test_reference_real_drives_capacity(self):
|
| 73 |
+
r=prepared();cp=r.invoke('reference.lookup',substance_id='water');self.assertTrue(4100<cp['cp_J_kg_K']<4300);self.assertAlmostEqual(r.capacity,.9*cp['cp_J_kg_K']+.08*2000+100)
|
| 74 |
+
def test_reference_range_rejected(self):
|
| 75 |
+
s=example_sample();s['temperature_K']=310.
|
| 76 |
+
with self.assertRaises(ActionRejected):prepared(sample=s)
|
| 77 |
+
def test_reference_failure_honest(self):
|
| 78 |
+
p=copy.deepcopy(PLANT_EXAMPLE);p.update(power_number=100.,heat_fraction=1.,cooling_W_K=0.,vessel_heat_capacity_J_K=0.)
|
| 79 |
+
s=example_sample();s['temperature_K']=303.14;m=copy.deepcopy(METHOD_EXAMPLE);m['speed_rad_s']=MAX_SPEED;r=prepared(plant=p,sample=s,method=m);r.invoke('acquisition.start');r.step(10);self.assertEqual(r.phase,'failed');self.assertEqual(r.mode,'reference_limit');self.assertLessEqual(r.temperature,303.15);self.assertEqual(r.mass,r.initial)
|
| 80 |
+
def test_display_resolution(self):
|
| 81 |
+
r=prepared();r.speed=13590*math.tau/60;r.motor=True;self.assertAlmostEqual(r._values()['panel.speed_krpm'],13.6);r.motor=False;self.assertEqual(r.indicated(),0.)
|
| 82 |
+
def test_half_step(self):
|
| 83 |
+
a=prepared();b=prepared();a.invoke('acquisition.start');b.invoke('acquisition.start')
|
| 84 |
+
for _ in range(400):a.step(.02)
|
| 85 |
+
for _ in range(800):b.step(.01)
|
| 86 |
+
for k in ['temperature','size','energy','heat','loss','storage','angle']:self.assertAlmostEqual(getattr(a,k),getattr(b,k),places=7)
|
| 87 |
+
if __name__=='__main__':unittest.main()
|
tests/test_asset_jasco_cpl300.py
ADDED
|
@@ -0,0 +1,213 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Finite independent CPL/PL oracles, detector statistics, motion and protocol checks."""
|
| 2 |
+
import copy,json,math,sys,unittest
|
| 3 |
+
from pathlib import Path
|
| 4 |
+
import numpy as np
|
| 5 |
+
ROOT=Path(__file__).resolve().parents[1];sys.path.insert(0,str(ROOT/'scripts'))
|
| 6 |
+
from asset_runtime.jasco_cpl300 import *
|
| 7 |
+
|
| 8 |
+
def toy_library():
|
| 9 |
+
record=dict(name='private_oracle_fluorophore',conditions=dict(solvent='basic ethanol',temperature_k=None,concentration_mol_m3=None,reference_excitation_m=400e-9),pl=dict(wavelength_m=[450e-9,500e-9,520e-9,540e-9,600e-9,900e-9,1000e-9],emission_relative=[0.,.2,1.,.6,0.,.8,0.],source_bandwidth_m=5e-9,evidence='independent_test_PL'),absorption=dict(wavelength_m=[250e-9,350e-9,400e-9,450e-9,500e-9,800e-9],epsilon_m2_mol=[0.,.5,1.,.5,0.,0.],source_bandwidth_m=5e-9,evidence='independent_test_absorption'),cpl=None)
|
| 10 |
+
ref=dict(name='one_material_left_configuration',raw_cpl_curve=dict(wavelength_m=[500e-9,520e-9],raw_cpl_mdeg=[1.,2.],cpl_display_angle_rad=[math.pi/180000,2*math.pi/180000],unit='rad',quantity='instrument_cpl_display_angle_not_delta_I'),cpl_glum_curve=dict(wavelength_m=[500e-9,520e-9],glum=[.01,.02],unit='1'),pl=None,cpl=None)
|
| 11 |
+
return dict(compounds={'pcad_032':record},cpl_references={'sfeg_blue_l':ref})
|
| 12 |
+
|
| 13 |
+
def host(noise=False,library=None,**plant):
|
| 14 |
+
h=JascoCpl300Runtime(library=toy_library() if library is None else library);h.invoke('plant.configure',**dict(PLANT_EXAMPLE,poisson_noise=noise,**plant));return h
|
| 15 |
+
|
| 16 |
+
def configure(h,method=None,sample=None):
|
| 17 |
+
h.invoke('sample.load',**(sample or BLANK_EXAMPLE));h.invoke('method.configure',**(method or METHOD_EXAMPLE));h.invoke('cover.set',opened=False);h.invoke('power.set',enabled=True);h.invoke('lamp.set',enabled=True);h.step(h.plant['lamp_warmup_s']);return h
|
| 18 |
+
|
| 19 |
+
def finish(h):
|
| 20 |
+
for _ in range(10001):
|
| 21 |
+
if h.phase!='running':return h
|
| 22 |
+
h.step(max(0.,h._due-h.time_s))
|
| 23 |
+
raise AssertionError('finite fixture did not terminate')
|
| 24 |
+
|
| 25 |
+
def blank(h,method=None):configure(h,method);h.invoke('blank.start');return finish(h)
|
| 26 |
+
def load_sample(h,sample=None):
|
| 27 |
+
h.invoke('cover.set',opened=True);h.invoke('sample.unload',recipient_id='external_rack');h.invoke('sample.load',**(sample or SAMPLE_EXAMPLE));h.invoke('cover.set',opened=False);return h
|
| 28 |
+
|
| 29 |
+
def ready(noise=False,method=None,**plant):return load_sample(blank(host(noise,**plant),method))
|
| 30 |
+
def run(h):h.invoke('acquisition.start');finish(h);return h.invoke('result.read')
|
| 31 |
+
def same(a,b):
|
| 32 |
+
if isinstance(a,np.ndarray):return isinstance(b,np.ndarray) and np.array_equal(a,b)
|
| 33 |
+
if isinstance(a,dict):return a.keys()==b.keys() and all(same(v,b[k]) for k,v in a.items())
|
| 34 |
+
if isinstance(a,(tuple,list)):return len(a)==len(b) and all(same(v,w) for v,w in zip(a,b))
|
| 35 |
+
return a==b
|
| 36 |
+
|
| 37 |
+
class Cpl300PhysicsTests(unittest.TestCase):
|
| 38 |
+
def rejected_atomic(self,h,cap,code=None,**args):
|
| 39 |
+
before=h.debug_snapshot()
|
| 40 |
+
with self.assertRaises(ActionRejected) as ctx:h.invoke(cap,**args)
|
| 41 |
+
if code:self.assertEqual(str(ctx.exception),code)
|
| 42 |
+
self.assertTrue(same(before,h.debug_snapshot()),str(ctx.exception))
|
| 43 |
+
def test_total_difference_and_glum_are_independent_oracle(self):
|
| 44 |
+
h=ready();r=run(h);self.assertEqual(len(r['points']),5)
|
| 45 |
+
expected=np.interp([p['requested_wavelength_m'] for p in r['points']],[500e-9,520e-9,540e-9],[.2,1.,.6])
|
| 46 |
+
for p,pl in zip(r['points'],expected):
|
| 47 |
+
self.assertAlmostEqual(p['pl'],pl);self.assertAlmostEqual(p['cpl'],.02*pl);self.assertAlmostEqual(p['glum'],.04);self.assertAlmostEqual(p['left_relative'],.51*pl);self.assertAlmostEqual(p['right_relative'],.49*pl)
|
| 48 |
+
def test_manufacturer_half_sum_does_not_double_glum(self):
|
| 49 |
+
h=host();r=h.invoke('glum.compute',left_relative=6.,right_relative=4.,net_counts=1000.,minimum_net_counts=25.)
|
| 50 |
+
self.assertEqual(r['pl'],10.);self.assertEqual(r['cpl'],2.);self.assertAlmostEqual(r['glum'],.4)
|
| 51 |
+
def test_glum_sign_and_pure_circular_boundaries(self):
|
| 52 |
+
for g in [-2.,0.,2.]:
|
| 53 |
+
h=load_sample(blank(host()),dict(SAMPLE_EXAMPLE,synthetic_glum=g));r=run(h)
|
| 54 |
+
for p in r['points']:self.assertAlmostEqual(p['glum'],g,places=11)
|
| 55 |
+
def test_zero_signal_and_low_counts_are_undefined(self):
|
| 56 |
+
h=load_sample(blank(host(blank_pl_relative=0.,dark_counts_s=0.)),dict(SAMPLE_EXAMPLE,peak_pl_relative=0.));r=run(h)
|
| 57 |
+
self.assertTrue(all(p['glum'] is None and p['glum_quality']=='nonpositive_pl' for p in r['points']))
|
| 58 |
+
r=run(ready(counts_per_relative_unit_s=10.));self.assertTrue(all(p['glum'] is None and p['glum_quality']=='low_net_counts' for p in r['points']))
|
| 59 |
+
def test_negative_blank_corrected_channel_not_clipped(self):
|
| 60 |
+
h=host();r=h.invoke('glum.compute',left_relative=1.,right_relative=-.1,net_counts=1000.,minimum_net_counts=25.)
|
| 61 |
+
self.assertIsNone(r['glum']);self.assertEqual(r['quality'],'outside_physical_range');self.assertEqual(r['cpl'],1.1)
|
| 62 |
+
def test_glum_finite_extremes_and_overflow_reject(self):
|
| 63 |
+
h=host();r=h.invoke('glum.compute',left_relative=1e-300,right_relative=5e-301,net_counts=100.,minimum_net_counts=25.);self.assertAlmostEqual(r['glum'],2/3)
|
| 64 |
+
self.rejected_atomic(h,'glum.compute','ANALYSIS_RANGE',left_relative=1e308,right_relative=1e308,net_counts=1e3,minimum_net_counts=25.)
|
| 65 |
+
def test_blank_correction_removes_host_background_and_dark_mean(self):
|
| 66 |
+
h=ready(blank_pl_relative=.2,blank_glum=-.3,dark_counts_s=1000.);r=run(h)
|
| 67 |
+
for p in r['points']:self.assertAlmostEqual(p['glum'],.04)
|
| 68 |
+
self.assertAlmostEqual(r['points'][2]['pl'],1.)
|
| 69 |
+
def test_blank_required_and_partial_blank_never_valid(self):
|
| 70 |
+
h=configure(host(),sample=SAMPLE_EXAMPLE);self.rejected_atomic(h,'acquisition.start','MATCHED_BLANK_REQUIRED')
|
| 71 |
+
h=configure(host());h.invoke('blank.start');h.step(1.56);h.invoke('acquisition.stop');self.assertFalse(h.read()['blank.valid']);self.assertIsNone(h.invoke('blank.read')['result']);self.assertEqual(len(h._points),1)
|
| 72 |
+
def test_wrong_sample_kind_rejects_without_mutation(self):
|
| 73 |
+
h=configure(host());self.rejected_atomic(h,'acquisition.start','WRONG_SAMPLE_KIND');h=ready();self.rejected_atomic(h,'blank.start','WRONG_SAMPLE_KIND')
|
| 74 |
+
def test_method_change_preserves_result_and_invalidates_blank(self):
|
| 75 |
+
h=ready();r=run(h);h.invoke('method.configure',**dict(METHOD_EXAMPLE,response_s=.04));self.assertEqual(h.invoke('result.read'),r);self.assertFalse(h.read()['blank.valid']);self.rejected_atomic(h,'acquisition.start','MATCHED_BLANK_REQUIRED')
|
| 76 |
+
def test_power_or_lamp_off_invalidates_blank(self):
|
| 77 |
+
for cap in ['power.set','lamp.set']:
|
| 78 |
+
h=ready();h.invoke(cap,enabled=False);self.assertFalse(h.read()['blank.valid']);self.assertFalse(h.shutter)
|
| 79 |
+
def test_volume_and_solute_inventory_independent_of_measurement(self):
|
| 80 |
+
h=ready();old=h._ledger();run(h);new=h._ledger();self.assertEqual(old['current_volume_m3'],new['current_volume_m3']);self.assertEqual(old['current_solute_mol'],new['current_solute_mol']);h.invoke('cover.set',opened=True);h.invoke('sample.unload',recipient_id='rack');l=h._ledger();self.assertAlmostEqual(l['volume_residual_m3'],0.,places=20);self.assertAlmostEqual(l['solute_residual_mol'],0.,places=20)
|
| 81 |
+
def test_concentration_is_inventory_not_invented_pl_calibration(self):
|
| 82 |
+
spectra=[]
|
| 83 |
+
for c in [.0001,.001]:spectra.append(run(load_sample(blank(host()),dict(SAMPLE_EXAMPLE,concentration_mol_m3=c))))
|
| 84 |
+
self.assertEqual([p['pl'] for p in spectra[0]['points']],[p['pl'] for p in spectra[1]['points']])
|
| 85 |
+
def test_sample_ack_and_source_solvent_gates(self):
|
| 86 |
+
h=host()
|
| 87 |
+
for args,code in [({'accept_synthetic_cpl':False},'SYNTHETIC_CPL_ACK_REQUIRED'),({'accept_unknown_conditions':False},'UNKNOWN_CONDITIONS_ACK_REQUIRED'),({'solvent':'water'},'SOURCE_CONDITIONS_MISMATCH')]:self.rejected_atomic(h,'sample.load',code,**dict(SAMPLE_EXAMPLE,**args))
|
| 88 |
+
def test_occupied_cell_requires_unload(self):
|
| 89 |
+
h=host();h.invoke('sample.load',**BLANK_EXAMPLE);self.rejected_atomic(h,'sample.load','UNLOAD_REQUIRED',**SAMPLE_EXAMPLE)
|
| 90 |
+
def test_manual_sample_requires_open_cover(self):
|
| 91 |
+
h=ready();self.rejected_atomic(h,'sample.unload','COVER_MUST_BE_OPEN',recipient_id='rack')
|
| 92 |
+
def test_lamp_warmup_advances_only_on_step(self):
|
| 93 |
+
h=host();h.invoke('sample.load',**BLANK_EXAMPLE);h.invoke('method.configure',**METHOD_EXAMPLE);h.invoke('cover.set',opened=False);h.invoke('power.set',enabled=True);h.invoke('lamp.set',enabled=True);self.rejected_atomic(h,'blank.start','OPTICS_NOT_READY');h.step(.05);self.assertFalse(h._ready());h.step(.05);self.assertTrue(h._ready())
|
| 94 |
+
def test_shutter_interlocks_and_two_shared_scene_states(self):
|
| 95 |
+
h=host();self.rejected_atomic(h,'shutter.set','OPTICS_NOT_READY',opened=True);h=ready();h.invoke('shutter.set',opened=True);self.assertEqual(h.read()['shutter.angle_rad'],math.pi/2);h.invoke('cover.set',opened=True);self.assertFalse(h.shutter)
|
| 96 |
+
def test_finite_simultaneous_prism_repositioning(self):
|
| 97 |
+
h=configure(host());h.invoke('blank.start');before=h.read();self.assertEqual(before['optics.excitation_m'],250e-9);h.step(.75);self.assertAlmostEqual(h.excitation,325e-9);self.assertAlmostEqual(h.emission,375e-9);self.assertEqual(h.stage,'moving');self.assertFalse(h.shutter)
|
| 98 |
+
def test_step_gate_holds_wavelength_and_response_window(self):
|
| 99 |
+
h=ready();h.invoke('acquisition.start');h.step(.24);self.assertEqual(h.stage,'integrating');self.assertAlmostEqual(h.emission,500e-9);h.step(.05);p=h._points[0];self.assertEqual(p['wavelength_window_m'],[500e-9,500e-9]);self.assertAlmostEqual(p['sample_window_s'][1]-p['sample_window_s'][0],.05)
|
| 100 |
+
def test_continuous_gate_uses_trailing_window_and_exact_linear_average(self):
|
| 101 |
+
m=dict(METHOD_EXAMPLE,scan_mode='continuous',scan_speed_m_s=100e-9,response_s=.05);h=ready(method=m);r=run(h);p=r['points'][1]
|
| 102 |
+
np.testing.assert_allclose(p['wavelength_window_m'],[505e-9,510e-9],atol=1e-20);self.assertAlmostEqual(p['emission_m'],507.5e-9);self.assertAlmostEqual(p['pl'],.5);self.assertAlmostEqual(p['glum'],.04)
|
| 103 |
+
def test_continuous_gate_integrates_an_interior_spectral_peak(self):
|
| 104 |
+
m=dict(METHOD_EXAMPLE,scan_mode='continuous',start_m=490e-9,stop_m=530e-9,interval_m=40e-9,scan_speed_m_s=100e-9,response_s=.3)
|
| 105 |
+
r=run(ready(method=m));p=r['points'][1]
|
| 106 |
+
np.testing.assert_allclose(p['wavelength_window_m'],[500e-9,530e-9],atol=1e-20)
|
| 107 |
+
self.assertAlmostEqual(p['pl'],(.6*20+.9*10)/30)
|
| 108 |
+
def test_continuous_and_step_are_not_identical_sampling(self):
|
| 109 |
+
step=run(ready());cont=run(ready(method=dict(METHOD_EXAMPLE,scan_mode='continuous',scan_speed_m_s=100e-9,response_s=.05)));self.assertNotAlmostEqual(step['points'][1]['pl'],cont['points'][1]['pl'],places=10)
|
| 110 |
+
def test_continuous_overlap_and_short_final_interval_reject(self):
|
| 111 |
+
h=host();self.rejected_atomic(h,'method.configure','RESPONSE_OVERLAPS_INTERVAL',**dict(METHOD_EXAMPLE,scan_mode='continuous',response_s=.1));self.rejected_atomic(h,'method.configure','RESPONSE_OVERLAPS_INTERVAL',**dict(METHOD_EXAMPLE,scan_mode='continuous',stop_m=541e-9,response_s=.05))
|
| 112 |
+
def test_excitation_scan_uses_absorption_proxy_not_emission_axis(self):
|
| 113 |
+
m=dict(METHOD_EXAMPLE,scan_axis='excitation',start_m=350e-9,stop_m=450e-9,interval_m=25e-9,emission_m=520e-9);r=run(ready(method=m));np.testing.assert_allclose([p['pl'] for p in r['points']],[.5,.75,1.,.75,.5],atol=1e-15)
|
| 114 |
+
def test_kasha_approximation_requires_explicit_host_acceptance(self):
|
| 115 |
+
h=ready(accept_kasha_model=False);self.rejected_atomic(h,'acquisition.start','KASHA_ACK_REQUIRED')
|
| 116 |
+
def test_unsupported_detector_band_and_excitation_bounds(self):
|
| 117 |
+
h=host();self.rejected_atomic(h,'method.configure','OPTION_NOT_INSTALLED',**dict(METHOD_EXAMPLE,detector_band='extended'))
|
| 118 |
+
self.rejected_atomic(h,'method.configure','DETECTOR_WINDOW',**dict(METHOD_EXAMPLE,start_m=840e-9,stop_m=900e-9))
|
| 119 |
+
self.rejected_atomic(h,'method.configure','EXCITATION_WINDOW',**dict(METHOD_EXAMPLE,scan_axis='excitation',start_m=800e-9,stop_m=900e-9,emission_m=1000e-9))
|
| 120 |
+
def test_extended_pmt_range_requires_option_and_excludes_blue(self):
|
| 121 |
+
h=host(extended_pmt_installed=True);self.rejected_atomic(h,'method.configure','DETECTOR_WINDOW',**dict(METHOD_EXAMPLE,excitation_m=250e-9,start_m=350e-9,stop_m=450e-9,detector_band='extended'))
|
| 122 |
+
h=ready(method=dict(METHOD_EXAMPLE,start_m=880e-9,stop_m=940e-9,interval_m=15e-9,detector_band='extended'),extended_pmt_installed=True);self.assertEqual(run(h)['phase'],'succeeded')
|
| 123 |
+
def test_anti_stokes_regime_is_explicitly_unsupported(self):
|
| 124 |
+
h=host();self.rejected_atomic(h,'method.configure','STOKES_MODEL_REQUIRED',**dict(METHOD_EXAMPLE,excitation_m=520e-9))
|
| 125 |
+
def test_source_bandwidth_and_range_guards(self):
|
| 126 |
+
h=ready(method=dict(METHOD_EXAMPLE,em_bandwidth_m=1e-9));self.rejected_atomic(h,'acquisition.start','SOURCE_BANDWIDTH_LIMIT')
|
| 127 |
+
h=ready(method=dict(METHOD_EXAMPLE,start_m=420e-9,stop_m=460e-9));self.rejected_atomic(h,'acquisition.start','SOURCE_WAVELENGTH_RANGE')
|
| 128 |
+
def test_source_negative_baseline_only_clipped_in_forward_model(self):
|
| 129 |
+
lib=toy_library();lib['compounds']['pcad_032']['pl']['emission_relative'][1]=-.2;h=load_sample(blank(host(library=lib)));r=run(h);self.assertAlmostEqual(r['points'][0]['pl'],0.);source=json.loads(h.invoke('template.read',substance_id='pcad_032')['template_json']);self.assertEqual(source['pl']['emission_relative'][1],-.2)
|
| 130 |
+
def test_additional_bandwidth_broadens_without_deconvolution(self):
|
| 131 |
+
lib=toy_library();x=np.arange(450e-9,601e-9,1e-9);lib['compounds']['pcad_032']['pl'].update(wavelength_m=x.tolist(),emission_relative=np.exp(-.5*((x-520e-9)/1e-9)**2).tolist());h=load_sample(blank(host(library=lib),dict(METHOD_EXAMPLE,em_bandwidth_m=20e-9)));r=run(h);self.assertLess(r['points'][2]['pl'],.2)
|
| 132 |
+
def test_poisson_category_draws_and_detector_partition_oracle(self):
|
| 133 |
+
h=configure(host(noise=True));h.invoke('blank.start');finish(h);rng=np.random.default_rng(78);expected=[]
|
| 134 |
+
for _ in range(5):
|
| 135 |
+
counts=rng.poisson([0.,0.,1250.,1250.,.5,.5]);expected.append((float(counts[0]+counts[2]+counts[4]),float(counts[1]+counts[3]+counts[5])))
|
| 136 |
+
self.assertEqual([(p['raw_left_counts'],p['raw_right_counts']) for p in h._points],expected);self.assertEqual(h._ledger()['detector_partition_residual'],0.)
|
| 137 |
+
def test_sampling_noise_partition_independent_of_step_size(self):
|
| 138 |
+
h=ready(noise=True);g=ready(noise=True);h.invoke('acquisition.start');g.invoke('acquisition.start');h.step(1.)
|
| 139 |
+
for _ in range(100):g.step(.01)
|
| 140 |
+
self.assertEqual([(p['raw_left_counts'],p['raw_right_counts']) for p in h._points],[(p['raw_left_counts'],p['raw_right_counts']) for p in g._points]);self.assertEqual(g.phase,'succeeded')
|
| 141 |
+
def test_cancel_partial_gate_does_not_fabricate_detected_events(self):
|
| 142 |
+
h=ready();ledger=copy.deepcopy(h._ledger());h.invoke('acquisition.start');h.step(.26);self.assertEqual(len(h._points),0);h.invoke('acquisition.stop');self.assertEqual(h._ledger(),ledger);old=h.elapsed_s;h.step(10.);self.assertEqual(h.elapsed_s,old)
|
| 143 |
+
def test_completed_gates_survive_cancellation(self):
|
| 144 |
+
h=ready();h.invoke('acquisition.start');h.step(.31);self.assertEqual(len(h._points),1);h.invoke('acquisition.stop');r=h._result();h.step(10.);self.assertEqual(h._result(),r);self.assertAlmostEqual(h._ledger()['completed_gate_s'],.3)
|
| 145 |
+
def test_manual_idle_open_shutter_not_claimed_as_completed_gate(self):
|
| 146 |
+
h=ready();h.invoke('shutter.set',opened=True);old=h._ledger();h.step(5.);self.assertEqual(h._ledger(),old);self.assertIn('idle-open-shutter',old['evidence'])
|
| 147 |
+
def test_all_interrupts_close_shutters_and_keep_completed_points(self):
|
| 148 |
+
for cap,args in [('cover.set',{'opened':True}),('power.set',{'enabled':False}),('lamp.set',{'enabled':False}),('shutter.set',{'opened':False})]:
|
| 149 |
+
h=ready();h.invoke('acquisition.start');h.step(.31);h.invoke(cap,**args);self.assertEqual(h.phase,'cancelled');self.assertFalse(h.shutter);self.assertEqual(len(h._points),1)
|
| 150 |
+
def test_busy_method_is_atomic(self):
|
| 151 |
+
h=ready();h.invoke('acquisition.start');self.rejected_atomic(h,'method.configure','BUSY',**METHOD_EXAMPLE)
|
| 152 |
+
def test_resource_and_nonfinite_settings_reject_atomically(self):
|
| 153 |
+
h=host()
|
| 154 |
+
for value in [float('nan'),float('inf'),0.,True]:self.rejected_atomic(h,'method.configure','INVALID_ARGUMENT',**dict(METHOD_EXAMPLE,response_s=value))
|
| 155 |
+
self.rejected_atomic(h,'method.configure','EVENT_RESOURCE_LIMIT',**dict(METHOD_EXAMPLE,start_m=420e-9,stop_m=850e-9,interval_m=.025e-9))
|
| 156 |
+
self.rejected_atomic(h,'method.configure','SPECTRAL_GRID',**dict(METHOD_EXAMPLE,stop_m=500e-9))
|
| 157 |
+
def test_queries_and_zero_step_are_pure(self):
|
| 158 |
+
h=ready(noise=True);run(h);snap=h.debug_snapshot();h.step(0.)
|
| 159 |
+
for k in ['process.measure','result.read','raw.read','blank.read','product.read']:h.invoke(k)
|
| 160 |
+
h.invoke('template.read',substance_id='pcad_032');h.invoke('reference.read',reference_id='sfeg_blue_l');h.invoke('result.export',format='csv');h.describe();h.read();self.assertTrue(same(snap,h.debug_snapshot()))
|
| 161 |
+
def test_reference_query_preserves_display_angle_not_delta_intensity(self):
|
| 162 |
+
h=host();r=json.loads(h.invoke('reference.read',reference_id='sfeg_blue_l')['reference_json']);self.assertEqual(r['raw_cpl_curve']['quantity'],'instrument_cpl_display_angle_not_delta_I');self.assertIsNone(r['pl']);self.assertIsNone(r['cpl'])
|
| 163 |
+
def test_actual_source_default_and_real_reference_replay(self):
|
| 164 |
+
h=JascoCpl300Runtime();h.invoke('plant.configure',**dict(PLANT_EXAMPLE,poisson_noise=False));blank(h);load_sample(h);r=run(h);self.assertTrue(r['complete']);self.assertEqual(r['provenance']['cpl_evidence'],'synthetic');self.assertIsNone(r['provenance']['source_temperature_k']);reference=json.loads(h.invoke('reference.read',reference_id='sfeg_blue_l')['reference_json']);self.assertIn('raw_cpl_curve',reference)
|
| 165 |
+
|
| 166 |
+
class Cpl300ProtocolTests(unittest.TestCase):
|
| 167 |
+
def sessions(self):
|
| 168 |
+
h=ready();h.register_principal('host','evaluator');h.register_principal('other');return h,h.session(),h.session('host'),h.session('other')
|
| 169 |
+
def invoke(self,s,h,cap,args=None,rid='unique'):return s.invoke(instance_id=h.instance_id,capability_id=cap,arguments=args or {},request_id=rid)
|
| 170 |
+
def test_private_capabilities_and_truth_are_filtered(self):
|
| 171 |
+
h,a,e,o=self.sessions();snap=h.debug_snapshot();r=self.invoke(a,h,'sample.load',SAMPLE_EXAMPLE);self.assertEqual(r['error']['code'],'ACCESS_DENIED');self.assertTrue(same(snap,h.debug_snapshot()));self.assertNotIn('truth.ledger',a.read(instance_id=h.instance_id)['observations']);self.assertIn('truth.ledger',e.read(instance_id=h.instance_id)['observations'])
|
| 172 |
+
with self.assertRaises(ActionRejected):a.read(instance_id=h.instance_id,state_ids=['truth.ledger'])
|
| 173 |
+
with self.assertRaises(ActionRejected):h.read('administrator')
|
| 174 |
+
def test_agent_cannot_self_register_via_arguments(self):
|
| 175 |
+
h,a,e,o=self.sessions();r=self.invoke(a,h,'power.set',{'enabled':True,'visibility':'evaluator'});self.assertEqual(r['status'],'rejected');self.assertEqual(r['error']['side_effects'],'none')
|
| 176 |
+
def test_no_hidden_sample_identity_in_observations_or_exports(self):
|
| 177 |
+
h,a,e,o=self.sessions();run(h)
|
| 178 |
+
for cap in ['process.measure','result.read','raw.read','result.export']:
|
| 179 |
+
r=self.invoke(a,h,cap,{'format':'json'} if cap=='result.export' else {},rid=cap);text=json.dumps(r)
|
| 180 |
+
for hidden in ['private_oracle_fluorophore','external_cpl_cell','pcad_032']:self.assertNotIn(hidden,text)
|
| 181 |
+
def test_idempotent_start_and_conflicting_request(self):
|
| 182 |
+
h,a,e,o=self.sessions();r=self.invoke(a,h,'acquisition.start');snap=h.debug_snapshot();self.assertEqual(self.invoke(a,h,'acquisition.start'),r);self.assertTrue(same(snap,h.debug_snapshot()));bad=self.invoke(a,h,'acquisition.stop');self.assertEqual(bad['error']['code'],'REQUEST_CONFLICT')
|
| 183 |
+
def test_terminal_result_and_windows_survive_later_operation(self):
|
| 184 |
+
h,a,e,o=self.sessions();op=self.invoke(a,h,'acquisition.start')['operation_id'];finish(h);old=a.poll(op);self.assertEqual(old['result'],h._result());self.invoke(a,h,'acquisition.start',rid='next');h.step(.3);self.assertEqual(a.poll(op),old)
|
| 185 |
+
with self.assertRaises(ActionRejected):o.poll(op)
|
| 186 |
+
def test_cancel_old_terminal_never_cancels_current(self):
|
| 187 |
+
h,a,e,o=self.sessions();old=self.invoke(a,h,'acquisition.start')['operation_id'];finish(h);new=self.invoke(a,h,'acquisition.start',rid='next')['operation_id'];a.cancel(old,'cancel-old');self.assertEqual(h.operation_id,new);self.assertEqual(h.phase,'running')
|
| 188 |
+
def test_cancellation_snapshot_matches_current_read(self):
|
| 189 |
+
h,a,e,o=self.sessions();op=self.invoke(a,h,'acquisition.start')['operation_id'];h.step(.31);a.cancel(op,'cancel');p=a.poll(op);obs=a.read(instance_id=h.instance_id)['observations']
|
| 190 |
+
for k in ['scan.pl','scan.cpl','scan.glum']:self.assertEqual(p['observations'][k],obs[k]);self.assertEqual(obs[k]['sample_window_s'],h._points[-1]['sample_window_s'])
|
| 191 |
+
def test_new_run_observations_are_unavailable_without_stale_windows(self):
|
| 192 |
+
h,a,e,o=self.sessions();run(h);self.invoke(a,h,'acquisition.start');obs=a.read(instance_id=h.instance_id)['observations']
|
| 193 |
+
for k in ['scan.pl','scan.cpl','scan.glum']:self.assertIsNone(obs[k]['value']);self.assertIsNone(obs[k]['sample_window_s']);self.assertEqual(obs[k]['quality'],'unavailable')
|
| 194 |
+
def test_observed_glum_null_keeps_actual_gate_window(self):
|
| 195 |
+
h,a,e,o=self.sessions();h.invoke('cover.set',opened=True);h.invoke('sample.unload',recipient_id='rack');h.invoke('sample.load',**dict(SAMPLE_EXAMPLE,peak_pl_relative=0.));h.invoke('cover.set',opened=False);run(h);obs=a.read(instance_id=h.instance_id)['observations']['scan.glum'];self.assertIsNone(obs['value']);self.assertEqual(obs['sample_window_s'],h._points[-1]['sample_window_s'])
|
| 196 |
+
def test_csv_null_and_provenance_roundtrip(self):
|
| 197 |
+
h=ready(counts_per_relative_unit_s=10.);r=run(h);out=h.invoke('result.export',format='csv')['content'].splitlines();meta=json.loads(out[0][2:]);self.assertEqual(meta['provenance'],r['provenance']);self.assertEqual(len(out)-2,5);self.assertEqual(out[2].split(',')[7],'')
|
| 198 |
+
def test_real_results_validate_against_schema(self):
|
| 199 |
+
h=ready();run(h)
|
| 200 |
+
for k in ['process.measure','result.read','raw.read','blank.read','product.read','result.export','template.read','reference.read','glum.compute']:validate(CAPS[k][1],h.invoke(k,**CAPS[k][6]))
|
| 201 |
+
for k,value in h.read('evaluator').items():validate(SLOTS[k][0],value)
|
| 202 |
+
def test_metadata_queries_effects_timing_and_version(self):
|
| 203 |
+
h=ready();m=export_jasco_cpl300_contract_metadata();self.assertEqual(len(m['capabilities']),22);self.assertEqual(len(m['state_slots']),29);self.assertEqual(h.describe()['asset_version'],'1.0.1')
|
| 204 |
+
for k,c in m['capabilities'].items():
|
| 205 |
+
if c['kind'] in ['query','analysis'] or k in UNSUPPORTED:self.assertEqual(c['state_effects'],[])
|
| 206 |
+
self.assertTrue(set(c['observes'])<=SLOTS.keys())
|
| 207 |
+
self.assertFalse(any(x['state_id']=='optics.excitation_m' and x['timing']=='immediate' for x in m['capabilities']['method.configure']['state_effects']))
|
| 208 |
+
def test_unsupported_capabilities_are_atomic(self):
|
| 209 |
+
h,a,e,o=self.sessions()
|
| 210 |
+
for k in UNSUPPORTED:
|
| 211 |
+
snap=h.debug_snapshot();r=self.invoke(a,h,k,rid=k);self.assertEqual(r['status'],'unsupported');self.assertTrue(same(snap,h.debug_snapshot()))
|
| 212 |
+
|
| 213 |
+
if __name__=='__main__':unittest.main()
|
tests/test_asset_jasco_fp8350.py
ADDED
|
@@ -0,0 +1,199 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""FP-8350 process, source-data, physics, protocol, async, and negative control tests."""
|
| 2 |
+
import copy,json,math,sys,unittest
|
| 3 |
+
from pathlib import Path
|
| 4 |
+
import numpy as np
|
| 5 |
+
ROOT=Path(__file__).resolve().parents[1];sys.path.insert(0,str(ROOT/'scripts'))
|
| 6 |
+
from asset_runtime.jasco_fp8350 import *
|
| 7 |
+
def ready(kind='sample',method=None,plant=None,sample=None):
|
| 8 |
+
h=JascoFp8350Runtime();h.invoke('plant.configure',**(plant or FAST_PLANT));m=copy.deepcopy(method or METHOD_EXAMPLE);s=copy.deepcopy(sample or SAMPLE_EXAMPLE);b=dict(s,sample_id='blank_01',kind='blank',template_id='',concentration_mol_m3=0.)
|
| 9 |
+
h.invoke('solution.register',**b);h.invoke('sample.load',sample_id=b['sample_id']);h.invoke('method.configure',**m);h.invoke('lid.set',opened=False);h.invoke('power.set',enabled=True);h.invoke('lamp.set',enabled=True);h.step(h.plant['lamp_warmup_s']+.01)
|
| 10 |
+
if kind=='blank':return h
|
| 11 |
+
h.invoke('acquisition.start',kind='blank');h.step(1+len(h._grid())*max(m['integration_s'],m['interval_s']));h.invoke('lid.set',opened=True);h.invoke('sample.unload',recipient_id='rack');h.invoke('solution.register',**s);h.invoke('sample.load',sample_id=s['sample_id']);h.invoke('lid.set',opened=False)
|
| 12 |
+
return h
|
| 13 |
+
class TestFp8350(unittest.TestCase):
|
| 14 |
+
def done(self,**kw):
|
| 15 |
+
h=ready(**kw);h.invoke('acquisition.start',kind='sample');h.step(10);self.assertEqual(h.phase,'succeeded');return h
|
| 16 |
+
def reject(self,h,cap,code='INVALID_ARGUMENT',**a):
|
| 17 |
+
old=h.debug_snapshot()
|
| 18 |
+
with self.assertRaisesRegex(ActionRejected,code):h.invoke(cap,**a)
|
| 19 |
+
self.assertEqual(old,h.debug_snapshot())
|
| 20 |
+
def test_01_library_paired(self):
|
| 21 |
+
h=JascoFp8350Runtime();self.assertGreaterEqual(len(h.templates),50)
|
| 22 |
+
for r in h.templates.values():self.assertGreater(len(r['epsilon_m2_mol']),20);self.assertGreater(len(r['emission_relative']),20);self.assertGreater(r['quantum_yield'],0)
|
| 23 |
+
def test_02_distinct_names(self):
|
| 24 |
+
rows=JascoFp8350Runtime().templates.values();self.assertEqual(len(rows),len({r['canonical_source_name_key'] for r in rows}))
|
| 25 |
+
def test_03_source_sixg_units(self):
|
| 26 |
+
r=JascoFp8350Runtime().templates['pcad_083'];eps=np.interp(529.8e-9,r['abs_wavelength_m'],r['epsilon_m2_mol']);self.assertLess(abs(eps-11600)/11600,.005);self.assertAlmostEqual(r['quantum_yield'],.95)
|
| 27 |
+
def test_04_unknown_temp_null(self):self.assertTrue(all(r['conditions']['temperature_k'] is None for r in JascoFp8350Runtime().templates.values()))
|
| 28 |
+
def test_05_initial_null(self):
|
| 29 |
+
v=JascoFp8350Runtime().read();self.assertIsNone(v['scan.intensity']);self.assertIsNone(v['thermal.setpoint_k'])
|
| 30 |
+
def test_06_initialization_only(self):
|
| 31 |
+
h=ready();self.reject(h,'plant.configure','INITIALIZATION_ONLY',**FAST_PLANT)
|
| 32 |
+
def test_07_init_after_host_time(self):
|
| 33 |
+
h=JascoFp8350Runtime();h.step(.02);h.invoke('plant.configure',**FAST_PLANT);self.assertTrue(h.plant)
|
| 34 |
+
def test_08_bool_numeric(self):
|
| 35 |
+
h=ready();self.reject(h,'method.configure',**dict(METHOD_EXAMPLE,gain=True))
|
| 36 |
+
def test_09_nan_numeric(self):
|
| 37 |
+
h=ready();self.reject(h,'thermal.set_temperature',temperature_k=float('nan'))
|
| 38 |
+
def test_10_unknown_argument(self):
|
| 39 |
+
h=ready();self.reject(h,'power.set',enabled=True,secret=1)
|
| 40 |
+
def test_11_extra_type_guard(self):
|
| 41 |
+
h=ready();self.reject(h,'lid.set',opened=1)
|
| 42 |
+
def test_12_detached_arguments(self):
|
| 43 |
+
p=copy.deepcopy(FAST_PLANT);h=JascoFp8350Runtime();h.invoke('plant.configure',**p);p['incident_photons_s_inv']=1.;self.assertNotEqual(h.plant['incident_photons_s_inv'],1.)
|
| 44 |
+
def test_13_unknown_solvent(self):
|
| 45 |
+
h=ready();self.reject(h,'solution.register','SOURCE_SOLVENT_MISMATCH',**dict(SAMPLE_EXAMPLE,sample_id='new',solvent_id='water'))
|
| 46 |
+
def test_14_evidence_ack(self):
|
| 47 |
+
h=ready();self.reject(h,'solution.register','EVIDENCE_ACK_REQUIRED',**dict(SAMPLE_EXAMPLE,sample_id='new',accept_unknown_temperature=False))
|
| 48 |
+
def test_15_blank_nonzero(self):
|
| 49 |
+
h=ready();self.reject(h,'solution.register',**dict(BLANK_EXAMPLE,sample_id='bad',concentration_mol_m3=.001))
|
| 50 |
+
def test_16_duplicate_sample(self):
|
| 51 |
+
h=ready();self.reject(h,'solution.register','REQUEST_CONFLICT',**SAMPLE_EXAMPLE)
|
| 52 |
+
def test_17_no_access_through_lid(self):
|
| 53 |
+
h=ready();self.reject(h,'sample.unload','SAMPLE_ACCESS_REQUIRED',recipient_id='rack')
|
| 54 |
+
def test_18_lamp_warmup(self):
|
| 55 |
+
h=ready(kind='blank');h.invoke('lamp.set',enabled=False);h.invoke('lamp.set',enabled=True);self.reject(h,'acquisition.start','OPTICS_NOT_READY',kind='blank')
|
| 56 |
+
def test_19_blank_required(self):
|
| 57 |
+
h=ready();h.blank=None;self.reject(h,'acquisition.start','BLANK_REQUIRED',kind='sample')
|
| 58 |
+
def test_20_wrong_kind(self):
|
| 59 |
+
h=ready(kind='blank');self.reject(h,'acquisition.start','SAMPLE_KIND_MISMATCH',kind='sample')
|
| 60 |
+
def test_21_completed_emission(self):
|
| 61 |
+
h=self.done();self.assertEqual(len(h.points),15);self.assertGreater(max(x['intensity'] for x in h.points),0);self.assertFalse(h.shutter)
|
| 62 |
+
def test_22_excitation(self):
|
| 63 |
+
h=self.done(method=dict(METHOD_EXAMPLE,mode='excitation',start_m=450e-9,stop_m=510e-9));self.assertEqual(len({p['emission_m'] for p in h.points}),1);self.assertGreater(len({p['excitation_m'] for p in h.points}),1)
|
| 64 |
+
def test_23_time_trace_constant(self):
|
| 65 |
+
h=self.done(method=dict(METHOD_EXAMPLE,mode='time'));y=[p['intensity'] for p in h.points];self.assertEqual(len(y),11);self.assertLess(np.ptp(y),1e-12);self.assertAlmostEqual(h.points[-1]['elapsed_s'],1.04)
|
| 66 |
+
def test_24_blank_subtraction(self):
|
| 67 |
+
h=self.done();rate=h._rates(h.points[0]['excitation_m'],h.points[0]['emission_m']);self.assertAlmostEqual(h.points[0]['intensity'],rate['detected']/h.plant['reference_counts_s_inv'])
|
| 68 |
+
def test_25_concentration_response(self):
|
| 69 |
+
a=self.done();b=self.done(sample=dict(SAMPLE_EXAMPLE,concentration_mol_m3=.0001));ratio=max(p['intensity'] for p in a.points)/max(p['intensity'] for p in b.points);self.assertGreater(ratio,1.9);self.assertLess(ratio,2.001)
|
| 70 |
+
def test_26_gain_response(self):
|
| 71 |
+
a=self.done();b=self.done(method=dict(METHOD_EXAMPLE,gain=2.));self.assertAlmostEqual(max(p['intensity'] for p in b.points),2*max(p['intensity'] for p in a.points))
|
| 72 |
+
def test_27_dilute_limit(self):
|
| 73 |
+
h=ready(sample=dict(SAMPLE_EXAMPLE,concentration_mol_m3=.05));self.reject(h,'acquisition.start','DILUTE_MODEL_LIMIT',kind='sample')
|
| 74 |
+
def test_28_no_template_extrapolation(self):
|
| 75 |
+
h=ready(method=dict(METHOD_EXAMPLE,mode='excitation',start_m=210e-9,stop_m=250e-9,excitation_m=210e-9));self.reject(h,'acquisition.start','TEMPLATE_RANGE',kind='sample')
|
| 76 |
+
def test_29_no_900nm(self):
|
| 77 |
+
h=ready();self.reject(h,'method.configure',**dict(METHOD_EXAMPLE,emission_m=800e-9));self.reject(h,'optics.install_900nm','UNSUPPORTED')
|
| 78 |
+
def test_30_no_unsupported_lifetime(self):
|
| 79 |
+
h=ready();self.reject(h,'phosphorescence.measure','UNSUPPORTED')
|
| 80 |
+
def test_31_scatter_guard(self):
|
| 81 |
+
h=ready();self.reject(h,'method.configure','SCATTER_OR_ANTISTOKES_UNSUPPORTED',**dict(METHOD_EXAMPLE,excitation_m=550e-9))
|
| 82 |
+
def test_32_grid_guard(self):
|
| 83 |
+
h=ready();self.reject(h,'method.configure','GRID_INTERVAL_MISMATCH',**dict(METHOD_EXAMPLE,interval_m=3e-9))
|
| 84 |
+
def test_33_bandwidth_enum(self):
|
| 85 |
+
h=ready();self.reject(h,'method.configure',**dict(METHOD_EXAMPLE,emission_bandwidth_m=3e-9))
|
| 86 |
+
def test_34_time_overlap(self):
|
| 87 |
+
h=ready();self.reject(h,'method.configure','INTEGRATION_OVERLAP',**dict(METHOD_EXAMPLE,mode='time',interval_s=.02))
|
| 88 |
+
def test_35_busy_guard(self):
|
| 89 |
+
h=ready();h.invoke('acquisition.start',kind='sample');self.reject(h,'method.configure','BUSY',**METHOD_EXAMPLE)
|
| 90 |
+
def test_36_read_purity(self):
|
| 91 |
+
h=ready();before=h.debug_snapshot();h.describe();h.session().read(instance_id=h.instance_id);h.invoke('spectrum.read');h.invoke('template.read',substance_id='pcad_083');h.invoke('quantify.fit',**CAPS['quantify.fit'][6]);self.assertEqual(before,h.debug_snapshot())
|
| 92 |
+
def test_37_cancel_partial(self):
|
| 93 |
+
h=ready();h.invoke('acquisition.start',kind='sample');h.step(.10);h.invoke('acquisition.stop');n=len(h.points);h.step(20);self.assertEqual(n,2);self.assertEqual(len(h.points),2);self.assertEqual(h.phase,'cancelled')
|
| 94 |
+
def test_38_lid_interrupt(self):
|
| 95 |
+
h=ready();h.invoke('acquisition.start',kind='sample');h.step(.10);h.invoke('lid.set',opened=True);self.assertFalse(h.shutter);self.assertEqual(h.phase,'cancelled');self.assertEqual(len(h.points),2)
|
| 96 |
+
def test_39_power_interrupt(self):
|
| 97 |
+
h=ready();h.invoke('acquisition.start',kind='sample');h.invoke('power.set',enabled=False);self.assertFalse(h.lamp);self.assertFalse(h.shutter);self.assertEqual(h.phase,'cancelled')
|
| 98 |
+
def test_40_photon_conservation(self):
|
| 99 |
+
h=self.done();r=h.invoke('product.read')
|
| 100 |
+
for k in ['excitation_residual','excited_event_residual','collection_residual']:self.assertLess(abs(r[k]),1e-5)
|
| 101 |
+
self.assertGreater(r['absorbed_photons'],r['emitted_photons']);self.assertGreater(r['emitted_photons'],r['detected_photons'])
|
| 102 |
+
def test_41_solute_conservation(self):
|
| 103 |
+
h=ready();r=h.invoke('product.read');h.invoke('lid.set',opened=True);h.invoke('sample.unload',recipient_id='rack');v=h.invoke('product.read');self.assertEqual(r['registered_solute_mol'],v['external_solute_mol']);self.assertEqual(v['attached_solute_mol'],0);self.assertEqual(v['solute_residual_mol'],0)
|
| 104 |
+
def test_42_chunk_invariance(self):
|
| 105 |
+
a=ready();b=ready()
|
| 106 |
+
for h in [a,b]:h.invoke('acquisition.start',kind='sample')
|
| 107 |
+
a.step(1.)
|
| 108 |
+
for _ in range(100):b.step(.01)
|
| 109 |
+
self.assertEqual(len(a.points),len(b.points));np.testing.assert_allclose([p['intensity'] for p in a.points],[p['intensity'] for p in b.points],rtol=1e-12);self.assertAlmostEqual(a.time_s,b.time_s)
|
| 110 |
+
def test_43_noise_seed(self):
|
| 111 |
+
a=self.done(plant=PLANT_EXAMPLE);b=self.done(plant=PLANT_EXAMPLE);self.assertEqual(a.points,b.points);self.assertGreater(a.points[0]['estimated_sigma'],0)
|
| 112 |
+
def test_44_accessory_required(self):
|
| 113 |
+
h=ready();self.reject(h,'thermal.set_temperature','ACCESSORY_NOT_INSTALLED',temperature_k=300.)
|
| 114 |
+
def test_45_thermal_setting_vs_control(self):
|
| 115 |
+
h=ready(plant=dict(FAST_PLANT,temperature_accessory=True));h.invoke('thermal.set_temperature',temperature_k=343.15);self.assertFalse(h.read()['thermal.within_documented_control']);h.invoke('thermal.set_temperature',temperature_k=303.15);self.assertTrue(h.read()['thermal.within_documented_control'])
|
| 116 |
+
def test_46_thermal_energy(self):
|
| 117 |
+
h=ready(plant=dict(FAST_PLANT,temperature_accessory=True));h.invoke('thermal.set_temperature',temperature_k=333.15);h.step(100);r=h.invoke('product.read');self.assertGreater(h.temperature_k,320);self.assertLess(abs(r['thermal_residual_j']),1e-8)
|
| 118 |
+
def test_47_thermal_chunk_invariance(self):
|
| 119 |
+
a=ready(plant=dict(FAST_PLANT,temperature_accessory=True));b=ready(plant=dict(FAST_PLANT,temperature_accessory=True))
|
| 120 |
+
for h in [a,b]:h.invoke('thermal.set_temperature',temperature_k=333.15)
|
| 121 |
+
a.step(80)
|
| 122 |
+
for _ in range(800):b.step(.1)
|
| 123 |
+
self.assertAlmostEqual(a.temperature_k,b.temperature_k,places=8);self.assertAlmostEqual(a.controller_energy_j,b.controller_energy_j,places=7)
|
| 124 |
+
def test_48_no_thermal_transfer_spectra(self):
|
| 125 |
+
h=ready(plant=dict(FAST_PLANT,temperature_accessory=True));h.invoke('thermal.set_temperature',temperature_k=318.15);h.step(20);self.reject(h,'acquisition.start','REFERENCE_TEMPERATURE_MISMATCH',kind='sample')
|
| 126 |
+
def test_49_fit_known(self):
|
| 127 |
+
h=ready();q=h.invoke('quantify.fit',**CAPS['quantify.fit'][6]);self.assertAlmostEqual(q['estimated_concentration_mol_m3'],.00015);self.assertAlmostEqual(q['r_squared'],1.)
|
| 128 |
+
def test_50_fit_extrapolation_null(self):
|
| 129 |
+
q=ready().invoke('quantify.fit',**dict(CAPS['quantify.fit'][6],unknown_intensity=5.));self.assertIsNone(q['estimated_concentration_mol_m3']);self.assertFalse(q['within_calibration_range'])
|
| 130 |
+
def test_51_fit_degenerate(self):
|
| 131 |
+
h=ready();self.reject(h,'quantify.fit','CALIBRATION_INPUT',**dict(CAPS['quantify.fit'][6],concentrations_mol_m3=[0.,0.,0.]))
|
| 132 |
+
def test_52_agent_no_truth(self):
|
| 133 |
+
h=ready();s=h.session();self.assertNotIn('truth.ledger',h.read());self.assertNotIn('solution.register',s.describe(instance_id=h.instance_id)['capabilities'])
|
| 134 |
+
with self.assertRaisesRegex(ActionRejected,'ACCESS_DENIED'):s.read(instance_id=h.instance_id,state_ids=['truth.ledger'])
|
| 135 |
+
def test_53_no_self_evaluator(self):
|
| 136 |
+
h=ready();r=h.session().invoke(instance_id=h.instance_id,capability_id='product.read',arguments={},request_id='t');self.assertEqual(r['error']['code'],'ACCESS_DENIED')
|
| 137 |
+
def test_54_dedup(self):
|
| 138 |
+
h=ready();s=h.session();kw=dict(instance_id=h.instance_id,capability_id='acquisition.start',arguments={'kind':'sample'},request_id='same');a=s.invoke(**kw);b=s.invoke(**kw);self.assertEqual(a,b);self.assertEqual(h._op_count,2)
|
| 139 |
+
def test_55_conflicting_request(self):
|
| 140 |
+
h=ready();s=h.session();kw=dict(instance_id=h.instance_id,capability_id='power.set',request_id='same');s.invoke(**kw,arguments={'enabled':True});r=s.invoke(**kw,arguments={'enabled':False});self.assertEqual(r['error']['code'],'REQUEST_CONFLICT');self.assertTrue(h.powered)
|
| 141 |
+
def test_56_operation_owner(self):
|
| 142 |
+
h=ready();s=h.session();r=s.invoke(instance_id=h.instance_id,capability_id='acquisition.start',arguments={'kind':'sample'},request_id='start');h.register_principal('other')
|
| 143 |
+
with self.assertRaisesRegex(ActionRejected,'ACCESS_DENIED'):h.session('other').poll(r['operation_id'])
|
| 144 |
+
h.step(.1);self.assertEqual(s.cancel(r['operation_id'],'stop')['result']['phase'],'cancelled')
|
| 145 |
+
def test_57_write_routes(self):
|
| 146 |
+
h=ready();h.session().write(instance_id=h.instance_id,state_id='lid.opened',value=True,request_id='write');self.assertTrue(h.opened)
|
| 147 |
+
def test_58_two_instances(self):
|
| 148 |
+
a=ready();b=ready();a.invoke('power.set',enabled=False);self.assertTrue(b.powered);self.assertFalse(a.powered)
|
| 149 |
+
def test_59_sampling_window(self):
|
| 150 |
+
h=self.done();v=h.session().read(instance_id=h.instance_id,state_ids=['scan.intensity'])['observations']['scan.intensity'];self.assertAlmostEqual(v['sample_window_s'][1]-v['sample_window_s'][0],.04);self.assertLess(v['sample_time_s'],h.time_s)
|
| 151 |
+
def test_60_return_isolation(self):
|
| 152 |
+
h=self.done();p=h.invoke('spectrum.read');p['points'][0]['intensity']=-123;self.assertNotEqual(h.points[0]['intensity'],-123)
|
| 153 |
+
def test_61_wrong_instance(self):
|
| 154 |
+
h=ready();r=h.session().invoke(instance_id='foreign',capability_id='power.set',arguments={'enabled':False},request_id='x');self.assertEqual(r['error']['code'],'UNKNOWN_INSTANCE')
|
| 155 |
+
def test_62_negative_step(self):
|
| 156 |
+
h=ready();old=h.debug_snapshot()
|
| 157 |
+
with self.assertRaises(ActionRejected):h.step(-1)
|
| 158 |
+
self.assertEqual(old,h.debug_snapshot())
|
| 159 |
+
def test_63_fit_overflow_rejected_without_effects(self):
|
| 160 |
+
h=ready();s=h.session();before=h.debug_snapshot()
|
| 161 |
+
q=s.invoke(instance_id=h.instance_id,capability_id='quantify.fit',arguments=dict(CAPS['quantify.fit'][6],intensities=[-1e308,0.,1e308],unknown_intensity=0.),request_id='overflow')
|
| 162 |
+
self.assertEqual(q['status'],'rejected');self.assertEqual(q['error']['code'],'CALIBRATION_INPUT');self.assertEqual(before,h.debug_snapshot());json.dumps(q,allow_nan=False)
|
| 163 |
+
def test_64_fit_subnormal_concentration_rejected(self):
|
| 164 |
+
h=ready();before=h.debug_snapshot();s=h.session()
|
| 165 |
+
q=s.invoke(instance_id=h.instance_id,capability_id='quantify.fit',arguments=dict(CAPS['quantify.fit'][6],concentrations_mol_m3=[0.,1e-320,2e-320]),request_id='subnormal')
|
| 166 |
+
self.assertEqual(q['status'],'rejected');self.assertEqual(q['error']['code'],'CALIBRATION_INPUT');self.assertEqual(before,h.debug_snapshot())
|
| 167 |
+
def test_65_fit_scaled_finite_units(self):
|
| 168 |
+
h=ready();q=h.invoke('quantify.fit',**dict(CAPS['quantify.fit'][6],concentrations_mol_m3=[0.,1e-150,2e-150]))
|
| 169 |
+
self.assertAlmostEqual(q['slope_m3_mol']/1e150,1.);self.assertAlmostEqual(q['estimated_concentration_mol_m3']/1.5e-150,1.);json.dumps(q,allow_nan=False)
|
| 170 |
+
def test_66_fit_small_domain_extrapolation_is_null(self):
|
| 171 |
+
h=ready();q=h.invoke('quantify.fit',**dict(CAPS['quantify.fit'][6],concentrations_mol_m3=[0.,1e-16,2e-16],unknown_intensity=3.))
|
| 172 |
+
self.assertIsNone(q['estimated_concentration_mol_m3']);self.assertFalse(q['within_calibration_range'])
|
| 173 |
+
def test_67_completed_operation_survives_next_scan(self):
|
| 174 |
+
h=ready();s=h.session();start=lambda rid:s.invoke(instance_id=h.instance_id,capability_id='acquisition.start',arguments={'kind':'sample'},request_id=rid)
|
| 175 |
+
old=start('first')['operation_id'];h.step(2);completed=s.poll(old);start('second');before=h.debug_snapshot()
|
| 176 |
+
self.assertEqual(s.poll(old),completed);self.assertEqual(h.debug_snapshot(),before);self.assertEqual(completed['status'],'succeeded');self.assertEqual(completed['result']['completed_points'],15)
|
| 177 |
+
completed['result']['intensity']=-123;self.assertNotEqual(s.poll(old)['result']['intensity'],-123)
|
| 178 |
+
h.register_principal('other')
|
| 179 |
+
with self.assertRaisesRegex(ActionRejected,'ACCESS_DENIED'):h.session('other').poll(old)
|
| 180 |
+
self.assertNotIn('pcad_083',json.dumps(s.poll(old)));self.assertNotIn('truth.',json.dumps(s.poll(old)))
|
| 181 |
+
def test_68_cancel_completed_operation_keeps_new_scan(self):
|
| 182 |
+
h=ready();s=h.session();start=lambda rid:s.invoke(instance_id=h.instance_id,capability_id='acquisition.start',arguments={'kind':'sample'},request_id=rid)
|
| 183 |
+
old=start('first')['operation_id'];h.step(2);current=start('second')['operation_id'];revision=h.revision
|
| 184 |
+
result=s.cancel(old,'cancel_completed');self.assertEqual(result['result']['phase'],'succeeded');self.assertEqual(h.phase,'running');self.assertEqual(h.operation_id,current);self.assertTrue(h.shutter);self.assertEqual(h.revision,revision)
|
| 185 |
+
h.step(.02);self.assertEqual(s.cancel(old,'cancel_completed'),result)
|
| 186 |
+
with self.assertRaisesRegex(ActionRejected,'REQUEST_CONFLICT'):s.cancel(current,'cancel_completed')
|
| 187 |
+
self.assertEqual(h.phase,'running')
|
| 188 |
+
def test_69_cancelled_operation_snapshot_is_stable(self):
|
| 189 |
+
h=ready();s=h.session();old=s.invoke(instance_id=h.instance_id,capability_id='acquisition.start',arguments={'kind':'sample'},request_id='first')['operation_id'];h.step(.1)
|
| 190 |
+
s.cancel(old,'cancel');frozen=s.poll(old);h.invoke('lid.set',opened=True);h.invoke('method.configure',**METHOD_EXAMPLE)
|
| 191 |
+
self.assertEqual(frozen,s.poll(old));self.assertEqual(frozen['result']['completed_points'],2);self.assertEqual(frozen['status'],'cancelled');self.assertEqual(frozen['result']['warning'],'CANCELLED')
|
| 192 |
+
def test_70_temperature_contract_matches_target_and_time(self):
|
| 193 |
+
h=ready(plant=dict(FAST_PLANT,temperature_accessory=True));meta=export_jasco_fp8350_contract_metadata();cap=meta['capabilities']['thermal.set_temperature']
|
| 194 |
+
effects={timing:{e['state_id'] for e in cap['state_effects'] if e['timing']==timing} for timing in ['immediate','on_step']}
|
| 195 |
+
before=h.read('evaluator');h.invoke('thermal.set_temperature',temperature_k=303.15);after=h.read('evaluator');changed={k for k in before if before[k]!=after[k]}
|
| 196 |
+
self.assertLessEqual(changed,effects['immediate']);self.assertNotIn('thermal.temperature_k',effects['immediate']);self.assertNotIn('power.enabled',effects['immediate']);self.assertNotIn('lid.opened',effects['immediate']);self.assertEqual(before['thermal.temperature_k'],after['thermal.temperature_k'])
|
| 197 |
+
h.step(.1);self.assertNotEqual(h.temperature_k,before['thermal.temperature_k']);self.assertIn('thermal.temperature_k',effects['on_step']);self.assertIn('scan.intensity',meta['capabilities']['process.measure']['observes']);self.assertEqual(meta['capabilities']['process.measure']['state_effects'],[])
|
| 198 |
+
if __name__=='__main__':unittest.main()
|
| 199 |
+
|
tests/test_asset_jasco_fvs6000.py
ADDED
|
@@ -0,0 +1,219 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Independent finite oracles and protocol regressions for CHEM-077; no real hardware claims."""
|
| 2 |
+
import copy, json, math, sys, unittest
|
| 3 |
+
from pathlib import Path
|
| 4 |
+
import numpy as np
|
| 5 |
+
ROOT=Path(__file__).resolve().parents[1];sys.path.insert(0,str(ROOT/'scripts'))
|
| 6 |
+
from asset_runtime.jasco_fvs6000 import *
|
| 7 |
+
|
| 8 |
+
def toy_templates():
|
| 9 |
+
x=[120000.,140000.,160000.,180000.,190000.]
|
| 10 |
+
cond=dict(solvent='DMSO-d6',concentration_kg_m3=25.,path_length_m=100e-6,window_material='BaF2',is_aqueous=False,temperature_k=None)
|
| 11 |
+
ir=dict(wavenumber_m_inv=x,absorbance=[-.02,.1,.4,.2,.0],source_resolution_m_inv=800.,evidence='measured_test_oracle',unit_evidence='inferred_from_documented_instrument_output',original_unit_explicit=None,requires_accept_inferred_units=True)
|
| 12 |
+
vcd=dict(wavenumber_m_inv=x,delta_absorbance=[-2e-4,1e-4,-3e-4,2e-4,0.],source_resolution_m_inv=800.,evidence='measured_test_oracle',unit_evidence=ir['unit_evidence'],original_unit_explicit=None,requires_accept_inferred_units=True)
|
| 13 |
+
return {'peptide_tk082_ss':dict(name='private_oracle_label',absolute_configuration='SECRET_SS',conditions=cond,ir=ir,vcd=vcd),'shape':dict(name='public_shape',ir=dict(wavenumber_m_inv=[85000.,100000.,130000.,160000.,190000.,200000.,220000.,260000.,320000.],absorbance_normalized=[0.,0.,.2,1.,.2,0.,.3,1.,0.],source_resolution_m_inv=None,evidence='real_shape_test_oracle'),vcd=None)}
|
| 14 |
+
|
| 15 |
+
def host(noise=False,templates=None,**plant):
|
| 16 |
+
h=JascoFvs6000Runtime(templates=toy_templates() if templates is None else templates)
|
| 17 |
+
p=dict(PLANT_EXAMPLE,ir_noise_sd_1s=1e-5 if noise else 0.,vcd_noise_sd_1s=1e-6 if noise else 0.);p.update(plant);h.invoke('plant.configure',**p);return h
|
| 18 |
+
|
| 19 |
+
def blank(h,method=None,sample=None):
|
| 20 |
+
h.invoke('sample.load',**(sample or BLANK_EXAMPLE));h.invoke('method.configure',**(method or METHOD_EXAMPLE));h.invoke('cover.set',opened=False);h.invoke('power.set',enabled=True);h.invoke('blank.start');h.step(h.method['accumulation_s']);return h
|
| 21 |
+
|
| 22 |
+
def load_real(h,sample=None):
|
| 23 |
+
h.invoke('cover.set',opened=True);h.invoke('sample.unload',recipient_id='external_rack');h.invoke('sample.load',**(sample or SAMPLE_EXAMPLE));h.invoke('cover.set',opened=False);return h
|
| 24 |
+
|
| 25 |
+
def ready(noise=False,method=None,**plant):return load_real(blank(host(noise,**plant),method))
|
| 26 |
+
def run(h):h.invoke('acquisition.start');h.step(h.method['accumulation_s']);return h.invoke('result.read')
|
| 27 |
+
|
| 28 |
+
def equivalent(a,b):
|
| 29 |
+
if isinstance(a,np.ndarray):return isinstance(b,np.ndarray) and np.array_equal(a,b)
|
| 30 |
+
if isinstance(a,dict):return a.keys()==b.keys() and all(equivalent(v,b[k]) for k,v in a.items())
|
| 31 |
+
if isinstance(a,(tuple,list)):return len(a)==len(b) and all(equivalent(v,w) for v,w in zip(a,b))
|
| 32 |
+
return a==b
|
| 33 |
+
|
| 34 |
+
class Fvs6000PhysicsTests(unittest.TestCase):
|
| 35 |
+
def rejected_atomic(self,h,cap,code=None,**args):
|
| 36 |
+
before=h.debug_snapshot()
|
| 37 |
+
with self.assertRaises(ActionRejected) as ctx:h.invoke(cap,**args)
|
| 38 |
+
if code:self.assertEqual(str(ctx.exception),code)
|
| 39 |
+
self.assertTrue(equivalent(before,h.debug_snapshot()),str(ctx.exception))
|
| 40 |
+
def test_full_blank_then_reference_and_signed_delta(self):
|
| 41 |
+
h=ready();r=run(h);x=np.array(r['wavenumber_m_inv']);t=toy_templates()['peptide_tk082_ss']
|
| 42 |
+
self.assertTrue(r['complete']);self.assertEqual(r['frames'],4)
|
| 43 |
+
np.testing.assert_allclose(r['ir_absorbance'],np.interp(x,t['ir']['wavenumber_m_inv'],t['ir']['absorbance']),atol=1e-16)
|
| 44 |
+
np.testing.assert_allclose(r['vcd_delta_absorbance'],np.interp(x,t['vcd']['wavenumber_m_inv'],t['vcd']['delta_absorbance']),atol=1e-19)
|
| 45 |
+
def test_polarized_transmittance_log_identity(self):
|
| 46 |
+
r=run(ready());left=np.asarray(r['transmittance_left']);right=np.asarray(r['transmittance_right'])
|
| 47 |
+
np.testing.assert_allclose(np.log10(right/left),r['vcd_delta_absorbance'],atol=2e-16)
|
| 48 |
+
np.testing.assert_allclose(-.5*np.log10(left*right),r['ir_absorbance'],atol=2e-16)
|
| 49 |
+
self.assertIn('not measured raw',r['provenance']['limitations'][-1])
|
| 50 |
+
def test_negative_reference_values_preserved(self):
|
| 51 |
+
h=ready(method=dict(METHOD_EXAMPLE,wavenumber_start_m_inv=120000.,wavenumber_stop_m_inv=140000.));r=run(h)
|
| 52 |
+
self.assertLess(r['ir_absorbance'][0],0);self.assertGreater(r['transmittance_left'][0],1.)
|
| 53 |
+
def test_center_readout_uses_true_wavenumber_midpoint(self):
|
| 54 |
+
h=ready();r=run(h);m=h.invoke('process.measure');center=(r['wavenumber_m_inv'][0]+r['wavenumber_m_inv'][-1])/2
|
| 55 |
+
self.assertAlmostEqual(m['ir_center'],np.interp(center,r['wavenumber_m_inv'],r['ir_absorbance']))
|
| 56 |
+
self.assertNotEqual(m['ir_center'],r['ir_absorbance'][len(r['ir_absorbance'])//2])
|
| 57 |
+
def test_blank_is_observed_and_subtracted(self):
|
| 58 |
+
h=ready(blank_ir_absorbance=.3,blank_vcd_bias=-.002);b=h.invoke('blank.read')['result'];r=run(h)
|
| 59 |
+
np.testing.assert_allclose(b['ir_absorbance'],.3);np.testing.assert_allclose(b['vcd_delta_absorbance'],-.002)
|
| 60 |
+
self.assertAlmostEqual(r['ir_absorbance'][0],.25);self.assertAlmostEqual(r['vcd_delta_absorbance'][0],-.0001)
|
| 61 |
+
def test_complete_blank_required(self):
|
| 62 |
+
h=host();h.invoke('sample.load',**SAMPLE_EXAMPLE);h.invoke('method.configure',**METHOD_EXAMPLE);h.invoke('power.set',enabled=True);h.invoke('cover.set',opened=False)
|
| 63 |
+
self.rejected_atomic(h,'acquisition.start','MATCHED_BLANK_REQUIRED')
|
| 64 |
+
def test_partial_blank_never_becomes_background(self):
|
| 65 |
+
h=host();h.invoke('sample.load',**BLANK_EXAMPLE);h.invoke('method.configure',**METHOD_EXAMPLE);h.invoke('power.set',enabled=True);h.invoke('cover.set',opened=False);h.invoke('blank.start');h.step(.3);h.invoke('acquisition.stop')
|
| 66 |
+
self.assertEqual(h.invoke('result.read')['frames'],1);self.assertFalse(h.read()['blank.valid']);self.assertIsNone(h.invoke('blank.read')['result'])
|
| 67 |
+
def test_blank_accumulation_may_differ_but_grid_must_match(self):
|
| 68 |
+
h=ready();h.invoke('method.configure',**dict(METHOD_EXAMPLE,accumulation_s=.5));self.assertTrue(h.read()['blank.valid']);self.assertEqual(run(h)['frames'],2)
|
| 69 |
+
h.invoke('method.configure',**dict(METHOD_EXAMPLE,spacing_m_inv=500.));self.assertFalse(h.read()['blank.valid']);self.rejected_atomic(h,'acquisition.start','MATCHED_BLANK_REQUIRED')
|
| 70 |
+
def test_power_off_invalidates_blank(self):
|
| 71 |
+
h=ready();h.invoke('power.set',enabled=False);h.invoke('power.set',enabled=True);self.assertFalse(h.read()['blank.valid'])
|
| 72 |
+
def test_known_conditions_reject_without_mutating_inventory(self):
|
| 73 |
+
for field,value in [('solvent','water'),('concentration_kg_m3',24.),('is_aqueous',True)]:
|
| 74 |
+
h=host();self.rejected_atomic(h,'sample.load',**dict(SAMPLE_EXAMPLE,**{field:value}))
|
| 75 |
+
def test_unit_inference_and_unknown_temperature_require_host_ack(self):
|
| 76 |
+
for flag,code in [('accept_inferred_units','INFERRED_UNITS_ACK_REQUIRED'),('accept_unknown_conditions','UNKNOWN_CONDITIONS_ACK_REQUIRED')]:
|
| 77 |
+
h=host();self.rejected_atomic(h,'sample.load',code,**dict(SAMPLE_EXAMPLE,**{flag:False}))
|
| 78 |
+
def test_provenance_retains_unit_inference_and_unknown_temperature(self):
|
| 79 |
+
r=run(ready());p=r['provenance'];self.assertEqual(p['unit_evidence'],'inferred_from_documented_instrument_output');self.assertIsNone(p['original_unit_explicit']);self.assertIsNone(p['source_temperature_k']);self.assertTrue(p['inferred_units_accepted']);self.assertTrue(p['unknown_conditions_accepted'])
|
| 80 |
+
def test_source_resolution_not_improved(self):
|
| 81 |
+
h=ready(method=dict(METHOD_EXAMPLE,resolution_m_inv=400.));self.rejected_atomic(h,'acquisition.start','SOURCE_RESOLUTION_LIMIT')
|
| 82 |
+
def test_source_axis_intersection_not_extrapolated(self):
|
| 83 |
+
t=toy_templates();t['peptide_tk082_ss']['vcd']['wavenumber_m_inv'][0]=130000.
|
| 84 |
+
h=host(templates=t);load_real(blank(h,dict(METHOD_EXAMPLE,wavenumber_start_m_inv=120000.)));self.rejected_atomic(h,'acquisition.start','SOURCE_WAVENUMBER_RANGE')
|
| 85 |
+
def test_broader_resolution_reduces_independent_peak(self):
|
| 86 |
+
x=np.arange(120000.,190001.,100.);y=np.exp(-.5*((x-160000.)/100.)**2)
|
| 87 |
+
t=toy_templates();t['peptide_tk082_ss']['ir'].update(wavenumber_m_inv=x.tolist(),absorbance=y.tolist(),source_resolution_m_inv=800.)
|
| 88 |
+
h=host(templates=t);r=run(load_real(blank(h,dict(METHOD_EXAMPLE,resolution_m_inv=1600.))));self.assertLess(max(r['ir_absorbance']),.3)
|
| 89 |
+
def test_synthetic_ir_is_explicit_and_no_hidden_vcd(self):
|
| 90 |
+
h=blank(host());s=dict(SAMPLE_EXAMPLE,kind='synthetic_ir',template_id='shape',ir_peak_absorbance=.4,synthetic_vcd_ratio=-4e-5,accept_surrogate=True,accept_inferred_units=False)
|
| 91 |
+
r=run(load_real(h,s));np.testing.assert_allclose(r['vcd_delta_absorbance'],np.asarray(r['ir_absorbance'])*-4e-5,atol=2e-20);self.assertEqual(r['provenance']['vcd_evidence'],'synthetic')
|
| 92 |
+
def test_normalized_ir_cannot_be_claimed_measured_vcd(self):
|
| 93 |
+
h=host();self.rejected_atomic(h,'sample.load','MEASURED_VCD_REQUIRED',**dict(SAMPLE_EXAMPLE,template_id='shape'))
|
| 94 |
+
def test_synthetic_mode_requires_explicit_acceptance(self):
|
| 95 |
+
h=host();self.rejected_atomic(h,'sample.load','EVIDENCE_ACK_REQUIRED',**dict(SAMPLE_EXAMPLE,kind='synthetic_ir',template_id='shape',accept_surrogate=False))
|
| 96 |
+
def test_baf2_rejects_water(self):
|
| 97 |
+
h=host();self.rejected_atomic(h,'sample.load','BAF2_WATER_INCOMPATIBLE',**dict(BLANK_EXAMPLE,solvent='water',is_aqueous=True))
|
| 98 |
+
def test_caf2_and_filter_windows(self):
|
| 99 |
+
h=host();h.invoke('path.configure',path_length_m=25e-6,window_material='CaF2');h.invoke('sample.load',**dict(BLANK_EXAMPLE,solvent='water',is_aqueous=True));h.invoke('method.configure',**dict(METHOD_EXAMPLE,wavenumber_start_m_inv=100000.));h.invoke('cover.set',opened=False);h.invoke('power.set',enabled=True);self.rejected_atomic(h,'blank.start','CAF2_WINDOW')
|
| 100 |
+
h.invoke('method.configure',**dict(METHOD_EXAMPLE,wavenumber_start_m_inv=180000.,wavenumber_stop_m_inv=220000.));self.rejected_atomic(h,'blank.start','FILTER_WINDOW')
|
| 101 |
+
def test_finite_filter_motion_and_power_hold(self):
|
| 102 |
+
h=host();h.invoke('filter.select',selection='high');h.step(.25);self.assertEqual(h.read()['filter.angle_rad'],0.);h.invoke('power.set',enabled=True);h.step(.25);self.assertAlmostEqual(h.read()['filter.angle_rad'],math.pi/4);h.step(.75);self.assertEqual(h.read()['filter.angle_rad'],math.pi)
|
| 103 |
+
def test_filter_motion_blocks_acquisition(self):
|
| 104 |
+
h=blank(host());h.invoke('filter.select',selection='high');self.rejected_atomic(h,'blank.start','FILTER_NOT_SETTLED')
|
| 105 |
+
def test_three_position_option_and_empty_side_slots(self):
|
| 106 |
+
h=host(three_position_installed=False);self.rejected_atomic(h,'stage.select','OPTION_NOT_INSTALLED',position=1)
|
| 107 |
+
h=ready();h.invoke('stage.select',position=1);h.step(.2);self.assertAlmostEqual(h.read()['sample.position_m'],.01);self.rejected_atomic(h,'acquisition.start','CENTER_POSITION_REQUIRED');h.step(.5);self.assertAlmostEqual(h.read()['sample.position_m'],.035)
|
| 108 |
+
def test_thermal_closed_form_and_energy_accounting(self):
|
| 109 |
+
h=host();h.invoke('power.set',enabled=True);h.invoke('temperature.set',target_k=308.15);h.step(2.)
|
| 110 |
+
self.assertAlmostEqual(h.temperature,308.15-10*math.exp(-.5));self.assertAlmostEqual(h._ledger()['heat_residual_j'],0.,places=11)
|
| 111 |
+
h.invoke('power.set',enabled=False);t=h.temperature;h.step(3.);self.assertAlmostEqual(h.temperature,298.15+(t-298.15)*math.exp(-.75));self.assertAlmostEqual(h._ledger()['heat_residual_j'],0.,places=11)
|
| 112 |
+
def test_temperature_option_and_water_interlocks(self):
|
| 113 |
+
h=host(temperature_installed=False);self.rejected_atomic(h,'temperature.set','OPTION_NOT_INSTALLED',target_k=303.15)
|
| 114 |
+
h=host(water_ready=False);self.rejected_atomic(h,'temperature.set','COOLING_WATER_REQUIRED',target_k=303.15)
|
| 115 |
+
def test_unsettled_temperature_blocks_measurement(self):
|
| 116 |
+
h=ready();h.invoke('temperature.set',target_k=308.15);self.rejected_atomic(h,'acquisition.start','TEMPERATURE_NOT_SETTLED');self.assertFalse(h.read()['blank.valid'])
|
| 117 |
+
def test_load_unload_volume_and_solute_conserved(self):
|
| 118 |
+
h=ready();before=h._ledger();run(h);after=h._ledger();self.assertEqual(before['current_volume_m3'],after['current_volume_m3']);self.assertEqual(before['current_solute_kg'],after['current_solute_kg'])
|
| 119 |
+
h.invoke('cover.set',opened=True);h.invoke('sample.unload',recipient_id='rack');l=h._ledger();self.assertAlmostEqual(l['volume_residual_m3'],0.,places=20);self.assertAlmostEqual(l['solute_residual_kg'],0.,places=20);self.assertEqual(l['current_volume_m3'],0.)
|
| 120 |
+
def test_sample_load_does_not_overwrite_occupied_cell(self):
|
| 121 |
+
h=host();h.invoke('sample.load',**BLANK_EXAMPLE);self.rejected_atomic(h,'sample.load','UNLOAD_REQUIRED',**SAMPLE_EXAMPLE)
|
| 122 |
+
def test_host_utilities_and_cover_gates(self):
|
| 123 |
+
for flag in ['detector_ready','purge_ready']:
|
| 124 |
+
h=host(**{flag:False});h.invoke('sample.load',**BLANK_EXAMPLE);h.invoke('method.configure',**METHOD_EXAMPLE);h.invoke('power.set',enabled=True);h.invoke('cover.set',opened=False);self.rejected_atomic(h,'blank.start','OPTICS_NOT_READY')
|
| 125 |
+
def test_noise_time_weighting_independent_rng_oracle(self):
|
| 126 |
+
h=host(noise=True);m=dict(METHOD_EXAMPLE,accumulation_s=.6);blank(h,m);r=h.invoke('result.read');rng=np.random.default_rng(77);n=len(r['wavenumber_m_inv']);expected_a=np.zeros(n);expected_d=np.zeros(n)
|
| 127 |
+
for dt in [.25,.25,.1]:
|
| 128 |
+
expected_a+=dt*(.05+rng.normal(0,1e-5/math.sqrt(dt),n))/.6;expected_d+=dt*(2e-6+rng.normal(0,1e-6/math.sqrt(dt),n))/.6
|
| 129 |
+
np.testing.assert_allclose(r['ir_absorbance'],expected_a,atol=3e-17);np.testing.assert_allclose(r['vcd_delta_absorbance'],expected_d,atol=2e-20)
|
| 130 |
+
def test_step_partition_keeps_same_rng_frames_and_observations(self):
|
| 131 |
+
h=ready(noise=True);g=ready(noise=True);h.invoke('acquisition.start');g.invoke('acquisition.start');h.step(1.)
|
| 132 |
+
for dt in [.1]*10:g.step(dt)
|
| 133 |
+
np.testing.assert_array_equal(h._mean_ir,g._mean_ir);np.testing.assert_array_equal(h._mean_vcd,g._mean_vcd);self.assertEqual(g.phase,'succeeded');self.assertAlmostEqual(h.time_s,g.time_s)
|
| 134 |
+
def test_decimal_frame_duration_does_not_create_tiny_extra_frame(self):
|
| 135 |
+
h=ready(noise=True,frame_duration_s=.1);h.invoke('acquisition.start');h.step(1.);self.assertEqual(h._frames,10);self.assertEqual(h.phase,'succeeded');self.assertAlmostEqual(h._sampled_s,1.)
|
| 136 |
+
def test_synthetic_path_scaling_does_not_invent_concentration_response(self):
|
| 137 |
+
results=[]
|
| 138 |
+
for path,concentration in [(100e-6,25.),(50e-6,100.)]:
|
| 139 |
+
h=host();h.invoke('path.configure',path_length_m=path,window_material='BaF2');blank(h)
|
| 140 |
+
sample=dict(SAMPLE_EXAMPLE,kind='synthetic_ir',template_id='shape',ir_peak_absorbance=.4,synthetic_vcd_ratio=4e-5,accept_surrogate=True,concentration_kg_m3=concentration)
|
| 141 |
+
results.append(run(load_real(h,sample)))
|
| 142 |
+
np.testing.assert_allclose(results[0]['ir_absorbance'],2*np.array(results[1]['ir_absorbance']),atol=2e-16)
|
| 143 |
+
def test_no_early_future_frame_or_backward_clock(self):
|
| 144 |
+
h=ready();h.invoke('acquisition.start');h.step(.25-5e-13);self.assertEqual(h._frames,0);t=h.time_s;h.step(5e-13);self.assertGreaterEqual(h.time_s,t);self.assertLessEqual(h._last_sample_time,h.time_s)
|
| 145 |
+
def test_frame_windows_and_cancel_partial_accumulation(self):
|
| 146 |
+
h=ready();h.invoke('acquisition.start');start=h.time_s;h.step(.4);h.invoke('acquisition.stop');r=h.invoke('result.read');self.assertEqual(r['frames'],1);self.assertEqual(r['sample_window_s'],[start,start+.25]);self.assertAlmostEqual(h.elapsed_s,.4);before=h._result();h.step(10);self.assertEqual(h._result(),before)
|
| 147 |
+
def test_cover_and_power_cancel_without_fabricating_frame(self):
|
| 148 |
+
for cap,arg in [('cover.set',{'opened':True}),('power.set',{'enabled':False})]:
|
| 149 |
+
h=ready();h.invoke('acquisition.start');h.step(.4);h.invoke(cap,**arg);self.assertEqual(h.phase,'cancelled');self.assertEqual(h._frames,1);self.assertAlmostEqual(h.elapsed_s,.4)
|
| 150 |
+
def test_busy_reconfiguration_is_atomic(self):
|
| 151 |
+
h=ready();h.invoke('acquisition.start')
|
| 152 |
+
for cap,args in [('method.configure',METHOD_EXAMPLE),('filter.select',{'selection':'high'}),('temperature.set',{'target_k':303.15}),('stage.select',{'position':1})]:self.rejected_atomic(h,cap,'BUSY',**args)
|
| 153 |
+
def test_result_method_snapshot_survives_reconfiguration(self):
|
| 154 |
+
h=ready();r=run(h);h.invoke('method.configure',**dict(METHOD_EXAMPLE,accumulation_s=2.,spacing_m_inv=800.));self.assertEqual(h.invoke('result.read'),r);self.assertEqual(h.read()['method.accumulation_s'],2.)
|
| 155 |
+
def test_zero_step_and_queries_do_not_mutate_runtime_or_rng(self):
|
| 156 |
+
h=ready(noise=True);run(h);snap=h.debug_snapshot();h.step(0)
|
| 157 |
+
for k in ['process.measure','result.read','blank.read','product.read']:h.invoke(k)
|
| 158 |
+
h.invoke('result.export',format='json');h.invoke('template.read',substance_id='shape');h.read();h.describe();self.assertTrue(equivalent(snap,h.debug_snapshot()))
|
| 159 |
+
def test_reference_compare_sign_and_no_configuration_assignment(self):
|
| 160 |
+
h=host();same=h.invoke('reference.compare',observed=[2.,-2.,1.],reference=[1.,-1.,.5]);opposite=h.invoke('reference.compare',observed=[-2.,2.,-1.],reference=[1.,-1.,.5]);self.assertEqual(same['nonnegative_scale'],2.);self.assertAlmostEqual(same['signed_cosine'],1.);self.assertEqual(opposite['nonnegative_scale'],0.);self.assertAlmostEqual(opposite['signed_cosine'],-1.);self.assertEqual(opposite['configuration_assignment'],'not_assigned')
|
| 161 |
+
def test_reference_comparison_numeric_overflow_and_zero_rejection(self):
|
| 162 |
+
h=host();r=h.invoke('reference.compare',observed=[1e300,-1e300],reference=[1e300,-1e300]);self.assertEqual(r['nonnegative_scale'],1.)
|
| 163 |
+
self.rejected_atomic(h,'reference.compare','ANALYSIS_RANGE',observed=[1e300,1e300],reference=[1e-300,1e-300]);self.rejected_atomic(h,'reference.compare','ANALYSIS_INPUT',observed=[0.,0.],reference=[1.,2.])
|
| 164 |
+
def test_nonfinite_boolean_and_resource_inputs_reject_atomically(self):
|
| 165 |
+
h=host()
|
| 166 |
+
for x in [float('nan'),float('inf'),-1.,True]:self.rejected_atomic(h,'method.configure','INVALID_ARGUMENT',**dict(METHOD_EXAMPLE,accumulation_s=x))
|
| 167 |
+
self.rejected_atomic(h,'method.configure','SPECTRAL_GRID',**dict(METHOD_EXAMPLE,wavenumber_stop_m_inv=150000.))
|
| 168 |
+
g=host(frame_duration_s=.01);self.rejected_atomic(g,'method.configure','EVENT_RESOURCE_LIMIT',**dict(METHOD_EXAMPLE,accumulation_s=86400.,spacing_m_inv=25.))
|
| 169 |
+
def test_template_query_keeps_absence_and_unit_markers(self):
|
| 170 |
+
h=host();r=json.loads(h.invoke('template.read',substance_id='peptide_tk082_ss')['template_json']);self.assertTrue(r['vcd']['requires_accept_inferred_units']);self.assertIsNone(r['conditions']['temperature_k']);r=json.loads(h.invoke('template.read',substance_id='shape')['template_json']);self.assertIsNone(r['vcd'])
|
| 171 |
+
def test_actual_library_source_ranges_and_unit_flags(self):
|
| 172 |
+
h=JascoFvs6000Runtime();h.invoke('plant.configure',**dict(PLANT_EXAMPLE,ir_noise_sd_1s=0.,vcd_noise_sd_1s=0.));blank(h);load_real(h);r=run(h);self.assertEqual(r['provenance']['vcd_evidence'],'measured_literature');self.assertTrue(r['provenance']['inferred_units_accepted']);self.assertTrue(all(math.isfinite(x) for x in r['vcd_delta_absorbance']))
|
| 173 |
+
|
| 174 |
+
class Fvs6000ProtocolTests(unittest.TestCase):
|
| 175 |
+
def sessions(self):
|
| 176 |
+
h=ready();h.register_principal('host','evaluator');h.register_principal('other');return h,h.session(),h.session('host'),h.session('other')
|
| 177 |
+
def invoke(self,s,h,k,a=None,rid='unique'):return s.invoke(instance_id=h.instance_id,capability_id=k,arguments=a or {},request_id=rid)
|
| 178 |
+
def test_agent_cannot_escalate_or_read_truth(self):
|
| 179 |
+
h,a,e,o=self.sessions();before=h.debug_snapshot();r=self.invoke(a,h,'sample.load',SAMPLE_EXAMPLE);self.assertEqual(r['error']['code'],'ACCESS_DENIED');self.assertTrue(equivalent(before,h.debug_snapshot()));self.assertNotIn('truth.ledger',a.read(instance_id=h.instance_id)['observations']);self.assertIn('truth.ledger',e.read(instance_id=h.instance_id)['observations'])
|
| 180 |
+
with self.assertRaises(ActionRejected):a.read(instance_id=h.instance_id,state_ids=['truth.ledger'])
|
| 181 |
+
with self.assertRaises(ActionRejected):h.read('owner')
|
| 182 |
+
def test_public_result_never_leaks_current_sample_identity(self):
|
| 183 |
+
h,a,e,o=self.sessions();run(h)
|
| 184 |
+
for k in ['process.measure','result.read','result.export']:
|
| 185 |
+
r=self.invoke(a,h,k,{'format':'json'} if k=='result.export' else {},rid=k);text=json.dumps(r)
|
| 186 |
+
for hidden in ['private_oracle_label','SECRET_SS','external_reference_cell','peptide_tk082_ss']:self.assertNotIn(hidden,text)
|
| 187 |
+
def test_idempotent_start_and_request_conflict(self):
|
| 188 |
+
h,a,e,o=self.sessions();r=self.invoke(a,h,'acquisition.start',rid='start');snap=h.debug_snapshot();self.assertEqual(self.invoke(a,h,'acquisition.start',rid='start'),r);self.assertTrue(equivalent(snap,h.debug_snapshot()));bad=self.invoke(a,h,'acquisition.stop',rid='start');self.assertEqual(bad['error']['code'],'REQUEST_CONFLICT')
|
| 189 |
+
def test_historical_full_result_owned_and_method_bound(self):
|
| 190 |
+
h,a,e,o=self.sessions();r=self.invoke(a,h,'acquisition.start');op=r['operation_id'];h.step(1);old=a.poll(op);self.assertEqual(old['result'],h.invoke('result.read'));h.invoke('method.configure',**dict(METHOD_EXAMPLE,accumulation_s=.5));self.invoke(a,h,'acquisition.start',rid='next');h.step(.25);self.assertEqual(a.poll(op),old)
|
| 191 |
+
with self.assertRaises(ActionRejected):o.poll(op)
|
| 192 |
+
def test_historical_cancel_does_not_stop_new_acquisition(self):
|
| 193 |
+
h,a,e,o=self.sessions();op=self.invoke(a,h,'acquisition.start')['operation_id'];h.step(1);new=self.invoke(a,h,'acquisition.start',rid='next')['operation_id'];r=a.cancel(op,'cancel-old');self.assertEqual(r['result']['phase'],'succeeded');self.assertEqual(h.phase,'running');self.assertEqual(h.operation_id,new)
|
| 194 |
+
def test_cancel_history_and_mean_windows_match_read(self):
|
| 195 |
+
h,a,e,o=self.sessions();op=self.invoke(a,h,'acquisition.start')['operation_id'];h.step(.4);a.cancel(op,'cancel');p=a.poll(op);read=a.read(instance_id=h.instance_id)
|
| 196 |
+
for k in ['scan.ir_center','scan.vcd_center']:self.assertEqual(p['observations'][k],read['observations'][k]);self.assertEqual(read['observations'][k]['sample_window_s'],[1.,1.25])
|
| 197 |
+
self.invoke(a,h,'acquisition.start',rid='next');self.assertEqual(a.poll(op),p)
|
| 198 |
+
def test_new_acquisition_has_unavailable_observation_not_stale_window(self):
|
| 199 |
+
h,a,e,o=self.sessions();run(h);self.invoke(a,h,'acquisition.start');r=a.read(instance_id=h.instance_id)['observations']['scan.ir_center'];self.assertIsNone(r['value']);self.assertEqual(r['quality'],'unavailable');self.assertIsNone(r['sample_window_s'])
|
| 200 |
+
def test_csv_export_preserves_metadata_and_row_count(self):
|
| 201 |
+
h=ready();r=run(h);out=h.invoke('result.export',format='csv')['content'];lines=out.splitlines();meta=json.loads(lines[0][2:]);self.assertEqual(meta['provenance'],r['provenance']);self.assertEqual(len(lines)-2,len(r['wavenumber_m_inv']))
|
| 202 |
+
def test_all_current_outputs_and_slots_match_declared_schemas(self):
|
| 203 |
+
h,a,e,o=self.sessions();run(h)
|
| 204 |
+
for k in ['process.measure','result.read','blank.read','product.read','result.export','template.read','reference.compare']:
|
| 205 |
+
args=CAPS[k][6];validate(CAPS[k][1],h.invoke(k,**args))
|
| 206 |
+
for k,v in h.read('evaluator').items():validate(SLOTS[k][0],v)
|
| 207 |
+
def test_metadata_is_precise_and_queries_effect_free(self):
|
| 208 |
+
meta=export_jasco_fvs6000_contract_metadata();self.assertEqual(len(meta['capabilities']),22);self.assertEqual(len(meta['state_slots']),32)
|
| 209 |
+
for k,c in meta['capabilities'].items():
|
| 210 |
+
if c['kind'] in ['query','analysis'] or k in UNSUPPORTED:self.assertEqual(c['state_effects'],[])
|
| 211 |
+
self.assertTrue(set(c['observes'])<=SLOTS.keys())
|
| 212 |
+
effects=meta['capabilities']['filter.select']['state_effects'];self.assertIn({'state_id':'filter.angle_rad','timing':'on_step','description_zh':'仅后续宿主step推进有限运动、热学代理或完成全谱积分帧'},effects);self.assertFalse(any(x['state_id']=='scan.ir_center' for x in effects))
|
| 213 |
+
self.assertEqual(JascoFvs6000Runtime().describe()['asset_version'],'1.0.1')
|
| 214 |
+
def test_unsupported_capabilities_reject_without_effect(self):
|
| 215 |
+
h,a,e,o=self.sessions()
|
| 216 |
+
for k in UNSUPPORTED:
|
| 217 |
+
before=h.debug_snapshot();r=self.invoke(a,h,k,rid=k);self.assertEqual(r['status'],'unsupported');self.assertTrue(equivalent(before,h.debug_snapshot()))
|
| 218 |
+
|
| 219 |
+
if __name__=='__main__':unittest.main()
|
tests/test_asset_jasco_j1500.py
ADDED
|
@@ -0,0 +1,177 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Actual CHEM-065 protocol, optical math, finite-resource and timing regressions."""
|
| 2 |
+
import copy,json,math,unittest
|
| 3 |
+
import numpy as np
|
| 4 |
+
from scripts.asset_runtime.jasco_j1500 import *
|
| 5 |
+
def ready(kind='sample',method=None,plant=None,sample=None):
|
| 6 |
+
h=JascoJ1500Runtime();h.invoke('plant.configure',**dict(FAST_PLANT,**(plant or {})))
|
| 7 |
+
h.invoke('solution.register',**BLANK_EXAMPLE);h.invoke('sample.load',sample_id='blank_01')
|
| 8 |
+
h.invoke('method.configure',**dict(METHOD_EXAMPLE,**(method or {})));h.invoke('lid.set',opened=False);h.invoke('purge.set',flow_std_m3_s=2e-3/60);h.invoke('power.set',enabled=True);h.invoke('lamp.set',enabled=True);h.step(6)
|
| 9 |
+
if kind=='blank':return h
|
| 10 |
+
h.invoke('acquisition.start',kind='blank');h.step(200);h.invoke('lid.set',opened=True);h.invoke('sample.unload',recipient_id='rack')
|
| 11 |
+
h.invoke('solution.register',**dict(SAMPLE_EXAMPLE,**(sample or {})));h.invoke('sample.load',sample_id=(sample or {}).get('sample_id','sample_01'));h.invoke('lid.set',opened=False);h.step(120)
|
| 12 |
+
return h
|
| 13 |
+
class TestJ1500(unittest.TestCase):
|
| 14 |
+
def unchanged_reject(self,h,cap,**args):
|
| 15 |
+
before=h.debug_snapshot()
|
| 16 |
+
with self.assertRaises(ActionRejected):h.invoke(cap,**args)
|
| 17 |
+
self.assertEqual(before,h.debug_snapshot())
|
| 18 |
+
def test_library_real_71_and_units(self):
|
| 19 |
+
h=JascoJ1500Runtime();self.assertEqual(len(h.templates),71)
|
| 20 |
+
for r in h.templates.values():
|
| 21 |
+
self.assertEqual(r['evidence'],'measured_literature');self.assertEqual(len(r['delta_epsilon_m2_mol']),66);self.assertAlmostEqual(r['wavelength_m'][0],175e-9,places=20);self.assertAlmostEqual(sum(r['secondary_structure_fractions']),1.)
|
| 22 |
+
def test_full_blank_then_sample(self):
|
| 23 |
+
h=ready();h.invoke('acquisition.start',kind='sample');h.step(4);self.assertEqual(h.phase,'succeeded');self.assertEqual(len(h.points),41);self.assertFalse(h.shutter);self.assertEqual(h.invoke('spectrum.read')['absorbance_evidence'],'synthetic_host_supplied_independent_mean_absorption')
|
| 24 |
+
def test_setting_does_not_advance(self):
|
| 25 |
+
h=ready();t=h.time_s;h.invoke('method.configure',**METHOD_EXAMPLE);self.assertEqual(h.time_s,t)
|
| 26 |
+
def test_read_describe_are_pure(self):
|
| 27 |
+
h=ready();before=h.debug_snapshot();h.read();h.describe();h.invoke('process.measure');h.invoke('spectrum.read');h.session().read(instance_id=h.instance_id);self.assertEqual(before,h.debug_snapshot())
|
| 28 |
+
def test_invalid_numeric_bool_nan_unknown_atomic(self):
|
| 29 |
+
h=ready()
|
| 30 |
+
for v in [True,float('nan'),float('inf'),-1]:
|
| 31 |
+
self.unchanged_reject(h,'purge.set',flow_std_m3_s=v)
|
| 32 |
+
self.unchanged_reject(h,'power.set',enabled=True,evil='x')
|
| 33 |
+
def test_host_initialization_only(self):
|
| 34 |
+
h=ready();self.unchanged_reject(h,'plant.configure',**PLANT_EXAMPLE)
|
| 35 |
+
def test_purged_snapshot_explicit(self):
|
| 36 |
+
h=JascoJ1500Runtime();self.unchanged_reject(h,'plant.configure',**dict(FAST_PLANT,accept_purged_snapshot=False))
|
| 37 |
+
def test_no_lamp_before_purge(self):
|
| 38 |
+
h=JascoJ1500Runtime();h.invoke('plant.configure',**PLANT_EXAMPLE);h.invoke('power.set',enabled=True);h.invoke('purge.set',flow_std_m3_s=2e-3/60);self.unchanged_reject(h,'lamp.set',enabled=True);h.step(120);h.invoke('lamp.set',enabled=True);self.assertFalse(h.read()['lamp.ready']);h.step(5);self.assertTrue(h.read()['lamp.ready'])
|
| 39 |
+
def test_ambient_readout_not_temp_control(self):
|
| 40 |
+
h=ready(plant={'ambient_k':300.});self.assertEqual(h.read()['sample.temperature_k'],300.);self.unchanged_reject(h,'thermal.set_temperature',temperature_k=320.)
|
| 41 |
+
def test_access_requires_open(self):
|
| 42 |
+
h=ready();self.unchanged_reject(h,'sample.unload',recipient_id='r')
|
| 43 |
+
def test_duplicate_sample_id_atomic(self):
|
| 44 |
+
h=ready();self.unchanged_reject(h,'solution.register',**SAMPLE_EXAMPLE)
|
| 45 |
+
def test_unknown_sample_and_template(self):
|
| 46 |
+
h=ready();self.unchanged_reject(h,'sample.load',sample_id='unknown');self.unchanged_reject(h,'template.read',substance_id='unknown')
|
| 47 |
+
def test_polarization_absorption_physical_bound(self):
|
| 48 |
+
h=ready();self.unchanged_reject(h,'solution.register',**dict(SAMPLE_EXAMPLE,sample_id='bad',mean_epsilon_m2_mol=[0.]*66))
|
| 49 |
+
def test_rectangular_path_and_volume_proxy(self):
|
| 50 |
+
h=ready()
|
| 51 |
+
self.unchanged_reject(h,'solution.register',**dict(SAMPLE_EXAMPLE,sample_id='short',path_length_m=.0001))
|
| 52 |
+
self.unchanged_reject(h,'solution.register',**dict(SAMPLE_EXAMPLE,sample_id='large',volume_m3=1e-5))
|
| 53 |
+
def test_cylindrical_path_supported(self):
|
| 54 |
+
h=ready();h.invoke('solution.register',**dict(SAMPLE_EXAMPLE,sample_id='cyl',cell_shape='cylindrical',path_length_m=.0001,volume_m3=1e-8));self.assertIn('cyl',h.samples)
|
| 55 |
+
def test_uv_evidence_mandatory(self):
|
| 56 |
+
h=ready();self.unchanged_reject(h,'solution.register',**dict(SAMPLE_EXAMPLE,sample_id='bad',accept_synthetic_uv=False))
|
| 57 |
+
def test_method_ranges_and_grid(self):
|
| 58 |
+
h=ready()
|
| 59 |
+
for args in [dict(start_m=162e-9),dict(stop_m=951e-9),dict(speed_m_s=10001e-9/60),dict(bandwidth_m=17e-9),dict(integration_s=31.),dict(interval_m=3e-9),dict(accumulations=True)]:
|
| 60 |
+
self.unchanged_reject(h,'method.configure',**dict(METHOD_EXAMPLE,**args))
|
| 61 |
+
def test_hardware_range_not_template_range(self):
|
| 62 |
+
h=ready(kind='blank',method={'start_m':940e-9,'stop_m':900e-9});self.unchanged_reject(h,'acquisition.start',kind='blank')
|
| 63 |
+
def test_bandpass_edge_rejected_not_extrapolated(self):
|
| 64 |
+
h=ready(kind='blank',method={'start_m':239e-9,'stop_m':199e-9,'bandwidth_m':2e-9});self.unchanged_reject(h,'acquisition.start',kind='blank')
|
| 65 |
+
def test_purge_threshold_mapping(self):
|
| 66 |
+
h=ready();self.assertAlmostEqual(h._minimum_flow(186e-9),2e-3/60);self.assertAlmostEqual(h._minimum_flow(185e-9),5e-3/60);self.assertAlmostEqual(h._minimum_flow(180e-9),15e-3/60);self.assertGreater(h._minimum_flow(175e-9),15e-3/60)
|
| 67 |
+
with self.assertRaises(ActionRejected):h._minimum_flow(170e-9)
|
| 68 |
+
def test_low_wavelength_requires_more_gas(self):
|
| 69 |
+
h=ready(kind='blank',method={'start_m':226e-9,'stop_m':186e-9})
|
| 70 |
+
h.invoke('method.configure',**dict(METHOD_EXAMPLE,start_m=225e-9,stop_m=185e-9))
|
| 71 |
+
self.unchanged_reject(h,'acquisition.start',kind='blank');h.invoke('purge.set',flow_std_m3_s=5e-3/60);h.invoke('acquisition.start',kind='blank')
|
| 72 |
+
def test_blank_required(self):
|
| 73 |
+
h=ready(kind='blank');h.invoke('lid.set',opened=True);h.invoke('sample.unload',recipient_id='r');h.invoke('solution.register',**SAMPLE_EXAMPLE);h.invoke('sample.load',sample_id='sample_01');h.invoke('lid.set',opened=False);h.step(120);self.unchanged_reject(h,'acquisition.start',kind='sample')
|
| 74 |
+
def test_method_change_invalidates_blank(self):
|
| 75 |
+
h=ready();self.assertTrue(h.read()['blank.ready']);h.invoke('method.configure',**dict(METHOD_EXAMPLE,bandwidth_m=.5e-9));self.assertFalse(h.read()['blank.ready'])
|
| 76 |
+
def test_path_or_solvent_invalidates_blank(self):
|
| 77 |
+
for changed in [dict(path_length_m=.002),dict(solvent_id='different')]:
|
| 78 |
+
h=ready(sample=changed);self.assertFalse(h.read()['blank.ready']);self.unchanged_reject(h,'acquisition.start',kind='sample')
|
| 79 |
+
def test_no_implicit_sample_fill_or_consumption(self):
|
| 80 |
+
h=ready();before=h._ledger();h.invoke('acquisition.start',kind='sample');h.step(5);after=h._ledger();self.assertEqual(before['solution_registered_m3'],after['solution_registered_m3']);self.assertEqual(after['solution_residual_m3'],0.)
|
| 81 |
+
def test_n2_source_and_tagged_gas_conserved(self):
|
| 82 |
+
h=ready();h.step(10);h.invoke('lid.set',opened=True);h.step(11);r=h._ledger();self.assertAlmostEqual(r['nitrogen_source_residual_mol'],0.,places=12);self.assertAlmostEqual(r['purge_label_residual_mol'],0.,places=12);self.assertGreater(r['purge_label_exhaust_mol'],0.)
|
| 83 |
+
def test_source_exhaustion_exact_partial(self):
|
| 84 |
+
h=ready(kind='blank',plant={'initial_n2_mol':.010});h.invoke('acquisition.start',kind='blank');h.step(10);self.assertEqual(h.phase,'failed');self.assertEqual(h.n2,0.);self.assertFalse(h.lamp);self.assertFalse(h.shutter);self.assertLess(len(h.points),41);self.assertGreater(len(h.points),0)
|
| 85 |
+
def test_cancel_retains_completed_points_and_resource_use(self):
|
| 86 |
+
h=ready();h.invoke('acquisition.start',kind='sample');h.step(.6);n=len(h.points);used=h.throughput;h.invoke('acquisition.stop');h.step(1);self.assertEqual(h.phase,'cancelled');self.assertEqual(len(h.points),n);self.assertGreater(h.throughput,used)
|
| 87 |
+
def test_open_lid_interrupts_and_recontaminates(self):
|
| 88 |
+
h=ready();h.invoke('acquisition.start',kind='sample');h.step(.2);h.invoke('lid.set',opened=True);self.assertEqual(h.phase,'cancelled');self.assertEqual(h.air,1.);self.assertFalse(h.shutter)
|
| 89 |
+
def test_poweroff_interrupt_and_blank_loss(self):
|
| 90 |
+
h=ready();h.invoke('acquisition.start',kind='sample');h.step(.2);h.invoke('power.set',enabled=False);self.assertEqual(h.phase,'cancelled');self.assertFalse(h.lamp);self.assertIsNone(h.blank)
|
| 91 |
+
def test_lamp_off_shutter_close_purge_reduction_interrupt(self):
|
| 92 |
+
for cap,args in [('lamp.set',dict(enabled=False)),('shutter.set',dict(opened=False)),('purge.set',dict(flow_std_m3_s=0.))]:
|
| 93 |
+
h=ready();h.invoke('acquisition.start',kind='sample');h.step(.2);h.invoke(cap,**args);self.assertIn(h.phase,['cancelled','failed']);self.assertFalse(h.shutter)
|
| 94 |
+
def test_busy_rejected_no_mutation(self):
|
| 95 |
+
h=ready();h.invoke('acquisition.start',kind='sample');self.unchanged_reject(h,'method.configure',**METHOD_EXAMPLE);self.unchanged_reject(h,'acquisition.start',kind='sample')
|
| 96 |
+
def test_step_timing_and_accumulations(self):
|
| 97 |
+
h=ready(kind='blank',method={'accumulations':2});h.invoke('acquisition.start',kind='blank');h.step(4.919);self.assertEqual(h.phase,'running');h.step(.0011);self.assertEqual(h.phase,'succeeded');self.assertEqual(len(h.points),82);self.assertAlmostEqual(h.elapsed_s,82*.06)
|
| 98 |
+
def test_continuous_timing_and_filter(self):
|
| 99 |
+
h=ready(kind='blank',method={'scan_mode':'continuous','speed_m_s':10000e-9/60});h.invoke('acquisition.start',kind='blank');h.step(1);self.assertAlmostEqual(h.elapsed_s,.05+40e-9/(10000e-9/60));self.assertLess(h.points[0]['raw_ellipticity_rad'],h.points[-1]['raw_ellipticity_rad'])
|
| 100 |
+
def test_auto_dit_not_step_alias(self):
|
| 101 |
+
a=ready(kind='blank');b=ready(kind='blank',method={'scan_mode':'auto_dit'})
|
| 102 |
+
for h in [a,b]:h.invoke('acquisition.start',kind='blank');h.step(10)
|
| 103 |
+
self.assertGreater(b.elapsed_s,a.elapsed_s);self.assertGreater(b.points[0]['integration_s'],.05)
|
| 104 |
+
def test_partition_invariance_event_clock(self):
|
| 105 |
+
a=ready(kind='blank',plant={'noise_multiplier':1.});b=copy.deepcopy(a)
|
| 106 |
+
for h in [a,b]:h.invoke('acquisition.start',kind='blank')
|
| 107 |
+
a.step(3)
|
| 108 |
+
for _ in range(150):b.step(.02)
|
| 109 |
+
self.assertEqual(a.phase,b.phase);self.assertEqual(len(a.points),len(b.points));self.assertAlmostEqual(a.n2,b.n2,places=12)
|
| 110 |
+
np.testing.assert_allclose([p['ellipticity_rad'] for p in a.points],[p['ellipticity_rad'] for p in b.points],atol=1e-15)
|
| 111 |
+
def test_cd_and_uv_independent(self):
|
| 112 |
+
a=ready();b=ready(sample={'mean_epsilon_m2_mol':[1200.]*66})
|
| 113 |
+
for h in [a,b]:h.invoke('acquisition.start',kind='sample');h.step(3)
|
| 114 |
+
self.assertAlmostEqual(a.points[-1]['ellipticity_rad'],b.points[-1]['ellipticity_rad'],places=9);self.assertAlmostEqual(b.points[-1]['absorbance']-a.points[-1]['absorbance'],.12,places=8)
|
| 115 |
+
def test_beer_lambert_two_channel_oracle(self):
|
| 116 |
+
h=ready();w=220e-9;s=h._sample();h.templates[s['template_id']]['delta_epsilon_m2_mol']=[.5]*66;theta,a=h._spectral(w);delta=(.5*.2+.05)*.001;mean=(600*.2+50)*.001
|
| 117 |
+
self.assertAlmostEqual(theta,math.atan(math.tanh(CD_FACTOR*delta)),places=13)
|
| 118 |
+
expected=-math.log10((10**(-mean-delta/2)+10**(-mean+delta/2))/2);self.assertAlmostEqual(a,expected,places=13)
|
| 119 |
+
def test_bandwidth_changes_fine_structure(self):
|
| 120 |
+
a=ready();b=ready(method={'bandwidth_m':4e-9})
|
| 121 |
+
for h in [a,b]:h.invoke('acquisition.start',kind='sample');h.step(3)
|
| 122 |
+
self.assertGreater(max(abs(x['ellipticity_rad']-y['ellipticity_rad']) for x,y in zip(a.points,b.points)),1e-8)
|
| 123 |
+
def test_concentration_and_path_scaling(self):
|
| 124 |
+
a=ready();b=ready(sample={'residue_concentration_mol_m3':.4})
|
| 125 |
+
for h in [a,b]:h.invoke('acquisition.start',kind='sample');h.step(3)
|
| 126 |
+
self.assertAlmostEqual(b.points[-1]['ellipticity_rad']/a.points[-1]['ellipticity_rad'],2.,places=4)
|
| 127 |
+
def test_saturation_fails_no_clipping_valid_points(self):
|
| 128 |
+
h=ready(sample={'mean_epsilon_m2_mol':[50000.]*66});h.invoke('acquisition.start',kind='sample');h.step(1);self.assertEqual(h.phase,'failed');self.assertEqual(h.warning,'DETECTOR_SATURATED');self.assertEqual(len(h.points),0)
|
| 129 |
+
def test_noise_reproducible_read_does_not_advance_rng(self):
|
| 130 |
+
a=ready(kind='blank',plant={'noise_multiplier':1.});b=copy.deepcopy(a)
|
| 131 |
+
a.read();a.describe()
|
| 132 |
+
for h in [a,b]:h.invoke('acquisition.start',kind='blank');h.step(4)
|
| 133 |
+
self.assertEqual(a.points,b.points)
|
| 134 |
+
def test_two_instances_isolated(self):
|
| 135 |
+
a=ready();b=ready();before=b.debug_snapshot();a.invoke('acquisition.start',kind='sample');a.step(1);self.assertEqual(before,b.debug_snapshot())
|
| 136 |
+
def test_agent_truth_and_host_config_denied(self):
|
| 137 |
+
h=ready();s=h.session();self.assertNotIn('truth.ledger',s.describe(instance_id=h.instance_id)['state_slots'])
|
| 138 |
+
with self.assertRaises(ActionRejected):s.read(instance_id=h.instance_id,state_ids=['truth.ledger'])
|
| 139 |
+
r=s.invoke(instance_id=h.instance_id,capability_id='product.read',arguments={},request_id='secret');self.assertEqual(r['error']['code'],'ACCESS_DENIED')
|
| 140 |
+
self.assertNotIn('active_template_id',json.dumps(s.read(instance_id=h.instance_id)))
|
| 141 |
+
def test_missing_observations_null_unavailable(self):
|
| 142 |
+
h=ready();v=h.session().read(instance_id=h.instance_id,state_ids=['scan.wavelength_m'])['observations']['scan.wavelength_m']
|
| 143 |
+
# Previous completed blank points remain a valid observation until the next start, so use a fresh host.
|
| 144 |
+
h=JascoJ1500Runtime();v=h.session().read(instance_id=h.instance_id,state_ids=['scan.wavelength_m'])['observations']['scan.wavelength_m'];self.assertIsNone(v['value']);self.assertEqual(v['quality'],'unavailable')
|
| 145 |
+
def test_request_dedup_conflict_and_owner(self):
|
| 146 |
+
h=ready();s=h.session();args=dict(instance_id=h.instance_id,capability_id='acquisition.start',arguments={'kind':'sample'},request_id='one')
|
| 147 |
+
r=s.invoke(**args);h.step(.1);self.assertEqual(s.invoke(**args),r)
|
| 148 |
+
bad=s.invoke(**dict(args,arguments={'kind':'blank'}));self.assertEqual(bad['error']['code'],'REQUEST_CONFLICT')
|
| 149 |
+
h.register_principal('other');other=h.session('other')
|
| 150 |
+
with self.assertRaises(ActionRejected):other.poll(r['operation_id'])
|
| 151 |
+
s.cancel(r['operation_id'],'cancel');self.assertEqual(s.poll(r['operation_id'])['status'],'cancelled')
|
| 152 |
+
def test_wrong_instance_and_principal(self):
|
| 153 |
+
h=ready()
|
| 154 |
+
with self.assertRaises(ActionRejected):h.session('self_declared_evaluator')
|
| 155 |
+
r=h.session().invoke(instance_id='wrong',capability_id='power.set',arguments={'enabled':True},request_id='x');self.assertEqual(r['error']['code'],'UNKNOWN_INSTANCE')
|
| 156 |
+
def test_write_routes_and_unwritable_denied(self):
|
| 157 |
+
h=ready();s=h.session();s.write(instance_id=h.instance_id,state_id='lid.opened',value=True,request_id='x');self.assertTrue(h.opened)
|
| 158 |
+
with self.assertRaises(ActionRejected):s.write(instance_id=h.instance_id,state_id='sample.temperature_k',value=320.,request_id='x')
|
| 159 |
+
def test_unsupported_reported_not_success(self):
|
| 160 |
+
h=ready();r=h.session().invoke(instance_id=h.instance_id,capability_id='thermal.set_temperature',arguments={'temperature_k':320.},request_id='u');self.assertEqual(r['status'],'unsupported');self.assertEqual(r['error']['code'],'UNSUPPORTED')
|
| 161 |
+
def test_fit_pure_and_template_reconstruction(self):
|
| 162 |
+
h=ready();h.invoke('acquisition.start',kind='sample');h.step(3);before=h.debug_snapshot();r=h.invoke('structure.fit',residue_concentration_mol_m3=.2,path_length_m=.001);self.assertEqual(before,h.debug_snapshot());self.assertTrue(r['converged']);self.assertAlmostEqual(sum(r['fractions'].values()),1.);self.assertLess(r['rms_delta_epsilon_m2_mol'],1e-4);self.assertAlmostEqual(r['fractions']['Helix'],.72,places=3)
|
| 163 |
+
def test_fit_rejects_partial_and_narrow_spectrum(self):
|
| 164 |
+
h=ready();self.unchanged_reject(h,'structure.fit',residue_concentration_mol_m3=.2,path_length_m=.001)
|
| 165 |
+
h=ready(method={'start_m':220e-9,'stop_m':210e-9});h.invoke('acquisition.start',kind='sample');h.step(3);self.unchanged_reject(h,'structure.fit',residue_concentration_mol_m3=.2,path_length_m=.001)
|
| 166 |
+
def test_step_invalid_bool_and_negative(self):
|
| 167 |
+
h=ready()
|
| 168 |
+
for dt in [True,-1,float('nan')]:
|
| 169 |
+
before=h.debug_snapshot()
|
| 170 |
+
with self.assertRaises(ActionRejected):h.step(dt)
|
| 171 |
+
self.assertEqual(before,h.debug_snapshot())
|
| 172 |
+
def test_external_inputs_defensively_copied(self):
|
| 173 |
+
h=ready();a=copy.deepcopy(SAMPLE_EXAMPLE);a['sample_id']='new';h.invoke('solution.register',**a);a['mean_epsilon_m2_mol'][0]=999.;self.assertEqual(h.samples['new']['mean_epsilon_m2_mol'][0],600.)
|
| 174 |
+
def test_same_solvent_id_cannot_have_conflicting_definition(self):
|
| 175 |
+
h=ready();self.unchanged_reject(h,'solution.register',**dict(SAMPLE_EXAMPLE,sample_id='bad_buffer',solvent_alpha_m_inv=[100.]*66))
|
| 176 |
+
if __name__=='__main__':unittest.main()
|
| 177 |
+
|
tests/test_asset_jasco_nrs5500.py
ADDED
|
@@ -0,0 +1,210 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Independent numerical and protocol tests for NRS5500, not factory validation."""
|
| 2 |
+
import copy,hashlib,json,math,sys,unittest
|
| 3 |
+
from pathlib import Path
|
| 4 |
+
import numpy as np
|
| 5 |
+
ROOT=Path(__file__).resolve().parents[1];sys.path.insert(0,str(ROOT/'scripts'))
|
| 6 |
+
from asset_runtime.jasco_nrs5500 import *
|
| 7 |
+
def configured(plant=None,method=None,sample=None):
|
| 8 |
+
r=JascoNrs5500Runtime();r.invoke('plant.configure',**copy.deepcopy(plant or PLANT_EXAMPLE));r.invoke('sample.register',**copy.deepcopy(sample or SAMPLE_EXAMPLE));r.invoke('sample.load',sample_id=(sample or SAMPLE_EXAMPLE)['sample_id']);r.invoke('method.configure',**copy.deepcopy(method or METHOD_EXAMPLE));r.invoke('power.set',enabled=True);r.invoke('door.set',opened=False);r.invoke('laser.set',enabled=True);return r
|
| 9 |
+
def measured(**kw):
|
| 10 |
+
r=configured(**kw);r.invoke('acquisition.start');r.step(2);return r
|
| 11 |
+
class TestRaman(unittest.TestCase):
|
| 12 |
+
def reject(self,r,cap,args,code=None):
|
| 13 |
+
before=r.debug_snapshot()
|
| 14 |
+
with self.assertRaises(ActionRejected) as c:r.invoke(cap,**args)
|
| 15 |
+
if code:self.assertEqual(str(c.exception),code)
|
| 16 |
+
self.assertEqual(before,r.debug_snapshot())
|
| 17 |
+
def test_71_real_unique_phases_and_formulae(self):
|
| 18 |
+
ts=JascoNrs5500Runtime().templates;self.assertEqual(len(ts),71);self.assertEqual(len({t['formula_original'] for t in ts.values()}),71)
|
| 19 |
+
for t in ts.values():
|
| 20 |
+
self.assertEqual(t['excitation_wavelength_m'],532e-9);self.assertEqual(t['source']['headers_processed']['NAMES'],t['name']);self.assertEqual(t['evidence'],'measured_reference_spectrum')
|
| 21 |
+
for kind in ['raw','processed']:
|
| 22 |
+
self.assertEqual(hashlib.sha256((ROOT/t['source'][kind+'_file']).read_bytes()).hexdigest(),t['source'][kind+'_sha256'])
|
| 23 |
+
def test_all71_complete_and_independent_interp(self):
|
| 24 |
+
for sid,t in JascoNrs5500Runtime().templates.items():
|
| 25 |
+
with self.subTest(id=sid):
|
| 26 |
+
sample=copy.deepcopy(SAMPLE_EXAMPLE);sample['regions'][0]['template_id']=sid
|
| 27 |
+
r=measured(sample=sample);x=np.arange(25000,120001,100);shape=np.maximum(t['source_processed_intensity'],0);shape=shape/max(shape);expected=np.interp(x,t['raman_shift_m_inv'],shape)*10000
|
| 28 |
+
self.assertEqual(r.phase,'succeeded');np.testing.assert_allclose(r.points[0]['count_rate_s_inv'],expected,atol=1e-10);self.assertEqual(len(r.points[0]['counts']),951)
|
| 29 |
+
def test_not_dispersion_as_linewidth(self):
|
| 30 |
+
r=measured();t=r.templates['rruff_r040031'];x=np.array(r.points[0]['raman_shift_m_inv']);e=np.interp(x,t['raman_shift_m_inv'],t['normalized_shape'])*10000
|
| 31 |
+
np.testing.assert_allclose(r.points[0]['count_rate_s_inv'],e,atol=1e-10);self.assertEqual(r.plant['additional_fwhm_m_inv'],0.)
|
| 32 |
+
def test_power_scaling(self):
|
| 33 |
+
a=measured();b=measured(method=dict(METHOD_EXAMPLE,power_w=.005))
|
| 34 |
+
np.testing.assert_allclose(b.points[0]['counts'],np.array(a.points[0]['counts'])*.5)
|
| 35 |
+
def test_exposure_counts_not_rate_scaling(self):
|
| 36 |
+
a=measured();b=measured(method=dict(METHOD_EXAMPLE,integration_s=.04))
|
| 37 |
+
np.testing.assert_allclose(b.points[0]['counts'],np.array(a.points[0]['counts'])*2);np.testing.assert_allclose(a.points[0]['count_rate_s_inv'],b.points[0]['count_rate_s_inv'])
|
| 38 |
+
def test_defocus_gaussian_oracle(self):
|
| 39 |
+
a=measured();r=configured();r.invoke('door.set',opened=True);r.invoke('stage.manual_position',position_m=[0.,0.,3e-6]);r.invoke('door.set',opened=False);r.invoke('laser.set',enabled=True);r.invoke('acquisition.start');r.step(1)
|
| 40 |
+
np.testing.assert_allclose(r.points[0]['count_rate_s_inv'],np.array(a.points[0]['count_rate_s_inv'])*math.exp(-.5),rtol=1e-12)
|
| 41 |
+
def test_two_phase_center_half_weights(self):
|
| 42 |
+
r=configured(plant=AUTO_PLANT,sample=MAP_SAMPLE);r.invoke('mapping.start',**MAPPING_EXAMPLE);r.step(1)
|
| 43 |
+
np.testing.assert_allclose(r.points[1]['count_rate_s_inv'],(np.array(r.points[0]['count_rate_s_inv'])+r.points[2]['count_rate_s_inv'])/2,atol=1e-10)
|
| 44 |
+
self.assertAlmostEqual(r.elapsed_s,.12,places=12)
|
| 45 |
+
def test_stage_sign_sample_coordinates(self):
|
| 46 |
+
r=configured(plant=AUTO_PLANT,sample=MAP_SAMPLE);r.invoke('mapping.start',**MAPPING_EXAMPLE);r.step(1)
|
| 47 |
+
x=np.array(r.points[0]['raman_shift_m_inv']);calc=r.templates['rruff_r040070'];expected=np.interp(x,calc['raman_shift_m_inv'],calc['normalized_shape'])*10000
|
| 48 |
+
np.testing.assert_allclose(r.points[0]['count_rate_s_inv'],expected,atol=1e-9)
|
| 49 |
+
def test_standard_manual_no_autostage(self):
|
| 50 |
+
r=configured();self.reject(r,'stage.move',{'position_m':[0.,0.,0.]},'AUTOSTAGE_NOT_INSTALLED');self.reject(r,'mapping.start',MAPPING_EXAMPLE,'AUTOSTAGE_NOT_INSTALLED')
|
| 51 |
+
def test_manual_external_only_open(self):
|
| 52 |
+
r=configured();self.reject(r,'stage.manual_position',{'position_m':[0.,0.,0.]},'SAMPLE_ACCESS_REQUIRED');r.invoke('door.set',opened=True);r.invoke('stage.manual_position',position_m=[.0375,.025,.015]);self.assertEqual(r.position.tolist(),[.0375,.025,.015])
|
| 53 |
+
self.reject(r,'stage.manual_position',{'position_m':[.038,0.,0.]},'STAGE_RANGE')
|
| 54 |
+
def test_optional_range_boundaries(self):
|
| 55 |
+
r=configured(plant=AUTO_PLANT);r.invoke('stage.move',position_m=[.05,.035,.015]);r.step(50);self.assertEqual(r.position.tolist(),[.05,.035,.015]);self.assertEqual(r.phase,'succeeded')
|
| 56 |
+
self.reject(r,'stage.move',{'position_m':[0.,.036,0.]},'STAGE_RANGE')
|
| 57 |
+
def test_move_is_finite_and_shutter_off(self):
|
| 58 |
+
r=configured(plant=AUTO_PLANT);r.invoke('stage.move',position_m=[.001,0.,0.]);r.step(.25);self.assertAlmostEqual(r.position[0],.00025);self.assertFalse(r.read()['laser.emitting']);self.assertEqual(r._incident_energy_j,0.)
|
| 59 |
+
def test_scan_waits_for_position(self):
|
| 60 |
+
r=configured(plant=AUTO_PLANT);r.invoke('mapping.start',positions_m=[[.001,0.,0.]]);r.step(.5);self.assertEqual(r.windows,[]);self.assertEqual(r._laser_on_s,0.);r.step(.5);self.assertEqual(r.windows,[]);r.step(.02);self.assertEqual(len(r.points),1)
|
| 61 |
+
def test_1024pixel_sequential_windows(self):
|
| 62 |
+
r=configured(method=dict(METHOD_EXAMPLE,start_m_inv=20000.,stop_m_inv=125000.));r.invoke('acquisition.start');r.step(.02);self.assertEqual(len(r.windows),1);self.assertEqual(len(r.windows[0]['counts']),1024);self.assertEqual(r.points,[]);r.step(.02)
|
| 63 |
+
self.assertEqual(len(r.windows[1]['counts']),27);self.assertEqual(len(r.points[0]['counts']),1051);self.assertEqual(r.points[0]['exposures'],2);self.assertAlmostEqual(r.points[0]['sample_time_s'],.04)
|
| 64 |
+
def test_cancel_keeps_full_windows_not_partial(self):
|
| 65 |
+
r=configured(method=dict(METHOD_EXAMPLE,start_m_inv=20000.,stop_m_inv=125000.));r.invoke('acquisition.start');r.step(.03);r.invoke('acquisition.stop');self.assertEqual(len(r.windows),1);self.assertEqual(r.points,[]);self.assertAlmostEqual(r._incident_energy_j,.0003);r.step(1);self.assertAlmostEqual(r._incident_energy_j,.0003)
|
| 66 |
+
def test_door_interrupt(self):
|
| 67 |
+
r=configured();r.invoke('acquisition.start');r.step(.01);r.invoke('door.set',opened=True);self.assertEqual(r.phase,'cancelled');self.assertFalse(r.laser);self.assertFalse(r.read()['laser.emitting']);self.assertEqual(r.points,[])
|
| 68 |
+
def test_power_interrupt(self):
|
| 69 |
+
r=configured();r.invoke('acquisition.start');r.step(.01);r.invoke('power.set',enabled=False);self.assertEqual(r.phase,'cancelled');self.assertFalse(r.laser)
|
| 70 |
+
def test_laser_permission_is_not_idle_emission(self):
|
| 71 |
+
r=configured();self.assertTrue(r.laser);self.assertFalse(r.read()['laser.emitting']);r.step(3);self.assertEqual(r._incident_energy_j,0.)
|
| 72 |
+
def test_mass_and_incident_energy(self):
|
| 73 |
+
r=measured();v=r.invoke('product.read');self.assertAlmostEqual(v['incident_energy_j'],.01*.02);self.assertEqual(v['mass_residual_kg'],0.);r.invoke('door.set',opened=True);r.invoke('sample.unload',recipient_id='rack');v=r.invoke('product.read');self.assertEqual(v['attached_mass_kg'],0.);self.assertEqual(v['external_mass_kg'],.001)
|
| 74 |
+
def test_source_coverage_not_full_factory_range(self):
|
| 75 |
+
r=configured(method=dict(METHOD_EXAMPLE,start_m_inv=5000.,stop_m_inv=800000.));self.reject(r,'acquisition.start',{},'SOURCE_COVERAGE')
|
| 76 |
+
def test_all_mapping_positions_validated_before_start(self):
|
| 77 |
+
r=configured(plant=AUTO_PLANT);self.reject(r,'mapping.start',{'positions_m':[[0.,0.,0.],[0.,.04,0.]]},'STAGE_RANGE')
|
| 78 |
+
def test_reject_other_laser_power_grating(self):
|
| 79 |
+
r=configured()
|
| 80 |
+
for patch in [dict(laser_wavelength_m=785e-9),dict(power_w=.051),dict(grating_lines_m_inv=2400000)]:self.reject(r,'method.configure',dict(METHOD_EXAMPLE,**patch),'INVALID_ARGUMENT')
|
| 81 |
+
def test_invalid_pixel_interval(self):
|
| 82 |
+
r=configured();self.reject(r,'method.configure',dict(METHOD_EXAMPLE,stop_m_inv=120050.),'PIXEL_GRID')
|
| 83 |
+
def test_reject_regions_overlap_and_degenerate(self):
|
| 84 |
+
r=configured();s=copy.deepcopy(MAP_SAMPLE);s['regions'][1]['x_min_m']=-.001;self.reject(r,'sample.register',s,'OVERLAPPING_REGIONS')
|
| 85 |
+
s=copy.deepcopy(MAP_SAMPLE);s['regions'][0]['x_max_m']=s['regions'][0]['x_min_m'];self.reject(r,'sample.register',s,'INVALID_REGION')
|
| 86 |
+
def test_immutable_public_data(self):
|
| 87 |
+
r=measured();x=r.invoke('template.read',substance_id='rruff_r040031');x['normalized_shape'][0]=123;self.assertNotEqual(r.templates['rruff_r040031']['normalized_shape'][0],123)
|
| 88 |
+
y=r.invoke('result.read');y['spectra'][0]['counts'][0]=123;self.assertNotEqual(r.points[0]['counts'][0],123)
|
| 89 |
+
def test_peaks_only_caller_observations(self):
|
| 90 |
+
r=configured();a=CAPS['spectrum.peaks'][6];v=r.invoke('spectrum.peaks',**a);self.assertEqual(v['peak_shift_m_inv'],[40100.]);self.assertEqual(v['peak_rate_s_inv'],[2.])
|
| 91 |
+
self.reject(r,'spectrum.peaks',dict(a,raman_shift_m_inv=[40000.,40000.,40200.]),'ANALYSIS_INPUT')
|
| 92 |
+
def test_band_edge_interpolation_independent(self):
|
| 93 |
+
r=configured();a=copy.deepcopy(CAPS['map.band'][6]);a.update(low_m_inv=40050.,high_m_inv=40150.);v=r.invoke('map.band',**a);self.assertEqual(v['band_integrals_s_inv_m_inv'],[150.])
|
| 94 |
+
def test_band_map_discriminates_not_concentration(self):
|
| 95 |
+
r=configured(plant=AUTO_PLANT,sample=MAP_SAMPLE);r.invoke('mapping.start',**MAPPING_EXAMPLE);r.step(1);v=r.invoke('map.band',spectra=r.points,low_m_inv=45800.,high_m_inv=47000.);a=v['band_integrals_s_inv_m_inv'];self.assertGreater(a[2],a[0]*5);self.assertAlmostEqual(a[1],(a[0]+a[2])/2,places=7)
|
| 96 |
+
def test_axis_calibration_uses_caller_and_additive(self):
|
| 97 |
+
r=measured(plant=dict(PLANT_EXAMPLE,axis_bias_m_inv=200.));self.assertEqual(r.points[0]['raman_shift_m_inv'][0],25200.)
|
| 98 |
+
r.invoke('calibration.axis',observed_peak_m_inv=46600.,certified_peak_m_inv=46400.,accept_external_reference=True);r.invoke('acquisition.start');r.step(1);self.assertEqual(r.points[0]['raman_shift_m_inv'][0],25000.)
|
| 99 |
+
r.invoke('calibration.axis',observed_peak_m_inv=46400.,certified_peak_m_inv=46400.,accept_external_reference=True);self.assertEqual(r.axis_correction,-200.)
|
| 100 |
+
def test_step_partition_independent(self):
|
| 101 |
+
a=configured(plant=AUTO_PLANT,sample=MAP_SAMPLE);b=configured(plant=AUTO_PLANT,sample=MAP_SAMPLE)
|
| 102 |
+
for r in [a,b]:r.invoke('mapping.start',**MAPPING_EXAMPLE)
|
| 103 |
+
a.step(1)
|
| 104 |
+
for _ in range(100):b.step(.01)
|
| 105 |
+
for x,y in zip(a.points,b.points):
|
| 106 |
+
np.testing.assert_allclose(x['counts'],y['counts'],atol=1e-9);self.assertAlmostEqual(x['sample_time_s'],y['sample_time_s'],places=12)
|
| 107 |
+
self.assertAlmostEqual(a._incident_energy_j,b._incident_energy_j)
|
| 108 |
+
def test_seed_noise_reproducible(self):
|
| 109 |
+
p=dict(PLANT_EXAMPLE,shot_noise=True,read_noise_counts=2.,dark_rate_s_inv=3.);a=measured(plant=p);b=measured(plant=p);np.testing.assert_array_equal(a.points[0]['counts'],b.points[0]['counts']);c=measured(plant=dict(p,seed=74));self.assertFalse(np.array_equal(a.points[0]['counts'],c.points[0]['counts']))
|
| 110 |
+
def test_noise_statistics(self):
|
| 111 |
+
values=[]
|
| 112 |
+
for seed in range(120):
|
| 113 |
+
r=measured(plant=dict(PLANT_EXAMPLE,seed=seed,shot_noise=True));values.append(r.points[0]['counts'][214])
|
| 114 |
+
r=measured();mu=r.points[0]['counts'][214];self.assertLess(abs(np.mean(values)-mu),5*math.sqrt(mu/120));self.assertLess(abs(np.var(values)-mu),.6*mu)
|
| 115 |
+
def test_added_broadening_lowers_peak(self):
|
| 116 |
+
a=measured();b=measured(plant=dict(PLANT_EXAMPLE,additional_fwhm_m_inv=1000.));self.assertLess(max(b.points[0]['counts']),max(a.points[0]['counts']))
|
| 117 |
+
def test_boolean_nan_extra_atomic(self):
|
| 118 |
+
r=configured()
|
| 119 |
+
for val in [True,float('nan'),float('inf')]:self.reject(r,'method.configure',dict(METHOD_EXAMPLE,power_w=val),'INVALID_ARGUMENT')
|
| 120 |
+
self.reject(r,'laser.set',dict(enabled=True,private=True),'INVALID_ARGUMENT')
|
| 121 |
+
def test_step_invalid_atomic(self):
|
| 122 |
+
r=configured()
|
| 123 |
+
for dt in [-1,True,float('nan')]:
|
| 124 |
+
before=r.debug_snapshot()
|
| 125 |
+
with self.assertRaises(ActionRejected):r.step(dt)
|
| 126 |
+
self.assertEqual(before,r.debug_snapshot())
|
| 127 |
+
def test_read_only_no_clock_revision_rng_change(self):
|
| 128 |
+
r=measured();before=r.debug_snapshot()
|
| 129 |
+
for _ in range(2):r.read();r.invoke('process.measure');r.invoke('result.read');r.invoke('spectrum.peaks',**CAPS['spectrum.peaks'][6])
|
| 130 |
+
self.assertEqual(before,r.debug_snapshot())
|
| 131 |
+
def test_busy_and_failed_action_rollback(self):
|
| 132 |
+
r=configured();r.invoke('acquisition.start');self.reject(r,'method.configure',METHOD_EXAMPLE,'BUSY')
|
| 133 |
+
r.invoke('acquisition.stop');self.reject(r,'calibration.axis',dict(observed_peak_m_inv=100000.,certified_peak_m_inv=102100.,accept_external_reference=True),'CALIBRATION_RANGE')
|
| 134 |
+
def test_initialization_after_world_tick_allowed(self):
|
| 135 |
+
r=JascoNrs5500Runtime();r.step(.5);r.invoke('plant.configure',**PLANT_EXAMPLE);self.reject(r,'plant.configure',PLANT_EXAMPLE,'INITIALIZATION_ONLY')
|
| 136 |
+
def test_unimplemented_rejected(self):
|
| 137 |
+
r=configured()
|
| 138 |
+
for k in UNSUPPORTED:self.reject(r,k,{},'UNSUPPORTED')
|
| 139 |
+
def test_session_privacy_and_role_not_self_claimed(self):
|
| 140 |
+
r=configured();s=r.session();d=s.describe(instance_id=r.instance_id);self.assertNotIn('truth.ledger',d['state_slots']);self.assertNotIn('plant.configure',d['capabilities'])
|
| 141 |
+
for cap,args in [('product.read',{}),('sample.register',MAP_SAMPLE),('stage.manual_position',{'position_m':[0.,0.,0.]})]:
|
| 142 |
+
v=s.invoke(instance_id=r.instance_id,capability_id=cap,arguments=args,request_id=cap);self.assertEqual(v['error']['code'],'ACCESS_DENIED')
|
| 143 |
+
self.assertNotIn('rruff_r040031',json.dumps(r.invoke('result.read')));self.assertNotIn('active_sample_id',json.dumps(s.read(instance_id=r.instance_id)))
|
| 144 |
+
def test_request_dedup_conflict_and_instance_isolation(self):
|
| 145 |
+
r=configured();s=r.session();args=dict(instance_id=r.instance_id,capability_id='acquisition.start',arguments={},request_id='a');a=s.invoke(**args);b=s.invoke(**args);self.assertEqual(a,b);self.assertEqual(r._op_count,1)
|
| 146 |
+
c=s.invoke(**dict(args,capability_id='acquisition.stop'));self.assertEqual(c['error']['code'],'REQUEST_CONFLICT')
|
| 147 |
+
other=configured();other.step(.3);self.assertEqual(r.time_s,0.);self.assertNotEqual(other.instance_id+'_op_1',r.operation_id) if other.instance_id!=r.instance_id else self.assertEqual(other.phase,'idle')
|
| 148 |
+
def test_operation_owner_cancel_and_poll(self):
|
| 149 |
+
r=configured();r.register_principal('second');a=r.session();b=r.session('second');res=a.invoke(instance_id=r.instance_id,capability_id='acquisition.start',arguments={},request_id='start');op=res['operation_id']
|
| 150 |
+
with self.assertRaises(ActionRejected):b.poll(op)
|
| 151 |
+
r.step(.01);v=a.cancel(op,'cancel');self.assertEqual(v['result']['phase'],'cancelled')
|
| 152 |
+
def test_observation_time_not_world_time(self):
|
| 153 |
+
r=measured();s=r.session();v=s.read(instance_id=r.instance_id,state_ids=['scan.maximum_rate_s_inv'])['observations']['scan.maximum_rate_s_inv'];self.assertAlmostEqual(v['sample_time_s'],.02);np.testing.assert_allclose(v['sample_window_s'],[0.,.02]);self.assertEqual(r.time_s,2.)
|
| 154 |
+
def test_band_unrepresentable_output_rejects_without_effects(self):
|
| 155 |
+
r=configured();a=copy.deepcopy(CAPS['map.band'][6]);a['spectra'][0]['count_rate_s_inv']=[1e308]*3
|
| 156 |
+
self.reject(r,'map.band',a,'ANALYSIS_INPUT');before=r.debug_snapshot()
|
| 157 |
+
v=r.session().invoke(instance_id=r.instance_id,capability_id='map.band',arguments=a,request_id='overflow')
|
| 158 |
+
self.assertEqual(v['status'],'rejected');self.assertEqual(v['error']['code'],'ANALYSIS_INPUT');json.dumps(v,allow_nan=False);self.assertEqual(before,r.debug_snapshot())
|
| 159 |
+
def test_band_large_finite_integral_avoids_intermediate_overflow(self):
|
| 160 |
+
r=configured();a=copy.deepcopy(CAPS['map.band'][6]);a.update(low_m_inv=0.,high_m_inv=1.)
|
| 161 |
+
a['spectra'][0].update(raman_shift_m_inv=[0.,.5,1.],count_rate_s_inv=[1e308]*3)
|
| 162 |
+
v=r.invoke('map.band',**a);self.assertEqual(v['band_integrals_s_inv_m_inv'],[1e308]);json.dumps(v,allow_nan=False)
|
| 163 |
+
def test_old_spectra_keep_acquisition_method_after_reconfigure(self):
|
| 164 |
+
r=measured();old=r.invoke('result.read');replacement=dict(METHOD_EXAMPLE,integration_s=.04,power_w=.005)
|
| 165 |
+
r.invoke('method.configure',**replacement);retained=r.invoke('result.read')
|
| 166 |
+
self.assertEqual(retained,old);self.assertEqual(json.loads(retained['settings_json']),METHOD_EXAMPLE)
|
| 167 |
+
r.invoke('acquisition.start');self.assertEqual(r.invoke('result.read')['spectra'],[]);r.step(1)
|
| 168 |
+
fresh=r.invoke('result.read');self.assertEqual(json.loads(fresh['settings_json']),replacement);self.assertEqual(fresh['spectra'][0]['integration_s'],.04)
|
| 169 |
+
np.testing.assert_allclose(fresh['spectra'][0]['counts'],old['spectra'][0]['counts'])
|
| 170 |
+
def test_historical_operation_summary_owned_immutable_and_read_only(self):
|
| 171 |
+
r=configured();r.register_principal('second');s=r.session();other=r.session('second')
|
| 172 |
+
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)
|
| 173 |
+
s.invoke(instance_id=r.instance_id,capability_id='acquisition.start',arguments={},request_id='second');before=r.debug_snapshot()
|
| 174 |
+
self.assertEqual(s.poll(op),terminal);self.assertEqual(terminal['status'],'succeeded');self.assertEqual(terminal['result']['completed_points'],1)
|
| 175 |
+
terminal['result']['completed_points']=999;self.assertEqual(s.poll(op)['result']['completed_points'],1)
|
| 176 |
+
self.assertNotIn(SAMPLE_EXAMPLE['sample_id'],json.dumps(s.poll(op)));self.assertNotIn('rruff_r040031',json.dumps(s.poll(op)))
|
| 177 |
+
with self.assertRaisesRegex(ActionRejected,'ACCESS_DENIED'):other.poll(op)
|
| 178 |
+
self.assertEqual(before,r.debug_snapshot())
|
| 179 |
+
def test_cancel_completed_operation_preserves_new_running_operation(self):
|
| 180 |
+
r=configured();s=r.session();old=s.invoke(instance_id=r.instance_id,capability_id='acquisition.start',arguments={},request_id='old')['operation_id'];r.step(1)
|
| 181 |
+
current=s.invoke(instance_id=r.instance_id,capability_id='acquisition.start',arguments={},request_id='new')['operation_id'];r.step(.01);revision=r.revision;ledger=r.invoke('product.read')
|
| 182 |
+
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(r.invoke('product.read'),ledger)
|
| 183 |
+
self.assertEqual(s.cancel(old,'cancel-old'),v)
|
| 184 |
+
with self.assertRaisesRegex(ActionRejected,'REQUEST_CONFLICT'):s.cancel(current,'cancel-old')
|
| 185 |
+
self.assertEqual(r.phase,'running');r.step(.01);self.assertEqual(s.poll(current)['status'],'succeeded')
|
| 186 |
+
def test_partial_cancel_terminal_survives_later_move_without_phantom_exposure(self):
|
| 187 |
+
r=configured(plant=AUTO_PLANT,method=dict(METHOD_EXAMPLE,start_m_inv=20000.,stop_m_inv=125000.));s=r.session()
|
| 188 |
+
op=s.invoke(instance_id=r.instance_id,capability_id='acquisition.start',arguments={},request_id='wide')['operation_id'];r.step(.03);s.cancel(op,'cancel-wide');old=s.poll(op)
|
| 189 |
+
self.assertEqual(old['status'],'cancelled');self.assertEqual(old['result']['completed_windows'],1);self.assertEqual(old['result']['completed_points'],0);self.assertAlmostEqual(old['result']['elapsed_s'],.03)
|
| 190 |
+
energy=r.invoke('product.read')['incident_energy_j'];s.invoke(instance_id=r.instance_id,capability_id='stage.move',arguments={'position_m':[.001,0.,0.]},request_id='move');r.step(.5)
|
| 191 |
+
self.assertEqual(s.poll(op),old);self.assertEqual(r.invoke('product.read')['incident_energy_j'],energy);self.assertAlmostEqual(energy,.0003)
|
| 192 |
+
def test_move_metadata_matches_immediate_target_and_step_motion(self):
|
| 193 |
+
r=configured(plant=AUTO_PLANT);m=export_jasco_nrs5500_contract_metadata()['capabilities'];effects=m['stage.move']['state_effects']
|
| 194 |
+
immediate={v['state_id'] for v in effects if v['timing']=='immediate'};later={v['state_id'] for v in effects if v['timing']=='on_step'}
|
| 195 |
+
before=r.read('evaluator');r.invoke('stage.move',position_m=[.001,0.,0.]);after=r.read('evaluator')
|
| 196 |
+
self.assertLessEqual({k for k in before if before[k]!=after[k]},immediate);self.assertNotIn('stage.x_m',immediate);self.assertNotIn('truth.ledger',{v['state_id'] for v in effects})
|
| 197 |
+
r.step(.25);moved=r.read('evaluator');self.assertLessEqual({k for k in after if after[k]!=moved[k]},later);self.assertAlmostEqual(moved['stage.x_m'],.00025)
|
| 198 |
+
self.assertEqual(m['spectrum.peaks']['observes'],[]);self.assertEqual(m['map.band']['observes'],[]);self.assertEqual(m['method.configure']['observes'],['method.configured'])
|
| 199 |
+
def test_contract_numeric_units_and_examples(self):
|
| 200 |
+
m=export_jasco_nrs5500_contract_metadata();self.assertEqual(len(m['capabilities']),23)
|
| 201 |
+
def visit(v):
|
| 202 |
+
if isinstance(v,dict):
|
| 203 |
+
if v.get('type') in ['number','integer']:self.assertIn('x-unit',v)
|
| 204 |
+
for x in v.values():visit(x)
|
| 205 |
+
elif isinstance(v,list):
|
| 206 |
+
for x in v:visit(x)
|
| 207 |
+
visit(m)
|
| 208 |
+
for k,v in CAPS.items():validate(v[0],v[6])
|
| 209 |
+
if __name__=='__main__':unittest.main()
|
| 210 |
+
|
tests/test_asset_jasco_p4200.py
ADDED
|
@@ -0,0 +1,213 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Independent polarimetry, real-reference identity, calibration, conservation and protocol regression."""
|
| 2 |
+
import copy,json,math,sys,unittest
|
| 3 |
+
from pathlib import Path
|
| 4 |
+
import numpy as np
|
| 5 |
+
ROOT=Path(__file__).resolve().parents[1];sys.path.insert(0,str(ROOT/'scripts'))
|
| 6 |
+
from asset_runtime.jasco_p4200 import *
|
| 7 |
+
def swap(r,s):
|
| 8 |
+
r.invoke('lid.set',opened=True)
|
| 9 |
+
if r.active:r.invoke('sample.unload',recipient_id='rack')
|
| 10 |
+
r.invoke('sample.register',**s);r.invoke('sample.load',sample_id=s['sample_id']);r.invoke('lid.set',opened=False);r.invoke('lamp.set',enabled=True)
|
| 11 |
+
def run(r,kind):
|
| 12 |
+
r.invoke('acquisition.start',kind=kind);r.step(40+r.method['integration_s']*r.method['repeats']);return r
|
| 13 |
+
def configured(plant=None,method=None,sample=None,blank=True,quartz=True):
|
| 14 |
+
r=JascoP4200Runtime();p=copy.deepcopy(plant or PLANT_EXAMPLE);m=copy.deepcopy(method or METHOD_EXAMPLE);s=copy.deepcopy(sample or SAMPLE_EXAMPLE)
|
| 15 |
+
r.invoke('plant.configure',**p);r.invoke('method.configure',**m);r.invoke('power.set',enabled=True)
|
| 16 |
+
if blank:
|
| 17 |
+
b=dict(s,sample_id='blank_01',kind='blank',template_id='',concentration_kg_m3=0.,quartz_angle_rad=None)
|
| 18 |
+
swap(r,b);run(r,'blank')
|
| 19 |
+
if quartz:
|
| 20 |
+
q=dict(QUARTZ_EXAMPLE,reference_temperature_k=s['reference_temperature_k'])
|
| 21 |
+
swap(r,q);run(r,'quartz');r.invoke('calibration.quartz',certified_angle_rad=math.radians(10),accept_simulated_standard=True)
|
| 22 |
+
swap(r,s);return r
|
| 23 |
+
def measured(**kw):return run(configured(**kw),'sample')
|
| 24 |
+
class TestPolarimetry(unittest.TestCase):
|
| 25 |
+
def test_real_67_unique_stereochemical_parameters(self):
|
| 26 |
+
ts=JascoP4200Runtime().templates;self.assertEqual(len(ts),67);self.assertEqual(len({t['identity']['InChIKey'] for t in ts.values()}),67)
|
| 27 |
+
for t in ts.values():
|
| 28 |
+
self.assertTrue(t['stereocenters']);self.assertTrue(all(x[1]!='?' for x in t['stereocenters']));self.assertNotIn('\ufffd',json.dumps(t,ensure_ascii=False));self.assertAlmostEqual(t['specific_rotation_rad_m2_kg'],t['specific_rotation_deg_ml_g_dm']*math.pi/18000,places=15)
|
| 29 |
+
def test_all67_complete_and_rotation_formula(self):
|
| 30 |
+
for t in JascoP4200Runtime().templates.values():
|
| 31 |
+
with self.subTest(id=t['substance_id']):
|
| 32 |
+
cond=t['conditions'];c=cond['concentration_kg_m3'] if cond['concentration_kg_m3'] is not None else 100.
|
| 33 |
+
s=dict(SAMPLE_EXAMPLE,template_id=t['substance_id'],solvent=cond['solvent'],reference_temperature_k=cond['temperature_k'],concentration_kg_m3=c)
|
| 34 |
+
r=measured(sample=s,plant=dict(PLANT_EXAMPLE,ambient_k=cond['temperature_k']))
|
| 35 |
+
self.assertEqual(r.phase,'succeeded');self.assertEqual(len(r.points),3)
|
| 36 |
+
for p in r.points:self.assertAlmostEqual(p['rotation_rad'],t['specific_rotation_rad_m2_kg']*c*.1,places=12)
|
| 37 |
+
def test_sucrose_unit_oracle(self):
|
| 38 |
+
r=measured();self.assertAlmostEqual(math.degrees(r.points[-1]['rotation_rad']),6.637,places=11)
|
| 39 |
+
def test_malus_quadrature_oracle_signed(self):
|
| 40 |
+
for degrees in [-80,-10,0,10,80]:
|
| 41 |
+
theta=math.radians(degrees);channels=[.7*math.cos(psi-theta)**2+.15 for psi in [0,math.pi/4,math.pi/2,3*math.pi/4]]
|
| 42 |
+
self.assertAlmostEqual(JascoP4200Runtime.demodulate(channels),theta,places=12)
|
| 43 |
+
def test_unpolarized_signal_rejected(self):
|
| 44 |
+
with self.assertRaisesRegex(ActionRejected,'LOW_POLARIZED_SIGNAL'):JascoP4200Runtime.demodulate([1,1,1,1])
|
| 45 |
+
def test_real_serine_mass_fraction_not_fabricated(self):
|
| 46 |
+
t=JascoP4200Runtime().templates['pubchem_5951'];self.assertIsNone(t['conditions']['concentration_kg_m3']);self.assertIn('15 G',t['conditions']['source_condition_text'])
|
| 47 |
+
def test_alanine_specific_condition(self):
|
| 48 |
+
t=JascoP4200Runtime().templates['pubchem_5950'];self.assertEqual(t['specific_rotation_deg_ml_g_dm'],2.8);self.assertEqual(t['conditions']['concentration_kg_m3'],60.)
|
| 49 |
+
def test_source_wrong_solvent_atomic(self):
|
| 50 |
+
r=configured();before=r.debug_snapshot()
|
| 51 |
+
with self.assertRaisesRegex(ActionRejected,'SOURCE_SOLVENT_MISMATCH'):r.invoke('sample.register',**dict(SAMPLE_EXAMPLE,sample_id='wrong',solvent='ethanol'))
|
| 52 |
+
self.assertEqual(before,r.debug_snapshot())
|
| 53 |
+
def test_source_wrong_temperature_rejected(self):
|
| 54 |
+
r=configured()
|
| 55 |
+
with self.assertRaisesRegex(ActionRejected,'SOURCE_TEMPERATURE_MISMATCH'):r.invoke('sample.register',**dict(SAMPLE_EXAMPLE,sample_id='wrong',reference_temperature_k=298.15))
|
| 56 |
+
def test_known_source_concentration_no_extrapolation(self):
|
| 57 |
+
r=configured();t=r.templates['pubchem_5950']
|
| 58 |
+
with self.assertRaisesRegex(ActionRejected,'SOURCE_CONCENTRATION_MISMATCH'):r.invoke('sample.register',**dict(SAMPLE_EXAMPLE,sample_id='wrong',template_id='pubchem_5950',reference_temperature_k=298.15,concentration_kg_m3=10.))
|
| 59 |
+
def test_unknown_concentration_ack(self):
|
| 60 |
+
r=configured()
|
| 61 |
+
with self.assertRaisesRegex(ActionRejected,'EVIDENCE_ACK_REQUIRED'):r.invoke('sample.register',**dict(SAMPLE_EXAMPLE,sample_id='wrong',accept_missing_source_concentration=False))
|
| 62 |
+
def test_standard_configuration_only(self):
|
| 63 |
+
r=configured()
|
| 64 |
+
for m in [dict(METHOD_EXAMPLE,lamp='Hg'),dict(METHOD_EXAMPLE,wavelength_m=546e-9),dict(METHOD_EXAMPLE,integration_s=.5),dict(METHOD_EXAMPLE,integration_s=101)]:
|
| 65 |
+
before=r.debug_snapshot()
|
| 66 |
+
with self.assertRaises(ActionRejected):r.invoke('method.configure',**m)
|
| 67 |
+
self.assertEqual(before,r.debug_snapshot())
|
| 68 |
+
def test_cell_minimum_and_path_configuration(self):
|
| 69 |
+
r=configured()
|
| 70 |
+
for s in [dict(SAMPLE_EXAMPLE,sample_id='bad',volume_m3=.5e-6),dict(SAMPLE_EXAMPLE,sample_id='bad',path_m=.05)]:
|
| 71 |
+
with self.assertRaises(ActionRejected):r.invoke('sample.register',**s)
|
| 72 |
+
def test_blank_required(self):
|
| 73 |
+
r=configured(blank=False,quartz=False)
|
| 74 |
+
with self.assertRaisesRegex(ActionRejected,'BLANK_REQUIRED'):r.invoke('acquisition.start',kind='sample')
|
| 75 |
+
def test_quartz_required(self):
|
| 76 |
+
r=configured(quartz=False)
|
| 77 |
+
with self.assertRaisesRegex(ActionRejected,'QUARTZ_CALIBRATION_REQUIRED'):r.invoke('acquisition.start',kind='sample')
|
| 78 |
+
def test_calibration_recovers_observed_gain_not_true_read(self):
|
| 79 |
+
r=measured(plant=dict(PLANT_EXAMPLE,instrument_gain=1.17,zero_offset_rad=.027));self.assertAlmostEqual(r.calibration['gain'],1.17,places=12);self.assertAlmostEqual(math.degrees(r.points[0]['rotation_rad']),6.637,places=11)
|
| 80 |
+
def test_wrong_certified_quartz_has_observable_bias(self):
|
| 81 |
+
r=configured();q=dict(QUARTZ_EXAMPLE,sample_id='quartz_02');swap(r,q);run(r,'quartz');r.invoke('calibration.quartz',certified_angle_rad=math.radians(20),accept_simulated_standard=True)
|
| 82 |
+
r.invoke('lid.set',opened=True);r.invoke('sample.unload',recipient_id='rack');r.invoke('sample.load',sample_id='sample_01');r.invoke('lid.set',opened=False);r.invoke('lamp.set',enabled=True);run(r,'sample')
|
| 83 |
+
self.assertAlmostEqual(math.degrees(r.points[0]['rotation_rad']),2*6.637,places=10)
|
| 84 |
+
def test_analysis_uses_declared_concentration(self):
|
| 85 |
+
r=measured();angles=[p['rotation_rad'] for p in r.points];before=r.debug_snapshot()
|
| 86 |
+
a=r.invoke('quantify.specific',rotation_rad=angles,declared_concentration_kg_m3=50.,declared_path_m=.1)
|
| 87 |
+
self.assertAlmostEqual(a['specific_rotation_rad_m2_kg']*18000/math.pi,132.74,places=9);self.assertEqual(before,r.debug_snapshot())
|
| 88 |
+
def test_concentration_from_caller_inputs(self):
|
| 89 |
+
r=JascoP4200Runtime();a=r.invoke('quantify.concentration',**CAPS['quantify.concentration'][6]);self.assertAlmostEqual(a['concentration_kg_m3'],100.,places=12)
|
| 90 |
+
def test_analysis_bad_reference(self):
|
| 91 |
+
r=JascoP4200Runtime()
|
| 92 |
+
for a in [dict(CAPS['quantify.concentration'][6],same_conditions_confirmed=False),dict(CAPS['quantify.concentration'][6],reference_specific_rotation_rad_m2_kg=0.)]:
|
| 93 |
+
with self.assertRaises(ActionRejected):r.invoke('quantify.concentration',**a)
|
| 94 |
+
def test_queries_do_not_advance_or_mutate(self):
|
| 95 |
+
r=measured();old=r.debug_snapshot()
|
| 96 |
+
for _ in range(3):r.read();r.invoke('process.measure');r.invoke('result.read');r.invoke('template.read',substance_id='pubchem_5988');r.invoke('product.read')
|
| 97 |
+
self.assertEqual(old,r.debug_snapshot())
|
| 98 |
+
def test_slew_rate_and_integration_timing(self):
|
| 99 |
+
r=configured();start=r.time_s;initial=r.analyzer_rad;target=math.radians(6.637)*1.02+.001;duration=abs(target-initial)/math.radians(6)
|
| 100 |
+
r.invoke('acquisition.start',kind='sample');r.step(duration/2)
|
| 101 |
+
self.assertEqual(len(r.points),0);self.assertAlmostEqual(r.analyzer_rad,(initial+target)/2,places=12)
|
| 102 |
+
r.step(duration/2+.5);self.assertEqual(len(r.points),0);r.step(.5)
|
| 103 |
+
self.assertEqual(len(r.points),1);self.assertAlmostEqual(r.points[0]['sample_time_s'],start+duration+1,places=10);self.assertEqual(r.points[0]['integration_s'],1.)
|
| 104 |
+
def test_step_partition_deterministic(self):
|
| 105 |
+
a=configured();b=configured();a.invoke('acquisition.start',kind='sample');b.invoke('acquisition.start',kind='sample');a.step(5.)
|
| 106 |
+
for _ in range(500):b.step(.01)
|
| 107 |
+
np.testing.assert_allclose([p['rotation_rad'] for p in a.points],[p['rotation_rad'] for p in b.points],atol=1e-13);self.assertAlmostEqual(a.time_s,b.time_s,places=9);self.assertEqual(a.phase,b.phase)
|
| 108 |
+
def test_seed_reproducibility_and_noise(self):
|
| 109 |
+
p=dict(PLANT_EXAMPLE,noise_density_sqrt_s=.0001);a=measured(plant=p);b=measured(plant=p)
|
| 110 |
+
self.assertEqual(a.points,b.points);self.assertGreater(np.std([x['rotation_rad'] for x in a.points]),0)
|
| 111 |
+
def test_noise_scaling_density_not_display_resolution(self):
|
| 112 |
+
p=dict(PLANT_EXAMPLE,noise_density_sqrt_s=.001);a=measured(plant=p);b=measured(plant=p,method=dict(METHOD_EXAMPLE,integration_s=4.))
|
| 113 |
+
self.assertAlmostEqual(a.points[0]['detector_sigma_rad']/b.points[0]['detector_sigma_rad'],2.,places=12)
|
| 114 |
+
def test_partial_cancel_preserved(self):
|
| 115 |
+
r=configured();r.invoke('acquisition.start',kind='sample');r.step(r._remaining+1.2);self.assertEqual(len(r.points),1);points=copy.deepcopy(r.points);angle=r.analyzer_rad
|
| 116 |
+
r.invoke('acquisition.stop');r.step(2);self.assertEqual(r.phase,'cancelled');self.assertEqual(points,r.points);self.assertEqual(angle,r.analyzer_rad)
|
| 117 |
+
def test_open_lid_interlock(self):
|
| 118 |
+
r=configured();r.invoke('acquisition.start',kind='sample');r.step(.1);r.invoke('lid.set',opened=True);self.assertEqual(r.phase,'cancelled');self.assertFalse(r.lamp)
|
| 119 |
+
with self.assertRaises(ActionRejected):r.invoke('lamp.set',enabled=True)
|
| 120 |
+
def test_power_off_invalidates(self):
|
| 121 |
+
r=configured();r.invoke('acquisition.start',kind='sample');r.invoke('power.set',enabled=False);self.assertEqual(r.phase,'cancelled');self.assertIsNone(r.blank);self.assertIsNone(r.calibration)
|
| 122 |
+
def test_busy_rejects_method_without_mutation(self):
|
| 123 |
+
r=configured();r.invoke('acquisition.start',kind='sample');old=r.debug_snapshot()
|
| 124 |
+
with self.assertRaisesRegex(ActionRejected,'BUSY'):r.invoke('method.configure',**METHOD_EXAMPLE)
|
| 125 |
+
self.assertEqual(old,r.debug_snapshot())
|
| 126 |
+
def test_signed_temperature_standard_and_energy(self):
|
| 127 |
+
r=JascoP4200Runtime();r.invoke('plant.configure',**PLANT_EXAMPLE);r.invoke('power.set',enabled=True);old=r.temperature_k;r.invoke('thermal.set_temperature',temperature_k=303.15);self.assertEqual(r.temperature_k,old);r.step(150);self.assertAlmostEqual(r.temperature_k,303.15,places=8);self.assertAlmostEqual(r._ledger()['thermal_residual_j'],0,places=8)
|
| 128 |
+
r.invoke('thermal.set_temperature',temperature_k=288.15);r.step(200);self.assertAlmostEqual(r.temperature_k,288.15,places=7);self.assertAlmostEqual(r._ledger()['thermal_residual_j'],0,places=7)
|
| 129 |
+
def test_thermal_partition(self):
|
| 130 |
+
a=JascoP4200Runtime();b=JascoP4200Runtime()
|
| 131 |
+
for r in [a,b]:r.invoke('plant.configure',**PLANT_EXAMPLE);r.invoke('power.set',enabled=True);r.invoke('thermal.set_temperature',temperature_k=313.15)
|
| 132 |
+
a.step(50)
|
| 133 |
+
for _ in range(500):b.step(.1)
|
| 134 |
+
self.assertAlmostEqual(a.temperature_k,b.temperature_k,places=9);self.assertAlmostEqual(a.controller_energy_j,b.controller_energy_j,places=7)
|
| 135 |
+
def test_source_temperature_gate_not_full_factory_range(self):
|
| 136 |
+
r=configured();r.invoke('thermal.set_temperature',temperature_k=303.15);r.step(100);r.invoke('lamp.set',enabled=True)
|
| 137 |
+
with self.assertRaisesRegex(ActionRejected,'REFERENCE_TEMPERATURE_MISMATCH'):r.invoke('acquisition.start',kind='sample')
|
| 138 |
+
def test_angle_aliasing_outside_range_rejected(self):
|
| 139 |
+
r=configured(sample=dict(SAMPLE_EXAMPLE,concentration_kg_m3=1000.));r.plant['instrument_gain']=1.5
|
| 140 |
+
with self.assertRaisesRegex(ActionRejected,'ANGLE_BRANCH_RANGE'):r.invoke('acquisition.start',kind='sample')
|
| 141 |
+
def test_intact_cell_material_conservation(self):
|
| 142 |
+
r=measured();a=r.invoke('product.read');self.assertAlmostEqual(a['attached_solute_kg'],.0001)
|
| 143 |
+
r.invoke('lid.set',opened=True);r.invoke('sample.unload',recipient_id='rack');b=r.invoke('product.read')
|
| 144 |
+
self.assertEqual(a['registered_solute_kg'],b['registered_solute_kg']);self.assertEqual(b['attached_volume_m3'],0);self.assertEqual(b['mass_residual_kg'],0);self.assertEqual(b['volume_residual_m3'],0)
|
| 145 |
+
def test_two_instance_isolation(self):
|
| 146 |
+
a=configured();b=configured();old=b.debug_snapshot();a.invoke('acquisition.start',kind='sample');a.step(2);self.assertEqual(old,b.debug_snapshot())
|
| 147 |
+
def test_identity_acl_description_read_and_invoke(self):
|
| 148 |
+
r=configured();agent=r.session();r.register_principal('host','evaluator');host=r.session('host')
|
| 149 |
+
self.assertNotIn('truth.ledger',agent.describe(instance_id=r.instance_id)['state_slots']);self.assertNotIn('sample.register',agent.describe(instance_id=r.instance_id)['capabilities'])
|
| 150 |
+
with self.assertRaises(ActionRejected):agent.read(instance_id=r.instance_id,state_ids=['truth.ledger'])
|
| 151 |
+
denied=agent.invoke(instance_id=r.instance_id,capability_id='product.read',arguments={},request_id='private');self.assertEqual(denied['error']['code'],'ACCESS_DENIED')
|
| 152 |
+
self.assertIn('truth.ledger',host.read(instance_id=r.instance_id)['observations'])
|
| 153 |
+
def test_public_result_no_current_identity_or_concentration(self):
|
| 154 |
+
r=measured();public=json.dumps([r.read(),r.invoke('result.read')]);self.assertNotIn('pubchem_5988',public);self.assertNotIn('active_template_id',public);self.assertNotIn('instrument_gain',public)
|
| 155 |
+
def test_protocol_idempotency_conflict(self):
|
| 156 |
+
r=configured();s=r.session();a=s.invoke(instance_id=r.instance_id,capability_id='acquisition.start',arguments={'kind':'sample'},request_id='one');r.step(.1);rev=r.revision
|
| 157 |
+
b=s.invoke(instance_id=r.instance_id,capability_id='acquisition.start',arguments={'kind':'sample'},request_id='one');self.assertEqual(a,b);self.assertEqual(rev,r.revision)
|
| 158 |
+
c=s.invoke(instance_id=r.instance_id,capability_id='acquisition.stop',arguments={},request_id='one');self.assertEqual(c['error']['code'],'REQUEST_CONFLICT')
|
| 159 |
+
def test_protocol_operation_owner_cancel(self):
|
| 160 |
+
r=configured();r.register_principal('other');s=r.session();a=s.invoke(instance_id=r.instance_id,capability_id='acquisition.start',arguments={'kind':'sample'},request_id='one');op=a['operation_id']
|
| 161 |
+
with self.assertRaises(ActionRejected):r.session('other').poll(op)
|
| 162 |
+
self.assertEqual(s.poll(op)['status'],'running');self.assertEqual(s.cancel(op,'cancel')['result']['phase'],'cancelled')
|
| 163 |
+
def test_null_quality_and_last_sample_window(self):
|
| 164 |
+
r=configured();s=r.session();a=s.read(instance_id=r.instance_id,state_ids=['scan.rotation_rad']);self.assertEqual(a['observations']['scan.rotation_rad']['quality'],'unavailable')
|
| 165 |
+
run(r,'sample');r.step(5);o=s.read(instance_id=r.instance_id,state_ids=['scan.rotation_rad'])['observations']['scan.rotation_rad'];self.assertEqual(o['sample_time_s'],r.points[-1]['sample_time_s']);self.assertEqual(o['sample_window_s'],[o['sample_time_s']-1,o['sample_time_s']])
|
| 166 |
+
def test_argument_deepcopy_and_no_nan_bool_numbers(self):
|
| 167 |
+
r=JascoP4200Runtime();p=copy.deepcopy(PLANT_EXAMPLE);r.invoke('plant.configure',**p);p['ambient_k']=300;self.assertEqual(r.plant['ambient_k'],293.15)
|
| 168 |
+
for v in [True,float('nan'),float('inf')]:
|
| 169 |
+
with self.assertRaises(ActionRejected):r.invoke('thermal.set_temperature',temperature_k=v)
|
| 170 |
+
def test_query_deepcopy(self):
|
| 171 |
+
r=measured();value=r.invoke('result.read');value['points'][0]['rotation_rad']=99;self.assertLess(r.points[0]['rotation_rad'],1)
|
| 172 |
+
def test_unsupported_never_success(self):
|
| 173 |
+
r=configured()
|
| 174 |
+
for cap in UNSUPPORTED:
|
| 175 |
+
a=r.session().invoke(instance_id=r.instance_id,capability_id=cap,arguments={},request_id=cap);self.assertEqual(a['status'],'unsupported')
|
| 176 |
+
def test_host_clock_before_configuration(self):
|
| 177 |
+
r=JascoP4200Runtime();r.step(10);r.invoke('plant.configure',**PLANT_EXAMPLE);self.assertEqual(r.time_s,10)
|
| 178 |
+
def test_noisy_principal_angle_wrap_fails_and_preserves_points(self):
|
| 179 |
+
alpha=JascoP4200Runtime().templates[SAMPLE_EXAMPLE['template_id']]['specific_rotation_rad_m2_kg'];concentration=(math.pi/2-1e-6-.001)/(1.4*alpha*.1)
|
| 180 |
+
r=configured(plant=dict(PLANT_EXAMPLE,instrument_gain=1.4,noise_density_sqrt_s=.001,seed=70),sample=dict(SAMPLE_EXAMPLE,concentration_kg_m3=concentration,transmittance=1.));s=r.session();op=s.invoke(instance_id=r.instance_id,capability_id='acquisition.start',arguments={'kind':'sample'},request_id='branch')['operation_id'];r.step(40)
|
| 181 |
+
self.assertEqual(r.phase,'failed');self.assertEqual(r.warning,'ANGLE_BRANCH_RANGE');self.assertEqual(len(r.points),2);self.assertTrue(all(p['rotation_rad']>0 for p in r.points));self.assertFalse(r.lamp)
|
| 182 |
+
failed=s.poll(op);self.assertEqual(failed['status'],'failed');self.assertEqual(failed['result']['completed_points'],2);before=copy.deepcopy(r.points);r.step(10);self.assertEqual(r.points,before);self.assertEqual(s.poll(op),failed)
|
| 183 |
+
def test_near_branch_without_wrap_remains_measurable(self):
|
| 184 |
+
alpha=JascoP4200Runtime().templates[SAMPLE_EXAMPLE['template_id']]['specific_rotation_rad_m2_kg'];concentration=(math.pi/2-1e-6-.001)/(1.4*alpha*.1)
|
| 185 |
+
r=measured(plant=dict(PLANT_EXAMPLE,instrument_gain=1.4,noise_density_sqrt_s=.001,seed=71),sample=dict(SAMPLE_EXAMPLE,concentration_kg_m3=concentration,transmittance=1.))
|
| 186 |
+
self.assertEqual(r.phase,'succeeded');self.assertEqual(len(r.points),3);self.assertTrue(all(p['rotation_rad']>0 for p in r.points));self.assertGreater(math.degrees(r._target_angle),89.99)
|
| 187 |
+
def test_raw_angle_window_matches_corrected_angle_and_poll(self):
|
| 188 |
+
r=configured();s=r.session();op=s.invoke(instance_id=r.instance_id,capability_id='acquisition.start',arguments={'kind':'sample'},request_id='sample')['operation_id'];r.step(10)
|
| 189 |
+
observations=s.read(instance_id=r.instance_id,state_ids=['scan.raw_rotation_rad','scan.rotation_rad'])['observations'];raw=observations['scan.raw_rotation_rad'];corrected=observations['scan.rotation_rad']
|
| 190 |
+
self.assertEqual(raw['sample_window_s'],corrected['sample_window_s']);self.assertEqual(raw['sample_window_s'],[r.points[-1]['sample_time_s']-1.,r.points[-1]['sample_time_s']]);self.assertEqual(s.poll(op)['observations'],observations)
|
| 191 |
+
def test_completed_operation_and_windows_survive_next_scan(self):
|
| 192 |
+
r=configured();s=r.session();start=lambda rid:s.invoke(instance_id=r.instance_id,capability_id='acquisition.start',arguments={'kind':'sample'},request_id=rid)
|
| 193 |
+
old=start('first')['operation_id'];r.step(10);frozen=s.poll(old);r.invoke('lamp.set',enabled=True);start('second');r.step(1.2);before=r.debug_snapshot()
|
| 194 |
+
self.assertEqual(s.poll(old),frozen);self.assertEqual(before,r.debug_snapshot());self.assertEqual(frozen['status'],'succeeded');self.assertEqual(frozen['result']['completed_points'],3)
|
| 195 |
+
current=s.read(instance_id=r.instance_id,state_ids=['scan.raw_rotation_rad'])['observations']['scan.raw_rotation_rad'];self.assertGreater(current['sample_time_s'],frozen['observations']['scan.raw_rotation_rad']['sample_time_s'])
|
| 196 |
+
frozen['observations']['scan.raw_rotation_rad']['sample_window_s'][0]=-999;self.assertGreater(s.poll(old)['observations']['scan.raw_rotation_rad']['sample_window_s'][0],0);r.register_principal('other')
|
| 197 |
+
with self.assertRaisesRegex(ActionRejected,'ACCESS_DENIED'):r.session('other').poll(old)
|
| 198 |
+
self.assertNotIn('pubchem_',json.dumps(s.poll(old)));self.assertNotIn('truth.',json.dumps(s.poll(old)))
|
| 199 |
+
def test_cancel_old_operation_preserves_current_acquisition(self):
|
| 200 |
+
r=configured();s=r.session();start=lambda rid:s.invoke(instance_id=r.instance_id,capability_id='acquisition.start',arguments={'kind':'sample'},request_id=rid)
|
| 201 |
+
old=start('first')['operation_id'];r.step(10);r.invoke('lamp.set',enabled=True);current=start('second')['operation_id'];revision=r.revision
|
| 202 |
+
result=s.cancel(old,'cancel_old');self.assertEqual(result['result']['phase'],'succeeded');self.assertEqual(r.phase,'running');self.assertTrue(r.lamp);self.assertEqual(r.operation_id,current);self.assertEqual(r.revision,revision)
|
| 203 |
+
r.step(.1);self.assertEqual(s.cancel(old,'cancel_old'),result)
|
| 204 |
+
with self.assertRaisesRegex(ActionRejected,'REQUEST_CONFLICT'):s.cancel(current,'cancel_old')
|
| 205 |
+
self.assertEqual(r.phase,'running')
|
| 206 |
+
def test_cancelled_snapshot_survives_result_reset(self):
|
| 207 |
+
r=configured();s=r.session();op=s.invoke(instance_id=r.instance_id,capability_id='acquisition.start',arguments={'kind':'sample'},request_id='first')['operation_id'];r.step(r._remaining+1.2);s.cancel(op,'stop');frozen=s.poll(op)
|
| 208 |
+
r.invoke('lid.set',opened=True);r.invoke('method.configure',**METHOD_EXAMPLE);self.assertEqual(s.poll(op),frozen);self.assertEqual(frozen['result']['completed_points'],1);self.assertEqual(frozen['result']['warning'],'CANCELLED')
|
| 209 |
+
def test_temperature_metadata_separates_target_from_process(self):
|
| 210 |
+
r=configured();meta=export_jasco_p4200_contract_metadata();cap=meta['capabilities']['thermal.set_temperature'];immediate={e['state_id'] for e in cap['state_effects'] if e['timing']=='immediate'};later={e['state_id'] for e in cap['state_effects'] if e['timing']=='on_step'}
|
| 211 |
+
before=r.read('evaluator');r.invoke('thermal.set_temperature',temperature_k=303.15);after=r.read('evaluator');self.assertLessEqual({k for k in before if before[k]!=after[k]},immediate);self.assertNotIn('thermal.temperature_k',immediate);self.assertNotIn('optics.analyzer_rad',immediate);self.assertNotIn('power.enabled',immediate)
|
| 212 |
+
self.assertEqual(before['thermal.temperature_k'],after['thermal.temperature_k']);r.step(.1);self.assertNotEqual(r.temperature_k,before['thermal.temperature_k']);self.assertIn('thermal.temperature_k',later);self.assertIn('scan.raw_rotation_rad',meta['capabilities']['process.measure']['observes']);self.assertEqual(meta['capabilities']['process.measure']['state_effects'],[])
|
| 213 |
+
if __name__=='__main__':unittest.main()
|
tests/test_asset_jena_contraa800.py
ADDED
|
@@ -0,0 +1,245 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Behavioral regressions for contrAA800D: observed AAS, reference provenance, finite mechanisms and ACL."""
|
| 2 |
+
import copy,importlib.util,json,math,sys,unittest
|
| 3 |
+
from pathlib import Path
|
| 4 |
+
import numpy as np
|
| 5 |
+
ROOT=Path(__file__).resolve().parents[1];sys.path.insert(0,str(ROOT/'scripts'))
|
| 6 |
+
from asset_runtime import jena_contraa800 as rt
|
| 7 |
+
SPEC=importlib.util.spec_from_file_location('contraa_asset_tool',ROOT/'skills/chemistry-lab-assets/scripts/asset_tool.py');tool=importlib.util.module_from_spec(SPEC);SPEC.loader.exec_module(tool)
|
| 8 |
+
|
| 9 |
+
def make(mode='flame',noise=0.,**plant):
|
| 10 |
+
h=rt.JenaContraa800Runtime();h.invoke('plant.configure',**dict(rt.PLANT_EXAMPLE,detector_noise_sd=noise,**plant));h.invoke('method.configure',**(rt.METHOD_EXAMPLE if mode=='flame' else rt.FURNACE_METHOD_EXAMPLE));h.invoke('power.set',enabled=True);h.step(.3)
|
| 11 |
+
if mode=='flame':h.invoke('flame.ignite');h.step(.1)
|
| 12 |
+
else:h.invoke('cover.set',opened=True)
|
| 13 |
+
return h
|
| 14 |
+
|
| 15 |
+
def finish(h,dt=.02,limit=30):
|
| 16 |
+
for _ in range(math.ceil(limit/dt)):
|
| 17 |
+
if h.phase!='running':break
|
| 18 |
+
h.step(dt)
|
| 19 |
+
if h.phase!='succeeded':raise AssertionError((h.phase,h.stage,h.warning))
|
| 20 |
+
return h.invoke('result.read')
|
| 21 |
+
|
| 22 |
+
def load(h,s):
|
| 23 |
+
if h.sample:h.invoke('sample.unload',recipient_id='external')
|
| 24 |
+
h.invoke('sample.load',**s)
|
| 25 |
+
|
| 26 |
+
def blank(h):
|
| 27 |
+
load(h,rt.BLANK_EXAMPLE);h.invoke('measurement.start');return finish(h)
|
| 28 |
+
|
| 29 |
+
def calibrate(h):
|
| 30 |
+
blank(h);obs=[]
|
| 31 |
+
for i in [1,2,3]:
|
| 32 |
+
ref=f'aj_wastewater_std{i}_cu';load(h,dict(rt.STANDARD_EXAMPLE,template_id=ref));h.invoke('measurement.start');r=finish(h);obs.append(dict(reference_id=ref,dilution_factor=1.,injection_volume_m3=h.method['injection_volume_m3'],integrated_absorbance_s=r['assays'][0]['integrated_absorbance_s']))
|
| 33 |
+
result=h.invoke('calibration.fit',curve_id='observed_cu',observations=obs,accept_same_response_conditions=True);h.invoke('calibration.select',curve_id='observed_cu');return obs,result
|
| 34 |
+
|
| 35 |
+
class ContraaTests(unittest.TestCase):
|
| 36 |
+
def atomic_reject(self,h,cap,code=None,**args):
|
| 37 |
+
before=json.dumps(h.debug_snapshot(),sort_keys=True,default=lambda x:x.tolist() if hasattr(x,'tolist') else repr(x))
|
| 38 |
+
with self.assertRaises(rt.ActionRejected) as cm:h.invoke(cap,**args)
|
| 39 |
+
if code:self.assertEqual(str(cm.exception),code)
|
| 40 |
+
after=json.dumps(h.debug_snapshot(),sort_keys=True,default=lambda x:x.tolist() if hasattr(x,'tolist') else repr(x));self.assertEqual(before,after)
|
| 41 |
+
def balance(self,h):
|
| 42 |
+
l=h.invoke('product.read');self.assertAlmostEqual(l['element_mass_kg']['residual'],0.,delta=1e-18);self.assertAlmostEqual(l['liquid_volume_m3']['residual'],0.,delta=1e-15)
|
| 43 |
+
for gas in ['fuel_mol','oxidant_mol','argon_mol']:self.assertAlmostEqual(l[gas]['residual'],0.,delta=1e-12)
|
| 44 |
+
self.assertAlmostEqual(l['thermal_residual_j'],0.,delta=1e-8)
|
| 45 |
+
def test_identity_and_real_default(self):
|
| 46 |
+
h=rt.JenaContraa800Runtime();self.assertEqual(rt.CATALOG_ID,'CHEM-081');self.assertAlmostEqual(h.templates[rt.SAMPLE_EXAMPLE['template_id']]['concentration_kg_m3'],.000083,places=15);self.assertAlmostEqual(h.lines['cu_324754']['wavelength_m'],324.754e-9,places=18)
|
| 47 |
+
def test_queries_and_describe_do_not_mutate_rng_or_clock(self):
|
| 48 |
+
h=make();blank(h);before=h.debug_snapshot();h.describe();h.read();h.invoke('spectrum.read');h.invoke('result.read');h.invoke('records.list');self.assertEqual(json.dumps(before,sort_keys=True),json.dumps(h.debug_snapshot(),sort_keys=True))
|
| 49 |
+
def test_step_zero_is_pure(self):
|
| 50 |
+
h=make();before=h.debug_snapshot();h.step(0);self.assertEqual(before,h.debug_snapshot())
|
| 51 |
+
def test_step_rejects_nonfinite_bool_negative(self):
|
| 52 |
+
h=make()
|
| 53 |
+
for v in [True,-1.,float('nan'),float('inf')]:
|
| 54 |
+
with self.assertRaises(rt.ActionRejected):h.step(v)
|
| 55 |
+
def test_host_initialization_cannot_overwrite(self):self.atomic_reject(make(),'plant.configure','INITIALIZATION_ONLY',**rt.PLANT_EXAMPLE)
|
| 56 |
+
def test_assumed_response_ack_required(self):self.atomic_reject(rt.JenaContraa800Runtime(),'plant.configure','EVIDENCE_ACK_REQUIRED',**dict(rt.PLANT_EXAMPLE,accept_assumed_response=False))
|
| 57 |
+
def test_sample_reference_and_dilution_not_mutate_library(self):
|
| 58 |
+
h=make();before=copy.deepcopy(h.library);h.invoke('sample.load',**dict(rt.SAMPLE_EXAMPLE,dilution_factor=10));self.assertAlmostEqual(h.sample['concentration'],.0000083,places=17);self.assertEqual(h.library,before)
|
| 59 |
+
def test_censored_or_solid_concentration_rejected(self):
|
| 60 |
+
h=make();ids=[k for k,v in h.templates.items() if v.get('concentration_kg_m3') is None]
|
| 61 |
+
self.assertGreater(len(ids),0)
|
| 62 |
+
for key in ids[:4]:self.atomic_reject(h,'sample.load','LIQUID_CONCENTRATION_REQUIRED',**dict(rt.SAMPLE_EXAMPLE,template_id=key))
|
| 63 |
+
def test_line_only_query_no_fake_concentration(self):
|
| 64 |
+
h=make();r=h.invoke('template.read',substance_id='cu_324754');self.assertEqual(json.loads(r['template_json'])['element'],'Cu');self.atomic_reject(h,'sample.load','LIQUID_CONCENTRATION_REQUIRED',**dict(rt.SAMPLE_EXAMPLE,template_id='cu_324754'))
|
| 65 |
+
def test_unknown_conditions_requires_ack(self):self.atomic_reject(make(),'sample.load','EVIDENCE_ACK_REQUIRED',**dict(rt.SAMPLE_EXAMPLE,accept_unknown_conditions=False))
|
| 66 |
+
def test_unknown_reference_error_does_not_reveal_state(self):self.atomic_reject(make(),'sample.load','UNKNOWN_REFERENCE',**dict(rt.SAMPLE_EXAMPLE,template_id='unknown'))
|
| 67 |
+
def test_replacement_requires_unload(self):
|
| 68 |
+
h=make();h.invoke('sample.load',**rt.SAMPLE_EXAMPLE);self.atomic_reject(h,'sample.load','UNLOAD_REQUIRED',**rt.SAMPLE_EXAMPLE)
|
| 69 |
+
def test_donor_volume_return_only_remaining(self):
|
| 70 |
+
h=make();blank(h);load(h,rt.STANDARD_EXAMPLE);h.invoke('measurement.start');finish(h);initial=rt.STANDARD_EXAMPLE['volume_m3'];r=h.invoke('sample.unload',recipient_id='host');self.assertAlmostEqual(r['volume_m3'],initial-h.method['injection_volume_m3']);self.balance(h)
|
| 71 |
+
def test_method_requires_matching_element_line(self):
|
| 72 |
+
h=make();h.invoke('flame.extinguish');self.atomic_reject(h,'method.configure','ELEMENT_LINE_MISMATCH',**dict(rt.METHOD_EXAMPLE,element='Pb'))
|
| 73 |
+
def test_unknown_line_rejected(self):
|
| 74 |
+
h=make();h.invoke('flame.extinguish');self.atomic_reject(h,'method.configure','UNKNOWN_LINE',**dict(rt.METHOD_EXAMPLE,line_id='missing'))
|
| 75 |
+
def test_documented_optical_bounds_and_not_sigma(self):
|
| 76 |
+
h=make();h.invoke('flame.extinguish')
|
| 77 |
+
for wavelength in [184e-9,901e-9]:self.atomic_reject(h,'method.configure','INVALID_ARGUMENT',**dict(rt.METHOD_EXAMPLE,wavelength_m=wavelength))
|
| 78 |
+
self.assertNotEqual(rt.PLANT_EXAMPLE['line_sigma_m'],4e-13)
|
| 79 |
+
def test_large_line_detuning_is_explicit_error(self):
|
| 80 |
+
h=make();h.invoke('flame.extinguish');self.atomic_reject(h,'method.configure','LINE_WINDOW_MISMATCH',**dict(rt.METHOD_EXAMPLE,wavelength_m=325e-9))
|
| 81 |
+
def test_standard_tube_volume_limit50ul(self):
|
| 82 |
+
h=make('furnace');self.atomic_reject(h,'method.configure','STANDARD_TUBE_VOLUME_LIMIT',**dict(rt.FURNACE_METHOD_EXAMPLE,injection_volume_m3=51e-9))
|
| 83 |
+
def test_one_ul_minimum_dosing(self):
|
| 84 |
+
h=make('furnace');self.atomic_reject(h,'method.configure','INVALID_ARGUMENT',**dict(rt.FURNACE_METHOD_EXAMPLE,injection_volume_m3=.5e-9))
|
| 85 |
+
def test_furnace_temperature_and_ramp_bounds(self):
|
| 86 |
+
h=make('furnace')
|
| 87 |
+
for key,value in [('temperature_k',3274.),('ramp_k_s',3001.)]:
|
| 88 |
+
program=copy.deepcopy(rt.FURNACE_PROGRAM_EXAMPLE);program[2][key]=value;self.atomic_reject(h,'method.configure','INVALID_ARGUMENT',**dict(rt.FURNACE_METHOD_EXAMPLE,furnace_program=program))
|
| 89 |
+
def test_furnace_stage_order_enforced(self):
|
| 90 |
+
h=make('furnace');p=list(reversed(rt.FURNACE_PROGRAM_EXAMPLE));self.atomic_reject(h,'method.configure','FURNACE_PROGRAM_ORDER',**dict(rt.FURNACE_METHOD_EXAMPLE,furnace_program=p))
|
| 91 |
+
def test_atomizer_and_burner_targets_are_finite(self):
|
| 92 |
+
h=rt.JenaContraa800Runtime();h.invoke('plant.configure',**rt.PLANT_EXAMPLE);h.invoke('method.configure',**rt.METHOD_EXAMPLE);h.invoke('power.set',enabled=True);self.assertEqual(h.atomizer,0.);h.step(.01);self.assertGreater(h.atomizer,0.);self.assertLess(h.atomizer,math.pi/2)
|
| 93 |
+
h.invoke('burner.configure',height_m=.016,angle_rad=math.pi/2);self.assertEqual(h.burner_height,.004);h.step(.01);self.assertGreater(h.burner_height,.004);self.assertLess(h.burner_height,.016)
|
| 94 |
+
def test_ignition_requires_position_and_gas(self):
|
| 95 |
+
h=rt.JenaContraa800Runtime();h.invoke('plant.configure',**rt.PLANT_EXAMPLE);h.invoke('method.configure',**rt.METHOD_EXAMPLE);h.invoke('power.set',enabled=True);self.atomic_reject(h,'flame.ignite','IGNITION_INTERLOCK')
|
| 96 |
+
def test_ignition_delay_not_immediate_flame(self):
|
| 97 |
+
h=make();h.invoke('flame.extinguish');h.invoke('flame.ignite');self.assertFalse(h.flame);h.step(.01);self.assertFalse(h.flame);h.step(.05);self.assertTrue(h.flame)
|
| 98 |
+
def test_flame_requires_closed_door(self):
|
| 99 |
+
h=make();self.assertEqual(h.read()['cover.lift_m'],0.);h.invoke('flame.extinguish');h.invoke('cover.set',opened=True);self.assertEqual(h.read()['cover.lift_m'],.245);self.assertNotIn('cover.angle_rad',h.read());self.atomic_reject(h,'flame.ignite','IGNITION_INTERLOCK')
|
| 100 |
+
slot=rt.export_jena_contraa800_contract_metadata()['state_slots']['cover.lift_m'];self.assertEqual(slot['unit'],'m');self.assertEqual(slot['value_schema']['maximum'],.245)
|
| 101 |
+
def test_furnace_sampling_requires_open_sample_door(self):
|
| 102 |
+
h=make('furnace');self.assertEqual(h.read()['cover.lift_m'],.245);h.invoke('cover.set',opened=False);self.assertEqual(h.read()['cover.lift_m'],0.);h.invoke('sample.load',**rt.BLANK_EXAMPLE);self.atomic_reject(h,'measurement.start','SAMPLE_DOOR_MODE_INTERLOCK')
|
| 103 |
+
def test_furnace_and_lamp_maintenance_require_power_off(self):
|
| 104 |
+
h=make('furnace')
|
| 105 |
+
for cap in ['furnace.open','lamp_door.set']:self.atomic_reject(h,cap,'MAINTENANCE_INTERLOCK',opened=True)
|
| 106 |
+
def test_live_measurement_cannot_mutate_method(self):
|
| 107 |
+
h=make();blank(h);load(h,rt.STANDARD_EXAMPLE);h.invoke('measurement.start');self.atomic_reject(h,'method.configure','BUSY',**rt.METHOD_EXAMPLE)
|
| 108 |
+
def test_missing_blank_and_calibration_reject_before_consuming(self):
|
| 109 |
+
h=make();load(h,rt.SAMPLE_EXAMPLE);self.atomic_reject(h,'measurement.start','MATCHED_BLANK_REQUIRED');blank(h);load(h,rt.SAMPLE_EXAMPLE);self.atomic_reject(h,'measurement.start','MATCHED_CALIBRATION_REQUIRED')
|
| 110 |
+
def test_small_donor_volume_guard_is_atomic(self):
|
| 111 |
+
h=make();blank(h);load(h,dict(rt.STANDARD_EXAMPLE,volume_m3=1e-9));self.atomic_reject(h,'measurement.start','SAMPLE_VOLUME_LIMIT')
|
| 112 |
+
def test_cancelled_blank_does_not_become_valid(self):
|
| 113 |
+
h=make();load(h,rt.BLANK_EXAMPLE);h.invoke('measurement.start');h.step(.04);h.invoke('measurement.stop');self.assertFalse(h._blank_valid());self.assertEqual(h.phase,'cancelled')
|
| 114 |
+
def test_flame_mass_volume_gas_ledger(self):
|
| 115 |
+
h=make();blank(h);load(h,rt.STANDARD_EXAMPLE);h.invoke('measurement.start');finish(h);self.balance(h);self.assertGreater(h._waste,0);self.assertGreater(h._exhaust,0);self.assertGreater(h._gases['fuel']['consumed'],0)
|
| 116 |
+
def test_graphite_furnace_mass_and_heat_ledger(self):
|
| 117 |
+
h=make('furnace');blank(h);load(h,rt.STANDARD_EXAMPLE);h.invoke('measurement.start');finish(h);self.balance(h);self.assertGreater(h.heat,0);self.assertGreater(h._gases['argon']['consumed'],0);self.assertEqual(h._gases['fuel']['consumed'],0)
|
| 118 |
+
def test_furnace_ramp_never_jumps_to_setpoint(self):
|
| 119 |
+
h=make('furnace');load(h,rt.BLANK_EXAMPLE);h.invoke('measurement.start')
|
| 120 |
+
while h.stage!='heat_atomize':h.step(.001)
|
| 121 |
+
t=h.temperature;h.step(.005);self.assertLessEqual(h.temperature-t,15.00001);self.assertLess(h.temperature,h.target)
|
| 122 |
+
def test_108_sampler_angles_physically_reach_four_rings(self):
|
| 123 |
+
radii=[.058]*28+[.080]*32+[.102]*40+[.030]*8
|
| 124 |
+
for i,radius in enumerate(radii):
|
| 125 |
+
arm,tray=rt.sampler_pick_angles(i);point=np.array([.130*math.sin(arm),-.130*math.cos(arm)]);self.assertAlmostEqual(np.linalg.norm(point-np.array([0.,-.1125])),radius,places=12);self.assertTrue(0<=tray<2*math.pi)
|
| 126 |
+
def test_sampler_pick_and_injection_depths(self):
|
| 127 |
+
h=make('furnace');load(h,dict(rt.BLANK_EXAMPLE,vial_index=107));h.invoke('measurement.start');seen={}
|
| 128 |
+
while h.phase=='running':
|
| 129 |
+
h.step(.001)
|
| 130 |
+
if h.stage in ['aspirate','dispense']:seen[h.stage]=(h.injector,h.sampler_arm,h.sampler)
|
| 131 |
+
self.assertAlmostEqual(seen['aspirate'][0],.052);self.assertAlmostEqual(seen['dispense'][0],.077);self.assertAlmostEqual(seen['dispense'][1],math.pi);self.assertAlmostEqual(h.sampler_arm,math.pi/2);self.assertEqual(h.injector,0.)
|
| 132 |
+
def test_cancelled_sampler_requires_park_for_door(self):
|
| 133 |
+
h=make('furnace');load(h,rt.BLANK_EXAMPLE);h.invoke('measurement.start')
|
| 134 |
+
while h.stage!='aspirate':h.step(.005)
|
| 135 |
+
h.invoke('measurement.stop');self.atomic_reject(h,'cover.set','SAMPLER_PARK_REQUIRED',opened=False);h.invoke('sampler.park');self.assertTrue(h._parking);h.step(1);self.assertFalse(h._parking);h.invoke('cover.set',opened=False)
|
| 136 |
+
def test_cancel_does_not_return_aspirated_liquid(self):
|
| 137 |
+
h=make('furnace');load(h,rt.STANDARD_EXAMPLE);h._blanks[h._key()]={'baseline':0.};h.invoke('measurement.start')
|
| 138 |
+
while h.stage!='aspirate':h.step(.001)
|
| 139 |
+
h.step(.03);v=h.sample['volume'];h.invoke('measurement.stop');self.assertLess(v,rt.STANDARD_EXAMPLE['volume_m3']);self.assertGreater(h._pipette_v,0.);h.step(.1);self.assertEqual(v,h.sample['volume']);self.balance(h)
|
| 140 |
+
def test_cold_clean_transfers_residue_to_waste(self):
|
| 141 |
+
h=make('furnace');load(h,rt.BLANK_EXAMPLE);h.invoke('measurement.start')
|
| 142 |
+
while h.stage!='aspirate':h.step(.001)
|
| 143 |
+
h.step(.03);h.invoke('measurement.stop');h.invoke('power.set',enabled=False);before=h._pipette_v;r=h.invoke('fluidics.clean');self.assertEqual(r['removed_volume_m3'],before);self.assertEqual(h._pipette_v,0.);self.balance(h)
|
| 144 |
+
def test_power_loss_cancels_and_retains_peaks(self):
|
| 145 |
+
h=make();blank(h);load(h,rt.STANDARD_EXAMPLE);h.invoke('measurement.start');h.step(.1);n=len(h._active['points']);h.invoke('power.set',enabled=False);self.assertEqual(h.phase,'cancelled');self.assertFalse(h.flame);self.assertEqual(len(h._active['points']),n);self.balance(h)
|
| 146 |
+
def test_fuel_exhaustion_fails_without_fabricated_concentration(self):
|
| 147 |
+
h=make(fuel_inventory_mol=.0004);load(h,rt.BLANK_EXAMPLE);h.invoke('measurement.start');h.step(1);self.assertEqual(h.phase,'failed');self.assertEqual(h.warning,'GAS_EXHAUSTED');self.assertIsNone(h._concentration);self.balance(h)
|
| 148 |
+
def test_observed_calibration_recovers_blinded_flame_sample(self):
|
| 149 |
+
h=make();obs,fit=calibrate(h);load(h,rt.SAMPLE_EXAMPLE);h.invoke('measurement.start');r=finish(h);self.assertGreater(fit['r_squared'],.999999);self.assertAlmostEqual(r['concentration_kg_m3'],.000083,delta=1e-8)
|
| 150 |
+
def test_observed_calibration_recovers_furnace_sample(self):
|
| 151 |
+
h=make('furnace');calibrate(h);load(h,rt.SAMPLE_EXAMPLE);h.invoke('measurement.start');r=finish(h);self.assertAlmostEqual(r['concentration_kg_m3'],.000083,delta=1e-7)
|
| 152 |
+
def test_independent_centered_least_squares(self):
|
| 153 |
+
h=make();obs,fit=calibrate(h);x=np.array([h.templates[o['reference_id']]['concentration_kg_m3']*o['injection_volume_m3'] for o in obs]);y=np.array([o['integrated_absorbance_s'] for o in obs]);m,b=np.polyfit(x,y,1);self.assertAlmostEqual(fit['slope_s_kg']/m,1,places=12);self.assertAlmostEqual(fit['intercept_s'],b,places=15)
|
| 154 |
+
def test_degenerate_and_negative_slope_calibration_atomic(self):
|
| 155 |
+
h=make();obs,_=calibrate(h)
|
| 156 |
+
self.atomic_reject(h,'calibration.fit','DEGENERATE_CALIBRATION',curve_id='flat',observations=[obs[0]]*3,accept_same_response_conditions=True)
|
| 157 |
+
self.atomic_reject(h,'calibration.fit','CALIBRATION_FIT_INVALID',curve_id='reverse',observations=[dict(o,integrated_absorbance_s=-o['integrated_absorbance_s']) for o in obs],accept_same_response_conditions=True)
|
| 158 |
+
def test_nonfinite_calibration_area_rejected(self):
|
| 159 |
+
h=make();blank(h);a=copy.deepcopy(rt.CALIBRATION_EXAMPLE);a['observations'][0]['integrated_absorbance_s']=float('inf');self.atomic_reject(h,'calibration.fit','INVALID_ARGUMENT',**a)
|
| 160 |
+
def test_curve_duplicate_and_capacity_no_overwrite(self):
|
| 161 |
+
h=make();obs,_=calibrate(h);self.atomic_reject(h,'calibration.fit','CURVE_ID_EXISTS',curve_id='observed_cu',observations=obs,accept_same_response_conditions=True)
|
| 162 |
+
for i in range(rt.CURVE_CAPACITY-1):h.invoke('calibration.fit',curve_id=f'c{i}',observations=obs,accept_same_response_conditions=True)
|
| 163 |
+
self.assertEqual(len(h._curves),rt.CURVE_CAPACITY);self.atomic_reject(h,'calibration.fit','CURVE_STORE_FULL',curve_id='overflow',observations=obs,accept_same_response_conditions=True)
|
| 164 |
+
def test_method_signature_rejects_wrong_background_curve(self):
|
| 165 |
+
h=make();calibrate(h);h.invoke('flame.extinguish');h.invoke('method.configure',**dict(rt.METHOD_EXAMPLE,background='off'));self.assertFalse(h._calibration_ready());self.assertFalse(h._blank_valid());self.atomic_reject(h,'calibration.select','CURVE_METHOD_MISMATCH',curve_id='observed_cu')
|
| 166 |
+
def test_response_changed_not_source_lookup(self):
|
| 167 |
+
h=make();calibrate(h);load(h,rt.SAMPLE_EXAMPLE);h.sample['concentration']*=.8;h._registered-=rt.SAMPLE_EXAMPLE['volume_m3']*.000083*.2;h.invoke('measurement.start');r=finish(h);self.assertAlmostEqual(r['concentration_kg_m3'],.000083*.8,delta=1e-8)
|
| 168 |
+
def test_saturation_returns_null_with_qc(self):
|
| 169 |
+
h=make();calibrate(h);load(h,rt.SAMPLE_EXAMPLE);h.sample['background']=20.;h.invoke('measurement.start');r=finish(h);self.assertIsNone(r['concentration_kg_m3']);self.assertIn('SATURATED',r['qc'])
|
| 170 |
+
def test_outside_calibration_not_extrapolated(self):
|
| 171 |
+
h=make();calibrate(h);load(h,dict(rt.SAMPLE_EXAMPLE,dilution_factor=100));h.invoke('measurement.start');r=finish(h);self.assertIsNone(r['concentration_kg_m3']);self.assertIn('OUTSIDE_CALIBRATION',r['qc'])
|
| 172 |
+
def test_linear_reference_removes_linear_matrix_background(self):
|
| 173 |
+
areas=[]
|
| 174 |
+
for bg,slope in [(0.,0.),(.2,.1)]:
|
| 175 |
+
h=make();blank(h);load(h,dict(rt.STANDARD_EXAMPLE,background_absorbance=bg,background_slope=slope));h.invoke('measurement.start');areas.append(finish(h)['assays'][0]['integrated_absorbance_s'])
|
| 176 |
+
self.assertAlmostEqual(areas[0],areas[1],places=12)
|
| 177 |
+
def test_background_off_exposes_matrix_bias(self):
|
| 178 |
+
h=make();h.invoke('flame.extinguish');h.invoke('method.configure',**dict(rt.METHOD_EXAMPLE,background='off'));h.invoke('flame.ignite');h.step(.1);blank(h);load(h,dict(rt.STANDARD_EXAMPLE,background_absorbance=.2));h.invoke('measurement.start');r=finish(h);self.assertGreater(r['assays'][0]['integrated_absorbance_s'],.1)
|
| 179 |
+
def test_transmission_and_absorbance_arrays_log_relation(self):
|
| 180 |
+
h=make();blank(h);load(h,rt.STANDARD_EXAMPLE);h.invoke('measurement.start');h.step(.1);r=h.invoke('spectrum.read');self.assertEqual(len(r['wavelength_m']),21);np.testing.assert_allclose(-np.log10(r['normalized_transmission']),r['apparent_absorbance'],rtol=1e-12,atol=1e-15)
|
| 181 |
+
def test_repeat_consumption_and_sample_sd(self):
|
| 182 |
+
h=make(noise=1e-6);calibrate(h);h.invoke('flame.extinguish');h.invoke('method.configure',**dict(rt.METHOD_EXAMPLE,repeats=3));h.invoke('flame.ignite');h.step(.1);load(h,rt.SAMPLE_EXAMPLE);h.invoke('measurement.start');r=finish(h);self.assertEqual(len(r['assays']),3);self.assertAlmostEqual(h.sample['volume'],rt.SAMPLE_EXAMPLE['volume_m3']-3*rt.METHOD_EXAMPLE['injection_volume_m3']);self.assertGreater(r['sd_kg_m3'],0.)
|
| 183 |
+
def test_method_configure_preserves_prior_result_settings(self):
|
| 184 |
+
h=make();blank(h);old=h.invoke('result.read');h.invoke('flame.extinguish');h.invoke('method.configure',**dict(rt.METHOD_EXAMPLE,background='off'));self.assertEqual(old,h.invoke('result.read'))
|
| 185 |
+
def test_chunking_independent_complete_detector_windows(self):
|
| 186 |
+
hosts=[make(noise=1e-6) for _ in range(2)]
|
| 187 |
+
for h in hosts:load(h,rt.BLANK_EXAMPLE);h.invoke('measurement.start')
|
| 188 |
+
hosts[0].step(.4)
|
| 189 |
+
for _ in range(40):hosts[1].step(.01)
|
| 190 |
+
np.testing.assert_allclose([p['corrected_absorbance'] for p in hosts[0]._active['points']],[p['corrected_absorbance'] for p in hosts[1]._active['points']],atol=1e-12);self.assertAlmostEqual(hosts[0]._active['integrated_absorbance_s'],hosts[1]._active['integrated_absorbance_s'],places=13)
|
| 191 |
+
def test_no_partial_detector_sample_fabricated(self):
|
| 192 |
+
h=make();load(h,rt.BLANK_EXAMPLE);h.invoke('measurement.start');h.step(.002);self.assertIsNone(h._last_point);self.assertEqual(h._active['points'],[])
|
| 193 |
+
def test_agent_cannot_load_truth_or_read_private(self):
|
| 194 |
+
h=make();s=h.session();r=s.invoke(instance_id=h.instance_id,capability_id='sample.load',arguments=rt.SAMPLE_EXAMPLE,request_id='forbidden');self.assertEqual(r['error']['code'],'ACCESS_DENIED');self.assertNotIn('truth.ledger',s.read(instance_id=h.instance_id)['observations']);self.assertNotIn('sample.load',s.describe(instance_id=h.instance_id)['capabilities'])
|
| 195 |
+
def test_caller_cannot_choose_evaluator_role(self):
|
| 196 |
+
h=make()
|
| 197 |
+
with self.assertRaises(rt.ActionRejected):h.session('evaluator')
|
| 198 |
+
h.register_principal('trusted',visibility='evaluator');self.assertIn('truth.ledger',h.session('trusted').read(instance_id=h.instance_id)['observations'])
|
| 199 |
+
def test_request_dedup_and_argument_conflict(self):
|
| 200 |
+
h=make();h.invoke('flame.extinguish');s=h.session();args=dict(instance_id=h.instance_id,capability_id='burner.configure',arguments=rt.BURNER_EXAMPLE,request_id='one');r=s.invoke(**args);before=h.revision;self.assertEqual(r,s.invoke(**args));self.assertEqual(h.revision,before);bad=s.invoke(**dict(args,arguments=dict(rt.BURNER_EXAMPLE,height_m=.016)));self.assertEqual(bad['error']['code'],'REQUEST_CONFLICT')
|
| 201 |
+
def test_async_history_owned_and_preserves_old_result(self):
|
| 202 |
+
h=make();load(h,rt.BLANK_EXAMPLE);s=h.session();r=s.invoke(instance_id=h.instance_id,capability_id='measurement.start',arguments={},request_id='first');finish(h);op=r['operation_id'];old=s.poll(op);record=h._record_id;h.invoke('records.remove',record_id=record);h.invoke('measurement.start');finish(h);self.assertEqual(old,s.poll(op));h.register_principal('other')
|
| 203 |
+
with self.assertRaises(rt.ActionRejected):h.session('other').poll(op)
|
| 204 |
+
def test_cancel_history_partial_and_idempotent(self):
|
| 205 |
+
h=make();load(h,rt.BLANK_EXAMPLE);s=h.session();r=s.invoke(instance_id=h.instance_id,capability_id='measurement.start',arguments={},request_id='start');h.step(.04);a=s.cancel(r['operation_id'],'stop');h.step(.1);self.assertEqual(a,s.cancel(r['operation_id'],'stop'));self.assertEqual(s.poll(r['operation_id'])['status'],'cancelled')
|
| 206 |
+
def test_two_instances_isolate_rng_material_and_method(self):
|
| 207 |
+
a,b=make(),make();before=b.debug_snapshot();blank(a);self.assertEqual(before,b.debug_snapshot());self.assertIsNot(a.library,b.library)
|
| 208 |
+
def test_result_store_capacity_full_records(self):
|
| 209 |
+
h=make(fuel_inventory_mol=1.,oxidant_inventory_mol=10.);blank(h)
|
| 210 |
+
while len(h._records)<rt.RESULT_CAPACITY:
|
| 211 |
+
load(h,rt.BLANK_EXAMPLE);h.invoke('measurement.start');finish(h,dt=.1)
|
| 212 |
+
self.assertTrue(all(r['assays'][0]['points'] for r in h._records.values()));load(h,rt.BLANK_EXAMPLE);self.atomic_reject(h,'measurement.start','RESULT_STORE_FULL');first=next(iter(h._records));h.invoke('records.remove',record_id=first);h.invoke('measurement.start');finish(h);self.assertEqual(len(h._records),rt.RESULT_CAPACITY)
|
| 213 |
+
def test_export_json_csv_real_rows(self):
|
| 214 |
+
h=make();blank(h);r=h.invoke('result.read');self.assertEqual(json.loads(h.invoke('result.export',format='json')['content']),r);import csv,io;rows=list(csv.DictReader(io.StringIO(h.invoke('result.export',format='csv')['content'])));self.assertEqual(len(rows),len(r['assays'][0]['points']));self.assertAlmostEqual(float(rows[0]['time_s']),r['assays'][0]['points'][0]['time_s'])
|
| 215 |
+
def test_unsupported_actions_atomic(self):
|
| 216 |
+
h=make()
|
| 217 |
+
for cap in rt.UNSUPPORTED:self.atomic_reject(h,cap,'UNSUPPORTED')
|
| 218 |
+
def test_exported_error_codes_are_valid_and_include_real_failures(self):
|
| 219 |
+
meta=rt.export_jena_contraa800_contract_metadata()
|
| 220 |
+
for name,cap in meta['capabilities'].items():
|
| 221 |
+
for error in cap['errors']:
|
| 222 |
+
with self.subTest(capability=name,code=error['code']):self.assertRegex(error['code'],r'^[A-Z][A-Z0-9_]*\Z')
|
| 223 |
+
self.assertIn('SAMPLER_PARK_REQUIRED',{e['code'] for e in meta['capabilities']['cover.set']['errors']})
|
| 224 |
+
self.assertIn('GAS_EXHAUSTED',{e['code'] for e in meta['capabilities']['measurement.start']['errors']})
|
| 225 |
+
def test_metadata_and_actual_values_match_schema(self):
|
| 226 |
+
h=make();blank(h);meta=rt.export_jena_contraa800_contract_metadata()
|
| 227 |
+
for key,value in h.read('evaluator').items():rt.validate(meta['state_slots'][key]['value_schema'],value)
|
| 228 |
+
for key in ['process.measure','result.read','spectrum.read','blank.read','records.list','product.read']:rt.validate(rt.CAPS[key][1],h.invoke(key))
|
| 229 |
+
for key,cap in meta['capabilities'].items():
|
| 230 |
+
rt.validate(cap['input_schema'],cap['example_arguments'])
|
| 231 |
+
for effect in cap['state_effects']:self.assertIn(effect['state_id'],meta['state_slots'])
|
| 232 |
+
def test_source_negative_or_nonfinite_concentration_rejected(self):
|
| 233 |
+
for value in [float('nan'),-.1]:
|
| 234 |
+
h=make();h.templates['bad']=dict(element='Cu',concentration_kg_m3=value);self.atomic_reject(h,'sample.load','LIQUID_CONCENTRATION_REQUIRED',**dict(rt.SAMPLE_EXAMPLE,template_id='bad'))
|
| 235 |
+
|
| 236 |
+
def test_one_celsius_program_increment(self):
|
| 237 |
+
h=make('furnace');p=copy.deepcopy(rt.FURNACE_PROGRAM_EXAMPLE);p[0]['temperature_k']+=.1;self.atomic_reject(h,'method.configure','FURNACE_TEMPERATURE_INCREMENT',**dict(rt.FURNACE_METHOD_EXAMPLE,furnace_program=p))
|
| 238 |
+
def test_burner_geometry_change_invalidates_conditional_calibration(self):
|
| 239 |
+
h=make();calibrate(h);h.invoke('flame.extinguish');h.invoke('burner.configure',height_m=.012,angle_rad=.1);self.assertFalse(h._blank_valid());self.assertFalse(h._calibration_ready())
|
| 240 |
+
def test_outside_numerical_liquid_domain_rejected(self):
|
| 241 |
+
h=make();h.templates['overflow']=dict(element='Cu',concentration_kg_m3=1e308);self.atomic_reject(h,'sample.load','LIQUID_MODEL_DOMAIN',**dict(rt.SAMPLE_EXAMPLE,template_id='overflow'))
|
| 242 |
+
def test_park_retract_then_rotate_respects_elapsed_time(self):
|
| 243 |
+
h=make('furnace');h.injector=.1;h.sampler_arm=math.pi;h.invoke('sampler.park');h.step(.1);self.assertAlmostEqual(h.injector,.06);self.assertEqual(h.sampler_arm,math.pi);h.step(.15);self.assertAlmostEqual(h.injector,0.);self.assertEqual(h.sampler_arm,math.pi);h.step(.05);self.assertLess(h.sampler_arm,math.pi)
|
| 244 |
+
|
| 245 |
+
if __name__=='__main__':unittest.main()
|
tests/test_asset_jena_multix.py
ADDED
|
@@ -0,0 +1,212 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Finite combustion and observed calibration regressions; fixtures are expressly synthetic."""
|
| 2 |
+
import copy,hashlib,importlib.util,json,math,re,sys,unittest
|
| 3 |
+
from pathlib import Path
|
| 4 |
+
import numpy as np
|
| 5 |
+
ROOT=Path(__file__).resolve().parents[1];sys.path.insert(0,str(ROOT/'scripts'))
|
| 6 |
+
from asset_runtime.jena_multix import *
|
| 7 |
+
LIB={'compounds':{'standard':{'chlorine_equivalent_mass_kg':9.63e-9,'calibration_eligible':True,'evidence':'synthetic_test_fixture'},'unknown':{'chlorine_equivalent_mass_kg':9.05e-9,'calibration_eligible':False,'evidence':'synthetic_test_fixture'},'reference_only':{'reported_recovery_fraction':.95,'evidence':'synthetic_test_fixture'}}}
|
| 8 |
+
def ready(horizontal=False,mode=None,**plant):
|
| 9 |
+
r=JenaMultixRuntime('unit',LIB);r.invoke('plant.configure',**(PLANT_EXAMPLE|dict(optional_boat_drive_installed=horizontal,optional_pox_installed=True)|plant))
|
| 10 |
+
if horizontal:
|
| 11 |
+
for d in ['main_left','main_right']:r.invoke('cover.set',door=d,opened=True)
|
| 12 |
+
r.invoke('direction.set',direction='horizontal');r.invoke('tube.configure',tube_type='multi_purpose');r.step(.6)
|
| 13 |
+
for d in ['main_left','main_right']:r.invoke('cover.set',door=d,opened=False)
|
| 14 |
+
r.invoke('abd.power',enabled=True)
|
| 15 |
+
r.invoke('method.configure',**(METHOD_EXAMPLE|dict(mode=mode or ('TX' if horizontal else 'AOX'))))
|
| 16 |
+
if mode=='EOX' and not horizontal:
|
| 17 |
+
for d in ['main_left','main_right']:r.invoke('cover.set',door=d,opened=True)
|
| 18 |
+
r.invoke('tube.configure',tube_type='multi_purpose')
|
| 19 |
+
for d in ['main_left','main_right']:r.invoke('cover.set',door=d,opened=False)
|
| 20 |
+
r.invoke('cover.set',door='chlorine',opened=True);r.invoke('cell.prepare',cell_type='sensitive');r.invoke('cover.set',door='chlorine',opened=False);r.invoke('power.set',enabled=True);r.invoke('gas.set',enabled=True);r.step(.6);return r
|
| 21 |
+
def load(r,kind='sample',fraction=.2,**extra):
|
| 22 |
+
form={'AOX':'loaded_carbon','EOX':'extract','POX':'purged_gas','TX':'solid'}[r.method['mode']]
|
| 23 |
+
if r.direction=='horizontal':
|
| 24 |
+
r.step(1.)
|
| 25 |
+
if not r.port_open:r.invoke('sample_port.toggle');r.step(.5)
|
| 26 |
+
if r.sample:r.invoke('sample.unload',recipient_id='returned')
|
| 27 |
+
r.invoke('product.drain',recipient_id='waste')
|
| 28 |
+
a=SAMPLE_EXAMPLE|dict(template_id='' if kind=='blank' else 'standard' if kind=='standard' else 'unknown',kind=kind,reference_fraction=fraction,input_form=form,volume_m3=1e-8 if form=='extract' else 0.)|extra
|
| 29 |
+
r.invoke('sample.load',**a)
|
| 30 |
+
if r.direction=='horizontal':r.invoke('sample_port.toggle');r.step(.5)
|
| 31 |
+
return a
|
| 32 |
+
def measure(r,kind='sample',fraction=.2,**extra):
|
| 33 |
+
load(r,kind,fraction,**extra);r.invoke('measurement.start');r.step(r.method['integration_s']);return r.invoke('result.read')
|
| 34 |
+
def calibrated(**kwargs):
|
| 35 |
+
r=ready(**kwargs);measure(r,'blank');ids=[measure(r,'standard',f)['record_id'] for f in [.12,.2,.3]];r.invoke('calibration.fit',curve_id='observed',record_ids=ids);r.invoke('calibration.select',curve_id='observed');return r
|
| 36 |
+
def state(r):return json.dumps(r.read('evaluator'),sort_keys=True),r.time_s,r.revision,json.dumps(r._rng.bit_generator.state,sort_keys=True)
|
| 37 |
+
class MultiX(unittest.TestCase):
|
| 38 |
+
def rejected(self,r,cap,code=None,**args):
|
| 39 |
+
before=state(r)
|
| 40 |
+
with self.assertRaises(ActionRejected) as ex:r.invoke(cap,**args)
|
| 41 |
+
if code:self.assertEqual(str(ex.exception),code)
|
| 42 |
+
self.assertEqual(before,state(r))
|
| 43 |
+
def test_01_actual_blank_three_standard_inference(self):
|
| 44 |
+
r=calibrated();q=measure(r);self.assertAlmostEqual(q['chlorine_equivalent_mass_kg'],9.05e-9*.2,places=19);self.assertGreater(q['observed_charge_c'],0);self.assertNotEqual(q['faraday_equivalent_mass_kg'],q['chlorine_equivalent_mass_kg'])
|
| 45 |
+
def test_02_faraday_silver_charge(self):
|
| 46 |
+
r=ready();measure(r,'blank');measure(r);L=r._ledger();self.assertAlmostEqual(L['charge_generated_c'],(L['silver_precipitate_mol']+L['silver_removed_precipitate_mol'])*FARADAY,places=13)
|
| 47 |
+
def test_03_complete_window_integrals(self):
|
| 48 |
+
r=ready();q=measure(r,'blank');self.assertAlmostEqual(sum((w['end_s']-w['start_s'])*w['current_a'] for w in q['windows']),q['observed_charge_c'],places=15);self.assertEqual(len(q['windows']),60)
|
| 49 |
+
def test_04_cancel_partial_window_preserved(self):
|
| 50 |
+
r=ready();measure(r,'blank');load(r);r.invoke('measurement.start');r.step(.735);r.invoke('measurement.stop');q=r._result();self.assertEqual(q['phase'],'cancelled');self.assertAlmostEqual(q['windows'][-1]['end_s']-q['windows'][-1]['start_s'],.135,places=10);self.assertGreater(r.sample['burned'],0);self.assertLess(r.sample['burned'],1)
|
| 51 |
+
def test_05_cancel_not_fake_return(self):
|
| 52 |
+
r=ready();measure(r,'blank');load(r);r.invoke('measurement.start');r.step(.7);r.invoke('measurement.stop');ret=r.invoke('sample.unload',recipient_id='host');self.assertAlmostEqual(ret['unburned_mass_kg'],2.5e-5,places=13);self.assertLess(ret['unburned_mass_kg']+ret['residue_mass_kg'],5e-5)
|
| 53 |
+
def test_06_mass_balance(self):
|
| 54 |
+
r=ready();measure(r,'blank');measure(r);L=r._ledger();self.assertLess(abs(L['mass_residual_kg']),1e-16);self.assertGreater(L['reaction_products_kg'],0)
|
| 55 |
+
def test_07_equivalent_balance_cancel_drain(self):
|
| 56 |
+
r=ready();measure(r,'blank');load(r);r.invoke('measurement.start');r.step(.7);r.invoke('measurement.stop');r.invoke('sample.unload',recipient_id='host');r.invoke('product.drain',recipient_id='waste');L=json.loads(r._ledger()['equivalent_ledger_json']);self.assertLess(abs(L['residual_mol']),1e-16);self.assertGreater(L['drained_mol'],0)
|
| 57 |
+
def test_08_gas_balance_and_Ar_mode(self):
|
| 58 |
+
r=ready(horizontal=True);measure(r,'blank');measure(r);g=json.loads(r._ledger()['gas_ledger_json']);self.assertLess(abs(g['oxygen_residual_mol']),1e-9);self.assertLess(abs(g['argon_residual_mol']),1e-9);self.assertGreater(g['argon_exhaust_mol'],0)
|
| 59 |
+
def test_09_thermal_balance_cooling(self):
|
| 60 |
+
r=ready();r.invoke('power.set',enabled=False);r.step(1.);L=r._ledger();self.assertLess(abs(L['energy_residual_j']),1e-7);self.assertAlmostEqual(r.temperature,298.15)
|
| 61 |
+
def test_10_template_query_only(self):
|
| 62 |
+
r=ready();self.assertIn('reported_recovery',r.invoke('template.read',substance_id='reference_only')['template_json']);self.rejected(r,'sample.load','REFERENCE_QUERY_ONLY',**(SAMPLE_EXAMPLE|dict(template_id='reference_only')))
|
| 63 |
+
def test_11_unknown_not_standard(self):
|
| 64 |
+
r=ready();self.rejected(r,'sample.load','REFERENCE_NOT_CALIBRATION_ELIGIBLE',**(SAMPLE_EXAMPLE|dict(template_id='unknown',kind='standard')))
|
| 65 |
+
def test_12_missing_preparation_ack(self):
|
| 66 |
+
r=ready();self.rejected(r,'sample.load','PREPARATION_ACK_REQUIRED',**(SAMPLE_EXAMPLE|dict(template_id='unknown',accept_prepared_input=False)))
|
| 67 |
+
def test_13_wrong_mode_input(self):
|
| 68 |
+
r=ready();self.rejected(r,'sample.load','INPUT_FORM_MISMATCH',**(SAMPLE_EXAMPLE|dict(template_id='unknown',input_form='liquid')))
|
| 69 |
+
def test_14_invalid_liquid_volume(self):
|
| 70 |
+
r=ready(mode='EOX');self.rejected(r,'sample.load','INVALID_VOLUME',**(SAMPLE_EXAMPLE|dict(template_id='unknown',input_form='extract',volume_m3=0.)))
|
| 71 |
+
def test_15_excess_sample100mg(self):
|
| 72 |
+
r=ready();self.rejected(r,'sample.load','INVALID_ARGUMENT',**(SAMPLE_EXAMPLE|dict(template_id='unknown',mass_kg=.000101)))
|
| 73 |
+
def test_16_excess_volume100uL(self):
|
| 74 |
+
r=ready(mode='EOX');self.rejected(r,'sample.load','INVALID_ARGUMENT',**(SAMPLE_EXAMPLE|dict(template_id='unknown',input_form='extract',volume_m3=1.01e-7)))
|
| 75 |
+
def test_17_no_blank_no_measure(self):
|
| 76 |
+
r=ready();load(r);self.rejected(r,'measurement.start','BLANK_REQUIRED')
|
| 77 |
+
def test_18_consumed_no_repeat(self):
|
| 78 |
+
r=ready();measure(r,'blank');self.rejected(r,'measurement.start','SAMPLE_ALREADY_CONSUMED')
|
| 79 |
+
def test_19_thermal_target_finite(self):
|
| 80 |
+
r=ready();old=r.temperature;r.invoke('temperature.set',temperature_k=1373.15);self.assertEqual(r.temperature,old);r.step(.02);self.assertGreater(r.temperature,old);self.assertLess(r.temperature,1373.15)
|
| 81 |
+
def test_20_low_temperature_configurable_not_ready(self):
|
| 82 |
+
r=ready();r.invoke('method.configure',**(METHOD_EXAMPLE|dict(temperature_k=973.15)));r.step(.3);self.assertFalse(r._ready())
|
| 83 |
+
def test_21_overheated_setting_rejected(self):
|
| 84 |
+
r=ready();self.rejected(r,'temperature.set','INVALID_ARGUMENT',temperature_k=1373.16)
|
| 85 |
+
def test_22_cold_swap_requires_doors(self):
|
| 86 |
+
r=JenaMultixRuntime(library=LIB);r.invoke('plant.configure',**PLANT_EXAMPLE);self.rejected(r,'direction.set','MAINTENANCE_DOOR_CLOSED',direction='vertical')
|
| 87 |
+
def test_23_hot_door_rejected(self):
|
| 88 |
+
r=ready();self.rejected(r,'cover.set','COLD_ISOLATED_MAINTENANCE_REQUIRED',door='main_left',opened=True)
|
| 89 |
+
def test_24_independent_doors(self):
|
| 90 |
+
r=JenaMultixRuntime(library=LIB);r.invoke('plant.configure',**PLANT_EXAMPLE);r.invoke('cover.set',door='main_left',opened=True);v=r.read();self.assertEqual(v['cover.main_left_angle_rad'],1.6);self.assertEqual(v['cover.main_right_angle_rad'],0)
|
| 91 |
+
def test_25_horizontal_requires_option(self):
|
| 92 |
+
r=JenaMultixRuntime(library=LIB);r.invoke('plant.configure',**PLANT_EXAMPLE)
|
| 93 |
+
for d in ['main_left','main_right']:r.invoke('cover.set',door=d,opened=True)
|
| 94 |
+
self.rejected(r,'direction.set','OPTION_NOT_INSTALLED',direction='horizontal')
|
| 95 |
+
def test_26_pox_requires_option(self):
|
| 96 |
+
r=JenaMultixRuntime(library=LIB);r.invoke('plant.configure',**PLANT_EXAMPLE);self.rejected(r,'method.configure','OPTION_NOT_INSTALLED',**(METHOD_EXAMPLE|dict(mode='POX')))
|
| 97 |
+
def test_27_TX_requires_horizontal(self):
|
| 98 |
+
r=ready();self.rejected(r,'method.configure','DIRECTION_MODE_MISMATCH',**(METHOD_EXAMPLE|dict(mode='TX')))
|
| 99 |
+
def test_28_POX_conditioned_gas_chain(self):
|
| 100 |
+
r=ready(mode='POX');measure(r,'blank');q=measure(r);self.assertEqual(q['mode'],'POX');self.assertGreater(q['observed_charge_c'],0);self.assertIsNone(q['chlorine_equivalent_mass_kg'])
|
| 101 |
+
def test_29_EOX_conditioned_extract_chain(self):
|
| 102 |
+
r=ready(mode='EOX');measure(r,'blank');q=measure(r);self.assertEqual(q['mode'],'EOX');self.assertGreater(q['observed_charge_c'],0)
|
| 103 |
+
def test_30_TX_actual_calibration(self):
|
| 104 |
+
r=calibrated(horizontal=True);q=measure(r);self.assertAlmostEqual(q['chlorine_equivalent_mass_kg'],1.81e-9,places=17)
|
| 105 |
+
def test_31_F_not_detected(self):
|
| 106 |
+
r=ready();measure(r,'blank');q=measure(r,template_id='',halogen_moles=[{'element':'F','amount_mol':1e-8}]);self.assertAlmostEqual(q['blank_corrected_charge_c'],0.,places=15);L=json.loads(r._ledger()['species_ledger_json']);self.assertEqual(L['F']['registered_mol'],1e-8)
|
| 107 |
+
def test_32_ClBrI_same_moles_charge(self):
|
| 108 |
+
charges=[]
|
| 109 |
+
for e in ['Cl','Br','I']:
|
| 110 |
+
r=ready();measure(r,'blank');q=measure(r,template_id='',halogen_moles=[{'element':e,'amount_mol':4e-8}]);charges.append(q['blank_corrected_charge_c'])
|
| 111 |
+
self.assertTrue(np.allclose(charges,charges[0],rtol=1e-12,atol=0))
|
| 112 |
+
def test_33_cell_current_cap(self):
|
| 113 |
+
r=ready();measure(r,'blank');q=measure(r,fraction=1.);self.assertTrue(all(w['current_a']<=.001*PLANT_EXAMPLE['detector_gain']+PLANT_EXAMPLE['baseline_current_a']+1e-12 for w in q['windows']));self.assertGreater(r.cell_pending,0)
|
| 114 |
+
def test_34_cell_ranges_not_merged(self):
|
| 115 |
+
self.assertEqual(CELLS['high_sensitive']['max_kg'],1e-8);self.assertEqual(CELLS['sensitive']['min_kg'],1e-9);self.assertEqual(CELLS['high_concentration']['volume_m3'],.00012)
|
| 116 |
+
def test_35_high_sensitive_open_tube_forbidden(self):
|
| 117 |
+
r=JenaMultixRuntime(library=LIB);r.invoke('plant.configure',**PLANT_EXAMPLE);r.invoke('cover.set',door='chlorine',opened=True);self.rejected(r,'cell.prepare','CELL_TUBE_MISMATCH',cell_type='high_sensitive')
|
| 118 |
+
def test_36_silver_exhaustion_real_failure(self):
|
| 119 |
+
r=ready(silver_initial_mol=1e-9);measure(r,'blank');q=measure(r);self.assertEqual(q['phase'],'failed');self.assertGreater(r.cell_pending,0);self.assertIsNone(q['chlorine_equivalent_mass_kg'])
|
| 120 |
+
def test_37_gas_stop_cancels(self):
|
| 121 |
+
r=ready();measure(r,'blank');load(r);r.invoke('measurement.start');r.step(.7);r.invoke('gas.set',enabled=False);self.assertEqual(r.phase,'cancelled');self.assertGreater(r.sample['burned'],0)
|
| 122 |
+
def test_38_power_stop_cancels(self):
|
| 123 |
+
r=ready();measure(r,'blank');load(r);r.invoke('measurement.start');r.step(.7);r.invoke('power.set',enabled=False);self.assertEqual(r.phase,'cancelled')
|
| 124 |
+
def test_39_PORT_locked_running(self):
|
| 125 |
+
r=ready(horizontal=True);load(r,'blank');r.invoke('measurement.start');self.rejected(r,'sample_port.toggle','BUSY')
|
| 126 |
+
def test_40_ABD_stop_requires_cycle(self):
|
| 127 |
+
r=ready(horizontal=True);r.invoke('abd.stop');self.assertTrue(r.abd_stopped);r.invoke('abd.power',enabled=True);self.assertTrue(r.abd_stopped);r.invoke('abd.power',enabled=False);r.invoke('abd.power',enabled=True);self.assertFalse(r.abd_stopped)
|
| 128 |
+
def test_41_ABD_STOP_stops_motion(self):
|
| 129 |
+
r=ready(horizontal=True);load(r,'blank');r.invoke('measurement.start');r.step(.2);q=r.injection;r.invoke('abd.stop');r.step(.2);self.assertEqual(r.injection,q);self.assertEqual(r.phase,'cancelled')
|
| 130 |
+
def test_42_liquid_cooldown_not_accelerated(self):
|
| 131 |
+
r=ready(horizontal=True);q=measure(r,'blank',input_form='liquid',volume_m3=1e-8);self.assertEqual(r.cooldown,200);r.step(1);self.assertAlmostEqual(r.cooldown,199);self.rejected(r,'sample_port.toggle','ABD_NOT_READY')
|
| 132 |
+
def test_43_method_history_frozen(self):
|
| 133 |
+
r=ready();q=measure(r,'blank');r.invoke('method.configure',**(METHOD_EXAMPLE|dict(window_s=.3)));self.assertEqual(r._result(),q)
|
| 134 |
+
def test_44_foreign_config_calibration_rejected(self):
|
| 135 |
+
r=calibrated();r.invoke('method.configure',**(METHOD_EXAMPLE|dict(integration_s=13.)));self.rejected(r,'calibration.select','CALIBRATION_SIGNATURE_MISMATCH',curve_id='observed')
|
| 136 |
+
def test_45_fake_standard_record_rejected(self):
|
| 137 |
+
r=ready();q=measure(r,'blank');self.rejected(r,'calibration.fit','ACTUAL_STANDARD_REQUIRED',curve_id='bad',record_ids=[q['record_id'],'other','third'])
|
| 138 |
+
def test_46_duplicate_standard_not_fit(self):
|
| 139 |
+
r=ready();self.rejected(r,'calibration.fit','DUPLICATE_STANDARD',curve_id='bad',record_ids=['a','a','a'])
|
| 140 |
+
def test_47_agent_hidden_sample_denied(self):
|
| 141 |
+
r=ready();s=r.session();before=state(r);q=s.invoke(instance_id=r.instance_id,capability_id='sample.load',arguments=SAMPLE_EXAMPLE,request_id='x');self.assertEqual(q['error']['code'],'ACCESS_DENIED');self.assertEqual(before,state(r));self.assertNotIn('truth.ledger',s.read(instance_id=r.instance_id)['observations'])
|
| 142 |
+
def test_48_discovery_query_pure(self):
|
| 143 |
+
r=ready();before=state(r);r.describe();r.session().read(instance_id=r.instance_id);r.invoke('template.read',substance_id='unknown');self.assertEqual(before,state(r))
|
| 144 |
+
def test_49_de_duplicate_and_conflict(self):
|
| 145 |
+
r=ready();s=r.session();q=s.invoke(instance_id=r.instance_id,capability_id='power.set',arguments={'enabled':True},request_id='r');rev=r.revision;self.assertEqual(q,s.invoke(instance_id=r.instance_id,capability_id='power.set',arguments={'enabled':True},request_id='r'));self.assertEqual(rev,r.revision);self.assertEqual(s.invoke(instance_id=r.instance_id,capability_id='power.set',arguments={'enabled':False},request_id='r')['error']['code'],'REQUEST_CONFLICT')
|
| 146 |
+
def test_50_history_poll_and_ownership(self):
|
| 147 |
+
r=ready();r.register_principal('other');load(r,'blank');s=r.session();q=s.invoke(instance_id=r.instance_id,capability_id='measurement.start',arguments={},request_id='op');r.step(12);old=s.poll(q['operation_id']);measure(r,'blank');self.assertEqual(old,s.poll(q['operation_id']));self.assertRaises(ActionRejected,r.session('other').poll,q['operation_id'])
|
| 148 |
+
def test_51_poll_cancellation_idempotent(self):
|
| 149 |
+
r=ready();load(r,'blank');s=r.session();q=s.invoke(instance_id=r.instance_id,capability_id='measurement.start',arguments={},request_id='start');r.step(.135);a=s.cancel(q['operation_id'],'cancel');self.assertEqual(a,s.cancel(q['operation_id'],'cancel'));self.assertEqual(s.poll(q['operation_id'])['status'],'cancelled')
|
| 150 |
+
def test_52_dual_instances(self):
|
| 151 |
+
a=ready();b=ready();before=state(b);measure(a,'blank');self.assertEqual(before,state(b))
|
| 152 |
+
def test_53_finite_input_rejection(self):
|
| 153 |
+
r=ready()
|
| 154 |
+
for value in [True,float('nan'),float('inf'),-1.,1400.]:self.rejected(r,'temperature.set','INVALID_ARGUMENT',temperature_k=value)
|
| 155 |
+
def test_54_step_partition(self):
|
| 156 |
+
a=ready();b=ready();load(a,'blank');load(b,'blank');a.invoke('measurement.start');b.invoke('measurement.start');a.step(1.)
|
| 157 |
+
for _ in range(50):b.step(.02)
|
| 158 |
+
self.assertAlmostEqual(a.charge,b.charge,places=15);self.assertAlmostEqual(a.temperature,b.temperature,places=10)
|
| 159 |
+
def test_55_sampling_window_not_read_time(self):
|
| 160 |
+
r=ready();q=measure(r,'blank');end=q['windows'][-1]['end_s'];r.step(.3);v=r.session().read(instance_id=r.instance_id)['observations']['detector.current_a'];self.assertAlmostEqual(v['sample_time_s'],end);self.assertLess(v['sample_time_s'],r.time_s)
|
| 161 |
+
def test_56_JSON_CSV_roundtrip(self):
|
| 162 |
+
import csv,io
|
| 163 |
+
r=ready();q=measure(r,'blank');self.assertEqual(json.loads(r.invoke('result.export',format='json')['content']),q);rows=list(csv.DictReader(io.StringIO(r.invoke('result.export',format='csv')['content'])));self.assertEqual(len(rows),len(q['windows']));self.assertAlmostEqual(sum(float(v['observed_charge_c']) for v in rows),q['observed_charge_c'])
|
| 164 |
+
def test_57_complete_metadata_schema(self):
|
| 165 |
+
p=ROOT/'skills/chemistry-lab-assets/scripts/asset_tool.py';sp=importlib.util.spec_from_file_location('asset_tool_multix',p);t=importlib.util.module_from_spec(sp);sp.loader.exec_module(t);schema=json.loads((ROOT/'skills/chemistry-lab-assets/assets/asset-contract.schema.json').read_text());m=export_jena_multix_contract_metadata()
|
| 166 |
+
for key,group in [('capability',m['capabilities']),('slot',m['state_slots'])]:
|
| 167 |
+
for name,value in group.items():
|
| 168 |
+
errors=t.validate_value(value,{'$ref':'#/$defs/'+key},schema);self.assertEqual(errors,[],(name,errors))
|
| 169 |
+
for k,v in m['capabilities'].items():
|
| 170 |
+
validate(v['input_schema'],v['example_arguments']);self.assertTrue(all(re.fullmatch('[A-Z][A-Z0-9_]*',e['code']) for e in v['errors']))
|
| 171 |
+
def test_58_actual_return_schemas(self):
|
| 172 |
+
r=ready();q=measure(r,'blank');validate(RESULT,q)
|
| 173 |
+
for k,a in [('process.measure',{}),('signal.read',{}),('blank.read',{}),('records.list',{}),('product.read',{}),('result.export',{'format':'json'})]:validate(CAPS[k][1],r.invoke(k,**a))
|
| 174 |
+
def test_59_unsupported_never_success(self):
|
| 175 |
+
r=ready()
|
| 176 |
+
for k in UNSUPPORTED:self.rejected(r,k,'UNSUPPORTED')
|
| 177 |
+
def test_60_no_hidden_truth_in_result(self):
|
| 178 |
+
r=ready();measure(r,'blank');q=measure(r);j=json.dumps(q);self.assertNotIn('reference_mass_kg',j);self.assertNotIn('species',q);self.assertNotIn('truth',q);self.assertIsNone(q['chlorine_equivalent_mass_kg'])
|
| 179 |
+
def test_61_oxygen_depletion_failure(self):
|
| 180 |
+
r=ready(oxygen_supply_mol=.001);load(r,'blank');r.invoke('measurement.start');r.step(1);self.assertEqual(r.phase,'failed');g=json.loads(r._ledger()['gas_ledger_json']);self.assertLess(abs(g['oxygen_residual_mol']),1e-12)
|
| 181 |
+
def test_62_records_remove_preserves_live(self):
|
| 182 |
+
r=ready();q=measure(r,'blank');r.invoke('records.remove',record_id=q['record_id']);self.assertEqual(r._result(),q);self.assertEqual(r.invoke('records.list')['record_ids'],[])
|
| 183 |
+
def test_63_late_mode_change_does_not_reinterpret_sample(self):
|
| 184 |
+
r=ready();load(r,'blank');r.invoke('method.configure',**(METHOD_EXAMPLE|dict(mode='POX')));self.rejected(r,'measurement.start','INPUT_FORM_MISMATCH')
|
| 185 |
+
def test_64_impossible_window_rejected(self):
|
| 186 |
+
r=ready();self.rejected(r,'method.configure','INVALID_TIME_WINDOW',**(METHOD_EXAMPLE|dict(integration_s=.5)))
|
| 187 |
+
def test_65_horizontal_AOX_requires_argon(self):
|
| 188 |
+
r=ready(horizontal=True,mode='AOX');self.assertTrue(r._needs_argon());a=r.argon_remaining;r.step(.1);self.assertLess(r.argon_remaining,a)
|
| 189 |
+
def test_66_source_stage_cannot_be_forged(self):
|
| 190 |
+
r=ready(mode='EOX');r.templates['carbon']={'chlorine_equivalent_mass_kg':1e-9,'input_form':'loaded_carbon','supported_modes':['AOX'],'physical_input_eligible':True};self.rejected(r,'sample.load','SOURCE_STAGE_MISMATCH',**(SAMPLE_EXAMPLE|dict(template_id='carbon',input_form='extract',volume_m3=1e-8)))
|
| 191 |
+
def test_67_equivalent_cannot_exceed_gross_mass(self):
|
| 192 |
+
r=ready();self.rejected(r,'sample.load','EQUIVALENT_EXCEEDS_SAMPLE_MASS',**(SAMPLE_EXAMPLE|dict(template_id='unknown',mass_kg=1e-9,reference_fraction=1.)))
|
| 193 |
+
def test_68_nonliquid_volume_not_source_water(self):
|
| 194 |
+
r=ready();self.rejected(r,'sample.load','LIQUID_VOLUME_ONLY',**(SAMPLE_EXAMPLE|dict(template_id='unknown',volume_m3=1e-8)))
|
| 195 |
+
def test_69_original_water_query_only(self):
|
| 196 |
+
r=ready(mode='EOX');r.templates['water']={'basis':'chlorine_equivalent','concentration_kg_m3':.01,'physical_input_eligible':False};self.rejected(r,'sample.load','REFERENCE_QUERY_ONLY',**(SAMPLE_EXAMPLE|dict(template_id='water',input_form='extract',volume_m3=1e-8)))
|
| 197 |
+
def test_70_liquid_volume_cancel_balance(self):
|
| 198 |
+
r=ready(mode='EOX');measure(r,'blank');load(r);r.invoke('measurement.start');r.step(.7);r.invoke('measurement.stop');r.invoke('sample.unload',recipient_id='host');L=json.loads(r._ledger()['volume_ledger_json']);self.assertLess(abs(L['residual_m3']),1e-20);self.assertGreater(L['consumed_original_liquid_m3'],0);self.assertGreater(L['returned_m3'],0)
|
| 199 |
+
def test_71_sample_form_part_of_calibration(self):
|
| 200 |
+
r=calibrated(horizontal=True);before=r._key();load(r,kind='blank',input_form='liquid',volume_m3=1e-8);self.assertNotEqual(before,r._key());self.rejected(r,'calibration.select','CALIBRATION_SIGNATURE_MISMATCH',curve_id='observed')
|
| 201 |
+
def test_72_finite_boat_feed_cannot_burn_early(self):
|
| 202 |
+
r=ready(horizontal=True,feed_speed_m_s=.01);load(r,'blank');self.rejected(r,'measurement.start','FEED_TIME_TOO_SHORT')
|
| 203 |
+
def test_73_actual_private_library_stages(self):
|
| 204 |
+
j=_load_actual_library();r=ready();r.templates=j['compounds'];r.invoke('sample.load',**(SAMPLE_EXAMPLE|dict(template_id='aox_linear_100_r1_c1')));self.assertGreater(r.sample['equiv'],0);self.assertEqual(j['compounds']['tx_paper_ecf']['input_form'],'solid')
|
| 205 |
+
def test_74_agent_readonly_direction_and_host_invocation(self):
|
| 206 |
+
r=ready();meta=export_jena_multix_contract_metadata()['state_slots']['furnace.direction'];self.assertEqual(meta['access'],'read_only');self.assertIsNone(meta['write_via']);self.assertEqual(r.session().read(instance_id=r.instance_id,state_ids=['furnace.direction'])['observations']['furnace.direction']['value'],'vertical');self.assertRaises(ActionRejected,r.session().write,instance_id=r.instance_id,state_id='furnace.direction',value='horizontal',request_id='forbidden')
|
| 207 |
+
def test_75_observed_current_endpoint_tail_rejected(self):
|
| 208 |
+
r=ready();measure(r,'blank');q=measure(r,kind='standard',fraction=1.);self.assertTrue(any('endpoint unresolved' in x for x in q['quality']));self.assertIsNone(q['chlorine_equivalent_mass_kg']);self.assertGreater(q['windows'][-1]['current_a'],.0005);self.rejected(r,'calibration.fit','INVALID_STANDARD_OBSERVATION',curve_id='bad',record_ids=[q['record_id'],'x','y'])
|
| 209 |
+
def test_76_liquid_cooling_waits_for_return_to_sluice(self):
|
| 210 |
+
r=ready(horizontal=True);load(r,'blank',input_form='liquid',volume_m3=1e-8);r.invoke('measurement.start');r.step(.6);self.assertGreater(r.injection,.2);r.invoke('measurement.stop');r.step(.1);self.assertGreater(r.injection,0);self.assertEqual(r.cooldown,200.)
|
| 211 |
+
def _load_actual_library():return json.loads((ROOT/TEMPLATE_REL).read_text())
|
| 212 |
+
if __name__=='__main__':unittest.main()
|
tests/test_asset_knauer_k7400s.py
ADDED
|
@@ -0,0 +1,86 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from pathlib import Path
|
| 2 |
+
import sys,unittest,copy,math,importlib.util,json
|
| 3 |
+
ROOT=Path(__file__).resolve().parents[1];sys.path.insert(0,str(ROOT/'scripts'))
|
| 4 |
+
from asset_runtime import knauer_k7400s as m
|
| 5 |
+
OBSERVED=set()
|
| 6 |
+
def call(r,k,**a):
|
| 7 |
+
v=r.invoke(k,**a);OBSERVED.add(k);return v
|
| 8 |
+
def ready(plant=None,volume=150e-9):
|
| 9 |
+
r=m.KnauerK7400sRuntime();call(r,'plant.configure',**(plant or m.PLANT_EXAMPLE));call(r,'method.configure',**dict(m.METHOD_EXAMPLE,sample_volume_m3=volume));call(r,'power.set',enabled=True);r.step(300);return r
|
| 10 |
+
def load(r,sample):call(r,'head.position',position='raised');call(r,'sample.load',**sample);call(r,'head.position',position='measuring')
|
| 11 |
+
def unload(r):call(r,'head.position',position='raised');call(r,'sample.unload')
|
| 12 |
+
def calibrate(r,values=(0.,.4,.85)):
|
| 13 |
+
for v in values:
|
| 14 |
+
load(r,m.reference(v,r.method['sample_volume_m3']));call(r,'acquisition.start',purpose='calibration');r.step(130);assert r.phase=='succeeded',r.failure;call(r,'calibration.accept',known_osmolality_mol_kg=v);unload(r)
|
| 15 |
+
return r
|
| 16 |
+
class Tests(unittest.TestCase):
|
| 17 |
+
def test_01_reference_curves(self):
|
| 18 |
+
r=ready();self.assertEqual(len(r.templates),61);self.assertEqual(sum(len(v['rows']) for v in r.templates.values()),529)
|
| 19 |
+
for sid,t in r.templates.items():
|
| 20 |
+
for row in t['rows']:
|
| 21 |
+
x=call(r,'template.evaluate',substance_id=sid,molality_mol_kg=row['molality_mol_kg']);self.assertAlmostEqual(x['osmotic_coefficient'],row['osmotic_coefficient']);self.assertIn('10.1063/1.3253108',x['template_source'])
|
| 22 |
+
self.assertAlmostEqual(r.phi('NaCl',.1),.933);self.assertAlmostEqual(r.phi('NaBr',.1),.935)
|
| 23 |
+
def test_02_three_point_observed_measurement(self):
|
| 24 |
+
r=calibrate(ready());load(r,m.SAMPLE_EXAMPLE);call(r,'acquisition.start',purpose='sample');r.step(130);x=call(r,'process.measure');self.assertEqual(x['phase'],'succeeded');self.assertAlmostEqual(x['osmolality_mol_kg'],.187,places=3);self.assertTrue(110<x['elapsed_s']<125);self.assertLess(min(v['temperature_k'] for v in x['points']),x['freezing_temperature_k']-4)
|
| 25 |
+
def test_03_inventory_heat(self):
|
| 26 |
+
r=calibrate(ready(),(0,.4));load(r,m.SAMPLE_EXAMPLE);call(r,'acquisition.start',purpose='sample');r.step(70);self.assertGreater(r.ice,0)
|
| 27 |
+
l=call(r,'ledger.read');self.assertAlmostEqual(l['water_loaded_kg'],l['water_returned_kg']+l['water_remaining_kg'],places=15);self.assertLess(abs(l['energy_residual_j']),1e-8);self.assertLess(l['solute_residual_mol'],1e-15);r.step(60);unload(r);self.assertEqual(r.water,0);self.assertLess(abs(r._ledger()['energy_residual_j']),1e-8)
|
| 28 |
+
def test_04_freeze_interlock_and_cancel(self):
|
| 29 |
+
r=ready();load(r,m.reference(0));call(r,'acquisition.start',purpose='calibration');r.step(70);old=(r.water,r.H,copy.deepcopy(r.solutes));call(r,'acquisition.stop');self.assertEqual(old,(r.water,r.H,r.solutes))
|
| 30 |
+
with self.assertRaises(m.ActionRejected):r.invoke('head.position',position='raised')
|
| 31 |
+
r.step(50);self.assertTrue(r.thawed);self.assertEqual(r.phase,'cancelled');unload(r)
|
| 32 |
+
def test_05_power_pause(self):
|
| 33 |
+
r=ready();load(r,m.reference(.4));call(r,'acquisition.start',purpose='calibration');r.step(67);call(r,'power.set',enabled=False);h=r.H;r.step(100);self.assertEqual(h,r.H);self.assertEqual(r.phase,'cancelled');call(r,'power.set',enabled=True);r.step(60);self.assertTrue(r.thawed)
|
| 34 |
+
def test_06_warmup_and_uncalibrated(self):
|
| 35 |
+
r=ready();r.invoke('power.set',enabled=False);r.invoke('power.set',enabled=True);load(r,m.reference(0))
|
| 36 |
+
with self.assertRaisesRegex(m.ActionRejected,'NOT_READY'):r.invoke('acquisition.start',purpose='calibration')
|
| 37 |
+
r.step(300)
|
| 38 |
+
with self.assertRaisesRegex(m.ActionRejected,'NOT_CALIBRATED'):r.invoke('acquisition.start',purpose='sample')
|
| 39 |
+
def test_07_setting_invalidates_calibration(self):
|
| 40 |
+
r=calibrate(ready(),(0,.4));call(r,'method.configure',**dict(m.METHOD_EXAMPLE,sample_interval_s=.5));self.assertTrue(r.calibrated());call(r,'method.configure',**dict(m.METHOD_EXAMPLE,freeze_k=266.65));self.assertFalse(r.calibrated())
|
| 41 |
+
def test_08_volume_50(self):
|
| 42 |
+
r=ready(volume=50e-9);r.invoke('head.position',position='raised')
|
| 43 |
+
with self.assertRaisesRegex(m.ActionRejected,'VOLUME_MISMATCH'):r.invoke('sample.load',**m.reference(0))
|
| 44 |
+
calibrate(r,(0,.4));load(r,dict(m.SAMPLE_EXAMPLE,volume_m3=50e-9,water_mass_kg=.00005));r.invoke('acquisition.start',purpose='sample');r.step(130);self.assertEqual(r.osm,.187)
|
| 45 |
+
def test_09_faults(self):
|
| 46 |
+
for fault,code,rate in [('early_freeze','FREEZE',.4),('no_freeze','NO_FREEZE',.4),('none','COOLER_TIMEOUT',0.)]:
|
| 47 |
+
r=ready(dict(m.PLANT_EXAMPLE,fault=fault,cooling_rate_k_s=rate));load(r,m.reference(0));r.invoke('acquisition.start',purpose='calibration');r.step(301);self.assertEqual(r.phase,'failed');self.assertEqual(r.failure,code);self.assertLess(abs(r._ledger()['energy_residual_j']),1e-8)
|
| 48 |
+
def test_10_partition_invariance(self):
|
| 49 |
+
a=ready();load(a,m.reference(.4));a.invoke('acquisition.start',purpose='calibration');b=copy.deepcopy(a);a.step(118.)
|
| 50 |
+
for _ in range(1180):b.step(.1)
|
| 51 |
+
for k in ['H','ice','temp','freezing','elapsed']:self.assertEqual(getattr(a,k),getattr(b,k))
|
| 52 |
+
def test_11_invalid_atomic(self):
|
| 53 |
+
r=ready()
|
| 54 |
+
for a in [dict(m.METHOD_EXAMPLE,freeze_k=267.2),dict(m.METHOD_EXAMPLE,sample_interval_s=.15),dict(m.METHOD_EXAMPLE,cooling_limit_k=float('nan')),dict(m.METHOD_EXAMPLE,sample_volume_m3=True)]:
|
| 55 |
+
before=copy.deepcopy(r.__dict__)
|
| 56 |
+
with self.assertRaises(m.ActionRejected):r.invoke('method.configure',**a)
|
| 57 |
+
self.assertEqual(before,r.__dict__)
|
| 58 |
+
for dt in [-1,True,float('nan')]:
|
| 59 |
+
with self.assertRaises(m.ActionRejected):r.step(dt)
|
| 60 |
+
def test_12_observation_calibration_not_truth(self):
|
| 61 |
+
r=calibrate(ready());load(r,m.SAMPLE_EXAMPLE);r.invoke('acquisition.start',purpose='sample');r.step(130);peak=r.freezing;value=r.calibrated_osm(peak);r.solutes={'NaCl':1e-7};self.assertEqual(r.calibrated_osm(peak),value);self.assertNotEqual(r.calibrated_osm(peak-.1),value)
|
| 62 |
+
def test_13_mixing_and_pulse(self):
|
| 63 |
+
r=ready();load(r,m.reference(.4));r.invoke('acquisition.start',purpose='calibration');r.step(130)
|
| 64 |
+
with self.assertRaisesRegex(m.ActionRejected,'NOT_READY'):r.invoke('acquisition.start',purpose='calibration')
|
| 65 |
+
self.assertTrue(call(r,'vibrator.pulse')['active']);r.step(5.1);self.assertFalse(r.read()['vibrator.active']);r.invoke('acquisition.start',purpose='calibration')
|
| 66 |
+
def test_14_session_isolation(self):
|
| 67 |
+
r=ready();r.register_principal('a');r.register_principal('b');r.register_principal('e','evaluator');a=r.session('a');b=r.session('b');self.assertNotIn('sample.identity',a.read(instance_id=r.instance_id)['observations']);self.assertNotIn('sample.load',a.describe(asset_type_id=m.ASSET_TYPE_ID)['capabilities']);self.assertIn('sample.load',r.session('e').describe(instance_id=r.instance_id)['capabilities'])
|
| 68 |
+
x=dict(instance_id=r.instance_id,capability_id='head.position',arguments={'position':'parked'},request_id='1');v=a.invoke(**x);rev=r.revision;self.assertEqual(v,r.session('a').invoke(**x));self.assertEqual(rev,r.revision);x['arguments']={'position':'raised'};self.assertEqual(a.invoke(**x)['error']['code'],'REQUEST_CONFLICT')
|
| 69 |
+
with self.assertRaises(m.ActionRejected):a.read(instance_id='other')
|
| 70 |
+
denied=a.invoke(instance_id=r.instance_id,capability_id='ledger.read',arguments={},request_id='ledger');self.assertEqual(denied['status'],'rejected');self.assertEqual(b.read(instance_id=r.instance_id)['observations']['head.position']['value'],'parked')
|
| 71 |
+
def test_15_operation_ownership_and_observation_time(self):
|
| 72 |
+
r=ready();load(r,m.reference(0));r.register_principal('a');r.register_principal('b');a=r.session('a');b=r.session('b');v=a.invoke(instance_id=r.instance_id,capability_id='acquisition.start',arguments={'purpose':'calibration'},request_id='op');op=v['operation_id'];r.step(130);self.assertEqual(a.poll(op)['status'],'succeeded')
|
| 73 |
+
with self.assertRaises(m.ActionRejected):b.poll(op)
|
| 74 |
+
before=a.read(instance_id=r.instance_id,state_ids=['freezing.temperature_k']);r.step(1);after=a.read(instance_id=r.instance_id,state_ids=['freezing.temperature_k']);self.assertEqual(before['observations'],after['observations'])
|
| 75 |
+
def test_16_schema_and_unsupported(self):
|
| 76 |
+
spec=importlib.util.spec_from_file_location('asset_tool',ROOT/'skills/chemistry-lab-assets/scripts/asset_tool.py');tool=importlib.util.module_from_spec(spec);spec.loader.exec_module(tool);r=ready();meta=r.describe();self.assertEqual(len(meta['state_slots']),24)
|
| 77 |
+
for sid,value in r.read('evaluator').items():self.assertFalse(tool.validate_value(value,meta['state_slots'][sid]['value_schema']))
|
| 78 |
+
for k in m.UNSUPPORTED:
|
| 79 |
+
with self.assertRaisesRegex(m.ActionRejected,'UNSUPPORTED'):r.invoke(k)
|
| 80 |
+
def test_17_reject_bad_sample_and_source_range(self):
|
| 81 |
+
r=ready();r.invoke('head.position',position='raised')
|
| 82 |
+
for s in [dict(m.SAMPLE_EXAMPLE,components=[dict(substance_id='NaCl',molality_mol_kg=1)]),dict(m.SAMPLE_EXAMPLE,accept_temperature_transfer=False),dict(m.SAMPLE_EXAMPLE,components=m.SAMPLE_EXAMPLE['components']*2)]:
|
| 83 |
+
before=copy.deepcopy(r.__dict__)
|
| 84 |
+
with self.assertRaises(m.ActionRejected):r.invoke('sample.load',**s)
|
| 85 |
+
self.assertEqual(before,r.__dict__)
|
| 86 |
+
if __name__=='__main__':unittest.main()
|
tests/test_asset_laboao_cvdltf12p50.py
ADDED
|
@@ -0,0 +1,184 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""CHEM-063 independent physical/protocol invariants, not manufacturer calibration."""
|
| 2 |
+
import copy,math,sys,unittest
|
| 3 |
+
from pathlib import Path
|
| 4 |
+
sys.path.insert(0,str(Path(__file__).resolve().parents[1]/'scripts'))
|
| 5 |
+
from asset_runtime.laboao_cvdltf12p50 import *
|
| 6 |
+
def ready(warm=True,plant=None,gas=None,method=None,sample=True):
|
| 7 |
+
h=LaboaoCvdltf12p50Runtime();h.invoke('plant.configure',**dict(WARM_EXAMPLE if warm else PLANT_EXAMPLE,**(plant or {})));h.invoke('gas.install',**(gas or GASES_EXAMPLE))
|
| 8 |
+
if sample:h.invoke('sample.install',**(HOT_SAMPLE_EXAMPLE if warm else SAMPLE_EXAMPLE))
|
| 9 |
+
h.invoke('method.configure',**(method or METHOD_EXAMPLE))
|
| 10 |
+
if not warm:h.invoke('flange.set',opened=False);h.invoke('furnace.set',opened=False)
|
| 11 |
+
h.invoke('power.set',enabled=True);return h
|
| 12 |
+
class TestCVD(unittest.TestCase):
|
| 13 |
+
def assertConservative(self,h):
|
| 14 |
+
x=h.invoke('product.read');self.assertLess(max(map(abs,x['atom_residual_mol'])),1e-12);self.assertLess(abs(x['energy_residual_j']),1e-4)
|
| 15 |
+
self.assertTrue(all(v>=0 for v in x['gas_chamber_mol'].values()));self.assertTrue(all(v>=0 for v in x['source_remaining_mol']))
|
| 16 |
+
def test_library_count_identity_and_no_boolean_NO(self):
|
| 17 |
+
h=LaboaoCvdltf12p50Runtime();self.assertEqual(len(h.templates),54);self.assertIn('gri_NO',h.templates);self.assertIn('gri_CH2(S)',h.templates);self.assertIn('solid_C(gr)',h.templates)
|
| 18 |
+
self.assertEqual(len({r['name'] for r in h.templates.values()}),54)
|
| 19 |
+
def test_every_thermo_record_cp_dhdt_and_source(self):
|
| 20 |
+
h=LaboaoCvdltf12p50Runtime()
|
| 21 |
+
for sid,r in h.templates.items():
|
| 22 |
+
bounds=r['conditions']['temperature_ranges_k'];self.assertTrue(r['source']['sha256'])
|
| 23 |
+
for t in [(bounds[0]+bounds[1])/2,(bounds[1]+bounds[-1])/2]:
|
| 24 |
+
cp,enthalpy,entropy,u=h.thermo(sid,t);dh=(h.thermo(sid,t+.01)[1]-h.thermo(sid,t-.01)[1])/.02
|
| 25 |
+
self.assertGreater(cp,0);self.assertAlmostEqual(cp,dh,delta=1e-5)
|
| 26 |
+
self.assertAlmostEqual(enthalpy-u,R*t if r['phase']=='gas' else 0,delta=1e-8)
|
| 27 |
+
def test_thermo_per_record_range_and_split(self):
|
| 28 |
+
h=LaboaoCvdltf12p50Runtime()
|
| 29 |
+
for sid,r in h.templates.items():
|
| 30 |
+
low,mid,high=r['conditions']['temperature_ranges_k']
|
| 31 |
+
for t in [low,mid,high]:h.thermo(sid,t)
|
| 32 |
+
for t in [low-.01,high+.01]:
|
| 33 |
+
with self.assertRaises(ActionRejected):h.thermo(sid,t)
|
| 34 |
+
self.assertEqual(h.templates['gri_HNCO']['conditions']['temperature_ranges_k'][1],1478.)
|
| 35 |
+
with self.assertRaises(ActionRejected):h.thermo('gri_N2',298.15)
|
| 36 |
+
def test_ideal_argon_and_graphite(self):
|
| 37 |
+
h=LaboaoCvdltf12p50Runtime();self.assertAlmostEqual(h.thermo('gri_AR',800)[0],2.5*R);self.assertEqual(h.templates['solid_C(gr)']['values']['density_kg_m3'],2160.)
|
| 38 |
+
def test_warm_snapshot_initial_energy_not_device_teleport(self):
|
| 39 |
+
h=ready();self.assertGreater(h.initial_energy,1e7);self.assertConservative(h)
|
| 40 |
+
old=h.debug_snapshot()
|
| 41 |
+
with self.assertRaises(ActionRejected):h.invoke('plant.configure',**PLANT_EXAMPLE)
|
| 42 |
+
self.assertEqual(old,h.debug_snapshot())
|
| 43 |
+
def test_cold_initialization_cannot_smuggle_hot_state(self):
|
| 44 |
+
h=LaboaoCvdltf12p50Runtime()
|
| 45 |
+
with self.assertRaises(ActionRejected):h.invoke('plant.configure',**dict(PLANT_EXAMPLE,initial_oven_k=1173.15))
|
| 46 |
+
def test_pump_delay_exact_boundary(self):
|
| 47 |
+
h=ready();h.invoke('vacuum.set',enabled=True,mode='manual',pressure_pa=30.,manual_valve_fraction=1.)
|
| 48 |
+
p0=h._p();h.step(9.95);self.assertFalse(h.solenoid);self.assertTrue(h.motor);self.assertLess(abs(h._p()-p0),.01)
|
| 49 |
+
h.step(.05);self.assertTrue(h.solenoid);self.assertLess(h._p(),p0);self.assertConservative(h)
|
| 50 |
+
def test_restart_resets_ten_second_delay(self):
|
| 51 |
+
h=ready();a=dict(enabled=True,mode='manual',pressure_pa=30.,manual_valve_fraction=1.)
|
| 52 |
+
h.invoke('vacuum.set',**a);h.step(11);h.invoke('vacuum.set',**dict(a,enabled=False));h.invoke('vacuum.set',**a);h.step(9);self.assertFalse(h.solenoid)
|
| 53 |
+
def test_auto_motor_hysteresis_not_ideal_pressure_assignment(self):
|
| 54 |
+
h=ready();h.invoke('vacuum.set',enabled=True,mode='auto',pressure_pa=20.,manual_valve_fraction=.8);self.assertEqual(h._p(),30.);h.step(12)
|
| 55 |
+
self.assertFalse(h.motor);self.assertFalse(h.solenoid);self.assertLess(h._p(),20)
|
| 56 |
+
self.assertConservative(h)
|
| 57 |
+
def test_standalone_base_not_working_pressure(self):
|
| 58 |
+
h=ready();h.invoke('vacuum.set',enabled=True,mode='manual',pressure_pa=30.,manual_valve_fraction=1.);h.step(20)
|
| 59 |
+
self.assertAlmostEqual(h._p(),.3,delta=.001);self.assertConservative(h)
|
| 60 |
+
def test_cvd_completes_finite_mass_and_energy(self):
|
| 61 |
+
h=ready();h.invoke('acquisition.start',mode='cvd');h.step(20)
|
| 62 |
+
self.assertEqual(h.phase,'succeeded');self.assertGreater(h.film,0);self.assertGreater(h.wall,0);self.assertGreater(h.gas['H2']+h.exhaust['H2'],0);self.assertConservative(h)
|
| 63 |
+
self.assertGreater(h.oven,1100);self.assertTrue(h.fan)
|
| 64 |
+
def test_CH4_stoichiometry_and_thickness(self):
|
| 65 |
+
h=ready();h.invoke('acquisition.start',mode='cvd');h.step(16);x=h._ledger()
|
| 66 |
+
consumed=GASES_EXAMPLE['initial_mol'][2]-h.remaining[2]-h.gas['CH4']-h.exhaust['CH4']
|
| 67 |
+
self.assertAlmostEqual(consumed,h.film+h.wall,delta=1e-15);self.assertAlmostEqual(h.gas['H2']+h.exhaust['H2'],2*consumed,delta=1e-15)
|
| 68 |
+
self.assertAlmostEqual(x['thickness_m'],h.film*.012011/1e-4/2000);self.assertConservative(h)
|
| 69 |
+
def test_no_CH4_no_carbon_fabrication(self):
|
| 70 |
+
h=ready(gas=dict(GASES_EXAMPLE,species=['N2','AR','H2']));h.invoke('acquisition.start',mode='cvd');h.step(20);self.assertEqual(h.film,0);self.assertConservative(h)
|
| 71 |
+
def test_cancel_partial_film_and_reservoirs_preserved(self):
|
| 72 |
+
h=ready();h.invoke('acquisition.start',mode='cvd');h.step(13);self.assertGreater(h.film,0);before=h.film;gas=list(h.remaining)
|
| 73 |
+
h.invoke('acquisition.stop');h.step(1);self.assertEqual(h.film,before);self.assertEqual(h.remaining,gas);self.assertEqual(h.heater,0);self.assertTrue(h.fan);self.assertConservative(h)
|
| 74 |
+
def test_open_clamshell_cuts_heat_without_venting_tube(self):
|
| 75 |
+
h=ready();h.invoke('acquisition.start',mode='cvd');h.step(13);p=h._p();h.invoke('furnace.set',opened=True)
|
| 76 |
+
self.assertEqual(h._p(),p);self.assertFalse(h.flange);self.assertEqual(h.heater,0);self.assertEqual(h.phase,'cancelled')
|
| 77 |
+
def test_hot_vacuum_flange_open_rejected_atomically(self):
|
| 78 |
+
h=ready();before=h.debug_snapshot()
|
| 79 |
+
with self.assertRaises(ActionRejected):h.invoke('flange.set',opened=True)
|
| 80 |
+
self.assertEqual(h.debug_snapshot(),before)
|
| 81 |
+
def test_vent_is_species_enthalpy_transfer_not_set_pressure(self):
|
| 82 |
+
h=ready();h.invoke('vacuum.vent');self.assertEqual(h._p(),30.);h.step(8);self.assertGreater(h._p(),.999*101325);self.assertGreater(h.air['O2'],0);self.assertConservative(h)
|
| 83 |
+
def test_fan_threshold_body_not_oven_temperature(self):
|
| 84 |
+
h=ready(plant={'initial_oven_k':500.,'initial_body_k':340.});h.step(.05);self.assertTrue(h.fan)
|
| 85 |
+
g=ready(plant={'initial_oven_k':1173.15,'initial_body_k':310.});g.step(.05);self.assertFalse(g.fan)
|
| 86 |
+
def test_power_loss_stops_pump_gas_heat_not_heat_inventory(self):
|
| 87 |
+
h=ready();h.invoke('acquisition.start',mode='cvd');h.step(13);t=h.oven;film=h.film
|
| 88 |
+
h.invoke('power.set',enabled=False);self.assertFalse(h.fan);self.assertFalse(h.motor);self.assertEqual(h.flow,[0.]*3);self.assertEqual(h.oven,t);h.step(.2);self.assertEqual(h.film,film);self.assertConservative(h)
|
| 89 |
+
def test_three_channels_and_explicit_unknown_scale(self):
|
| 90 |
+
h=ready();self.assertEqual(len(h.gases['full_scale_std_m3_s']),3)
|
| 91 |
+
old=h.debug_snapshot()
|
| 92 |
+
with self.assertRaises(ActionRejected):h.invoke('method.configure',**dict(METHOD_EXAMPLE,flow_std_m3_s=[6e-6,0.,0.]))
|
| 93 |
+
self.assertEqual(h.debug_snapshot(),old)
|
| 94 |
+
def test_finite_source_underpressure(self):
|
| 95 |
+
h=ready(gas=dict(GASES_EXAMPLE,initial_mol=[1e-6]*3));h.invoke('acquisition.start',mode='cvd');h.step(20)
|
| 96 |
+
self.assertEqual(h.phase,'failed');self.assertEqual(h.warning,'SOURCE_UNDERPRESSURE');self.assertConservative(h)
|
| 97 |
+
def test_purge_has_no_heat_or_deposition(self):
|
| 98 |
+
h=ready(sample=False);h.invoke('acquisition.start',mode='purge');h.step(15)
|
| 99 |
+
self.assertEqual(h.phase,'succeeded');self.assertEqual(h.electric,0);self.assertEqual(h.film,0);self.assertEqual(h.remaining[2],GASES_EXAMPLE['initial_mol'][2]);self.assertConservative(h)
|
| 100 |
+
def test_cold_air_purge_oxygen_removed_finitely(self):
|
| 101 |
+
h=ready(warm=False);h.invoke('acquisition.start',mode='purge');h.step(30)
|
| 102 |
+
self.assertEqual(h.phase,'succeeded');self.assertLess(h.gas['O2']/sum(h.gas.values()),1e-4);self.assertGreater(h.exhaust['O2'],0);self.assertConservative(h)
|
| 103 |
+
def test_cold_ramp_nominal20_limited_to5(self):
|
| 104 |
+
h=ready(warm=False,method=dict(METHOD_EXAMPLE,segments=[dict(target_k=573.15,ramp_k_s=20/60,hold_s=1.)]))
|
| 105 |
+
h.invoke('acquisition.start',mode='cvd');h.step(35);start=h.setpoint;temp=h.oven;h.step(12)
|
| 106 |
+
self.assertAlmostEqual(h.setpoint-start,1.,delta=1e-7);self.assertGreater(h.oven,temp);self.assertLessEqual(h.heater,3000);self.assertLess(h.oven,573.15);self.assertConservative(h)
|
| 107 |
+
def test_piecewise_ramp_limits(self):
|
| 108 |
+
for t,lim in [(700,5/60),(800,10/60),(1100,5/60),(1400,2/60)]:
|
| 109 |
+
h=ready(plant={'initial_oven_k':float(t)});self.assertAlmostEqual(h._ramp_limit(),lim)
|
| 110 |
+
def test_zero_ramp_rejected_for_transition(self):
|
| 111 |
+
h=ready()
|
| 112 |
+
with self.assertRaises(ActionRejected):h.invoke('method.configure',**dict(METHOD_EXAMPLE,segments=[dict(target_k=1200.,ramp_k_s=0.,hold_s=1.)]))
|
| 113 |
+
h.invoke('method.configure',**dict(METHOD_EXAMPLE,segments=[dict(target_k=1173.15,ramp_k_s=0.,hold_s=1.)]));h.invoke('acquisition.start',mode='cvd');h.step(14);self.assertEqual(h.phase,'succeeded')
|
| 114 |
+
def test_four_curves_total40_and_selection(self):
|
| 115 |
+
h=ready()
|
| 116 |
+
for i in range(4):h.invoke('method.configure',**dict(METHOD_EXAMPLE,curve_slot=i,segments=METHOD_EXAMPLE['segments']*10))
|
| 117 |
+
self.assertEqual(sum(len(v['segments']) for v in h.programs.values()),40);h.invoke('program.select',curve_slot=2);self.assertEqual(h.method['curve_slot'],2)
|
| 118 |
+
old=h.debug_snapshot()
|
| 119 |
+
with self.assertRaises(ActionRejected):h.invoke('method.configure',**dict(METHOD_EXAMPLE,curve_slot=0,segments=METHOD_EXAMPLE['segments']*11))
|
| 120 |
+
self.assertEqual(h.debug_snapshot(),old)
|
| 121 |
+
def test_display_resolution_and_quantization_not_calibration(self):
|
| 122 |
+
h=ready();h.invoke('acquisition.start',mode='cvd')
|
| 123 |
+
for _ in range(10):
|
| 124 |
+
h.step(.13);m=h.invoke('process.measure');self.assertAlmostEqual(m['display_k']-273.15,round(m['display_k']-273.15));self.assertLessEqual(abs(m['display_k']-m['oven_k']),.5);self.assertFalse(m['calibrated'])
|
| 125 |
+
def test_pump_timeout_preserves_partial_inventory(self):
|
| 126 |
+
h=ready(warm=False,plant={'effective_pump_m3_s':1e-5,'pump_timeout_s':11.})
|
| 127 |
+
h.invoke('acquisition.start',mode='purge');h.step(12);self.assertEqual(h.phase,'failed');self.assertEqual(h.warning,'PUMP_OR_PURGE_TIMEOUT');self.assertConservative(h)
|
| 128 |
+
def test_no_unvalidated_substance_runtime_source(self):
|
| 129 |
+
h=LaboaoCvdltf12p50Runtime();h.invoke('plant.configure',**PLANT_EXAMPLE)
|
| 130 |
+
with self.assertRaises(ActionRejected):h.invoke('gas.install',**dict(GASES_EXAMPLE,species=['N2','AR','SiH4']))
|
| 131 |
+
self.assertIsNone(h.gases)
|
| 132 |
+
def test_collect_cold_sample_energy_and_identity(self):
|
| 133 |
+
h=ready(warm=False);h.invoke('power.set',enabled=False);h.invoke('flange.set',opened=True);h.invoke('sample.collect',recipient_id='holder');self.assertIsNone(h.sample);self.assertConservative(h)
|
| 134 |
+
with self.assertRaises(ActionRejected):h.invoke('sample.install',**SAMPLE_EXAMPLE)
|
| 135 |
+
def test_invalid_nan_bool_unknown_atomic(self):
|
| 136 |
+
h=ready()
|
| 137 |
+
for args in [dict(enabled=1),dict(enabled=True,extra=True)]:
|
| 138 |
+
before=h.debug_snapshot()
|
| 139 |
+
with self.assertRaises(ActionRejected):h.invoke('power.set',**args)
|
| 140 |
+
self.assertEqual(before,h.debug_snapshot())
|
| 141 |
+
for dt in [True,float('nan'),-1]:
|
| 142 |
+
with self.assertRaises(ActionRejected):h.step(dt)
|
| 143 |
+
def test_zero_step_no_mutation(self):
|
| 144 |
+
h=ready();before=h.debug_snapshot();h.step(0);self.assertEqual(h.debug_snapshot(),before)
|
| 145 |
+
def test_external_clock_partition(self):
|
| 146 |
+
h=ready();g=ready();h.invoke('acquisition.start',mode='cvd');g.invoke('acquisition.start',mode='cvd');h.step(15)
|
| 147 |
+
for _ in range(300):g.step(.05)
|
| 148 |
+
self.assertAlmostEqual(h.film,g.film,delta=1e-18);self.assertAlmostEqual(h.oven,g.oven,delta=1e-9)
|
| 149 |
+
def test_agent_visibility_and_host_config_denial(self):
|
| 150 |
+
h=ready();s=h.session();self.assertNotIn('truth.ledger',s.read(instance_id=h.instance_id)['observations']);self.assertNotIn('plant.configure',s.describe(instance_id=h.instance_id)['capabilities'])
|
| 151 |
+
r=s.invoke(instance_id=h.instance_id,capability_id='product.read',arguments={},request_id='deny');self.assertEqual(r['status'],'rejected')
|
| 152 |
+
with self.assertRaises(ActionRejected):s.read(instance_id=h.instance_id,state_ids=['truth.ledger'])
|
| 153 |
+
def test_idempotency_conflict_and_instance(self):
|
| 154 |
+
h=ready();s=h.session();a=dict(instance_id=h.instance_id,capability_id='acquisition.start',arguments={'mode':'cvd'},request_id='once');r=s.invoke(**a);rev=h.revision;self.assertEqual(s.invoke(**a),r);self.assertEqual(h.revision,rev)
|
| 155 |
+
self.assertEqual(s.invoke(**dict(a,arguments={'mode':'purge'}))['error']['code'],'REQUEST_CONFLICT')
|
| 156 |
+
self.assertEqual(s.invoke(**dict(a,instance_id='other'))['error']['code'],'UNKNOWN_INSTANCE')
|
| 157 |
+
def test_async_owner_poll_cancel(self):
|
| 158 |
+
h=ready();h.register_principal('other');s=h.session();r=s.invoke(instance_id=h.instance_id,capability_id='acquisition.start',arguments={'mode':'cvd'},request_id='go');op=r['operation_id'];h.step(13)
|
| 159 |
+
with self.assertRaises(ActionRejected):h.session('other').poll(op)
|
| 160 |
+
self.assertEqual(s.poll(op)['status'],'running');s.cancel(op,'stop');self.assertEqual(s.poll(op)['status'],'cancelled');self.assertConservative(h)
|
| 161 |
+
def test_write_routes_to_guarded_api(self):
|
| 162 |
+
h=ready();s=h.session();r=s.write(instance_id=h.instance_id,state_id='power.enabled',value=False,request_id='off');self.assertEqual(r['status'],'succeeded');self.assertFalse(h.powered)
|
| 163 |
+
with self.assertRaises(ActionRejected):s.write(instance_id=h.instance_id,state_id='oven.temperature_k',value=1200,request_id='bad')
|
| 164 |
+
def test_host_clock_before_one_time_initialization(self):
|
| 165 |
+
h=LaboaoCvdltf12p50Runtime();h.step(.1);h.invoke('plant.configure',**WARM_EXAMPLE);h.invoke('gas.install',**GASES_EXAMPLE);h.invoke('sample.install',**HOT_SAMPLE_EXAMPLE)
|
| 166 |
+
self.assertEqual(h.initialized_at_s,.1);self.assertConservative(h)
|
| 167 |
+
h.step(.01)
|
| 168 |
+
with self.assertRaises(ActionRejected):h.invoke('plant.configure',**WARM_EXAMPLE)
|
| 169 |
+
def test_auto_process_initial_band_no_deadlock(self):
|
| 170 |
+
h=ready(method=dict(METHOD_EXAMPLE,pump_mode='auto'));h.invoke('acquisition.start',mode='cvd');h.step(90)
|
| 171 |
+
self.assertEqual(h.phase,'succeeded');self.assertGreater(h.film,0);self.assertConservative(h)
|
| 172 |
+
def test_low_pressure_pauses_hold_and_reaction(self):
|
| 173 |
+
h=ready(method=dict(METHOD_EXAMPLE,flow_std_m3_s=[1e-9,1e-9,1e-9]))
|
| 174 |
+
h.invoke('acquisition.start',mode='cvd');h.step(20);self.assertEqual(h.stage,'hold');self.assertEqual(h.phase,'running');self.assertLess(h._p(),10);self.assertEqual(h.film,0);self.assertConservative(h)
|
| 175 |
+
def test_complete_cold_300C_program_with_finite_large_reservoirs(self):
|
| 176 |
+
h=ready(warm=False,gas=dict(GASES_EXAMPLE,initial_mol=[2.]*3),method=dict(METHOD_EXAMPLE,segments=[dict(target_k=573.15,ramp_k_s=20/60,hold_s=5.)]))
|
| 177 |
+
h.invoke('acquisition.start',mode='cvd');h.step(3500);x=h._ledger()
|
| 178 |
+
self.assertEqual(h.phase,'succeeded');self.assertGreater(h.elapsed_s,3240.);self.assertGreater(h.film,0)
|
| 179 |
+
self.assertLess(abs(x['energy_residual_j']),1e-4);self.assertLess(max(map(abs,x['atom_residual_mol'])),1e-10)
|
| 180 |
+
self.assertGreater(h.remaining[0],0);self.assertGreater(h.electric,3e6)
|
| 181 |
+
def test_independent_instances(self):
|
| 182 |
+
h=ready();g=ready();old=g.debug_snapshot();h.invoke('acquisition.start',mode='cvd');h.step(14);self.assertEqual(g.debug_snapshot(),old)
|
| 183 |
+
if __name__=='__main__':unittest.main()
|
| 184 |
+
|
tests/test_asset_leco_onh836.py
ADDED
|
@@ -0,0 +1,172 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""CHEM089 source-domain, chemistry, observed calibration and session regression."""
|
| 2 |
+
import copy,csv,io,json,math,re,sys,unittest,importlib.util
|
| 3 |
+
from pathlib import Path
|
| 4 |
+
import numpy as np
|
| 5 |
+
ROOT=Path(__file__).resolve().parents[1];sys.path.insert(0,str(ROOT/'scripts'))
|
| 6 |
+
from asset_runtime.leco_onh836 import *
|
| 7 |
+
LIB=json.loads((ROOT/TEMPLATE_REL).read_text())
|
| 8 |
+
def fixture(carrier='He',**kw):
|
| 9 |
+
r=LecoOnh836Runtime(library=LIB);p=copy.deepcopy(PLANT_EXAMPLE);p.update(noise_density_sqrt_s=zeros());p.update(kw);r.invoke('plant.configure',**p);m=copy.deepcopy(METHOD_EXAMPLE);m['carrier']=carrier;r.invoke('method.configure',**m);r.invoke('power.set',enabled=True);r.invoke('gas.set',enabled=True);return r
|
| 10 |
+
def sample(kind='sample',mass=.00013,i='leco_503558_reference'):
|
| 11 |
+
a=copy.deepcopy(BLANK_EXAMPLE if kind=='blank' else SAMPLE_EXAMPLE);a['kind']=kind
|
| 12 |
+
if kind!='blank':a.update(mass_kg=mass,template_id=i,declared_elements=[e for e in ELEMENTS if LIB['compounds'][i]['element_mass_fractions'].get(e) is not None])
|
| 13 |
+
return a
|
| 14 |
+
def prepare(r,a=None):
|
| 15 |
+
if not r._cold():r.step(2.)
|
| 16 |
+
r.invoke('furnace.open',opened=True);r.step(.14)
|
| 17 |
+
if r.crucible:r.invoke('crucible.remove',recipient_id='waste')
|
| 18 |
+
r.invoke('crucible.install',**CRUCIBLE_EXAMPLE);r.invoke('furnace.open',opened=False);r.step(.14);r.invoke('loading.set',loading=True);r.step(.06);r.invoke('sample.load',**(a or sample()));r.invoke('loading.set',loading=False);r.step(.06)
|
| 19 |
+
def run(r,a=None,dt=.02):
|
| 20 |
+
prepare(r,a);r.invoke('measurement.start')
|
| 21 |
+
for _ in range(math.ceil(2.1/dt)):r.step(dt)
|
| 22 |
+
return r.invoke('result.read')
|
| 23 |
+
def calibrate(r):
|
| 24 |
+
run(r,sample('blank'));ids=[run(r,sample('standard',m))['record_id'] for m in [.0001,.00012,.00015]];c=r.invoke('calibration.fit',record_ids=ids,elements=ELEMENTS);r.invoke('calibration.select',curve_id=c['curve_id']);return c
|
| 25 |
+
class RuntimeTests(unittest.TestCase):
|
| 26 |
+
def reject(self,r,cap,code,**a):
|
| 27 |
+
snap=r.debug_snapshot()
|
| 28 |
+
with self.assertRaises(ActionRejected) as ex:r.invoke(cap,**a)
|
| 29 |
+
self.assertEqual(str(ex.exception),code);self.assertEqual(r.debug_snapshot(),snap)
|
| 30 |
+
def ledger(self,r):
|
| 31 |
+
l=r.invoke('product.read')
|
| 32 |
+
for v in json.loads(l['elements_json']).values():self.assertLess(abs(v['residual_kg']),1e-15)
|
| 33 |
+
for k in ['carbon_residual_kg','unknown_matrix_residual_kg']:self.assertLess(abs(l[k]),1e-15)
|
| 34 |
+
for k,v in json.loads(l['species_json']).items():
|
| 35 |
+
if k.endswith('residual_mol'):self.assertLess(abs(v),1e-13)
|
| 36 |
+
for v in json.loads(l['gas_inventory_json']).values():self.assertLess(abs(v['residual_mol']),1e-10)
|
| 37 |
+
self.assertLess(abs(l['cuo_oxygen_residual_mol']),1e-10);self.assertLess(abs(l['energy_residual_j']),1e-8)
|
| 38 |
+
def test_01_source_units(self):self.assertEqual(LIMITS['He']['O'],[5e-11,5e-5]);self.assertEqual(LIMITS['Ar']['N'][0],2e-10);self.assertEqual(LIMITS['He']['H'][1],2.5e-6)
|
| 39 |
+
def test_02_nominal_not_hardware_max(self):self.assertIn('not a claimed maximumhardwarecapacity',LIMITATIONS[0])
|
| 40 |
+
def test_03_reject_unknown_argument(self):self.reject(fixture(),'gas.set','INVALID_ARGUMENT',enabled=True,extra=1)
|
| 41 |
+
def test_04_reject_bool_number(self):r=fixture();a=copy.deepcopy(r.method);a['fusion_power_w']=True;self.reject(r,'method.configure','INVALID_ARGUMENT',**a)
|
| 42 |
+
def test_05_reject_nan(self):r=fixture();a=copy.deepcopy(r.method);a['fusion_s']=float('nan');self.reject(r,'method.configure','INVALID_ARGUMENT',**a)
|
| 43 |
+
def test_06_initialization_only(self):r=fixture();self.reject(r,'plant.configure','INITIALIZATION_ONLY',**PLANT_EXAMPLE)
|
| 44 |
+
def test_07_unique_host_clock(self):r=fixture();r.step(.1);self.assertAlmostEqual(r.time_s,.1)
|
| 45 |
+
def test_08_invalid_step(self):
|
| 46 |
+
r=fixture()
|
| 47 |
+
for d in [-1,True,float('inf')]:
|
| 48 |
+
before=r.debug_snapshot()
|
| 49 |
+
with self.assertRaises(ActionRejected):r.step(d)
|
| 50 |
+
self.assertEqual(before,r.debug_snapshot())
|
| 51 |
+
def test_09_zero_step_pure(self):r=fixture();s=r.debug_snapshot();r.step(0);self.assertEqual(r.debug_snapshot(),s)
|
| 52 |
+
def test_10_read_pure(self):r=fixture();s=r.debug_snapshot();r.read();r.read('evaluator');r.describe();self.assertEqual(s,r.debug_snapshot())
|
| 53 |
+
def test_11_no_self_promotion(self):
|
| 54 |
+
r=fixture()
|
| 55 |
+
with self.assertRaises(ActionRejected):r.register_principal('__public_agent__','evaluator')
|
| 56 |
+
def test_12_truth_filter(self):r=fixture();self.assertNotIn('truth.ledger',r.read());self.assertIn('truth.ledger',r.read('evaluator'))
|
| 57 |
+
def test_13_capability_acl(self):r=fixture();x=r.session().invoke(instance_id=r.instance_id,capability_id='sample.load',arguments=sample(),request_id='x');self.assertEqual(x['error']['code'],'ACCESS_DENIED')
|
| 58 |
+
def test_14_describe_acl(self):r=fixture();d=r.describe();self.assertNotIn('sample.load',d['capabilities']);self.assertNotIn('truth.ledger',d['state_slots'])
|
| 59 |
+
def test_15_cross_instance(self):r=fixture();x=r.session().invoke(instance_id='other',capability_id='power.set',arguments={'enabled':True},request_id='x');self.assertEqual(x['error']['code'],'UNKNOWN_INSTANCE')
|
| 60 |
+
def test_16_dedup_after_time(self):r=fixture();s=r.session();a=dict(instance_id=r.instance_id,capability_id='power.set',arguments={'enabled':True},request_id='one');x=s.invoke(**a);r.step(.1);self.assertEqual(s.invoke(**a),x)
|
| 61 |
+
def test_17_request_conflict(self):r=fixture();s=r.session();a=dict(instance_id=r.instance_id,capability_id='power.set',arguments={'enabled':True},request_id='one');s.invoke(**a);a['arguments']['enabled']=False;self.assertEqual(s.invoke(**a)['error']['code'],'REQUEST_CONFLICT');self.assertTrue(r.powered)
|
| 62 |
+
def test_18_requested_truth_read_denied(self):
|
| 63 |
+
r=fixture()
|
| 64 |
+
with self.assertRaises(ActionRejected):r.session().read(instance_id=r.instance_id,state_ids=['truth.ledger'])
|
| 65 |
+
def test_19_independent_instances(self):r=fixture();q=fixture();run(r);self.assertEqual(q.time_s,0);self.assertFalse(q.crucible);self.assertEqual(q._records,{})
|
| 66 |
+
def test_20_finite_lower_electrode(self):r=fixture();r.invoke('furnace.open',opened=True);self.assertEqual(r.q['furnace.opening_m'],0);r.step(.04);self.assertGreater(r.q['furnace.opening_m'],0);self.assertLess(r.q['furnace.opening_m'],.1)
|
| 67 |
+
def test_21_finite_loading(self):r=fixture();r.invoke('loading.set',loading=True);r.step(.02);self.assertLess(r.q['loading.position_m'],.045);self.assertGreater(r.q['loading.position_m'],0)
|
| 68 |
+
def test_22_maintenance_cover_power_guard(self):r=fixture();self.reject(r,'cover.set','POWER_OFF_REQUIRED',opened=True);r.invoke('power.set',enabled=False);r.invoke('cover.set',opened=True);r.step(.10);self.assertGreater(r.q['cover.lift_m'],0);self.assertLess(r.q['cover.lift_m'],.160);r.step(.12);self.assertEqual(r.q['cover.lift_m'],.160)
|
| 69 |
+
def test_23_install_requires_open(self):self.reject(fixture(),'crucible.install','FURNACE_OPEN_COLD_REQUIRED',**CRUCIBLE_EXAMPLE)
|
| 70 |
+
def test_24_duplicate_crucible(self):r=fixture();r.invoke('furnace.open',opened=True);r.step(.14);r.invoke('crucible.install',**CRUCIBLE_EXAMPLE);self.reject(r,'crucible.install','CRUCIBLE_PRESENT',**CRUCIBLE_EXAMPLE)
|
| 71 |
+
def test_25_loading_requires_funnel(self):r=fixture();self.reject(r,'sample.load','LOAD_POSITION_REQUIRED',**sample())
|
| 72 |
+
def test_26_load_held_no_release(self):r=fixture();prepare(r);self.assertFalse(r.dropped);self.assertGreater(r.held['O'],0);r.step(.2);self.assertEqual(r.detected['O'],0)
|
| 73 |
+
def test_27_return_before_drop(self):r=fixture();prepare(r);r.invoke('loading.set',loading=True);r.step(.06);x=r.invoke('sample.unload',recipient_id='returned');self.assertEqual(x['returned_mass_kg'],.00013);self.ledger(r)
|
| 74 |
+
def test_28_no_return_after_fusion(self):r=fixture();run(r);self.reject(r,'sample.unload','SAMPLE_ALREADY_FUSED',recipient_id='returned')
|
| 75 |
+
def test_29_drop_gate_held_interlock(self):r=fixture();prepare(r);self.reject(r,'sample_gate.set','SAMPLE_RETAINED',opened=True)
|
| 76 |
+
def test_30_cold_lower_interlock(self):r=fixture();prepare(r);r.invoke('measurement.start');r.step(.1);r.invoke('measurement.stop');self.reject(r,'furnace.open','HOT_MAINTENANCE',opened=True)
|
| 77 |
+
def test_31_carrier_switch_requires_off(self):r=fixture();m=copy.deepcopy(r.method);m['carrier']='Ar';self.reject(r,'method.configure','CARRIER_CHANGE_REQUIRES_OFF',**m)
|
| 78 |
+
def test_32_duplicate_selected_element(self):r=fixture();m=copy.deepcopy(r.method);m['selected_elements']=['O','O'];self.reject(r,'method.configure','DUPLICATE_ELEMENT',**m)
|
| 79 |
+
def test_33_sampling_window_guard(self):r=fixture();m=copy.deepcopy(r.method);m['window_s']=1;self.reject(r,'method.configure','WINDOW_TOO_LONG',**m)
|
| 80 |
+
def test_34_power_7500_bound(self):r=fixture();m=copy.deepcopy(r.method);m['fusion_power_w']=7501;self.reject(r,'method.configure','INVALID_ARGUMENT',**m)
|
| 81 |
+
def test_35_blank_nonzero_rejected(self):
|
| 82 |
+
r=fixture();r.invoke('furnace.open',opened=True);r.step(.14);r.invoke('crucible.install',**CRUCIBLE_EXAMPLE);r.invoke('furnace.open',opened=False);r.step(.14);r.invoke('loading.set',loading=True);r.step(.06);a=sample('blank');a['mass_kg']=.0001;self.reject(r,'sample.load','INVALID_BLANK',**a)
|
| 83 |
+
def test_36_source_ack_required(self):
|
| 84 |
+
r=fixture();prepare(r);r.invoke('loading.set',loading=True);r.step(.06);r.invoke('sample.unload',recipient_id='r');a=sample();a['accept_source_condition_mismatch']=False;self.reject(r,'sample.load','SOURCE_CONDITIONS_REQUIRED',**a)
|
| 85 |
+
def test_37_no_truth_in_sample_result(self):r=fixture();x=run(r);self.assertIsNone(x['standard_reference']);self.assertNotIn('leco_503558_reference',json.dumps(x));self.assertEqual(x['element_mass_kg'],nulls())
|
| 86 |
+
def test_38_atomic_absent_result(self):self.reject(fixture(),'result.read','NO_RESULT')
|
| 87 |
+
def test_39_all_elements_same_run(self):r=fixture();x=run(r);self.assertEqual(x['carrier'],'He');self.assertTrue(all(x['integrals_s'][e]>0 for e in ELEMENTS));self.assertTrue(r.dropped)
|
| 88 |
+
def test_40_measured_baseline_not_constant(self):r=fixture();x=run(r);self.assertNotEqual(x['baseline_relative'],r.plant['baseline_relative']);self.assertTrue(any(w['stage']=='baseline' for w in x['windows']))
|
| 89 |
+
def test_41_integral_independent(self):r=fixture();x=run(r);expected={e:sum((w['end_s']-w['start_s'])*w['corrected_relative'][e] for w in x['windows'] if w['stage'] in ['fusion','integration']) for e in ELEMENTS};np.testing.assert_allclose(list(expected.values()),list(x['integrals_s'].values()),rtol=1e-12,atol=1e-13)
|
| 90 |
+
def test_42_blank_actual_record(self):r=fixture();x=run(r,sample('blank'));b=r.invoke('blank.read');self.assertEqual(b['record_id'],x['record_id']);self.assertEqual(b['integrals_s'],x['integrals_s'])
|
| 91 |
+
def test_43_fitted_standard_observations(self):r=fixture();c=calibrate(r);self.assertEqual(len(c['record_ids']),3);self.assertTrue(all(c['parameters'][e]['r_squared']>.999999 for e in ELEMENTS))
|
| 92 |
+
def test_44_unknown_inferred_from_observations(self):r=fixture();c=calibrate(r);x=run(r);expected=LIB['compounds']['leco_503558_reference']['element_mass_fractions'];np.testing.assert_allclose([x['element_mass_fractions'][e] for e in ELEMENTS],[expected[e] for e in ELEMENTS],rtol=1e-6)
|
| 93 |
+
def test_45_NO_direct_truth_return(self):r=fixture();c=calibrate(r);x=run(r);e='O';self.assertAlmostEqual(x['element_mass_kg'][e],(x['net_integrals_s'][e]-c['parameters'][e]['intercept_s'])/c['parameters'][e]['slope_s_kg'],places=16)
|
| 94 |
+
def test_46_calibration_wrong_kind(self):r=fixture();ids=[run(r)['record_id'] for _ in range(3)];self.reject(r,'calibration.fit','INVALID_STANDARD_OBSERVATION',record_ids=ids,elements=ELEMENTS)
|
| 95 |
+
def test_47_duplicate_standard_records(self):r=fixture();x=run(r);self.reject(r,'calibration.fit','DUPLICATE_OBSERVATION',record_ids=[x['record_id']]*3,elements=ELEMENTS)
|
| 96 |
+
def test_48_calibration_carrier_signature(self):r=fixture();c=calibrate(r);r.invoke('gas.set',enabled=False);m=copy.deepcopy(r.method);m['carrier']='Ar';r.invoke('method.configure',**m);self.reject(r,'calibration.select','CALIBRATION_MISMATCH',curve_id=c['curve_id']);self.assertFalse(r.read()['blank.valid'])
|
| 97 |
+
def test_49_calibration_power_signature(self):r=fixture();c=calibrate(r);m=copy.deepcopy(r.method);m['fusion_power_w']=4500;r.invoke('method.configure',**m);self.assertIsNone(r._curve());self.assertIsNone(r._blank())
|
| 98 |
+
def test_50_argon_independent_calibration(self):r=fixture('Ar');c=calibrate(r);x=run(r);self.assertTrue(all(v is not None for v in x['element_mass_kg'].values()));self.assertLess(c['parameters']['N']['slope_s_kg'],PLANT_EXAMPLE['response_gain_s_kg']['N'])
|
| 99 |
+
def test_51_mass_balance_complete(self):r=fixture();run(r);self.ledger(r)
|
| 100 |
+
def test_52_reagent_oxygen_separate(self):r=fixture();run(r);s=json.loads(r._ledger()['species_json']);self.assertGreater(s['reagent_oxygen_atoms_mol'],0);self.assertGreater(2*s['cumulative_outlet_mol']['CO2_post'],s['sample_oxygen_atoms_mol']);self.ledger(r)
|
| 101 |
+
def test_53_DFC_same_carrier(self):r=fixture();run(r);l=r._ledger();self.assertAlmostEqual(l['dfc_supplied_mol'],l['co2_captured_mol']+l['water_captured_mol'],places=13);self.assertEqual(r.gas_used['Ar'],0)
|
| 102 |
+
def test_54_carbon_finite_consumption(self):r=fixture();run(r);self.assertLess(r.carbon,CRUCIBLE_EXAMPLE['graphite_mass_kg']);self.assertGreater(r.carbon_gas,0);self.ledger(r)
|
| 103 |
+
def test_55_sample_unknown_matrix_no_O_inference(self):r=fixture();run(r);self.assertGreater(r.matrix_remaining,.00012);self.ledger(r)
|
| 104 |
+
def test_56_dispose_not_restore(self):r=fixture();run(r);r.invoke('furnace.open',opened=True);r.step(.14);r.invoke('crucible.remove',recipient_id='waste');self.assertFalse(r.crucible);self.assertGreater(r.disposed['O'],0);self.assertGreater(r.matrix_disposed,0);self.ledger(r)
|
| 105 |
+
def test_57_cancel_partial_window(self):r=fixture();prepare(r);r.invoke('measurement.start');r.step(.633);r.invoke('measurement.stop');x=r.invoke('result.read');self.assertFalse(x['complete']);self.assertFalse(x['windows'][-1]['complete']);self.assertTrue(r.dropped);self.assertTrue(all(v is None for v in x['element_mass_kg'].values()));self.ledger(r)
|
| 106 |
+
def test_58_cancel_preserves_inventory(self):r=fixture();prepare(r);before=r.held['O'];r.invoke('measurement.start');r.step(.7);r.invoke('measurement.stop');self.assertLess(r.remaining['O'],before);self.assertGreater(r.detected['O'],0);self.assertGreater(r.gas_used['He'],0);self.ledger(r)
|
| 107 |
+
def test_59_coolant_loss(self):r=fixture();prepare(r);r.invoke('measurement.start');r.step(.65);r.invoke('coolant.set',ready=False);self.assertEqual(r.phase,'failed');self.assertEqual(r.actual_power,0);self.ledger(r)
|
| 108 |
+
def test_60_power_loss(self):r=fixture();prepare(r);r.invoke('measurement.start');r.step(.65);r.invoke('power.set',enabled=False);self.assertEqual(r.phase,'cancelled');self.assertEqual(r.actual_power,0);self.ledger(r)
|
| 109 |
+
def test_61_gas_loss(self):r=fixture();prepare(r);r.invoke('measurement.start');r.step(.65);r.invoke('gas.set',enabled=False);self.assertEqual(r.phase,'cancelled');self.ledger(r)
|
| 110 |
+
def test_62_CuO_exhaustion(self):r=fixture(cuo_oxygen_inventory_mol=1e-8);x=run(r);self.assertEqual(x['status'],'failed');self.assertIn('CUO_EXHAUSTED',r.warning);self.ledger(r)
|
| 111 |
+
def test_63_scrubber_exhaustion(self):r=fixture(co2_scrubber_capacity_mol=1e-8);x=run(r);self.assertEqual(x['status'],'failed');self.assertEqual(r.warning,'SCRUBBER_BREAKTHROUGH');self.ledger(r)
|
| 112 |
+
def test_64_DFC_deficit(self):r=fixture(dfc_maximum_mol_s=0);x=run(r);self.assertEqual(x['status'],'failed');self.assertEqual(r.warning,'DFC_FLOW_DEFICIT');self.ledger(r)
|
| 113 |
+
def test_65_noise_is_host_not_spec(self):r=fixture(noise_density_sqrt_s={'O':1e-5,'N':1e-5,'H':1e-5});x=run(r);self.assertTrue(all(math.isfinite(v) for w in x['windows'] for v in w['raw_relative'].values()));self.ledger(r)
|
| 114 |
+
def test_66_time_partition_consistency(self):r=fixture();q=fixture();a=run(r,dt=.02);b=run(q,dt=.01);np.testing.assert_allclose(list(a['integrals_s'].values()),list(b['integrals_s'].values()),rtol=1e-10,atol=1e-12);self.ledger(r);self.ledger(q)
|
| 115 |
+
def test_67_window_times_are_observation_times(self):r=fixture();run(r);o=r.session().read(instance_id=r.instance_id,state_ids=['detector.total_relative'])['observations']['detector.total_relative'];self.assertLess(o['sample_time_s'],r.time_s);self.assertEqual(o['sample_window_s'],[r._last_window['start_s'],r._last_window['end_s']])
|
| 116 |
+
def test_68_csv_actual_array(self):r=fixture();x=run(r);rows=list(csv.DictReader(io.StringIO(r.invoke('result.export',format='csv')['data'])));self.assertEqual(len(rows),len(x['windows']));self.assertEqual(float(rows[0]['O_raw_relative']),x['windows'][0]['raw_relative']['O'])
|
| 117 |
+
def test_69_record_returns_copy(self):r=fixture();x=run(r);y=r.invoke('records.read',record_id=x['record_id']);y['windows'].clear();self.assertTrue(r._records[x['record_id']]['windows'])
|
| 118 |
+
def test_70_record_in_use(self):r=fixture();c=calibrate(r);self.reject(r,'records.remove','RECORD_IN_USE',record_id=c['record_ids'][0])
|
| 119 |
+
def test_71_delete_unused_record(self):r=fixture();x=run(r);r.invoke('records.remove',record_id=x['record_id']);self.assertNotIn(x['record_id'],r._records)
|
| 120 |
+
def test_72_async_owner_and_cancel(self):
|
| 121 |
+
r=fixture();prepare(r);s=r.session();x=s.invoke(instance_id=r.instance_id,capability_id='measurement.start',arguments={},request_id='start');op=x['operation_id'];r.register_principal('other','agent')
|
| 122 |
+
with self.assertRaises(ActionRejected):r.session('other').poll(op)
|
| 123 |
+
r.step(.633);s.cancel(op,'cancel');self.assertEqual(s.poll(op)['status'],'cancelled');self.ledger(r)
|
| 124 |
+
def test_73_metadata_errorcodes_legal(self):
|
| 125 |
+
m=export_leco_onh836_contract_metadata()
|
| 126 |
+
for c in m['capabilities'].values():
|
| 127 |
+
for e in c['errors']:self.assertRegex(e['code'],r'^[A-Z][A-Z0-9_]*$')
|
| 128 |
+
def test_74_metadata_schemas_examples(self):
|
| 129 |
+
spec=importlib.util.spec_from_file_location('tool',ROOT/'skills/chemistry-lab-assets/scripts/asset_tool.py');tool=importlib.util.module_from_spec(spec);spec.loader.exec_module(tool);m=export_leco_onh836_contract_metadata();errors=[]
|
| 130 |
+
for k,c in m['capabilities'].items():tool.lint_schema(c['input_schema'],'input'+k,errors);tool.lint_schema(c['output_schema'],'output'+k,errors);tool.validate_value(c['example_arguments'],c['input_schema'],'example'+k,errors)
|
| 131 |
+
self.assertEqual(errors,[])
|
| 132 |
+
def test_75_runtime_output_schema(self):
|
| 133 |
+
r=fixture();x=run(r);validate(RESULT,x);validate(LEDGER,r._ledger())
|
| 134 |
+
for k,v in r.read('evaluator').items():validate(SLOTS[k][0],v)
|
| 135 |
+
def test_76_unsupported_no_success(self):
|
| 136 |
+
r=fixture()
|
| 137 |
+
for k in UNSUPPORTED:self.reject(r,k,'UNSUPPORTED')
|
| 138 |
+
def test_77_bound_capacity(self):
|
| 139 |
+
r=fixture();prepare(r);r._records={str(i):{} for i in range(MAX_RECORDS)};self.reject(r,'measurement.start','RESULT_STORE_FULL')
|
| 140 |
+
def test_78_no_hidden_positive_precondition(self):
|
| 141 |
+
r=fixture();prepare(r);r.held=zeros();r.sample['amount']=zeros();r.invoke('measurement.start');r.step(1.3);self.assertEqual(r.phase,'succeeded');self.assertIsNone(r.invoke('result.read')['element_mass_kg']['O'])
|
| 142 |
+
def test_79_missing_source_channel_public_null(self):
|
| 143 |
+
lib=copy.deepcopy(LIB);ref=lib['compounds']['leco_503558_reference'];ref['element_mass_fractions']['H']=None;ref['calibration_eligible_elements']=['O','N'];r=LecoOnh836Runtime(library=lib);p=copy.deepcopy(PLANT_EXAMPLE);p['noise_density_sqrt_s']=zeros();r.invoke('plant.configure',**p);r.invoke('power.set',enabled=True);r.invoke('gas.set',enabled=True);a=sample();a['declared_elements']=['O','N'];x=run(r,a);self.assertIn('unreported_element_unknown_not_zero',x['element_quality']['H']);self.assertIsNone(x['element_mass_fractions']['H'])
|
| 144 |
+
def test_80_finite_sample_gate(self):r=fixture();prepare(r);r.invoke('measurement.start');r.step(.38);self.assertEqual(r.stage,'gate_open');self.assertGreater(r.q['sample_gate.position_m'],0);self.assertLess(r.q['sample_gate.position_m'],.04)
|
| 145 |
+
def test_81_no_repeat_used_crucible(self):r=fixture();run(r);self.reject(r,'measurement.start','INSTRUMENT_NOT_READY')
|
| 146 |
+
def test_82_calibration_outside_mass_domain_null(self):r=fixture();calibrate(r);x=run(r,sample(mass=.00018));self.assertTrue(all(v is None for v in x['element_mass_kg'].values()));self.assertTrue(all('outside_calibration_domain' in x['element_quality'][e] for e in ELEMENTS))
|
| 147 |
+
def test_83_zero_power_no_fabricated_outgas(self):
|
| 148 |
+
r=fixture();m=copy.deepcopy(r.method);m['outgas_power_w']=0.;r.invoke('method.configure',**m);prepare(r);before=r.background.copy();r.invoke('measurement.start');r.step(.14);self.assertEqual(r.background,before);self.assertEqual(r.actual_power,0.);self.ledger(r)
|
| 149 |
+
def test_84_graphite_exhaustion_conserves(self):
|
| 150 |
+
lib=copy.deepcopy(LIB);lib['compounds']['leco_503558_reference']['element_mass_fractions']={'O':1.,'N':0.,'H':0.};r=LecoOnh836Runtime(library=lib);p=copy.deepcopy(PLANT_EXAMPLE);p['noise_density_sqrt_s']=zeros();p['response_gain_s_kg']={e:1. for e in ELEMENTS};p['dfc_maximum_mol_s']=.1;r.invoke('plant.configure',**p);r.invoke('power.set',enabled=True);r.invoke('gas.set',enabled=True);prepare(r);r.carbon_registered-=r.carbon-1e-5;r.carbon=1e-5;r.invoke('measurement.start');r.step(1.3);self.assertEqual(r.phase,'failed');self.assertEqual(r.warning,'GRAPHITE_EXHAUSTED');self.ledger(r)
|
| 151 |
+
def test_85_carrier_empty_finite(self):
|
| 152 |
+
r=fixture(helium_inventory_mol=.0004);x=run(r);self.assertEqual(x['status'],'failed');self.assertGreaterEqual(r.gas['He'],0);self.assertIn(r.warning,['UTILITY_LOSS','DFC_FLOW_DEFICIT']);self.ledger(r)
|
| 153 |
+
def test_86_metadata_effects_all_states_defined(self):
|
| 154 |
+
m=export_leco_onh836_contract_metadata()
|
| 155 |
+
for v in m['capabilities'].values():
|
| 156 |
+
self.assertTrue(all(s['state_id'] in m['state_slots'] for s in v['state_effects']))
|
| 157 |
+
def test_87_accepted_ack_provenance(self):
|
| 158 |
+
r=fixture();x=run(r);self.assertTrue(json.loads(x['provenance_json'])['source_condition_transfer_acknowledged'])
|
| 159 |
+
def test_88_highCO2_before_CuO_lowCO2_after(self):
|
| 160 |
+
r=fixture();x=run(r)
|
| 161 |
+
for w in x['windows']:
|
| 162 |
+
ch=w['gas_channels_relative'];self.assertAlmostEqual(ch['co2_high']+ch['co'],ch['co2_low']-ch['co'],places=12)
|
| 163 |
+
ch=max(x['windows'],key=lambda w:w['gas_channels_relative']['co2_low'])['gas_channels_relative'];self.assertGreater(ch['co2_low'],ch['co2_high']);self.assertNotAlmostEqual(ch['co2_high'],.5*ch['co2_low'],places=8)
|
| 164 |
+
def test_89_window_storage_bound(self):
|
| 165 |
+
r=fixture();m=copy.deepcopy(r.method);m.update(outgas_s=600.,purge_s=600.,baseline_s=600.,fusion_s=600.,integration_s=600.,window_s=.005);self.reject(r,'method.configure','WINDOW_CAPACITY',**m)
|
| 166 |
+
def test_90_whole_source_pin_not_arbitrary_fraction(self):
|
| 167 |
+
r=fixture();prepare(r);r.invoke('loading.set',loading=True);r.step(.06);r.invoke('sample.unload',recipient_id='r');a=sample(i='bam_d267_reference',mass=.0005);self.reject(r,'sample.load','WHOLE_SOURCE_PIN_REQUIRED',**a)
|
| 168 |
+
def test_91_idempotent_enable_preserves_active_power(self):
|
| 169 |
+
r=fixture();prepare(r);r.invoke('measurement.start');r.step(.08);p=r.actual_power;r.invoke('power.set',enabled=True);self.assertEqual(r.actual_power,p);self.assertEqual(r.phase,'running')
|
| 170 |
+
def test_92_cancel_gate_does_not_continue_command(self):
|
| 171 |
+
r=fixture();prepare(r);r.invoke('measurement.start');r.step(.38);q=r.q['sample_gate.position_m'];r.invoke('measurement.stop');r.step(.1);self.assertEqual(r.q['sample_gate.position_m'],q);self.assertFalse(r.dropped);self.ledger(r)
|
| 172 |
+
if __name__=='__main__':unittest.main()
|
tests/test_asset_linari_rtadvanced.py
ADDED
|
@@ -0,0 +1,125 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""CHEM-059 actual physics/protocol guards; no hardware validation."""
|
| 2 |
+
import copy,json,math,sys,unittest
|
| 3 |
+
from pathlib import Path
|
| 4 |
+
ROOT=Path(__file__).resolve().parents[1];sys.path.insert(0,str(ROOT/'scripts'))
|
| 5 |
+
from asset_runtime.linari_rtadvanced import *
|
| 6 |
+
def ready(all_pumps=False,method=None,plant=None):
|
| 7 |
+
h=LinariRtadvancedRuntime();h.invoke('plant.configure',**(plant or PLANT_EXAMPLE));h.invoke('collector.configure',**COLLECTOR_EXAMPLE)
|
| 8 |
+
for i in range(8 if all_pumps else 1):h.invoke('solution.load',**dict(SOLUTION_EXAMPLE,pump=i))
|
| 9 |
+
m=copy.deepcopy(method or METHOD_EXAMPLE)
|
| 10 |
+
if all_pumps:m['flows_m3_s']=[m['flows_m3_s'][0]]*8
|
| 11 |
+
h.invoke('method.configure',**m);h.invoke('power.set',enabled=True);h.invoke('vent.set',enabled=True);h.invoke('door.set',opened=False);h.invoke('hv.set',enabled=True);h.step(5)
|
| 12 |
+
return h
|
| 13 |
+
class TestRTAdvanced(unittest.TestCase):
|
| 14 |
+
def rejected(self,h,k,**a):
|
| 15 |
+
before=h.debug_snapshot()
|
| 16 |
+
with self.assertRaises(ActionRejected):h.invoke(k,**a)
|
| 17 |
+
self.assertEqual(before,h.debug_snapshot())
|
| 18 |
+
def conserved(self,h):
|
| 19 |
+
p=h.invoke('product.read')
|
| 20 |
+
for s in ['solvent','polymer']:self.assertAlmostEqual(p['initial_'+s+'_kg'],sum(p[l+'_'+s+'_kg'] for l in ['syringe','cone','mat','waste','evaporated','collected']),places=14)
|
| 21 |
+
def test_zero_stroke_needle(self):
|
| 22 |
+
h=ready(method=dict(METHOD_EXAMPLE,needle_low_m=[.03,.03],needle_high_m=[.03,.03]));h.invoke('acquisition.start');h.step(4);self.assertEqual(h.needle,[.03,.03]);self.conserved(h)
|
| 23 |
+
def test_button_power_toggle(self):
|
| 24 |
+
h=ready();h.invoke('power.toggle');self.assertFalse(h.powered);h.invoke('power.toggle');self.assertTrue(h.powered)
|
| 25 |
+
def test_axial_deposition_matches_tip_datum(self):
|
| 26 |
+
h=ready(method=dict(METHOD_EXAMPLE,needle_low_m=[.03,.03],needle_high_m=[.03,.03]));h.invoke('acquisition.start');h.step(4)
|
| 27 |
+
rows=h._product()['axial_polymer_kg'];expected=int((.03+.035)/.5*32);self.assertGreater(rows[expected],0);self.assertEqual(sum(rows[:expected]+rows[expected+1:]),0)
|
| 28 |
+
def test_outside_collector_goes_to_waste(self):
|
| 29 |
+
h=ready(plant=dict(PLANT_EXAMPLE,needle_speed_m_s=.1),method=dict(METHOD_EXAMPLE,needle_low_m=[.49,.49],needle_high_m=[.49,.49],duration_s=6.));h.invoke('acquisition.start');h.step(6)
|
| 30 |
+
self.assertEqual(h._product()['mat_polymer_kg'],0);self.assertGreater(h._product()['waste_polymer_kg'],0);self.conserved(h)
|
| 31 |
+
def test_ambiguous_morphology_not_runtime_anchor(self):
|
| 32 |
+
h=ready();rows=[r for r in h.templates.values() if r['fiber_morphology_ambiguous']];self.assertGreater(len(rows),0);self.assertTrue(all(not r['usable_as_runtime_anchor'] for r in rows))
|
| 33 |
+
def test_dimensions_and_ratings(self):
|
| 34 |
+
g=json.loads((ROOT/'assets/expansion_batch04/t5_automation/linari_rtadvanced/geometry_manifest.json').read_text());self.assertEqual(g['overall_dimensions_m'],[1.05,1.035,2.2])
|
| 35 |
+
def test_real_reference_lineage(self):
|
| 36 |
+
h=LinariRtadvancedRuntime();self.assertGreater(len(h.templates),1800)
|
| 37 |
+
for r in h.templates.values():self.assertGreater(r['value'],0);self.assertTrue(r['source']);self.assertGreater(r['row'],1);self.assertEqual(h.invoke('reference.lookup',substance_id=r['substance_id'])['mean_diameter_m'],r['value'])
|
| 38 |
+
def test_reference_is_not_rt_measurement(self):
|
| 39 |
+
h=ready();r=h.invoke('reference.lookup',substance_id='prelim_row_1261');self.assertEqual(r['evidence'],'measured_literature');self.assertIn('NOT_RT',h.invoke('spinning.measure')['evidence'])
|
| 40 |
+
def test_unknown_reference_atomic(self):self.rejected(ready(),'reference.lookup',substance_id='fake')
|
| 41 |
+
def test_eight_pumps_mass(self):
|
| 42 |
+
h=ready(True);h.invoke('acquisition.start');h.step(10);self.conserved(h);self.assertGreater(h.invoke('product.read')['mat_polymer_kg'],0)
|
| 43 |
+
self.assertTrue(all(h.read()['plunger.pump_'+str(i)+'_m']>0 for i in range(8)))
|
| 44 |
+
def test_finite_exhaustion(self):
|
| 45 |
+
h=ready(method=dict(METHOD_EXAMPLE,flows_m3_s=[1e-7]+[0.]*7,duration_s=100.));h.invoke('acquisition.start');h.step(30);self.assertEqual(h.phase,'failed');self.assertEqual(h.fault,'SYRINGE_EMPTY');self.conserved(h)
|
| 46 |
+
def test_low_field_drips(self):
|
| 47 |
+
h=ready(method=dict(METHOD_EXAMPLE,voltage_v=[100.,100.]));h.invoke('acquisition.start');h.step(10);p=h.invoke('product.read');self.assertEqual(p['mat_polymer_kg'],0);self.assertGreater(p['waste_polymer_kg'],0);self.conserved(h)
|
| 48 |
+
def test_cancel_retains_cone(self):
|
| 49 |
+
h=ready();h.invoke('acquisition.start');h.step(4);before=sum(h.cones[0]);h.invoke('acquisition.stop');self.assertEqual(sum(h.cones[0]),before);self.assertGreater(before,0);h.step(2);self.assertLess(sum(h.cones[0]),before);self.conserved(h)
|
| 50 |
+
def test_time_completion(self):
|
| 51 |
+
h=ready();h.invoke('acquisition.start');h.step(20);self.assertEqual(h.phase,'succeeded');self.assertAlmostEqual(h.elapsed_s,10.)
|
| 52 |
+
def test_plunger_volume(self):
|
| 53 |
+
h=ready();h.invoke('acquisition.start');h.step(6);consumed=h.loaded_volumes[0]-h._volume(h.syringes[0],h.solutions[0]);self.assertAlmostEqual(h.read()['plunger.pump_0_m']*math.pi*.022**2/4,consumed,places=16)
|
| 54 |
+
def test_two_independent_hv(self):
|
| 55 |
+
h=ready(method=dict(METHOD_EXAMPLE,voltage_v=[10000.,20000.]));self.assertAlmostEqual(h.volts[1],2*h.volts[0]);self.assertGreater(h.volts[0],0)
|
| 56 |
+
def test_rc_energy_conservation(self):
|
| 57 |
+
h=ready();h.step(3);h.invoke('hv.set',enabled=False);h.step(20);p=h.invoke('product.read');self.assertAlmostEqual(p['hv_source_j'],p['hv_dissipated_j']+p['hv_stored_j'],places=12)
|
| 58 |
+
def test_residual_hv_blocks_door(self):
|
| 59 |
+
h=ready();h.invoke('hv.set',enabled=False);self.rejected(h,'door.set',opened=True);h.step(25);h.invoke('door.set',opened=True);self.assertTrue(h.door)
|
| 60 |
+
def test_door_blocks_hv(self):
|
| 61 |
+
h=ready();h.invoke('hv.set',enabled=False);h.step(25);h.invoke('door.set',opened=True);self.rejected(h,'hv.set',enabled=True)
|
| 62 |
+
def test_vent_loss_fails_and_bleeds(self):
|
| 63 |
+
h=ready();h.invoke('acquisition.start');h.step(1);v=h.volts[0];h.invoke('vent.set',enabled=False);self.assertEqual(h.phase,'failed');h.step(1);self.assertLess(h.volts[0],v);self.assertFalse(h.hv)
|
| 64 |
+
def test_emergency_latched(self):
|
| 65 |
+
h=ready();h.invoke('acquisition.start');h.invoke('safety.trip');self.assertTrue(h.latched);self.assertEqual(h.phase,'failed');self.rejected(h,'safety.reset');h.step(25);h.invoke('safety.reset');self.assertFalse(h.latched)
|
| 66 |
+
def test_poweroff_residuals(self):
|
| 67 |
+
h=ready();h.invoke('acquisition.start');h.step(4);v=h.volts[0];h.invoke('power.set',enabled=False);self.assertEqual(h.phase,'cancelled');self.assertGreater(h.volts[0],0);h.step(1);self.assertLess(h.volts[0],v);self.conserved(h)
|
| 68 |
+
def test_climate_noninstant_and_balance(self):
|
| 69 |
+
h=ready();h.invoke('climate.set_targets',temperature_k=313.15,humidity=.65);h.invoke('climate.set',enabled=True);self.assertEqual(h.temperature,298.15);h.step(10);self.assertGreater(h.temperature,298.15);self.assertLess(h.temperature,313.15);self.assertGreater(h.rh,.4);self.assertLess(h.rh,.65)
|
| 70 |
+
p=h.invoke('product.read');self.assertAlmostEqual(p['heater_input_j']-p['thermal_loss_j'],p['sensible_j'],places=7)
|
| 71 |
+
def test_cooling_after_poweroff(self):
|
| 72 |
+
h=ready();h.invoke('climate.set_targets',temperature_k=313.15,humidity=.65);h.invoke('climate.set',enabled=True);h.step(10);before=h.temperature;h.invoke('power.set',enabled=False);h.step(10);self.assertLess(h.temperature,before)
|
| 73 |
+
def test_task_rh_temperature_bounds(self):
|
| 74 |
+
h=ready()
|
| 75 |
+
for t,r in [(324.,.5),(293.15,.5),(303.15,.19),(303.15,.71)]:self.rejected(h,'climate.set_targets',temperature_k=t,humidity=r)
|
| 76 |
+
def test_rotation_negative_and_angle(self):
|
| 77 |
+
h=ready(method=dict(METHOD_EXAMPLE,rpm=-5000.));h.invoke('acquisition.start');h.step(1);self.assertLess(h.rpm,0);self.assertGreaterEqual(h.angle,0);self.assertLess(h.angle,2*math.pi)
|
| 78 |
+
def test_needle_reversal_bounds(self):
|
| 79 |
+
h=ready(method=dict(METHOD_EXAMPLE,needle_low_m=[.02,.02],needle_high_m=[.04,.04],duration_s=10));h.invoke('acquisition.start')
|
| 80 |
+
for _ in range(15):h.step(.2);self.assertTrue(all(0<=z<=.04 for z in h.needle))
|
| 81 |
+
self.assertTrue(any(d<0 for d in h.direction))
|
| 82 |
+
def test_collector_range_and_capacity(self):
|
| 83 |
+
h=LinariRtadvancedRuntime();h.invoke('plant.configure',**PLANT_EXAMPLE);self.rejected(h,'solution.load',**dict(SOLUTION_EXAMPLE,solvent_kg=.06));h.invoke('collector.configure',**dict(COLLECTOR_EXAMPLE,length_m=.1));self.rejected(h,'method.configure',**METHOD_EXAMPLE)
|
| 84 |
+
def test_invalid_scalars_and_extra_fields(self):
|
| 85 |
+
h=ready()
|
| 86 |
+
for d in [-1,float('nan'),float('inf'),True]:
|
| 87 |
+
before=h.debug_snapshot()
|
| 88 |
+
with self.assertRaises(ActionRejected):h.step(d)
|
| 89 |
+
self.assertEqual(before,h.debug_snapshot())
|
| 90 |
+
self.rejected(h,'power.set',enabled=1);self.rejected(h,'power.set',enabled=True,extra=1)
|
| 91 |
+
def test_double_loading_atomic(self):
|
| 92 |
+
h=ready();self.rejected(h,'solution.load',**SOLUTION_EXAMPLE)
|
| 93 |
+
def test_clean_drain_collect_mass(self):
|
| 94 |
+
h=ready();h.invoke('acquisition.start');h.step(10);h.invoke('hv.set',enabled=False);h.step(25);h.invoke('needle.clean',group=0);h.invoke('door.set',opened=True);h.invoke('product.collect',recipient_id='mat');h.invoke('solution.drain',pump=0);self.conserved(h);self.assertFalse(h.collector_present)
|
| 95 |
+
def test_step_subdivision(self):
|
| 96 |
+
a=ready();b=ready()
|
| 97 |
+
for h in [a,b]:h.invoke('acquisition.start')
|
| 98 |
+
a.step(8)
|
| 99 |
+
for _ in range(400):b.step(.02)
|
| 100 |
+
for k in ['mat_polymer_kg','evaporated_solvent_kg','syringe_polymer_kg']:self.assertAlmostEqual(a._product()[k],b._product()[k],places=14)
|
| 101 |
+
def test_material_50_systems_not_rows(self):
|
| 102 |
+
h=ready();labels={r['canonical_material_system'] for r in h.templates.values()};self.assertGreaterEqual(len(labels),50);self.assertGreater(len(h.templates),len(labels))
|
| 103 |
+
def test_agent_truth_and_role_boundary(self):
|
| 104 |
+
h=ready();s=h.session();self.assertNotIn('truth.ledger',s.describe(instance_id=h.instance_id)['state_slots'])
|
| 105 |
+
with self.assertRaises(ActionRejected):s.read(instance_id=h.instance_id,state_ids=['truth.ledger'])
|
| 106 |
+
r=s.invoke(instance_id=h.instance_id,capability_id='product.read',arguments={},request_id='x');self.assertEqual(r['error']['code'],'ACCESS_DENIED')
|
| 107 |
+
self.assertNotIn('product.read',s.describe(instance_id=h.instance_id)['capabilities'])
|
| 108 |
+
def test_request_idempotency_and_conflict(self):
|
| 109 |
+
h=ready();s=h.session();args=dict(instance_id=h.instance_id,capability_id='acquisition.start',arguments={},request_id='a');a=s.invoke(**args);rev=h.revision;self.assertEqual(s.invoke(**args),a);self.assertEqual(h.revision,rev)
|
| 110 |
+
r=s.invoke(**dict(args,capability_id='acquisition.stop'));self.assertEqual(r['error']['code'],'REQUEST_CONFLICT')
|
| 111 |
+
def test_operation_ownership_and_cancel(self):
|
| 112 |
+
h=ready();s=h.session();h.register_principal('other');t=h.session('other');r=s.invoke(instance_id=h.instance_id,capability_id='acquisition.start',arguments={},request_id='a');op=r['operation_id']
|
| 113 |
+
with self.assertRaises(ActionRejected):t.poll(op)
|
| 114 |
+
h.step(3);self.assertEqual(s.cancel(op,'cancel')['status'],'succeeded');self.assertEqual(s.poll(op)['status'],'cancelled')
|
| 115 |
+
def test_read_does_not_advance_or_alias(self):
|
| 116 |
+
h=ready();before=h.debug_snapshot();p=h.read('evaluator');p['truth.ledger']['axial_polymer_kg'][0]=999;self.assertEqual(h.debug_snapshot(),before);h.invoke('spinning.measure');self.assertEqual(h.debug_snapshot(),before)
|
| 117 |
+
def test_write_routes_and_permissions(self):
|
| 118 |
+
h=ready();s=h.session();r=s.write(instance_id=h.instance_id,state_id='hv.enabled',value=False,request_id='w');self.assertEqual(r['status'],'succeeded')
|
| 119 |
+
with self.assertRaises(ActionRejected):s.write(instance_id=h.instance_id,state_id='vent.enabled',value=True,request_id='forbidden')
|
| 120 |
+
def test_session_errors_and_unknown_instance(self):
|
| 121 |
+
h=ready();s=h.session();r=s.invoke(instance_id='unknown',capability_id='power.set',arguments={'enabled':True},request_id='x');self.assertEqual(r['error']['code'],'UNKNOWN_INSTANCE')
|
| 122 |
+
r=s.invoke(instance_id=h.instance_id,capability_id='fake',arguments={},request_id='x');self.assertEqual(r['error']['code'],'UNKNOWN_CAPABILITY')
|
| 123 |
+
def test_collector_reconfigure_and_no_free_mass(self):
|
| 124 |
+
h=ready();h.invoke('acquisition.start');h.step(10);h.invoke('hv.set',enabled=False);h.step(25);h.invoke('needle.clean',group=0);h.invoke('door.set',opened=True);h.invoke('product.collect',recipient_id='mat');h.invoke('collector.configure',**COLLECTOR_EXAMPLE);self.conserved(h);self.assertEqual(sum(h._product()['axial_polymer_kg']),0)
|
| 125 |
+
if __name__=='__main__':unittest.main()
|
tests/test_asset_malvern_leneo.py
ADDED
|
@@ -0,0 +1,101 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import copy,json,math,sys,unittest
|
| 2 |
+
from pathlib import Path
|
| 3 |
+
ROOT=Path(__file__).resolve().parents[1];sys.path.insert(0,str(ROOT/'scripts'))
|
| 4 |
+
from asset_runtime.malvern_leneo import *
|
| 5 |
+
def configured(fast=False,solution=False,mode=1):
|
| 6 |
+
r=MalvernLeneoRuntime();p=copy.deepcopy(PLANT_EXAMPLE);m=copy.deepcopy(METHOD_EXAMPLE);s=copy.deepcopy(SAMPLE_EXAMPLE)
|
| 7 |
+
if fast:
|
| 8 |
+
p.update(chamber_C_J_K=100.,crucible_C_J_K=10.,receiver_C_J_K=10.,chamber_UA_W_K=.1,charge_UA_W_K=30.,fan_UA_W_K=10.,heater_W=4800.,supply_V=240.,controller_W_K=1000.,solidus_K=500.,liquidus_K=600.,latent_J_kg=10000.,dissolution_rate_s=2.,viscosity_Pa_s=.1,viscosity_activation_K=0.,pour_kg_s=.005,solution_rate_s=2.)
|
| 9 |
+
m.update(segments=[dict(duration_s=6.,end_temperature_K=700.),dict(duration_s=12.,end_temperature_K=700.)],host_pour_profiles=[dict(angle_rad=a,duration_s=4.) for a in [1.6,1.8,2.,2.2]],minimum_cooling_s=2.)
|
| 10 |
+
if solution:m['output']='borate_solution';s['solvent_kg']=.1
|
| 11 |
+
m['pour_mode']=mode
|
| 12 |
+
for k,a in [('plant.configure',p),('method.configure',m),('sample.configure',s),('power.set',dict(enabled=True)),('door.set_open',dict(open=False))]:r.invoke(k,**a)
|
| 13 |
+
r.step(1);return r
|
| 14 |
+
def complete(r,seconds=3000):
|
| 15 |
+
r.invoke('acquisition.start')
|
| 16 |
+
for j in range(seconds):
|
| 17 |
+
r.step(1)
|
| 18 |
+
if r.phase!='running':break
|
| 19 |
+
return r
|
| 20 |
+
def balances(r):
|
| 21 |
+
q=r._product();return [q['initial_sample_kg']-sum(q[k] for k in ['crucible_sample_kg','receiver_sample_kg','lost_sample_kg','collected_sample_kg']),q['initial_flux_kg']-q['crucible_flux_kg']-q['receiver_flux_kg']-q['collected_flux_kg'],q['initial_solvent_kg']-q['receiver_solvent_kg']-q['collected_solvent_kg'],q['electrical_J']-q['storage_J']-q['loss_J']-q['advected_loss_J']-q['collected_enthalpy_J']]
|
| 22 |
+
class LeNeoTests(unittest.TestCase):
|
| 23 |
+
def test_set_target_not_heat(self):
|
| 24 |
+
r=configured(True);t=r.chamber;r.invoke('thermal.set_temperature',temperature_K=1473.15);self.assertEqual(r.chamber,t);r.step(2);self.assertEqual(r.chamber,t)
|
| 25 |
+
def test_default_complete(self):self.assertEqual(complete(configured()).phase,'succeeded')
|
| 26 |
+
def test_fast_complete(self):self.assertEqual(complete(configured(True),150).phase,'succeeded')
|
| 27 |
+
def test_four_modes(self):
|
| 28 |
+
for i in range(1,5):self.assertEqual(complete(configured(True,mode=i),150).phase,'succeeded')
|
| 29 |
+
def test_solution(self):
|
| 30 |
+
r=complete(configured(True,True),150);self.assertEqual(r.phase,'succeeded');self.assertGreater(r.rs,0);self.assertEqual(r.solvent,.1)
|
| 31 |
+
def test_finite_collect(self):
|
| 32 |
+
r=complete(configured(True),150);r.invoke('door.set_open',open=True);r.step(1);old=r.rs+r.rf;self.assertAlmostEqual(r.invoke('product.collect',fraction=.5,recipient_id='XRF')['transferred_kg'],old/2)
|
| 33 |
+
for v in balances(r):self.assertLess(abs(v),1e-5)
|
| 34 |
+
def test_ledgers(self):
|
| 35 |
+
r=configured(True);r.invoke('acquisition.start')
|
| 36 |
+
for i in range(80):
|
| 37 |
+
r.step(1)
|
| 38 |
+
for v in balances(r):self.assertLess(abs(v),1e-5)
|
| 39 |
+
def test_flow_not_teleport(self):
|
| 40 |
+
r=configured(True);r.invoke('acquisition.start');r.step(18);self.assertEqual(r.rs+r.rf,0);r.step(.1);self.assertLess(r.rs+r.rf,r.sample['sample_kg']+r.sample['flux_kg'])
|
| 41 |
+
def test_emergency(self):
|
| 42 |
+
r=configured(True);r.invoke('acquisition.start');r.step(8);r.invoke('emergency.stop');old=r.electrical;r.step(1);self.assertEqual(old,r.electrical);self.assertTrue(r.locked());self.assertEqual(r.phase,'failed')
|
| 43 |
+
def test_hot_door(self):
|
| 44 |
+
r=configured(True);r.invoke('acquisition.start');r.step(8);r.invoke('acquisition.stop')
|
| 45 |
+
with self.assertRaises(ActionRejected):r.invoke('door.set_open',open=True)
|
| 46 |
+
def test_cancel(self):
|
| 47 |
+
r=configured(True);r.invoke('acquisition.start');r.step(8);mass=r.ms+r.mf;r.invoke('acquisition.stop');r.step(2);self.assertEqual(r.ms+r.mf,mass)
|
| 48 |
+
def test_power_cancel(self):
|
| 49 |
+
r=configured(True);r.invoke('acquisition.start');r.invoke('power.toggle');self.assertEqual(r.phase,'cancelled')
|
| 50 |
+
def test_door_actual(self):
|
| 51 |
+
r=configured(True);r.invoke('door.set_open',open=True)
|
| 52 |
+
with self.assertRaises(ActionRejected):r.invoke('acquisition.start')
|
| 53 |
+
def test_missing_config(self):
|
| 54 |
+
with self.assertRaises(ActionRejected):MalvernLeneoRuntime().invoke('acquisition.start')
|
| 55 |
+
def test_one_position(self):
|
| 56 |
+
with self.assertRaises(ActionRejected):configured(True).invoke('sample.configure',**SAMPLE_EXAMPLE)
|
| 57 |
+
def test_voltage_power(self):
|
| 58 |
+
p=dict(PLANT_EXAMPLE,heater_W=4800.,supply_V=208.)
|
| 59 |
+
with self.assertRaises(ActionRejected):MalvernLeneoRuntime().invoke('plant.configure',**p)
|
| 60 |
+
def test_bad_phase_range(self):
|
| 61 |
+
with self.assertRaises(ActionRejected):MalvernLeneoRuntime().invoke('plant.configure',**dict(PLANT_EXAMPLE,liquidus_K=999.))
|
| 62 |
+
def test_mode_count(self):
|
| 63 |
+
with self.assertRaises(ActionRejected):MalvernLeneoRuntime().invoke('method.configure',**dict(METHOD_EXAMPLE,host_pour_profiles=[]))
|
| 64 |
+
def test_acceptance_required(self):
|
| 65 |
+
with self.assertRaises(ActionRejected):MalvernLeneoRuntime().invoke('plant.configure',**dict(PLANT_EXAMPLE,accept_uncalibrated_model=False))
|
| 66 |
+
def test_temperature_limit(self):
|
| 67 |
+
with self.assertRaises(ActionRejected):configured().invoke('thermal.set_temperature',temperature_K=1474.)
|
| 68 |
+
def test_invalid_steps_atomic(self):
|
| 69 |
+
r=configured(True);old=r.debug_snapshot()
|
| 70 |
+
for x in [True,-1,float('nan'),float('inf'),7201]:
|
| 71 |
+
with self.assertRaises(ActionRejected):r.step(x)
|
| 72 |
+
self.assertEqual(old,r.debug_snapshot())
|
| 73 |
+
def test_query_pure(self):
|
| 74 |
+
r=configured(True);old=r.debug_snapshot()
|
| 75 |
+
for k in ['fusion.measure','product.read']:r.invoke(k)
|
| 76 |
+
r.invoke('reference.lookup',substance_id='janaf_al_096',temperature_K=1000.);self.assertEqual(old,r.debug_snapshot())
|
| 77 |
+
def test_real_cp(self):
|
| 78 |
+
r=MalvernLeneoRuntime();t=r.templates['janaf_al_096'];self.assertAlmostEqual(r.reference('janaf_al_096',298.15)['cp_J_kg_K'],79.015/t['molar_mass_kg_mol'])
|
| 79 |
+
def test_reference_no_extrapolation(self):
|
| 80 |
+
with self.assertRaises(ActionRejected):MalvernLeneoRuntime().reference('janaf_al_096',1501.)
|
| 81 |
+
def test_unknown_reference(self):
|
| 82 |
+
with self.assertRaises(ActionRejected):MalvernLeneoRuntime().reference('fake',1000.)
|
| 83 |
+
def test_truth_hidden(self):
|
| 84 |
+
r=configured(True);self.assertFalse(any(x.startswith('truth.') for x in r.read()));self.assertIn('truth.ledger',r.read('evaluator'))
|
| 85 |
+
def test_principal_filter(self):
|
| 86 |
+
r=configured(True);x=r.session().invoke(instance_id=r.instance_id,capability_id='product.read',arguments={},request_id='p');self.assertEqual(x['error']['code'],'ACCESS_DENIED')
|
| 87 |
+
def test_request_idempotency(self):
|
| 88 |
+
r=configured(True);s=r.session();a=dict(instance_id=r.instance_id,capability_id='power.toggle',arguments={},request_id='x');x=s.invoke(**a);self.assertEqual(x,s.invoke(**a));self.assertFalse(r.powered)
|
| 89 |
+
def test_request_conflict(self):
|
| 90 |
+
r=configured(True);s=r.session();s.invoke(instance_id=r.instance_id,capability_id='power.toggle',arguments={},request_id='x');x=s.invoke(instance_id=r.instance_id,capability_id='power.set',arguments=dict(enabled=True),request_id='x');self.assertEqual(x['error']['code'],'REQUEST_CONFLICT')
|
| 91 |
+
def test_async(self):
|
| 92 |
+
r=configured(True);s=r.session();x=s.invoke(instance_id=r.instance_id,capability_id='acquisition.start',arguments={},request_id='x');self.assertEqual(x['status'],'accepted');self.assertEqual(s.poll(x['operation_id'])['status'],'running');s.cancel(x['operation_id'],'c');self.assertEqual(r.phase,'cancelled')
|
| 93 |
+
def test_time_partition(self):
|
| 94 |
+
a=configured(True);b=configured(True)
|
| 95 |
+
for r in [a,b]:r.invoke('acquisition.start')
|
| 96 |
+
a.step(2)
|
| 97 |
+
for i in range(100):b.step(.02)
|
| 98 |
+
self.assertAlmostEqual(a.chamber,b.chamber,8)
|
| 99 |
+
def test_partial_fusion_failure(self):
|
| 100 |
+
r=configured(True);r.method['segments']=[dict(duration_s=1,end_temperature_K=310.)];r.invoke('acquisition.start');r.step(2);self.assertEqual(r.stage,'incomplete_fusion')
|
| 101 |
+
if __name__=='__main__':unittest.main()
|
tests/test_asset_markes_unityxr.py
ADDED
|
@@ -0,0 +1,85 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import unittest,copy,math,importlib.util
|
| 2 |
+
from scripts.asset_runtime import markes_unityxr as r
|
| 3 |
+
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()
|
| 4 |
+
def call(h,k,a=None):
|
| 5 |
+
v=h.invoke(k,**(a or {}));tool.validate_value(v,r.CAPS[k][1]);OBSERVED.add(k);return v
|
| 6 |
+
def setup(plant=None,method=None,sample=None):
|
| 7 |
+
h=r.MarkesUnityxrRuntime()
|
| 8 |
+
for k,a in [('plant.configure',dict(r.PLANT_EXAMPLE,**(plant or {}))),('method.configure',dict(r.METHOD_EXAMPLE,**(method or {}))),('lid.set',{'lift_m':.18}),('sample_lever.set',{'angle_rad':1.1}),('recollect_lever.set',{'angle_rad':1.1}),('sample.load',sample or r.SAMPLE_EXAMPLE),('recollection.install',{'installed':True}),('sample_lever.set',{'angle_rad':0.}),('recollect_lever.set',{'angle_rad':0.}),('lid.set',{'lift_m':0.}),('power.set',{'enabled':True})]:call(h,k,a)
|
| 9 |
+
return h
|
| 10 |
+
def until(h,stage,max_s=600):
|
| 11 |
+
for _ in range(max_s*2):
|
| 12 |
+
if h.stage==stage:return
|
| 13 |
+
if h.phase=='failed':raise AssertionError(h.failure)
|
| 14 |
+
h.step(.5)
|
| 15 |
+
raise AssertionError((stage,h.stage,h.T,h.phase))
|
| 16 |
+
def finish(h):
|
| 17 |
+
if h.phase!='running':call(h,'acquisition.start')
|
| 18 |
+
call(h,'gc.ready',{'ready':True})
|
| 19 |
+
for _ in range(1200):
|
| 20 |
+
h.step(.5)
|
| 21 |
+
if h.phase!='running':break
|
| 22 |
+
assert h.phase=='succeeded',(h.phase,h.stage,h.T,h.failure)
|
| 23 |
+
return h
|
| 24 |
+
class Tests(unittest.TestCase):
|
| 25 |
+
def ledger(self,h):
|
| 26 |
+
v=call(h,'ledger.read');self.assertLess(abs(v['carrier_residual_mol']),2e-10);self.assertLess(abs(v['dry_residual_mol']),2e-10);self.assertLess(abs(v['energy_residual_j']),1e-6);self.assertLessEqual(v['peak_electrical_w'],650.)
|
| 27 |
+
for x in v['species']:self.assertLess(abs(x['residual_kg']),max(1e-19,x['loaded_kg']*1e-11))
|
| 28 |
+
def test_01_real_values_and_metadata(self):
|
| 29 |
+
h=setup();m=r.export_markes_unityxr_contract_metadata();self.assertEqual(len(m['capabilities']),26);self.assertEqual(len(h.library['substances']),197);self.assertEqual(sum(x['kinetics_enabled'] for x in h.library['substances'].values()),178);v=call(h,'template.reference',{'substance_id':'tenax_toluene'});self.assertEqual(v['retention_volume_m3'],.076);self.assertEqual(v['evidence'],'derived');self.assertTrue(call(h,'template.reference',{'substance_id':'tenax_tetrachloromethane'})['flags'])
|
| 30 |
+
def test_02_complete_conservation(self):
|
| 31 |
+
h=finish(setup());self.assertEqual(h.triggers,1);self.assertEqual(sum(x['gc_trigger'] for x in h.trace),1);self.assertGreater(sum(h.output.values()),0.);self.assertGreater(sum(h.recollect.values()),0.);self.ledger(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.ledger(h)
|
| 32 |
+
def test_03_gc_waits_without_loss(self):
|
| 33 |
+
h=setup();call(h,'acquisition.start');until(h,'wait_gc');before=h.trap.copy();h.step(10);self.assertEqual(h.stage,'wait_gc');self.assertEqual(h.trap,before);self.assertEqual(h.triggers,0);finish(h);self.ledger(h)
|
| 34 |
+
def test_04_common_capacity_and_recollection(self):
|
| 35 |
+
h=finish(setup(plant={'trap_capacity_kg':1e-10,'recollect_capacity_kg':2e-10}));self.assertLessEqual(sum(h.trap.values()),1e-10+1e-20);self.assertLessEqual(sum(h.recollect.values()),2e-10+1e-20);self.assertGreater(sum(h.waste.values()),1e-8);self.ledger(h)
|
| 36 |
+
def test_05_capture_not_species_order_dependent(self):
|
| 37 |
+
a=setup(plant={'trap_capacity_kg':3e-9});b=copy.deepcopy(a);a._capture({'tenax_toluene':4e-9,'tenax_hexane':2e-9},'trap',3e-9);b._capture({'tenax_hexane':2e-9,'tenax_toluene':4e-9},'trap',3e-9);self.assertEqual(a.trap,b.trap);self.assertAlmostEqual(a.trap['tenax_toluene'],2e-9,places=20)
|
| 38 |
+
def test_06_failed_leak_preserves_sample(self):
|
| 39 |
+
h=setup(plant={'leak_rate_s_inv':.2});before=h.tube.copy();call(h,'acquisition.start');h.step(5);self.assertEqual(h.failure,'LEAK_TEST_FAILED');self.assertEqual(h.tube,before);self.assertFalse(h.output);self.assertEqual(h.T[0],293.15);self.ledger(h)
|
| 40 |
+
def test_07_gas_depletion(self):
|
| 41 |
+
h=setup(plant={'dry_supply_mol':.001});before=h.tube.copy();call(h,'acquisition.start');h.step(20.);self.assertEqual(h.failure,'DRY_GAS_DEPLETED');self.assertEqual(before,h.tube);self.ledger(h)
|
| 42 |
+
h=setup(plant={'carrier_supply_mol':.001});call(h,'acquisition.start');h.step(100.);self.assertEqual(h.failure,'CARRIER_DEPLETED');self.ledger(h)
|
| 43 |
+
def test_08_cancel_keeps_partial_effects(self):
|
| 44 |
+
h=setup();call(h,'acquisition.start');until(h,'primary');h.step(55.);self.assertGreater(sum(h.recollect.values()),0);call(h,'acquisition.stop');before=[x.copy() for x in [h.tube,h.trap,h.recollect]];h.step(10.);self.assertEqual(before,[h.tube,h.trap,h.recollect]);self.assertEqual(h.phase,'cancelled');self.ledger(h)
|
| 45 |
+
def test_09_poweroff_still_cools(self):
|
| 46 |
+
h=setup();call(h,'acquisition.start');until(h,'primary');h.step(30);t=h.T[0];heat=h.heat;cool=h.cooling;call(h,'power.set',{'enabled':False});h.step(10);self.assertLess(h.T[0],t);self.assertEqual(heat,h.heat);self.assertEqual(cool,h.cooling);self.ledger(h)
|
| 47 |
+
def test_10_invalid_atomic(self):
|
| 48 |
+
h=setup();old=h.read('evaluator')
|
| 49 |
+
for k,a in [('method.configure',dict(r.METHOD_EXAMPLE,tube_hold_s=7.)),('method.configure',dict(r.METHOD_EXAMPLE,tube_k=698.15)),('method.configure',dict(r.METHOD_EXAMPLE,outlet_split_m3_s=0.,column_flow_m3_s=2e-6/60)),('lid.set',{'lift_m':float('nan')}),('power.set',{'enabled':1})]:
|
| 50 |
+
with self.assertRaises(r.ActionRejected):call(h,k,a)
|
| 51 |
+
self.assertEqual(h.read('evaluator'),old)
|
| 52 |
+
def test_11_partition(self):
|
| 53 |
+
a=setup();call(a,'acquisition.start');b=copy.deepcopy(a);a.step(7.3)
|
| 54 |
+
for _ in range(73):b.step(.1)
|
| 55 |
+
self.assertEqual(a.read('evaluator'),b.read('evaluator'));self.assertEqual(a.T,b.T);self.assertEqual(a.tube,b.tube)
|
| 56 |
+
def test_12_pure_queries_and_instances(self):
|
| 57 |
+
a=setup();b=setup();call(a,'acquisition.start');a.step(40);old=a.read('evaluator');call(a,'process.measure');call(a,'ledger.read');a.describe();self.assertEqual(a.read('evaluator'),old);self.assertEqual(b.time_s,0.)
|
| 58 |
+
def test_13_hot_and_access_interlocks(self):
|
| 59 |
+
h=setup()
|
| 60 |
+
with self.assertRaises(r.ActionRejected):call(h,'sample_lever.set',{'angle_rad':1.1})
|
| 61 |
+
call(h,'acquisition.start');until(h,'primary');h.step(30)
|
| 62 |
+
with self.assertRaises(r.ActionRejected):call(h,'lid.set',{'lift_m':.18})
|
| 63 |
+
call(h,'acquisition.stop')
|
| 64 |
+
with self.assertRaises(r.ActionRejected):call(h,'shield.set',{'lift_m':.12})
|
| 65 |
+
def test_14_real_reference_transport(self):
|
| 66 |
+
h=setup();n=h.tube['tenax_toluene'];q=100e-6/60;out=h._release(h.tube,293.15,.0002,q);self.assertAlmostEqual(out['tenax_toluene'],n*(-math.expm1(-q/.076*r.DT)),places=24)
|
| 67 |
+
def test_15_cold_unload_recollection(self):
|
| 68 |
+
h=finish(setup());call(h,'lid.set',{'lift_m':.18});call(h,'sample_lever.set',{'angle_rad':1.1});call(h,'recollect_lever.set',{'angle_rad':1.1});v=call(h,'recollection.collect');self.assertGreater(sum(x['mass_kg'] for x in v['species']),0);self.assertFalse(call(h,'recollection.collect')['species']);call(h,'sample.unload');call(h,'recollection.install',{'installed':False});self.ledger(h)
|
| 69 |
+
h=setup();call(h,'power.set',{'enabled':False});call(h,'rear.set',{'slide_m':.15});call(h,'shield.set',{'lift_m':.12})
|
| 70 |
+
def test_16_conditioning_routes(self):
|
| 71 |
+
h=finish(setup(method={'mode':'tube_condition','recollect':False}));self.assertFalse(h.output);self.assertFalse(h.trap);self.assertEqual(h.triggers,0);self.assertGreater(sum(h.waste.values()),1e-8);self.ledger(h)
|
| 72 |
+
h=setup();call(h,'acquisition.start');until(h,'primary');h.step(60);call(h,'acquisition.stop');self.assertGreater(sum(h.trap.values()),0);call(h,'method.configure',dict(r.METHOD_EXAMPLE,mode='trap_condition',recollect=False));finish(h);self.assertFalse(h.output);self.assertEqual(h.triggers,0);self.ledger(h)
|
| 73 |
+
def test_17_ballistic_and_nitrogen(self):
|
| 74 |
+
h=setup(plant={'carrier':'nitrogen'})
|
| 75 |
+
with self.assertRaises(r.ActionRejected):call(h,'method.configure',dict(r.METHOD_EXAMPLE,trap_flow_m3_s=300e-6/60))
|
| 76 |
+
a=setup();call(a,'acquisition.start');until(a,'wait_gc');b=copy.deepcopy(a);b.method['trap_heating']='ballistic';call(a,'gc.ready',{'ready':True});call(b,'gc.ready',{'ready':True});a.step(1.);b.step(1.);self.assertGreater(b.T[1],a.T[1]+40);self.assertLessEqual(b.T[1]-263.15,100.1);self.ledger(a);self.ledger(b)
|
| 77 |
+
def test_18_permissions_dedup_unsupported(self):
|
| 78 |
+
h=setup();h.register_principal('agent');h.register_principal('second');h.register_principal('eval','evaluator');s=h.session('agent');q=h.session('second');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')
|
| 79 |
+
with self.assertRaises(r.ActionRejected):q.poll(v['operation_id'])
|
| 80 |
+
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')
|
| 81 |
+
for k in r.UNSUPPORTED:
|
| 82 |
+
with self.assertRaisesRegex(r.ActionRejected,'UNSUPPORTED'):h.invoke(k)
|
| 83 |
+
for dt in [True,-1,float('nan'),float('inf')]:
|
| 84 |
+
with self.assertRaises(r.ActionRejected):h.step(dt)
|
| 85 |
+
if __name__=='__main__':unittest.main()
|
tests/test_asset_metrohm_909uv.py
ADDED
|
@@ -0,0 +1,83 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import copy,math,sys,unittest
|
| 2 |
+
from pathlib import Path
|
| 3 |
+
sys.path.insert(0,str(Path(__file__).resolve().parents[1]/'scripts'))
|
| 4 |
+
from asset_runtime.metrohm_909uv import *
|
| 5 |
+
def prepared(plant=None,method=None,sample=None):
|
| 6 |
+
r=Metrohm909uvRuntime();p=copy.deepcopy(PLANT_EXAMPLE);p.update(plant or {});m=copy.deepcopy(METHOD_EXAMPLE);m.update(method or {});s=example_sample();s.update(sample or {})
|
| 7 |
+
for c,a in [('plant.configure',p),('method.configure',m),('sample.configure',s),('power.set',dict(enabled=True)),('shield.set_open',dict(open=False))]:r.invoke(c,**a)
|
| 8 |
+
r.step(1.1);return r
|
| 9 |
+
class Tests(unittest.TestCase):
|
| 10 |
+
def reject(self,r,c,**a):
|
| 11 |
+
before=r.debug_snapshot()
|
| 12 |
+
with self.assertRaises(ActionRejected):r.invoke(c,**a)
|
| 13 |
+
self.assertEqual(before,r.debug_snapshot())
|
| 14 |
+
def test_setpoint_only(self):
|
| 15 |
+
r=prepared();t=r.temperature;r.invoke('thermal.set_temperature',temperature_K=373.15);self.assertEqual(t,r.temperature)
|
| 16 |
+
def test_shield_only_on_step(self):
|
| 17 |
+
r=Metrohm909uvRuntime();r.invoke('shield.set_open',open=False);self.assertEqual(r.shield_angle,math.pi);r.step(.5);self.assertAlmostEqual(r.shield_angle,math.pi/2)
|
| 18 |
+
def test_query_pure(self):
|
| 19 |
+
r=prepared();before=r.debug_snapshot();r.read();r.describe();r.invoke('digestion.measure');r.session().read(instance_id=r.instance_id);self.assertEqual(before,r.debug_snapshot())
|
| 20 |
+
def test_start_requires_all(self):
|
| 21 |
+
self.reject(Metrohm909uvRuntime(),'acquisition.start')
|
| 22 |
+
def test_volume(self):
|
| 23 |
+
r=Metrohm909uvRuntime();r.invoke('plant.configure',**PLANT_EXAMPLE);s=example_sample();s['tubes'][0]['volume_m3']=12.1e-6;self.reject(r,'sample.configure',**s)
|
| 24 |
+
def test_12_tubes(self):
|
| 25 |
+
r=Metrohm909uvRuntime();r.invoke('plant.configure',**PLANT_EXAMPLE);s=example_sample();s['tubes'].pop();self.reject(r,'sample.configure',**s)
|
| 26 |
+
def test_sensor6(self):
|
| 27 |
+
r=Metrohm909uvRuntime();r.invoke('plant.configure',**PLANT_EXAMPLE);s=example_sample();s['sensor_position']=5;self.reject(r,'sample.configure',**s)
|
| 28 |
+
def test_ph_guard(self):
|
| 29 |
+
r=Metrohm909uvRuntime();r.invoke('plant.configure',**PLANT_EXAMPLE);s=example_sample();s['tubes'][5]['pH']=1.;self.reject(r,'sample.configure',**s)
|
| 30 |
+
def test_unknown_reference(self):
|
| 31 |
+
r=prepared();self.reject(r,'reference.lookup',substance_id='not_real')
|
| 32 |
+
def test_method_granularity(self):
|
| 33 |
+
r=prepared();self.reject(r,'method.configure',temperature_K=363.15,duration_s=61.);self.reject(r,'thermal.set_temperature',temperature_K=363.65)
|
| 34 |
+
def test_timer_from_ignition(self):
|
| 35 |
+
r=prepared();r.invoke('acquisition.start');r.step(1.);self.assertAlmostEqual(r.elapsed_s,1.);self.assertLess(r.temperature,353.15)
|
| 36 |
+
def test_complete_then_cool(self):
|
| 37 |
+
r=prepared(method=dict(duration_s=60.));r.invoke('acquisition.start');r.step(60.);self.assertEqual(r.phase,'succeeded');self.assertAlmostEqual(r.cooldown,600.);self.assertEqual(r.lamp_power,0.);self.reject(r,'acquisition.start');r.step(600.);r.invoke('acquisition.start')
|
| 38 |
+
def test_cancel_residue(self):
|
| 39 |
+
r=prepared();r.invoke('acquisition.start');r.step(5);p=r.parent.copy();r.invoke('acquisition.stop');r.step(3);self.assertEqual(p,r.parent);self.assertGreater(r.converted[5],0);self.assertAlmostEqual(r.cooldown,597.)
|
| 40 |
+
def test_runtime_change_method(self):
|
| 41 |
+
r=prepared();r.invoke('acquisition.start');r.step(10);r.invoke('method.configure',temperature_K=358.15,duration_s=60.);r.step(50);self.assertEqual(r.phase,'succeeded')
|
| 42 |
+
def test_interruption_pauses_fan(self):
|
| 43 |
+
r=prepared();r.invoke('acquisition.start');r.step(1);r.invoke('power.interrupt');r.step(10);self.assertAlmostEqual(r.cooldown,600);self.assertFalse(r.read()['fan.running']);r.invoke('power.set',enabled=True);r.step(10);self.assertAlmostEqual(r.cooldown,590)
|
| 44 |
+
def test_host_guard(self):
|
| 45 |
+
r=prepared();r.invoke('acquisition.start');self.reject(r,'shield.set_open',open=True);self.reject(r,'power.set',enabled=False)
|
| 46 |
+
def test_sensor_fault(self):
|
| 47 |
+
r=prepared();r.invoke('acquisition.start');r.step(1);r.invoke('sensor.set_connected',connected=False);self.assertEqual(r.phase,'failed');self.assertIsNone(r.indicated());r.step(600);self.reject(r,'fault.acknowledge');r.invoke('sensor.set_connected',connected=True);r.invoke('fault.acknowledge')
|
| 48 |
+
def test_overtemp(self):
|
| 49 |
+
r=prepared(plant=dict(absorbed_electrical_fraction=1.,fan_UA_W_K=1.,dry_heat_capacity_J_K=10.),method=dict(duration_s=600.));r.invoke('acquisition.start');r.step(600);self.assertEqual(r.phase,'failed');self.assertEqual(r.fault,'Max. temp. reached')
|
| 50 |
+
def test_thermal_energy(self):
|
| 51 |
+
r=prepared();r.invoke('acquisition.start');r.step(120);self.assertAlmostEqual(r.energy,r.storage+r.loss+r.collected_heat,places=7)
|
| 52 |
+
def test_parent_conservation(self):
|
| 53 |
+
r=prepared();r.invoke('acquisition.start');r.step(120)
|
| 54 |
+
for i in range(12):self.assertAlmostEqual(r.initial[i],r.parent[i]+r.converted[i]+r.collected[i],places=15)
|
| 55 |
+
def test_collect_finite(self):
|
| 56 |
+
r=prepared();r.invoke('acquisition.start');r.step(720);r.invoke('shield.set_open',open=True);r.step(1.1);out=r.invoke('product.collect',fraction=.25,recipient_id='vials');self.assertAlmostEqual(out['transferred_volume_m3'],30e-6)
|
| 57 |
+
for i in range(12):self.assertAlmostEqual(10e-6,r.volumes[i]+r.collected_volumes[i]);self.assertAlmostEqual(r.initial[i],r.parent[i]+r.converted[i]+r.collected[i])
|
| 58 |
+
self.assertAlmostEqual(r.energy,r.storage+r.loss+r.collected_heat,places=7)
|
| 59 |
+
def test_lamp_replace(self):
|
| 60 |
+
r=prepared();r.invoke('acquisition.start');r.step(720);r.invoke('shield.set_open',open=True);r.step(1.1);self.reject(r,'lamp.replace',replacement_confirmed=True);r.invoke('power.set',enabled=False);r.invoke('lamp.replace',replacement_confirmed=True);self.assertEqual(r.lamp_usage,0.)
|
| 61 |
+
def test_isolation(self):
|
| 62 |
+
a=prepared();b=prepared();a.invoke('acquisition.start');a.step(10);self.assertEqual(b.elapsed_s,0.);self.assertEqual(b.parent[5],1e-7)
|
| 63 |
+
def test_agent_filter(self):
|
| 64 |
+
r=prepared();s=r.session();self.assertFalse(any(k.startswith('truth.') for k in s.read(instance_id=r.instance_id)['observations']));self.assertNotIn('product.read',s.describe(instance_id=r.instance_id)['capabilities']);o=s.invoke(instance_id=r.instance_id,capability_id='product.read',arguments={},request_id='x');self.assertEqual(o['error']['code'],'ACCESS_DENIED')
|
| 65 |
+
def test_idempotency(self):
|
| 66 |
+
r=prepared();s=r.session();kw=dict(instance_id=r.instance_id,capability_id='acquisition.start',arguments={},request_id='start');a=s.invoke(**kw);r.step(2);self.assertEqual(a,s.invoke(**kw));kw['capability_id']='acquisition.stop';self.assertEqual(s.invoke(**kw)['error']['code'],'REQUEST_CONFLICT')
|
| 67 |
+
def test_poll_cancel_owner(self):
|
| 68 |
+
r=prepared();r.register_principal('second','agent');s=r.session();o=s.invoke(instance_id=r.instance_id,capability_id='acquisition.start',arguments={},request_id='start');op=o['operation_id'];r.step(1);self.assertEqual(s.poll(op)['status'],'running')
|
| 69 |
+
with self.assertRaises(ActionRejected):r.session('second').poll(op)
|
| 70 |
+
self.assertEqual(s.cancel(op,'cancel')['status'],'cancelled')
|
| 71 |
+
def test_write_routes(self):
|
| 72 |
+
r=prepared();s=r.session();o=s.write(instance_id=r.instance_id,state_id='thermal.target_k',value=368.15,request_id='t');self.assertEqual(o['status'],'succeeded');self.assertEqual(r.target,368.15)
|
| 73 |
+
def test_invalid_dt(self):
|
| 74 |
+
r=prepared()
|
| 75 |
+
for dt in [-1,float('nan'),True,3601]:
|
| 76 |
+
before=r.debug_snapshot()
|
| 77 |
+
with self.assertRaises(ActionRejected):r.step(dt)
|
| 78 |
+
self.assertEqual(before,r.debug_snapshot())
|
| 79 |
+
def test_fifty_templates(self):
|
| 80 |
+
r=prepared();self.assertEqual(len(r.templates),50)
|
| 81 |
+
def test_zero_oh(self):
|
| 82 |
+
r=prepared(plant=dict(oh_concentration_mol_m3=0));r.invoke('acquisition.start');r.step(120);self.assertEqual(r.parent[5],1e-7)
|
| 83 |
+
if __name__=='__main__':unittest.main()
|
tests/test_asset_micromeritics_autochemiii.py
ADDED
|
@@ -0,0 +1,160 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import copy, importlib.util, json, math, sys, unittest
|
| 2 |
+
from pathlib import Path
|
| 3 |
+
from unittest import mock
|
| 4 |
+
ROOT=Path(__file__).resolve().parents[1];sys.path.insert(0,str(ROOT/'scripts'))
|
| 5 |
+
from asset_runtime import micromeritics_autochemiii as rt
|
| 6 |
+
OBSERVED=[]
|
| 7 |
+
|
| 8 |
+
def call(h,k,**a):
|
| 9 |
+
result=h.invoke(k,**a);OBSERVED.append((k,copy.deepcopy(a),copy.deepcopy(result)));return result
|
| 10 |
+
|
| 11 |
+
def setup(mode='tpd',instance_id='autochemiii_01',plant=None,sample=None):
|
| 12 |
+
h=rt.MicromeriticsAutochemiiiRuntime(instance_id);call(h,'plant.configure',**dict(rt.PLANT_EXAMPLE,**(plant or {})));s=dict(rt.SAMPLE_EXAMPLE,mode=mode);s.update(sample or {})
|
| 13 |
+
if mode=='pulse':s['initial_bound_mol']=0.
|
| 14 |
+
call(h,'sample.load',**s);gas=dict(rt.GAS_EXAMPLE)
|
| 15 |
+
if mode in ('tpr','tpo'):
|
| 16 |
+
fractions=[.9]+[0.]*8;fractions[rt.SPECIES.index('h2' if mode=='tpr' else 'o2')]=.1;gas['mole_fractions']=fractions
|
| 17 |
+
call(h,'gas.load',**gas)
|
| 18 |
+
if mode=='pulse':
|
| 19 |
+
fractions=[0.]*9;fractions[rt.SPECIES.index(s['adsorbate'])]=1.;call(h,'gas.load',**dict(rt.GAS_EXAMPLE,bank='loop',mole_fractions=fractions))
|
| 20 |
+
call(h,'furnace.set_open',opened=False);call(h,'power.set',enabled=True);call(h,'method.configure',**dict(rt.METHOD_EXAMPLE,mode=mode));call(h,'gas.open',enabled=True);return h
|
| 21 |
+
|
| 22 |
+
def finish(h,seconds=100):
|
| 23 |
+
for _ in range(round(seconds/rt.DT)):
|
| 24 |
+
h.step(rt.DT)
|
| 25 |
+
if h.phase!='running':break
|
| 26 |
+
return h.invoke('acquisition.result')
|
| 27 |
+
|
| 28 |
+
class TestAutoChemIII(unittest.TestCase):
|
| 29 |
+
def assert_ledger(self,h):
|
| 30 |
+
ledger=h._ledger();self.assertLess(abs(ledger['mass_error_kg']),1e-12);self.assertLess(max(map(abs,ledger['element_error_mol'])),1e-10);self.assertLess(abs(ledger['heat_error_j']),1e-6)
|
| 31 |
+
def test_01_short_actual_tpd(self):
|
| 32 |
+
h=setup();initial=h.bound;call(h,'acquisition.start');r=finish(h);self.assertEqual(r['phase'],'succeeded');self.assertGreater(len(r['rows']),10);self.assertLess(h.bound,initial);self.assertGreater(h.tcd,0.);self.assertGreater(r['integral_v_s'],0.);self.assert_ledger(h)
|
| 33 |
+
def test_02_tpr_and_tpo_atoms(self):
|
| 34 |
+
for mode,product in [('tpr','h2o'),('tpo','co2')]:
|
| 35 |
+
h=setup(mode);initial=h.bound;h.invoke('acquisition.start');finish(h);self.assertLess(h.bound,initial);self.assertGreater(h.exhaust[rt.SPECIES.index(product)],0.);self.assert_ledger(h)
|
| 36 |
+
def test_03_pulse_finite_sites(self):
|
| 37 |
+
h=setup('pulse',sample={'preexponential_s':2.,'activation_j_mol':0.});h.invoke('acquisition.start');r=finish(h);self.assertEqual(r['phase'],'succeeded');self.assertEqual(h.pulses,3);self.assertGreater(h.bound,0.);self.assertLessEqual(h.bound,h.sample['capacity_mol']);self.assert_ledger(h)
|
| 38 |
+
def test_04_pure_reads_and_host_clock(self):
|
| 39 |
+
h=setup();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');h.invoke('ledger.read');self.assertEqual(before,h.__dict__);h.invoke('thermal.set_temperature',temperature_k=303.15,ramp_k_s=1.);self.assertEqual(h.temperature,298.15);self.assertEqual(h.time_s,0.);h.step(.1);self.assertGreater(h.temperature,298.15)
|
| 40 |
+
def test_05_partition_independence(self):
|
| 41 |
+
a=setup();b=setup();a.invoke('acquisition.start');b.invoke('acquisition.start');a.step(3.)
|
| 42 |
+
for _ in range(30):b.step(.1)
|
| 43 |
+
self.assertEqual(a.read(),b.read());self.assertEqual(a.rows,b.rows)
|
| 44 |
+
def test_06_two_instances(self):
|
| 45 |
+
a=setup(instance_id='a');b=setup(instance_id='b');before=copy.deepcopy(b.__dict__);a.invoke('acquisition.start');a.step(3);self.assertEqual(before,b.__dict__)
|
| 46 |
+
def test_07_agent_truth_boundary(self):
|
| 47 |
+
h=setup();s=h.session();d=s.describe(instance_id=h.instance_id);self.assertNotIn('truth.bound_mol',d['state_slots']);self.assertNotIn('gas.load',d['capabilities']);before=copy.deepcopy(h.__dict__)
|
| 48 |
+
for cap,args in [('ledger.read',{}),('sample.remove',{}),('gas.unload',{'bank':'carrier','inlet':1}),('sim.step',{'dt_s':1.})]:
|
| 49 |
+
r=s.invoke(instance_id=h.instance_id,capability_id=cap,arguments=args,request_id=cap);self.assertEqual(r['error']['code'],'ACCESS_DENIED');self.assertEqual(before,h.__dict__)
|
| 50 |
+
with self.assertRaisesRegex(rt.ActionRejected,'ACCESS_DENIED'):s.read(instance_id=h.instance_id,state_ids=['truth.stock_mol'])
|
| 51 |
+
def test_08_ownership_and_queries(self):
|
| 52 |
+
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'];q=b.invoke(instance_id=h.instance_id,capability_id='acquisition.result',arguments={},request_id='query');self.assertIsNone(q['operation_id'])
|
| 53 |
+
with self.assertRaisesRegex(rt.ActionRejected,'ACCESS_DENIED'):b.poll(op)
|
| 54 |
+
self.assertEqual(b.invoke(instance_id=h.instance_id,capability_id='acquisition.stop',arguments={},request_id='stop')['error']['code'],'ACCESS_DENIED');self.assertEqual(a.cancel(op,'cancel')['status'],'succeeded')
|
| 55 |
+
def test_09_retry(self):
|
| 56 |
+
h=setup();s=h.session();a=dict(instance_id=h.instance_id,capability_id='gas.set_flow',arguments={'reference_m3_s':20e-6/60},request_id='x');self.assertEqual(s.invoke(**a),s.invoke(**a));a['arguments']={'reference_m3_s':50e-6/60};self.assertEqual(s.invoke(**a)['error']['code'],'REQUEST_CONFLICT')
|
| 57 |
+
def test_10_terminal_history_and_return_copies(self):
|
| 58 |
+
h=setup();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);h.invoke('gas.open',enabled=False);h.invoke('furnace.set_open',opened=True);h.invoke('sample.remove');h.invoke('method.configure',**dict(rt.METHOD_EXAMPLE,mode='tpr'));self.assertEqual(saved,s.poll(op));self.assertEqual(saved['result'],h.invoke('acquisition.result'));saved['result']['rows'][0]['tcd_v']=123.;self.assertNotEqual(saved,s.poll(op))
|
| 59 |
+
def test_11_cancel_keeps_partial_effects(self):
|
| 60 |
+
h=setup('pulse');s=h.session();op=s.invoke(instance_id=h.instance_id,capability_id='acquisition.start',arguments={},request_id='start')['operation_id'];h.step(1.);bound=h.bound;stock=h.read()['truth.stock_mol'];s.cancel(op,'cancel');frozen=s.poll(op);h.step(1.);self.assertEqual(frozen,s.poll(op));self.assertFalse(h.gas_enabled);self.assertLessEqual(h.read()['truth.stock_mol'],stock);self.assertGreaterEqual(h.bound,bound);self.assert_ledger(h)
|
| 61 |
+
def test_12_depletion_terminal_snapshot_includes_last_tick(self):
|
| 62 |
+
h=setup();h.invoke('gas.open',enabled=False);h.invoke('gas.unload',bank='carrier',inlet=1);h.invoke('gas.load',**dict(rt.GAS_EXAMPLE,amount_mol=1e-9));h.invoke('gas.open',enabled=True);h.invoke('acquisition.start');h.step(.1);r=h.invoke('acquisition.result');self.assertEqual(r['phase'],'failed');self.assertEqual(r['error_code'],'GAS_EXHAUSTED');self.assertEqual(r['elapsed_s'],.1);self.assertEqual(r['rows'][-1]['time_s'],h.time_s);self.assertEqual(h.read()['truth.stock_mol'],0.);self.assert_ledger(h)
|
| 63 |
+
def test_13_pulse_shortage_atomic(self):
|
| 64 |
+
h=setup('pulse');h.invoke('gas.open',enabled=False);h.invoke('gas.unload',bank='loop',inlet=1);h.invoke('gas.load',**dict(rt.GAS_EXAMPLE,bank='loop',amount_mol=1e-9));h.invoke('gas.open',enabled=True);before=copy.deepcopy(h.__dict__)
|
| 65 |
+
with self.assertRaisesRegex(rt.ActionRejected,'FINITE_INVENTORY'):h.invoke('acquisition.start')
|
| 66 |
+
self.assertEqual(before,h.__dict__)
|
| 67 |
+
def test_14_ramp_three_temperature_bands(self):
|
| 68 |
+
h=setup();h.invoke('gas.open',enabled=False)
|
| 69 |
+
for target,rate in [(1073.15,100/60),(1273.15,50/60),(1473.15,25/60)]:h.invoke('thermal.set_temperature',temperature_k=target,ramp_k_s=rate)
|
| 70 |
+
for target,rate in [(1073.25,100/60),(1273.25,50/60),(1473.15,26/60)]:
|
| 71 |
+
before=copy.deepcopy(h.__dict__)
|
| 72 |
+
with self.assertRaisesRegex(rt.ActionRejected,'RAMP_LIMIT'):h.invoke('thermal.set_temperature',temperature_k=target,ramp_k_s=rate)
|
| 73 |
+
self.assertEqual(before,h.__dict__)
|
| 74 |
+
def test_15_temperature_increment_lower_bound_and_path(self):
|
| 75 |
+
h=setup();h.invoke('thermal.set_temperature',temperature_k=293.15,ramp_k_s=1/60)
|
| 76 |
+
for args,error in [(dict(temperature_k=293.05,ramp_k_s=1/60),'TEMPERATURE_RANGE'),(dict(temperature_k=300.16,ramp_k_s=1/60),'TEMPERATURE_INCREMENT'),(dict(temperature_k=300.15,ramp_k_s=.5/60),'INVALID_ARGUMENT')]:
|
| 77 |
+
before=copy.deepcopy(h.__dict__)
|
| 78 |
+
with self.assertRaisesRegex(rt.ActionRejected,error):h.invoke('thermal.set_temperature',**args)
|
| 79 |
+
self.assertEqual(before,h.__dict__)
|
| 80 |
+
call(h,'path.set_temperature',temperature_k=423.15)
|
| 81 |
+
with self.assertRaises(rt.ActionRejected):h.invoke('path.set_temperature',temperature_k=423.25)
|
| 82 |
+
def test_16_downramp_start_temperature(self):
|
| 83 |
+
h=setup(plant={'thermal_capacity_j_k':1.,'heat_loss_w_k':0.,'controller_w_k':1000.},sample={'preexponential_s':0.});h.invoke('gas.open',enabled=False);h.invoke('thermal.set_temperature',temperature_k=1473.15,ramp_k_s=25/60);h.step(3000.);self.assertGreater(h.programmed,1273.15)
|
| 84 |
+
with self.assertRaisesRegex(rt.ActionRejected,'RAMP_LIMIT'):h.invoke('thermal.set_temperature',temperature_k=298.15,ramp_k_s=100/60)
|
| 85 |
+
h.invoke('thermal.set_temperature',temperature_k=298.15,ramp_k_s=25/60)
|
| 86 |
+
def test_17_all_inlets_and_flow_limits(self):
|
| 87 |
+
h=setup();h.invoke('gas.open',enabled=False)
|
| 88 |
+
for bank in rt.BANKS:
|
| 89 |
+
for inlet in range(1,7):call(h,'gas.select',bank=bank,inlet=inlet)
|
| 90 |
+
call(h,'gas.route',bank='pretreatment')
|
| 91 |
+
for q in [0.,1e-6/60,100e-6/60]:call(h,'gas.set_flow',reference_m3_s=q)
|
| 92 |
+
for q in [.5e-6/60,101e-6/60,-1.]:
|
| 93 |
+
before=copy.deepcopy(h.__dict__)
|
| 94 |
+
with self.assertRaises(rt.ActionRejected):h.invoke('gas.set_flow',reference_m3_s=q)
|
| 95 |
+
self.assertEqual(before,h.__dict__)
|
| 96 |
+
def test_18_engineering_and_unknown_rejection(self):
|
| 97 |
+
h=rt.MicromeriticsAutochemiiiRuntime();before=copy.deepcopy(h.__dict__)
|
| 98 |
+
with self.assertRaisesRegex(rt.ActionRejected,'MODEL_NOT_ACCEPTED'):h.invoke('plant.configure',**dict(rt.PLANT_EXAMPLE,accept_engineering=False))
|
| 99 |
+
self.assertEqual(before,h.__dict__);h.invoke('plant.configure',**rt.PLANT_EXAMPLE);before=copy.deepcopy(h.__dict__)
|
| 100 |
+
for change in [{'accept_engineering_kinetics':False},{'accept_unknown_conditions':False},{'particle_diameter_m':.0091},{'initial_bound_mol':.2}]:
|
| 101 |
+
with self.assertRaises(rt.ActionRejected):h.invoke('sample.load',**dict(rt.SAMPLE_EXAMPLE,**change))
|
| 102 |
+
self.assertEqual(before,h.__dict__)
|
| 103 |
+
def test_19_invalid_numbers_and_busy_atomic(self):
|
| 104 |
+
h=setup();before=copy.deepcopy(h.__dict__)
|
| 105 |
+
for value in [True,float('nan'),float('inf')]:
|
| 106 |
+
with self.assertRaises(rt.ActionRejected):h.invoke('gas.set_flow',reference_m3_s=value)
|
| 107 |
+
self.assertEqual(before,h.__dict__)
|
| 108 |
+
h.invoke('acquisition.start');before=copy.deepcopy(h.__dict__)
|
| 109 |
+
with self.assertRaisesRegex(rt.ActionRejected,'BUSY'):h.invoke('method.configure',**rt.METHOD_EXAMPLE)
|
| 110 |
+
self.assertEqual(before,h.__dict__)
|
| 111 |
+
def test_20_independent_integral_calibration_dispersion(self):
|
| 112 |
+
h=setup();c=call(h,'detector.calibrate',known_moles_mol=[1e-6,2e-6],observed_areas_v_s=[.1,.2]);self.assertAlmostEqual(c['mol_per_v_s'],1e-5);r=call(h,'analysis.integrate',times_s=[0.,1.,2.],signals_v=[0.,.1,0.],baseline_v=0.,mol_per_v_s=c['mol_per_v_s']);self.assertAlmostEqual(r['amount_mol'],1e-6);d=call(h,'analysis.dispersion',**rt.CAPS['analysis.dispersion']['example_arguments']);self.assertAlmostEqual(d['fraction'],.00586934)
|
| 113 |
+
def test_21_stiff_thermal_inputs_remain_stable(self):
|
| 114 |
+
h=setup(plant={'thermal_capacity_j_k':1.,'controller_w_k':1000.,'heater_limit_w':10000.,'cooler_limit_w':10000.,'heat_loss_w_k':100.},sample={'preexponential_s':0.});h.invoke('thermal.set_temperature',temperature_k=373.15,ramp_k_s=100/60);h.step(60.);self.assertTrue(298.15<=h.temperature<=373.15);h.invoke('thermal.set_temperature',temperature_k=293.15,ramp_k_s=100/60);h.step(100.);self.assertTrue(293.15<=h.temperature<=298.15);self.assert_ledger(h)
|
| 115 |
+
def test_22_timeout_and_independent_queries(self):
|
| 116 |
+
h=setup();h.invoke('method.configure',**dict(rt.METHOD_EXAMPLE,maximum_duration_s=.2));h.invoke('acquisition.start');h.step(1.);r=h.invoke('acquisition.result');self.assertEqual(r['error_code'],'TIMEOUT');before=copy.deepcopy(h.__dict__);h.invoke('reference.query',reference_id='parlett2023_nio_sio2');self.assertEqual(before,h.__dict__)
|
| 117 |
+
def test_23_mechanical_access_and_actual_commands(self):
|
| 118 |
+
h=setup();h.invoke('gas.open',enabled=False);call(h,'furnace.open',opened=True);call(h,'front_cover.set',distance_m=.16)
|
| 119 |
+
before=copy.deepcopy(h.__dict__)
|
| 120 |
+
with self.assertRaisesRegex(rt.ActionRejected,'SAMPLE_CONNECTION'):h.invoke('sample.set_position',distance_m=.12)
|
| 121 |
+
self.assertEqual(before,h.__dict__);call(h,'sample.release',angle_rad=.6);call(h,'sample.set_position',distance_m=.12)
|
| 122 |
+
with self.assertRaisesRegex(rt.ActionRejected,'SAMPLE_CONNECTION'):h.invoke('furnace.set_open',opened=False)
|
| 123 |
+
call(h,'sample.set_position',distance_m=0.);call(h,'sample.release',angle_rad=0.);call(h,'sample.remove');call(h,'gas.unload',bank='carrier',inlet=1);call(h,'power.set',enabled=False);call(h,'service.set',distance_m=.1);self.assert_ledger(h)
|
| 124 |
+
def test_24_reference_curves_and_summary_are_not_tcd(self):
|
| 125 |
+
h=setup();a=call(h,'reference.query',reference_id='parlett2023_nio_sio2');b=call(h,'reference.query',reference_id='rodbuk2025_cu_ti_itq2_tpd');c=call(h,'reference.query',reference_id='garidzirai2021_pt_alumina');self.assertEqual(json.loads(b['reference_json'])['values']['signal_unit'],'Pa');self.assertEqual(json.loads(c['reference_json'])['values']['metal_dispersion_fraction'],.38);self.assertIn('source',json.loads(a['reference_json']))
|
| 126 |
+
def test_25_terminal_source_is_snapshot(self):
|
| 127 |
+
h=setup(sample={'reference_id':'parlett2023_nio_sio2'});h.invoke('acquisition.start');r=finish(h);h.invoke('gas.open',enabled=False);h.invoke('furnace.set_open',opened=True);h.invoke('sample.remove');h.invoke('sample.load',**dict(rt.SAMPLE_EXAMPLE,reference_id='garidzirai2021_pt_alumina'));self.assertEqual(r,h.invoke('acquisition.result'))
|
| 128 |
+
def test_26_invalid_composition(self):
|
| 129 |
+
h=setup();h.invoke('gas.open',enabled=False);before=copy.deepcopy(h.__dict__)
|
| 130 |
+
with self.assertRaisesRegex(rt.ActionRejected,'INVALID_COMPOSITION'):h.invoke('gas.load',**dict(rt.GAS_EXAMPLE,inlet=2,mole_fractions=[.5]*9))
|
| 131 |
+
self.assertEqual(before,h.__dict__)
|
| 132 |
+
def test_27_unsupported_and_identity(self):
|
| 133 |
+
h=setup();self.assertEqual(rt.CATALOG_ID,'CHEM-122')
|
| 134 |
+
for k in rt.UNSUPPORTED:
|
| 135 |
+
with self.assertRaisesRegex(rt.ActionRejected,'UNSUPPORTED'):h.invoke(k)
|
| 136 |
+
with self.assertRaises(rt.ActionRejected):h.session('unregistered')
|
| 137 |
+
with self.assertRaises(rt.ActionRejected):h.register_principal('agent','evaluator')
|
| 138 |
+
def test_28_state_effects_cover_real_changes(self):
|
| 139 |
+
meta=rt.export_micromeritics_autochemiii_contract_metadata();original=rt.MicromeriticsAutochemiiiRuntime.invoke
|
| 140 |
+
def audited(h,k,**a):
|
| 141 |
+
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
|
| 142 |
+
with mock.patch.object(rt.MicromeriticsAutochemiiiRuntime,'invoke',audited):
|
| 143 |
+
h=setup();call(h,'path.set_temperature',temperature_k=323.15);call(h,'acquisition.start');call(h,'sim.step',dt_s=2.);call(h,'acquisition.stop');call(h,'furnace.set_open',opened=True);call(h,'sample.remove');call(h,'power.set',enabled=False);call(h,'service.set',distance_m=.1)
|
| 144 |
+
def test_28b_invalid_time_and_hot_access_are_atomic(self):
|
| 145 |
+
h=setup();before=copy.deepcopy(h.__dict__)
|
| 146 |
+
for dt in [-.1,True,float('nan'),float('inf')]:
|
| 147 |
+
with self.assertRaises(rt.ActionRejected):h.step(dt)
|
| 148 |
+
self.assertEqual(before,h.__dict__)
|
| 149 |
+
h.step(0.);self.assertEqual(before,h.__dict__);h.invoke('gas.open',enabled=False);h.invoke('thermal.set_temperature',temperature_k=343.15,ramp_k_s=100/60);h.step(40.);self.assertGreater(h.temperature,323.15);before=copy.deepcopy(h.__dict__)
|
| 150 |
+
with self.assertRaisesRegex(rt.ActionRejected,'HOT_OR_FLOWING'):h.invoke('furnace.set_open',opened=True)
|
| 151 |
+
self.assertEqual(before,h.__dict__)
|
| 152 |
+
def test_29_all_actual_api_and_state_schema(self):
|
| 153 |
+
spec=importlib.util.spec_from_file_location('autochem_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_micromeritics_autochemiii_contract_metadata()
|
| 154 |
+
h=setup();call(h,'acquisition.start');call(h,'sim.step',dt_s=20.);call(h,'acquisition.result');call(h,'ledger.read');call(h,'thermal.set_temperature',temperature_k=313.15,ramp_k_s=1.)
|
| 155 |
+
for k,c in rt.CAPS.items():
|
| 156 |
+
if k in rt.UNSUPPORTED:continue
|
| 157 |
+
cases=[x for x in OBSERVED if x[0]==k];self.assertTrue(cases,k)
|
| 158 |
+
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)
|
| 159 |
+
for key,value in h.read().items():self.assertEqual(tool.validate_value(value,meta['state_slots'][key]['value_schema']),[],key)
|
| 160 |
+
if __name__=='__main__':unittest.main()
|
tests/test_asset_milestone_dma80.py
ADDED
|
@@ -0,0 +1,223 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Independent process, observation, protocol and source-boundary regressions for CHEM-086."""
|
| 2 |
+
import copy,csv,io,json,math,re,sys,unittest,importlib.util
|
| 3 |
+
from pathlib import Path
|
| 4 |
+
import numpy as np
|
| 5 |
+
ROOT=Path(__file__).resolve().parents[1];sys.path.insert(0,str(ROOT/'scripts'))
|
| 6 |
+
from asset_runtime import milestone_dma80 as rt
|
| 7 |
+
|
| 8 |
+
def new(plant=None,method=None,library=None):
|
| 9 |
+
r=rt.MilestoneDma80Runtime('dma80',library=library);r.invoke('plant.configure',**(rt.PLANT_EXAMPLE|(plant or {})))
|
| 10 |
+
r.invoke('method.configure',**(rt.METHOD_EXAMPLE|(method or {})));r.invoke('dust_cover.set',opened=True);return r
|
| 11 |
+
|
| 12 |
+
def warm(r):
|
| 13 |
+
r.invoke('dust_cover.set',opened=False);r.invoke('power.set',enabled=True);r.invoke('gas.set',enabled=True);r.step(.3)
|
| 14 |
+
|
| 15 |
+
def run(r,indices):
|
| 16 |
+
r.invoke('sequence.start',slot_indices=indices)
|
| 17 |
+
for _ in range(20000):
|
| 18 |
+
r.step(.02)
|
| 19 |
+
if r.phase!='running':return r.invoke('sequence.read')['completed_records']
|
| 20 |
+
raise AssertionError('finite sequence failed to terminate')
|
| 21 |
+
|
| 22 |
+
def until(r,stage):
|
| 23 |
+
for _ in range(10000):
|
| 24 |
+
if r.stage==stage:return
|
| 25 |
+
r.step(.01)
|
| 26 |
+
raise AssertionError('stage not reached: '+stage)
|
| 27 |
+
|
| 28 |
+
def load(r,i,a):r.invoke('sample.load',**(a|dict(slot_index=i)))
|
| 29 |
+
def blank_ready(plant=None,method=None):
|
| 30 |
+
r=new(plant,method);load(r,0,rt.BLANK_EXAMPLE);load(r,1,rt.SAMPLE_EXAMPLE);warm(r);run(r,[0]);return r
|
| 31 |
+
|
| 32 |
+
def calibrated():
|
| 33 |
+
r=new();load(r,0,rt.BLANK_EXAMPLE)
|
| 34 |
+
for i,m in enumerate([.0001,.0005,.001],1):load(r,i,rt.STANDARD_EXAMPLE|dict(mass_kg=m,volume_m3=m*.001))
|
| 35 |
+
for i,m in [(4,.0001),(5,.00008),(6,.00015)]:load(r,i,rt.SAMPLE_EXAMPLE|dict(mass_kg=m))
|
| 36 |
+
warm(r);run(r,[0,1,2,3]);r.invoke('calibration.fit',curve_id='observed',record_ids=['record_2','record_3','record_4']);r.invoke('calibration.select',curve_id='observed');return r
|
| 37 |
+
|
| 38 |
+
class Dma80Tests(unittest.TestCase):
|
| 39 |
+
@classmethod
|
| 40 |
+
def setUpClass(cls):cls.cal=calibrated()
|
| 41 |
+
def reject(self,r,k,args,code=None):
|
| 42 |
+
before=copy.deepcopy(r.__dict__);rng=copy.deepcopy(r.rng.bit_generator.state)
|
| 43 |
+
with self.assertRaises(rt.ActionRejected) as e:r.invoke(k,**args)
|
| 44 |
+
if code:self.assertEqual(str(e.exception),code)
|
| 45 |
+
after=copy.deepcopy(r.__dict__);before.pop('rng');after.pop('rng');self.assertEqual(before,after);self.assertEqual(rng,r.rng.bit_generator.state)
|
| 46 |
+
def ledger(self,r):
|
| 47 |
+
x=r.invoke('product.read');self.assertLess(abs(x['mass_residual_kg']),1e-14);self.assertLess(abs(x['energy_residual_j']),1e-7)
|
| 48 |
+
for key,res,tol in [('mercury_ledger_json','residual_kg',1e-20),('gas_ledger_json','residual_mol',1e-10),('volume_ledger_json','residual_m3',1e-15)]:self.assertLess(abs(json.loads(x[key])[res]),tol)
|
| 49 |
+
def test_identity_and_source_units(self):
|
| 50 |
+
self.assertEqual(rt.CATALOG_ID,'CHEM-086');self.assertEqual(rt.WAVELENGTH_M,253.65e-9);self.assertEqual(rt.METHOD_EXAMPLE['range_min_kg'],1e-14)
|
| 51 |
+
def test_step_rejects_zero_negative_nan_bool(self):
|
| 52 |
+
for v in [0,-1,math.nan,math.inf,True]:
|
| 53 |
+
r=new();before=r.time_s
|
| 54 |
+
with self.assertRaises(rt.ActionRejected):r.step(v)
|
| 55 |
+
self.assertEqual(r.time_s,before)
|
| 56 |
+
def test_initialization_only(self):
|
| 57 |
+
r=new();self.reject(r,'plant.configure',rt.PLANT_EXAMPLE,'INITIALIZATION_ONLY')
|
| 58 |
+
def test_reads_and_describe_pure(self):
|
| 59 |
+
r=copy.deepcopy(self.cal);t=r.time_s;v=r.revision;state=copy.deepcopy(r.rng.bit_generator.state)
|
| 60 |
+
for _ in range(4):r.read();r.describe();r.invoke('result.read');r.invoke('signal.read');r.invoke('sample.inventory')
|
| 61 |
+
self.assertEqual((r.time_s,r.revision,r.rng.bit_generator.state),(t,v,state))
|
| 62 |
+
def test_loading_uses_independent_dust_cover(self):
|
| 63 |
+
r=new();self.assertEqual(r.cover,0);load(r,0,rt.SAMPLE_EXAMPLE);self.assertEqual(len(r.samples),1)
|
| 64 |
+
def test_main_cover_open_requires_dust_closed(self):
|
| 65 |
+
self.reject(new(),'cover.set',{'opened':True},'DUST_COVER_OPEN')
|
| 66 |
+
def test_main_cover_is_cold_maintenance(self):
|
| 67 |
+
r=new();warm(r);self.reject(r,'cover.set',{'opened':True},'COLD_MAINTENANCE_REQUIRED')
|
| 68 |
+
def test_main_cover_does_not_expose_loading(self):
|
| 69 |
+
r=new();r.invoke('dust_cover.set',opened=False);r.invoke('cover.set',opened=True);self.reject(r,'sample.load',rt.SAMPLE_EXAMPLE,'SAMPLE_ACCESS')
|
| 70 |
+
def test_dust_cover_blocks_indexing_and_measurement(self):
|
| 71 |
+
r=new();load(r,0,rt.BLANK_EXAMPLE);warm(r);r.invoke('dust_cover.set',opened=True)
|
| 72 |
+
self.reject(r,'carousel.select',{'slot_index':5},'CAROUSEL_INTERLOCK');self.reject(r,'measurement.start',{'slot_index':0},'NOT_READY')
|
| 73 |
+
def test_carousel_moving_blocks_access(self):
|
| 74 |
+
r=new();warm(r);r.invoke('carousel.select',slot_index=39);r.step(.01);self.reject(r,'dust_cover.set',{'opened':True},'CAROUSEL_MOVING')
|
| 75 |
+
def test_power_guard_before_mutation(self):
|
| 76 |
+
r=new();r.invoke('dust_cover.set',opened=False);r.invoke('cover.set',opened=True);self.reject(r,'power.set',{'enabled':True},'COVER_OPEN')
|
| 77 |
+
def test_liquid_requires_quartz_and_positive_volume(self):
|
| 78 |
+
for a in [dict(boat_material='metal'),dict(volume_m3=0.)]:self.reject(new(),'sample.load',rt.STANDARD_EXAMPLE|a,'LIQUID_QUARTZ_BOAT_REQUIRED')
|
| 79 |
+
def test_nonliquid_has_no_fictitious_volume(self):self.reject(new(),'sample.load',rt.SAMPLE_EXAMPLE|dict(volume_m3=1e-7),'VOLUME_IS_LIQUID_ONLY')
|
| 80 |
+
def test_mass_and_liquid_volume_limits(self):
|
| 81 |
+
for a in [rt.SAMPLE_EXAMPLE|dict(mass_kg=.0015001),rt.STANDARD_EXAMPLE|dict(volume_m3=1.5001e-6)]:self.reject(new(),'sample.load',a,'INVALID_ARGUMENT')
|
| 82 |
+
def test_unknown_density_is_not_inferred(self):
|
| 83 |
+
r=new();a=rt.STANDARD_EXAMPLE|dict(volume_m3=1.4e-6);load(r,0,a);self.assertAlmostEqual(r.hg_registered,1.013e-11,23);self.assertEqual(r.vol_registered,1.4e-6)
|
| 84 |
+
def test_dry_mass_requires_declared_fraction(self):
|
| 85 |
+
lib={'compounds':{'dry':dict(physical_input_eligible=True,input_form='solid',calibration_eligible=False,mercury_mass_fraction_kg_kg=1e-6,conditions={'mass_basis':'dry_mass'})}}
|
| 86 |
+
r=new(library=lib);a=rt.SAMPLE_EXAMPLE|dict(template_id='dry');self.reject(r,'sample.load',a,'DRY_MASS_FRACTION_REQUIRED');load(r,0,a|dict(dry_mass_fraction=.6));self.assertAlmostEqual(r.hg_registered,6e-11,22)
|
| 87 |
+
def test_source_conditions_explicit_ack(self):self.reject(new(),'sample.load',rt.SAMPLE_EXAMPLE|dict(accept_source_condition_mismatch=False),'SOURCE_CONDITION_ACK_REQUIRED')
|
| 88 |
+
def test_source_form_not_interchangeable(self):self.reject(new(),'sample.load',rt.SAMPLE_EXAMPLE|dict(input_form='liquid',boat_material='quartz',volume_m3=1e-7),'SOURCE_FORM_MISMATCH')
|
| 89 |
+
def test_query_only_preserves_raw_record(self):
|
| 90 |
+
record={'physical_input_eligible':False,'input_form':'solid','mercury_mass_kg':1e-11,'conditions':{'basis':'unknown'}};r=new(library={'compounds':{'q':record}})
|
| 91 |
+
self.assertEqual(json.loads(r.invoke('template.read',substance_id='q')['template_json']),record);self.reject(r,'sample.load',rt.SAMPLE_EXAMPLE|dict(template_id='q'),'REFERENCE_QUERY_ONLY')
|
| 92 |
+
def test_trap_requires_declared_option(self):
|
| 93 |
+
a=rt.SAMPLE_EXAMPLE|dict(template_id='',input_form='collected_gas_sorbent',boat_material='collected_trap',host_mercury_mass_kg=1e-11);self.reject(new(),'sample.load',a,'COLLECTED_TRAP_OPTION_REQUIRED');r=new({'optional_collected_trap_installed':True});load(r,0,a);self.assertEqual(r.hg_registered,1e-11)
|
| 94 |
+
def test_blank_cannot_smuggle_mercury(self):self.reject(new(),'sample.load',rt.BLANK_EXAMPLE|dict(host_mercury_mass_kg=1e-12),'BLANK_CONTENT')
|
| 95 |
+
def test_element_mass_cannot_exceed_gross_mass(self):self.reject(new(),'sample.load',rt.SAMPLE_EXAMPLE|dict(template_id='',host_mercury_mass_kg=.001),'MERCURY_MASS_EXCEEDS_SAMPLE')
|
| 96 |
+
def test_host_truth_not_a_source_standard(self):self.reject(new(),'sample.load',rt.STANDARD_EXAMPLE|dict(template_id='',host_mercury_mass_kg=1e-11),'SOURCE_STANDARD_REQUIRED')
|
| 97 |
+
def test_all_40_independent_slots(self):
|
| 98 |
+
r=new()
|
| 99 |
+
for i in range(40):load(r,i,rt.BLANK_EXAMPLE)
|
| 100 |
+
self.assertEqual(len(r.invoke('sample.inventory')['slots']),40);self.assertTrue(all(x['occupied'] for x in r.invoke('sample.inventory')['slots']));self.reject(r,'sample.load',rt.BLANK_EXAMPLE,'SLOT_OCCUPIED')
|
| 101 |
+
def test_sequence_prevalidates_all_slots(self):
|
| 102 |
+
r=blank_ready();self.reject(r,'sequence.start',{'slot_indices':[1,12]},'SAMPLE_MISSING_OR_PROCESSED');self.reject(r,'sequence.start',{'slot_indices':[1,1]},'DUPLICATE_SLOT')
|
| 103 |
+
def test_blank_required_before_any_nonblank(self):
|
| 104 |
+
r=new();load(r,0,rt.SAMPLE_EXAMPLE);warm(r);self.reject(r,'measurement.start',{'slot_index':0},'MATCHED_BLANK_REQUIRED')
|
| 105 |
+
def test_full_40_slot_sequence(self):
|
| 106 |
+
r=new()
|
| 107 |
+
for i in range(40):load(r,i,rt.BLANK_EXAMPLE if i==0 else rt.SAMPLE_EXAMPLE|dict(template_id='',host_mercury_mass_kg=(i+1)*1e-12,mass_kg=1e-5))
|
| 108 |
+
warm(r);results=run(r,list(range(40)));self.assertEqual([x['slot_index'] for x in results],list(range(40)));self.assertTrue(all(x['complete'] for x in results));self.assertAlmostEqual(r.carousel,39*math.pi/20);self.ledger(r)
|
| 109 |
+
def test_carousel_target_finite_and_fourty_mapping(self):
|
| 110 |
+
r=new();warm(r);r.invoke('carousel.select',slot_index=39);self.assertEqual(r.carousel,0);r.step(.01);self.assertGreater(r.carousel,0);self.assertLess(r.carousel,39*math.pi/20);r.step(1);self.assertAlmostEqual(r.carousel,39*math.pi/20)
|
| 111 |
+
def test_lift_precedes_insertion_and_returns(self):
|
| 112 |
+
r=blank_ready();r.invoke('measurement.start',slot_index=1);until(r,'lifting');r.step(.01);self.assertGreater(r.lift,0);self.assertLess(r.lift,.05);self.assertEqual(r.injection,0);until(r,'inserting');r.step(.01);self.assertEqual(r.lift,.05);self.assertGreater(r.injection,0);self.assertLess(r.injection,.23);until(r,'lowering');self.assertAlmostEqual(r.injection,0);r.step(.1);self.assertTrue(r._home())
|
| 113 |
+
def test_mechanical_positions_bound_entire_assay(self):
|
| 114 |
+
r=blank_ready();r.invoke('measurement.start',slot_index=1)
|
| 115 |
+
while r.phase=='running':
|
| 116 |
+
v=r.step(.02)
|
| 117 |
+
for k in ['carousel.angle_rad','transfer.lift_m','injection.position_m']:rt.validate(rt.SLOTS[k][0],v[k])
|
| 118 |
+
def test_temperature_changes_only_on_step(self):
|
| 119 |
+
r=new();r.invoke('dust_cover.set',opened=False);r.invoke('power.set',enabled=True);self.assertEqual(r.temps['catalyst'],298.15);r.step(.01);self.assertGreater(r.temps['catalyst'],298.15);self.assertLess(r.temps['catalyst'],838.15)
|
| 120 |
+
def test_window_duration_no_phantom_sample(self):
|
| 121 |
+
windows=self.cal._records['record_2']['windows'];self.assertEqual(len(windows),16);self.assertAlmostEqual(sum(w['end_s']-w['start_s'] for w in windows),.8,11);self.assertTrue(all(abs(w['end_s']-w['start_s']-.05)<1e-10 for w in windows))
|
| 122 |
+
def test_double_beam_log_relation(self):
|
| 123 |
+
p=self.cal.plant
|
| 124 |
+
for w in self.cal._records['record_2']['windows']:
|
| 125 |
+
ratio=(w['sample_relative']-p['sample_dark_relative'])/(w['reference_relative']-p['reference_dark_relative'])/p['sample_beam_ratio'];self.assertAlmostEqual(w['transmission_ratio'],ratio,13);self.assertAlmostEqual(w['absorbance'],-math.log10(ratio),13)
|
| 126 |
+
def test_integral_recomputed_from_actual_windows(self):
|
| 127 |
+
for r in self.cal._records.values():self.assertAlmostEqual(r['integrated_absorbance_s'],sum(w['absorbance']*(w['end_s']-w['start_s']) for w in r['windows']),13)
|
| 128 |
+
def test_blank_corrects_observed_baseline(self):
|
| 129 |
+
self.assertAlmostEqual(self.cal._records['record_1']['integrated_absorbance_s'],.8*rt.PLANT_EXAMPLE['baseline_absorbance'],12)
|
| 130 |
+
def test_fit_independent_lstsq(self):
|
| 131 |
+
c=self.cal._curves['observed'];x=np.array([r['reference_mass_kg'] for r in c['observations']]);y=np.array([r['integrated_absorbance_s'] for r in c['observations']]);scale=x.max();co=np.linalg.lstsq(np.c_[x/scale,np.ones(3)],y,rcond=None)[0];self.assertAlmostEqual(c['slope_s_kg'],co[0]/scale,5);self.assertAlmostEqual(c['intercept_s'],co[1],15)
|
| 132 |
+
def test_real_source_sample_is_observationally_recovered(self):
|
| 133 |
+
r=copy.deepcopy(self.cal);out=run(r,[4])[0];expected=7.23e-11;self.assertLess(abs(out['mercury_mass_kg']/expected-1),.001);self.assertEqual(out['mercury_concentration_kg_m3'],None);self.assertAlmostEqual(out['mercury_mass_fraction_kg_kg'],out['mercury_mass_kg']/.0001);self.ledger(r)
|
| 134 |
+
def test_no_calibration_keeps_signal_and_null(self):
|
| 135 |
+
r=blank_ready();out=run(r,[1])[0];self.assertIsNone(out['mercury_mass_kg']);self.assertGreater(out['blank_corrected_integral_s'],0)
|
| 136 |
+
def test_exact_upper_outside_calibration_is_null(self):
|
| 137 |
+
r=copy.deepcopy(self.cal);out=run(r,[6])[0];self.assertIsNone(out['mercury_mass_kg']);self.assertTrue(any('interpolation' in q for q in out['quality']))
|
| 138 |
+
def test_fit_cannot_accept_fabricated_observations(self):self.reject(copy.deepcopy(self.cal),'calibration.fit',{'curve_id':'x','record_ids':['record_1','record_2','record_3']},'ACTUAL_STANDARD_REQUIRED')
|
| 139 |
+
def test_duplicate_standard_rejected(self):self.reject(copy.deepcopy(self.cal),'calibration.fit',{'curve_id':'x','record_ids':['record_2']*3},'DUPLICATE_STANDARD')
|
| 140 |
+
def test_method_change_invalidates_both_blank_and_curve(self):
|
| 141 |
+
r=copy.deepcopy(self.cal);old=r.invoke('result.read');r.invoke('method.configure',**(r.method|dict(window_s=.04)));self.assertFalse(r.read()['blank.valid']);self.assertFalse(r.read()['calibration.ready']);self.assertEqual(r.invoke('result.read'),old);self.reject(r,'calibration.select',{'curve_id':'observed'},'CALIBRATION_SIGNATURE_MISMATCH')
|
| 142 |
+
def test_historical_record_preserves_method(self):
|
| 143 |
+
r=copy.deepcopy(self.cal);old=r.invoke('records.read',record_id='record_2');r.invoke('method.configure',**(r.method|dict(record_s=1.)));self.assertEqual(r.invoke('records.read',record_id='record_2'),old)
|
| 144 |
+
def test_response_signature_excludes_inventory_and_seed_only(self):
|
| 145 |
+
a=new();b=new({'seed':7,'oxygen_supply_mol':2.});c=new({'sample_beam_ratio':.8});self.assertEqual(a._key(),b._key());self.assertNotEqual(a._key(),c._key())
|
| 146 |
+
def test_cancel_partial_window_preserves_consumption(self):
|
| 147 |
+
r=blank_ready();r.invoke('measurement.start',slot_index=1);until(r,'recording');r.step(.073);r.invoke('measurement.stop');out=r.invoke('result.read');self.assertEqual(out['status'],'cancelled');self.assertFalse(out['complete']);self.assertIsNone(out['mercury_mass_kg']);self.assertAlmostEqual(sum(w['end_s']-w['start_s'] for w in out['windows']),.073,10);self.assertGreater(r.products,0);self.assertGreater(r.hg_gold+r.hg_cell+r.hg_exhaust,0);self.ledger(r)
|
| 148 |
+
def test_cancelled_cell_keeps_flushing_with_actual_carrier(self):
|
| 149 |
+
r=blank_ready();r.invoke('measurement.start',slot_index=1);until(r,'recording');r.step(.02);r.invoke('measurement.stop');cell=r.hg_cell;exhaust=r.hg_exhaust;history=r.invoke('result.read');self.assertGreater(cell,0);r.step(.04);self.assertLess(r.hg_cell,cell);self.assertGreater(r.hg_exhaust,exhaust);self.assertEqual(r.invoke('result.read'),history);self.ledger(r)
|
| 150 |
+
def test_exhausted_supply_cannot_flush_cancelled_cell(self):
|
| 151 |
+
r=blank_ready();r.invoke('measurement.start',slot_index=1);until(r,'recording');r.step(.02);r.invoke('measurement.stop');r.oxygen_exhaust+=r.oxygen_remaining;r.oxygen_remaining=0.;cell=r.hg_cell;r.step(.04);self.assertEqual(r.hg_cell,cell);self.assertFalse(r.read()['instrument.ready']);self.ledger(r)
|
| 152 |
+
def test_no_carrier_retains_cancelled_cell_inventory(self):
|
| 153 |
+
r=blank_ready();r.invoke('measurement.start',slot_index=1);until(r,'recording');r.step(.02);r.invoke('gas.set',enabled=False);cell=r.hg_cell;r.step(.04);self.assertEqual(r.hg_cell,cell);self.ledger(r)
|
| 154 |
+
def test_stop_does_not_restore_sample(self):
|
| 155 |
+
r=blank_ready();r.invoke('measurement.start',slot_index=1);until(r,'decomposing');r.step(.2);before=r.samples[1]['remaining'];r.invoke('measurement.stop');self.assertEqual(r.samples[1]['remaining'],before);self.assertGreater(before,0);self.assertLess(before,.0001);self.ledger(r)
|
| 156 |
+
def test_cancelled_transfer_returns_only_with_power(self):
|
| 157 |
+
r=blank_ready();r.invoke('measurement.start',slot_index=1);until(r,'inserting');r.step(.1);r.invoke('power.set',enabled=False);q=r.injection;r.step(.1);self.assertEqual(r.injection,q);r.invoke('power.set',enabled=True);r.step(.4);self.assertTrue(r._home())
|
| 158 |
+
def test_gas_loss_cancels_no_reset(self):
|
| 159 |
+
r=blank_ready();r.invoke('measurement.start',slot_index=1);until(r,'decomposing');r.step(.1);r.invoke('gas.set',enabled=False);self.assertEqual(r.phase,'cancelled');self.assertGreater(r.products,0);self.ledger(r)
|
| 160 |
+
def test_oxygen_inventory_depletion_fails_conservatively(self):
|
| 161 |
+
r=new({'oxygen_supply_mol':4e-5});load(r,0,rt.BLANK_EXAMPLE);warm(r);run(r,[0]);self.assertEqual(r.phase,'failed');self.ledger(r)
|
| 162 |
+
def test_oxygen_demand_cannot_borrow_previously_exhausted_carrier(self):
|
| 163 |
+
r=new({'oxygen_demand_mol_kg':100.});load(r,0,rt.BLANK_EXAMPLE|dict(mass_kg=1e-9));load(r,1,rt.SAMPLE_EXAMPLE);warm(r);run(r,[0]);r.invoke('measurement.start',slot_index=1);until(r,'decomposing');r.step(.02);self.assertEqual(r.phase,'failed');self.ledger(r)
|
| 164 |
+
def test_zero_reference_beam_protects_log(self):
|
| 165 |
+
r=copy.deepcopy(self.cal);r._pending_dt=.02;r._pending_r=0;r._pending_s=.01;r._pending_end=r.time_s;r._window();self.assertIsNone(r._last_point['absorbance']);self.assertTrue(r._last_point['saturated'])
|
| 166 |
+
def test_common_lamp_drift_cancels_blank(self):
|
| 167 |
+
r=blank_ready({'common_drift_fraction':.7});self.assertAlmostEqual(r.area,.8*r.plant['baseline_absorbance'],12)
|
| 168 |
+
def test_positive_noise_seed_and_query_independence(self):
|
| 169 |
+
r=blank_ready({'beam_noise_density_sqrt_s':1e-5});a=copy.deepcopy(r);b=copy.deepcopy(r);a.invoke('measurement.start',slot_index=1);b.invoke('measurement.start',slot_index=1)
|
| 170 |
+
while a.phase=='running':a.step(.02);b.read();b.invoke('signal.read');b.step(.02)
|
| 171 |
+
self.assertEqual(a.windows,b.windows)
|
| 172 |
+
def test_time_partition_matches_point_one_vs_point_zero_two(self):
|
| 173 |
+
a=blank_ready();b=copy.deepcopy(a);a.invoke('measurement.start',slot_index=1);b.invoke('measurement.start',slot_index=1)
|
| 174 |
+
for _ in range(40):
|
| 175 |
+
a.step(.1)
|
| 176 |
+
for _ in range(5):b.step(.02)
|
| 177 |
+
self.assertEqual(a.phase,b.phase);self.assertAlmostEqual(a.area,b.area,12);self.assertAlmostEqual(a.hg_exhaust,b.hg_exhaust,22)
|
| 178 |
+
def test_noninteger_release_boundary_preserved(self):
|
| 179 |
+
r=blank_ready(method={'release_s':.505});r.invoke('measurement.start',slot_index=1);until(r,'recording');g=r.hg_gold;r.step(.505);self.assertAlmostEqual(r.hg_gold/g,math.exp(-.505/r.plant['release_tau_s']),7)
|
| 180 |
+
def test_all_ledger_categories_after_unload_and_cleanup(self):
|
| 181 |
+
r=copy.deepcopy(self.cal);run(r,[4]);r.invoke('power.set',enabled=False);r.invoke('gas.set',enabled=False);r.step(.5);r.invoke('dust_cover.set',opened=True);result=r.invoke('sample.unload',slot_index=4,recipient_id='waste');self.assertLess(abs(result['unburned_mass_kg']),1e-12);self.assertGreater(result['residue_mass_kg'],0);r.invoke('product.drain',recipient_id='trap_waste');self.ledger(r)
|
| 182 |
+
def test_csv_json_actual_array_roundtrip(self):
|
| 183 |
+
r=copy.deepcopy(self.cal);run(r,[4]);self.assertEqual(json.loads(r.invoke('result.export',format='json')['content']),r.invoke('result.read'));rows=list(csv.DictReader(io.StringIO(r.invoke('result.export',format='csv')['content'])));self.assertEqual(len(rows),len(r.windows));self.assertAlmostEqual(float(rows[3]['absorbance']),r.windows[3]['absorbance'])
|
| 184 |
+
def test_every_unsupported_cap_explicitly_rejects(self):
|
| 185 |
+
r=new()
|
| 186 |
+
for cap in rt.UNSUPPORTED:self.reject(r,cap,{},'UNSUPPORTED')
|
| 187 |
+
def test_acl_hides_sample_truth_and_host_loading(self):
|
| 188 |
+
r=new();s=r.session();out=s.invoke(instance_id='dma80',capability_id='sample.load',arguments=rt.SAMPLE_EXAMPLE,request_id='x');self.assertEqual(out['error']['code'],'ACCESS_DENIED');self.assertNotIn('truth.ledger',s.read(instance_id='dma80')['observations']);self.assertNotIn('sample.load',s.describe(instance_id='dma80')['capabilities'])
|
| 189 |
+
def test_unknown_instance_atomic(self):
|
| 190 |
+
r=new();s=r.session();out=s.invoke(instance_id='other',capability_id='power.set',arguments={'enabled':True},request_id='x');self.assertEqual(out['error']['code'],'UNKNOWN_INSTANCE');self.assertFalse(r.powered)
|
| 191 |
+
def test_request_dedup_and_conflict(self):
|
| 192 |
+
r=new();s=r.session();args=dict(instance_id='dma80',capability_id='gas.set',arguments={'enabled':True},request_id='same');a=s.invoke(**args);revision=r.revision;r.step(.01);self.assertEqual(s.invoke(**args),a);self.assertEqual(r.revision,revision+1);self.assertEqual(s.invoke(**(args|dict(arguments={'enabled':False})))['error']['code'],'REQUEST_CONFLICT')
|
| 193 |
+
def test_operation_history_owner_and_cancel_idempotence(self):
|
| 194 |
+
r=copy.deepcopy(self.cal);s=r.session();response=s.invoke(instance_id='dma80',capability_id='measurement.start',arguments={'slot_index':4},request_id='a');op=response['operation_id'];r.step(.2);a=s.cancel(op,'stop');self.assertEqual(s.cancel(op,'stop'),a);old=s.poll(op);r.step(.5);s.invoke(instance_id='dma80',capability_id='measurement.start',arguments={'slot_index':5},request_id='b');self.assertEqual(s.poll(op),old);r.register_principal('other','agent')
|
| 195 |
+
with self.assertRaises(rt.ActionRejected):r.session('other').poll(op)
|
| 196 |
+
def test_completed_history_survives_record_removal(self):
|
| 197 |
+
r=copy.deepcopy(self.cal);s=r.session();o=s.invoke(instance_id='dma80',capability_id='measurement.start',arguments={'slot_index':4},request_id='run')['operation_id'];until(r,'lowering');r.step(.1);history=s.poll(o);r.invoke('records.remove',record_id='record_5');self.assertEqual(s.poll(o),history)
|
| 198 |
+
def test_sample_time_not_query_clock(self):
|
| 199 |
+
r=copy.deepcopy(self.cal);s=r.session();before=s.read(instance_id='dma80',state_ids=['detector.absorbance']);r.step(.1);after=s.read(instance_id='dma80',state_ids=['detector.absorbance']);self.assertEqual(before['observations'],after['observations']);self.assertNotEqual(before['clock'],after['clock'])
|
| 200 |
+
def test_instances_remain_isolated(self):
|
| 201 |
+
a=copy.deepcopy(self.cal);b=copy.deepcopy(self.cal);before=b.read('evaluator');run(a,[4]);self.assertEqual(b.read('evaluator'),before)
|
| 202 |
+
def test_state_and_output_schemas_are_real(self):
|
| 203 |
+
r=copy.deepcopy(self.cal)
|
| 204 |
+
for k,v in r.read('evaluator').items():rt.validate(rt.SLOTS[k][0],v)
|
| 205 |
+
for name in ['process.measure','result.read','sequence.read','signal.read','blank.read','records.list','sample.inventory','product.read']:rt.validate(rt.CAPS[name][1],r.invoke(name))
|
| 206 |
+
def test_metadata_matches_full_asset_schema(self):
|
| 207 |
+
base=Path(__file__).resolve().parents[1].joinpath('skills/chemistry-lab-assets');spec=importlib.util.spec_from_file_location('dma_schema_tool',base/'scripts/asset_tool.py');tool=importlib.util.module_from_spec(spec);spec.loader.exec_module(tool);schema=json.loads((base/'assets/asset-contract.schema.json').read_text());meta=rt.export_milestone_dma80_contract_metadata()
|
| 208 |
+
for group,name in [('capabilities','capability'),('state_slots','slot'),('mechanisms','mechanism')]:
|
| 209 |
+
for k,v in meta[group].items():self.assertEqual(tool.validate_value(v,schema['$defs'][name],schema,path=k),[],k)
|
| 210 |
+
def test_metadata_errors_legal_and_effects_defined(self):
|
| 211 |
+
meta=rt.export_milestone_dma80_contract_metadata()
|
| 212 |
+
for cap in meta['capabilities'].values():
|
| 213 |
+
self.assertTrue(all(re.fullmatch('[A-Z][A-Z0-9_]*',x['code']) for x in cap['errors']));self.assertTrue(all(x['state_id'] in rt.SLOTS for x in cap['state_effects']))
|
| 214 |
+
if cap['kind']=='query':self.assertEqual(cap['state_effects'],[])
|
| 215 |
+
def test_authority_cannot_be_escalated_by_session_arguments(self):
|
| 216 |
+
r=new()
|
| 217 |
+
with self.assertRaises(rt.ActionRejected):r.session('unregistered')
|
| 218 |
+
with self.assertRaises(rt.ActionRejected):r.register_principal('__public_agent__','evaluator')
|
| 219 |
+
def test_method_rejection_is_atomic(self):self.reject(new(),'method.configure',rt.METHOD_EXAMPLE|dict(record_s=.1,release_s=.5),'INVALID_METHOD')
|
| 220 |
+
def test_library_scalar_not_exposed_by_inventory(self):
|
| 221 |
+
r=new();load(r,0,rt.SAMPLE_EXAMPLE);visible=json.dumps(r.invoke('sample.inventory'));self.assertNotIn('nist_2448',visible);self.assertNotIn('mercury',visible)
|
| 222 |
+
|
| 223 |
+
if __name__=='__main__':unittest.main()
|
tests/test_asset_ossila_dipcoater.py
ADDED
|
@@ -0,0 +1,107 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""CHEM-054 actual process, material, protocol and geometry-limit tests."""
|
| 2 |
+
import copy,math,unittest
|
| 3 |
+
from scripts.asset_runtime.ossila_dipcoater import *
|
| 4 |
+
def configured(name='test',evap=0.,cycles=1):
|
| 5 |
+
h=OssilaDipcoaterRuntime(name);h.invoke('plant.configure',**dict(PLANT_EXAMPLE,mass_transfer_m_s=evap))
|
| 6 |
+
h.invoke('power.set',enabled=True);h.invoke('stage.home');h.step(.02)
|
| 7 |
+
h.invoke('bath.configure',**BATH_EXAMPLE);h.invoke('method.configure',**dict(METHOD_EXAMPLE,cycles=cycles))
|
| 8 |
+
h.invoke('clamp.set_gap',gap_m=.012);h.step(.7);h.invoke('substrate.configure',**SAMPLE_EXAMPLE);h.invoke('clamp.set_gap',gap_m=0.);h.step(.7);return h
|
| 9 |
+
def balance(h):
|
| 10 |
+
p=h._product()
|
| 11 |
+
return [p['initial_'+sp+'_kg']-sum(p[loc+'_'+sp+'_kg'] for loc in ['bath','film','solid','evaporated','collected']) for sp in ['solvent','solute']]
|
| 12 |
+
class DipTests(unittest.TestCase):
|
| 13 |
+
def test_target_only(self):
|
| 14 |
+
h=configured();q=h.q;h.invoke('stage.move_to',position_m=.16,speed_m_s=.005);self.assertEqual(q,h.q);h.step(.1);self.assertAlmostEqual(q-h.q,.0005)
|
| 15 |
+
def test_home_needs_step(self):
|
| 16 |
+
h=OssilaDipcoaterRuntime();h.invoke('plant.configure',**PLANT_EXAMPLE);h.invoke('power.set',enabled=True);h.invoke('stage.home');self.assertFalse(h.homed);h.step(.01);self.assertTrue(h.homed)
|
| 17 |
+
def test_queries_pure(self):
|
| 18 |
+
h=configured();before=h.debug_snapshot();h.read();h.describe();h.invoke('product.read');h.invoke('coating.measure');self.assertEqual(before,h.debug_snapshot())
|
| 19 |
+
def test_rejection_atomic(self):
|
| 20 |
+
h=configured();before=h.debug_snapshot()
|
| 21 |
+
for arguments in [dict(METHOD_EXAMPLE,cycles=True),dict(METHOD_EXAMPLE,cycles=1001),dict(METHOD_EXAMPLE,withdrawal_initial_m_s=0.),dict(METHOD_EXAMPLE,bogus=1)]:
|
| 22 |
+
with self.assertRaises(ActionRejected):h.invoke('method.configure',**arguments)
|
| 23 |
+
self.assertEqual(before,h.debug_snapshot())
|
| 24 |
+
def test_clamp_target_only(self):
|
| 25 |
+
h=configured();h.invoke('product.collect',recipient_id='out');before=h.gap;self.assertEqual(before,0);self.assertEqual(h.gap,0);h.step(.1);self.assertGreater(h.gap,0)
|
| 26 |
+
def test_cannot_open_attached(self):
|
| 27 |
+
h=configured()
|
| 28 |
+
with self.assertRaises(ActionRejected):h.invoke('clamp.set_gap',gap_m=.012)
|
| 29 |
+
def test_bad_geometry(self):
|
| 30 |
+
h=configured();h.invoke('method.configure',**dict(METHOD_EXAMPLE,coating_length_m=.15));before=h.debug_snapshot()
|
| 31 |
+
with self.assertRaises(ActionRejected):h.invoke('acquisition.start')
|
| 32 |
+
self.assertEqual(before,h.debug_snapshot())
|
| 33 |
+
def test_surface_displacement(self):
|
| 34 |
+
h=configured();initial=h._surface();h.q=.04;higher=h._surface();self.assertGreater(higher,initial)
|
| 35 |
+
submerged=max(0,min(h.sample['length_m'],higher-h._bottom()))
|
| 36 |
+
b=h.bath_cfg;s=h.sample
|
| 37 |
+
self.assertAlmostEqual(b['cross_section_m2']*(higher-b['bottom_z_m']),h._volume(h.bath)+s['width_m']*s['thickness_m']*submerged,places=14)
|
| 38 |
+
def test_completed_program(self):
|
| 39 |
+
h=configured();h.invoke('acquisition.start');h.step(60);self.assertEqual(h.phase,'succeeded');self.assertEqual(h.cycle_index,1);self.assertGreater(h._product()['film_solute_kg'],0)
|
| 40 |
+
def test_multicycle_preserves_species(self):
|
| 41 |
+
h=configured(evap=.0001,cycles=3);h.invoke('acquisition.start');h.step(100)
|
| 42 |
+
self.assertEqual(h.phase,'succeeded');self.assertEqual(h.cycle_index,3)
|
| 43 |
+
for residual in balance(h):self.assertLess(abs(residual),1e-12)
|
| 44 |
+
self.assertEqual(h.evaporated[1],0)
|
| 45 |
+
def test_cancel_retains(self):
|
| 46 |
+
h=configured();h.invoke('acquisition.start');h.step(12);self.assertGreater(h._product()['film_solute_kg'],0);p=h._product();q=h.q;h.invoke('acquisition.stop');self.assertEqual(h._product(),p);h.step(1);self.assertEqual(h.q,q);self.assertEqual(h.phase,'cancelled')
|
| 47 |
+
def test_poweroff_needs_rehome(self):
|
| 48 |
+
h=configured();h.invoke('acquisition.start');h.step(1);h.invoke('power.set',enabled=False);q=h.q;h.step(1);self.assertEqual(h.q,q);self.assertFalse(h.homed)
|
| 49 |
+
h.invoke('power.set',enabled=True)
|
| 50 |
+
with self.assertRaises(ActionRejected):h.invoke('acquisition.start')
|
| 51 |
+
def test_crash_immediate_and_reset(self):
|
| 52 |
+
h=configured();h.invoke('acquisition.start');h.step(1);q=h.q;h.invoke('safety.set_crash',triggered=True);self.assertEqual(h.speed,0);h.step(.3);self.assertEqual(h.q,q);self.assertEqual(h.phase,'failed')
|
| 53 |
+
with self.assertRaises(ActionRejected):h.invoke('fault.acknowledge')
|
| 54 |
+
h.invoke('safety.set_crash',triggered=False);h.invoke('fault.acknowledge');self.assertFalse(h.fault)
|
| 55 |
+
def test_bottom_collision(self):
|
| 56 |
+
h=configured();h.invoke('stage.move_to',position_m=0.,speed_m_s=.02);h.bath_cfg['bottom_z_m']=.09;h.step(20);self.assertTrue(h.crash);self.assertGreaterEqual(h._bottom(),.091-1e-12)
|
| 57 |
+
def test_finite_drying(self):
|
| 58 |
+
h=configured(evap=.1);h.invoke('acquisition.start');h.step(40)
|
| 59 |
+
for _ in range(5):h.step(1000)
|
| 60 |
+
for residual in balance(h):self.assertLess(abs(residual),1e-10)
|
| 61 |
+
self.assertTrue(all(v>=0 for v in [*h.bath,*h.evaporated,*h.collected]))
|
| 62 |
+
def test_lld_reference_and_exponent(self):
|
| 63 |
+
h=configured();u=.003;b=h.bath_cfg;rho=sum(h.bath)/h._volume(h.bath)
|
| 64 |
+
expected=.94*math.sqrt(b['surface_tension_n_m']/(rho*9.80665))*(b['viscosity_pa_s']*u/b['surface_tension_n_m'])**(2/3)
|
| 65 |
+
self.assertAlmostEqual(h._lld(u),expected,places=15);self.assertAlmostEqual(h._lld(2*u)/h._lld(u),2**(2/3))
|
| 66 |
+
def test_lld_rejects_high_ca(self):
|
| 67 |
+
h=configured();h.bath_cfg['viscosity_pa_s']=1.;before=h.debug_snapshot()
|
| 68 |
+
with self.assertRaisesRegex(ActionRejected,'MODEL_OUT_OF_RANGE'):h.invoke('acquisition.start')
|
| 69 |
+
self.assertEqual(before,h.debug_snapshot())
|
| 70 |
+
def test_gradient_film(self):
|
| 71 |
+
h=configured();h.invoke('acquisition.start');h.step(60);profile=h._product()['film_profile_m'];nonzero=[x for x in profile if x>0]
|
| 72 |
+
self.assertGreater(len(nonzero),20);self.assertGreater(max(nonzero)/min(nonzero),1.1)
|
| 73 |
+
def test_collect_exactly_once(self):
|
| 74 |
+
h=configured();h.invoke('acquisition.start');h.step(60);h.invoke('product.collect',recipient_id='x');self.assertGreater(h.collected[1],0)
|
| 75 |
+
with self.assertRaises(ActionRejected):h.invoke('product.collect',recipient_id='x')
|
| 76 |
+
for residual in balance(h):self.assertLess(abs(residual),1e-12)
|
| 77 |
+
def test_reference(self):
|
| 78 |
+
h=configured();r=h.invoke('reference.lookup',substance_id='ethanol',temperature_k=298.15);self.assertAlmostEqual(r['vapor_pressure_pa'],7869.085,places=2)
|
| 79 |
+
with self.assertRaises(ActionRejected):h.invoke('reference.lookup',substance_id='ethanol',temperature_k=5.)
|
| 80 |
+
def test_two_instances(self):
|
| 81 |
+
a=configured('a');b=configured('b');before=b.debug_snapshot();a.invoke('acquisition.start');a.step(10);self.assertEqual(before,b.debug_snapshot())
|
| 82 |
+
def test_clock_partition(self):
|
| 83 |
+
a=configured('a');b=configured('b');a.invoke('acquisition.start');b.invoke('acquisition.start');a.step(2)
|
| 84 |
+
for _ in range(20):b.step(.1)
|
| 85 |
+
self.assertAlmostEqual(a.q,b.q,places=12);self.assertAlmostEqual(a.time_s,b.time_s,places=10)
|
| 86 |
+
def test_invalid_clock(self):
|
| 87 |
+
h=configured();before=h.debug_snapshot()
|
| 88 |
+
for dt in [0,-1,float('nan'),True]:
|
| 89 |
+
with self.assertRaises(ActionRejected):h.step(dt)
|
| 90 |
+
self.assertEqual(before,h.debug_snapshot())
|
| 91 |
+
def test_agent_truth_filter(self):
|
| 92 |
+
h=configured();s=h.session();self.assertNotIn('truth.ledger',s.read(instance_id=h.instance_id)['observations']);self.assertNotIn('product.read',s.describe(instance_id=h.instance_id)['capabilities'])
|
| 93 |
+
r=s.invoke(instance_id=h.instance_id,capability_id='product.read',arguments={},request_id='deny');self.assertEqual(r['error']['code'],'ACCESS_DENIED')
|
| 94 |
+
with self.assertRaises(ActionRejected):h.session('evaluator')
|
| 95 |
+
def test_request_dedup(self):
|
| 96 |
+
h=configured();s=h.session();a=dict(instance_id=h.instance_id,capability_id='power.toggle',arguments={},request_id='same');r=s.invoke(**a);powered=h.powered;self.assertEqual(s.invoke(**a),r);self.assertEqual(powered,h.powered)
|
| 97 |
+
self.assertEqual(s.invoke(**dict(a,capability_id='power.set',arguments={'enabled':True}))['error']['code'],'REQUEST_CONFLICT')
|
| 98 |
+
def test_async_owner_cancel(self):
|
| 99 |
+
h=configured();s=h.session();h.register_principal('other');other=h.session('other');r=s.invoke(instance_id=h.instance_id,capability_id='acquisition.start',arguments={},request_id='start');op=r['operation_id'];self.assertEqual(r['status'],'accepted');h.step(12)
|
| 100 |
+
with self.assertRaises(ActionRejected):other.poll(op)
|
| 101 |
+
before=h._product();s.cancel(op,'cancel');self.assertEqual(s.poll(op)['status'],'cancelled');self.assertEqual(h._product(),before)
|
| 102 |
+
def test_write_routes(self):
|
| 103 |
+
h=configured();s=h.session();r=s.write(instance_id=h.instance_id,state_id='power.enabled',value=False,request_id='write');self.assertEqual(r['status'],'succeeded');self.assertFalse(h.powered)
|
| 104 |
+
with self.assertRaises(ActionRejected):s.write(instance_id=h.instance_id,state_id='truth.ledger',value={},request_id='bad')
|
| 105 |
+
def test_no_implicit_time(self):
|
| 106 |
+
h=configured();t=h.time_s;h.invoke('acquisition.start');h.invoke('coating.measure');self.assertEqual(t,h.time_s)
|
| 107 |
+
if __name__=='__main__':unittest.main()
|
tests/test_asset_ossila_doctorblade.py
ADDED
|
@@ -0,0 +1,117 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""CHEM-055 actual physics, protocol and finite-inventory tests."""
|
| 2 |
+
import copy,math,unittest
|
| 3 |
+
from scripts.asset_runtime.ossila_doctorblade import *
|
| 4 |
+
def configured(name='test',evap=0.,charge=True):
|
| 5 |
+
h=OssilaDoctorbladeRuntime(name);h.invoke('plant.configure',**dict(PLANT_EXAMPLE,mass_transfer_m_s=evap));h.invoke('power.set',enabled=True);h.invoke('stage.home');h.step(.02)
|
| 6 |
+
h.invoke('method.configure',**METHOD_EXAMPLE);h.invoke('substrate.configure',**SAMPLE_EXAMPLE);h.invoke('gap.set',left_m=.0001,right_m=.0001);h.step(.1)
|
| 7 |
+
if charge:h.invoke('charge.configure',**CHARGE_EXAMPLE)
|
| 8 |
+
return h
|
| 9 |
+
def balance(h):
|
| 10 |
+
p=h._product()
|
| 11 |
+
return [p['initial_'+sp+'_kg']-sum(p[loc+'_'+sp+'_kg'] for loc in ['bead','film','waste','evaporated','collected']) for sp in ['solvent','solute']]
|
| 12 |
+
class BladeTests(unittest.TestCase):
|
| 13 |
+
def test_targets_only(self):
|
| 14 |
+
h=configured(charge=False);h.invoke('stage.move_to',position_m=.1,speed_m_s=.02);self.assertEqual(h.q,0.);h.step(.1);self.assertAlmostEqual(h.q,.002)
|
| 15 |
+
def test_home_needs_clock(self):
|
| 16 |
+
h=OssilaDoctorbladeRuntime();h.invoke('plant.configure',**PLANT_EXAMPLE);h.invoke('power.set',enabled=True);h.invoke('stage.home');self.assertFalse(h.homed);h.step(.01);self.assertTrue(h.homed)
|
| 17 |
+
def test_manual_gap_poweroff(self):
|
| 18 |
+
h=configured();h.invoke('power.set',enabled=False);h.invoke('gap.set',left_m=.001,right_m=.002);self.assertEqual(h.gaps,[.0001,.0001]);h.step(.05);self.assertGreater(h.gaps[0],.0001);h.step(1);self.assertEqual(h.gaps,[.001,.002])
|
| 19 |
+
def test_nonparallel_gap_pose(self):
|
| 20 |
+
h=configured();h.invoke('gap.set',left_m=.0001,right_m=.0003);h.step(.1);v=h.read();self.assertAlmostEqual(v['gap.mean_m'],.0002);self.assertAlmostEqual(v['gap.tilt_rad'],-math.atan(.002))
|
| 21 |
+
def test_queries_pure(self):
|
| 22 |
+
h=configured();before=h.debug_snapshot();h.read();h.describe();h.invoke('coating.measure');h.invoke('product.read');self.assertEqual(before,h.debug_snapshot())
|
| 23 |
+
def test_rejection_atomic(self):
|
| 24 |
+
h=configured();before=h.debug_snapshot()
|
| 25 |
+
for a in [dict(METHOD_EXAMPLE,speed_m_s=True),dict(METHOD_EXAMPLE,speed_m_s=.000051),dict(METHOD_EXAMPLE,speed_m_s=float('nan')),dict(METHOD_EXAMPLE,bogus=1)]:
|
| 26 |
+
with self.assertRaises(ActionRejected):h.invoke('method.configure',**a)
|
| 27 |
+
self.assertEqual(before,h.debug_snapshot())
|
| 28 |
+
def test_gap_increment(self):
|
| 29 |
+
h=configured();before=h.debug_snapshot()
|
| 30 |
+
with self.assertRaises(ActionRejected):h.invoke('gap.set',left_m=.0001015,right_m=.0001)
|
| 31 |
+
self.assertEqual(before,h.debug_snapshot())
|
| 32 |
+
def test_schema_negative_control(self):
|
| 33 |
+
import importlib.util
|
| 34 |
+
s=importlib.util.spec_from_file_location('tool',ROOT/'skills/chemistry-lab-assets/scripts/asset_tool.py');t=importlib.util.module_from_spec(s);s.loader.exec_module(t)
|
| 35 |
+
self.assertTrue(t.validate_value({'enabled':1},CAPS['power.set'][1]));self.assertTrue(t.validate_value({'phase':'fake'},CAPS['acquisition.stop'][1]))
|
| 36 |
+
def test_complete_and_mass(self):
|
| 37 |
+
h=configured(evap=.0002);h.invoke('acquisition.start');h.step(20);self.assertEqual(h.phase,'succeeded');self.assertEqual(h.q,.26)
|
| 38 |
+
self.assertGreater(h._product()['film_solute_kg'],0);self.assertGreater(h.waste[1],0)
|
| 39 |
+
for e in balance(h):self.assertLess(abs(e),1e-14)
|
| 40 |
+
def test_analytic_inventory_integral(self):
|
| 41 |
+
h=configured();v=h._volume(h.bead);rho=sum(h.bead)/v;c=h.charge_cfg;g=.0001;u=.02;length=.01
|
| 42 |
+
a=.1*g/2;b=.1*rho*9.80665*g**3/(12*c['viscosity_pa_s']*c['blade_contact_length_m']*u*c['reservoir_area_m2'])
|
| 43 |
+
expect=(v+a/b)*math.exp(-b*length)-a/b;h._deposit(0,length,u);self.assertAlmostEqual(h._volume(h.bead),expect,places=15)
|
| 44 |
+
def test_not_gap_equals_thickness(self):
|
| 45 |
+
h=configured();h.invoke('acquisition.start');h.step(20);p=h._product();self.assertGreater(p['wet_thickness_m'],.00005);self.assertLess(p['wet_thickness_m'],.0001)
|
| 46 |
+
def test_pressure_speed_dependence(self):
|
| 47 |
+
a=configured();b=configured();a._deposit(.03,.05,.001);b._deposit(.03,.05,.1);self.assertGreater(a._product()['film_solute_kg'],b._product()['film_solute_kg'])
|
| 48 |
+
def test_empty_inventory_no_creation(self):
|
| 49 |
+
h=configured(charge=False);h.invoke('charge.configure',**dict(CHARGE_EXAMPLE,solvent_kg=1e-8,solute_kg=1e-8));h.invoke('acquisition.start');h.step(20)
|
| 50 |
+
self.assertEqual(h.phase,'succeeded');self.assertLess(sum(h.bead),1e-20);self.assertEqual(h._product()['film_solute_kg'],0.)
|
| 51 |
+
for e in balance(h):self.assertLess(abs(e),1e-20)
|
| 52 |
+
def test_model_rejects_large_gap(self):
|
| 53 |
+
h=configured();h.invoke('gap.set',left_m=.01,right_m=.01);h.step(3);before=h.debug_snapshot()
|
| 54 |
+
with self.assertRaisesRegex(ActionRejected,'MODEL_OUT_OF_RANGE'):h.invoke('acquisition.start')
|
| 55 |
+
self.assertEqual(before,h.debug_snapshot())
|
| 56 |
+
def test_no_reverse_coating(self):
|
| 57 |
+
h=configured()
|
| 58 |
+
with self.assertRaises(ActionRejected):h.invoke('stage.move_to',position_m=.1,speed_m_s=.02)
|
| 59 |
+
def test_cancel_retains_and_freezes(self):
|
| 60 |
+
h=configured();h.invoke('acquisition.start');h.step(3);p=h._product();q=h.q;h.invoke('acquisition.stop');self.assertEqual(p,h._product());h.step(1);self.assertEqual(h.q,q);self.assertEqual(h.phase,'cancelled')
|
| 61 |
+
def test_evaporation_after_stop(self):
|
| 62 |
+
h=configured(evap=.0002);h.invoke('acquisition.start');h.step(3);h.invoke('acquisition.stop');before=h.evaporated[0];h.step(1);self.assertGreater(h.evaporated[0],before)
|
| 63 |
+
for e in balance(h):self.assertLess(abs(e),1e-14)
|
| 64 |
+
def test_poweroff_rehome(self):
|
| 65 |
+
h=configured();h.invoke('power.set',enabled=False);self.assertFalse(h.homed);h.invoke('power.set',enabled=True)
|
| 66 |
+
with self.assertRaises(ActionRejected):h.invoke('acquisition.start')
|
| 67 |
+
def test_emergency_reset_sequence(self):
|
| 68 |
+
h=configured();h.invoke('acquisition.start');h.step(3);q=h.q;h.invoke('emergency.stop');h.step(1);self.assertEqual(h.q,q);self.assertFalse(h.powered);self.assertEqual(h.phase,'failed')
|
| 69 |
+
with self.assertRaises(ActionRejected):h.invoke('power.set',enabled=True)
|
| 70 |
+
h.invoke('emergency.release')
|
| 71 |
+
with self.assertRaises(ActionRejected):h.invoke('power.set',enabled=True)
|
| 72 |
+
h.invoke('power.set',enabled=False);h.invoke('power.set',enabled=True);self.assertFalse(h.latched);self.assertFalse(h.homed)
|
| 73 |
+
def test_reset_powercycle_before_release_not_enough(self):
|
| 74 |
+
h=configured();h.invoke('emergency.stop');h.invoke('power.set',enabled=False);h.invoke('emergency.release')
|
| 75 |
+
with self.assertRaises(ActionRejected):h.invoke('power.set',enabled=True)
|
| 76 |
+
def test_collect_and_cleanup(self):
|
| 77 |
+
h=configured();h.invoke('acquisition.start');h.step(20);h.invoke('product.collect',recipient_id='x');self.assertGreater(h.collected[1],0);h.invoke('reservoir.empty');h.invoke('stage.home');h.step(20);self.assertEqual(h.q,0.)
|
| 78 |
+
with self.assertRaises(ActionRejected):h.invoke('product.collect',recipient_id='x')
|
| 79 |
+
for e in balance(h):self.assertLess(abs(e),1e-14)
|
| 80 |
+
def test_finite_drying(self):
|
| 81 |
+
h=configured(evap=.1);h.invoke('acquisition.start');h.step(100);self.assertEqual(h.evaporated[1],0.)
|
| 82 |
+
for e in balance(h):self.assertLess(abs(e),1e-14)
|
| 83 |
+
self.assertTrue(all(v>=0 for v in [*h.bead,*h.waste,*h.evaporated,*h.collected,*[v for f in h.film for v in f]]))
|
| 84 |
+
def test_reference(self):
|
| 85 |
+
h=configured();self.assertAlmostEqual(h.invoke('reference.lookup',substance_id='ethanol',temperature_k=298.15)['vapor_pressure_pa'],7869.085,places=2)
|
| 86 |
+
with self.assertRaises(ActionRejected):h.invoke('reference.lookup',substance_id='ethanol',temperature_k=5.)
|
| 87 |
+
def test_instances_and_partition(self):
|
| 88 |
+
a=configured('a');b=configured('b');before=b.debug_snapshot();a.invoke('acquisition.start');a.step(2);self.assertEqual(before,b.debug_snapshot());b.invoke('acquisition.start')
|
| 89 |
+
for _ in range(20):b.step(.1)
|
| 90 |
+
self.assertAlmostEqual(a.q,b.q,places=12)
|
| 91 |
+
self.assertAlmostEqual(a._product()['film_solute_kg'],b._product()['film_solute_kg'],places=14)
|
| 92 |
+
def test_invalid_clock(self):
|
| 93 |
+
h=configured();before=h.debug_snapshot()
|
| 94 |
+
for dt in [0,-1,float('nan'),True]:
|
| 95 |
+
with self.assertRaises(ActionRejected):h.step(dt)
|
| 96 |
+
self.assertEqual(before,h.debug_snapshot())
|
| 97 |
+
def test_agent_truth_filter(self):
|
| 98 |
+
h=configured();s=h.session();self.assertNotIn('truth.ledger',s.read(instance_id=h.instance_id)['observations']);self.assertNotIn('product.read',s.describe(instance_id=h.instance_id)['capabilities'])
|
| 99 |
+
self.assertEqual(s.invoke(instance_id=h.instance_id,capability_id='product.read',arguments={},request_id='deny')['error']['code'],'ACCESS_DENIED')
|
| 100 |
+
with self.assertRaises(ActionRejected):h.session('evaluator')
|
| 101 |
+
def test_request_dedup_and_write(self):
|
| 102 |
+
h=configured();s=h.session();a=dict(instance_id=h.instance_id,capability_id='power.toggle',arguments={},request_id='same');r=s.invoke(**a);powered=h.powered;self.assertEqual(s.invoke(**a),r);self.assertEqual(powered,h.powered)
|
| 103 |
+
self.assertEqual(s.invoke(**dict(a,capability_id='power.set',arguments={'enabled':True}))['error']['code'],'REQUEST_CONFLICT')
|
| 104 |
+
self.assertEqual(s.write(instance_id=h.instance_id,state_id='power.enabled',value=True,request_id='write')['status'],'succeeded')
|
| 105 |
+
with self.assertRaises(ActionRejected):s.write(instance_id=h.instance_id,state_id='truth.ledger',value={},request_id='bad')
|
| 106 |
+
def test_async_owner_cancel(self):
|
| 107 |
+
h=configured();s=h.session();h.register_principal('other');other=h.session('other');r=s.invoke(instance_id=h.instance_id,capability_id='acquisition.start',arguments={},request_id='start');op=r['operation_id'];self.assertEqual(r['status'],'accepted');h.step(3)
|
| 108 |
+
with self.assertRaises(ActionRejected):other.poll(op)
|
| 109 |
+
before=h._product();s.cancel(op,'cancel');self.assertEqual(s.poll(op)['status'],'cancelled');self.assertEqual(h._product(),before)
|
| 110 |
+
def test_zero_distance_transition_does_not_double_gap_clock(self):
|
| 111 |
+
h=configured(charge=False);h.invoke('gap.set',left_m=.01,right_m=.01);before=h.gaps[0];h.invoke('stage.home');h.step(.005)
|
| 112 |
+
self.assertAlmostEqual(h.gaps[0]-before,.005*.005,places=15)
|
| 113 |
+
def test_no_implicit_time(self):
|
| 114 |
+
h=configured();t=h.time_s;h.invoke('acquisition.start');h.invoke('coating.measure');self.assertEqual(t,h.time_s)
|
| 115 |
+
if __name__=='__main__':unittest.main()
|
| 116 |
+
|
| 117 |
+
|
tests/test_asset_ossila_slotdie.py
ADDED
|
@@ -0,0 +1,123 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""CHEM-056 finite fluid chain, metering, energy, timing and trusted protocol tests."""
|
| 2 |
+
import copy,math,unittest
|
| 3 |
+
from scripts.asset_runtime.ossila_slotdie import *
|
| 4 |
+
def configured(name='test',evap=0.,prime=True,ink=True):
|
| 5 |
+
h=OssilaSlotdieRuntime(name);h.invoke('plant.configure',**dict(PLANT_EXAMPLE,mass_transfer_m_s=evap));h.invoke('power.set',enabled=True);h.invoke('stage.home');h.step(.02)
|
| 6 |
+
h.invoke('method.configure',**METHOD_EXAMPLE);h.invoke('substrate.configure',**SAMPLE_EXAMPLE);h.invoke('gap.set',left_m=.0001,right_m=.0001);h.step(.1)
|
| 7 |
+
if ink:h.invoke('ink.configure',**INK_EXAMPLE)
|
| 8 |
+
if prime and ink:h.invoke('pump.dispense',volume_m3=1e-7,flow_m3_s=2e-8);h.step(6)
|
| 9 |
+
return h
|
| 10 |
+
def residuals(h):
|
| 11 |
+
p=h._product()
|
| 12 |
+
return [p['initial_'+sp+'_kg']-sum(p[loc+'_'+sp+'_kg'] for loc in ['syringe','line','bead','film','waste','evaporated','collected']) for sp in ['solvent','solute']]
|
| 13 |
+
class SlotTests(unittest.TestCase):
|
| 14 |
+
def test_spec_limits(self):
|
| 15 |
+
h=configured(ink=False)
|
| 16 |
+
for speed in [.00005,.075]:h.invoke('method.configure',**dict(METHOD_EXAMPLE,speed_m_s=speed))
|
| 17 |
+
for x in [0,.013]:h.invoke('gap.set',left_m=x,right_m=x)
|
| 18 |
+
h.invoke('thermal.set_temperature',temperature_k=413.15)
|
| 19 |
+
with self.assertRaises(ActionRejected):h.invoke('thermal.set_temperature',temperature_k=413.16)
|
| 20 |
+
self.assertAlmostEqual(Q_MIN*1e9,.499937346929,places=5);self.assertAlmostEqual(Q_MAX*1e9,624.921683661265,places=4)
|
| 21 |
+
def test_targets_and_home_are_asynchronous(self):
|
| 22 |
+
h=OssilaSlotdieRuntime();h.invoke('plant.configure',**PLANT_EXAMPLE);h.invoke('power.set',enabled=True);h.invoke('stage.home');self.assertFalse(h.homed);h.step(.02);self.assertTrue(h.homed)
|
| 23 |
+
h.invoke('stage.move_to',position_m=.1,speed_m_s=.01);self.assertEqual(h.q,0);h.step(.1);self.assertAlmostEqual(h.q,.001)
|
| 24 |
+
def test_manual_gap_and_exact_endpoints(self):
|
| 25 |
+
h=configured(ink=False);h.invoke('power.set',enabled=False);h.invoke('gap.set',left_m=.001,right_m=.003);self.assertEqual(h.gaps,[.0001,.0001]);h.step(1);s=h.read()
|
| 26 |
+
self.assertAlmostEqual(s['gap.mean_m']+.05*math.sin(s['gap.tilt_rad']),.001)
|
| 27 |
+
self.assertAlmostEqual(s['gap.mean_m']-.05*math.sin(s['gap.tilt_rad']),.003)
|
| 28 |
+
def test_no_double_zero_distance_gap_clock(self):
|
| 29 |
+
h=configured(ink=False);h.invoke('gap.set',left_m=.01,right_m=.01);q=h.gaps[0];h.invoke('stage.home');h.step(.005);self.assertAlmostEqual(h.gaps[0]-q,.000025)
|
| 30 |
+
def test_query_purity(self):
|
| 31 |
+
h=configured();snap=h.debug_snapshot();h.describe();h.read();h.invoke('coating.measure');h.invoke('product.read');self.assertEqual(h.debug_snapshot(),snap)
|
| 32 |
+
def test_atomic_rejection(self):
|
| 33 |
+
h=configured();snap=h.debug_snapshot()
|
| 34 |
+
for args in [dict(METHOD_EXAMPLE,speed_m_s=True),dict(METHOD_EXAMPLE,flow_m3_s=Q_MIN/2),dict(METHOD_EXAMPLE,flow_m3_s=float('nan')),dict(METHOD_EXAMPLE,bogus=1)]:
|
| 35 |
+
with self.assertRaises(ActionRejected):h.invoke('method.configure',**args)
|
| 36 |
+
self.assertEqual(h.debug_snapshot(),snap)
|
| 37 |
+
def test_cannot_start_unprimed(self):
|
| 38 |
+
h=configured(prime=False);snap=h.debug_snapshot()
|
| 39 |
+
with self.assertRaisesRegex(ActionRejected,'NOT_PRIMED'):h.invoke('acquisition.start')
|
| 40 |
+
self.assertEqual(h.debug_snapshot(),snap)
|
| 41 |
+
def test_prime_chain_and_plunger(self):
|
| 42 |
+
h=configured(prime=False);q=h.pump_q;h.invoke('pump.dispense',volume_m3=1e-7,flow_m3_s=2e-8);self.assertEqual(q,h.pump_q);h.step(6)
|
| 43 |
+
self.assertEqual(h.phase,'succeeded');self.assertAlmostEqual(h._volume(h.line),5e-8,places=15);self.assertAlmostEqual(h._volume(h.bead),1e-8,places=15);self.assertAlmostEqual(h._volume(h.waste),4e-8,places=15)
|
| 44 |
+
self.assertAlmostEqual((h.pump_q-q)*PISTON_AREA,1e-7,places=15)
|
| 45 |
+
def test_closed_mass_and_complete(self):
|
| 46 |
+
h=configured(evap=.0002);h.invoke('acquisition.start');h.step(20);self.assertEqual(h.phase,'succeeded');self.assertAlmostEqual(h.q,.14)
|
| 47 |
+
for r in residuals(h):self.assertLess(abs(r),1e-13)
|
| 48 |
+
self.assertGreater(h._product()['film_solute_kg'],0);self.assertEqual(h.evaporated[1],0)
|
| 49 |
+
def test_metered_thickness(self):
|
| 50 |
+
h=configured();h.invoke('method.configure',**dict(METHOD_EXAMPLE,stage_delay_s=0.));h.invoke('acquisition.start');h.step(20)
|
| 51 |
+
self.assertAlmostEqual(h._product()['wet_thickness_m'],METHOD_EXAMPLE['flow_m3_s']/(.1*METHOD_EXAMPLE['speed_m_s']),places=12)
|
| 52 |
+
def test_flow_over_speed_scaling(self):
|
| 53 |
+
a=configured();b=configured();b.invoke('method.configure',**dict(METHOD_EXAMPLE,flow_m3_s=4e-8));a.invoke('acquisition.start');b.invoke('acquisition.start');a.step(20);b.step(20)
|
| 54 |
+
self.assertAlmostEqual(b._product()['wet_thickness_m']/a._product()['wet_thickness_m'],2.,places=8)
|
| 55 |
+
def test_delay_pumps_without_axis_motion(self):
|
| 56 |
+
h=configured();h.invoke('method.configure',**dict(METHOD_EXAMPLE,stage_delay_s=2));before=h.delivered;h.invoke('acquisition.start');h.step(1);self.assertEqual(h.q,0);self.assertAlmostEqual(h.delivered-before,2e-8,places=15)
|
| 57 |
+
def test_delay_zero_stage_never_divides_zero(self):
|
| 58 |
+
h=configured();h.invoke('pump.dispense',volume_m3=2e-8,flow_m3_s=2e-8);h.step(2);self.assertEqual(h.q,0)
|
| 59 |
+
for r in residuals(h):self.assertLess(abs(r),1e-13)
|
| 60 |
+
def test_window_rejection_atomic(self):
|
| 61 |
+
h=configured();h.invoke('gap.set',left_m=.013,right_m=.013);h.step(3);snap=h.debug_snapshot()
|
| 62 |
+
with self.assertRaisesRegex(ActionRejected,'MODEL_OUT_OF_RANGE'):h.invoke('acquisition.start')
|
| 63 |
+
self.assertEqual(snap,h.debug_snapshot())
|
| 64 |
+
def test_cancel_preserves_line_film(self):
|
| 65 |
+
h=configured();h.invoke('acquisition.start');h.step(3);p=h._product();q=h.q;h.invoke('acquisition.stop');self.assertEqual(p,h._product());h.step(1);self.assertEqual(q,h.q);self.assertEqual(h.flow,0)
|
| 66 |
+
def test_empty_syringe_fails_without_creation(self):
|
| 67 |
+
h=configured(ink=False);volume=1.2e-7;h.invoke('ink.configure',**dict(INK_EXAMPLE,solvent_kg=volume*789,solute_kg=0.));h.invoke('pump.dispense',volume_m3=8e-8,flow_m3_s=2e-8);h.step(5)
|
| 68 |
+
h.invoke('acquisition.start');h.step(10);self.assertEqual(h.phase,'failed');self.assertEqual(h.fault,'SYRINGE_EMPTY')
|
| 69 |
+
for r in residuals(h):self.assertLess(abs(r),1e-14)
|
| 70 |
+
def test_heating_target_only_and_energy(self):
|
| 71 |
+
h=configured(ink=False);t=h.temp;h.invoke('thermal.set_temperature',temperature_k=313.15);h.invoke('thermal.set_enabled',enabled=True);self.assertEqual(t,h.temp);h.step(20);self.assertGreater(h.temp,t);self.assertLess(h.temp,313.15)
|
| 72 |
+
p=h._product();self.assertAlmostEqual(p['sensible_j'],p['energy_input_j']-p['energy_loss_j']-p['latent_j'],places=9)
|
| 73 |
+
def test_film_evaporation_latent_energy(self):
|
| 74 |
+
h=configured(evap=.001);h.invoke('thermal.set_temperature',temperature_k=313.15);h.invoke('thermal.set_enabled',enabled=True);h.invoke('acquisition.start');h.step(20)
|
| 75 |
+
self.assertGreater(h.evaporated[0],0);p=h._product();self.assertAlmostEqual(p['latent_j'],h.evaporated[0]*INK_EXAMPLE['latent_heat_j_kg'],places=9)
|
| 76 |
+
self.assertAlmostEqual(p['sensible_j'],p['energy_input_j']-p['energy_loss_j']-p['latent_j'],places=8)
|
| 77 |
+
def test_normal_stop_preserves_heater(self):
|
| 78 |
+
h=configured();h.invoke('thermal.set_temperature',temperature_k=313.15);h.invoke('thermal.set_enabled',enabled=True);h.invoke('acquisition.start');h.step(2);h.invoke('acquisition.stop');self.assertTrue(h.heating);t=h.temp;h.step(1);self.assertGreater(h.temp,t)
|
| 79 |
+
def test_poweroff_cools_not_teleports(self):
|
| 80 |
+
h=configured(ink=False);h.invoke('thermal.set_temperature',temperature_k=313.15);h.invoke('thermal.set_enabled',enabled=True);h.step(20);t=h.temp;h.invoke('power.set',enabled=False);self.assertEqual(h.temp,t);self.assertFalse(h.heating);h.step(1);self.assertLess(h.temp,t)
|
| 81 |
+
def test_reference_target_guard(self):
|
| 82 |
+
h=configured();snap=h.debug_snapshot()
|
| 83 |
+
with self.assertRaisesRegex(ActionRejected,'REFERENCE_OUT_OF_RANGE'):h.invoke('thermal.set_temperature',temperature_k=413.15)
|
| 84 |
+
self.assertEqual(snap,h.debug_snapshot())
|
| 85 |
+
def test_offset_display_only(self):
|
| 86 |
+
h=configured();t=h.temp;h.invoke('thermal.set_offset',offset_k=2.);self.assertEqual(h.temp,t);self.assertEqual(h.read()['thermal.indicated_k'],t+2)
|
| 87 |
+
def test_emergency_stops_both_and_heat(self):
|
| 88 |
+
h=configured();h.invoke('thermal.set_enabled',enabled=True);h.invoke('acquisition.start');h.step(2);h.invoke('emergency.stop');q=h.q;p=h.pump_q;h.step(1);self.assertEqual(h.q,q);self.assertEqual(h.pump_q,p);self.assertFalse(h.heating)
|
| 89 |
+
h.invoke('emergency.release')
|
| 90 |
+
with self.assertRaises(ActionRejected):h.invoke('power.set',enabled=True)
|
| 91 |
+
h.invoke('power.set',enabled=False);h.invoke('power.set',enabled=True);self.assertFalse(h.latched);self.assertFalse(h.homed)
|
| 92 |
+
def test_collect_drain_and_conservation(self):
|
| 93 |
+
h=configured();h.invoke('acquisition.start');h.step(20);h.invoke('product.collect',recipient_id='x');h.invoke('fluid.drain');self.assertGreater(h.collected[1],0)
|
| 94 |
+
for r in residuals(h):self.assertLess(abs(r),1e-13)
|
| 95 |
+
with self.assertRaises(ActionRejected):h.invoke('product.collect',recipient_id='x')
|
| 96 |
+
def test_time_partition_instances(self):
|
| 97 |
+
a=configured('a');b=configured('b');before=b.debug_snapshot();a.invoke('acquisition.start');a.step(2);self.assertEqual(before,b.debug_snapshot());b.invoke('acquisition.start')
|
| 98 |
+
for _ in range(20):b.step(.1)
|
| 99 |
+
self.assertAlmostEqual(a.q,b.q,places=12);self.assertAlmostEqual(a.delivered,b.delivered,places=14)
|
| 100 |
+
def test_invalid_clock(self):
|
| 101 |
+
h=configured();snap=h.debug_snapshot()
|
| 102 |
+
for dt in [0,-1,True,float('nan')]:
|
| 103 |
+
with self.assertRaises(ActionRejected):h.step(dt)
|
| 104 |
+
self.assertEqual(snap,h.debug_snapshot())
|
| 105 |
+
def test_agent_truth_filter(self):
|
| 106 |
+
h=configured();s=h.session();self.assertNotIn('truth.ledger',s.read(instance_id=h.instance_id)['observations']);self.assertNotIn('ink.configure',s.describe(instance_id=h.instance_id)['capabilities'])
|
| 107 |
+
self.assertEqual(s.invoke(instance_id=h.instance_id,capability_id='product.read',arguments={},request_id='deny')['error']['code'],'ACCESS_DENIED')
|
| 108 |
+
with self.assertRaises(ActionRejected):h.session('evaluator')
|
| 109 |
+
def test_dedup_and_write(self):
|
| 110 |
+
h=configured();s=h.session();a=dict(instance_id=h.instance_id,capability_id='power.toggle',arguments={},request_id='id');r=s.invoke(**a);self.assertEqual(r,s.invoke(**a));self.assertFalse(h.powered)
|
| 111 |
+
self.assertEqual(s.invoke(**dict(a,arguments={'enabled':True},capability_id='power.set'))['error']['code'],'REQUEST_CONFLICT')
|
| 112 |
+
self.assertEqual(s.write(instance_id=h.instance_id,state_id='power.enabled',value=True,request_id='w')['status'],'succeeded')
|
| 113 |
+
def test_async_owner_cancel(self):
|
| 114 |
+
h=configured();s=h.session();h.register_principal('other');other=h.session('other');r=s.invoke(instance_id=h.instance_id,capability_id='acquisition.start',arguments={},request_id='start');op=r['operation_id'];h.step(2)
|
| 115 |
+
with self.assertRaises(ActionRejected):other.poll(op)
|
| 116 |
+
s.cancel(op,'c');self.assertEqual(s.poll(op)['status'],'cancelled')
|
| 117 |
+
def test_negative_schema(self):
|
| 118 |
+
import importlib.util
|
| 119 |
+
s=importlib.util.spec_from_file_location('tool',ROOT/'skills/chemistry-lab-assets/scripts/asset_tool.py');t=importlib.util.module_from_spec(s);s.loader.exec_module(t)
|
| 120 |
+
self.assertTrue(t.validate_value({'enabled':1},CAPS['power.set'][1]));self.assertTrue(t.validate_value({'phase':'fake'},CAPS['acquisition.stop'][1]))
|
| 121 |
+
if __name__=='__main__':unittest.main()
|
| 122 |
+
|
| 123 |
+
|
tests/test_asset_ossila_spincoater.py
ADDED
|
@@ -0,0 +1,146 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Meaningful process, ledger, schema, cancellation and access-boundary tests."""
|
| 2 |
+
import copy,importlib.util,json,math,sys,unittest
|
| 3 |
+
from pathlib import Path
|
| 4 |
+
ROOT=Path(__file__).resolve().parents[1];sys.path.insert(0,str(ROOT/'scripts'))
|
| 5 |
+
from asset_runtime import ossila_spincoater as rt
|
| 6 |
+
spec=importlib.util.spec_from_file_location('spin_asset_tool',ROOT/'skills/chemistry-lab-assets/scripts/asset_tool.py')
|
| 7 |
+
tool=importlib.util.module_from_spec(spec);spec.loader.exec_module(tool)
|
| 8 |
+
|
| 9 |
+
def configured(name='spincoater_01',evap=.001):
|
| 10 |
+
h=rt.OssilaSpincoaterRuntime(name)
|
| 11 |
+
h.invoke('plant.configure',**dict(rt.PLANT_EXAMPLE,mass_transfer_m_s=evap))
|
| 12 |
+
h.invoke('method.configure',**copy.deepcopy(rt.METHOD_EXAMPLE))
|
| 13 |
+
h.invoke('lid.set_angle',angle_rad=1.5);h.step(1.1)
|
| 14 |
+
h.invoke('sample.configure',**copy.deepcopy(rt.SAMPLE_EXAMPLE))
|
| 15 |
+
h.invoke('lid.set_angle',angle_rad=0.);h.step(1.1);h.invoke('power.set',enabled=True)
|
| 16 |
+
return h
|
| 17 |
+
|
| 18 |
+
def balances(h):
|
| 19 |
+
return [h.initial[i]-h.film[i]-h.waste[i]-h.evaporated[i]-h.collected[i] for i in range(2)]
|
| 20 |
+
|
| 21 |
+
class SpinCoaterTests(unittest.TestCase):
|
| 22 |
+
def test_schema_negative_control(self):
|
| 23 |
+
self.assertTrue(tool.validate_value({'enabled':1},rt.CAPS['power.set'][1]))
|
| 24 |
+
self.assertTrue(tool.validate_value({'phase':'invented'},rt.CAPS['acquisition.stop'][1]))
|
| 25 |
+
def test_target_does_not_advance(self):
|
| 26 |
+
h=configured();before=h.read('evaluator');h.invoke('acquisition.start')
|
| 27 |
+
self.assertEqual(h.speed,0);self.assertEqual(h.film[0],before['truth.ledger']['film_solvent_kg'])
|
| 28 |
+
self.assertGreater(h.target_speed,0);h.step(.1);self.assertGreater(h.speed,0)
|
| 29 |
+
def test_read_describe_are_pure(self):
|
| 30 |
+
h=configured();before=h.debug_snapshot()
|
| 31 |
+
for _ in range(3):h.read();h.describe();h.invoke('coating.measure')
|
| 32 |
+
self.assertEqual(before,h.debug_snapshot())
|
| 33 |
+
def test_reject_preserves_all_process_state(self):
|
| 34 |
+
h=configured();before=h.debug_snapshot()
|
| 35 |
+
for cap,args in [('method.configure',{'steps':[]}),('lid.set_angle',{'angle_rad':float('nan')}),('power.set',{'enabled':1}),('sample.configure',rt.SAMPLE_EXAMPLE)]:
|
| 36 |
+
with self.assertRaises(rt.ActionRejected):h.invoke(cap,**args)
|
| 37 |
+
self.assertEqual(before,h.debug_snapshot())
|
| 38 |
+
def test_standard_has_no_acceleration_device_setting(self):
|
| 39 |
+
h=configured();before=h.debug_snapshot()
|
| 40 |
+
with self.assertRaises(rt.ActionRejected):h.invoke('method.configure',steps=rt.METHOD_EXAMPLE['steps'],acceleration_rad_s2=10.)
|
| 41 |
+
self.assertEqual(before,h.debug_snapshot())
|
| 42 |
+
self.assertNotIn('plant.configure',h.describe()['capabilities'])
|
| 43 |
+
def test_open_lid_blocks_start(self):
|
| 44 |
+
h=configured();h.invoke('lid.set_angle',angle_rad=1.5);h.step(1.1);before=h.debug_snapshot()
|
| 45 |
+
with self.assertRaises(rt.ActionRejected):h.invoke('acquisition.start')
|
| 46 |
+
self.assertEqual(before,h.debug_snapshot())
|
| 47 |
+
def test_open_lid_during_running_decelerates(self):
|
| 48 |
+
h=configured();h.invoke('acquisition.start');h.step(.5);speed=h.speed
|
| 49 |
+
h.invoke('lid.set_angle',angle_rad=1.5);self.assertEqual(h.speed,speed);self.assertEqual(h.phase,'stopping')
|
| 50 |
+
h.step(.1);self.assertLess(h.speed,speed);h.step(2);self.assertEqual(h.phase,'cancelled')
|
| 51 |
+
def test_power_off_is_not_instant_stop(self):
|
| 52 |
+
h=configured();h.invoke('acquisition.start');h.step(.5);h.invoke('power.set',enabled=False)
|
| 53 |
+
self.assertGreater(h.speed,0);h.step(3);self.assertEqual(h.speed,0)
|
| 54 |
+
def test_sequence_completes_after_braking(self):
|
| 55 |
+
h=configured();h.invoke('acquisition.start');h.step(6)
|
| 56 |
+
self.assertAlmostEqual(h.elapsed_s,6);self.assertEqual(h.step_index,2);self.assertEqual(h.phase,'stopping')
|
| 57 |
+
h.step(4);self.assertEqual(h.phase,'succeeded');self.assertEqual(h.speed,0)
|
| 58 |
+
def test_material_conservation_and_cancel_residue(self):
|
| 59 |
+
h=configured();h.invoke('acquisition.start');h.step(1.8)
|
| 60 |
+
film=h.film.copy();self.assertGreater(h.waste[0],0);self.assertGreater(h.evaporated[0],0)
|
| 61 |
+
h.invoke('acquisition.stop');self.assertEqual(film,h.film)
|
| 62 |
+
h.step(4)
|
| 63 |
+
for value in balances(h):self.assertLess(abs(value),1e-16)
|
| 64 |
+
self.assertEqual(h.evaporated[1],0);self.assertGreater(h.film[1],0)
|
| 65 |
+
def test_no_clock_no_evaporation(self):
|
| 66 |
+
h=configured();before=h.film.copy()
|
| 67 |
+
for _ in range(10):h.invoke('product.read')
|
| 68 |
+
self.assertEqual(before,h.film)
|
| 69 |
+
def test_cancel_does_not_stop_natural_evaporation(self):
|
| 70 |
+
h=configured();h.invoke('acquisition.start');h.step(.1);h.invoke('acquisition.stop');h.step(1)
|
| 71 |
+
solvent=h.film[0];h.step(2);self.assertLess(h.film[0],solvent)
|
| 72 |
+
def test_dry_mass_finite(self):
|
| 73 |
+
h=configured(evap=.1);h.invoke('acquisition.start');h.step(100)
|
| 74 |
+
self.assertGreaterEqual(h.film[0],0);self.assertGreaterEqual(h.film[1],0)
|
| 75 |
+
for value in balances(h):self.assertLess(abs(value),1e-16)
|
| 76 |
+
def test_collect_and_no_repeated_transfer(self):
|
| 77 |
+
h=configured();h.invoke('acquisition.start');h.step(12)
|
| 78 |
+
h.invoke('lid.set_angle',angle_rad=1.5);h.step(1.1)
|
| 79 |
+
h.invoke('product.collect',recipient_id='output');before=h.debug_snapshot()
|
| 80 |
+
self.assertGreater(h.collected[1],0)
|
| 81 |
+
with self.assertRaises(rt.ActionRejected):h.invoke('product.collect',recipient_id='output')
|
| 82 |
+
self.assertEqual(before,h.debug_snapshot())
|
| 83 |
+
for value in balances(h):self.assertLess(abs(value),1e-16)
|
| 84 |
+
def test_two_instances_isolated(self):
|
| 85 |
+
a=configured('a');b=configured('b');before=b.debug_snapshot()
|
| 86 |
+
a.invoke('acquisition.start');a.step(3);self.assertEqual(before,b.debug_snapshot())
|
| 87 |
+
def test_agent_truth_filter(self):
|
| 88 |
+
h=configured();s=h.session()
|
| 89 |
+
self.assertNotIn('truth.ledger',s.read(instance_id=h.instance_id)['observations'])
|
| 90 |
+
self.assertNotIn('product.read',s.describe(instance_id=h.instance_id)['capabilities'])
|
| 91 |
+
result=s.invoke(instance_id=h.instance_id,capability_id='product.read',arguments={},request_id='truth')
|
| 92 |
+
self.assertEqual(result['error']['code'],'ACCESS_DENIED');self.assertNotIn('solvent',json.dumps(result))
|
| 93 |
+
with self.assertRaises(rt.ActionRejected):s.read(instance_id=h.instance_id,state_ids=['truth.ledger'])
|
| 94 |
+
def test_rejected_role_escalation(self):
|
| 95 |
+
h=configured();s=h.session()
|
| 96 |
+
with self.assertRaises(TypeError):s.read(instance_id=h.instance_id,visibility='evaluator')
|
| 97 |
+
with self.assertRaises(rt.ActionRejected):h.session('evaluator')
|
| 98 |
+
def test_idempotency_and_request_conflict(self):
|
| 99 |
+
h=configured();s=h.session();kw=dict(instance_id=h.instance_id,capability_id='acquisition.start',arguments={},request_id='start')
|
| 100 |
+
a=s.invoke(**kw);h.step(.3);before=h.debug_snapshot();b=s.invoke(**kw)
|
| 101 |
+
self.assertEqual(a,b);self.assertEqual(before,h.debug_snapshot())
|
| 102 |
+
result=s.invoke(instance_id=h.instance_id,capability_id='acquisition.stop',arguments={},request_id='start')
|
| 103 |
+
self.assertEqual(result['error']['code'],'REQUEST_CONFLICT')
|
| 104 |
+
def test_async_owner_and_cancel(self):
|
| 105 |
+
h=configured();s=h.session();h.register_principal('other');other=h.session('other')
|
| 106 |
+
r=s.invoke(instance_id=h.instance_id,capability_id='acquisition.start',arguments={},request_id='start');op=r['operation_id']
|
| 107 |
+
self.assertEqual(r['status'],'accepted');h.step(.5)
|
| 108 |
+
with self.assertRaises(rt.ActionRejected):other.poll(op)
|
| 109 |
+
before=h.debug_snapshot();s.poll(op);self.assertEqual(before,h.debug_snapshot())
|
| 110 |
+
s.cancel(op,'cancel');h.step(3);self.assertEqual(s.poll(op)['status'],'cancelled')
|
| 111 |
+
def test_write_routes_capability(self):
|
| 112 |
+
h=configured();s=h.session();s.write(instance_id=h.instance_id,state_id='power.enabled',value=False,request_id='off')
|
| 113 |
+
self.assertFalse(h.powered)
|
| 114 |
+
with self.assertRaises(rt.ActionRejected):s.write(instance_id=h.instance_id,state_id='motor.indicated_rad_s',value=200.,request_id='bad')
|
| 115 |
+
def test_reference_known_value_and_no_extrapolation(self):
|
| 116 |
+
h=configured();r=h.invoke('reference.lookup',substance_id='ethanol',temperature_k=298.15)
|
| 117 |
+
self.assertAlmostEqual(r['vapor_pressure_pa'],7869.08504803628,places=8)
|
| 118 |
+
with self.assertRaises(rt.ActionRejected):h.invoke('reference.lookup',substance_id='ethanol',temperature_k=1.)
|
| 119 |
+
self.assertGreaterEqual(len(h.templates),50)
|
| 120 |
+
def test_analytic_pure_solvent_drainage(self):
|
| 121 |
+
h=configured(evap=0);h.film[1]=0.;h.initial[1]=0.;h.waste[1]=0.
|
| 122 |
+
h0=h._product()['wet_thickness_m'];omega=120*rt.RPM;dt=.1
|
| 123 |
+
rho=h.sample['solvent_density_kg_m3'];mu=h.sample['viscosity_pa_s']
|
| 124 |
+
expected=h0/math.sqrt(1+4*rho*omega**2*h0**2*dt/(3*mu))
|
| 125 |
+
h._film_step(dt,omega)
|
| 126 |
+
self.assertAlmostEqual(h._product()['wet_thickness_m'],expected,places=14)
|
| 127 |
+
def test_step_partition_consistent(self):
|
| 128 |
+
a=configured();b=configured();a.invoke('acquisition.start');b.invoke('acquisition.start');a.step(3.)
|
| 129 |
+
for _ in range(300):b.step(.01)
|
| 130 |
+
self.assertAlmostEqual(a.speed,b.speed,places=9);self.assertAlmostEqual(a.film[0],b.film[0],places=12)
|
| 131 |
+
def test_invalid_clock(self):
|
| 132 |
+
h=configured();before=h.debug_snapshot()
|
| 133 |
+
for value in [0,-1,True,float('inf'),float('nan')]:
|
| 134 |
+
with self.assertRaises(rt.ActionRejected):h.step(value)
|
| 135 |
+
self.assertEqual(before,h.debug_snapshot())
|
| 136 |
+
def test_actual_output_schemas(self):
|
| 137 |
+
h=configured();results=[]
|
| 138 |
+
for c,args in [('power.set',{'enabled':True}),('power.toggle',{}),('method.configure',rt.METHOD_EXAMPLE),('reference.lookup',{'substance_id':'ethanol','temperature_k':298.15}),('coating.measure',{}),('product.read',{})]:
|
| 139 |
+
result=h.invoke(c,**args);errors=tool.validate_value(result,rt.CAPS[c][1],path='result');self.assertFalse(errors,(c,errors));results.append(c)
|
| 140 |
+
h.invoke('power.set',enabled=True)
|
| 141 |
+
for c in ['acquisition.start','acquisition.stop']:
|
| 142 |
+
result=h.invoke(c);errors=tool.validate_value(result,rt.CAPS[c][1],path='result');self.assertFalse(errors,(c,errors))
|
| 143 |
+
for k,v in h.read('evaluator').items():
|
| 144 |
+
errors=tool.validate_value(v,rt.SLOTS[k][0],path=k);self.assertFalse(errors,(k,errors))
|
| 145 |
+
|
| 146 |
+
if __name__=='__main__':unittest.main()
|