Add files using upload-large-folder tool
Browse files- CITATION.cff +37 -0
- LICENSE +25 -0
- LICENSE-ASSETS.md +20 -0
- NOTICE.md +299 -0
- README.md +424 -0
- assets/initial_state.json +29 -0
- assets/physics_annotations.json +0 -0
- pytest.ini +3 -0
- release_manifest.json +0 -0
- requirements.txt +5 -0
- scripts/balance_runtime.py +135 -0
- scripts/basic40_runtime.py +841 -0
- scripts/basic40_runtime_analytical.py +0 -0
- scripts/basic40_runtime_automation.py +0 -0
- scripts/basic40_runtime_measure.py +0 -0
- scripts/basic40_runtime_thermal.py +0 -0
- scripts/basic40_runtime_vacuum.py +0 -0
- scripts/gc_runtime.py +492 -0
- tests/test_asset_antonpaar_abbematadvanced.py +113 -0
- tests/test_asset_antonpaar_dma5002.py +109 -0
- tests/test_asset_antonpaar_monowave400.py +101 -0
- tests/test_asset_aqualab_4te.py +82 -0
- tests/test_asset_buchi_minispray.py +77 -0
- tests/test_asset_buchi_speedextractore.py +83 -0
- tests/test_asset_cem_libertyblue.py +93 -0
- tests/test_asset_cytiva_ktaoligosynt.py +97 -0
- tests/test_asset_elma_elmasonics60h.py +62 -0
- tests/test_asset_genevac_mivac2.py +92 -0
- tests/test_asset_gilson_cpc250.py +53 -0
- tests/test_asset_hach_tl2300epa.py +85 -0
- tests/test_asset_hepatochem_photoredoxbox.py +103 -0
- tests/test_asset_ika_electrasyn2.py +87 -0
- tests/test_asset_ika_ks4000.py +66 -0
- tests/test_asset_mt_hx204.py +160 -0
- tests/test_asset_mt_mp70.py +80 -0
- tests/test_asset_sartorius_vivaflow200.py +56 -0
- tests/test_asset_scp_digiprepms.py +97 -0
- tests/test_asset_sft_sft110.py +74 -0
- tests/test_asset_syrris_asiadiscovery.py +91 -0
- tests/test_asset_syrris_asiafllex.py +85 -0
- tests/test_asset_thalesnano_hcube.py +94 -0
- tests/test_asset_tousimis_autosamdri815.py +83 -0
- tests/test_balance_runtime.py +47 -0
- tests/test_basic40_analytical.py +0 -0
- tests/test_basic40_automation.py +0 -0
- tests/test_basic40_measure.py +0 -0
- tests/test_basic40_runtime.py +483 -0
- tests/test_basic40_thermal.py +0 -0
- tests/test_basic40_vacuum.py +0 -0
- tests/test_gc_runtime.py +213 -0
CITATION.cff
ADDED
|
@@ -0,0 +1,37 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
cff-version: 1.2.0
|
| 2 |
+
title: "ChemLab-Assets: Simulation-Ready Chemistry Laboratory Instruments with Executable Behaviour Contracts"
|
| 3 |
+
message: "If you use these assets, please cite the release."
|
| 4 |
+
type: dataset
|
| 5 |
+
version: "1.0.0"
|
| 6 |
+
date-released: "2026-10-14"
|
| 7 |
+
license: CC-BY-NC-4.0
|
| 8 |
+
repository: "https://huggingface.co/datasets/MBZUAI/ChemLab-Assets"
|
| 9 |
+
url: "https://huggingface.co/datasets/MBZUAI/ChemLab-Assets"
|
| 10 |
+
keywords:
|
| 11 |
+
- chemistry laboratory
|
| 12 |
+
- laboratory automation
|
| 13 |
+
- embodied AI
|
| 14 |
+
- robot simulation
|
| 15 |
+
- digital twin
|
| 16 |
+
- 3D assets
|
| 17 |
+
- URDF
|
| 18 |
+
- Isaac Lab
|
| 19 |
+
authors:
|
| 20 |
+
- family-names: "Song"
|
| 21 |
+
given-names: "Zirui"
|
| 22 |
+
affiliation: "Mohamed bin Zayed University of Artificial Intelligence"
|
| 23 |
+
- family-names: "Zhang"
|
| 24 |
+
given-names: "Jiadong"
|
| 25 |
+
affiliation: "Mohamed bin Zayed University of Artificial Intelligence"
|
| 26 |
+
- family-names: "Zhang"
|
| 27 |
+
given-names: "Jiahao"
|
| 28 |
+
affiliation: "Mohamed bin Zayed University of Artificial Intelligence"
|
| 29 |
+
- family-names: "Chang"
|
| 30 |
+
given-names: "Xiaojun"
|
| 31 |
+
affiliation: "Mohamed bin Zayed University of Artificial Intelligence"
|
| 32 |
+
- family-names: "Ma"
|
| 33 |
+
given-names: "Xiaosong"
|
| 34 |
+
affiliation: "Mohamed bin Zayed University of Artificial Intelligence"
|
| 35 |
+
- family-names: "Chen"
|
| 36 |
+
given-names: "Xiuying"
|
| 37 |
+
affiliation: "Mohamed bin Zayed University of Artificial Intelligence"
|
LICENSE
ADDED
|
@@ -0,0 +1,25 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
MIT License
|
| 2 |
+
|
| 3 |
+
Copyright (c) 2026 Zirui Song, Jiadong Zhang, Jiahao Zhang, Xiaojun Chang, Xiaosong Ma, Xiuying Chen
|
| 4 |
+
|
| 5 |
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
| 6 |
+
of this software and associated documentation files (the "Software"), to deal
|
| 7 |
+
in the Software without restriction, including without limitation the rights
|
| 8 |
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
| 9 |
+
copies of the Software, and to permit persons to whom the Software is
|
| 10 |
+
furnished to do so, subject to the following conditions:
|
| 11 |
+
|
| 12 |
+
The above copyright notice and this permission notice shall be included in all
|
| 13 |
+
copies or substantial portions of the Software.
|
| 14 |
+
|
| 15 |
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
| 16 |
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
| 17 |
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
| 18 |
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
| 19 |
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
| 20 |
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
| 21 |
+
SOFTWARE.
|
| 22 |
+
|
| 23 |
+
This licence covers the code in this repository: scripts/, tests/, examples/,
|
| 24 |
+
tools/, skills/chemistry-lab-assets/scripts/ and the website and explorer
|
| 25 |
+
sources. 3D models, asset contracts and data are covered by LICENSE-ASSETS.md.
|
LICENSE-ASSETS.md
ADDED
|
@@ -0,0 +1,20 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Licence for assets and data
|
| 2 |
+
|
| 3 |
+
Copyright (c) 2026 Zirui Song, Jiadong Zhang, Jiahao Zhang, Xiaojun Chang, Xiaosong Ma, Xiuying Chen.
|
| 4 |
+
|
| 5 |
+
The 3D models (GLB, URDF, OBJ/MTL, Blender files, textures), asset contracts
|
| 6 |
+
(`asset.contract.json`), geometry manifests, collision proxies, instrument models,
|
| 7 |
+
output templates, catalogs, renders and previews in ChemLab-Assets are licensed under the
|
| 8 |
+
**Creative Commons Attribution-NonCommercial 4.0 International licence (CC BY-NC 4.0)**.
|
| 9 |
+
|
| 10 |
+
Summary (the legal code governs): https://creativecommons.org/licenses/by-nc/4.0/
|
| 11 |
+
Legal code: https://creativecommons.org/licenses/by-nc/4.0/legalcode
|
| 12 |
+
|
| 13 |
+
You may share and adapt the material for non-commercial purposes, provided you give
|
| 14 |
+
appropriate credit (cite the release, see CITATION.cff), link to the licence and indicate
|
| 15 |
+
if changes were made.
|
| 16 |
+
|
| 17 |
+
Third-party data inside the release keeps its own terms. Some files are distributed under
|
| 18 |
+
CC BY-SA 4.0 or under their source's non-commercial terms, and some contain values derived
|
| 19 |
+
from sources that reserve their rights. NOTICE.md lists every affected file and its source.
|
| 20 |
+
Code is licensed separately under the MIT licence (LICENSE).
|
NOTICE.md
ADDED
|
@@ -0,0 +1,299 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# NOTICE
|
| 2 |
+
|
| 3 |
+
ChemLab-Assets, release 1.0 (October 2026). Copyright (c) 2026 Zirui Song, Jiadong Zhang, Jiahao Zhang, Xiaojun Chang, Xiaosong Ma, Xiuying Chen.
|
| 4 |
+
|
| 5 |
+
* Code: MIT (`LICENSE`). Assets and data: CC BY-NC 4.0 (`LICENSE-ASSETS.md`).
|
| 6 |
+
* Third-party data keep their own terms. This file lists the sources behind every data file that needs attribution.
|
| 7 |
+
* Raw third-party documents (PDF manuals, brochures, application notes, papers, web pages, spectra files and photos) are **not**
|
| 8 |
+
redistributed. The release keeps citations, selected values and derived templates.
|
| 9 |
+
|
| 10 |
+
## Trademarks
|
| 11 |
+
|
| 12 |
+
Instrument, product and company names (for example Agilent, Anton Paar, BINDER, BUCHI, Eppendorf, Esco, IKA,
|
| 13 |
+
METTLER TOLEDO, Shimadzu and Thermo Fisher Scientific) are trademarks of their owners. They appear only to
|
| 14 |
+
identify the instrument that an asset models. The 3D models, textures and screen designs were made by the authors
|
| 15 |
+
from published specifications and are not manufacturer CAD or artwork. This project is not affiliated with or
|
| 16 |
+
endorsed by any manufacturer.
|
| 17 |
+
|
| 18 |
+
## Files under other licences
|
| 19 |
+
|
| 20 |
+
The following files are distributed under the terms of their source instead of CC BY-NC 4.0:
|
| 21 |
+
|
| 22 |
+
**CC BY-SA 4.0** (FPbase spectra, Wikipedia rows):
|
| 23 |
+
|
| 24 |
+
* `assets/expansion_batch03/t4_measure/thermo_ibrightfl1500/fluorophore_library.json`
|
| 25 |
+
* `assets/expansion_batch04/t4_measure/bd_facsariaiii/fluorochrome_library.json`
|
| 26 |
+
* `assets/expansion_batch04/t4_measure/biorad_cfxopus/fluorophore_library.json`
|
| 27 |
+
* `assets/expansion_batch04/t3_analytical/nanosurf_naiostm/tunneling_library.json`
|
| 28 |
+
* `assets/expansion_batch04/t3_analytical/park_nx10/nanomechanical_library.json`
|
| 29 |
+
* `assets/expansion_batch04/t3_analytical/park_nx10/sample_library.json`
|
| 30 |
+
|
| 31 |
+
**Non-commercial terms of the source**, compatible with this release's non-commercial licence:
|
| 32 |
+
|
| 33 |
+
* `assets/expansion_batch04/t1_thermal/ametek_oxtran/oxygen_permeation_library.json`: polyVERSE data under the Georgia Tech Research Corporation non-commercial licence (`polyverse_LICENSE.txt` in the same folder).
|
| 34 |
+
* `assets/reactions/ika_electrasyn2_redox_library/templates.json`: Elhajj & Gozem (2024) reduction potentials, CC BY-NC 4.0.
|
| 35 |
+
* `assets/reactions/cytiva_ktaoligosynt_oligo_library/templates.json`: retention table from Nucleic Acids Research (2007) supplementary data, CC BY-NC 2.0 UK.
|
| 36 |
+
* `assets/expansion_batch03/t4_measure/microtrac_turbiscanlab/turbiscan_library.json`, `assets/expansion_batch04/t1_thermal/lakeshore_8604vsm/magnetic_library.json`, `assets/expansion_batch04/t1_thermal/ta_dma850/dma_library.json`: records from CC BY-NC (or CC BY-NC-ND) datasets, cited per record.
|
| 37 |
+
* `assets/reactions/spectral_library/nmr.json`: NMR peak lists from HMDB via PubChem; HMDB permits non-commercial use with citation (Wishart et al., Nucleic Acids Res. 2022).
|
| 38 |
+
|
| 39 |
+
**Licence texts of open-source data and code** used to build some libraries are in `LICENSES/`
|
| 40 |
+
(CoolProp, OPERA, chemicals, XrayDB, openpoly, teMatDb, Biopython, srsinst-rga, KiMoPack (GPL-3.0), COGNI (CC0)).
|
| 41 |
+
Libraries that already carry their source's licence file next to the data: `assets/reactions/cem_libertyblue_peptide_library/LICENSE`
|
| 42 |
+
(Peptimizer, MIT), `assets/reactions/jasco_j1500_cd_library/LICENSE` (PCDDB, MIT), `assets/reactions/laboao_cvdltf12p50_thermo_library/LICENSE.txt` (Cantera, BSD-3-Clause).
|
| 43 |
+
|
| 44 |
+
## Data derived from sources that reserve their rights
|
| 45 |
+
|
| 46 |
+
Some libraries contain values, spectra or tables derived from sources whose terms reserve the rights of the publisher,
|
| 47 |
+
for example NIST Standard Reference Data (Chemistry WebBook SRD 69, JANAF SRD 13, SRD 20, SRD 126, the NIST/EPA/NIH mass
|
| 48 |
+
spectral library, ISODB, ThermoML), OMLC / PhotochemCAD and RRUFF spectra, the CRC Handbook of Chemistry and Physics,
|
| 49 |
+
journal tables and manufacturer documents. They are included, with the citation of every record, so that the
|
| 50 |
+
instrument models can be used for non-commercial research. These terms are not changed by this release. If you hold
|
| 51 |
+
rights to any of this material and want it removed or changed, open an issue at https://huggingface.co/datasets/MBZUAI/ChemLab-Assets/discussions and we will act on it.
|
| 52 |
+
|
| 53 |
+
The files concerned are listed below with their sources.
|
| 54 |
+
|
| 55 |
+
* `assets/expansion_batch03/t1_thermal/ika_c6000/combustion_library.json`: https://webbook.nist.gov/chemistry/ (NIST Standard Reference Data (SRD 69 Chemistry WebBook): (c) U.S. Secretary of Commerce, all rights reserved under the Standard Reference Data Act (15 U.S.C. 290e); no open licence; individual cited values usable as …); http://large.stanford.edu/publications/coal/references/docs/hoc.pdf (paper by FAA (US federal) authors; numeric gross heats are facts - cite); https://tsapps.nist.gov/srmext/certificates/39j.pdf (US federal government work (17 U.S.C. 105) - public domain in the US; attribution requested)
|
| 56 |
+
* `assets/expansion_batch03/t1_thermal/ta_dsc2500/thermal_library.json`: https://webbook.nist.gov/chemistry/ (NIST Standard Reference Data (SRD 69 Chemistry WebBook): (c) U.S. Secretary of Commerce, all rights reserved under the Standard Reference Data Act (15 U.S.C. 290e); no open licence; individual cited values usable as …); https://nvlpubs.nist.gov/nistpubs/SpecialPublications/NIST.SP.260-242.pdf (US federal government work (17 U.S.C. 105) - public domain in the US; attribution requested); https://doi.org/10.17863/CAM.122922 (CC BY 4.0 - attribution)
|
| 57 |
+
* `assets/expansion_batch03/t1_thermal/ta_tga5500/tga_library.json`: https://github.com/ulfsri/fsri_materials_database (no LICENSE file in repo (checked main + pinned commit, materials.fsri.org has no terms); README only asks for citation -> all rights reserved by default (NIJ grant-funded, not US-gov work)); https://doi.org/10.1021/acssuschemeng.4c06407 (CC BY 4.0 article; scalar Td values); https://doi.org/10.1038/s41467-025-62449-8 (CC BY-NC-ND 4.0 article (Crossref); only 10 scalar Td5% facts); https://www.tainstruments.com/wp-content/uploads/2020-TGA-Online-Training-Part-1.pdf (manufacturer document, copyrighted; numeric facts/specs extractable with citation)
|
| 58 |
+
* `assets/expansion_batch03/t2_vacuum/tuttnauer_3870elvd/liquid_library.json`: https://webbook.nist.gov/chemistry/ (NIST Standard Reference Data (SRD 69 Chemistry WebBook): (c) U.S. Secretary of Commerce, all rights reserved under the Standard Reference Data Act (15 U.S.C. 290e); no open licence; individual cited values usable as …); https://pubchem.ncbi.nlm.nih.gov/ (US federal government work (17 U.S.C. 105) - public domain in the US; attribution requested)
|
| 59 |
+
* `assets/expansion_batch03/t3_analytical/frontier_egapy/pyrolyzate_library.json`: https://chemdata.nist.gov/dokuwiki/doku.php?id=chemdata:polymersearch (NIST SRD - all rights reserved; no redistribution grant); https://doi.org/10.1021/acs.est.5c18872 (CC BY 4.0 article describing the library)
|
| 60 |
+
* `assets/expansion_batch03/t3_analytical/markes_unityxr/retention_library.json`: https://www.ingenieria-analitica.com/attachment/pdf/print/td20-confirming-sorbent-tube-retention-volumes-and-checking-for-analyte-breakthrough-pdf-417 (manufacturer technical note, copyrighted; table is a vendor reference compilation (Markes states it has not validated the data))
|
| 61 |
+
* `assets/expansion_batch03/t4_measure/antonpaar_autosorb6100/adsorption_library.json`: https://adsorption.nist.gov/isodb/ ('(c)2016 copyright by the U.S. Department of Commerce ... All rights reserved'; GitHub mirror NIST-ISODB/isodb-library has no LICENSE; underlying figures from mostly paywalled articles); https://webbook.nist.gov/chemistry/fluid/ (NIST Standard Reference Data (SRD 69 Chemistry WebBook): (c) U.S. Secretary of Commerce, all rights reserved under the Standard Reference Data Act (15 U.S.C. 290e); no open licence; individual cited values usable as …)
|
| 62 |
+
* `assets/expansion_batch03/t4_measure/microtrac_turbiscanlab/turbiscan_library.json`: https://doi.org/10.25824/redu/5GDVXU (CC BY-NC 4.0 (Dataverse API) - non-commercial); https://doi.org/10.25949/33412420.v1 (CC BY 4.0 (figshare API))
|
| 63 |
+
* `assets/expansion_batch03/t4_measure/surface_dvsresolution/dvs_isotherm_library.json`: https://adsorption.nist.gov/isodb/ (ISODB '(c)2016 ... All rights reserved'; source article ACS paywalled); https://doi.org/10.1007/s10450-023-00383-1 (CC BY 4.0 article (Crossref))
|
| 64 |
+
* `assets/expansion_batch03/t4_measure/surface_dvsresolution/dvs_isotherm_reference_library.json`: https://adsorption.nist.gov/isodb/ (ISODB '(c)2016 copyright U.S. Department of Commerce ... All rights reserved')
|
| 65 |
+
* `assets/expansion_batch03/t5_automation/bronkhorst_cemw/vapour_library.json`: https://webbook.nist.gov/chemistry/ (NIST Standard Reference Data (SRD 69 Chemistry WebBook): (c) U.S. Secretary of Commerce, all rights reserved under the Standard Reference Data Act (15 U.S.C. 290e); no open licence; individual cited values usable as …)
|
| 66 |
+
* `assets/expansion_batch04/t1_thermal/ametek_oxtran/oxygen_permeation_library.json`: assets/expansion_batch04/t1_thermal/ametek_oxtran/oxygen_permeation_library.json: contains a modified subset (unit conversion and selection, 2026-09-24) of polyVERSE master_transport_2025_08_13.csv, Copyright 2022 Georgia Tech Research Corporation, licensed under the GTRC General Public Use License (see polyverse_LICENSE.txt); not for commercial use.
|
| 67 |
+
* `assets/expansion_batch04/t1_thermal/lakeshore_8604vsm/magnetic_library.json`: assets/expansion_batch04/t1_thermal/lakeshore_8604vsm/magnetic_library.json: hysteresis loops from KU Leuven RDR dataset doi:10.48804/1LDRAQ (Breynaert et al.), licensed CC BY-NC 4.0 (non-commercial); molar susceptibilities cited from the CRC Handbook of Chemistry and Physics ((c) CRC Press) and NIST SRM 772a certificate (public domain).
|
| 68 |
+
* `assets/expansion_batch04/t1_thermal/mt_rc1mxhfcal/reaction_mass_library.json`: assets/expansion_batch04/t1_thermal/mt_rc1mxhfcal/reaction_mass_library.json: liquid heat capacities and enthalpies of formation selected from the NIST Chemistry WebBook, NIST SRD 69 (Linstrom & Mallard, eds.), doi:10.18434/T4D303, (c) U.S. Secretary of Commerce; densities from PubChem/HSDB (public domain); reaction enthalpies derived by Chemistry-Sim.
|
| 69 |
+
* `assets/expansion_batch04/t1_thermal/netzsch_lfa467/lfa_library.json`: assets/expansion_batch04/t1_thermal/netzsch_lfa467/lfa_library.json: contains laser-flash transients from the PULsE sample datasets (A. Lunev, https://kotik-coder.github.io/; PULsE is Apache-2.0), values cited from USGS Open-File Report 88-690 (public domain), Parker et al. 1961 (doi:10.1063/1.1728417), the NIST Structural Ceramics Database (NIST SRD 30) and NETZSCH AN048.
|
| 70 |
+
* `assets/expansion_batch04/t1_thermal/ta_dma850/dma_library.json`: assets/expansion_batch04/t1_thermal/ta_dma850/dma_library.json: contains source data from doi:10.1038/s41467-025-68263-6 (CC BY-NC-ND 4.0), doi:10.1038/s41467-023-41084-1 (CC BY 4.0), DaRUS doi:10.18419/DARUS-4318 (CC BY 4.0), Mendeley doi:10.17632/k6pggf8zxw.1 (CC BY 4.0) and TA Instruments example data; scalar values cited from the listed papers and patent US8137807B2.
|
| 71 |
+
* `assets/expansion_batch04/t1_thermal/ta_tma450/tma_library.json`: assets/expansion_batch04/t1_thermal/ta_tma450/tma_library.json: contains TA Instruments example data ('TMA - Teflon Disk', software.tainstruments.com), NIST SRM 736 certificate values, NBS Circular 486 and NIST cryogenic data (public domain), values cited from the NIST Structural Ceramics Database (NIST SRD 30) and Adak et al. 2011 (arXiv:1104.3554).
|
| 72 |
+
* `assets/expansion_batch04/t2_vacuum/binder_kbf115/sorption_templates.json`: assets/expansion_batch04/t2_vacuum/binder_kbf115/sorption_templates.json: deliquescence humidities from Greenspan, J. Res. NBS 81A, 89 (1977) (public domain); water activities from the NIST/TRC ThermoML Archive (data distributed with permission of the journal publishers; original DOIs retained); isotherms from the NIST/ARPA-E ISODB ((c) U.S. Dept. of Commerce).
|
| 73 |
+
* `assets/expansion_batch04/t2_vacuum/esco_ac24s8/liquid_library.json`: assets/expansion_batch04/t2_vacuum/esco_ac24s8/liquid_library.json: vapour-pressure, vaporization-enthalpy and heat-capacity data from the NIST Chemistry WebBook, NIST SRD 69 (Linstrom & Mallard, eds.), doi:10.18434/T4D303, (c) U.S. Secretary of Commerce; molar masses from PubChem (public domain).
|
| 74 |
+
* `assets/expansion_batch04/t3_analytical/bruker_x4poseidon/xray_attenuation_library.json`: https://physics.nist.gov/PhysRefData/XrayMassCoef/ (NIST Standard Reference Data: 'Copyright protection on this compilation of data has been secured by the Secretary of the U.S. Department of Commerce ... 15 U.S.C. 290(e) ... All rights reserved'; no redistribution grant …); https://pubchem.ncbi.nlm.nih.gov (NCBI/NLM public domain (depositor terms may apply))
|
| 75 |
+
* `assets/expansion_batch04/t3_analytical/gas_flavourspec25gc/ims_library.json`: assets/expansion_batch04/t3_analytical/gas_flavourspec25gc/ims_library.json — If shipped: assets/expansion_batch04/t3_analytical/gas_flavourspec25gc/ims_library.json: GC-IMS retention indices and drift-time ratios cited from Ma et al., J. AOAC Int. 106, 445 (2023), doi:10.1093/jaoacint/qsac108; © the authors/AOAC International (Oxford University Press); used as factual data with citation.
|
| 76 |
+
* `assets/expansion_batch04/t3_analytical/jasco_cpl300/output_templates/library.json`: https://omlc.org/spectra/PhotochemCAD/ (OMLC: 'Copyright 2018 Scott Prahl & Steve Jacques', no licence; underlying PhotochemCAD data copyrighted, no licence); https://doi.org/10.5281/zenodo.10258367 (CC BY 4.0)
|
| 77 |
+
* `assets/expansion_batch04/t3_analytical/jasco_fvs6000/output_templates/library.json`: https://webbook.nist.gov/cgi/cbook.cgi?JCAMP=C67561&Index=2&Type=IR (NIST Standard Reference Data: 'Copyright protection on this compilation of data has been secured by the Secretary of the U.S. Department of Commerce ... 15 U.S.C. 290(e) ... All rights reserved'; no redistribution grant …); https://doi.org/10.18710/FBHIJK (CC0 1.0)
|
| 78 |
+
* `assets/expansion_batch04/t3_analytical/kratos_axissupra/xps_library.json`: https://srdata.nist.gov/xps/ (NIST Standard Reference Data: 'Copyright protection on this compilation of data has been secured by the Secretary of the U.S. Department of Commerce ... 15 U.S.C. 290(e) ... All rights reserved'; no redistribution grant …); powell2012 (journal articles; scalar reference values = facts); https://vuo.elettra.eu/services/elements/ (published tables; cross sections at 1486.6 eV = scalar facts); https://pypi.org/project/xraydb/ (XrayDB (xraypy/XrayDB): database files placed in the public domain under CC0 1.0 'to the extent possible'; python code MIT (Newville) — verified from XrayDB docs 'Copyright, Licensing, and Re-distribution'); nifs_data_23 (institute report; fit parameters = facts); https://www.crystallography.net/cod/ (Crystallography Open Database: public domain / CC0 (COD data are dedicated to the public domain))
|
| 79 |
+
* `assets/expansion_batch04/t3_analytical/stanford_rga100/output_templates/library.json`: https://webbook.nist.gov/chemistry/ (NIST Standard Reference Data: 'Copyright protection on this compilation of data has been secured by the Secretary of the U.S. Department of Commerce ... 15 U.S.C. 290(e) ... All rights reserved'; no redistribution grant …); https://pubchem.ncbi.nlm.nih.gov (NCBI/NLM public domain); https://raw.githubusercontent.com/thinkSRS/srsinst.rga/47cc514dd7b9bc3b6253b5f945736667c5f96ce8/srsinst/rga/gaslib.dat (MIT (licence copy is in raw/srs_driver_LICENSE, which is excluded)); https://physics.nist.gov/cuu/Constants/ (freely usable constants)
|
| 80 |
+
* `assets/expansion_batch04/t4_measure/aqualab_4te/output_templates.json`: assets/expansion_batch04/t4_measure/aqualab_4te/output_templates.json: (for a facts-only subset) Water-activity data distributed through the J. Chem. Eng. Data, J. Chem. Thermodyn. and Fluid Phase Equilib. ThermoML Archives (NIST TRC), https://trc.nist.gov/ThermoML/; original article DOI cited per point.
|
| 81 |
+
* `assets/expansion_batch04/t4_measure/bmg_clariostarplus/spectral_library.json`: https://omlc.org/spectra/PhotochemCAD/ (OMLC pages: 'Copyright 2018 Scott Prahl & Steve Jacques', no licence; PhotochemCAD data © original authors, no redistribution grant (all rights reserved by default))
|
| 82 |
+
* `assets/expansion_batch04/t4_measure/cytiva_biacoret200/solution_library.json`: https://chemistry.mdma.ch/hiveboard/rhodium/pdf/chemical-data/prop_aq.pdf (unofficial mirror used by fetch_sources.py) (CRC Press / Taylor & Francis, © all rights reserved; obtained from an unauthorised mirror; no licence); https://srd.nist.gov/jpcrdreprint/1.556029.pdf (JPCRD/NIST SRD © — 7 tabulated values of a published formula = facts); https://cdn.cytivalifesciences.com (manufacturer documents © Cytiva; specs/recipes = facts)
|
| 83 |
+
* `assets/expansion_batch04/t4_measure/knauer_k7400s/osmotic_library.json`: https://srd.nist.gov/jpcrdreprint/1.3253108.pdf (official); accessed via https://www.scribd.com/document/755542048/... mirror (JPCRD = NIST Standard Reference Data (NBS authors), © U.S. Secretary of Commerce / AIP, all rights reserved; Scribd copy is an unofficial mirror)
|
| 84 |
+
* `assets/expansion_batch04/t4_measure/malvern_microcalpeaq/buffer_library.json`: https://doi.org/10.1063/1.1416902 (NIST reprint https://srd.nist.gov/jpcrdreprint/1.1416902.pdf) (JPCRD = NIST Standard Reference Data (NIST authors), SRDA copyright, all rights reserved (15 U.S.C. 290e); no redistribution grant); iupac_water (fact)
|
| 85 |
+
* `assets/reactions/applied_sx20_kinetics_library/templates.json`: assets/reactions/applied_sx20_kinetics_library/templates.json — (for a partial/regenerated subset) PhotochemCAD 2.1a spectral data: H. Du et al., Photochem. Photobiol. 68, 141 (1998); J.M. Dixon et al., Photochem. Photobiol. 81, 212 (2005); as reworked by S. Prahl, Oregon Medical Laser Center, https://omlc.org/spectra/PhotochemCAD/.
|
| 86 |
+
* `assets/reactions/aqualab_4te_water_activity_library/templates.json`: assets/reactions/aqualab_4te_water_activity_library/templates.json — (for a facts-only subset) Water-activity data distributed through the J. Chem. Eng. Data, J. Chem. Thermodyn. and Fluid Phase Equilib. ThermoML Archives (NIST TRC), https://trc.nist.gov/ThermoML/; original article DOI cited per point.
|
| 87 |
+
* `assets/reactions/biotage_selekt_uv_library/templates.json`: assets/reactions/biotage_selekt_uv_library/templates.json — (for a partial/regenerated subset) PhotochemCAD 2.1a spectral data: H. Du et al., Photochem. Photobiol. 68, 141 (1998); J.M. Dixon et al., Photochem. Photobiol. 81, 212 (2005); as reworked by S. Prahl, OMLC, https://omlc.org/spectra/PhotochemCAD/.
|
| 88 |
+
* `assets/reactions/buchi_minispray_drying_library/templates.json`: assets/reactions/buchi_minispray_drying_library/templates.json: glass-transition, melting and glass-forming classification data transcribed from Table 1 of Eur. J. Pharm. Sci. 2013, doi:10.1016/j.ejps.2013.03.016, (c) Elsevier; used as factual data with citation.
|
| 89 |
+
* `assets/reactions/buchi_speedextractore_extraction_library/templates.json`: assets/reactions/buchi_speedextractore_extraction_library/templates.json: relative recovery values transcribed from Dionex Application Note 317 (Thermo Fisher Scientific, 2011), Table 1, (c) Thermo Fisher Scientific; used as factual data with citation.
|
| 90 |
+
* `assets/reactions/cytiva_ktaoligosynt_oligo_library/templates.json`: assets/reactions/cytiva_ktaoligosynt_oligo_library/templates.json — (for the shippable subset) Extinction coefficients cited from Anal. Biochem. (2014), doi:10.1016/j.ab.2014.08.001, Table 1, (c) Elsevier, used as factual data; retention data (if carved out) from Nucleic Acids Res. (2007), doi:10.1093/nar/gkm338, Table A.1, licensed CC BY-NC 2.0 UK.
|
| 91 |
+
* `assets/reactions/hepatochem_photoredoxbox_absorption_library/templates.json`: https://www.photochemcad.com/download (Copyrighted program + database, no open licence → all rights reserved by default); https://doi.org/10.1111/php.12860 (Wiley article — cited only)
|
| 92 |
+
* `assets/reactions/ika_electrasyn2_redox_library/templates.json`: https://doi.org/10.1021/acs.jctc.4c00602.s002 (CC BY-NC 4.0 — non-commercial only; incompatible with an OSI open-source licence)
|
| 93 |
+
* `assets/reactions/ika_t25_dispersion_library/templates.json`: https://webbook.nist.gov/chemistry/ (NIST Chemistry WebBook = NIST Standard Reference Database 69: 'Copyright ... secured by the Secretary of the U.S. Department of Commerce ... pursuant to 15 U.S.C. 290(e) ... All rights reserved'; no open licence. …)
|
| 94 |
+
* `assets/reactions/jasco_fp8350_fluorescence_library/templates.json`: https://omlc.org/spectra/PhotochemCAD/ (No licence on OMLC or PhotochemCAD → all rights reserved by default)
|
| 95 |
+
* `assets/reactions/jasco_nrs5500_raman_library/templates.json`: https://www.rruff.net/zipped_data_files/raman/excellent_unoriented.zip (Copyright notice, no licence found → all rights reserved by default (free to download, not licensed for redistribution))
|
| 96 |
+
* `assets/reactions/malvern_leneo_fusion_library/templates.json`: https://janaf.nist.gov/ (NIST Standard Reference Data (SRD 13): copyright U.S. Secretary of Commerce under 15 U.S.C. 290e, all rights reserved; table reproduction needs NIST permission); https://www.malvernpanalytical.com/en/learn/knowledge-center/application-notes/ (© Malvern Panalytical; compositions and protocol numbers = facts)
|
| 97 |
+
* `assets/reactions/quorum_q150tes_coating_library/templates.json`: assets/reactions/quorum_q150tes_coating_library/templates.json (if a reduced version ships): densities and Z-ratios cited from INFICON IC6 Operating Manual 074-505-P1K, Appendix A Table A-1 ((c)2018 INFICON, all rights reserved); used as factual data with citation; SI conversion by Chemistry-Sim.
|
| 98 |
+
* `assets/reactions/sft_sft110_solubility_library/templates.json`: assets/reactions/sft_sft110_solubility_library/templates.json (if shipped): scCO2 solubility data selected from the curated workbook of Makarov et al., J. Chem. Inf. Model. (2025), https://doi.org/10.1021/acs.jcim.5c00432, https://github.com/MDMISC/Solubility_scCO2 (commit 1c595c54); original measurement references retained per entry.
|
| 99 |
+
* `assets/reactions/sonics_vcx750_sonication_library/templates.json`: assets/reactions/sonics_vcx750_sonication_library/templates.json (stripped version): liquid heat capacities cited from NIST Chemistry WebBook, NIST Standard Reference Database 69 (P.J. Linstrom & W.G. Mallard, eds.), https://doi.org/10.18434/T4D303, (c) U.S. Secretary of Commerce on behalf of the USA, all rights reserved; primary references retained per entry; mass-specific conversion by Chemistry-Sim.
|
| 100 |
+
* `assets/reactions/spectral_library/ir_spectra.json`: https://webbook.nist.gov/chemistry/ (NIST Chemistry WebBook, NIST SRD 69: (c) U.S. Secretary of Commerce, all rights reserved under the Standard Reference Data Act (15 U.S.C. 290e); no redistribution grant. Individual values usable as cited facts; …)
|
| 101 |
+
* `assets/reactions/spectral_library/ms_ei.json`: https://webbook.nist.gov/chemistry/ (NIST Chemistry WebBook, NIST SRD 69: (c) U.S. Secretary of Commerce, all rights reserved under the Standard Reference Data Act (15 U.S.C. 290e); no redistribution grant. Individual values usable as cited facts; …)
|
| 102 |
+
* `assets/reactions/spectral_library/nmr.json`: https://hmdb.ca (Non-commercial only; commercial redistribution needs HMDB authors' permission. Some HMDB experimental spectra originate from third-party collections (e.g. JEOL 90 MHz CDCl3 lists).); https://nmrshiftdb.nmr.uni-koeln.de (Open content licence; only URLs are stored.)
|
| 103 |
+
* `assets/reactions/spectral_library/uv_vis.json`: https://webbook.nist.gov/chemistry/ (NIST Chemistry WebBook, NIST SRD 69: (c) U.S. Secretary of Commerce, all rights reserved under the Standard Reference Data Act (15 U.S.C. 290e); no redistribution grant. Individual values usable as cited facts; …); https://pubchem.ncbi.nlm.nih.gov (PubChem (NCBI/NLM): US public domain per NLM web policies; depositor records keep source terms.)
|
| 104 |
+
* `assets/reactions/thalesnano_hcube_hydrogenation_library/compatibility_records.json`: assets/reactions/thalesnano_hcube_hydrogenation_library/compatibility_records.json (if shipped): material compatibility ratings transcribed from ThalesNano 'H-Cube Advance/Pro Solvent Resistance' chart (2025), https://thalesnano.com/wp-content/uploads/2025/11/H-Cube-Advance-and-Pro-solvent-resistance.pdf, (c) ThalesNano.
|
| 105 |
+
* `assets/reactions/thinky_are310s_mixing_library/templates.json`: assets/reactions/thinky_are310s_mixing_library/templates.json (stripped version): liquid heat capacities cited from NIST Chemistry WebBook, NIST Standard Reference Database 69 (P.J. Linstrom & W.G. Mallard, eds.), https://doi.org/10.18434/T4D303, (c) U.S. Secretary of Commerce on behalf of the USA, all rights reserved; primary references retained per entry; mass-specific conversion by Chemistry-Sim.
|
| 106 |
+
* `assets/reactions/ultrafast_helios_ta_library/templates.json`: assets/reactions/ultrafast_helios_ta_library/templates.json (if any part ships): absorption spectra from PhotochemCAD 2.1a (H. Du et al., Photochem. Photobiol. 68 (1998) 141; J.M. Dixon et al., Photochem. Photobiol. 81 (2005) 212) via OMLC (S. Prahl, https://omlc.org/spectra/PhotochemCAD/); TA matrix from KiMoPack (Müller et al., J. Phys. Chem. A 2022, https://doi.org/10.1021/acs.jpca.2c00907; data GPL-3.0).
|
| 107 |
+
|
| 108 |
+
## Attribution for other data files
|
| 109 |
+
|
| 110 |
+
* `assets/GC7890B/component_semantics.json`: component semantics written by Chemistry-Sim with reference to Agilent 7890B GC documentation (G3430-96055, G3430-96052, 5991-1436EN); Agilent and 7890B are trademarks of Agilent Technologies.
|
| 111 |
+
* `assets/GC7890B/physics_annotations.json`: overall dimensions and mass cited from Agilent 7890B GC System Data Sheet 5991-1436EN (© Agilent Technologies); all other values are Chemistry-Sim estimates.
|
| 112 |
+
* `assets/expansion_batch03/t2_vacuum/tuttnauer_3870elvd/instrument_model.json`: specifications cited from Tuttnauer product page and 3870ELV manuals; (c) Tuttnauer; used as factual data with citation.
|
| 113 |
+
* `assets/expansion_batch03/t2_vacuum/tuttnauer_3870elvd/load_material_library.json`: material temperature limits cited from Thermo Scientific Nalgene autoclaving guide and Tuttnauer manuals; (c) respective owners; factual data with citation.
|
| 114 |
+
* `assets/expansion_batch03/t2_vacuum/tuttnauer_3870elvd/organism_library.json`: D121/z values cited from Wells-Bennik et al. (2019, PMID 30504002) and standard thermal-destruction references.
|
| 115 |
+
* `assets/expansion_batch03/t2_vacuum/tuttnauer_3870elvd/steam_tables.json`: saturation equation from IAPWS R7-97(2012) (IAPWS-IF97).
|
| 116 |
+
* `assets/expansion_batch03/t3_analytical/jena_contraa800/output_templates/library.json`: atomic line wavelengths from NIST Atomic Spectra Database (NIST SRD 78, Kramida et al.), (c) U.S. Secretary of Commerce, cited as facts; measured concentrations transcribed from Analytik Jena application notes AAS_0017 and AAS_0030, (c) Analytik Jena; factual data with citation.
|
| 117 |
+
* `assets/expansion_batch03/t3_analytical/shimadzu_tocl/output_templates/library.json`: USGS NWIS data via the Water Quality Portal (public domain); TOC results cited from Shimadzu application notes and Altus Science / Veolia Sievers certificates of analysis, (c) respective owners; factual data with citation.
|
| 118 |
+
* `assets/expansion_batch03/t3_analytical/shimadzu_tocl/output_templates/records/crm_*.json`: certified values cited from Altus Science and Veolia Sievers certificates of analysis, (c) respective owners.
|
| 119 |
+
* `assets/expansion_batch03/t3_analytical/shimadzu_tocl/output_templates/records/shimadzu_*.json`: TOC results cited from Shimadzu application notes (SCA-130-509, TOC-09, O41, PFOS, phenol, ethylene glycol, dichloroisocyanurate), (c) Shimadzu Corp.; factual data with citation.
|
| 120 |
+
* `assets/expansion_batch03/t3_analytical/shimadzu_tocl/output_templates/records/sievers_*.json`: values cited from Veolia Sievers certificates of analysis (2023-74405, 2025 99006).
|
| 121 |
+
* `assets/expansion_batch03/t3_analytical/shimadzu_tocl/output_templates/records/usgs_nwisma_*.json`: U.S. Geological Survey NWIS water-quality data (public domain), retrieved via the Water Quality Portal (waterqualitydata.us).
|
| 122 |
+
* `assets/expansion_batch03/t3_analytical/teledyne_analyteexcite/reference_library.json`: preferred values for NIST SRM 610/612 from GeoReM (georem.earth, Max Planck Institute for Chemistry) after Jochum et al., Geostand. Geoanal. Res. 35 (2011) 397-429, doi:10.1111/j.1751-908X.2011.00120.x.
|
| 123 |
+
* `assets/expansion_batch03/t3_analytical/teledyne_atomxxyz/application_library.json`: method-performance values cited from Teledyne Tekmar application note on EPA 524.2 with Atomx XYZ (A. Nutter, 2022), (c) Teledyne Tekmar; factual data with citation.
|
| 124 |
+
* `assets/expansion_batch03/t3_analytical/teledyne_atomxxyz/henry_library.json`: Henry's law constants from R. Sander, Atmos. Chem. Phys. 23, 10901-12440 (2023), doi:10.5194/acp-23-10901-2023 (CC BY 4.0); selection and unit handling by Chemistry-Sim.
|
| 125 |
+
* `assets/expansion_batch03/t3_analytical/thermo_dionexintegrion/ion_library.json`: diffusion coefficients from USGS PHREEQC database (Parkhurst & Appelo), public domain.
|
| 126 |
+
* `assets/expansion_batch03/t4_measure/antonpaar_abbematadvanced/output_templates.json`: refractive-index values from PubChem (NCBI/NLM) Hazardous Substances Data Bank records, https://pubchem.ncbi.nlm.nih.gov (U.S. public domain; acknowledgement to the U.S. National Library of Medicine); original handbook citations retained per record.
|
| 127 |
+
* `assets/expansion_batch03/t4_measure/antonpaar_dma5002/output_templates.json`: density values from PubChem (NCBI/NLM) HSDB records (U.S. public domain) and ILO-WHO International Chemical Safety Cards (c) ILO/WHO, reproduced as short factual excerpts with source indicated; https://pubchem.ncbi.nlm.nih.gov, https://chemicalsafety.ilo.org.
|
| 128 |
+
* `assets/expansion_batch03/t4_measure/antonpaar_litesizerdia/image_library.json`: particle data from Pereira-Diaz et al. (2022), Univ. Strathclyde, doi:10.15129/3005493b-a125-4a5d-8599-525ce952facf (CC BY 4.0) and GRAIN V1.0 by L. Li & M. Iskander, Mendeley Data, doi:10.17632/b935grbkxm.1 (CC BY 4.0); converted/resampled by Chemistry-Sim.
|
| 129 |
+
* `assets/expansion_batch03/t4_measure/antonpaar_litesizerdia/particle_images/`: images from GRAIN V1.0, L. Li & M. Iskander, Mendeley Data, doi:10.17632/b935grbkxm.1, CC BY 4.0.
|
| 130 |
+
* `assets/expansion_batch03/t4_measure/antonpaar_litesizerdia/solvent_reference.json`: water properties from NIST Chemistry WebBook fluid data (IAPWS-95).
|
| 131 |
+
* `assets/expansion_batch03/t4_measure/antonpaar_litesizerdls/dls_library.json`: LNP DLS statistics from Xue et al., Nat. Commun. 2024, doi:10.1038/s41467-024-45422-9 (CC BY 4.0); raw DLS correlation data from O. Burastero & M. Garcia-Alai, Zenodo, doi:10.5281/zenodo.7856850 (CC BY 4.0); units converted by Chemistry-Sim.
|
| 132 |
+
* `assets/expansion_batch03/t4_measure/antonpaar_litesizerdls/solvent_reference.json`: water properties from NIST Chemistry WebBook fluid data (IAPWS-95).
|
| 133 |
+
* `assets/expansion_batch03/t4_measure/antonpaar_poremaster60/porosimetry_library.json`: MICP data from Alaska Division of Geological & Geophysical Surveys RDF 2025-10 (Qureshi & PetroTech Associates, doi:10.14509/31522; units converted psia->Pa, ml/g->m3/kg by Chemistry-Sim), Meng et al. limestone dataset, Zenodo doi:10.5281/zenodo.17196680 (CC BY 4.0), and Dryad doi:10.5061/dryad.8t8v6 (CC0).
|
| 134 |
+
* `assets/expansion_batch03/t4_measure/antonpaar_poremaster60/psd_reference_library.json`: data from RepOD dataset doi:10.18150/DKKERN, CC BY 4.0.
|
| 135 |
+
* `assets/expansion_batch03/t4_measure/antonpaar_psa1190/particle_library.json`: particle-size data from Montes et al., Dryad doi:10.5061/dryad.dp8dr44 (CC0), Livsey et al., Zenodo doi:10.5281/zenodo.6788303 (CC BY 4.0), Pereira-Diaz et al., Univ. Strathclyde doi:10.15129/3005493b-a125-4a5d-8599-525ce952facf (CC BY 4.0); two d-values cited from Anton Paar application report E27IA019EN-B.
|
| 136 |
+
* `assets/expansion_batch03/t4_measure/antonpaar_psa1190/solvent_reference.json`: water properties from NIST Chemistry WebBook fluid data (IAPWS-95).
|
| 137 |
+
* `assets/expansion_batch03/t4_measure/antonpaar_surpass3/zeta_library.json`: zeta potentials from NovaMechanics, Zenodo doi:10.5281/zenodo.14864383 (CC BY 4.0); verification value cited from Anton Paar SurPASS 3 manual.
|
| 138 |
+
* `assets/expansion_batch03/t4_measure/antonpaar_ultrapyc5000/density_library.json`: element densities cited from NIST X-Ray Mass Attenuation Coefficients (NIST SRD 126, Hubbell & Seltzer) Table 1; two powder densities from J. Mater. Res. Technol. (2026), doi:10.1016/j.jmrt.2026.06.063.
|
| 139 |
+
* `assets/expansion_batch03/t4_measure/biolin_mediuml/langmuir_library.json`: Langmuir isotherms from Zaborowska et al., Univ. Warsaw RDR doi:10.58132/Y7RE4S (CC BY 4.0) and Jemmett et al., Univ. Birmingham eData doi:10.25500/edata.bham.00000718 (CC BY 4.0); units converted by Chemistry-Sim.
|
| 140 |
+
* `assets/expansion_batch03/t4_measure/biolin_sigma700/surface_library.json`: surface-tension coefficients from Jasper, J. Phys. Chem. Ref. Data 1, 841 (1972) as compiled in the 'chemicals' package (MIT, (c) Caleb Bell); curves from Chai et al., Mendeley Data doi:10.17632/m4cc5y33vw.1 and F. Amankeldi, doi:10.17632/p84zb3wfxp.1 (both CC BY 4.0).
|
| 141 |
+
* `assets/expansion_batch03/t4_measure/biolin_thetaflex/contact_library.json`: contact angles from Bhattarai & Rauniyar, Mendeley Data doi:10.17632/t768bkhfz7.1 (CC BY 4.0) and DaRUS doi:10.18419/DARUS-5038 (CC BY 4.0).
|
| 142 |
+
* `assets/expansion_batch03/t4_measure/biolin_thetaflex/output_templates.json`: contact angles from Bhattarai & Rauniyar, Mendeley Data doi:10.17632/t768bkhfz7.1 (CC BY 4.0) and DaRUS doi:10.18419/DARUS-5038 (CC BY 4.0).
|
| 143 |
+
* `assets/expansion_batch03/t4_measure/biorad_miniprotean/electrophoresis_model.json`: migration model fitted by Chemistry-Sim to band positions read from Bio-Rad Mini-PROTEAN TGX / Precision Plus migration charts, (c) Bio-Rad Laboratories.
|
| 144 |
+
* `assets/expansion_batch03/t4_measure/biorad_miniprotean/gel_buffer_library.json`: gel and buffer specifications cited from Bio-Rad Mini-PROTEAN precast gel (bulletin 1658100) and Tetra cell manuals, (c) Bio-Rad Laboratories; factual data with citation.
|
| 145 |
+
* `assets/expansion_batch03/t4_measure/biorad_miniprotean/protein_library.json`: protein data derived from UniProtKB (The UniProt Consortium, CC BY 4.0); marker nominal masses cited from Bio-Rad Precision Plus Protein standards documentation.
|
| 146 |
+
* `assets/expansion_batch03/t4_measure/freeman_ft4powder/powder_flow_library.json`: FT4 results from Pharmaceutics 18 (2026) 558, doi:10.3390/pharmaceutics18050558 (CC BY 4.0).
|
| 147 |
+
* `assets/expansion_batch03/t4_measure/freeman_ft4powder/powder_flow_reference_library.json`: data from Pereira-Diaz et al., Univ. Strathclyde doi:10.15129/3005493b-a125-4a5d-8599-525ce952facf (CC BY 4.0) and Sci. Rep. 10 (2020) doi:10.1038/s41598-020-77974-3 (CC BY 4.0).
|
| 148 |
+
* `assets/expansion_batch03/t4_measure/hach_tl2300epa/output_templates.json`: data providers Meadowlands Research & Restoration Institute and Delaware River Basin Commission (STORET/WQX), U.S. public data; StablCal nominal levels cited from the Hach TL2300 user manual, © Hach, used as factual data.
|
| 149 |
+
* `assets/expansion_batch03/t4_measure/micromeritics_autochemiii/chem_template_library.json`: TPR data from C. Parlett, Univ. Manchester doi:10.48420/23223803.v1 (CC BY 4.0); NH3-TPD data from Jankowska et al., RODBUK doi:10.57903/UJ/IY06G6 (CC0); summaries from Garidzirai et al., Catalysts 11 (2021) 490 (CC BY 4.0).
|
| 150 |
+
* `assets/expansion_batch03/t4_measure/micromeritics_autochemiii/raw_tpr_reference_library.json`: raw TPR tables from Jankowska et al., RODBUK doi:10.57903/UJ/IY06G6 (CC0 1.0).
|
| 151 |
+
* `assets/expansion_batch03/t4_measure/mt_mp70/output_templates.json`: melting points cited from PubChem (NCBI/NLM; contributing sources HSDB, ILO ICSC, HMDB, U.S. DOE PAC/TEEL, EU CLP, Haz-Map) and the NIST Chemistry WebBook (NIST SRD 69, https://doi.org/10.18434/T4D303, © U.S. Secretary of Commerce); original literature citations retained per record; used as factual data with citation.
|
| 152 |
+
* `assets/expansion_batch03/t4_measure/porometer_poroluxrevo/porometry_library.json`: porometry data from Lammertink & Bazyar, 4TU.ResearchData doi:10.4121/13953545.v1 (CC0) and digitized from ACS Omega 2025, doi:10.1021/acsomega.5c05746 (CC BY 4.0); PU values cited from PMC12227223.
|
| 153 |
+
* `assets/expansion_batch03/t4_measure/thermo_ibrightfl1500/fluorophore_library.json`: spectra derived from FPbase (T. Lambert, Nat. Methods 16, 277 (2019), fpbase.org), CC BY-SA 4.0 - this file is distributed under CC BY-SA 4.0 (ShareAlike), resampled/normalized by Chemistry-Sim.
|
| 154 |
+
* `assets/expansion_batch03/t5_automation/bronkhorst_cemw/gas_library.json`: Shomate heat-capacity coefficients cited from NIST Chemistry WebBook, NIST SRD 69 (doi:10.18434/T4D303) (after Chase, NIST-JANAF 1998).
|
| 155 |
+
* `assets/expansion_batch03/t5_automation/bronkhorst_cemw/instrument_model.json`: specifications cited from Bronkhorst CEM-W manual/brochure; (c) Bronkhorst High-Tech; factual data with citation.
|
| 156 |
+
* `assets/expansion_batch04/t1_thermal/antonpaar_hit300/indentation_library.json`: contains data from Lee, Marimuthu & Lee (2018), Mendeley Data, doi:10.17632/m46hwp78h4.1 (CC BY 4.0); MPEA nano-indentation database, doi:10.6084/m9.figshare.25244884 (CC BY 4.0); doi:10.3390/ma18071462 (CC BY 4.0); doi:10.5281/zenodo.15030675 / doi:10.1021/acs.macromol.4c03081 (CC BY 4.0) - values converted to SI units by Chemistry-Sim.
|
| 157 |
+
* `assets/expansion_batch04/t1_thermal/antonpaar_mcr503/rheology_library.json`: viscosity values from PubChem (NCBI/NLM) Hazardous Substances Data Bank records (public domain; original references such as the CRC Handbook retained per entry) and one ILO-WHO ICSC record (c) ILO; used as factual data with citation.
|
| 158 |
+
* `assets/expansion_batch04/t1_thermal/antonpaar_rst300/scratch_library.json`: contains data from Lee, Marimuthu & Lee (2018), Mendeley Data, doi:10.17632/m46hwp78h4.1 (CC BY 4.0); doi:10.3390/coatings14020159 and doi:10.3390/coatings16030279 (CC BY 4.0); JRC BCR-692 certificate values (European Commission, reuse with acknowledgement) - converted to SI units by Chemistry-Sim.
|
| 159 |
+
* `assets/expansion_batch04/t1_thermal/antonpaar_trb/tribology_library.json`: contains data from Grabovic (2024), Mendeley Data, doi:10.17632/27c6d6xthp.2 (CC BY 4.0) and doi:10.1021/acsomega.5c05944 SI (CC BY 4.0), plus friction/wear values cited from the NIST Structural Ceramics Database (NIST SRD 30, (c) U.S. Secretary of Commerce) - curves decimated and converted to SI by Chemistry-Sim.
|
| 160 |
+
* `assets/expansion_batch04/t1_thermal/hot_tps2500/thermal_transport_library.json`: values cited from USGS Open-File Report 88-690 (public domain), Parker et al., J. Appl. Phys. 32, 1679 (1961), doi:10.1063/1.1728417, the NIST Structural Ceramics Database (NIST SRD 30, (c) U.S. Secretary of Commerce) and the Hot Disk TPS 2500 S brochure; (c) respective owners; used as factual data with citation.
|
| 161 |
+
* `assets/expansion_batch04/t1_thermal/lakeshore_measurereadym91/hall_library.json`: contains digitized curves from the Starrydata2 database (NIMS; Katsura et al., Sci. Technol. Adv. Mater.: Methods 2025, doi:10.1080/27660400.2025.2506976; snapshot 2026-09-21), free for commercial and non-commercial use; original papers cited per record by DOI; units converted to SI by Chemistry-Sim.
|
| 162 |
+
* `assets/expansion_batch04/t1_thermal/linseis_lsr3/thermoelectric_library.json`: contains data from teMatDb272 (B. Ryu et al., 2025), doi:10.5281/zenodo.15518036, arXiv:2505.19150, (c) 2025 Byungki Ryu, licensed CC BY 4.0; original papers cited per record; converted to SI units by Chemistry-Sim.
|
| 163 |
+
* `assets/expansion_batch04/t1_thermal/netzsch_mmc315/arc_decomposition_library.json`: decomposition kinetics cited from Nouryon initiator/crosslinking-peroxide brochures, NETZSCH MMC 274/315 documentation, Arkema and American Chemistry Council references, and NIST Chemistry WebBook (SRD 69) toluene data; (c) respective owners; used as factual data with citation.
|
| 164 |
+
* `assets/expansion_batch04/t1_thermal/novocontrol_alphat/dielectric_library.json`: static permittivities from the 'chemicals' library (Caleb Bell, MIT License, https://github.com/CalebBell/chemicals), originally compiled from the CRC Handbook of Chemistry and Physics, 95th ed. (Haynes, Bruno & Lide, CRC Press, 2014); used as factual data with citation.
|
| 165 |
+
* `assets/expansion_batch04/t1_thermal/shimadzu_ags10knxd/mechanical_library.json`: contains data from the EPFL structural-steel tensile dataset, doi:10.5281/zenodo.6965147 (CC BY 4.0), and the OpenPoly benchmark (WangGroupFDU; doi:10.1007/s10118-025-3402-y; data CC BY 4.0, code MIT) - stresses converted to Pa by Chemistry-Sim.
|
| 166 |
+
* `assets/expansion_batch04/t1_thermal/signatone_quadpro2/sheet_resistance_library.json`: contains digitized resistivity curves from the Starrydata2 database (NIMS; doi:10.1080/27660400.2025.2506976; snapshot 2026-09-21), free for commercial and non-commercial use; original papers cited per record by DOI; converted to SI by Chemistry-Sim.
|
| 167 |
+
* `assets/expansion_batch04/t1_thermal/ta_tamiv/microcalorimetry_library.json`: dissolution enthalpies and log K from minteq.v4.dat distributed with USGS PHREEQC (U.S. Geological Survey, public domain).
|
| 168 |
+
* `assets/expansion_batch04/t1_thermal/zwick_hit5p/impact_library.json`: Charpy impact values cited from the BASF Ultradur(R) product range chart (2025) and B4520 data sheet (2026), (c) BASF SE; typical values used as factual data with citation.
|
| 169 |
+
* `assets/expansion_batch04/t1_thermal/zwick_mflow/melt_flow_library.json`: melt volume-flow rates and properties cited from the BASF Ultradur(R) product range chart (2025) and B4520 data sheet (2026), (c) BASF SE; typical values used as factual data with citation.
|
| 170 |
+
* `assets/expansion_batch04/t2_vacuum/binder_kbf115/instrument_model.json`: specifications cited from BINDER KBF 115 data sheet and KBF/KBF-S operating manuals, (c) BINDER GmbH; engineering parameters by Chemistry-Sim.
|
| 171 |
+
* `assets/expansion_batch04/t2_vacuum/eppendorf_cryocubef570n/instrument_model.json`: specifications cited from Eppendorf CryoCube F570 brochure, operating manual and product page, (c) Eppendorf SE; engineering parameters by Chemistry-Sim.
|
| 172 |
+
* `assets/expansion_batch04/t2_vacuum/esco_ac24s8/instrument_model.json`: specifications cited from Esco Airstream Plus AC2 brochure, product page and AC2 G3 manual, (c) Esco Lifesciences; engineering parameters by Chemistry-Sim.
|
| 173 |
+
* `assets/expansion_batch04/t2_vacuum/inert_puresolvmd/instrument_model.json`: specifications cited from Inert PureSolv MD product page and data sheet ((c) Inert Corporation) and procedures cited from University College Dublin and Texas A&M solvent-system SOPs; engineering parameters by Chemistry-Sim.
|
| 174 |
+
* `assets/expansion_batch04/t2_vacuum/inert_puresolvmd/solvent_templates.json`: Antoine parameters selected from the NIST Chemistry WebBook (NIST SRD 69, (c) U.S. Secretary of Commerce; original literature references retained) and densities/viscosities from PubChem/HSDB (public domain); used as factual data with citation.
|
| 175 |
+
* `assets/expansion_batch04/t2_vacuum/inficon_ul1000fab/gas_conversion_library.json`: molar masses from PubChem (public domain) and NIST Chemistry WebBook; conversion factors computed by Chemistry-Sim.
|
| 176 |
+
* `assets/expansion_batch04/t2_vacuum/inficon_ul1000fab/instrument_model.json`: specifications cited from INFICON UL1000 Fab brochure and operation manual, (c) INFICON; engineering parameters by Chemistry-Sim.
|
| 177 |
+
* `assets/expansion_batch04/t2_vacuum/inficon_ul1000fab/outgassing_library.json`: outgassing rates cited from P. Chiggiato, arXiv:1404.0960 and V. Baglin, arXiv:2601.11361 (CERN Accelerator School proceedings, CC BY 4.0); converted to SI by Chemistry-Sim.
|
| 178 |
+
* `assets/expansion_batch04/t2_vacuum/peak_precisionhydrogen/instrument_model.json`: specifications cited from Peak Scientific Precision Hydrogen data sheets, installation guide and user manual, (c) Peak Scientific Instruments; engineering parameters by Chemistry-Sim.
|
| 179 |
+
* `assets/expansion_batch04/t2_vacuum/vaisala_dmt152/gas_library.json`: molar masses from PubChem (public domain) and NIST Chemistry WebBook; gas-compatibility statements quoted from the Vaisala DMT152 data sheet and user guide, (c) Vaisala Oyj.
|
| 180 |
+
* `assets/expansion_batch04/t2_vacuum/vaisala_dmt152/humidity_formulation.json`: coefficients from B. Hardy, ITS-90 Formulations for Vapor Pressure, Frostpoint Temperature, Dewpoint Temperature and Enhancement Factors (-100 to +100 C), Proc. 3rd Int. Symp. on Humidity & Moisture, 1998; saturation table computed by Chemistry-Sim.
|
| 181 |
+
* `assets/expansion_batch04/t2_vacuum/vaisala_dmt152/instrument_model.json`: specifications cited from the Vaisala DRYCAP DMT152 data sheet and user guide M210865EN, (c) Vaisala Oyj; engineering parameters by Chemistry-Sim.
|
| 182 |
+
* `assets/expansion_batch04/t2_vacuum/vaisala_dmt152/tubing_library.json`: water-vapour transmission rates cited from CMC Klebetechnik 'Water vapor permeability of various plastic films' and the Vaisala DMT152 user guide; (c) respective owners; sorption parameters are Chemistry-Sim engineering assumptions.
|
| 183 |
+
* `assets/expansion_batch04/t3_analytical/agilent_1290infinity/sec_library.json`: nominal peak molecular weights and dispersities of 73 GPC/SEC standards cited from Agilent Technologies, 'GPC/SEC Standards' brochure 5990-7996E, https://www.agilent.com/cs/library/brochures/5990-7996E_GPC-standards.pdf; © Agilent Technologies; used as factual catalogue data with citation.
|
| 184 |
+
* `assets/expansion_batch04/t3_analytical/antonpaar_saxspace/saxs_library.json`: data free of copyright restrictions, original depositing authors credited per entry (source.code / source.publication); NIST SRM 3600 and RM 8011/8012/8013 certificate data (NIST, U.S. public domain); AgBh d-spacings from the pyFAI calibrant file (MIT, Blanton et al. 1999); material densities from XrayDB (CC0).
|
| 185 |
+
* `assets/expansion_batch04/t3_analytical/elementar_isoprimeprecision/delta_templates.json`: delta values of isotope reference materials cited from the IUPAC Commission on Isotopic Abundances and Atomic Weights (CIAAW) reference-material tables, https://www.ciaaw.org, and U.S. Geological Survey Reston Stable Isotope Laboratory reports (USGS, public domain); used as factual data with citation; scale ratios derived by Chemistry-Sim.
|
| 186 |
+
* `assets/expansion_batch04/t3_analytical/elementar_isoprimeprecision/instrument_model.json`: instrument specifications cited from Elementar Analysensysteme GmbH, isoprime precisION brochure (2020) and product page; © Elementar; used as factual specifications with citation; engineering parameters are Chemistry-Sim assumptions.
|
| 187 |
+
* `assets/expansion_batch04/t3_analytical/elementar_varioel/output_templates/library.json`: elemental-analysis results cited from EP 0 459 505 B1 (Kyowa Hakko Kogyo), the Elementar vario EL cube flyer (11/2019, © Elementar) and doi:10.1155/2010/867195 (CC BY 3.0); used as factual data with citation, converted to mass fractions by Chemistry-Sim.
|
| 188 |
+
* `assets/expansion_batch04/t3_analytical/evident_bx53p/birefringence_library.json`: refractive-index data from the refractiveindex.info database (M. N. Polyanskiy, Sci. Data 11, 94 (2024), doi:10.1038/s41597-023-02898-2), CC0 1.0; original measurement references retained per entry.
|
| 189 |
+
* `assets/expansion_batch04/t3_analytical/ja_alphase/optical_constants_library.json`: optical constants from the refractiveindex.info database (M. N. Polyanskiy, Sci. Data 11, 94 (2024)), CC0 1.0; original measurement references retained per entry; resampled by Chemistry-Sim.
|
| 190 |
+
* `assets/expansion_batch04/t3_analytical/jena_multix/output_templates/library.json`: measured AOX/EOX/TX values cited from Analytik Jena multi X 2500 application notes and manual (© Analytik Jena), EPA-600/D-84-169 (U.S. EPA, public domain) and PubChem (NCBI); used as factual data with citation.
|
| 191 |
+
* `assets/expansion_batch04/t3_analytical/jeol_jem1400flash/tem_library.json`: crystal structures from the Crystallography Open Database (Gražulis et al., public domain/CC0; COD IDs per entry); Waasmaier–Kirfel scattering factors via XrayDB (CC0); radiation-damage thresholds cited from Egerton et al., Micron 35, 399 (2004).
|
| 192 |
+
* `assets/expansion_batch04/t3_analytical/jeol_jsmit200/sem_eds_library.json`: X-ray level, line and attenuation data from XrayDB (M. Newville; database CC0 1.0; Elam, Ravel & Sieber, Radiat. Phys. Chem. 63, 121 (2002); Chantler, J. Phys. Chem. Ref. Data 29, 597 (2000)); Z/A, mean excitation energies and densities cited from J. H. Hubbell & S. M. Seltzer, NIST SRD 126 (© U.S. Secretary of Commerce), used as factual constants.
|
| 193 |
+
* `assets/expansion_batch04/t3_analytical/keyence_vkx3000/optical_constants_library.json`: optical constants from the refractiveindex.info database (M. N. Polyanskiy, Sci. Data 11, 94 (2024)), CC0 1.0; original measurement references retained per entry; resampled by Chemistry-Sim.
|
| 194 |
+
* `assets/expansion_batch04/t3_analytical/leco_onh836/output_templates/library.json`: O/N/H results cited from LECO Corporation / LECO Japan application notes (© LECO), BAM reference-material certificates (© BAM) and NIST SRM 1755 / NBS SP 260-26 (NIST, public domain); used as factual data with citation.
|
| 195 |
+
* `assets/expansion_batch04/t3_analytical/milestone_dma80/output_templates/library.json`: certified mercury mass fractions cited from NIST SRM certificates (public domain), European Commission JRC and NRC Canada CRM certificates, and Milestone application reports (© Milestone); used as factual data with citation.
|
| 196 |
+
* `assets/expansion_batch04/t3_analytical/nanosurf_naiostm/sample_library.json`: sample specifications quoted from Nanosurf AG, NaioSTM Operating Instructions 3.7 (© Nanosurf); other parameters are Chemistry-Sim assumptions.
|
| 197 |
+
* `assets/expansion_batch04/t3_analytical/nanosurf_naiostm/tunneling_library.json`: contains values and quoted table rows from Wikipedia articles 'Work function', 'Band gap', 'Lattice constant', 'Electrical resistivity and conductivity' and element infoboxes (Wikipedia contributors, CC BY-SA 4.0, https://en.wikipedia.org), modified (unit conversion, derived step heights) by Chemistry-Sim.
|
| 198 |
+
* `assets/expansion_batch04/t3_analytical/park_nx10/nanomechanical_library.json`: contains values from Wikipedia articles 'Young's modulus', 'Poisson's ratio', 'Surface energy', 'Elastic properties of the elements (data page)' and others (Wikipedia contributors, CC BY-SA 4.0); surface energies cited from Accu Dyne Test and moduli from The Engineering ToolBox (© respective owners, facts with citation); optical data from refractiveindex.info (CC0).
|
| 199 |
+
* `assets/expansion_batch04/t3_analytical/park_nx10/probe_library.json`: nominal probe specifications cited from BudgetSensors, NanoWorld, NanoAndMore (Olympus OMCL) and MikroMasch product documentation (© respective manufacturers); used as factual specifications with citation.
|
| 200 |
+
* `assets/expansion_batch04/t3_analytical/park_nx10/sample_library.json`: grating dimensions cited from Park Systems NX10 User's Manual v2.3.2 (© Park Systems); graphite interlayer spacing 0.335 nm (Delhaes, Graphite and Precursors); other parameters are Chemistry-Sim assumptions.
|
| 201 |
+
* `assets/expansion_batch04/t3_analytical/rigaku_xtalabsynergy/crystal_structure_library.json`: crystal structures from the Crystallography Open Database (Gražulis et al., Nucleic Acids Res. 40, D420 (2012)), public domain; COD IDs and original article DOIs retained per entry.
|
| 202 |
+
* `assets/expansion_batch04/t3_analytical/rigaku_xtalabsynergy/xray_scattering_library.json`: Waasmaier & Kirfel, Acta Cryst. A51, 416 (1995); Henke, Gullikson & Davis, At. Data Nucl. Data Tables 54, 181 (1993); NIST XCOM (Berger et al.) and Deslattes et al., Rev. Mod. Phys. 75, 35 (2003); used as factual constants.
|
| 203 |
+
* `assets/expansion_batch04/t3_analytical/shimadzu_edx7200/output_templates/library.json`: X-ray emission and binding energies cited from the X-Ray Data Booklet, Lawrence Berkeley National Laboratory (G. P. Williams; Bearden & Burr, Rev. Mod. Phys. 39, 125 (1967)); measured compositions cited from Shimadzu application notes (© Shimadzu Corporation); used as factual data with citation.
|
| 204 |
+
* `assets/expansion_batch04/t3_analytical/shimadzu_icpe9800/output_templates/library.json`: atomic line wavelengths cited from the NIST Atomic Spectra Database (Kramida, Ralchenko, Reader & NIST ASD Team, NIST SRD 78, © U.S. Secretary of Commerce) and ICP-OES results from Shimadzu application notes (© Shimadzu Corporation); used as factual data with citation.
|
| 205 |
+
* `assets/expansion_batch04/t3_analytical/shimadzu_icpms2030/output_templates/library.json`: isotopic masses and abundances cited from NIST Atomic Weights and Isotopic Compositions (Coursey et al., NIST SRD 144; IUPAC/AME values), NIST SRM 1643f (public domain) and Shimadzu application notes (© Shimadzu Corporation); used as factual data with citation.
|
| 206 |
+
* `assets/expansion_batch04/t3_analytical/thermo_orbitrapexploris/output_templates/library.json`: converted to SI units and isotope patterns derived by Chemistry-Sim.
|
| 207 |
+
* `assets/expansion_batch04/t4_measure/bd_facsariaiii/fluidics_model.json`: instrument settings cited from BD FACSAria User's Guide 333608 Rev. A (2003) Table 3-1 and BD FACSAria III Technical Specifications 23-11585-02 (2018), © Becton, Dickinson and Company; used as factual data with citation; other values are Chemistry-Sim assumptions.
|
| 208 |
+
* `assets/expansion_batch04/t4_measure/bd_facsariaiii/fluorochrome_library.json`: excitation/emission spectra and photophysical constants from FPbase (T. J. Lambert, Nat. Methods 16, 277-278 (2019), https://www.fpbase.org), licensed CC BY-SA 4.0, resampled and combined with derived detector responses by Chemistry-Sim; this file is distributed under CC BY-SA 4.0 (ShareAlike).
|
| 209 |
+
* `assets/expansion_batch04/t4_measure/bd_facsariaiii/optics_model.json`: laser, filter, ADC and sensitivity specifications cited from BD FACSAria III Technical Specifications 23-11585-02 (2018) and BD FACSAria User's Guide 333608 Rev. A (2003), © Becton, Dickinson and Company; used as factual data with citation.
|
| 210 |
+
* `assets/expansion_batch04/t4_measure/bd_facsariaiii/particle_library.json`: bead refractive indices from the refractiveindex.info database (M. N. Polyanskiy, Sci. Data 11, 94 (2024)), CC0 1.0; Mie tables computed by Chemistry-Sim.
|
| 211 |
+
* `assets/expansion_batch04/t4_measure/biorad_cfxopus/assay_library.json`: qPCR primer pairs from PrimerBank (X. Wang et al., Nucleic Acids Res. 40, D1144 (2012), https://pga.mgh.harvard.edu/primerbank) with amplicon sequences from NCBI RefSeq; multiplex example values from Bio-Rad Bulletin 7279 (© Bio-Rad Laboratories); used as factual data with citation; melting temperatures computed by Chemistry-Sim.
|
| 212 |
+
* `assets/expansion_batch04/t4_measure/biorad_cfxopus/fluorophore_library.json`: dye spectra and photophysical constants from FPbase (T. J. Lambert, Nat. Methods 16, 277-278 (2019), https://www.fpbase.org), licensed CC BY-SA 4.0, resampled with derived channel responses by Chemistry-Sim; this file is distributed under CC BY-SA 4.0 (ShareAlike).
|
| 213 |
+
* `assets/expansion_batch04/t4_measure/biorad_cfxopus/optics_model.json`: channel filter bands cited from Bio-Rad Bulletin 7279 (© Bio-Rad Laboratories); used as factual data with citation; calibration constants derived by Chemistry-Sim.
|
| 214 |
+
* `assets/expansion_batch04/t4_measure/biotek_405ts/plate_library.json`: microplate dimensions cited from the Arbor Assays plate-dimension sheet (Corning Costar catalogue numbers) and ANSI/SLAS 1-2004, 2-2004 and 4-2004; used as factual data with citation; Corning and Costar are trademarks of Corning Inc.
|
| 215 |
+
* `assets/expansion_batch04/t4_measure/biotek_405ts/wash_liquid_library.json`: properties computed from VDI Heat Atlas (2nd ed., Springer 2010) PPDS correlations as tabulated in the `chemicals` package (MIT, © Caleb Bell) and from the model of M. Laliberté, J. Chem. Eng. Data 54, 1725 (2009); values computed by Chemistry-Sim.
|
| 216 |
+
* `assets/expansion_batch04/t4_measure/bmg_clariostarplus/instrument_model.json`: specifications cited from the BMG LABTECH CLARIOstar Plus product page (© BMG LABTECH); used as factual data with citation; engineering parameters by Chemistry-Sim.
|
| 217 |
+
* `assets/expansion_batch04/t4_measure/bmg_clariostarplus/plate_library.json`: microplate footprint and well positions cited from ANSI/SLAS 1-2004 and 4-2004; used as factual data with citation.
|
| 218 |
+
* `assets/expansion_batch04/t4_measure/ch_chi440c/qcm_material_library.json`: molar masses from PubChem (NCBI/NLM, public domain) and the CIAAW standard atomic weight of copper.
|
| 219 |
+
* `assets/expansion_batch04/t4_measure/ch_chi920d/diffusion_library.json`: aqueous diffusion coefficients from the USGS PHREEQC database phreeqc.dat (D. L. Parkhurst & C. A. J. Appelo, U.S. Geological Survey), U.S. public domain.
|
| 220 |
+
* `assets/expansion_batch04/t4_measure/cytiva_biacoret200/chip_library.json`: sensor-chip properties cited from the Biacore Sensor Surface Handbook BR-1005-71 AB and Biacore T200 Operating Instructions 28-9768-83 AH (© Cytiva); used as factual data with citation; Biacore is a trademark of Cytiva.
|
| 221 |
+
* `assets/expansion_batch04/t4_measure/cytiva_biacoret200/instrument_model.json`: specifications cited from Cytiva Biacore T200 data file CY12747, Operating Instructions 28-9768-83 AH, Instrument Handbook 28-9768-63 AC and Software Handbook 28-9768-78 AA (© Cytiva); used as factual data with citation.
|
| 222 |
+
* `assets/expansion_batch04/t4_measure/cytiva_biacoret200/interaction_library.json`: kinetic constants from SKEMPI 2.0 (J. Jankauskaite et al., Bioinformatics 35, 462 (2019), https://life.bsc.es/pid/skempi2), licensed CC BY 4.0, with original references retained; partner sequences from the RCSB PDB (CC0); molecular weights, pI and diffusion coefficients derived by Chemistry-Sim.
|
| 223 |
+
* `assets/expansion_batch04/t4_measure/eppendorf_cellxpertc170i/cell_line_library.json`: cell-line metadata and doubling times from Cellosaurus (A. Bairoch, J. Biomol. Tech. 29, 25 (2018), https://www.cellosaurus.org, SIB Swiss Institute of Bioinformatics), licensed CC BY 4.0; median doubling times derived by Chemistry-Sim.
|
| 224 |
+
* `assets/expansion_batch04/t4_measure/eppendorf_cellxpertc170i/equilibrium_model.json`: Henry's-law constants from R. Sander, Atmos. Chem. Phys. 23, 10901 (2023), doi:10.5194/acp-23-10901-2023 (CC BY 4.0); constants cited from Harned & Davis (1943), Good et al. (1966) and Buck (1981).
|
| 225 |
+
* `assets/expansion_batch04/t4_measure/eppendorf_cellxpertc170i/media_library.json`: medium formulations cited from HiMedia Laboratories technical data sheets AL002-AL251 (© HiMedia Laboratories); used as factual data with citation; molar concentrations derived by Chemistry-Sim.
|
| 226 |
+
* `assets/expansion_batch04/t4_measure/eppendorf_cellxpertc170i/vessel_library.json`: culture-vessel areas, cell numbers and medium volumes cited from Thermo Fisher Scientific 'Useful Numbers for Cell Culture' (© Thermo Fisher Scientific); used as factual data with citation.
|
| 227 |
+
* `assets/expansion_batch04/t4_measure/malvern_microcalpeaq/binding_library.json`: values cited from Malvern Panalytical TN240816 and MAN0578 (© Malvern Panalytical) and from I. Wadso & R. N. Goldberg, Pure Appl. Chem. 73, 1625 (2001) (IUPAC); used as factual data with citation.
|
| 228 |
+
* `assets/expansion_batch04/t4_measure/malvern_microcalpeaq/dilution_library.json`: dilution-enthalpy coefficients cited from I. Wadso & R. N. Goldberg, Pure Appl. Chem. 73, 1625 (2001) (IUPAC Technical Report); used as factual data with citation.
|
| 229 |
+
* `assets/expansion_batch04/t4_measure/malvern_microcalpeaq/instrument_model.json`: specifications cited from Malvern Panalytical PEAQ-ITC brochure PN12309, user manual MAN0573, getting-started guide MAN0578 and TN240816/TN161202 (© Malvern Panalytical); used as factual data with citation.
|
| 230 |
+
* `assets/expansion_batch04/t4_measure/mt_hx204/output_templates.json`: normal boiling points cited from the NIST Chemistry WebBook, NIST Standard Reference Database 69 (P.J. Linstrom, W.G. Mallard, eds.), https://doi.org/10.18434/T4D303, © U.S. Secretary of Commerce; used as factual data with citation.
|
| 231 |
+
* `assets/expansion_batch04/t4_measure/pine_wavevortex10/diffusion_library.json`: aqueous diffusion coefficients from the USGS PHREEQC database phreeqc.dat (D. L. Parkhurst & C. A. J. Appelo, U.S. Geological Survey), U.S. public domain.
|
| 232 |
+
* `assets/expansion_batch04/t4_measure/seal_aa500/instrument_model.json`: specifications cited from SEAL Analytical AA500 product page and brochure and the Omniprocess distributor page (© respective owners) and from US EPA Method 366.0 (public domain); used as factual data with citation.
|
| 233 |
+
* `assets/expansion_batch04/t4_measure/seal_aa500/method_library.json`: method numbers and ranges cited from the SEAL Analytical AA500 product page (© SEAL Analytical) and colour chemistry from US EPA Methods 353.2/350.1/365.1/366.0 (public domain); used as factual data with citation.
|
| 234 |
+
* `assets/expansion_batch04/t4_measure/seal_aa500/substance_library.json`: identities from PubChem (NCBI/NLM) and recipes from US EPA Methods 353.2/350.1/365.1/366.0, both public domain.
|
| 235 |
+
* `assets/expansion_batch04/t4_measure/wtw_oxitopi/instrument_model.json`: specifications cited from the WTW OxiTop manual ba77059e02, WTW BOD primer and WTW catalogue 2019 (© Xylem Analytics) and USGS Technical Memorandum 2011.03 (public domain); used as factual data with citation.
|
| 236 |
+
* `assets/expansion_batch04/t4_measure/wtw_oxitopi/sample_library.json`: standard-solution and reagent recipes cited from the WTW BOD primer and OxiTop manual ba77059e02 (© Xylem Analytics); used as factual data with citation.
|
| 237 |
+
* `assets/expansion_batch04/t4_measure/wtw_oxitopi/substance_library.json`: biodegradation data points and identities from PubChem/HSDB (U.S. National Library of Medicine, public domain), original references retained; ThOD and kinetics derived by Chemistry-Sim.
|
| 238 |
+
* `assets/expansion_batch05/t2_vacuum/esco_efa5uduvw/instrument_model.json`: specifications cited from Esco Frontier Acela catalogue 9010376 vI and Sentinel XL data sheet 9010040 vC (© Esco Micro Pte Ltd); used as factual data with citation.
|
| 239 |
+
* `assets/expansion_batch05/t2_vacuum/esco_efa5uduvw/vapour_templates.json`: vapour-pressure and boiling-point values from the NIST Chemistry WebBook, NIST SRD 69 (P. J. Linstrom & W. G. Mallard, eds., doi:10.18434/T4D303; © U.S. Secretary of Commerce), physical properties and NIOSH exposure limits via PubChem (NCBI/NLM; NIOSH, public domain); used as factual data with citation.
|
| 240 |
+
* `assets/expansion_batch05/t4_measure/binder_fd056/instrument_model.json`: specifications cited from the BINDER FD 56 data sheet (2022) and operating manual E3.1 (2017) (© BINDER GmbH); used as factual data with citation.
|
| 241 |
+
* `assets/expansion_batch05/t4_measure/binder_fd056/load_templates.json`: material properties cited from SCHOTT DURAN, CoorsTek and other vendor data sheets (© respective owners), thermochemical values from the NIST Chemistry WebBook, NIST SRD 69 (doi:10.18434/T4D303; © U.S. Secretary of Commerce) and properties from PubChem (NCBI/NLM); used as factual data with citation.
|
| 242 |
+
* `assets/expansion_batch05/t4_measure/ika_plate_rctdigital/instrument_model.json`: specifications cited from the IKA Plate (RCT digital) data sheet and operating instructions 20014388a (© IKA-Werke GmbH & Co. KG); used as factual data with citation.
|
| 243 |
+
* `assets/expansion_batch05/t4_measure/ika_plate_rctdigital/liquid_templates.json`: thermochemical values from the NIST Chemistry WebBook, NIST SRD 69 (doi:10.18434/T4D303; © U.S. Secretary of Commerce) and physical properties from PubChem/HSDB (NCBI/NLM, public domain); used as factual data with citation.
|
| 244 |
+
* `assets/expansion_batch05/t5_automation/newera_ne1000/instrument_model.json`: specifications cited from the New Era NE-1000 user manual (Publication 1200-01) and dimension drawing Rev A (© New Era Pump Systems Inc.); used as factual data with citation.
|
| 245 |
+
* `assets/expansion_batch05/t5_automation/newera_ne1000/syringe_templates.json`: syringe inside diameters and rate limits cited from the New Era NE-1000 user manual section 12.7 (© New Era Pump Systems Inc.), liquid properties from the NIST Chemistry WebBook (NIST SRD 69, doi:10.18434/T4D303) and PubChem; used as factual data with citation.
|
| 246 |
+
* `assets/physics_annotations.json`: overall specifications cited from OHAUS Pioneer PX224/E and Scout SPX2201 product documentation (© OHAUS Corporation); geometry and physics are Chemistry-Sim estimates.
|
| 247 |
+
* `assets/reactions/antonpaar_abbematadvanced_refractive_library/templates.json`: refractive-index values from PubChem (NCBI/NLM) Hazardous Substances Data Bank records, https://pubchem.ncbi.nlm.nih.gov (U.S. public domain; acknowledgement to the U.S. National Library of Medicine); original handbook citations retained per record.
|
| 248 |
+
* `assets/reactions/antonpaar_dma5002_density_library/templates.json`: density values from PubChem (NCBI/NLM) HSDB records (U.S. public domain) and ILO-WHO International Chemical Safety Cards (c) ILO/WHO, reproduced as short factual excerpts with source indicated; https://pubchem.ncbi.nlm.nih.gov, https://chemicalsafety.ilo.org.
|
| 249 |
+
* `assets/reactions/antonpaar_monowave400_thermophysical_library/templates.json`: Antoine vapour-pressure coefficients from the NIST Chemistry WebBook, NIST Standard Reference Database 69 (P.J. Linstrom and W.G. Mallard, eds.), https://doi.org/10.18434/T4D303, (c) U.S. Secretary of Commerce on behalf of the United States (Standard Reference Data Act); original literature reference retained per fit; reference points computed by Chemistry-Sim.
|
| 250 |
+
* `assets/reactions/arradiance_gemstarxt_ald_library/templates.json`: contains 109 rows from 'ALD process parameter database v2.1' (S. Kim, Y. Kim, H. Park), https://doi.org/10.5281/zenodo.22653094, licensed CC BY 4.0 (rows selected, unit-annotated by Chemistry-Sim); plus 3 growth-per-cycle values cited from Arradiance-hosted publications (Li et al. 2016; Bent group 2020; doi:10.1021/acsaem.2c00870), (c) respective owners, used as factual data.
|
| 251 |
+
* `assets/reactions/bruker_magnettechesr5000_epr_library/templates.json`: hyperfine coupling constants from the NIEHS Spin Trap Database (U.S. National Institute of Environmental Health Sciences), https://www.niehs.nih.gov (U.S. Government work); original literature reference retained per record.
|
| 252 |
+
* `assets/reactions/bruker_minispecmq20_relaxometry_library/templates.json`: 20 MHz relaxivity values cited from US patents US5650133A, US9290535B2, US20200123155A1 and PMC articles PMC3532952, PMC4095929, PMC8069257, PMC11510030, PMC6767212, PMC5962812, PMC8769378, PMC8456821, PMC8558862, PMC10207321; (c) respective owners / article licences; used as factual data with citation.
|
| 253 |
+
* `assets/reactions/buchi_encapsulatorb_bead_library/templates.json`: molecular weights from PubChem (NCBI/NLM, public domain); operating conditions cited from BUCHI Encapsulator B-390 Operation Manual 11593477, Table 6-4, (c) BUCHI Labortechnik AG, used as factual data with citation.
|
| 254 |
+
* `assets/reactions/buchi_hydrolexh_hydrolysis_library/templates.json`: fat contents from USDA FoodData Central Foundation Foods (U.S. Department of Agriculture, public domain/CC0), https://fdc.nal.usda.gov; certified matrix values and method endpoints cited from BUCHI Application Note 350/2019 and Short Notes 348/2019, 354/2019, 356/2019, (c) BUCHI Labortechnik AG, used as factual data with citation.
|
| 255 |
+
* `assets/reactions/buchi_speedextractore_extraction_library/solvents.json`: fluid parameters derived from CoolProp 7.2.0 (I.H. Bell et al., Ind. Eng. Chem. Res. 53, 2498 (2014)), https://github.com/CoolProp/CoolProp, MIT License, Copyright (c) 2012-2018 Ian H. Bell and other CoolProp developers; reference points computed by Chemistry-Sim.
|
| 256 |
+
* `assets/reactions/cem_libertyblue_peptide_library/templates.json`: contains rows derived from the Peptimizer AFPS dataset, https://github.com/learningmatter-mit/peptimizer, MIT License, Copyright (c) 2020 Learning Matter @ MIT; S. Mohapatra et al., ACS Cent. Sci. 6, 2277 (2020), doi:10.1021/acscentsci.0c00979; rows selected and re-ordered by Chemistry-Sim.
|
| 257 |
+
* `assets/reactions/cytiva_ktaoligosynt_oligo_library/synthesis_reference.json`: synthesis figures cited from Cytiva document CY43669-17Apr24-PO, (c) Cytiva, used as factual data with citation.
|
| 258 |
+
* `assets/reactions/cytiva_nanoassemblrignite_lnp_library/structure_index.json`: structures derived from the LNP Atlas dataset (S. Song, J. Baek, S. Seo), Sci. Data (2025), doi:10.1038/s41597-025-06456-w, dataset doi:10.5281/zenodo.17243732, licensed CC BY 4.0; canonicalised by Chemistry-Sim (RDKit).
|
| 259 |
+
* `assets/reactions/cytiva_nanoassemblrignite_lnp_library/templates.json`: contains data derived from the LNP Atlas dataset (S. Song, J. Baek, S. Seo), Sci. Data (2025), doi:10.1038/s41597-025-06456-w, dataset doi:10.5281/zenodo.17243732, licensed CC BY 4.0 - values converted to SI and filtered by Chemistry-Sim; original publication DOI retained per record.
|
| 260 |
+
* `assets/reactions/edinburgh_fls1000tcspc_lifetime_library/templates.json`: contains data derived from S. Polcownuk and I. Davis (2024), https://doi.org/10.5281/zenodo.11083940, licensed CC BY 4.0 - converted to SI units and filtered by Chemistry-Sim; 11 Alexa Fluor lifetimes cross-checked against the Thermo Fisher Molecular Probes Handbook (cited as fact).
|
| 261 |
+
* `assets/reactions/fujifilm_dmp2850_ink_library/templates.json`: Antoine vapour-pressure coefficients from the NIST Chemistry WebBook, NIST Standard Reference Database 69 (P.J. Linstrom and W.G. Mallard, eds.), https://doi.org/10.18434/T4D303, (c) U.S. Secretary of Commerce (Standard Reference Data Act); original literature reference retained per fit.
|
| 262 |
+
* `assets/reactions/genevac_mivac2_evaporation_library/templates.json`: Antoine vapour-pressure coefficients from the NIST Chemistry WebBook, NIST Standard Reference Database 69 (P.J. Linstrom and W.G. Mallard, eds.), https://doi.org/10.18434/T4D303, (c) U.S. Secretary of Commerce (Standard Reference Data Act); original literature reference retained per fit.
|
| 263 |
+
* `assets/reactions/gilson_cpc250_partition_library/templates.json`: experimental logP values from the OPERA data set (K. Mansouri et al., J. Cheminform. 10, 10 (2018), doi:10.1186/s13321-018-0263-1), https://github.com/kmansouri/OPERA, MIT License, Copyright (c) 2016 kmansouri; original literature reference retained per record.
|
| 264 |
+
* `assets/reactions/glatt_miniglatt_granulation_library/templates.json`: values converted to SI and normalised by Chemistry-Sim.
|
| 265 |
+
* `assets/reactions/hach_tl2300epa_turbidity_library/templates.json`: data providers Meadowlands Research & Restoration Institute and Delaware River Basin Commission (STORET/WQX), U.S. public data; StablCal nominal levels cited from the Hach TL2300 user manual, © Hach, used as factual data.
|
| 266 |
+
* `assets/reactions/jasco_j1500_cd_library/templates.json`: units converted (L mol⁻¹ cm⁻¹ → m² mol⁻¹) and wavelength order reversed by Chemistry-Sim.
|
| 267 |
+
* `assets/reactions/jasco_p4200_rotation_library/templates.json`: specific optical rotations cited from PubChem (NCBI/NLM) Hazardous Substances Data Bank annotations (U.S. public domain), which quote The Merck Index, the CRC Handbook of Chemistry and Physics and IARC Monographs; per-record references retained; converted to SI by Chemistry-Sim; used as factual data with citation.
|
| 268 |
+
* `assets/reactions/laboao_cvdltf12p50_thermo_library/templates.json`: Copyright (c) 2001-2009 California Institute of Technology, (c) 2009 Sandia Corporation, (c) 2011-2024 Cantera Developers, BSD-3-Clause (see LICENSE.txt in the same folder); graphene growth activation enthalpies cited from Wang et al., Angew. Chem. Int. Ed. (2024), doi:10.1002/anie.202412131.
|
| 269 |
+
* `assets/reactions/linari_rtadvanced_fiber_library/templates.json`: converted to SI and material labels normalised by Chemistry-Sim.
|
| 270 |
+
* `assets/reactions/metrohm_909uv_digestion_library/templates.json`: aqueous OH-radical rate constants transcribed from Farhataziz and A.B. Ross, NSRDS-NBS 59 (U.S. National Bureau of Standards, 1977), https://nvlpubs.nist.gov/nistpubs/Legacy/NSRDS/nbsnsrds59.pdf; original literature references retained; converted to SI by Chemistry-Sim.
|
| 271 |
+
* `assets/reactions/mt_hx204_moisture_library/templates.json`: normal boiling points cited from the NIST Chemistry WebBook, NIST Standard Reference Database 69 (P.J. Linstrom, W.G. Mallard, eds.), https://doi.org/10.18434/T4D303, © U.S. Secretary of Commerce; used as factual data with citation.
|
| 272 |
+
* `assets/reactions/mt_mp70_thermal_library/templates.json`: melting points cited from PubChem (NCBI/NLM; contributing sources HSDB, ILO ICSC, HMDB, U.S. DOE PAC/TEEL, EU CLP, Haz-Map) and the NIST Chemistry WebBook (NIST SRD 69, https://doi.org/10.18434/T4D303, © U.S. Secretary of Commerce); original literature citations retained per record; used as factual data with citation.
|
| 273 |
+
* `assets/reactions/ossila_dipcoater_film_library/templates.json`: Antoine vapour-pressure parameters and melting points cited from the NIST Chemistry WebBook, NIST Standard Reference Database 69 (P.J. Linstrom, W.G. Mallard, eds.), https://doi.org/10.18434/T4D303, © U.S. Secretary of Commerce; original references (e.g. Ambrose & Sprake 1970) retained per fit; used as factual data with citation.
|
| 274 |
+
* `assets/reactions/ossila_doctorblade_film_library/templates.json`: Antoine vapour-pressure parameters and melting points cited from the NIST Chemistry WebBook, NIST Standard Reference Database 69 (P.J. Linstrom, W.G. Mallard, eds.), https://doi.org/10.18434/T4D303, © U.S. Secretary of Commerce; original references (e.g. Ambrose & Sprake 1970) retained per fit; used as factual data with citation.
|
| 275 |
+
* `assets/reactions/ossila_slotdie_film_library/templates.json`: Antoine vapour-pressure parameters and melting points cited from the NIST Chemistry WebBook, NIST Standard Reference Database 69 (P.J. Linstrom, W.G. Mallard, eds.), https://doi.org/10.18434/T4D303, © U.S. Secretary of Commerce; original references (e.g. Ambrose & Sprake 1970) retained per fit; used as factual data with citation.
|
| 276 |
+
* `assets/reactions/ossila_spincoater_film_library/templates.json`: Antoine vapour-pressure parameters and melting points cited from the NIST Chemistry WebBook, NIST Standard Reference Database 69 (P.J. Linstrom, W.G. Mallard, eds.), https://doi.org/10.18434/T4D303, © U.S. Secretary of Commerce; original references (e.g. Ambrose & Sprake 1970) retained per fit; used as factual data with citation.
|
| 277 |
+
* `assets/reactions/pccell_ed64002_ion_library/templates.json`: limiting molar conductivities computed by Chemistry-Sim (Nernst–Einstein) from tracer diffusion coefficients in the PHREEQC database phreeqc.dat (Parkhurst D.L., Appelo C.A.J., U.S. Geological Survey Techniques and Methods 6-A43, 2013; https://github.com/phreeqc-dev/phreeqc3).
|
| 278 |
+
* `assets/reactions/pilodist_pilodist104_vle_library/templates.json`: Antoine vapour-pressure coefficients cited from NIST Chemistry WebBook, NIST Standard Reference Database 69 (P.J. Linstrom & W.G. Mallard, eds.), https://doi.org/10.18434/T4D303, (c) U.S. Secretary of Commerce on behalf of the USA, all rights reserved; per-fit primary literature references retained; reference pressures computed by Chemistry-Sim.
|
| 279 |
+
* `assets/reactions/retsch_as200_particle_library/templates.json`: molar volumes and phase records from ThermoChimie v12a (Andra-NWS-Ondraf; Giffaut et al., Appl. Geochem. 49 (2014) 225-236) as distributed in USGS PHREEQC sit.dat (https://github.com/phreeqc-dev/phreeqc3); certified particle-size distributions from NIST SRM 1003c and SRM 1017b certificates of analysis (NIST, U.S. Government work); densities derived by Chemistry-Sim.
|
| 280 |
+
* `assets/reactions/retsch_pm100_thermal_library/templates.json`: heat capacities cited from NIST-JANAF Thermochemical Tables, NIST SRD 13 (M.W. Chase Jr., J. Phys. Chem. Ref. Data Monograph 9, 1998), https://doi.org/10.18434/T42S31, (c) U.S. Secretary of Commerce on behalf of the USA; used as factual data with citation.
|
| 281 |
+
* `assets/reactions/retsch_pt100_particle_library/templates.json`: molar volumes and phase records from ThermoChimie v12a (Andra-NWS-Ondraf; Giffaut et al., Appl. Geochem. 49 (2014) 225-236) as distributed in USGS PHREEQC sit.dat (https://github.com/phreeqc-dev/phreeqc3); densities derived by Chemistry-Sim.
|
| 282 |
+
* `assets/reactions/sartorius_vivaflow200_filtration_library/manufacturer_performance.json`: typical performance values cited from Sartorius Vivaflow 50/200 operating manual SLU6097-e231111 ((c) Sartorius Lab Instruments GmbH & Co. KG, all rights reserved), p.37; used as factual data with citation; SI conversion by Chemistry-Sim.
|
| 283 |
+
* `assets/reactions/sartorius_vivaflow200_filtration_library/templates.json`: protein sequences and chain annotations from UniProtKB release 2026_03 (The UniProt Consortium, Nucleic Acids Res. 2025), https://www.uniprot.org, licensed CC BY 4.0; chain molar masses computed by Chemistry-Sim (RDKit).
|
| 284 |
+
* `assets/reactions/scp_digiprepms_digestion_library/templates.json`: mineral reaction equilibrium data from LLNL thermo.com.V8.R6.230 (J. Johnson, Lawrence Livermore National Laboratory) as distributed in USGS PHREEQC llnl.dat (D.L. Parkhurst & C.A.J. Appelo; https://github.com/phreeqc-dev/phreeqc3); log K evaluated by Chemistry-Sim.
|
| 285 |
+
* `assets/reactions/sft_sft110_solubility_library/co2_eos_reference.json`: CO2 properties computed with CoolProp 7.2.0 (Bell et al., Ind. Eng. Chem. Res. 53 (2014) 2498; MIT License) using the Span-Wagner EOS (J. Phys. Chem. Ref. Data 25 (1996) 1509, https://doi.org/10.1063/1.555991).
|
| 286 |
+
* `assets/reactions/specac_atlasmanual_compaction_library/templates.json`: element densities cited from NIST X-Ray Mass Attenuation Coefficients, NIST SRD 126 (J.H. Hubbell & S.M. Seltzer), Table 1, https://physics.nist.gov/PhysRefData/XrayMassCoef/tab1.html ((c) U.S. Secretary of Commerce); powder densities and compaction parameters from Wünsch et al., Pharmaceutics 11 (2019) 121, https://doi.org/10.3390/pharmaceutics11030121, CC BY 4.0; KBr density from the Specac Advanced Solid Pack manual ((c) Specac Ltd); unit conversions by Chemistry-Sim.
|
| 287 |
+
* `assets/reactions/spectral_library/compounds.json`: identifiers and computed properties from PubChem (NCBI/NLM, public domain; Kim et al., Nucleic Acids Res. 2023); boiling/melting points cited from the NIST Chemistry WebBook, NIST Standard Reference Database 69 (Linstrom & Mallard, eds., doi:10.18434/T4D303), (c) U.S. Secretary of Commerce, used as factual data with citation.
|
| 288 |
+
* `assets/reactions/spectral_library/gc_retention.json`: retention-index statistics and enthalpies of vaporization derived from the NIST Chemistry WebBook, NIST Standard Reference Database 69 (doi:10.18434/T4D303), (c) U.S. Secretary of Commerce, used as factual data with citation; model parameters computed by Chemistry-Sim (column calibration is an assumption).
|
| 289 |
+
* `assets/reactions/spectral_library/hplc_uv.json`: XLogP3 values computed by PubChem (NCBI/NLM, public domain).
|
| 290 |
+
* `assets/reactions/substances.json`: molar masses and densities are standard handbook values (CRC Handbook of Chemistry and Physics); GC fingerprints derived by Chemistry-Sim from NIST SRD 69 retention indices.
|
| 291 |
+
* `assets/reactions/syrris_asiadiscovery_flow_library/templates.json`: Antoine vapour-pressure coefficients cited from NIST Chemistry WebBook, NIST Standard Reference Database 69 (P.J. Linstrom & W.G. Mallard, eds.), https://doi.org/10.18434/T4D303, (c) U.S. Secretary of Commerce on behalf of the USA, all rights reserved; per-fit primary literature references retained; reference pressures computed by Chemistry-Sim.
|
| 292 |
+
* `assets/reactions/syrris_asiafllex_partition_library/templates.json`: experimental log Kow values from the OPERA data set (K. Mansouri et al., J. Cheminform. 10, 10 (2018), https://doi.org/10.1186/s13321-018-0263-1), https://github.com/kmansouri/OPERA, MIT License, Copyright (c) 2016 kmansouri; original references retained per entry.
|
| 293 |
+
* `assets/reactions/thalesnano_hcube_hydrogenation_library/conversion_reference.json`: conversion values cited from Magritek application note 'H-Cube Pro + Spinsolve synthesis' (2023), p.6 Fig. 8 ((c) Magritek); used as factual data with citation; SI conversion by Chemistry-Sim.
|
| 294 |
+
* `assets/reactions/thalesnano_hcube_hydrogenation_library/templates.json`: Antoine vapour-pressure coefficients cited from NIST Chemistry WebBook, NIST Standard Reference Database 69 (P.J. Linstrom & W.G. Mallard, eds.), https://doi.org/10.18434/T4D303, (c) U.S. Secretary of Commerce on behalf of the USA, all rights reserved; per-fit primary literature references retained; reference pressures computed by Chemistry-Sim. Solvent compatibility ratings cited from the ThalesNano H-Cube Advance/Pro solvent resistance chart ((c) ThalesNano).
|
| 295 |
+
* `assets/reactions/thermo_process11_extrusion_library/templates.json`: extrusion conditions cited from Prasad, Robertson, Florence & Halbert, Additive Manufacturing 77 (2023) 103803, https://doi.org/10.1016/j.addma.2023.103803, CC BY 4.0; SI conversions by Chemistry-Sim.
|
| 296 |
+
* `assets/reactions/tousimis_autosamdri815_phase_library/co2_eos_reference.json`: CO2 properties computed with CoolProp 7.2.0 (Bell et al., Ind. Eng. Chem. Res. 53 (2014) 2498; MIT License) using the Span-Wagner EOS (J. Phys. Chem. Ref. Data 25 (1996) 1509, https://doi.org/10.1063/1.555991).
|
| 297 |
+
* `assets/reactions/tousimis_autosamdri815_phase_library/templates.json`: surface-tension correlation coefficients and critical constants from CoolProp 7.2.0 fluid files (https://github.com/CoolProp/CoolProp, MIT License, Copyright (c) Ian H. Bell and the CoolProp contributors), originally from Mulero, Cachadiña & Parra, J. Phys. Chem. Ref. Data 41 (2012) 043105, https://doi.org/10.1063/1.4768782; sigma(298.15 K) computed by Chemistry-Sim.
|
| 298 |
+
* `assets/reactions/uic_kdl1basic_evaporation_library/templates.json`: Antoine vapour-pressure coefficients cited from NIST Chemistry WebBook, NIST Standard Reference Database 69 (P.J. Linstrom & W.G. Mallard, eds.), https://doi.org/10.18434/T4D303, (c) U.S. Secretary of Commerce on behalf of the USA, all rights reserved; per-fit primary literature references retained; reference pressures computed by Chemistry-Sim.
|
| 299 |
+
* `assets/reactions/velp_udk159_nitrogen_library/templates.json`: total-nitrogen values from USDA FoodData Central, Foundation Foods (2026-04-30 release), https://fdc.nal.usda.gov (CC0 1.0); cereal Kjeldahl results cited from VELP Scientifica application note F&F-K-009-2013/A4 ((c) VELP Scientifica); SI conversion by Chemistry-Sim.
|
README.md
ADDED
|
@@ -0,0 +1,424 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
---
|
| 2 |
+
license: cc-by-nc-4.0
|
| 3 |
+
pretty_name: ChemLab-Assets
|
| 4 |
+
language:
|
| 5 |
+
- en
|
| 6 |
+
- zh
|
| 7 |
+
tags:
|
| 8 |
+
- chemistry
|
| 9 |
+
- laboratory
|
| 10 |
+
- robotics
|
| 11 |
+
- embodied-ai
|
| 12 |
+
- simulation
|
| 13 |
+
- 3d
|
| 14 |
+
- urdf
|
| 15 |
+
- isaac-lab
|
| 16 |
+
- digital-twin
|
| 17 |
+
size_categories:
|
| 18 |
+
- n<1K
|
| 19 |
+
configs:
|
| 20 |
+
- config_name: catalog
|
| 21 |
+
data_files:
|
| 22 |
+
- split: train
|
| 23 |
+
path: catalog/catalog.parquet
|
| 24 |
+
---
|
| 25 |
+
|
| 26 |
+
<div align="center">
|
| 27 |
+
|
| 28 |
+
<img src="media/banner.jpg" alt="Twenty-four of the 198 instruments, rendered in the same studio setup" width="100%">
|
| 29 |
+
|
| 30 |
+
# ChemLab-Assets
|
| 31 |
+
|
| 32 |
+
**198 simulation-ready chemistry laboratory instruments**<br>
|
| 33 |
+
part-level geometry · working joints · executable behaviour models · machine-readable contracts
|
| 34 |
+
|
| 35 |
+
<a href="https://huggingface.co/spaces/MBZUAI/ChemLab-Assets-Explorer"><img alt="3D explorer" src="https://img.shields.io/badge/%F0%9F%A4%97%20space-3D%20explorer-ff9d00"></a>
|
| 36 |
+
<img alt="Code licence" src="https://img.shields.io/badge/code-MIT-15202a">
|
| 37 |
+
<img alt="Asset licence" src="https://img.shields.io/badge/assets-CC%20BY--NC%204.0-15202a">
|
| 38 |
+
<img alt="Python" src="https://img.shields.io/badge/python-3.12-15202a">
|
| 39 |
+
|
| 40 |
+
Zirui Song · Jiadong Zhang · Jiahao Zhang · Xiaojun Chang · Xiaosong Ma · Xiuying Chen<br>
|
| 41 |
+
Mohamed bin Zayed University of Artificial Intelligence (MBZUAI)
|
| 42 |
+
|
| 43 |
+
</div>
|
| 44 |
+
|
| 45 |
+
## Overview
|
| 46 |
+
|
| 47 |
+
Agents that work in a chemistry lab need more than meshes. They need to know that a fume-hood sash travels 673 mm and
|
| 48 |
+
stops at 457 mm, that moving a balance's draft-shield door restarts its stability check, and which quantities a policy
|
| 49 |
+
may observe and which are hidden ground truth kept for evaluation. ChemLab-Assets ships that knowledge with the geometry.
|
| 50 |
+
|
| 51 |
+
Each asset is one specific commercial instrument, chosen from a survey of 200 instruments and modules used in university
|
| 52 |
+
chemistry teaching and research, and built from published brochures, manuals and papers. The models reproduce documented
|
| 53 |
+
behaviour; they are not manufacturer CAD and have not been calibrated against physical units.
|
| 54 |
+
|
| 55 |
+
This dataset holds everything: models, contracts, runtimes, tests and the catalog. The code is mirrored on GitHub (link added at release); see also the Project website (link added at release).
|
| 56 |
+
|
| 57 |
+
## At a glance
|
| 58 |
+
|
| 59 |
+
| | |
|
| 60 |
+
|---|---|
|
| 61 |
+
| **Instruments** | 198 commercial models from 115 manufacturers, in 16 capability domains |
|
| 62 |
+
| **Geometry** | GLB, URDF with primitive collision proxies, 14,492 per-part OBJ meshes, Blender sources |
|
| 63 |
+
| **Articulation** | 1,328 joints (909 prismatic, 388 revolute, 31 continuous): doors, sashes, lids, keys and knobs |
|
| 64 |
+
| **Contracts** | 14,272 components, 6,280 typed state slots, 4,639 capabilities with JSON-Schema arguments and declared errors |
|
| 65 |
+
| **Interfaces** | 648 readouts (displays, LEDs) and 2,348 interface points (place, grasp, ports) |
|
| 66 |
+
| **Behaviour** | a Python runtime per instrument: time-stepped process models behind `describe` / `read` / `invoke` / `poll`, agent and evaluator views, seeded noise |
|
| 67 |
+
| **Provenance** | 3,001 cited sources; raw third-party documents are not redistributed |
|
| 68 |
+
| **Simulation** | all 198 converted to USD and stepped in NVIDIA Isaac Lab through the Matterix framework |
|
| 69 |
+
|
| 70 |
+
## Gallery
|
| 71 |
+
|
| 72 |
+
<table>
|
| 73 |
+
<tr><td align="center" width="25%"><img src="media/thumb/esco_efa5uduvw.webp" width="190" alt="Chemical fume hood"><br><sub><b>Chemical fume hood</b><br>Esco Lifesciences Frontier Acela EFA-5UDUVW-9</sub></td><td align="center" width="25%"><img src="media/thumb/agilent_7890b_ssl_fid.webp" width="190" alt="Gas chromatograph (S/SL inlet + FID)"><br><sub><b>Gas chromatograph (S/SL inlet + FID)</b><br>Agilent 7890B</sub></td><td align="center" width="25%"><img src="media/thumb/mt_xpr204e.webp" width="190" alt="Analytical balance"><br><sub><b>Analytical balance</b><br>METTLER TOLEDO XPR204E</sub></td><td align="center" width="25%"><img src="media/thumb/brooks_preciseflex_400.webp" width="190" alt="Lab sample-transfer robot arm"><br><sub><b>Lab sample-transfer robot arm</b><br>Brooks Automation PreciseFlex 400</sub></td></tr>
|
| 74 |
+
<tr><td align="center" width="25%"><img src="media/thumb/ika_rv10_digital_v.webp" width="190" alt="Rotary evaporator"><br><sub><b>Rotary evaporator</b><br>IKA RV 10 digital V</sub></td><td align="center" width="25%"><img src="media/thumb/thermo_orbitrapexploris.webp" width="190" alt="High-resolution Orbitrap mass spectrometer"><br><sub><b>High-resolution Orbitrap mass spectrometer</b><br>Thermo Fisher Scientific Orbitrap Exploris 120</sub></td><td align="center" width="25%"><img src="media/thumb/jeol_jsmit200.webp" width="190" alt="Scanning electron microscope"><br><sub><b>Scanning electron microscope</b><br>JEOL JSM-IT200 LA</sub></td><td align="center" width="25%"><img src="media/thumb/buchi_lyovapor_l250_pro.webp" width="190" alt="Freeze dryer"><br><sub><b>Freeze dryer</b><br>BUCHI Lyovapor L-250 Pro</sub></td></tr>
|
| 75 |
+
<tr><td align="center" width="25%"><img src="media/thumb/opentrons_flex_single_5_1000ul.webp" width="190" alt="Automated liquid-handling robot"><br><sub><b>Automated liquid-handling robot</b><br>Opentrons Flex (1-channel 5–1000 µL)</sub></td><td align="center" width="25%"><img src="media/thumb/magritek_spinsolve80.webp" width="190" alt="Benchtop NMR spectrometer"><br><sub><b>Benchtop NMR spectrometer</b><br>Magritek Spinsolve 80 Carbon</sub></td><td align="center" width="25%"><img src="media/thumb/inert_purelab_he_2gb.webp" width="190" alt="Inert-atmosphere glovebox"><br><sub><b>Inert-atmosphere glovebox</b><br>Inert PureLab HE 2GB</sub></td><td align="center" width="25%"><img src="media/thumb/park_nx10.webp" width="190" alt="Atomic force microscope"><br><sub><b>Atomic force microscope</b><br>Park Systems NX10</sub></td></tr>
|
| 76 |
+
</table>
|
| 77 |
+
|
| 78 |
+
Browse all 198 in 3D, with joint sliders and part-by-part annotations, in the [3D explorer](https://huggingface.co/spaces/MBZUAI/ChemLab-Assets-Explorer).
|
| 79 |
+
|
| 80 |
+
## Instruments by domain
|
| 81 |
+
|
| 82 |
+
| Domain | Instruments | Examples |
|
| 83 |
+
|---|---:|---|
|
| 84 |
+
| Thermal, Mechanical & Transport | 23 | Pin-on-disk tribometer (Anton Paar TRB³); Coating scratch tester (Anton Paar RST 300); Nanoindentation tester (Anton Paar HIT 300) |
|
| 85 |
+
| Basic Metrology & Sample Handling | 16 | Analytical balance (METTLER TOLEDO XPR204E); Halogen moisture analyzer (METTLER TOLEDO HX204); Oscillating U-tube density meter (Anton Paar DMA 5002) |
|
| 86 |
+
| Lab Environment & Utilities | 16 | Muffle furnace (Nabertherm L 9/11/SKM); Tube furnace (controlled atmosphere) (Carbolite Gero TF1 12/60/300); Heating/refrigerated circulator (JULABO CORIO CD-200F) |
|
| 87 |
+
| Extraction, Purification & Drying | 15 | Rotary evaporator (IKA RV 10 digital V); Freeze dryer (BUCHI Lyovapor L-250 Pro); Lab spray dryer (BUCHI Mini Spray Dryer S-300) |
|
| 88 |
+
| Particles, Pores & Interfaces | 15 | Solid-surface streaming-potential analyzer (Anton Paar SurPASS 3); Gas pycnometer (true density) (Anton Paar Ultrapyc 5000); Gas physisorption surface-area & pore analyzer (Anton Paar Autosorb 6100) |
|
| 89 |
+
| Molecular Spectroscopy & Structure | 14 | Circular dichroism spectrometer (JASCO J-1500); Time-domain NMR relaxometer (Bruker minispec mq20); Spectrofluorometer (JASCO FP-8350) |
|
| 90 |
+
| Digestion & Solid Sample Prep | 13 | Graphite block digestion system (SCP SCIENCE DigiPREP MS); Planetary ball mill (RETSCH PM 100); Vibratory sieve shaker (RETSCH AS 200 control) |
|
| 91 |
+
| Thin-Film & Functional Materials | 13 | Vibrating-nozzle encapsulator (BUCHI Encapsulator B-390); Spin coater (Ossila Spin Coater V3); Dip coater (Ossila Dip Coater V2) |
|
| 92 |
+
| Elemental & Mass Spectrometry | 12 | Organic elemental (CHNS) analyzer (Elementar vario EL cube); Total organic carbon analyzer (Shimadzu TOC-L CSH); Atomic absorption spectrometer (Analytik Jena contrAA 800 D) |
|
| 93 |
+
| Microscopy, Imaging & Diffraction | 12 | Scanning electron microscope (JEOL JSM-IT200 LA); Transmission electron microscope (JEOL JEM-1400Flash); Small-angle X-ray scattering system (Anton Paar SAXSpace) |
|
| 94 |
+
| Biochemical & Wet-Chemistry Assays | 11 | Microplate washer (Agilent BioTek 405 TS (96-tube manifold)); Gel electrophoresis system (Bio-Rad Mini-PROTEAN Tetra + power supply); Gel & blot imager (Thermo Fisher Scientific iBright FL1500) |
|
| 95 |
+
| Automation & Gas/Liquid Supply | 11 | Automated powder dosing system (METTLER TOLEDO Quantos Q2 + XPE206DR); Automated liquid-handling robot (Opentrons Flex (1-channel 5–1000 µL)); Automated microplate heat sealer (Azenta Life Sciences Automated Roll Heat Sealer (a4S)) |
|
| 96 |
+
| Reaction & Molecular Synthesis | 9 | Microwave synthesis reactor (Anton Paar Monowave 400); Electro-organic synthesis system (IKA ElectraSyn 2.0); Photochemical reactor (HepatoChem PhotoRedOx Box UV-Vis) |
|
| 97 |
+
| Electrochemistry & Titration | 7 | Automatic potentiometric titrator (Metrohm OMNIS Professional Titrator); Karl Fischer coulometer (Metrohm 899 Coulometer); Potentiostat / electrochemical workstation (Gamry Reference 620) |
|
| 98 |
+
| Chromatography & Electrophoresis | 6 | Gas chromatograph (Agilent 8890B GC); HPLC system (Agilent 1260 Infinity III LC); Ion chromatograph (Thermo Fisher Scientific Dionex Integrion HPIC) |
|
| 99 |
+
| Analytical Sampling & Interfaces | 5 | Headspace autosampler (48-vial tray) (Agilent 8697); Purge-and-trap autosampler (Teledyne Tekmar Atomx XYZ); Laser ablation sampling system (Teledyne CETAC Analyte Excite+) |
|
| 100 |
+
|
| 101 |
+
<details>
|
| 102 |
+
<summary><b>All 198 instruments</b></summary>
|
| 103 |
+
|
| 104 |
+
| CHEM ID | Instrument | Maker | Model | Domain | Joints | State slots | Capabilities |
|
| 105 |
+
|---|---|---|---|---|---:|---:|---:|
|
| 106 |
+
| CHEM-001 | Analytical balance | METTLER TOLEDO | XPR204E | Basic Metrology & Sample Handling | 16 | 22 | 9 |
|
| 107 |
+
| CHEM-002 | Halogen moisture analyzer | METTLER TOLEDO | HX204 | Basic Metrology & Sample Handling | 5 | 14 | 8 |
|
| 108 |
+
| CHEM-003 | Oscillating U-tube density meter | Anton Paar | DMA 5002 | Basic Metrology & Sample Handling | 4 | 17 | 9 |
|
| 109 |
+
| CHEM-004 | Digital refractometer | Anton Paar | Abbemat Advanced 5201 | Basic Metrology & Sample Handling | 5 | 19 | 10 |
|
| 110 |
+
| CHEM-005 | pH / DO / conductivity meter | Metrohm | 914 pH/DO/Conductometer | Basic Metrology & Sample Handling | 3 | 44 | 11 |
|
| 111 |
+
| CHEM-006 | Automatic melting-point system | METTLER TOLEDO | MP70 | Basic Metrology & Sample Handling | 4 | 26 | 10 |
|
| 112 |
+
| CHEM-007 | Water-activity meter | AQUALAB | 4TE | Basic Metrology & Sample Handling | 10 | 27 | 13 |
|
| 113 |
+
| CHEM-008 | Magnetic hotplate stirrer | IKA | Plate RCT digital | Basic Metrology & Sample Handling | 8 | 33 | 33 |
|
| 114 |
+
| CHEM-009 | Incubated orbital shaker | IKA | KS 4000 i control | Basic Metrology & Sample Handling | 14 | 33 | 14 |
|
| 115 |
+
| CHEM-010 | Refrigerated multipurpose centrifuge | Eppendorf | 5910 Ri | Basic Metrology & Sample Handling | 2 | 23 | 13 |
|
| 116 |
+
| CHEM-011 | Forced-convection drying oven | BINDER | FD 56 | Basic Metrology & Sample Handling | 7 | 25 | 32 |
|
| 117 |
+
| CHEM-012 | Vacuum drying oven | BINDER | VD 56 | Basic Metrology & Sample Handling | 7 | 10 | 6 |
|
| 118 |
+
| CHEM-013 | Ultrasonic cleaning bath | Elma | Elmasonic S60H | Basic Metrology & Sample Handling | 8 | 56 | 15 |
|
| 119 |
+
| CHEM-014 | Benchtop turbidimeter | Hach | TL2300 EPA | Basic Metrology & Sample Handling | 2 | 26 | 11 |
|
| 120 |
+
| CHEM-015 | Microwave synthesis reactor | Anton Paar | Monowave 400 | Reaction & Molecular Synthesis | 3 | 32 | 12 |
|
| 121 |
+
| CHEM-016 | Electro-organic synthesis system | IKA | ElectraSyn 2.0 | Reaction & Molecular Synthesis | 2 | 40 | 12 |
|
| 122 |
+
| CHEM-017 | Photochemical reactor | HepatoChem | PhotoRedOx Box UV-Vis | Reaction & Molecular Synthesis | 3 | 36 | 15 |
|
| 123 |
+
| CHEM-018 | Micro high-pressure stirred reactor | Parr Instrument | 4591 | Reaction & Molecular Synthesis | 9 | 22 | 10 |
|
| 124 |
+
| CHEM-019 | Continuous-flow chemistry system | Syrris | Asia Discovery | Reaction & Molecular Synthesis | 4 | 38 | 13 |
|
| 125 |
+
| CHEM-020 | Continuous-flow hydrogenation reactor | ThalesNano | H-Cube Pro | Reaction & Molecular Synthesis | 5 | 41 | 17 |
|
| 126 |
+
| CHEM-021 | Parallel reaction station (4 independent zones) | Radleys | Mya 4 | Reaction & Molecular Synthesis | 4 | 92 | 15 |
|
| 127 |
+
| CHEM-022 | Automated microwave peptide synthesizer | CEM | Liberty Blue 2.0 | Reaction & Molecular Synthesis | 2 | 34 | 13 |
|
| 128 |
+
| CHEM-023 | Oligonucleotide synthesizer | Cytiva | ÄKTA oligosynt | Reaction & Molecular Synthesis | 3 | 31 | 12 |
|
| 129 |
+
| CHEM-024 | Rotary evaporator | IKA | RV 10 digital V | Extraction, Purification & Drying | 5 | 26 | 10 |
|
| 130 |
+
| CHEM-025 | Freeze dryer | BUCHI | Lyovapor L-250 Pro | Extraction, Purification & Drying | 3 | 34 | 13 |
|
| 131 |
+
| CHEM-026 | Lab spray dryer | BUCHI | Mini Spray Dryer S-300 | Extraction, Purification & Drying | 2 | 26 | 16 |
|
| 132 |
+
| CHEM-027 | Critical point dryer | Tousimis | Autosamdri-815 Series B | Extraction, Purification & Drying | 2 | 30 | 13 |
|
| 133 |
+
| CHEM-028 | Pressurized solvent extractor | BUCHI | SpeedExtractor E-916 | Extraction, Purification & Drying | 4 | 33 | 14 |
|
| 134 |
+
| CHEM-029 | Centrifugal partition chromatograph | Gilson | CPC 250 | Extraction, Purification & Drying | 3 | 28 | 10 |
|
| 135 |
+
| CHEM-030 | Tangential-flow ultrafiltration module | Sartorius | Vivaflow 200 | Extraction, Purification & Drying | 1 | 33 | 10 |
|
| 136 |
+
| CHEM-031 | Automated solid-phase extraction workstation | Biotage | Extrahera Classic | Extraction, Purification & Drying | 0 | 30 | 10 |
|
| 137 |
+
| CHEM-032 | Supercritical fluid extractor | Supercritical Fluid Technologies | SFT-110 | Extraction, Purification & Drying | 3 | 30 | 13 |
|
| 138 |
+
| CHEM-033 | Flow liquid–liquid extraction module | Syrris | Asia FLLEX | Extraction, Purification & Drying | 2 | 42 | 15 |
|
| 139 |
+
| CHEM-034 | Automated flash chromatography system | Biotage | Selekt (UV, single bed) | Extraction, Purification & Drying | 3 | 55 | 15 |
|
| 140 |
+
| CHEM-035 | Lab electrodialysis stack | PCCell | ED 64002 + BED1-2 Basic | Extraction, Purification & Drying | 3 | 28 | 14 |
|
| 141 |
+
| CHEM-036 | Centrifugal vacuum concentrator | Genevac / SP Industries | miVac 2 Duo | Extraction, Purification & Drying | 9 | 22 | 13 |
|
| 142 |
+
| CHEM-037 | High-efficiency lab fractional distillation unit | PILODIST | PILODIST 104 | Extraction, Purification & Drying | 4 | 24 | 15 |
|
| 143 |
+
| CHEM-038 | Short-path wiped-film molecular still | UIC | KDL1 Basic | Extraction, Purification & Drying | 5 | 30 | 17 |
|
| 144 |
+
| CHEM-039 | Graphite block digestion system | SCP SCIENCE | DigiPREP MS | Digestion & Solid Sample Prep | 2 | 24 | 13 |
|
| 145 |
+
| CHEM-040 | Planetary ball mill | RETSCH | PM 100 | Digestion & Solid Sample Prep | 8 | 24 | 13 |
|
| 146 |
+
| CHEM-041 | Vibratory sieve shaker | RETSCH | AS 200 control | Digestion & Solid Sample Prep | 16 | 24 | 20 |
|
| 147 |
+
| CHEM-042 | Rotary sample divider | RETSCH | PT 100 | Digestion & Solid Sample Prep | 15 | 25 | 21 |
|
| 148 |
+
| CHEM-043 | Rotor–stator disperser | IKA | T 25 digital ULTRA-TURRAX | Digestion & Solid Sample Prep | 4 | 30 | 16 |
|
| 149 |
+
| CHEM-044 | Probe ultrasonic processor | Sonics | VCX 750 | Digestion & Solid Sample Prep | 25 | 34 | 19 |
|
| 150 |
+
| CHEM-045 | Planetary centrifugal mixer | THINKY | ARE-310 | Digestion & Solid Sample Prep | 10 | 33 | 14 |
|
| 151 |
+
| CHEM-046 | UV digester | Metrohm | 909 UV Digester | Digestion & Solid Sample Prep | 10 | 31 | 17 |
|
| 152 |
+
| CHEM-047 | Microwave acid digestion system | Anton Paar | Multiwave 7101 | Digestion & Solid Sample Prep | 1 | 16 | 11 |
|
| 153 |
+
| CHEM-048 | Automatic Kjeldahl distillation & titration unit | VELP | UDK 159 | Digestion & Solid Sample Prep | 6 | 34 | 18 |
|
| 154 |
+
| CHEM-049 | Acid hydrolysis unit | BUCHI | HydrolEx H-506 | Digestion & Solid Sample Prep | 10 | 25 | 19 |
|
| 155 |
+
| CHEM-050 | Automated fusion bead maker | Malvern Panalytical / Claisse | LeNeo | Digestion & Solid Sample Prep | 6 | 20 | 15 |
|
| 156 |
+
| CHEM-051 | Hydraulic pellet press | Specac | Atlas Manual 15T | Digestion & Solid Sample Prep | 9 | 27 | 16 |
|
| 157 |
+
| CHEM-052 | Vibrating-nozzle encapsulator | BUCHI | Encapsulator B-390 | Thin-Film & Functional Materials | 8 | 30 | 23 |
|
| 158 |
+
| CHEM-053 | Spin coater | Ossila | Spin Coater V3 | Thin-Film & Functional Materials | 15 | 13 | 12 |
|
| 159 |
+
| CHEM-054 | Dip coater | Ossila | Dip Coater V2 | Thin-Film & Functional Materials | 15 | 18 | 17 |
|
| 160 |
+
| CHEM-055 | Automated doctor-blade coater | Ossila | Doctor Blade Coater | Thin-Film & Functional Materials | 16 | 21 | 18 |
|
| 161 |
+
| CHEM-056 | Slot-die coater | Ossila | Slot-Die Coater V2 | Thin-Film & Functional Materials | 17 | 29 | 22 |
|
| 162 |
+
| CHEM-057 | Lab twin-screw extruder | Thermo Fisher Scientific | Process 11 | Thin-Film & Functional Materials | 5 | 32 | 22 |
|
| 163 |
+
| CHEM-058 | Materials inkjet printer | FUJIFILM Dimatix | DMP-2850 | Thin-Film & Functional Materials | 4 | 28 | 21 |
|
| 164 |
+
| CHEM-059 | Electrospinning system | Linari Nanotech | RT Advanced | Thin-Film & Functional Materials | 14 | 33 | 21 |
|
| 165 |
+
| CHEM-060 | Microfluidic nanoparticle formulation system | Cytiva / Precision NanoSystems | NanoAssemblr Ignite | Thin-Film & Functional Materials | 9 | 35 | 20 |
|
| 166 |
+
| CHEM-061 | Fluid-bed granulator / coater | Glatt | Mini-Glatt | Thin-Film & Functional Materials | 12 | 33 | 21 |
|
| 167 |
+
| CHEM-062 | Sputter & carbon coater | Quorum Technologies | Q150T ES Plus | Thin-Film & Functional Materials | 7 | 28 | 18 |
|
| 168 |
+
| CHEM-063 | Chemical vapour deposition system | LABOAO | CVD-LTF12P50 | Thin-Film & Functional Materials | 10 | 34 | 16 |
|
| 169 |
+
| CHEM-064 | Atomic layer deposition system | Arradiance | GEMStar XT-SP (PEALD / thermal ALD) | Thin-Film & Functional Materials | 8 | 31 | 21 |
|
| 170 |
+
| CHEM-065 | Circular dichroism spectrometer | JASCO | J-1500 | Molecular Spectroscopy & Structure | 2 | 25 | 18 |
|
| 171 |
+
| CHEM-066 | Time-domain NMR relaxometer | Bruker | minispec mq20 | Molecular Spectroscopy & Structure | 1 | 21 | 17 |
|
| 172 |
+
| CHEM-067 | Spectrofluorometer | JASCO | FP-8350 | Molecular Spectroscopy & Structure | 2 | 25 | 19 |
|
| 173 |
+
| CHEM-068 | Benchtop NMR spectrometer | Magritek | Spinsolve 80 Carbon | Molecular Spectroscopy & Structure | 1 | 24 | 15 |
|
| 174 |
+
| CHEM-069 | Benchtop EPR spectrometer | Bruker | Magnettech ESR5000 | Molecular Spectroscopy & Structure | 1 | 21 | 19 |
|
| 175 |
+
| CHEM-070 | Digital polarimeter | JASCO | P-4200 | Molecular Spectroscopy & Structure | 2 | 23 | 20 |
|
| 176 |
+
| CHEM-071 | UV-Vis spectrophotometer | Hach | DR6000 | Molecular Spectroscopy & Structure | 1 | 14 | 13 |
|
| 177 |
+
| CHEM-072 | FT-IR spectrometer | JASCO | FT/IR-4700 | Molecular Spectroscopy & Structure | 1 | 18 | 12 |
|
| 178 |
+
| CHEM-073 | Raman microscope | JASCO | NRS-5500 | Molecular Spectroscopy & Structure | 4 | 26 | 23 |
|
| 179 |
+
| CHEM-074 | Stopped-flow kinetics spectrometer | Applied Photophysics | SX20 | Molecular Spectroscopy & Structure | 6 | 30 | 19 |
|
| 180 |
+
| CHEM-075 | Time-resolved fluorescence (TCSPC) spectrometer | Edinburgh Instruments | FLS1000 | Molecular Spectroscopy & Structure | 4 | 26 | 18 |
|
| 181 |
+
| CHEM-076 | Femtosecond transient absorption spectrometer | Ultrafast Systems | HELIOS | Molecular Spectroscopy & Structure | 4 | 25 | 17 |
|
| 182 |
+
| CHEM-077 | Vibrational circular dichroism spectrometer | JASCO | FVS-6000 | Molecular Spectroscopy & Structure | 4 | 32 | 22 |
|
| 183 |
+
| CHEM-078 | Circularly polarized luminescence spectrometer | JASCO | CPL-300 | Molecular Spectroscopy & Structure | 5 | 29 | 22 |
|
| 184 |
+
| CHEM-079 | Organic elemental (CHNS) analyzer | Elementar | vario EL cube | Elemental & Mass Spectrometry | 5 | 31 | 23 |
|
| 185 |
+
| CHEM-080 | Total organic carbon analyzer | Shimadzu | TOC-L CSH | Elemental & Mass Spectrometry | 40 | 32 | 29 |
|
| 186 |
+
| CHEM-081 | Atomic absorption spectrometer | Analytik Jena | contrAA 800 D | Elemental & Mass Spectrometry | 10 | 41 | 33 |
|
| 187 |
+
| CHEM-082 | ICP optical emission spectrometer | Shimadzu | ICPE-9800 | Elemental & Mass Spectrometry | 3 | 36 | 33 |
|
| 188 |
+
| CHEM-083 | ICP mass spectrometer | Shimadzu | ICPMS-2030 | Elemental & Mass Spectrometry | 5 | 37 | 30 |
|
| 189 |
+
| CHEM-084 | Energy-dispersive XRF spectrometer | Shimadzu | EDX-7200 | Elemental & Mass Spectrometry | 3 | 33 | 29 |
|
| 190 |
+
| CHEM-085 | Total organic halogen (AOX/TOX) analyzer | Analytik Jena | multi X 2500 | Elemental & Mass Spectrometry | 8 | 38 | 37 |
|
| 191 |
+
| CHEM-086 | Direct mercury analyzer | Milestone | DMA-80 evo | Elemental & Mass Spectrometry | 5 | 38 | 34 |
|
| 192 |
+
| CHEM-087 | Residual gas analyzer | Stanford Research Systems | RGA100 | Elemental & Mass Spectrometry | 2 | 40 | 34 |
|
| 193 |
+
| CHEM-088 | High-resolution Orbitrap mass spectrometer | Thermo Fisher Scientific | Orbitrap Exploris 120 | Elemental & Mass Spectrometry | 4 | 37 | 37 |
|
| 194 |
+
| CHEM-089 | Inert-gas fusion O/N/H analyzer | LECO | ONH836 | Elemental & Mass Spectrometry | 4 | 36 | 35 |
|
| 195 |
+
| CHEM-090 | Stable isotope-ratio mass spectrometer | Elementar | isoprime precisION | Elemental & Mass Spectrometry | 2 | 21 | 30 |
|
| 196 |
+
| CHEM-096 | Gas chromatograph | Agilent | 8890B GC | Chromatography & Electrophoresis | 50 | 22 | 55 |
|
| 197 |
+
| CHEM-097 | HPLC system | Agilent | 1260 Infinity III LC | Chromatography & Electrophoresis | 1 | 24 | 14 |
|
| 198 |
+
| CHEM-098 | Ion chromatograph | Thermo Fisher Scientific | Dionex Integrion HPIC | Chromatography & Electrophoresis | 2 | 21 | 16 |
|
| 199 |
+
| CHEM-099 | GPC/SEC system | Agilent | 1290 Infinity II GPC/SEC | Chromatography & Electrophoresis | 3 | 25 | 18 |
|
| 200 |
+
| CHEM-100 | GC–ion mobility spectrometer | G.A.S. | FlavourSpec25 GC-IMS | Chromatography & Electrophoresis | 4 | 29 | 20 |
|
| 201 |
+
| CHEM-101 | Automatic potentiometric titrator | Metrohm | OMNIS Professional Titrator | Electrochemistry & Titration | 2 | 34 | 12 |
|
| 202 |
+
| CHEM-102 | Karl Fischer coulometer | Metrohm | 899 Coulometer | Electrochemistry & Titration | 11 | 26 | 7 |
|
| 203 |
+
| CHEM-103 | Potentiostat / electrochemical workstation | Gamry | Reference 620 | Electrochemistry & Titration | 0 | 21 | 7 |
|
| 204 |
+
| CHEM-104 | Scanning electrochemical microscope | CH Instruments | CHI920D | Electrochemistry & Titration | 3 | 29 | 16 |
|
| 205 |
+
| CHEM-105 | Electrochemical quartz crystal microbalance | CH Instruments | CHI440C | Electrochemistry & Titration | 1 | 19 | 17 |
|
| 206 |
+
| CHEM-106 | Freezing-point osmometer | KNAUER | K-7400S | Electrochemistry & Titration | 2 | 24 | 17 |
|
| 207 |
+
| CHEM-107 | Rotating ring-disk electrode rotator | Pine Research | WaveVortex 10 | Electrochemistry & Titration | 4 | 30 | 22 |
|
| 208 |
+
| CHEM-108 | Headspace autosampler (48-vial tray) | Agilent | 8697 | Analytical Sampling & Interfaces | 1 | 24 | 13 |
|
| 209 |
+
| CHEM-109 | Purge-and-trap autosampler | Teledyne Tekmar | Atomx XYZ | Analytical Sampling & Interfaces | 7 | 25 | 20 |
|
| 210 |
+
| CHEM-110 | Laser ablation sampling system | Teledyne CETAC | Analyte Excite+ | Analytical Sampling & Interfaces | 6 | 22 | 23 |
|
| 211 |
+
| CHEM-111 | Multi-shot pyrolyzer (GC inlet) | Frontier Laboratories | EGA/PY-3030D | Analytical Sampling & Interfaces | 4 | 22 | 22 |
|
| 212 |
+
| CHEM-112 | Thermal desorber | Markes International | UNITY-xr | Analytical Sampling & Interfaces | 6 | 27 | 26 |
|
| 213 |
+
| CHEM-113 | Solid-surface streaming-potential analyzer | Anton Paar | SurPASS 3 | Particles, Pores & Interfaces | 7 | 29 | 25 |
|
| 214 |
+
| CHEM-114 | Gas pycnometer (true density) | Anton Paar | Ultrapyc 5000 | Particles, Pores & Interfaces | 6 | 33 | 25 |
|
| 215 |
+
| CHEM-115 | Gas physisorption surface-area & pore analyzer | Anton Paar | Autosorb 6100 | Particles, Pores & Interfaces | 8 | 49 | 33 |
|
| 216 |
+
| CHEM-116 | Mercury intrusion porosimeter | Anton Paar | PoreMaster 60 | Particles, Pores & Interfaces | 7 | 27 | 28 |
|
| 217 |
+
| CHEM-117 | DLS & zeta-potential analyzer | Anton Paar | Litesizer DLS 701 | Particles, Pores & Interfaces | 6 | 31 | 29 |
|
| 218 |
+
| CHEM-118 | Laser-diffraction particle sizer | Anton Paar | PSA 1190 | Particles, Pores & Interfaces | 9 | 31 | 28 |
|
| 219 |
+
| CHEM-119 | Dynamic image analyzer (particle shape) | Anton Paar | Litesizer DIA 700 | Particles, Pores & Interfaces | 7 | 31 | 29 |
|
| 220 |
+
| CHEM-120 | Force tensiometer | Biolin Scientific | Sigma 700 | Particles, Pores & Interfaces | 7 | 30 | 32 |
|
| 221 |
+
| CHEM-121 | Optical contact-angle meter | Biolin Scientific | Theta Flex | Particles, Pores & Interfaces | 8 | 33 | 35 |
|
| 222 |
+
| CHEM-122 | Temperature-programmed chemisorption analyzer | Micromeritics | AutoChem III | Particles, Pores & Interfaces | 6 | 36 | 35 |
|
| 223 |
+
| CHEM-123 | Dynamic vapour sorption analyzer | Surface Measurement Systems | DVS Resolution | Particles, Pores & Interfaces | 6 | 40 | 37 |
|
| 224 |
+
| CHEM-124 | Powder rheometer | Freeman Technology / Micromeritics | FT4 Powder Rheometer | Particles, Pores & Interfaces | 6 | 39 | 33 |
|
| 225 |
+
| CHEM-125 | Capillary flow porometer | POROMETER | POROLUX Revo | Particles, Pores & Interfaces | 3 | 28 | 33 |
|
| 226 |
+
| CHEM-126 | Dispersion stability analyzer | Microtrac | TURBISCAN LAB | Particles, Pores & Interfaces | 5 | 28 | 27 |
|
| 227 |
+
| CHEM-127 | Langmuir / Langmuir–Blodgett trough | Biolin Scientific KSV NIMA | Medium L&LB Trough | Particles, Pores & Interfaces | 7 | 36 | 34 |
|
| 228 |
+
| CHEM-128 | Pin-on-disk tribometer | Anton Paar | TRB³ | Thermal, Mechanical & Transport | 6 | 42 | 39 |
|
| 229 |
+
| CHEM-129 | Coating scratch tester | Anton Paar | RST 300 | Thermal, Mechanical & Transport | 6 | 42 | 38 |
|
| 230 |
+
| CHEM-130 | Nanoindentation tester | Anton Paar | HIT 300 | Thermal, Mechanical & Transport | 6 | 38 | 33 |
|
| 231 |
+
| CHEM-131 | Differential scanning calorimeter | TA Instruments | DSC 2500 | Thermal, Mechanical & Transport | 5 | 43 | 36 |
|
| 232 |
+
| CHEM-132 | Thermogravimetric analyzer | TA Instruments | TGA 5500 | Thermal, Mechanical & Transport | 4 | 48 | 40 |
|
| 233 |
+
| CHEM-133 | Dynamic mechanical analyzer | TA Instruments | DMA 850 | Thermal, Mechanical & Transport | 5 | 43 | 41 |
|
| 234 |
+
| CHEM-134 | Thermomechanical analyzer | TA Instruments | TMA 450 | Thermal, Mechanical & Transport | 3 | 50 | 47 |
|
| 235 |
+
| CHEM-135 | Laser/light flash thermal diffusivity analyzer | NETZSCH | LFA 467 HyperFlash | Thermal, Mechanical & Transport | 4 | 54 | 47 |
|
| 236 |
+
| CHEM-136 | Transient plane source thermal-conductivity analyzer | Hot Disk | TPS 2500 S | Thermal, Mechanical & Transport | 4 | 25 | 25 |
|
| 237 |
+
| CHEM-137 | Rotational & oscillatory rheometer | Anton Paar | MCR 503 | Thermal, Mechanical & Transport | 3 | 26 | 28 |
|
| 238 |
+
| CHEM-138 | Isothermal microcalorimeter | TA Instruments | TAM IV | Thermal, Mechanical & Transport | 2 | 25 | 31 |
|
| 239 |
+
| CHEM-139 | Thermoelectric (Seebeck) tester | Linseis | LSR-3 | Thermal, Mechanical & Transport | 5 | 32 | 31 |
|
| 240 |
+
| CHEM-140 | Broadband dielectric spectrometer | Novocontrol Technologies | Alpha-T | Thermal, Mechanical & Transport | 3 | 27 | 30 |
|
| 241 |
+
| CHEM-141 | Hall-effect measurement system | Lake Shore Cryotronics | MeasureReady M91 FastHall | Thermal, Mechanical & Transport | 4 | 36 | 31 |
|
| 242 |
+
| CHEM-142 | Automated four-point-probe sheet-resistance mapper | Signatone | QuadPro2 | Thermal, Mechanical & Transport | 5 | 34 | 29 |
|
| 243 |
+
| CHEM-143 | Vibrating sample magnetometer | Lake Shore Cryotronics | 8604 VSM | Thermal, Mechanical & Transport | 5 | 34 | 32 |
|
| 244 |
+
| CHEM-144 | Universal testing machine | Shimadzu | AGS-10kNXD | Thermal, Mechanical & Transport | 6 | 35 | 28 |
|
| 245 |
+
| CHEM-145 | Pendulum impact tester | ZwickRoell | HIT5P | Thermal, Mechanical & Transport | 4 | 31 | 27 |
|
| 246 |
+
| CHEM-146 | Melt flow indexer | ZwickRoell | Mflow | Thermal, Mechanical & Transport | 9 | 43 | 36 |
|
| 247 |
+
| CHEM-147 | Oxygen transmission-rate analyzer | AMETEK MOCON | OX-TRAN 2/22 L | Thermal, Mechanical & Transport | 8 | 55 | 31 |
|
| 248 |
+
| CHEM-148 | Adiabatic (ARC) reaction calorimeter | NETZSCH | MMC 315 Nexus | Thermal, Mechanical & Transport | 3 | 30 | 24 |
|
| 249 |
+
| CHEM-149 | Heat-flow reaction calorimeter | METTLER TOLEDO | RC1mx + HFCal | Thermal, Mechanical & Transport | 5 | 57 | 37 |
|
| 250 |
+
| CHEM-150 | Oxygen bomb calorimeter | IKA | C 6000 isoperibol | Thermal, Mechanical & Transport | 3 | 43 | 44 |
|
| 251 |
+
| CHEM-151 | Scanning electron microscope | JEOL | JSM-IT200 LA | Microscopy, Imaging & Diffraction | 12 | 64 | 48 |
|
| 252 |
+
| CHEM-152 | Transmission electron microscope | JEOL | JEM-1400Flash | Microscopy, Imaging & Diffraction | 21 | 77 | 59 |
|
| 253 |
+
| CHEM-153 | Small-angle X-ray scattering system | Anton Paar | SAXSpace | Microscopy, Imaging & Diffraction | 13 | 76 | 54 |
|
| 254 |
+
| CHEM-154 | X-ray photoelectron spectrometer | Kratos / Shimadzu | AXIS Supra+ | Microscopy, Imaging & Diffraction | 10 | 67 | 49 |
|
| 255 |
+
| CHEM-155 | 3D laser-scanning profilometer microscope | KEYENCE | VK-X3000 / VK-X3100 | Microscopy, Imaging & Diffraction | 7 | 51 | 38 |
|
| 256 |
+
| CHEM-156 | Micro X-ray computed tomography | Bruker | X4 POSEIDON | Microscopy, Imaging & Diffraction | 7 | 60 | 46 |
|
| 257 |
+
| CHEM-157 | Spectroscopic ellipsometer | J.A. Woollam | alpha-SE | Microscopy, Imaging & Diffraction | 5 | 39 | 37 |
|
| 258 |
+
| CHEM-158 | Atomic force microscope | Park Systems | NX10 | Microscopy, Imaging & Diffraction | 12 | 54 | 56 |
|
| 259 |
+
| CHEM-159 | Scanning tunneling microscope | Nanosurf | NaioSTM | Microscopy, Imaging & Diffraction | 3 | 36 | 52 |
|
| 260 |
+
| CHEM-160 | Powder X-ray diffractometer | Rigaku | MiniFlex600 | Microscopy, Imaging & Diffraction | 3 | 25 | 12 |
|
| 261 |
+
| CHEM-161 | Single-crystal X-ray diffractometer | Rigaku Oxford Diffraction | XtaLAB Synergy-R | Microscopy, Imaging & Diffraction | 11 | 44 | 55 |
|
| 262 |
+
| CHEM-162 | Polarizing microscope | Evident / Olympus | BX53-P | Microscopy, Imaging & Diffraction | 14 | 47 | 34 |
|
| 263 |
+
| CHEM-163 | Microplate washer | Agilent BioTek | 405 TS (96-tube manifold) | Biochemical & Wet-Chemistry Assays | 3 | 36 | 26 |
|
| 264 |
+
| CHEM-164 | Gel electrophoresis system | Bio-Rad | Mini-PROTEAN Tetra + power supply | Biochemical & Wet-Chemistry Assays | 8 | 36 | 37 |
|
| 265 |
+
| CHEM-165 | Gel & blot imager | Thermo Fisher Scientific | iBright FL1500 | Biochemical & Wet-Chemistry Assays | 3 | 24 | 32 |
|
| 266 |
+
| CHEM-166 | CO₂ cell-culture incubator | Eppendorf | CellXpert C170i | Biochemical & Wet-Chemistry Assays | 5 | 57 | 46 |
|
| 267 |
+
| CHEM-167 | Real-time qPCR system | Bio-Rad | CFX Opus 96 | Biochemical & Wet-Chemistry Assays | 3 | 40 | 35 |
|
| 268 |
+
| CHEM-168 | Flow cytometer & cell sorter | BD Biosciences | FACSAria III | Biochemical & Wet-Chemistry Assays | 10 | 105 | 69 |
|
| 269 |
+
| CHEM-169 | Isothermal titration calorimeter | Malvern Panalytical | MicroCal PEAQ-ITC | Biochemical & Wet-Chemistry Assays | 5 | 58 | 45 |
|
| 270 |
+
| CHEM-170 | Surface plasmon resonance system | Cytiva | Biacore T200 | Biochemical & Wet-Chemistry Assays | 7 | 66 | 64 |
|
| 271 |
+
| CHEM-171 | Respirometric BOD system | WTW (Xylem) | OxiTop-i | Biochemical & Wet-Chemistry Assays | 30 | 45 | 33 |
|
| 272 |
+
| CHEM-172 | Segmented continuous-flow analyzer | SEAL Analytical | AA500 | Biochemical & Wet-Chemistry Assays | 11 | 29 | 40 |
|
| 273 |
+
| CHEM-173 | Multi-mode microplate reader | BMG LABTECH | CLARIOstar Plus | Biochemical & Wet-Chemistry Assays | 5 | 22 | 37 |
|
| 274 |
+
| CHEM-174 | Automated powder dosing system | METTLER TOLEDO | Quantos Q2 + XPE206DR | Automation & Gas/Liquid Supply | 3 | 20 | 12 |
|
| 275 |
+
| CHEM-175 | Automated liquid-handling robot | Opentrons | Flex (1-channel 5–1000 µL) | Automation & Gas/Liquid Supply | 4 | 15 | 10 |
|
| 276 |
+
| CHEM-176 | Automated microplate heat sealer | Azenta Life Sciences | Automated Roll Heat Sealer (a4S) | Automation & Gas/Liquid Supply | 1 | 22 | 9 |
|
| 277 |
+
| CHEM-177 | Automated tube decapper/recapper | Azenta Life Sciences | IntelliXcap S1 46-0001 | Automation & Gas/Liquid Supply | 8 | 13 | 6 |
|
| 278 |
+
| CHEM-178 | Lab sample-transfer robot arm | Brooks Automation | PreciseFlex 400 | Automation & Gas/Liquid Supply | 4 | 15 | 9 |
|
| 279 |
+
| CHEM-179 | 2D-barcode rack reader | Azenta Ziath | DP5 Mirage | Automation & Gas/Liquid Supply | 1 | 16 | 7 |
|
| 280 |
+
| CHEM-180 | Gas mass-flow controller | Alicat Scientific | MC, 1 SLPM full scale, Rev6 | Automation & Gas/Liquid Supply | 7 | 25 | 8 |
|
| 281 |
+
| CHEM-181 | Electronic back-pressure controller | Bronkhorst | EL-PRESS P-702CV | Automation & Gas/Liquid Supply | 1 | 18 | 9 |
|
| 282 |
+
| CHEM-182 | Multi-position gas stream-selection valve | VICI Valco | EUTA-2SD6MWE | Automation & Gas/Liquid Supply | 1 | 8 | 3 |
|
| 283 |
+
| CHEM-183 | Controlled evaporator & mixer | Bronkhorst | CEM W-202A | Automation & Gas/Liquid Supply | 1 | 20 | 21 |
|
| 284 |
+
| CHEM-184 | Programmable syringe pump | New Era Pump Systems | NE-1000 Multi-Phaser | Automation & Gas/Liquid Supply | 12 | 31 | 35 |
|
| 285 |
+
| CHEM-185 | Muffle furnace | Nabertherm | L 9/11/SKM | Lab Environment & Utilities | 7 | 12 | 10 |
|
| 286 |
+
| CHEM-186 | Tube furnace (controlled atmosphere) | Carbolite Gero | TF1 12/60/300 | Lab Environment & Utilities | 6 | 14 | 5 |
|
| 287 |
+
| CHEM-187 | Heating/refrigerated circulator | JULABO | CORIO CD-200F | Lab Environment & Utilities | 6 | 15 | 4 |
|
| 288 |
+
| CHEM-188 | Chemistry vacuum pumping unit | VACUUBRAND | PC 3001 VARIO select | Lab Environment & Utilities | 3 | 12 | 7 |
|
| 289 |
+
| CHEM-189 | Inert-atmosphere glovebox | Inert | PureLab HE 2GB | Lab Environment & Utilities | 2 | 27 | 10 |
|
| 290 |
+
| CHEM-190 | Lab ultrapure water system | ELGA LabWater | PURELAB flex 3 | Lab Environment & Utilities | 6 | 26 | 8 |
|
| 291 |
+
| CHEM-191 | Laboratory glassware washer | Miele | PLW 6111 | Lab Environment & Utilities | 7 | 20 | 8 |
|
| 292 |
+
| CHEM-192 | Steam autoclave | Tuttnauer | 3870ELV-D | Lab Environment & Utilities | 5 | 19 | 24 |
|
| 293 |
+
| CHEM-193 | Biological safety cabinet | Esco Lifesciences | AC2-4S8-TU | Lab Environment & Utilities | 9 | 30 | 24 |
|
| 294 |
+
| CHEM-194 | Helium leak detector | INFICON | UL1000 Fab | Lab Environment & Utilities | 6 | 28 | 26 |
|
| 295 |
+
| CHEM-195 | Trace-moisture dew-point transmitter | Vaisala | DMT152 | Lab Environment & Utilities | 1 | 25 | 21 |
|
| 296 |
+
| CHEM-196 | Laboratory hydrogen generator | PEAK Scientific | Precision Hydrogen Trace 500 | Lab Environment & Utilities | 2 | 23 | 21 |
|
| 297 |
+
| CHEM-197 | Ultra-low temperature freezer | Eppendorf | CryoCube F570n | Lab Environment & Utilities | 12 | 35 | 34 |
|
| 298 |
+
| CHEM-198 | Constant climate (T/RH) chamber | BINDER | KBF 115 | Lab Environment & Utilities | 3 | 33 | 33 |
|
| 299 |
+
| CHEM-199 | Chemical fume hood | Esco Lifesciences | Frontier Acela EFA-5UDUVW-9 | Lab Environment & Utilities | 11 | 32 | 32 |
|
| 300 |
+
| CHEM-200 | Solvent purification system | Inert | PureSolv MD 7 | Lab Environment & Utilities | 27 | 67 | 23 |
|
| 301 |
+
| — | Gas chromatograph (S/SL inlet + FID) | Agilent | 7890B | Chromatography & Electrophoresis | 50 | 0 | 16 |
|
| 302 |
+
| — | Analytical balance | OHAUS | Pioneer PX224/E | Basic Metrology & Sample Handling | 16 | 0 | 7 |
|
| 303 |
+
| — | Portable precision balance | OHAUS | Scout SPX2201 | Basic Metrology & Sample Handling | 15 | 0 | 7 |
|
| 304 |
+
|
| 305 |
+
</details>
|
| 306 |
+
|
| 307 |
+
## Quick start
|
| 308 |
+
|
| 309 |
+
**1. Get the data.** Everything (about 1.5 GB), or one instrument plus the code:
|
| 310 |
+
|
| 311 |
+
```bash
|
| 312 |
+
pip install -U huggingface_hub
|
| 313 |
+
hf download MBZUAI/ChemLab-Assets --repo-type dataset --local-dir ChemLab-Assets
|
| 314 |
+
pip install -r ChemLab-Assets/requirements.txt # NumPy 2.0–2.3, SciPy, Pillow, OpenCV, CoolProp, pytest
|
| 315 |
+
|
| 316 |
+
hf download MBZUAI/ChemLab-Assets --repo-type dataset --local-dir ChemLab-Assets \
|
| 317 |
+
--include "assets/expansion_batch05/t2_vacuum/esco_efa5uduvw/*" "scripts/*" "examples/*"
|
| 318 |
+
```
|
| 319 |
+
|
| 320 |
+
`catalog/catalog.csv` gives every instrument's folder, so any subset can be fetched the same way. Run the test suite
|
| 321 |
+
with `python -m pytest` from the dataset root (tests that re-hash cached third-party source files skip themselves,
|
| 322 |
+
because those files are not redistributed).
|
| 323 |
+
|
| 324 |
+
**2. Run an instrument.** The fume hood below starts with an uncalibrated airflow monitor. The robot raises the sash,
|
| 325 |
+
sees a low reading, measures the opening with an anemometer and calibrates the monitor. It never sees the true face
|
| 326 |
+
velocity (0.299 m/s), which is an evaluator-only slot. Full script: [`examples/quickstart_fume_hood.py`](examples/quickstart_fume_hood.py).
|
| 327 |
+
|
| 328 |
+
```python
|
| 329 |
+
from asset_runtime import esco_efa5uduvw as rt # run from the repo root with scripts/ on sys.path
|
| 330 |
+
|
| 331 |
+
hood = rt.EscoEfa5uduvwRuntime("hood_01")
|
| 332 |
+
hood.register_principal("lab", "evaluator") # sets up the world, sees hidden truth
|
| 333 |
+
hood.register_principal("robot", "agent") # sees what a policy may see
|
| 334 |
+
lab, robot = hood.session("lab"), hood.session("robot")
|
| 335 |
+
|
| 336 |
+
call(lab, "plant.configure", **rt.PLANT_EXAMPLE) # 295.15 K, 101.325 kPa
|
| 337 |
+
call(lab, "exhaust.configure", **rt.EXHAUST_EXAMPLE) # building exhaust, damper half open
|
| 338 |
+
call(robot, "sash.set", height_m=0.457) # raise to the 18-inch stop
|
| 339 |
+
call(lab, "sim.step", dt_s=30.0)
|
| 340 |
+
show("before calibration")
|
| 341 |
+
|
| 342 |
+
v = call(robot, "anemometer.measure")["face_velocity_m_s"]
|
| 343 |
+
call(robot, "monitor.calibrate", reference_m_s=round(v, 3))
|
| 344 |
+
call(lab, "sim.step", dt_s=10.0)
|
| 345 |
+
show("after calibration")
|
| 346 |
+
```
|
| 347 |
+
|
| 348 |
+
```text
|
| 349 |
+
before calibration reading 0.28 m/s alarm low
|
| 350 |
+
anemometer 0.309 m/s
|
| 351 |
+
after calibration reading 0.31 m/s alarm none
|
| 352 |
+
```
|
| 353 |
+
|
| 354 |
+
**3. Load it in a simulator.** URDF mesh paths are relative, so any URDF loader works from the asset folder. All 198
|
| 355 |
+
URDFs load with [yourdfpy](https://github.com/clemense/yourdfpy):
|
| 356 |
+
|
| 357 |
+
```python
|
| 358 |
+
import yourdfpy
|
| 359 |
+
hood = yourdfpy.URDF.load("assets/expansion_batch05/t2_vacuum/esco_efa5uduvw/model.urdf")
|
| 360 |
+
hood.update_cfg({"sash_joint": 0.45}) # raise the sash 450 mm
|
| 361 |
+
hood.show()
|
| 362 |
+
```
|
| 363 |
+
|
| 364 |
+
For Isaac Lab, convert `model.urdf` with the Isaac Lab URDF importer. GLB files keep the Z-up asset frame; rotate −90° about
|
| 365 |
+
X in Y-up viewers (the catalog's `glb_up` column says which files need it).
|
| 366 |
+
|
| 367 |
+
## What an asset contains
|
| 368 |
+
|
| 369 |
+
```text
|
| 370 |
+
assets/expansion_batch05/t2_vacuum/esco_efa5uduvw/
|
| 371 |
+
├── asset.contract.json # the contract: components, joints, state slots, capabilities, sources, limitations
|
| 372 |
+
├── model.glb # viewing (asset frame: Z up, front faces −Y)
|
| 373 |
+
├── model.urdf # simulators: links, joints with limits, primitive collision proxies
|
| 374 |
+
├── meshes/ # one OBJ + MTL per functional part (78 files here)
|
| 375 |
+
├── textures/ # panel, label and screen textures drawn for the model
|
| 376 |
+
├── model.blend # Blender source with named parts
|
| 377 |
+
├── geometry_manifest.json # parts, frames, dimensions and joint layout
|
| 378 |
+
├── collision_proxies.json # primitive colliders per part
|
| 379 |
+
├── instrument_model.json # runtime parameters (this instrument)
|
| 380 |
+
├── vapour_templates.json # reference data used by the runtime (53 vapour sources)
|
| 381 |
+
└── 说明.md # notes on the model and its data (Chinese)
|
| 382 |
+
|
| 383 |
+
scripts/asset_runtime/esco_efa5uduvw.py # the behaviour runtime
|
| 384 |
+
tests/test_asset_esco_efa5uduvw.py # its tests
|
| 385 |
+
```
|
| 386 |
+
|
| 387 |
+
The contract is the centre of each asset. It names every functional **component** and binds it to meshes and colliders;
|
| 388 |
+
lists **state slots** with type, unit, range, origin (setpoint, sensor, derived, process truth) and visibility (agent,
|
| 389 |
+
evaluator, debug); defines **capabilities** with JSON-Schema arguments, preconditions, state effects, declared errors and
|
| 390 |
+
a verification level for process, host, scene, robot and hardware; and records **mechanisms**, **ports**, **sources** and
|
| 391 |
+
**limitations**. The specification is in [`skills/chemistry-lab-assets/references/contract.md`](skills/chemistry-lab-assets/references/contract.md)
|
| 392 |
+
and the call protocol in [`protocol.md`](skills/chemistry-lab-assets/references/protocol.md) (both in Chinese); the
|
| 393 |
+
validator is `skills/chemistry-lab-assets/scripts/asset_tool.py`.
|
| 394 |
+
|
| 395 |
+
## Provenance, licences and limits
|
| 396 |
+
|
| 397 |
+
* **Sources.** Each state slot and capability lists the sources it rests on: manufacturer documents for dimensions,
|
| 398 |
+
ranges and limits; papers, standards and open databases for the measurements behind instrument outputs; explicit
|
| 399 |
+
assumptions where neither exists. Raw third-party documents (PDF manuals, brochures, application notes, papers,
|
| 400 |
+
spectra files, photos) are not redistributed; contracts keep the citations and derived values.
|
| 401 |
+
* **Licences.** Code is MIT ([`LICENSE`](LICENSE)). Models, contracts and data are CC BY-NC 4.0
|
| 402 |
+
([`LICENSE-ASSETS.md`](LICENSE-ASSETS.md)). Some data files carry their source's terms (CC BY-SA, non-commercial, or
|
| 403 |
+
rights reserved by the publisher); [`NOTICE.md`](NOTICE.md) lists every one with its source.
|
| 404 |
+
* **Trademarks.** Product and company names identify the modelled instrument only. This project is not affiliated
|
| 405 |
+
with or endorsed by any manufacturer.
|
| 406 |
+
* **Limits.** 786 capabilities are declared but marked unsupported. No capability claims robot-contact or
|
| 407 |
+
real-hardware validation. Treat the assets as documented, testable behaviour models for embodied-AI research, not
|
| 408 |
+
as certified digital twins.
|
| 409 |
+
* **Build records.** Contracts list the files of the original build (validation logs, review records, cached source
|
| 410 |
+
documents). Those are not part of the release; `release_manifest.json` says which artifacts ship.
|
| 411 |
+
|
| 412 |
+
## Citation
|
| 413 |
+
|
| 414 |
+
```bibtex
|
| 415 |
+
@misc{song2026chemlabassets,
|
| 416 |
+
title = {ChemLab-Assets: Simulation-Ready Chemistry Laboratory
|
| 417 |
+
Instruments with Executable Behaviour Contracts},
|
| 418 |
+
author = {Song, Zirui and Zhang, Jiadong and Zhang, Jiahao and
|
| 419 |
+
Chang, Xiaojun and Ma, Xiaosong and Chen, Xiuying},
|
| 420 |
+
year = {2026},
|
| 421 |
+
howpublished = {\url{https://huggingface.co/datasets/MBZUAI/ChemLab-Assets}},
|
| 422 |
+
note = {Dataset, release 1.0}
|
| 423 |
+
}
|
| 424 |
+
```
|
assets/initial_state.json
ADDED
|
@@ -0,0 +1,29 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"PX224E": {
|
| 3 |
+
"foot_front_left_joint": 0.0,
|
| 4 |
+
"foot_rear_left_joint": 0.0,
|
| 5 |
+
"foot_front_right_joint": 0.0,
|
| 6 |
+
"foot_rear_right_joint": 0.0,
|
| 7 |
+
"button_zero_joint": 0.0,
|
| 8 |
+
"button_print_joint": 0.0,
|
| 9 |
+
"button_function_joint": 0.0,
|
| 10 |
+
"button_tare_joint": 0.0,
|
| 11 |
+
"door_left_joint": 0.0,
|
| 12 |
+
"door_right_joint": 0.0,
|
| 13 |
+
"door_top_joint": 0.0,
|
| 14 |
+
"security_switch_joint": 0.0
|
| 15 |
+
},
|
| 16 |
+
"SPX2201": {
|
| 17 |
+
"foot_front_left_joint": 0.0,
|
| 18 |
+
"foot_rear_left_joint": 0.0,
|
| 19 |
+
"foot_front_right_joint": 0.0,
|
| 20 |
+
"foot_rear_right_joint": 0.0,
|
| 21 |
+
"button_zero_joint": 0.0,
|
| 22 |
+
"button_print_joint": 0.0,
|
| 23 |
+
"button_function_joint": 0.0,
|
| 24 |
+
"button_tare_joint": 0.0,
|
| 25 |
+
"transport_lock_joint": 1.5707963267948966,
|
| 26 |
+
"pan_joint": 0.0,
|
| 27 |
+
"security_switch_joint": 0.0
|
| 28 |
+
}
|
| 29 |
+
}
|
assets/physics_annotations.json
ADDED
|
The diff for this file is too large to render.
See raw diff
|
|
|
pytest.ini
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
[pytest]
|
| 2 |
+
testpaths = tests
|
| 3 |
+
pythonpath = . scripts
|
release_manifest.json
ADDED
|
The diff for this file is too large to render.
See raw diff
|
|
|
requirements.txt
ADDED
|
@@ -0,0 +1,5 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
numpy>=1.26
|
| 2 |
+
scipy>=1.11
|
| 3 |
+
pytest>=8 # tests
|
| 4 |
+
huggingface_hub>=0.24 # tools/download_assets.py
|
| 5 |
+
CoolProp==7.2.0 # only for the sft_sft110 and tousimis_autosamdri815 runtimes
|
scripts/balance_runtime.py
ADDED
|
@@ -0,0 +1,135 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Simulator-neutral, explicit weighing-state abstraction, SI inputs/outputs.
|
| 2 |
+
|
| 3 |
+
No contact solver is implemented here. Feed only the pan's supported load force,
|
| 4 |
+
excluding pan self-weight. The host simulator must own collisions, gravity,
|
| 5 |
+
force aggregation through containers, joint constraints, and object attachment.
|
| 6 |
+
"""
|
| 7 |
+
from dataclasses import dataclass
|
| 8 |
+
from decimal import Decimal, ROUND_HALF_UP
|
| 9 |
+
import math
|
| 10 |
+
|
| 11 |
+
@dataclass
|
| 12 |
+
class Balance:
|
| 13 |
+
capacity_kg: float
|
| 14 |
+
readability_kg: float
|
| 15 |
+
settling_s: float
|
| 16 |
+
analytical: bool=False
|
| 17 |
+
powered: bool=False
|
| 18 |
+
pan_installed: bool=True
|
| 19 |
+
pan_latched: bool=True
|
| 20 |
+
transport_unlocked: bool=True
|
| 21 |
+
security_locked: bool=False
|
| 22 |
+
calibrated: bool=False
|
| 23 |
+
g_cal: float=9.80665
|
| 24 |
+
tare_kg: float=0.0
|
| 25 |
+
zero_kg: float=0.0
|
| 26 |
+
gross_kg: float=0.0
|
| 27 |
+
stable: bool=False
|
| 28 |
+
elapsed_s: float=0.0
|
| 29 |
+
unit: str='g'
|
| 30 |
+
mode: str='weighing'
|
| 31 |
+
ports_connected: bool=False
|
| 32 |
+
door_fraction: float=0.0
|
| 33 |
+
tilt_rad: float=0.0
|
| 34 |
+
last_environment_valid: bool=False
|
| 35 |
+
|
| 36 |
+
@classmethod
|
| 37 |
+
def for_model(cls,model):
|
| 38 |
+
if model=='PX224E': return cls(.220,1e-7,3,True)
|
| 39 |
+
if model=='SPX2201': return cls(2.2,.0001,1,False)
|
| 40 |
+
raise ValueError('Unknown model')
|
| 41 |
+
|
| 42 |
+
def update(self,pan_load_force_N,dt_s,*,door_fraction=0.0,tilt_rad=0.0,vibration=False):
|
| 43 |
+
"""Force is net supported load along pan local +Z; no pan self-force.
|
| 44 |
+
|
| 45 |
+
Door and tilt stability gating is a conservative task rule, not a measured
|
| 46 |
+
transfer function. No invented airflow/noise accuracy is asserted.
|
| 47 |
+
"""
|
| 48 |
+
if not math.isfinite(pan_load_force_N) or not math.isfinite(dt_s) or dt_s<0:
|
| 49 |
+
raise ValueError('Finite force and nonnegative finite dt required')
|
| 50 |
+
m=pan_load_force_N/self.g_cal
|
| 51 |
+
changed=abs(m-self.gross_kg)>self.readability_kg/2
|
| 52 |
+
self.gross_kg=m; self.door_fraction=door_fraction; self.tilt_rad=tilt_rad
|
| 53 |
+
environmental_gate=(not self.analytical or door_fraction<=.01) and abs(tilt_rad)<=math.radians(.2) and not vibration
|
| 54 |
+
hardware_gate=self.powered and self.pan_installed and self.pan_latched and self.transport_unlocked
|
| 55 |
+
valid=environmental_gate and hardware_gate
|
| 56 |
+
if changed or not valid or not self.last_environment_valid: self.elapsed_s=0
|
| 57 |
+
else: self.elapsed_s+=dt_s
|
| 58 |
+
self.last_environment_valid=valid
|
| 59 |
+
self.stable=bool(hardware_gate and environmental_gate and self.elapsed_s>=self.settling_s and 0<=m<=self.capacity_kg)
|
| 60 |
+
return self.read()
|
| 61 |
+
|
| 62 |
+
def read(self):
|
| 63 |
+
if not self.powered: status='OFF'
|
| 64 |
+
elif not self.pan_installed: status='PAN_REMOVED'
|
| 65 |
+
elif not self.pan_latched: status='PAN_UNLATCHED'
|
| 66 |
+
elif not self.transport_unlocked: status='TRANSPORT_LOCKED'
|
| 67 |
+
elif self.gross_kg>self.capacity_kg: status='OVERLOAD'
|
| 68 |
+
elif self.gross_kg<0: status='UNDERLOAD'
|
| 69 |
+
elif not self.stable: status='UNSTABLE'
|
| 70 |
+
else: status='STABLE'
|
| 71 |
+
# Quantize to readability; do not interpret readability as accuracy.
|
| 72 |
+
x=Decimal(str(self.gross_kg))-Decimal(str(self.zero_kg))-Decimal(str(self.tare_kg))
|
| 73 |
+
step=Decimal(str(self.readability_kg))
|
| 74 |
+
value=float((x/step).quantize(Decimal('1'),rounding=ROUND_HALF_UP)*step)
|
| 75 |
+
observable=status in ['STABLE','UNSTABLE']
|
| 76 |
+
scale=1000 if self.unit=='g' else 1
|
| 77 |
+
return {'status':status,'stable':self.stable,'value':value*scale if observable else None,
|
| 78 |
+
'unit':self.unit,'net_kg':value if observable else None,'gross_kg':self.gross_kg,
|
| 79 |
+
'tare_kg':self.tare_kg,'calibrated':self.calibrated,
|
| 80 |
+
'task_ready':status=='STABLE' and self.calibrated}
|
| 81 |
+
|
| 82 |
+
def press(self,key,hold_s=.1):
|
| 83 |
+
if hold_s<0: raise ValueError('negative hold time')
|
| 84 |
+
long=hold_s>=2
|
| 85 |
+
if key=='zero':
|
| 86 |
+
if long: self.powered=False; self.stable=False; self.elapsed_s=0
|
| 87 |
+
elif not self.powered: self.powered=True; self.elapsed_s=0; self.stable=False
|
| 88 |
+
elif self.stable:
|
| 89 |
+
# 2% zero capture limit is an explicit task assumption, not a vendor value.
|
| 90 |
+
if abs(self.gross_kg)>.02*self.capacity_kg: raise ValueError('Outside assumed zero capture range')
|
| 91 |
+
self.zero_kg=self.gross_kg; self.tare_kg=0
|
| 92 |
+
else: raise ValueError('Wait for stable load')
|
| 93 |
+
elif not self.powered: raise ValueError('Power is off')
|
| 94 |
+
elif key=='tare':
|
| 95 |
+
if long: return {'event':'open_menu','security_locked':self.security_locked}
|
| 96 |
+
if not self.stable: raise ValueError('Wait for stable load')
|
| 97 |
+
self.tare_kg=self.gross_kg-self.zero_kg
|
| 98 |
+
elif key=='print':
|
| 99 |
+
if long: self.unit='kg' if self.unit=='g' else 'g'
|
| 100 |
+
else: return {'event':'print','transmitted':self.ports_connected,'reading':self.read()}
|
| 101 |
+
elif key=='function':
|
| 102 |
+
return {'event':'mode_menu' if long else 'application_function','mode':self.mode,'implemented':self.mode=='weighing'}
|
| 103 |
+
else: raise ValueError('Unknown key')
|
| 104 |
+
return self.read()
|
| 105 |
+
|
| 106 |
+
def calibrate_span(self,known_mass_kg,measured_load_force_N):
|
| 107 |
+
"""Simplified one-point force gain calibration, not full vendor procedure."""
|
| 108 |
+
if not self.powered or not self.stable or self.security_locked:
|
| 109 |
+
raise ValueError('Calibration requires stable powered balance with security unlocked')
|
| 110 |
+
if not 0<known_mass_kg<=self.capacity_kg or measured_load_force_N<=0:
|
| 111 |
+
raise ValueError('Invalid calibration load')
|
| 112 |
+
self.g_cal=measured_load_force_N/known_mass_kg
|
| 113 |
+
self.tare_kg=0; self.zero_kg=0; self.calibrated=True; self.elapsed_s=0; self.stable=False
|
| 114 |
+
|
| 115 |
+
def remove_pan(self,unlock_angle_rad=0.0):
|
| 116 |
+
if self.powered or abs(self.gross_kg)>self.readability_kg:
|
| 117 |
+
raise ValueError('Power off and unload before pan removal')
|
| 118 |
+
if not self.analytical and unlock_angle_rad>-math.radians(20)+1e-9:
|
| 119 |
+
raise ValueError('Rotate clockwise to assumed -20 degree bayonet release first')
|
| 120 |
+
self.pan_installed=False; self.pan_latched=False; self.stable=False
|
| 121 |
+
return {'event':'release_attachment','free_dof':6}
|
| 122 |
+
|
| 123 |
+
def install_pan(self,latched=True):
|
| 124 |
+
self.pan_installed=True; self.pan_latched=latched; self.stable=False; self.elapsed_s=0
|
| 125 |
+
|
| 126 |
+
def set_transport_lock(self,angle_rad):
|
| 127 |
+
if self.analytical: raise ValueError('PX224E has no modeled user transport lock')
|
| 128 |
+
if self.pan_installed: raise ValueError('Transport lock is beneath pan; remove pan first')
|
| 129 |
+
if not 0<=angle_rad<=math.pi/2: raise ValueError('Manufacturer range is 0 to 90 degrees')
|
| 130 |
+
self.transport_unlocked=abs(angle_rad-math.pi/2)<1e-6
|
| 131 |
+
self.stable=False; self.elapsed_s=0
|
| 132 |
+
|
| 133 |
+
def foot_extension_m(theta_rad,pitch_m_per_turn=.001):
|
| 134 |
+
if abs(theta_rad)>4*math.pi: raise ValueError('Outside assumed leveling range')
|
| 135 |
+
return pitch_m_per_turn*theta_rad/(2*math.pi)
|
scripts/basic40_runtime.py
ADDED
|
@@ -0,0 +1,841 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Synthetic, simulator-neutral runtime for the first four basic-40 assets.
|
| 2 |
+
|
| 3 |
+
Only LabHost advances the common clock. LabSession identities are assigned by
|
| 4 |
+
the host, never taken from a request's arguments. This is an API access filter,
|
| 5 |
+
NOT a sandbox against Python introspection, shared memory or filesystem access.
|
| 6 |
+
Deploy the host in a separate trusted process before giving an untrusted agent
|
| 7 |
+
filesystem/code execution access. No real instrument or robot driver is present.
|
| 8 |
+
|
| 9 |
+
Scene commands require a synchronous, atomic scene_adapter callback. It receives
|
| 10 |
+
(instance_id, updates), with SI-valued state IDs. Success means that callback
|
| 11 |
+
returned; evaluated Blender poses require separate backend verification.
|
| 12 |
+
"""
|
| 13 |
+
from __future__ import annotations
|
| 14 |
+
|
| 15 |
+
import argparse
|
| 16 |
+
import copy
|
| 17 |
+
import hashlib
|
| 18 |
+
import json
|
| 19 |
+
import math
|
| 20 |
+
import platform
|
| 21 |
+
import threading
|
| 22 |
+
from dataclasses import dataclass, field
|
| 23 |
+
from datetime import datetime, timezone
|
| 24 |
+
from pathlib import Path
|
| 25 |
+
from typing import Any, Callable
|
| 26 |
+
|
| 27 |
+
PROTOCOL_VERSION = "1.0.0"
|
| 28 |
+
RPM_TO_RAD_S = 2 * math.pi / 60
|
| 29 |
+
|
| 30 |
+
|
| 31 |
+
def _slot(unit, origin, visibility="agent", access="read_only", capability=None, parameter=None):
|
| 32 |
+
return {"unit": unit, "origin": origin, "visibility": visibility, "access": access,
|
| 33 |
+
"write_via": None if not capability else {"capability_id": capability, "parameter": parameter}}
|
| 34 |
+
|
| 35 |
+
|
| 36 |
+
COMMON_SLOTS = {
|
| 37 |
+
"power.enabled": _slot("1", "setpoint", access="read_write", capability="power.set", parameter="enabled"),
|
| 38 |
+
}
|
| 39 |
+
THERMAL_SLOTS = {
|
| 40 |
+
"thermal.target_k": _slot("K", "setpoint", access="read_write", capability="thermal.set_temperature", parameter="temperature_K"),
|
| 41 |
+
"thermal.temperature_k": _slot("K", "process_truth", "debug"),
|
| 42 |
+
"thermal.indicated_temperature_k": _slot("K", "derived"),
|
| 43 |
+
}
|
| 44 |
+
ASSET_SPECS: dict[str, dict[str, Any]] = {
|
| 45 |
+
"instrument.ika_rct_digital": {
|
| 46 |
+
"catalog_id": "CHEM-008", "model": "IKA RCT digital", "asset_version": "1.0.0",
|
| 47 |
+
"capabilities": ["power.set", "thermal.set_temperature", "stirring.set_speed"],
|
| 48 |
+
"state_slots": {**COMMON_SLOTS, **THERMAL_SLOTS,
|
| 49 |
+
"stirring.target_rad_s": _slot("rad/s", "setpoint", access="read_write", capability="stirring.set_speed", parameter="speed_rad_s"),
|
| 50 |
+
"stirring.speed_rad_s": _slot("rad/s", "process_truth", "debug"),
|
| 51 |
+
"stirring.indicated_speed_rad_s": _slot("rad/s", "derived"),
|
| 52 |
+
"stirring.angle_rad": _slot("rad", "process_truth", "debug")},
|
| 53 |
+
"parameters": {
|
| 54 |
+
"heater_power_W": {"value": 600.0, "evidence": "catalog", "source": "CHEM-008 specification"},
|
| 55 |
+
"maximum_temperature_K": {"value": 583.15, "evidence": "catalog", "source": "CHEM-008: 310 deg C"},
|
| 56 |
+
"minimum_speed_rad_s": {"value": 50 * RPM_TO_RAD_S, "evidence": "catalog", "source": "CHEM-008: 50 rpm"},
|
| 57 |
+
"maximum_speed_rad_s": {"value": 1500 * RPM_TO_RAD_S, "evidence": "catalog", "source": "CHEM-008: 1500 rpm"},
|
| 58 |
+
"speed_increment_rad_s": {"value": 10 * RPM_TO_RAD_S, "evidence": "catalog", "source": "CHEM-008: 10 rpm; grid starts at 50 rpm"},
|
| 59 |
+
"thermal_capacity_J_K": {"value": 1800.0, "evidence": "assumption", "source": "Empty plate lumped model; uncalibrated"},
|
| 60 |
+
"heat_loss_W_K": {"value": 1.2, "evidence": "assumption", "source": "Empty plate convection/loss approximation"},
|
| 61 |
+
"stirring_time_constant_s": {"value": 1.5, "evidence": "assumption", "source": "First-order rotor response; not vendor response time"},
|
| 62 |
+
},
|
| 63 |
+
},
|
| 64 |
+
"instrument.binder_fd56": {
|
| 65 |
+
"catalog_id": "CHEM-011", "model": "BINDER FD 56", "asset_version": "1.0.0",
|
| 66 |
+
"capabilities": ["power.set", "thermal.set_temperature", "scene.set_door"],
|
| 67 |
+
"state_slots": {**COMMON_SLOTS, **THERMAL_SLOTS,
|
| 68 |
+
"door.angle_rad": _slot("rad", "scene", access="read_write", capability="scene.set_door", parameter="angle_rad")},
|
| 69 |
+
"parameters": {
|
| 70 |
+
"heater_power_W": {"value": 1100.0, "evidence": "catalog", "source": "CHEM-011 specification"},
|
| 71 |
+
"minimum_target_above_ambient_K": {"value": 10.0, "evidence": "catalog", "source": "CHEM-011: ambient + 10 deg C"},
|
| 72 |
+
"maximum_temperature_K": {"value": 573.15, "evidence": "catalog", "source": "CHEM-011: 300 deg C"},
|
| 73 |
+
"maximum_door_angle_rad": {"value": math.radians(100), "evidence": "assumption", "source": "Scene articulation limit 100 deg; not measured manufacturer travel"},
|
| 74 |
+
"thermal_capacity_J_K": {"value": 15000.0, "evidence": "assumption", "source": "Empty chamber effective heat capacity; no sample drying chemistry"},
|
| 75 |
+
"heat_loss_W_K": {"value": 2.5, "evidence": "assumption", "source": "Closed chamber lumped loss"},
|
| 76 |
+
"door_open_loss_W_K": {"value": 20.0, "evidence": "assumption", "source": "Additional loss at fully open door"},
|
| 77 |
+
"door_open_heater_fraction": {"value": 0.25, "evidence": "assumption", "source": "Simulation reduction at full opening; NOT a manufacturer interlock"},
|
| 78 |
+
},
|
| 79 |
+
},
|
| 80 |
+
"instrument.ne1000_bd10ml": {
|
| 81 |
+
"catalog_id": "CHEM-184", "model": "New Era NE-1000, B-D 10 mL syringe", "asset_version": "1.0.0",
|
| 82 |
+
"capabilities": ["power.set", "pumping.set_flow_rate", "pumping.set_direction", "pumping.start", "pumping.stop"],
|
| 83 |
+
"state_slots": {**COMMON_SLOTS,
|
| 84 |
+
"pumping.flow_rate_m3_s": _slot("m^3/s", "setpoint", access="read_write", capability="pumping.set_flow_rate", parameter="flow_rate_m3_s"),
|
| 85 |
+
"pumping.running": _slot("1", "derived"),
|
| 86 |
+
"pumping.direction": _slot("1", "setpoint", access="read_write", capability="pumping.set_direction", parameter="direction"),
|
| 87 |
+
"pumping.transferred_volume_m3": _slot("m^3", "process_truth", "debug"),
|
| 88 |
+
"pumping.plunger_displacement_m": _slot("m", "derived")},
|
| 89 |
+
"parameters": {
|
| 90 |
+
"maximum_flow_rate_m3_s": {"value": 500.4e-6 / 3600, "evidence": "public_document", "source": "NE-1000 manual 1200-01, 2016-04-06, p50: B-D 10 mL syringe 500.4 mL/h"},
|
| 91 |
+
"minimum_flow_rate_m3_s": {"value": 6.876e-9 / 3600, "evidence": "public_document", "source": "NE-1000 manual 1200-01, 2016-04-06, p50: B-D 10 mL syringe 6.876 uL/h"},
|
| 92 |
+
"syringe_diameter_m": {"value": .01443, "evidence": "public_document", "source": "NE-1000 manual 1200-01, 2016-04-06, p50: B-D 10 mL inner diameter 14.43 mm; supplemental configuration choice"},
|
| 93 |
+
"syringe_stroke_m": {"value": 10e-6 / (math.pi * .01443**2 / 4), "evidence": "assumption", "source": "Ideal 10 mL cylinder travel V/A; not a measured manufacturer stroke"},
|
| 94 |
+
},
|
| 95 |
+
},
|
| 96 |
+
"instrument.esco_efa5": {
|
| 97 |
+
"catalog_id": "CHEM-199", "model": "Esco EFA-5UDUVW-9", "asset_version": "1.0.0",
|
| 98 |
+
"capabilities": ["power.set", "scene.set_sash"],
|
| 99 |
+
"state_slots": {**COMMON_SLOTS,
|
| 100 |
+
"sash.opening_m": _slot("m", "scene", access="read_write", capability="scene.set_sash", parameter="opening_m"),
|
| 101 |
+
"ventilation.external_exhaust_m3_s": _slot("m^3/s", "derived"),
|
| 102 |
+
"ventilation.face_velocity_m_s": _slot("m/s", "derived")},
|
| 103 |
+
"parameters": {
|
| 104 |
+
"opening_width_m": {"value": 1.301, "evidence": "public_document", "source": "Esco EFA-5UDUVW-9 technical specifications: clear opening width 1301 mm"},
|
| 105 |
+
"maximum_sash_opening_m": {"value": .670, "evidence": "public_document", "source": "Esco EFA-5UDUVW-9 technical specifications: maximum sash opening 670 mm"},
|
| 106 |
+
},
|
| 107 |
+
},
|
| 108 |
+
}
|
| 109 |
+
|
| 110 |
+
CAPABILITY_ARGUMENTS = {
|
| 111 |
+
"power.set": {"enabled": {"type": "boolean"}},
|
| 112 |
+
"thermal.set_temperature": {"temperature_K": {"type": "number", "x-unit": "K"}},
|
| 113 |
+
"stirring.set_speed": {"speed_rad_s": {"type": "number", "x-unit": "rad/s"}},
|
| 114 |
+
"scene.set_door": {"angle_rad": {"type": "number", "x-unit": "rad"}},
|
| 115 |
+
"pumping.set_flow_rate": {"flow_rate_m3_s": {"type": "number", "x-unit": "m^3/s"}},
|
| 116 |
+
"pumping.set_direction": {"direction": {"type": "string", "enum": ["infuse", "withdraw"]}},
|
| 117 |
+
"pumping.start": {}, "pumping.stop": {},
|
| 118 |
+
"scene.set_sash": {"opening_m": {"type": "number", "x-unit": "m"}},
|
| 119 |
+
}
|
| 120 |
+
CAPABILITY_RESULT_SLOT = {
|
| 121 |
+
"power.set": ("enabled", "power.enabled"),
|
| 122 |
+
"thermal.set_temperature": ("setpoint_K", "thermal.target_k"),
|
| 123 |
+
"stirring.set_speed": ("setpoint_rad_s", "stirring.target_rad_s"),
|
| 124 |
+
"scene.set_door": ("angle_rad", "door.angle_rad"),
|
| 125 |
+
"pumping.set_flow_rate": ("flow_rate_m3_s", "pumping.flow_rate_m3_s"),
|
| 126 |
+
"pumping.set_direction": ("direction", "pumping.direction"),
|
| 127 |
+
"pumping.start": ("running", "pumping.running"),
|
| 128 |
+
"pumping.stop": ("running", "pumping.running"),
|
| 129 |
+
"scene.set_sash": ("opening_m", "sash.opening_m"),
|
| 130 |
+
}
|
| 131 |
+
|
| 132 |
+
DECLARED_CAPABILITIES = {"instrument.ne1000_bd10ml": {
|
| 133 |
+
"pumping.program": {"availability": "declared", "kind": "configuration",
|
| 134 |
+
"description_zh": "NE-1000 41 阶段程序功能尚未实现;本接口不接受或执行程序。下述结构仅为本项目未来仿真提案,不是厂家串口格式。",
|
| 135 |
+
"input_schema": {"type": "object", "properties": {"phases": {"type": "array", "minItems": 1, "maxItems": 41,
|
| 136 |
+
"items": {"type": "object", "properties": {
|
| 137 |
+
"direction": {"type": "string", "enum": ["infuse", "withdraw"]},
|
| 138 |
+
"flow_rate_m3_s": {"type": "number", "exclusiveMinimum": 0, "x-unit": "m^3/s"},
|
| 139 |
+
"duration_s": {"type": "number", "exclusiveMinimum": 0, "x-unit": "s"}},
|
| 140 |
+
"required": ["direction", "flow_rate_m3_s", "duration_s"], "additionalProperties": False}}},
|
| 141 |
+
"required": ["phases"], "additionalProperties": False},
|
| 142 |
+
"output_schema": {"type": "object", "properties": {}, "additionalProperties": False},
|
| 143 |
+
"example_arguments": [{"phases": [{"direction": "infuse", "flow_rate_m3_s": 1e-9, "duration_s": 10}]}],
|
| 144 |
+
"state_effects": [], "observes": [], "binding": None}
|
| 145 |
+
}}
|
| 146 |
+
|
| 147 |
+
HOST_CAPABILITIES = {
|
| 148 |
+
"sim.step": {"kind": "simulation", "visibility": "trusted_host_only",
|
| 149 |
+
"scope": "All registered instances in this LabHost share one world clock",
|
| 150 |
+
"input_schema": {"type": "object", "properties": {"dt_s": {"type": "number", "minimum": 0,
|
| 151 |
+
"maximum": 3600, "x-unit": "s"}}, "required": ["dt_s"], "additionalProperties": False},
|
| 152 |
+
"binding": "basic40_runtime.LabHost.step(dt_s)",
|
| 153 |
+
"completion_criterion": "Common host time equals previous time + dt_s; all process instances advanced under one world lock",
|
| 154 |
+
"partial_failure": "SceneSynchronizationError means process and time advanced; failed scene updates remain in trusted diagnostics"},
|
| 155 |
+
"host.configure_syringe": {"kind": "configuration", "visibility": "trusted_host_only", "binding": "LabHost.configure_syringe"},
|
| 156 |
+
"host.connect_pump": {"kind": "configuration", "visibility": "trusted_host_only", "binding": "LabHost.connect_pump",
|
| 157 |
+
"constraints": "Each syringe vessel belongs exclusively to one pump and cannot be another pump's external vessel; external collection vessels may be shared. All checks precede connection, position and revision changes."},
|
| 158 |
+
"host.set_external_exhaust": {"kind": "configuration", "visibility": "trusted_host_only", "binding": "LabHost.set_external_exhaust"},
|
| 159 |
+
"host.sync_scene": {"kind": "configuration", "visibility": "trusted_host_only", "binding": "LabHost.sync_scene"},
|
| 160 |
+
}
|
| 161 |
+
|
| 162 |
+
|
| 163 |
+
def export_contract_metadata():
|
| 164 |
+
"""Type metadata only: no instance values, identities, samples or task state.
|
| 165 |
+
|
| 166 |
+
capability.output_schema describes the protocol envelope's result member.
|
| 167 |
+
All other envelope fields follow Chemistry Lab protocol 1.0.0.
|
| 168 |
+
"""
|
| 169 |
+
assets = copy.deepcopy(ASSET_SPECS)
|
| 170 |
+
summaries = {"power.set": "设置本机供电;风柜仅本机照明,不改变外部排风量",
|
| 171 |
+
"thermal.set_temperature": "写入温度目标;实际温度仅随宿主时间演化",
|
| 172 |
+
"stirring.set_speed": "设置搅拌角速度;50–1500 rpm 按 10 rpm 递增,0 单独表示停止目标",
|
| 173 |
+
"scene.set_door": "经场景适配器设置门转角;无机器人抓取或碰撞求解",
|
| 174 |
+
"pumping.set_flow_rate": "设置所选 B-D 10 mL 注射器的正值体积流率",
|
| 175 |
+
"pumping.set_direction": "停泵时设置注入或回抽方向",
|
| 176 |
+
"pumping.start": "启动受行程与容器容量限制的输液;本调用不转移物质",
|
| 177 |
+
"pumping.stop": "停止后续输液;保留已经转移的物质",
|
| 178 |
+
"scene.set_sash": "经场景适配器设置视窗垂直开口并派生估计面风速"}
|
| 179 |
+
examples = {"power.set": {"enabled": True}, "thermal.set_temperature": {"temperature_K": 333.15},
|
| 180 |
+
"stirring.set_speed": {"speed_rad_s": 300 * RPM_TO_RAD_S}, "scene.set_door": {"angle_rad": .5},
|
| 181 |
+
"pumping.set_flow_rate": {"flow_rate_m3_s": 1e-9}, "pumping.set_direction": {"direction": "infuse"},
|
| 182 |
+
"pumping.start": {}, "pumping.stop": {}, "scene.set_sash": {"opening_m": .457}}
|
| 183 |
+
for type_id, spec in assets.items():
|
| 184 |
+
for sid, slot in spec["state_slots"].items():
|
| 185 |
+
if sid in ("power.enabled", "pumping.running"):
|
| 186 |
+
slot["value_schema"] = {"type": "boolean"}
|
| 187 |
+
elif sid == "pumping.direction":
|
| 188 |
+
slot["value_schema"] = {"type": "string", "enum": ["infuse", "withdraw"]}
|
| 189 |
+
elif sid == "ventilation.face_velocity_m_s":
|
| 190 |
+
slot["value_schema"] = {"anyOf": [{"type": "number", "minimum": 0}, {"type": "null"}]}
|
| 191 |
+
else:
|
| 192 |
+
slot["value_schema"] = {"type": "number"}
|
| 193 |
+
slot["read_binding"] = f"LabSession.read(instance_id=..., state_ids=['{sid}'])"
|
| 194 |
+
slot["sampling"] = {"mode": "instant", "time_domain": "simulation", "window": None}
|
| 195 |
+
slot["reference_conditions"] = "Actual room conditions supplied by host; no standard-state conversion" if sid == "ventilation.external_exhaust_m3_s" else None
|
| 196 |
+
if slot["origin"] == "derived":
|
| 197 |
+
slot["observation_note_zh"] = "明确的理想化模型观测,quality=estimated;不是厂家真实传感器读数或精度声明"
|
| 198 |
+
caps = {}
|
| 199 |
+
for capability in spec["capabilities"]:
|
| 200 |
+
args = copy.deepcopy(CAPABILITY_ARGUMENTS[capability])
|
| 201 |
+
if capability == "thermal.set_temperature":
|
| 202 |
+
args["temperature_K"].update(minimum=283.15 if type_id.endswith("binder_fd56") else 273.15,
|
| 203 |
+
maximum=spec["parameters"]["maximum_temperature_K"]["value"],
|
| 204 |
+
description="Actual lower bound is host ambient + 10 K for FD 56, or host ambient for RCT")
|
| 205 |
+
elif capability == "stirring.set_speed":
|
| 206 |
+
args["speed_rad_s"].update(minimum=0, maximum=1500 * RPM_TO_RAD_S,
|
| 207 |
+
description="Allowed: 0, or (50 + 10*n) rpm converted to rad/s, n=0..145")
|
| 208 |
+
elif capability == "scene.set_door":
|
| 209 |
+
args["angle_rad"].update(minimum=0, maximum=spec["parameters"]["maximum_door_angle_rad"]["value"])
|
| 210 |
+
elif capability == "scene.set_sash":
|
| 211 |
+
args["opening_m"].update(minimum=0, maximum=spec["parameters"]["maximum_sash_opening_m"]["value"])
|
| 212 |
+
elif capability == "pumping.set_flow_rate":
|
| 213 |
+
args["flow_rate_m3_s"].update(minimum=spec["parameters"]["minimum_flow_rate_m3_s"]["value"],
|
| 214 |
+
maximum=spec["parameters"]["maximum_flow_rate_m3_s"]["value"],
|
| 215 |
+
**{"x-reference-conditions": "Liquid geometric displacement at modeled room conditions; no gas reference state"})
|
| 216 |
+
output_key, sid = CAPABILITY_RESULT_SLOT[capability]
|
| 217 |
+
out_value = copy.deepcopy(spec["state_slots"][sid]["value_schema"])
|
| 218 |
+
if out_value.get("type") == "number":
|
| 219 |
+
out_value["x-unit"] = spec["state_slots"][sid]["unit"]
|
| 220 |
+
effects = [{"state_id": sid, "timing": "immediate", "description_zh": summaries[capability]}]
|
| 221 |
+
if capability in ("thermal.set_temperature", "scene.set_door") or (capability == "power.set" and "thermal.target_k" in spec["state_slots"]):
|
| 222 |
+
effects += [{"state_id": key, "timing": "on_step", "description_zh": "空载集中参数热模型及理想化显示"}
|
| 223 |
+
for key in ("thermal.temperature_k", "thermal.indicated_temperature_k")]
|
| 224 |
+
if capability == "stirring.set_speed" or (capability == "power.set" and "stirring.target_rad_s" in spec["state_slots"]):
|
| 225 |
+
effects += [{"state_id": key, "timing": "on_step", "description_zh": "有限响应时间的速度及其时间积分角度"}
|
| 226 |
+
for key in ("stirring.speed_rad_s", "stirring.indicated_speed_rad_s", "stirring.angle_rad")]
|
| 227 |
+
if capability in ("pumping.start", "pumping.set_flow_rate", "pumping.set_direction"):
|
| 228 |
+
effects += [{"state_id": key, "timing": "on_step", "description_zh": "输液事务后更新累计体积、真实几何行程与边界停止状态"}
|
| 229 |
+
for key in ("pumping.transferred_volume_m3", "pumping.plunger_displacement_m", "pumping.running")]
|
| 230 |
+
if capability == "power.set" and "pumping.running" in spec["state_slots"]:
|
| 231 |
+
effects.append({"state_id": "pumping.running", "timing": "immediate", "description_zh": "断电时停止输液"})
|
| 232 |
+
if capability == "scene.set_sash":
|
| 233 |
+
effects.append({"state_id": "ventilation.face_velocity_m_s", "timing": "immediate", "description_zh": "外部Q/(1.301×开口)估计;开口为0时不可用,不能用于安全判断"})
|
| 234 |
+
caps[capability] = {"availability": "implemented", "visibility": "agent",
|
| 235 |
+
"kind": "simulation" if capability.startswith("scene.") else "device_command",
|
| 236 |
+
"description_zh": summaries[capability],
|
| 237 |
+
"input_schema": {"type": "object", "properties": args, "required": list(args), "additionalProperties": False},
|
| 238 |
+
"output_schema": {"type": "object", "properties": {output_key: out_value}, "required": [output_key], "additionalProperties": False},
|
| 239 |
+
"state_effects": effects, "observes": [sid], "example_arguments": [examples[capability]],
|
| 240 |
+
"binding": "basic40_runtime.LabSession.invoke(instance_id=..., capability_id='" + capability + "', arguments=..., request_id=...)",
|
| 241 |
+
"scene_backend_required": capability.startswith("scene."),
|
| 242 |
+
"preconditions_zh": (["本机已上电"] if capability in ("thermal.set_temperature", "stirring.set_speed", "pumping.set_flow_rate", "pumping.set_direction", "pumping.start") else [])
|
| 243 |
+
+ (["目标≥宿主环境温度" + ("+10 K" if type_id.endswith("binder_fd56") else "")] if capability == "thermal.set_temperature" else [])
|
| 244 |
+
+ (["非零值必须为从50 rpm起每10 rpm递增的离散值"] if capability == "stirring.set_speed" else [])
|
| 245 |
+
+ (["方向只能在停泵时改变"] if capability == "pumping.set_direction" else [])
|
| 246 |
+
+ (["宿主已配置固定注射器、连接液体容器并设置正流量;供体非空、受体未满、剩余行程为正"] if capability == "pumping.start" else [])
|
| 247 |
+
+ (["宿主注册了实际场景回调"] if capability.startswith("scene.") else []),
|
| 248 |
+
"completion_criterion_zh": "返回值中的设定或开关状态已写入;过程演化仅发生于宿主step,succeeded不代表达到温度或完成输液"}
|
| 249 |
+
spec["capabilities"] = caps
|
| 250 |
+
spec["declared_capabilities"] = copy.deepcopy(DECLARED_CAPABILITIES.get(type_id, {}))
|
| 251 |
+
return {"asset_types": assets, "host_capabilities": copy.deepcopy(HOST_CAPABILITIES),
|
| 252 |
+
"result_schema_scope": "Each capability output_schema describes response.result, not the entire standard protocol envelope",
|
| 253 |
+
"trusted_scene_callback": "__call__(instance_id: str, updates: dict[state_id, value]); all state values use SI"}
|
| 254 |
+
|
| 255 |
+
|
| 256 |
+
def _number(value: Any) -> bool:
|
| 257 |
+
if type(value) not in (int, float):
|
| 258 |
+
return False
|
| 259 |
+
try:
|
| 260 |
+
return math.isfinite(value)
|
| 261 |
+
except (OverflowError, TypeError):
|
| 262 |
+
return False
|
| 263 |
+
|
| 264 |
+
|
| 265 |
+
@dataclass
|
| 266 |
+
class _Instance:
|
| 267 |
+
instance_id: str
|
| 268 |
+
asset_type_id: str
|
| 269 |
+
state: dict[str, Any]
|
| 270 |
+
revision: int = 0
|
| 271 |
+
syringe: dict[str, Any] | None = None
|
| 272 |
+
connections: tuple[str, str] | None = None
|
| 273 |
+
|
| 274 |
+
|
| 275 |
+
@dataclass
|
| 276 |
+
class _Vessel:
|
| 277 |
+
volume_m3: float
|
| 278 |
+
capacity_m3: float
|
| 279 |
+
species_mass_kg: dict[str, float] = field(default_factory=dict)
|
| 280 |
+
|
| 281 |
+
|
| 282 |
+
class SceneSynchronizationError(RuntimeError):
|
| 283 |
+
"""World time/process advanced, but at least one backend sync failed."""
|
| 284 |
+
|
| 285 |
+
|
| 286 |
+
class LabHost:
|
| 287 |
+
"""Trusted host API: registration, identity, materials, scene and world time.
|
| 288 |
+
|
| 289 |
+
Do not expose this object to an untrusted agent. Supply a LabSession or a
|
| 290 |
+
remote wrapper with authenticated host-side principal selection instead.
|
| 291 |
+
Deduplication is in-memory and intentionally makes no restart guarantee.
|
| 292 |
+
"""
|
| 293 |
+
def __init__(self, *, ambient_temperature_K=293.15,
|
| 294 |
+
scene_adapter: Callable[[str, dict[str, Any]], None] | None = None):
|
| 295 |
+
if not _number(ambient_temperature_K) or not 273.15 <= ambient_temperature_K <= 313.15:
|
| 296 |
+
raise ValueError("Ambient temperature must be finite and within the assumed 273.15–313.15 K model range")
|
| 297 |
+
self.ambient_temperature_K = float(ambient_temperature_K)
|
| 298 |
+
self.time_s = 0.0
|
| 299 |
+
self.scene_adapter = scene_adapter
|
| 300 |
+
self._instances: dict[str, _Instance] = {}
|
| 301 |
+
self._vessels: dict[str, _Vessel] = {}
|
| 302 |
+
self._principals: dict[str, tuple[str, frozenset[str] | None]] = {}
|
| 303 |
+
self._requests: dict[tuple[str, str, str], tuple[str, dict[str, Any]]] = {}
|
| 304 |
+
self._logs: dict[str, list[dict[str, Any]]] = {}
|
| 305 |
+
self._transactions: list[dict[str, Any]] = []
|
| 306 |
+
self._scene_faults: list[dict[str, Any]] = []
|
| 307 |
+
self._lock = threading.RLock()
|
| 308 |
+
|
| 309 |
+
def create_instance(self, instance_id: str, asset_type_id: str):
|
| 310 |
+
with self._lock:
|
| 311 |
+
if not isinstance(instance_id, str) or not instance_id or instance_id in self._instances:
|
| 312 |
+
raise ValueError("Instance ID must be unique and nonempty")
|
| 313 |
+
if asset_type_id not in ASSET_SPECS:
|
| 314 |
+
raise ValueError("Unknown asset type")
|
| 315 |
+
slots = ASSET_SPECS[asset_type_id]["state_slots"]
|
| 316 |
+
state = {sid: 0.0 for sid in slots}
|
| 317 |
+
state["power.enabled"] = False
|
| 318 |
+
if "thermal.target_k" in slots:
|
| 319 |
+
state["thermal.target_k"] = self.ambient_temperature_K + (10 if asset_type_id.endswith("binder_fd56") else 0)
|
| 320 |
+
state["thermal.temperature_k"] = self.ambient_temperature_K
|
| 321 |
+
state["thermal.indicated_temperature_k"] = round(self.ambient_temperature_K, 1)
|
| 322 |
+
if "pumping.running" in slots:
|
| 323 |
+
state["pumping.running"] = False
|
| 324 |
+
state["pumping.direction"] = "infuse"
|
| 325 |
+
if "ventilation.face_velocity_m_s" in slots:
|
| 326 |
+
state["ventilation.face_velocity_m_s"] = None
|
| 327 |
+
if self.scene_adapter:
|
| 328 |
+
self.scene_adapter(instance_id, copy.deepcopy(state))
|
| 329 |
+
self._instances[instance_id] = _Instance(instance_id, asset_type_id, state)
|
| 330 |
+
|
| 331 |
+
def sync_scene(self, instance_ids=None):
|
| 332 |
+
"""Explicit host resync after loading/configuration; no time advance.
|
| 333 |
+
|
| 334 |
+
Call this after configuring a syringe and connecting its loaded content.
|
| 335 |
+
Initial creation already pushes all initial slots when a backend exists.
|
| 336 |
+
"""
|
| 337 |
+
if self.scene_adapter is None:
|
| 338 |
+
raise RuntimeError("No scene backend is registered")
|
| 339 |
+
with self._lock:
|
| 340 |
+
ids = list(self._instances) if instance_ids is None else list(instance_ids)
|
| 341 |
+
if any(key not in self._instances for key in ids):
|
| 342 |
+
raise ValueError("Unknown scene instance")
|
| 343 |
+
for key in ids:
|
| 344 |
+
try:
|
| 345 |
+
self.scene_adapter(key, copy.deepcopy(self._instances[key].state))
|
| 346 |
+
except Exception:
|
| 347 |
+
self._scene_faults.append({"instance_id": key, "time_s": self.time_s, "code": "SCENE_SYNC_FAILED"})
|
| 348 |
+
raise SceneSynchronizationError("Scene resynchronization failed; backend may have partial effects") from None
|
| 349 |
+
|
| 350 |
+
def describe_host(self):
|
| 351 |
+
"""Trusted host metadata; sim.step is never an instrument capability."""
|
| 352 |
+
return copy.deepcopy(HOST_CAPABILITIES)
|
| 353 |
+
|
| 354 |
+
def register_principal(self, principal_id: str, *, visibility: str, instance_ids=None):
|
| 355 |
+
if visibility not in ("agent", "debug", "evaluator"):
|
| 356 |
+
raise ValueError("Invalid host-assigned visibility")
|
| 357 |
+
if not isinstance(principal_id, str) or not principal_id:
|
| 358 |
+
raise ValueError("Invalid principal ID")
|
| 359 |
+
with self._lock:
|
| 360 |
+
if principal_id in self._principals:
|
| 361 |
+
raise ValueError("Principal already registered; identities are immutable for session lifetime")
|
| 362 |
+
allowed = None if instance_ids is None else frozenset(instance_ids)
|
| 363 |
+
if allowed is not None and not allowed <= self._instances.keys():
|
| 364 |
+
raise ValueError("Principal scope includes an unknown instance")
|
| 365 |
+
self._principals[principal_id] = (visibility, allowed)
|
| 366 |
+
self._logs[principal_id] = []
|
| 367 |
+
|
| 368 |
+
def session(self, principal_id: str) -> "LabSession":
|
| 369 |
+
if principal_id not in self._principals:
|
| 370 |
+
raise ValueError("Principal must first be authenticated and registered by the host")
|
| 371 |
+
return LabSession(self, principal_id)
|
| 372 |
+
|
| 373 |
+
def create_vessel(self, vessel_id: str, *, volume_m3: float, capacity_m3: float,
|
| 374 |
+
species_mass_kg: dict[str, float]):
|
| 375 |
+
with self._lock:
|
| 376 |
+
if not isinstance(vessel_id, str) or not vessel_id or vessel_id in self._vessels:
|
| 377 |
+
raise ValueError("Vessel ID must be unique and nonempty")
|
| 378 |
+
if not (_number(volume_m3) and _number(capacity_m3) and 0 <= volume_m3 <= capacity_m3 and capacity_m3 > 0):
|
| 379 |
+
raise ValueError("Invalid vessel volume or capacity")
|
| 380 |
+
if not isinstance(species_mass_kg, dict) or any(not isinstance(k, str) or not k or not _number(v) or v < 0 for k, v in species_mass_kg.items()):
|
| 381 |
+
raise ValueError("Invalid material masses")
|
| 382 |
+
if volume_m3 == 0 and any(species_mass_kg.values()):
|
| 383 |
+
raise ValueError("An empty liquid vessel cannot contain nonzero material mass")
|
| 384 |
+
self._vessels[vessel_id] = _Vessel(float(volume_m3), float(capacity_m3), copy.deepcopy(species_mass_kg))
|
| 385 |
+
|
| 386 |
+
def configure_syringe(self, instance_id: str, *, diameter_m: float, stroke_m: float, evidence: str):
|
| 387 |
+
with self._lock:
|
| 388 |
+
inst = self._require_pump(instance_id)
|
| 389 |
+
if inst.state["pumping.running"]:
|
| 390 |
+
raise ValueError("Stop pump before changing calibrated syringe")
|
| 391 |
+
if not (_number(diameter_m) and _number(stroke_m)
|
| 392 |
+
and math.isclose(diameter_m, self._value(inst, "syringe_diameter_m"), rel_tol=1e-9)
|
| 393 |
+
and math.isclose(stroke_m, self._value(inst, "syringe_stroke_m"), rel_tol=1e-9)):
|
| 394 |
+
raise ValueError("This asset type requires the declared B-D 10 mL nominal geometry")
|
| 395 |
+
if not isinstance(evidence, str) or not evidence.strip():
|
| 396 |
+
raise ValueError("Per-instance calibration evidence is required")
|
| 397 |
+
inst.syringe = {"diameter_m": float(diameter_m), "stroke_m": float(stroke_m),
|
| 398 |
+
"area_m2": math.pi * diameter_m**2 / 4, "evidence": evidence}
|
| 399 |
+
inst.state["pumping.transferred_volume_m3"] = 0.0
|
| 400 |
+
inst.state["pumping.plunger_displacement_m"] = 0.0
|
| 401 |
+
inst.connections = None
|
| 402 |
+
inst.revision += 1
|
| 403 |
+
|
| 404 |
+
def connect_pump(self, instance_id: str, syringe_vessel_id: str, external_vessel_id: str):
|
| 405 |
+
"""Bind syringe content and external liquid vessel; direction selects donor.
|
| 406 |
+
|
| 407 |
+
Infuse: syringe -> external. Withdraw: external -> syringe. Initial
|
| 408 |
+
plunger position is derived from the explicitly loaded syringe volume.
|
| 409 |
+
Host setup represents physical loading; it never adds or deletes matter.
|
| 410 |
+
Each syringe vessel is exclusive to its pump and cannot be used as any
|
| 411 |
+
other pump's external vessel. External collection vessels may be shared.
|
| 412 |
+
Rejected configuration leaves connections, plunger and revision unchanged.
|
| 413 |
+
"""
|
| 414 |
+
with self._lock:
|
| 415 |
+
inst = self._require_pump(instance_id)
|
| 416 |
+
if inst.state["pumping.running"]:
|
| 417 |
+
raise ValueError("Stop pump before changing material connections")
|
| 418 |
+
if syringe_vessel_id == external_vessel_id or syringe_vessel_id not in self._vessels or external_vessel_id not in self._vessels:
|
| 419 |
+
raise ValueError("Two distinct registered material vessels are required")
|
| 420 |
+
if not inst.syringe:
|
| 421 |
+
raise ValueError("Configure the declared syringe geometry before connecting")
|
| 422 |
+
for other in self._instances.values():
|
| 423 |
+
if other is inst or not other.connections:
|
| 424 |
+
continue
|
| 425 |
+
other_syringe, other_external = other.connections
|
| 426 |
+
if syringe_vessel_id in (other_syringe, other_external) or external_vessel_id == other_syringe:
|
| 427 |
+
raise ValueError("A syringe vessel must be exclusive to one pump and cannot serve another pump as an external vessel")
|
| 428 |
+
syringe = self._vessels[syringe_vessel_id]
|
| 429 |
+
capacity = inst.syringe["area_m2"] * inst.syringe["stroke_m"]
|
| 430 |
+
if syringe.volume_m3 > capacity + 1e-18:
|
| 431 |
+
raise ValueError("Loaded content exceeds the declared 10 mL syringe")
|
| 432 |
+
inst.connections = (syringe_vessel_id, external_vessel_id)
|
| 433 |
+
inst.state["pumping.plunger_displacement_m"] = max(0.0, inst.syringe["stroke_m"] - syringe.volume_m3 / inst.syringe["area_m2"])
|
| 434 |
+
inst.revision += 1
|
| 435 |
+
|
| 436 |
+
def set_external_exhaust(self, instance_id: str, flow_rate_m3_s: float):
|
| 437 |
+
"""Host facility boundary condition, at current room conditions; not a sensor."""
|
| 438 |
+
with self._lock:
|
| 439 |
+
inst = self._instances[instance_id]
|
| 440 |
+
if inst.asset_type_id != "instrument.esco_efa5":
|
| 441 |
+
raise ValueError("External exhaust applies only to the fume hood")
|
| 442 |
+
if not _number(flow_rate_m3_s) or not 0 <= flow_rate_m3_s <= 5:
|
| 443 |
+
raise ValueError("Flow must fit the assumed 0–5 m^3/s facility envelope")
|
| 444 |
+
inst.state["ventilation.external_exhaust_m3_s"] = float(flow_rate_m3_s)
|
| 445 |
+
self._update_face_velocity(inst)
|
| 446 |
+
inst.revision += 1
|
| 447 |
+
|
| 448 |
+
def _require_pump(self, instance_id):
|
| 449 |
+
inst = self._instances[instance_id]
|
| 450 |
+
if inst.asset_type_id != "instrument.ne1000_bd10ml":
|
| 451 |
+
raise ValueError("Operation requires a syringe pump")
|
| 452 |
+
return inst
|
| 453 |
+
|
| 454 |
+
def _value(self, inst, name):
|
| 455 |
+
return ASSET_SPECS[inst.asset_type_id]["parameters"][name]["value"]
|
| 456 |
+
|
| 457 |
+
def _update_face_velocity(self, inst):
|
| 458 |
+
opening = inst.state["sash.opening_m"]
|
| 459 |
+
area = self._value(inst, "opening_width_m") * opening
|
| 460 |
+
inst.state["ventilation.face_velocity_m_s"] = inst.state["ventilation.external_exhaust_m3_s"] / area if area > 0 else None
|
| 461 |
+
|
| 462 |
+
def _thermal_step(self, inst, dt):
|
| 463 |
+
s = inst.state
|
| 464 |
+
ambient = self.ambient_temperature_K
|
| 465 |
+
old = s["thermal.temperature_k"]
|
| 466 |
+
capacity = self._value(inst, "thermal_capacity_J_K")
|
| 467 |
+
loss = self._value(inst, "heat_loss_W_K")
|
| 468 |
+
power = self._value(inst, "heater_power_W") if s["power.enabled"] else 0
|
| 469 |
+
if "door.angle_rad" in s:
|
| 470 |
+
fraction = s["door.angle_rad"] / self._value(inst, "maximum_door_angle_rad")
|
| 471 |
+
loss += fraction * self._value(inst, "door_open_loss_W_K")
|
| 472 |
+
power *= 1 - fraction * (1 - self._value(inst, "door_open_heater_fraction"))
|
| 473 |
+
target = s["thermal.target_k"]
|
| 474 |
+
decay = math.exp(-loss * dt / capacity)
|
| 475 |
+
if not power:
|
| 476 |
+
temperature = ambient + (old - ambient) * decay
|
| 477 |
+
elif old < target:
|
| 478 |
+
equilibrium = ambient + power / loss
|
| 479 |
+
temperature = min(target, equilibrium + (old - equilibrium) * decay)
|
| 480 |
+
else:
|
| 481 |
+
cooled = ambient + (old - ambient) * decay
|
| 482 |
+
if cooled >= target:
|
| 483 |
+
temperature = cooled
|
| 484 |
+
else:
|
| 485 |
+
crossing_s = -capacity / loss * math.log((target - ambient) / (old - ambient)) if target > ambient and old > target else 0.0
|
| 486 |
+
equilibrium = ambient + power / loss
|
| 487 |
+
temperature = min(target, equilibrium + (target - equilibrium) * math.exp(-loss * max(0.0, dt - crossing_s) / capacity))
|
| 488 |
+
s["thermal.temperature_k"] = temperature
|
| 489 |
+
# A declared ideal display proxy, rounded to 0.1 K; no sensor accuracy claim.
|
| 490 |
+
s["thermal.indicated_temperature_k"] = round(temperature, 1)
|
| 491 |
+
|
| 492 |
+
def _pump_step(self, inst, dt):
|
| 493 |
+
s = inst.state
|
| 494 |
+
if not s["pumping.running"]:
|
| 495 |
+
return
|
| 496 |
+
if not s["power.enabled"] or not inst.syringe or not inst.connections:
|
| 497 |
+
s["pumping.running"] = False
|
| 498 |
+
return
|
| 499 |
+
infuse = s["pumping.direction"] == "infuse"
|
| 500 |
+
donor_id, recipient_id = inst.connections if infuse else tuple(reversed(inst.connections))
|
| 501 |
+
donor, recipient = self._vessels[donor_id], self._vessels[recipient_id]
|
| 502 |
+
area = inst.syringe["area_m2"]
|
| 503 |
+
stroke_remaining = max(0.0, inst.syringe["stroke_m"] - s["pumping.plunger_displacement_m"] if infuse else s["pumping.plunger_displacement_m"])
|
| 504 |
+
available = min(donor.volume_m3, max(0.0, recipient.capacity_m3 - recipient.volume_m3), stroke_remaining * area)
|
| 505 |
+
requested = s["pumping.flow_rate_m3_s"] * dt
|
| 506 |
+
volume = min(requested, available)
|
| 507 |
+
if volume > 0:
|
| 508 |
+
fraction = min(1.0, volume / donor.volume_m3)
|
| 509 |
+
masses = {key: value * fraction for key, value in donor.species_mass_kg.items()}
|
| 510 |
+
# All checks and the entire material transaction occur under the world lock.
|
| 511 |
+
for key, mass in masses.items():
|
| 512 |
+
donor.species_mass_kg[key] -= mass
|
| 513 |
+
recipient.species_mass_kg[key] = recipient.species_mass_kg.get(key, 0.0) + mass
|
| 514 |
+
donor.volume_m3 -= volume
|
| 515 |
+
recipient.volume_m3 += volume
|
| 516 |
+
s["pumping.transferred_volume_m3"] += volume
|
| 517 |
+
s["pumping.plunger_displacement_m"] += (1 if infuse else -1) * volume / area
|
| 518 |
+
self._transactions.append({"transaction_id": f"transfer_{len(self._transactions) + 1:06d}",
|
| 519 |
+
"instance_id": inst.instance_id, "donor_id": donor_id, "recipient_id": recipient_id,
|
| 520 |
+
"volume_m3": volume, "species_mass_kg": masses,
|
| 521 |
+
"start_time_s": self.time_s, "end_time_s": self.time_s + dt,
|
| 522 |
+
"direction": s["pumping.direction"], "quality": "synthetic_process_truth"})
|
| 523 |
+
if available <= requested + 1e-18:
|
| 524 |
+
s["pumping.running"] = False
|
| 525 |
+
|
| 526 |
+
def step(self, dt_s: float):
|
| 527 |
+
"""Advance one trusted world step; read/invoke never call this method.
|
| 528 |
+
|
| 529 |
+
The batch model permits up to 3600 seconds per step. Transfers use a
|
| 530 |
+
constant commanded rate, exact bounded volume and homogeneous material.
|
| 531 |
+
A failed backend synchronization leaves already-advanced process state
|
| 532 |
+
intact and raises SceneSynchronizationError after the common clock commits.
|
| 533 |
+
"""
|
| 534 |
+
if not _number(dt_s) or not 0 <= dt_s <= 3600:
|
| 535 |
+
raise ValueError("dt_s must be finite and in [0, 3600]")
|
| 536 |
+
if not dt_s:
|
| 537 |
+
return
|
| 538 |
+
with self._lock:
|
| 539 |
+
scene_failed = False
|
| 540 |
+
for inst in self._instances.values():
|
| 541 |
+
before = copy.deepcopy(inst.state)
|
| 542 |
+
s = inst.state
|
| 543 |
+
if "thermal.temperature_k" in s:
|
| 544 |
+
self._thermal_step(inst, dt_s)
|
| 545 |
+
if "stirring.speed_rad_s" in s:
|
| 546 |
+
old = s["stirring.speed_rad_s"]
|
| 547 |
+
target = s["stirring.target_rad_s"] if s["power.enabled"] else 0.0
|
| 548 |
+
tau = self._value(inst, "stirring_time_constant_s")
|
| 549 |
+
decay = math.exp(-dt_s / tau)
|
| 550 |
+
s["stirring.speed_rad_s"] = target + (old - target) * decay
|
| 551 |
+
s["stirring.angle_rad"] = (s["stirring.angle_rad"] + target * dt_s + (old - target) * tau * (1 - decay)) % (2 * math.pi)
|
| 552 |
+
s["stirring.indicated_speed_rad_s"] = round(s["stirring.speed_rad_s"] / RPM_TO_RAD_S) * RPM_TO_RAD_S
|
| 553 |
+
if "pumping.running" in s:
|
| 554 |
+
self._pump_step(inst, dt_s)
|
| 555 |
+
if before != s:
|
| 556 |
+
inst.revision += 1
|
| 557 |
+
if self.scene_adapter:
|
| 558 |
+
updates = {key: copy.deepcopy(value) for key, value in s.items() if before[key] != value}
|
| 559 |
+
if updates:
|
| 560 |
+
try:
|
| 561 |
+
self.scene_adapter(inst.instance_id, updates)
|
| 562 |
+
except Exception:
|
| 563 |
+
scene_failed = True
|
| 564 |
+
self._scene_faults.append({"instance_id": inst.instance_id,
|
| 565 |
+
"time_s": self.time_s + dt_s, "code": "SCENE_SYNC_FAILED"})
|
| 566 |
+
self.time_s += dt_s
|
| 567 |
+
if scene_failed:
|
| 568 |
+
raise SceneSynchronizationError("Process and common clock advanced; one or more scene updates failed. Inspect trusted host diagnostics.")
|
| 569 |
+
|
| 570 |
+
def debug_snapshot(self):
|
| 571 |
+
"""Host-only diagnostic state. Never expose as an agent tool or file."""
|
| 572 |
+
with self._lock:
|
| 573 |
+
return copy.deepcopy({"time_s": self.time_s,
|
| 574 |
+
"instances": {key: {"asset_type_id": inst.asset_type_id, "revision": inst.revision,
|
| 575 |
+
"state": inst.state, "syringe": inst.syringe, "connections": inst.connections}
|
| 576 |
+
for key, inst in self._instances.items()},
|
| 577 |
+
"vessels": {key: {"volume_m3": vessel.volume_m3, "capacity_m3": vessel.capacity_m3,
|
| 578 |
+
"species_mass_kg": vessel.species_mass_kg} for key, vessel in self._vessels.items()},
|
| 579 |
+
"transactions": self._transactions, "scene_faults": self._scene_faults})
|
| 580 |
+
|
| 581 |
+
|
| 582 |
+
class LabSession:
|
| 583 |
+
"""Agent-facing adapter; access is resolved from an immutable host registry."""
|
| 584 |
+
def __init__(self, host: LabHost, principal_id: str):
|
| 585 |
+
self.__host = host
|
| 586 |
+
self.__principal_id = principal_id
|
| 587 |
+
|
| 588 |
+
def _allowed(self, inst):
|
| 589 |
+
_, scope = self.__host._principals[self.__principal_id]
|
| 590 |
+
return scope is None or inst.instance_id in scope
|
| 591 |
+
|
| 592 |
+
def _visible(self, spec):
|
| 593 |
+
role, _ = self.__host._principals[self.__principal_id]
|
| 594 |
+
return spec["visibility"] == "agent" or role in ("debug", "evaluator")
|
| 595 |
+
|
| 596 |
+
def _envelope(self, instance_id, request_id=None, *, status="succeeded", result=None, observations=None, error=None):
|
| 597 |
+
host = self.__host
|
| 598 |
+
safe_instance_id = instance_id if isinstance(instance_id, str) else None
|
| 599 |
+
safe_request_id = request_id if isinstance(request_id, str) else None
|
| 600 |
+
inst = host._instances.get(safe_instance_id)
|
| 601 |
+
return {"protocol_version": PROTOCOL_VERSION, "instance_id": safe_instance_id,
|
| 602 |
+
"request_id": safe_request_id, "operation_id": None, "status": status,
|
| 603 |
+
"state_revision": inst.revision if inst and self._allowed(inst) else None,
|
| 604 |
+
"clock": {"domain": "simulation", "time_s": host.time_s},
|
| 605 |
+
"result": {} if result is None else result,
|
| 606 |
+
"observations": {} if observations is None else observations, "error": error}
|
| 607 |
+
|
| 608 |
+
def _error(self, instance_id, code, request_id=None, status="rejected"):
|
| 609 |
+
# Deliberately static messages; never interpolate internal state/exception text.
|
| 610 |
+
messages = {"UNKNOWN_INSTANCE": "Instance is unavailable in this session.",
|
| 611 |
+
"UNKNOWN_CAPABILITY": "Capability is unavailable for this asset.",
|
| 612 |
+
"INVALID_ARGUMENT": "Arguments do not meet the declared schema or limits.",
|
| 613 |
+
"PRECONDITION_FAILED": "Required operating configuration or state is unavailable.",
|
| 614 |
+
"ACCESS_DENIED": "Requested operation is outside the session access policy.",
|
| 615 |
+
"REQUEST_CONFLICT": "Request ID was already used for a different operation or arguments.",
|
| 616 |
+
"UNSUPPORTED": "Capability execution is not available in this adapter configuration.",
|
| 617 |
+
"DEVICE_ERROR": "Scene backend did not complete the command."}
|
| 618 |
+
return self._envelope(instance_id, request_id, status=status,
|
| 619 |
+
error={"code": code, "message": messages[code], "retryable": False,
|
| 620 |
+
"side_effects": "unknown" if code == "DEVICE_ERROR" else "none", "progress": None})
|
| 621 |
+
|
| 622 |
+
def _instance(self, instance_id):
|
| 623 |
+
if not isinstance(instance_id, str):
|
| 624 |
+
return None
|
| 625 |
+
inst = self.__host._instances.get(instance_id)
|
| 626 |
+
return inst if inst and self._allowed(inst) else None
|
| 627 |
+
|
| 628 |
+
def describe(self, *, asset_type_id=None, instance_id=None):
|
| 629 |
+
with self.__host._lock:
|
| 630 |
+
if (asset_type_id is None) == (instance_id is None):
|
| 631 |
+
return self._error(None, "INVALID_ARGUMENT")
|
| 632 |
+
if instance_id is not None:
|
| 633 |
+
inst = self._instance(instance_id)
|
| 634 |
+
if not inst:
|
| 635 |
+
return self._error(instance_id, "UNKNOWN_INSTANCE")
|
| 636 |
+
asset_type_id = inst.asset_type_id
|
| 637 |
+
if not isinstance(asset_type_id, str) or asset_type_id not in ASSET_SPECS:
|
| 638 |
+
return self._error(instance_id, "INVALID_ARGUMENT")
|
| 639 |
+
_, scope = self.__host._principals[self.__principal_id]
|
| 640 |
+
if scope is not None and not any(self.__host._instances[key].asset_type_id == asset_type_id for key in scope):
|
| 641 |
+
return self._error(instance_id, "ACCESS_DENIED")
|
| 642 |
+
spec = export_contract_metadata()["asset_types"][asset_type_id]
|
| 643 |
+
capabilities = {}
|
| 644 |
+
for capability, info in spec["capabilities"].items():
|
| 645 |
+
capabilities[capability] = {"input_schema": copy.deepcopy(info["input_schema"]),
|
| 646 |
+
"output_schema": copy.deepcopy(info["output_schema"]),
|
| 647 |
+
"description_zh": info["description_zh"], "preconditions_zh": info["preconditions_zh"],
|
| 648 |
+
"availability": "unsupported" if capability.startswith("scene.") and self.__host.scene_adapter is None else "implemented"}
|
| 649 |
+
capabilities.update(copy.deepcopy(spec["declared_capabilities"]))
|
| 650 |
+
return {"protocol_version": PROTOCOL_VERSION, "asset_type_id": asset_type_id,
|
| 651 |
+
"asset_version": spec["asset_version"], "instance_id": instance_id,
|
| 652 |
+
"catalog_id": spec["catalog_id"], "model": spec["model"],
|
| 653 |
+
"adapter": "basic40_runtime.LabSession", "capabilities": capabilities,
|
| 654 |
+
"state_slots": copy.deepcopy({sid: slot for sid, slot in spec["state_slots"].items() if self._visible(slot)}),
|
| 655 |
+
"limitations": ["Synthetic process model; no real hardware or robot execution.",
|
| 656 |
+
"Readout proxies are estimated, not measured sensor readings.",
|
| 657 |
+
"In-memory request deduplication does not survive host restart.",
|
| 658 |
+
"Python API filtering is not process/filesystem isolation.",
|
| 659 |
+
"Esco model uses the base switch-controlled lighting configuration; no digital display or Sentinel airflow sensor is assumed.",
|
| 660 |
+
"Fume face velocity is a host Q/area estimate; manufacturer rated working points are not this model's measurements or a safety assessment."]}
|
| 661 |
+
|
| 662 |
+
def read(self, *, instance_id, state_ids=None):
|
| 663 |
+
with self.__host._lock:
|
| 664 |
+
inst = self._instance(instance_id)
|
| 665 |
+
if not inst:
|
| 666 |
+
return self._error(instance_id, "UNKNOWN_INSTANCE")
|
| 667 |
+
slots = ASSET_SPECS[inst.asset_type_id]["state_slots"]
|
| 668 |
+
if state_ids is None:
|
| 669 |
+
state_ids = [key for key, slot in slots.items() if self._visible(slot)]
|
| 670 |
+
if not isinstance(state_ids, list) or any(not isinstance(key, str) for key in state_ids) or len(set(state_ids)) != len(state_ids):
|
| 671 |
+
return self._error(instance_id, "INVALID_ARGUMENT")
|
| 672 |
+
# Unknown and restricted IDs have the same error to avoid truth discovery.
|
| 673 |
+
if any(key not in slots or not self._visible(slots[key]) for key in state_ids):
|
| 674 |
+
return self._error(instance_id, "ACCESS_DENIED")
|
| 675 |
+
observations = {}
|
| 676 |
+
for key in state_ids:
|
| 677 |
+
value = copy.deepcopy(inst.state[key])
|
| 678 |
+
quality = "unavailable" if value is None else "estimated" if slots[key]["origin"] == "derived" else "valid"
|
| 679 |
+
observations[key] = {"value": value, "unit": slots[key]["unit"], "quality": quality,
|
| 680 |
+
"sample_time_s": self.__host.time_s, "sample_window_s": None}
|
| 681 |
+
if value is None:
|
| 682 |
+
observations[key]["reason"] = "Face velocity is undefined at zero modeled open area."
|
| 683 |
+
return self._envelope(instance_id, observations=observations)
|
| 684 |
+
|
| 685 |
+
def invoke(self, *, instance_id, capability_id, arguments, request_id):
|
| 686 |
+
host = self.__host
|
| 687 |
+
with host._lock:
|
| 688 |
+
inst = self._instance(instance_id)
|
| 689 |
+
if not inst:
|
| 690 |
+
return self._error(instance_id, "UNKNOWN_INSTANCE", request_id)
|
| 691 |
+
if not isinstance(request_id, str) or not request_id or len(request_id) > 256 or not isinstance(capability_id, str) or not isinstance(arguments, dict):
|
| 692 |
+
return self._error(instance_id, "INVALID_ARGUMENT", request_id if isinstance(request_id, str) else None)
|
| 693 |
+
try:
|
| 694 |
+
digest = hashlib.sha256(json.dumps([capability_id, arguments], sort_keys=True, allow_nan=False, separators=(",", ":")).encode()).hexdigest()
|
| 695 |
+
except (ValueError, TypeError):
|
| 696 |
+
return self._error(instance_id, "INVALID_ARGUMENT", request_id)
|
| 697 |
+
key = (self.__principal_id, instance_id, request_id)
|
| 698 |
+
if key in host._requests:
|
| 699 |
+
previous_digest, response = host._requests[key]
|
| 700 |
+
if digest != previous_digest:
|
| 701 |
+
return self._error(instance_id, "REQUEST_CONFLICT", request_id)
|
| 702 |
+
return copy.deepcopy(response)
|
| 703 |
+
response = self._invoke_checked(inst, capability_id, arguments, request_id)
|
| 704 |
+
host._requests[key] = (digest, copy.deepcopy(response))
|
| 705 |
+
host._logs[self.__principal_id].append({"instance_id": instance_id, "capability_id": capability_id,
|
| 706 |
+
"request_id": request_id, "response": copy.deepcopy(response)})
|
| 707 |
+
return response
|
| 708 |
+
|
| 709 |
+
def _invoke_checked(self, inst, capability, args, request):
|
| 710 |
+
host, s = self.__host, inst.state
|
| 711 |
+
spec = ASSET_SPECS[inst.asset_type_id]
|
| 712 |
+
fail = lambda code, status="rejected": self._error(inst.instance_id, code, request, status)
|
| 713 |
+
if capability in DECLARED_CAPABILITIES.get(inst.asset_type_id, {}):
|
| 714 |
+
return fail("UNSUPPORTED", "unsupported")
|
| 715 |
+
if capability not in spec["capabilities"]:
|
| 716 |
+
return fail("UNKNOWN_CAPABILITY")
|
| 717 |
+
expected = CAPABILITY_ARGUMENTS[capability]
|
| 718 |
+
if set(args) != set(expected):
|
| 719 |
+
return fail("INVALID_ARGUMENT")
|
| 720 |
+
for key, description in expected.items():
|
| 721 |
+
if description["type"] == "boolean" and type(args[key]) is not bool:
|
| 722 |
+
return fail("INVALID_ARGUMENT")
|
| 723 |
+
if description["type"] == "number" and not _number(args[key]):
|
| 724 |
+
return fail("INVALID_ARGUMENT")
|
| 725 |
+
if description["type"] == "string" and (not isinstance(args[key], str) or args[key] not in description["enum"]):
|
| 726 |
+
return fail("INVALID_ARGUMENT")
|
| 727 |
+
value = next(iter(args.values()), None)
|
| 728 |
+
if capability == "thermal.set_temperature":
|
| 729 |
+
minimum = host.ambient_temperature_K + (10 if inst.asset_type_id.endswith("binder_fd56") else 0)
|
| 730 |
+
if not minimum <= value <= host._value(inst, "maximum_temperature_K"):
|
| 731 |
+
return fail("INVALID_ARGUMENT")
|
| 732 |
+
elif capability == "stirring.set_speed":
|
| 733 |
+
rpm = value / RPM_TO_RAD_S
|
| 734 |
+
if value != 0 and (rpm < 50 - 1e-9 or rpm > 1500 + 1e-9 or not math.isclose((rpm - 50) / 10, round((rpm - 50) / 10), abs_tol=1e-8)):
|
| 735 |
+
return fail("INVALID_ARGUMENT")
|
| 736 |
+
elif capability == "scene.set_door":
|
| 737 |
+
if not 0 <= value <= host._value(inst, "maximum_door_angle_rad"):
|
| 738 |
+
return fail("INVALID_ARGUMENT")
|
| 739 |
+
elif capability == "scene.set_sash":
|
| 740 |
+
if not 0 <= value <= host._value(inst, "maximum_sash_opening_m"):
|
| 741 |
+
return fail("INVALID_ARGUMENT")
|
| 742 |
+
elif capability == "pumping.set_flow_rate":
|
| 743 |
+
if not host._value(inst, "minimum_flow_rate_m3_s") <= value <= host._value(inst, "maximum_flow_rate_m3_s"):
|
| 744 |
+
return fail("INVALID_ARGUMENT")
|
| 745 |
+
if capability in ("thermal.set_temperature", "stirring.set_speed", "pumping.set_flow_rate", "pumping.set_direction", "pumping.start") and not s["power.enabled"]:
|
| 746 |
+
return fail("PRECONDITION_FAILED")
|
| 747 |
+
if capability == "pumping.set_direction" and s["pumping.running"]:
|
| 748 |
+
return fail("PRECONDITION_FAILED")
|
| 749 |
+
if capability == "pumping.start":
|
| 750 |
+
if not inst.syringe or not inst.connections or s["pumping.flow_rate_m3_s"] <= 0:
|
| 751 |
+
return fail("PRECONDITION_FAILED")
|
| 752 |
+
infuse = s["pumping.direction"] == "infuse"
|
| 753 |
+
donor, recipient = (host._vessels[key] for key in (inst.connections if infuse else tuple(reversed(inst.connections))))
|
| 754 |
+
remaining = max(0.0, inst.syringe["stroke_m"] - s["pumping.plunger_displacement_m"] if infuse else s["pumping.plunger_displacement_m"]) * inst.syringe["area_m2"]
|
| 755 |
+
if donor.volume_m3 <= 0 or remaining <= 1e-18 or recipient.volume_m3 >= recipient.capacity_m3:
|
| 756 |
+
return fail("PRECONDITION_FAILED")
|
| 757 |
+
output_key, slot = CAPABILITY_RESULT_SLOT[capability]
|
| 758 |
+
if capability == "pumping.start":
|
| 759 |
+
value = True
|
| 760 |
+
elif capability == "pumping.stop":
|
| 761 |
+
value = False
|
| 762 |
+
if capability.startswith("scene.") and host.scene_adapter is None:
|
| 763 |
+
return fail("UNSUPPORTED", "unsupported")
|
| 764 |
+
updates = {slot: value}
|
| 765 |
+
if capability == "power.set" and not value and "pumping.running" in s:
|
| 766 |
+
updates["pumping.running"] = False
|
| 767 |
+
if capability == "scene.set_sash":
|
| 768 |
+
area = host._value(inst, "opening_width_m") * value
|
| 769 |
+
updates["ventilation.face_velocity_m_s"] = s["ventilation.external_exhaust_m3_s"] / area if area > 0 else None
|
| 770 |
+
if host.scene_adapter:
|
| 771 |
+
try:
|
| 772 |
+
host.scene_adapter(inst.instance_id, copy.deepcopy(updates))
|
| 773 |
+
except Exception:
|
| 774 |
+
# A foreign backend can have partial effects. Internal process state
|
| 775 |
+
# is unchanged, but this is failed/unknown, never rejected/none.
|
| 776 |
+
return fail("DEVICE_ERROR", "failed")
|
| 777 |
+
s.update(updates)
|
| 778 |
+
inst.revision += 1
|
| 779 |
+
# Only declared, visible completion values are returned; no full snapshot.
|
| 780 |
+
return self._envelope(inst.instance_id, request, result={output_key: value})
|
| 781 |
+
|
| 782 |
+
def write(self, *, instance_id, state_id, value, request_id):
|
| 783 |
+
with self.__host._lock:
|
| 784 |
+
inst = self._instance(instance_id)
|
| 785 |
+
if not inst:
|
| 786 |
+
return self._error(instance_id, "UNKNOWN_INSTANCE", request_id)
|
| 787 |
+
slots = ASSET_SPECS[inst.asset_type_id]["state_slots"]
|
| 788 |
+
if not isinstance(state_id, str) or state_id not in slots or not self._visible(slots[state_id]):
|
| 789 |
+
return self._error(instance_id, "ACCESS_DENIED", request_id)
|
| 790 |
+
slot = slots[state_id]
|
| 791 |
+
if slot["access"] != "read_write" or not slot["write_via"]:
|
| 792 |
+
return self._error(instance_id, "ACCESS_DENIED", request_id)
|
| 793 |
+
route = slot["write_via"]
|
| 794 |
+
return self.invoke(instance_id=instance_id, capability_id=route["capability_id"],
|
| 795 |
+
arguments={route["parameter"]: value}, request_id=request_id)
|
| 796 |
+
|
| 797 |
+
def logs(self):
|
| 798 |
+
"""Only this principal's already-filtered response records."""
|
| 799 |
+
with self.__host._lock:
|
| 800 |
+
return copy.deepcopy(self.__host._logs[self.__principal_id])
|
| 801 |
+
|
| 802 |
+
|
| 803 |
+
def validate_runtime(output: Path | None = None):
|
| 804 |
+
"""Run deterministic synthetic tests, recording actual environment and time."""
|
| 805 |
+
import importlib.util
|
| 806 |
+
import io
|
| 807 |
+
import unittest
|
| 808 |
+
test_file = Path(__file__).resolve().parents[1] / "tests" / "test_basic40_runtime.py"
|
| 809 |
+
spec = importlib.util.spec_from_file_location("test_basic40_runtime", test_file)
|
| 810 |
+
module = importlib.util.module_from_spec(spec)
|
| 811 |
+
spec.loader.exec_module(module)
|
| 812 |
+
suite = unittest.defaultTestLoader.loadTestsFromModule(module)
|
| 813 |
+
stream = io.StringIO()
|
| 814 |
+
result = unittest.TextTestRunner(stream=stream, verbosity=2).run(suite)
|
| 815 |
+
report = {"schema_version": "1.0.0", "recorded_at": datetime.now(timezone.utc).isoformat(),
|
| 816 |
+
"method": "unittest through real LabSession describe/read/invoke/write and trusted LabHost.step",
|
| 817 |
+
"environment": {"python": platform.python_version(), "platform": platform.platform()},
|
| 818 |
+
"data_classification": "Deterministic synthetic fixtures only; no real sample state",
|
| 819 |
+
"tests_run": result.testsRun, "result": "passed" if result.wasSuccessful() else "failed",
|
| 820 |
+
"failures": len(result.failures), "errors": len(result.errors), "log": stream.getvalue(),
|
| 821 |
+
"layers": {"process": "passed" if result.wasSuccessful() else "failed",
|
| 822 |
+
"host": "passed" if result.wasSuccessful() else "failed", "scene": "not_run",
|
| 823 |
+
"robot": "not_run", "hardware": "not_run"},
|
| 824 |
+
"limitations": ["Scene tests use an atomic recording callback, not evaluated Blender geometry.",
|
| 825 |
+
"API visibility filtering is verified; filesystem/process isolation is not implemented.",
|
| 826 |
+
"Physics coefficients are uncalibrated assumptions and sensor proxies are estimated."]}
|
| 827 |
+
if output:
|
| 828 |
+
output.parent.mkdir(parents=True, exist_ok=True)
|
| 829 |
+
output.write_text(json.dumps(report, ensure_ascii=False, indent=2) + "\n", encoding="utf-8")
|
| 830 |
+
return report
|
| 831 |
+
|
| 832 |
+
|
| 833 |
+
if __name__ == "__main__":
|
| 834 |
+
parser = argparse.ArgumentParser(description=__doc__)
|
| 835 |
+
parser.add_argument("--validate", type=Path, metavar="REPORT_JSON")
|
| 836 |
+
parsed = parser.parse_args()
|
| 837 |
+
if parsed.validate:
|
| 838 |
+
report = validate_runtime(parsed.validate)
|
| 839 |
+
print(json.dumps({key: report[key] for key in ("tests_run", "result", "failures", "errors")}, indent=2))
|
| 840 |
+
raise SystemExit(0 if report["result"] == "passed" else 1)
|
| 841 |
+
parser.print_help()
|
scripts/basic40_runtime_analytical.py
ADDED
|
The diff for this file is too large to render.
See raw diff
|
|
|
scripts/basic40_runtime_automation.py
ADDED
|
The diff for this file is too large to render.
See raw diff
|
|
|
scripts/basic40_runtime_measure.py
ADDED
|
The diff for this file is too large to render.
See raw diff
|
|
|
scripts/basic40_runtime_thermal.py
ADDED
|
The diff for this file is too large to render.
See raw diff
|
|
|
scripts/basic40_runtime_vacuum.py
ADDED
|
The diff for this file is too large to render.
See raw diff
|
|
|
scripts/gc_runtime.py
ADDED
|
@@ -0,0 +1,492 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Synthetic GC-FID process semantics, SI units, Python standard library only.
|
| 2 |
+
|
| 3 |
+
This is NOT calibrated Agilent firmware, a pressure-flow network, or a contact
|
| 4 |
+
solver. The host simulator owns joints, contacts, grasping, alignment and thermal
|
| 5 |
+
contact. Every numerical default below is an explicit educational assumption.
|
| 6 |
+
"""
|
| 7 |
+
from __future__ import annotations
|
| 8 |
+
|
| 9 |
+
import argparse
|
| 10 |
+
import csv
|
| 11 |
+
from dataclasses import asdict, dataclass
|
| 12 |
+
import json
|
| 13 |
+
import math
|
| 14 |
+
from pathlib import Path
|
| 15 |
+
|
| 16 |
+
R_J_MOL_K = 8.31446261815324
|
| 17 |
+
PARAMETER_PROVENANCE = "synthetic_assumption_not_manufacturer_calibration"
|
| 18 |
+
ACTION_COMPONENTS = {
|
| 19 |
+
"plug_power": "power_inlet", "power": "power_switch",
|
| 20 |
+
"connect_gas": "carrier_port", "door": "oven_door",
|
| 21 |
+
"set_temperature": "control_panel", "ignite": "fid_igniter",
|
| 22 |
+
"extinguish": "fid_body", "start": "start_key", "stop": "stop_key",
|
| 23 |
+
"aspirate": "sample_vial", "insert_syringe": "septum",
|
| 24 |
+
"depress_plunger": "plunger", "retract_syringe": "syringe",
|
| 25 |
+
}
|
| 26 |
+
|
| 27 |
+
|
| 28 |
+
def component_for_action(action, **kwargs):
|
| 29 |
+
"""Resolve the scene component, including the selected gas supply port."""
|
| 30 |
+
if action == "connect_gas":
|
| 31 |
+
gas = kwargs.get("gas")
|
| 32 |
+
if gas not in {"carrier", "hydrogen", "air", "makeup"}:
|
| 33 |
+
raise ValueError("Unknown gas port")
|
| 34 |
+
return f"{gas}_port"
|
| 35 |
+
if action not in ACTION_COMPONENTS:
|
| 36 |
+
raise ValueError(f"Unknown action: {action}")
|
| 37 |
+
return ACTION_COMPONENTS[action]
|
| 38 |
+
|
| 39 |
+
|
| 40 |
+
def finite(value, name, *, positive=False):
|
| 41 |
+
value = float(value)
|
| 42 |
+
if not math.isfinite(value) or (value <= 0 if positive else value < 0):
|
| 43 |
+
raise ValueError(f"{name} must be finite and {'positive' if positive else 'nonnegative'}")
|
| 44 |
+
return value
|
| 45 |
+
|
| 46 |
+
|
| 47 |
+
class ActionRejected(ValueError):
|
| 48 |
+
"""An embodied task precondition was not satisfied; state is unchanged."""
|
| 49 |
+
|
| 50 |
+
|
| 51 |
+
@dataclass(frozen=True)
|
| 52 |
+
class Species:
|
| 53 |
+
name: str
|
| 54 |
+
k_ref: float
|
| 55 |
+
delta_h_J_mol: float
|
| 56 |
+
response_C_kg: float
|
| 57 |
+
reference_temperature_K: float = 353.15
|
| 58 |
+
|
| 59 |
+
def __post_init__(self):
|
| 60 |
+
if not self.name:
|
| 61 |
+
raise ValueError("Species requires an identifier")
|
| 62 |
+
finite(self.k_ref, "k_ref")
|
| 63 |
+
finite(self.response_C_kg, "response_C_kg")
|
| 64 |
+
finite(self.reference_temperature_K, "reference_temperature_K", positive=True)
|
| 65 |
+
if not math.isfinite(self.delta_h_J_mol):
|
| 66 |
+
raise ValueError("delta_h_J_mol must be finite")
|
| 67 |
+
|
| 68 |
+
def retention_factor(self, temperature_K):
|
| 69 |
+
temperature_K = finite(temperature_K, "temperature_K", positive=True)
|
| 70 |
+
exponent = -self.delta_h_J_mol / R_J_MOL_K * (
|
| 71 |
+
1 / temperature_K - 1 / self.reference_temperature_K)
|
| 72 |
+
return self.k_ref * math.exp(max(-100, min(100, exponent)))
|
| 73 |
+
|
| 74 |
+
|
| 75 |
+
SYNTHETIC_SPECIES = (
|
| 76 |
+
Species("synthetic_A", 1.0, -30000, 1.0),
|
| 77 |
+
Species("synthetic_B", 2.5, -38000, 1.2),
|
| 78 |
+
Species("synthetic_C", 5.0, -45000, 0.8),
|
| 79 |
+
)
|
| 80 |
+
|
| 81 |
+
|
| 82 |
+
@dataclass(frozen=True)
|
| 83 |
+
class Method:
|
| 84 |
+
mode: str = "split"
|
| 85 |
+
split_ratio: float = 20.0
|
| 86 |
+
purge_time_s: float = 30.0
|
| 87 |
+
purge_flow_m3_s: float = 8.333333333333334e-7
|
| 88 |
+
# Both column and liner flow use this SAME assumed representative state.
|
| 89 |
+
# This omits real pressure/temperature conversion between inlet and column.
|
| 90 |
+
column_flow_m3_s: float = 1.6666666666666667e-8
|
| 91 |
+
septum_purge_flow_m3_s: float = 5e-8
|
| 92 |
+
# Septum purge is a distinct branch, not a perfectly mixed liner outlet.
|
| 93 |
+
# Zero means ideal separation of injected sample from the septum-purge path.
|
| 94 |
+
septum_sample_loss_fraction: float = 0.0
|
| 95 |
+
hydrogen_flow_m3_s: float = 5e-7
|
| 96 |
+
air_flow_m3_s: float = 5e-6
|
| 97 |
+
makeup_flow_m3_s: float = 4.166666666666667e-7
|
| 98 |
+
liner_volume_m3: float = 8e-7
|
| 99 |
+
column_length_m: float = 30.0
|
| 100 |
+
column_inner_diameter_m: float = 2.5e-4
|
| 101 |
+
column_film_thickness_m: float = 2.5e-7
|
| 102 |
+
longitudinal_B_m2_s: float = 3e-5
|
| 103 |
+
mass_transfer_C_s: float = 4e-4
|
| 104 |
+
oven_temperature_K: float = 353.15
|
| 105 |
+
inlet_temperature_K: float = 523.15
|
| 106 |
+
fid_temperature_K: float = 573.15
|
| 107 |
+
temperature_tolerance_K: float = 1.0
|
| 108 |
+
ready_dwell_s: float = 5.0
|
| 109 |
+
fid_ignition_minimum_K: float = 423.15
|
| 110 |
+
|
| 111 |
+
def __post_init__(self):
|
| 112 |
+
if self.mode not in {"split", "splitless"}:
|
| 113 |
+
raise ValueError("mode must be split or splitless")
|
| 114 |
+
for key, value in asdict(self).items():
|
| 115 |
+
if key != "mode":
|
| 116 |
+
finite(value, key)
|
| 117 |
+
for key in ("liner_volume_m3", "column_length_m", "column_inner_diameter_m",
|
| 118 |
+
"column_flow_m3_s", "oven_temperature_K", "inlet_temperature_K",
|
| 119 |
+
"fid_temperature_K", "fid_ignition_minimum_K"):
|
| 120 |
+
finite(getattr(self, key), key, positive=True)
|
| 121 |
+
if self.septum_sample_loss_fraction > 1:
|
| 122 |
+
raise ValueError("septum_sample_loss_fraction must be in [0, 1]")
|
| 123 |
+
if self.column_film_thickness_m >= self.column_inner_diameter_m / 2:
|
| 124 |
+
raise ValueError("Stationary film must leave an open mobile-phase core")
|
| 125 |
+
|
| 126 |
+
|
| 127 |
+
@dataclass
|
| 128 |
+
class ThermalZone:
|
| 129 |
+
temperature_K: float
|
| 130 |
+
setpoint_K: float
|
| 131 |
+
heat_capacity_J_K: float
|
| 132 |
+
conductance_W_K: float
|
| 133 |
+
maximum_power_W: float
|
| 134 |
+
control_gain_W_K: float
|
| 135 |
+
heater_power_W: float = 0.0
|
| 136 |
+
|
| 137 |
+
def advance(self, dt_s, ambient_K, enabled, open_door=False):
|
| 138 |
+
conductance = self.conductance_W_K * (12 if open_door else 1)
|
| 139 |
+
demand = (self.control_gain_W_K * (self.setpoint_K - self.temperature_K)
|
| 140 |
+
+ conductance * (self.setpoint_K - ambient_K))
|
| 141 |
+
self.heater_power_W = min(self.maximum_power_W, max(0, demand)) if enabled else 0.0
|
| 142 |
+
equilibrium = ambient_K + self.heater_power_W / conductance
|
| 143 |
+
decay = math.exp(-conductance * dt_s / self.heat_capacity_J_K)
|
| 144 |
+
self.temperature_K = equilibrium + (self.temperature_K - equilibrium) * decay
|
| 145 |
+
|
| 146 |
+
|
| 147 |
+
@dataclass
|
| 148 |
+
class Band:
|
| 149 |
+
species: str
|
| 150 |
+
injected_mass_kg: float
|
| 151 |
+
sigma_progress: float
|
| 152 |
+
progress: float = 0.0
|
| 153 |
+
released_fraction: float = 0.0
|
| 154 |
+
|
| 155 |
+
def advance(self, progress_delta):
|
| 156 |
+
self.progress += progress_delta
|
| 157 |
+
# Gaussian residence-time kernel conditioned on nonnegative residence.
|
| 158 |
+
sigma = self.sigma_progress
|
| 159 |
+
initial = .5 * math.erfc(1 / (sigma * math.sqrt(2)))
|
| 160 |
+
cdf = .5 * math.erfc((1 - self.progress) / (sigma * math.sqrt(2)))
|
| 161 |
+
released = min(1.0, max(self.released_fraction, (cdf - initial) / (1 - initial)))
|
| 162 |
+
mass = self.injected_mass_kg * (released - self.released_fraction)
|
| 163 |
+
self.released_fraction = released
|
| 164 |
+
return mass
|
| 165 |
+
|
| 166 |
+
|
| 167 |
+
class GC:
|
| 168 |
+
"""Agilent 7890B-inspired, single SSL/FID task state and process abstraction."""
|
| 169 |
+
|
| 170 |
+
def __init__(self, method=None, species=SYNTHETIC_SPECIES, vial_masses_kg=None):
|
| 171 |
+
self.method = method or Method()
|
| 172 |
+
species = tuple(species)
|
| 173 |
+
self.species = {item.name: item for item in species}
|
| 174 |
+
if not species or len(self.species) != len(species):
|
| 175 |
+
raise ValueError("Species identifiers must be nonempty and unique")
|
| 176 |
+
self.ambient_K = 298.15
|
| 177 |
+
self.zones = {
|
| 178 |
+
"oven": ThermalZone(self.ambient_K, self.method.oven_temperature_K, 6000, 3, 2000, 200),
|
| 179 |
+
"inlet": ThermalZone(self.ambient_K, self.method.inlet_temperature_K, 100, .4, 200, 8),
|
| 180 |
+
"fid": ThermalZone(self.ambient_K, self.method.fid_temperature_K, 150, .35, 200, 8),
|
| 181 |
+
}
|
| 182 |
+
self.power_connected = False
|
| 183 |
+
self.powered = False
|
| 184 |
+
self.gases = {gas: False for gas in ("carrier", "hydrogen", "air", "makeup")}
|
| 185 |
+
self.door_open = False
|
| 186 |
+
self.flame_lit = False
|
| 187 |
+
self.syringe_inserted = False
|
| 188 |
+
self.running = False
|
| 189 |
+
self.time_s = self.run_time_s = self.stable_time_s = 0.0
|
| 190 |
+
self.injection_time_s = None
|
| 191 |
+
self.fid_current_A = self.fid_integral_C = 0.0
|
| 192 |
+
self.vial = self._masses(vial_masses_kg if vial_masses_kg is not None else
|
| 193 |
+
{name: 1e-7 for name in self.species})
|
| 194 |
+
self.syringe = self._masses({})
|
| 195 |
+
self.liner = self._masses({})
|
| 196 |
+
self.ledger = {name: dict(injected_kg=0.0, split_vent_kg=0.0,
|
| 197 |
+
septum_purge_kg=0.0, column_loaded_kg=0.0,
|
| 198 |
+
eluted_kg=0.0, flame_off_eluted_kg=0.0)
|
| 199 |
+
for name in self.species}
|
| 200 |
+
self.bands = []
|
| 201 |
+
self.events = []
|
| 202 |
+
|
| 203 |
+
def _masses(self, mapping):
|
| 204 |
+
if set(mapping) - set(self.species):
|
| 205 |
+
raise ValueError("Unknown species in mass mapping")
|
| 206 |
+
return {name: finite(mapping.get(name, 0), name) for name in self.species}
|
| 207 |
+
|
| 208 |
+
def flows(self):
|
| 209 |
+
m = self.method
|
| 210 |
+
carrier = self.powered and self.gases["carrier"]
|
| 211 |
+
split_open = m.mode == "split" or self.injection_time_s is None or (
|
| 212 |
+
self.time_s - self.injection_time_s >= m.purge_time_s - 1e-10)
|
| 213 |
+
split = m.split_ratio * m.column_flow_m3_s if m.mode == "split" else m.purge_flow_m3_s
|
| 214 |
+
return {
|
| 215 |
+
"column": m.column_flow_m3_s if carrier else 0.0,
|
| 216 |
+
"split_vent": split if carrier and split_open else 0.0,
|
| 217 |
+
"septum_purge": m.septum_purge_flow_m3_s if carrier else 0.0,
|
| 218 |
+
"hydrogen": m.hydrogen_flow_m3_s if self.powered and self.gases["hydrogen"] else 0.0,
|
| 219 |
+
"air": m.air_flow_m3_s if self.powered and self.gases["air"] else 0.0,
|
| 220 |
+
"makeup": m.makeup_flow_m3_s if self.powered and self.gases["makeup"] else 0.0,
|
| 221 |
+
}
|
| 222 |
+
|
| 223 |
+
def _thermal_ready(self):
|
| 224 |
+
return all(abs(z.temperature_K - z.setpoint_K) <= self.method.temperature_tolerance_K
|
| 225 |
+
for z in self.zones.values())
|
| 226 |
+
|
| 227 |
+
def not_ready_reasons(self):
|
| 228 |
+
reasons = []
|
| 229 |
+
if not self.powered:
|
| 230 |
+
reasons.append("POWER_OFF")
|
| 231 |
+
if self.door_open:
|
| 232 |
+
reasons.append("OVEN_DOOR_OPEN")
|
| 233 |
+
flow = self.flows()
|
| 234 |
+
for gas, key in (("carrier", "column"), ("hydrogen", "hydrogen"), ("air", "air")):
|
| 235 |
+
if flow[key] <= 0:
|
| 236 |
+
reasons.append(f"NO_{gas.upper()}_FLOW")
|
| 237 |
+
if self.method.makeup_flow_m3_s > 0 and flow["makeup"] <= 0:
|
| 238 |
+
reasons.append("NO_MAKEUP_FLOW")
|
| 239 |
+
if not self._thermal_ready() or self.stable_time_s < self.method.ready_dwell_s:
|
| 240 |
+
reasons.append("TEMPERATURE_NOT_READY")
|
| 241 |
+
if not self.flame_lit:
|
| 242 |
+
reasons.append("FID_FLAME_OFF")
|
| 243 |
+
return reasons
|
| 244 |
+
|
| 245 |
+
def perform(self, action, **kwargs):
|
| 246 |
+
"""Apply a semantic event AFTER the host has verified its physical contact.
|
| 247 |
+
|
| 248 |
+
Insert/retract are symbolic acknowledgments, never collision detection.
|
| 249 |
+
All booleans are explicit; arguments with the wrong type are rejected.
|
| 250 |
+
"""
|
| 251 |
+
def boolean(key):
|
| 252 |
+
value = kwargs[key]
|
| 253 |
+
if type(value) is not bool:
|
| 254 |
+
raise ValueError(f"{key} must be bool")
|
| 255 |
+
return value
|
| 256 |
+
|
| 257 |
+
def fraction():
|
| 258 |
+
value = finite(kwargs.get("fraction", 1.0), "fraction", positive=True)
|
| 259 |
+
if value > 1:
|
| 260 |
+
raise ValueError("fraction must be <= 1")
|
| 261 |
+
return value
|
| 262 |
+
|
| 263 |
+
if action == "plug_power":
|
| 264 |
+
self.power_connected = boolean("connected")
|
| 265 |
+
if not self.power_connected:
|
| 266 |
+
self.powered = self.running = self.flame_lit = False
|
| 267 |
+
elif action == "power":
|
| 268 |
+
enabled = boolean("enabled")
|
| 269 |
+
if enabled and not self.power_connected:
|
| 270 |
+
raise ActionRejected("Connect power_inlet first")
|
| 271 |
+
self.powered = enabled
|
| 272 |
+
if not enabled:
|
| 273 |
+
self.running = self.flame_lit = False
|
| 274 |
+
elif action == "connect_gas":
|
| 275 |
+
gas = kwargs["gas"]
|
| 276 |
+
if gas not in self.gases:
|
| 277 |
+
raise ValueError("Unknown gas port")
|
| 278 |
+
self.gases[gas] = boolean("connected")
|
| 279 |
+
if gas in {"hydrogen", "air"} and not self.gases[gas]:
|
| 280 |
+
self.flame_lit = False
|
| 281 |
+
elif action == "door":
|
| 282 |
+
self.door_open = boolean("open")
|
| 283 |
+
elif action == "set_temperature":
|
| 284 |
+
if kwargs["zone"] not in self.zones:
|
| 285 |
+
raise ValueError("Unknown thermal zone")
|
| 286 |
+
temperature = finite(kwargs["temperature_K"], "temperature_K", positive=True)
|
| 287 |
+
if not 273.15 <= temperature <= 723.15:
|
| 288 |
+
raise ValueError("Outside synthetic model's supported thermal interval")
|
| 289 |
+
self.zones[kwargs["zone"]].setpoint_K = temperature
|
| 290 |
+
self.stable_time_s = 0.0
|
| 291 |
+
elif action == "ignite":
|
| 292 |
+
flow = self.flows()
|
| 293 |
+
if not self.powered or flow["hydrogen"] <= 0 or flow["air"] <= 0:
|
| 294 |
+
raise ActionRejected("FID ignition requires power, hydrogen and air")
|
| 295 |
+
if self.zones["fid"].temperature_K < self.method.fid_ignition_minimum_K:
|
| 296 |
+
raise ActionRejected("FID below synthetic ignition readiness temperature")
|
| 297 |
+
self.flame_lit = True
|
| 298 |
+
elif action == "extinguish":
|
| 299 |
+
self.flame_lit = False
|
| 300 |
+
elif action == "start":
|
| 301 |
+
if self.running:
|
| 302 |
+
raise ActionRejected("A run is already acquiring")
|
| 303 |
+
reasons = self.not_ready_reasons()
|
| 304 |
+
if reasons:
|
| 305 |
+
raise ActionRejected(", ".join(reasons))
|
| 306 |
+
self.running = True
|
| 307 |
+
self.run_time_s = self.fid_integral_C = 0.0
|
| 308 |
+
self.injection_time_s = None
|
| 309 |
+
elif action == "stop":
|
| 310 |
+
self.running = False
|
| 311 |
+
elif action == "aspirate":
|
| 312 |
+
f = fraction()
|
| 313 |
+
if self.syringe_inserted:
|
| 314 |
+
raise ActionRejected("Syringe must be at the vial, not inside the inlet")
|
| 315 |
+
if not any(self.vial.values()):
|
| 316 |
+
raise ActionRejected("Sample vial is empty")
|
| 317 |
+
for name in self.species:
|
| 318 |
+
amount = self.vial[name] * f
|
| 319 |
+
self.vial[name] -= amount
|
| 320 |
+
self.syringe[name] += amount
|
| 321 |
+
elif action == "insert_syringe":
|
| 322 |
+
if self.syringe_inserted:
|
| 323 |
+
raise ActionRejected("Syringe is already inserted")
|
| 324 |
+
self.syringe_inserted = True
|
| 325 |
+
elif action == "depress_plunger":
|
| 326 |
+
f = fraction()
|
| 327 |
+
reasons = self.not_ready_reasons()
|
| 328 |
+
if not self.running or not self.syringe_inserted or reasons:
|
| 329 |
+
raise ActionRejected("Injection requires acquiring, aligned syringe and ready state: "
|
| 330 |
+
+ ", ".join(reasons))
|
| 331 |
+
if not any(self.syringe.values()):
|
| 332 |
+
raise ActionRejected("Syringe is empty")
|
| 333 |
+
for name in self.species:
|
| 334 |
+
amount = self.syringe[name] * f
|
| 335 |
+
purge_loss = amount * self.method.septum_sample_loss_fraction
|
| 336 |
+
self.syringe[name] -= amount
|
| 337 |
+
self.liner[name] += amount - purge_loss
|
| 338 |
+
self.ledger[name]["injected_kg"] += amount
|
| 339 |
+
self.ledger[name]["septum_purge_kg"] += purge_loss
|
| 340 |
+
if self.injection_time_s is None:
|
| 341 |
+
self.injection_time_s = self.time_s
|
| 342 |
+
elif action == "retract_syringe":
|
| 343 |
+
self.syringe_inserted = False
|
| 344 |
+
else:
|
| 345 |
+
raise ValueError(f"Unknown action: {action}")
|
| 346 |
+
if not self.powered or self.door_open or not self._thermal_ready():
|
| 347 |
+
self.stable_time_s = 0.0
|
| 348 |
+
if not self.flame_lit:
|
| 349 |
+
self.fid_current_A = 0.0
|
| 350 |
+
self.events.append({"time_s": self.time_s, "action": action,
|
| 351 |
+
"component_id": component_for_action(action, **kwargs), "arguments": kwargs})
|
| 352 |
+
return self.observe()
|
| 353 |
+
|
| 354 |
+
def _advance(self, dt_s):
|
| 355 |
+
for name, zone in self.zones.items():
|
| 356 |
+
zone.advance(dt_s, self.ambient_K, self.powered and not (name == "oven" and self.door_open),
|
| 357 |
+
open_door=name == "oven" and self.door_open)
|
| 358 |
+
if self.powered and not self.door_open and self._thermal_ready():
|
| 359 |
+
self.stable_time_s += dt_s
|
| 360 |
+
else:
|
| 361 |
+
self.stable_time_s = 0.0
|
| 362 |
+
flow = self.flows()
|
| 363 |
+
if not self.powered or flow["hydrogen"] <= 0 or flow["air"] <= 0:
|
| 364 |
+
self.flame_lit = False
|
| 365 |
+
if self.zones["fid"].temperature_K < self.method.fid_ignition_minimum_K:
|
| 366 |
+
self.flame_lit = False
|
| 367 |
+
m = self.method
|
| 368 |
+
core_diameter = m.column_inner_diameter_m - 2 * m.column_film_thickness_m
|
| 369 |
+
velocity = flow["column"] / (math.pi * core_diameter ** 2 / 4)
|
| 370 |
+
charge = 0.0
|
| 371 |
+
survivors = []
|
| 372 |
+
for band in self.bands:
|
| 373 |
+
k = self.species[band.species].retention_factor(self.zones["oven"].temperature_K)
|
| 374 |
+
eluted = band.advance(dt_s * velocity / (m.column_length_m * (1 + k)))
|
| 375 |
+
self.ledger[band.species]["eluted_kg"] += eluted
|
| 376 |
+
if self.flame_lit:
|
| 377 |
+
charge += eluted * self.species[band.species].response_C_kg
|
| 378 |
+
else:
|
| 379 |
+
self.ledger[band.species]["flame_off_eluted_kg"] += eluted
|
| 380 |
+
if band.released_fraction < 1:
|
| 381 |
+
survivors.append(band)
|
| 382 |
+
self.bands = survivors
|
| 383 |
+
# A well-mixed vapor compartment transfers mass by competing outflows.
|
| 384 |
+
# Newly transferred bands enter at the END of this small numerical step.
|
| 385 |
+
total = flow["column"] + flow["split_vent"]
|
| 386 |
+
if total > 0:
|
| 387 |
+
fraction_out = -math.expm1(-total * dt_s / m.liner_volume_m3)
|
| 388 |
+
column_fraction = flow["column"] / total
|
| 389 |
+
H = m.longitudinal_B_m2_s / velocity + m.mass_transfer_C_s * velocity
|
| 390 |
+
sigma = math.sqrt(max(H / m.column_length_m, 1e-12))
|
| 391 |
+
for name, mass in self.liner.items():
|
| 392 |
+
out = mass * fraction_out
|
| 393 |
+
loaded = out * column_fraction
|
| 394 |
+
self.liner[name] -= out
|
| 395 |
+
self.ledger[name]["column_loaded_kg"] += loaded
|
| 396 |
+
self.ledger[name]["split_vent_kg"] += out - loaded
|
| 397 |
+
if loaded > 0:
|
| 398 |
+
self.bands.append(Band(name, loaded, sigma))
|
| 399 |
+
self.time_s += dt_s
|
| 400 |
+
if self.running:
|
| 401 |
+
self.run_time_s += dt_s
|
| 402 |
+
self.fid_integral_C += charge
|
| 403 |
+
return charge
|
| 404 |
+
|
| 405 |
+
def step(self, dt_s):
|
| 406 |
+
"""Advance time; returned current is the average over this whole step."""
|
| 407 |
+
dt_s = finite(dt_s, "dt_s", positive=True)
|
| 408 |
+
remaining = dt_s
|
| 409 |
+
charge = 0.0
|
| 410 |
+
while remaining > 1e-12:
|
| 411 |
+
h = min(.5, remaining)
|
| 412 |
+
# Align the numerical grid with the splitless purge transition.
|
| 413 |
+
if self.method.mode == "splitless" and self.injection_time_s is not None:
|
| 414 |
+
until_purge = self.injection_time_s + self.method.purge_time_s - self.time_s
|
| 415 |
+
if until_purge > 1e-10:
|
| 416 |
+
h = min(h, until_purge)
|
| 417 |
+
charge += self._advance(h)
|
| 418 |
+
remaining -= h
|
| 419 |
+
self.fid_current_A = charge / dt_s
|
| 420 |
+
return self.observe()
|
| 421 |
+
|
| 422 |
+
def mass_balance(self):
|
| 423 |
+
result = {}
|
| 424 |
+
for name, ledger in self.ledger.items():
|
| 425 |
+
remaining = sum(b.injected_mass_kg * (1 - b.released_fraction)
|
| 426 |
+
for b in self.bands if b.species == name)
|
| 427 |
+
accounted = (self.liner[name] + remaining + ledger["split_vent_kg"]
|
| 428 |
+
+ ledger["septum_purge_kg"] + ledger["eluted_kg"])
|
| 429 |
+
result[name] = dict(ledger, liner_kg=self.liner[name], column_remaining_kg=remaining,
|
| 430 |
+
residual_kg=ledger["injected_kg"] - accounted)
|
| 431 |
+
return result
|
| 432 |
+
|
| 433 |
+
def observe(self):
|
| 434 |
+
reasons = self.not_ready_reasons()
|
| 435 |
+
flow = self.flows()
|
| 436 |
+
return {
|
| 437 |
+
"parameter_provenance": PARAMETER_PROVENANCE, "time_s": self.time_s,
|
| 438 |
+
"run_time_s": self.run_time_s, "powered": self.powered,
|
| 439 |
+
"door_open": self.door_open, "syringe_inserted": self.syringe_inserted,
|
| 440 |
+
"flame_lit": self.flame_lit, "running": self.running,
|
| 441 |
+
"ready": not reasons, "not_ready_reasons": reasons,
|
| 442 |
+
"temperatures_K": {name: z.temperature_K for name, z in self.zones.items()},
|
| 443 |
+
"heater_power_W": {name: z.heater_power_W for name, z in self.zones.items()},
|
| 444 |
+
"flows_m3_s": flow,
|
| 445 |
+
"carrier_total_flow_m3_s": sum(flow[name] for name in ("column", "split_vent", "septum_purge")),
|
| 446 |
+
"fid_current_A": self.fid_current_A, "fid_integral_C": self.fid_integral_C,
|
| 447 |
+
"mass_balance_kg": self.mass_balance(),
|
| 448 |
+
"vial_masses_kg": dict(self.vial), "syringe_masses_kg": dict(self.syringe),
|
| 449 |
+
}
|
| 450 |
+
|
| 451 |
+
|
| 452 |
+
def synthetic_demo(output_dir):
|
| 453 |
+
"""Write explicitly synthetic chromatogram, provenance and action history."""
|
| 454 |
+
output_dir = Path(output_dir)
|
| 455 |
+
output_dir.mkdir(parents=True, exist_ok=True)
|
| 456 |
+
gc = GC()
|
| 457 |
+
gc.perform("plug_power", connected=True)
|
| 458 |
+
gc.perform("power", enabled=True)
|
| 459 |
+
for gas in gc.gases:
|
| 460 |
+
gc.perform("connect_gas", gas=gas, connected=True)
|
| 461 |
+
gc.step(1200)
|
| 462 |
+
gc.perform("ignite")
|
| 463 |
+
gc.perform("start")
|
| 464 |
+
gc.perform("aspirate", fraction=.01)
|
| 465 |
+
gc.perform("insert_syringe")
|
| 466 |
+
gc.perform("depress_plunger")
|
| 467 |
+
gc.perform("retract_syringe")
|
| 468 |
+
rows = []
|
| 469 |
+
for _ in range(1800):
|
| 470 |
+
state = gc.step(.5)
|
| 471 |
+
rows.append({"synthetic_run_time_s": state["run_time_s"],
|
| 472 |
+
"synthetic_fid_current_A": state["fid_current_A"],
|
| 473 |
+
"synthetic_fid_integral_C": state["fid_integral_C"],
|
| 474 |
+
"oven_temperature_K": state["temperatures_K"]["oven"]})
|
| 475 |
+
csv_path = output_dir / "synthetic_chromatogram.csv"
|
| 476 |
+
with csv_path.open("w", newline="", encoding="utf-8") as stream:
|
| 477 |
+
writer = csv.DictWriter(stream, fieldnames=rows[0])
|
| 478 |
+
writer.writeheader()
|
| 479 |
+
writer.writerows(rows)
|
| 480 |
+
metadata = {"parameter_provenance": PARAMETER_PROVENANCE, "method": asdict(gc.method),
|
| 481 |
+
"synthetic_species": [asdict(item) for item in gc.species.values()],
|
| 482 |
+
"final_state": gc.observe(), "events": gc.events,
|
| 483 |
+
"integration": "Each CSV current is an interval mean; integral = sum(current * 0.5 s)."}
|
| 484 |
+
(output_dir / "synthetic_run.json").write_text(json.dumps(metadata, ensure_ascii=False, indent=2), encoding="utf-8")
|
| 485 |
+
return csv_path
|
| 486 |
+
|
| 487 |
+
|
| 488 |
+
if __name__ == "__main__":
|
| 489 |
+
parser = argparse.ArgumentParser(description=__doc__)
|
| 490 |
+
parser.add_argument("--demo-dir", type=Path, required=True)
|
| 491 |
+
args = parser.parse_args()
|
| 492 |
+
print(synthetic_demo(args.demo_dir))
|
tests/test_asset_antonpaar_abbematadvanced.py
ADDED
|
@@ -0,0 +1,113 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Abbemat 5201: real protocol, calibration specificity, optics and ledger tests."""
|
| 2 |
+
import copy
|
| 3 |
+
import json
|
| 4 |
+
import math
|
| 5 |
+
import sys
|
| 6 |
+
import unittest
|
| 7 |
+
from pathlib import Path
|
| 8 |
+
ROOT=Path(__file__).resolve().parents[1]; sys.path.insert(0,str(ROOT/'scripts')); sys.path.insert(0,str(ROOT/'skills/chemistry-lab-assets/scripts'))
|
| 9 |
+
from asset_runtime import antonpaar_abbematadvanced as rt
|
| 10 |
+
from asset_tool import lint_schema,validate_value
|
| 11 |
+
class AntonpaarAbbematadvancedTests(unittest.TestCase):
|
| 12 |
+
def setUp(self):
|
| 13 |
+
self.h=rt.AntonpaarAbbematadvancedRuntime(); self.agent=self.h.session(); self.h.register_principal('evaluator',visibility='evaluator'); self.ev=self.h.session('evaluator')
|
| 14 |
+
def ready(self,fractions=None):
|
| 15 |
+
h=self.h; h.invoke('power.set',enabled=True); h.invoke('lid.set_angle',angle_rad=math.pi/2)
|
| 16 |
+
h.invoke('sample.configure',volume_fractions=fractions or {'ethanol':1.},volume_m3=100e-9,matrix_id='ethanol',contamination_fraction=0.)
|
| 17 |
+
h.invoke('lid.set_angle',angle_rad=0.)
|
| 18 |
+
def start(self,cap='acquisition.start',args=None):
|
| 19 |
+
return self.agent.invoke(instance_id=self.h.instance_id,capability_id=cap,arguments=args or {},request_id='start-'+str(self.h._operation_count))
|
| 20 |
+
def calibration(self,matrix='ethanol',temperature=293.15):
|
| 21 |
+
return dict(matrix_id=matrix,temperature_k=temperature,points=[{'index':1.35,'mass_fraction':0.},{'index':1.38,'mass_fraction':1.}],source='synthetic test calibration, not experiment')
|
| 22 |
+
def test_setpoints_are_not_temperature(self):
|
| 23 |
+
self.h.invoke('thermal.set_temperature',temperature_k=313.15); self.assertEqual(self.h.temperature_k,293.15); self.assertEqual(self.h.time_s,0)
|
| 24 |
+
self.h.invoke('power.set',enabled=True); self.h.step(10); self.assertGreater(self.h.temperature_k,293.15); self.assertLess(self.h.temperature_k,313.15)
|
| 25 |
+
def test_reads_and_describe_pure_detached(self):
|
| 26 |
+
self.ready(); self.start(); self.h.step(4); before=copy.deepcopy(self.h.__dict__)
|
| 27 |
+
for _ in range(3):
|
| 28 |
+
d=self.agent.describe(instance_id=self.h.instance_id); d['capabilities'].clear(); self.agent.read(instance_id=self.h.instance_id); self.h.invoke('refractometry.measure')
|
| 29 |
+
self.assertEqual(before,self.h.__dict__)
|
| 30 |
+
def test_rejections_atomic(self):
|
| 31 |
+
for cap,args in [('acquisition.start',{}),('power.set',{'enabled':1}),('thermal.set_temperature',{'temperature_k':math.nan}),
|
| 32 |
+
('lid.set_angle',{'angle_rad':2}),('method.configure',{'mode':'brix'}),('power.set',{'enabled':True,'visibility':'evaluator'})]:
|
| 33 |
+
before=copy.deepcopy(self.h.__dict__)
|
| 34 |
+
with self.assertRaises(rt.ActionRejected): self.h.invoke(cap,**args)
|
| 35 |
+
self.assertEqual(before,self.h.__dict__)
|
| 36 |
+
for dt in [0,-1,True,math.inf,math.nan]:
|
| 37 |
+
with self.assertRaises(ValueError): self.h.step(dt)
|
| 38 |
+
def test_reference_and_async_completion(self):
|
| 39 |
+
self.ready(); response=self.start(); self.assertEqual(response['status'],'accepted')
|
| 40 |
+
self.assertIsNone(self.h.invoke('refractometry.measure')['index']); self.assertEqual(self.agent.poll(response['operation_id'])['status'],'running')
|
| 41 |
+
self.h.step(15); result=self.h.invoke('refractometry.measure')
|
| 42 |
+
self.assertEqual(result['phase'],'succeeded'); self.assertEqual(self.h.elapsed_s,10); self.assertEqual(self.h.time_s,15)
|
| 43 |
+
self.assertAlmostEqual(result['index'],1.3611); self.assertEqual(result['evidence'],'derived'); self.assertIsNone(result['mass_fraction'])
|
| 44 |
+
def test_calibration_specificity_not_universal_brix(self):
|
| 45 |
+
self.ready(); self.h.invoke('method.configure',mode='calibrated_concentration')
|
| 46 |
+
with self.assertRaises(rt.ActionRejected): self.h.invoke('acquisition.start')
|
| 47 |
+
for matrix,temp in [('wrong_matrix',293.15),('ethanol',303.15)]:
|
| 48 |
+
self.h.invoke('calibration.configure',**self.calibration(matrix,temp))
|
| 49 |
+
with self.assertRaises(rt.ActionRejected): self.h.invoke('acquisition.start')
|
| 50 |
+
self.h.invoke('calibration.configure',**self.calibration()); self.start(); self.h.step(10)
|
| 51 |
+
r=self.h.invoke('refractometry.measure'); self.assertAlmostEqual(r['mass_fraction'],.37); self.assertEqual(r['concentration_evidence'],'user_supplied_calibration')
|
| 52 |
+
def test_invalid_calibration_arrays_and_monotonicity(self):
|
| 53 |
+
args=self.calibration()
|
| 54 |
+
variants=[[],{},[{'index':1.35,'mass_fraction':0.}],
|
| 55 |
+
[{'index':1.35,'mass_fraction':0.},{'index':1.35,'mass_fraction':1.}],
|
| 56 |
+
[{'index':1.35,'mass_fraction':0.},{'index':1.38,'mass_fraction':math.nan}],
|
| 57 |
+
[{'index':1.35,'mass_fraction':0.},{'index':1.36,'mass_fraction':.8},{'index':1.38,'mass_fraction':.2}]]
|
| 58 |
+
for points in variants:
|
| 59 |
+
before=copy.deepcopy(self.h.__dict__); args['points']=points
|
| 60 |
+
with self.assertRaises(rt.ActionRejected): self.h.invoke('calibration.configure',**args)
|
| 61 |
+
self.assertEqual(before,self.h.__dict__)
|
| 62 |
+
def test_mixture_is_lorentz_lorenz_and_synthetic(self):
|
| 63 |
+
self.ready({'ethanol':.5,'methanol':.5}); self.start(); self.h.step(10); result=self.h.invoke('refractometry.measure')
|
| 64 |
+
nums=[self.h.templates[s]['value'] for s in ('ethanol','methanol')]
|
| 65 |
+
ll=sum((n*n-1)/(n*n+2) for n in nums)/2; expected=math.sqrt((1+2*ll)/(1-ll))
|
| 66 |
+
self.assertAlmostEqual(result['index'],expected,places=6); self.assertEqual(result['evidence'],'synthetic')
|
| 67 |
+
def test_thermal_interlock_and_off_reference(self):
|
| 68 |
+
self.ready(); self.h.invoke('thermal.set_temperature',temperature_k=303.15)
|
| 69 |
+
with self.assertRaises(rt.ActionRejected): self.h.invoke('acquisition.start')
|
| 70 |
+
self.h.step(200); self.start(); self.h.step(10); r=self.h.invoke('refractometry.measure')
|
| 71 |
+
self.assertLess(r['index'],1.3611); self.assertEqual(r['evidence'],'synthetic')
|
| 72 |
+
def test_cleaning_species_volume_conservation_cancel_recovery(self):
|
| 73 |
+
self.ready({'ethanol':.5,'methanol':.5}); self.h.invoke('lid.set_angle',angle_rad=math.pi/2)
|
| 74 |
+
response=self.start('cleaning.start',{'volume_m3':1e-6}); self.h.step(5)
|
| 75 |
+
self.assertGreater(sum(self.h.waste_species.values()),0)
|
| 76 |
+
self.agent.cancel(response['operation_id'],'cancel'); before=copy.deepcopy(self.h.remaining); self.h.step(5); self.assertEqual(self.h.remaining,before)
|
| 77 |
+
self.start('cleaning.start',{'volume_m3':1e-6})
|
| 78 |
+
for dt in [1,3,8,40]:
|
| 79 |
+
self.h.step(dt)
|
| 80 |
+
for sid,v in self.h.initial_species.items(): self.assertAlmostEqual(v,self.h.remaining.get(sid,0)+self.h.waste_species[sid],places=17)
|
| 81 |
+
self.assertAlmostEqual(self.h.cleaner_input_m3,self.h.cleaner_remaining_m3+self.h.cleaner_waste_m3,places=17)
|
| 82 |
+
self.assertFalse(self.h.read()['sample.filled']); self.assertEqual(self.h.phase,'succeeded')
|
| 83 |
+
def test_lid_and_operation_interlocks_power_loss(self):
|
| 84 |
+
self.ready(); self.start()
|
| 85 |
+
for cap,args in [('lid.set_angle',{'angle_rad':1.5}),('calibration.configure',self.calibration()),('cleaning.start',{'volume_m3':1e-6})]:
|
| 86 |
+
before=copy.deepcopy(self.h.__dict__)
|
| 87 |
+
with self.assertRaises(rt.ActionRejected): self.h.invoke(cap,**args)
|
| 88 |
+
self.assertEqual(before,self.h.__dict__)
|
| 89 |
+
self.h.invoke('power.set',enabled=False); self.h.step(15); self.assertEqual(self.h.phase,'cancelled'); self.assertIsNone(self.h.result)
|
| 90 |
+
def test_instance_principal_truth_isolation_retry(self):
|
| 91 |
+
self.ready(); other=rt.AntonpaarAbbematadvancedRuntime('other'); before=copy.deepcopy(other.__dict__); response=self.start(); self.h.step(2); self.assertEqual(before,other.__dict__)
|
| 92 |
+
desc=self.agent.describe(instance_id=self.h.instance_id); self.assertNotIn('sample.configure',desc['capabilities']); self.assertNotIn('sample.remaining_m3',desc['state_slots'])
|
| 93 |
+
with self.assertRaises(rt.ActionRejected): self.agent.read(instance_id=self.h.instance_id,state_ids=['sample.remaining_m3'])
|
| 94 |
+
with self.assertRaises(TypeError): self.agent.read(instance_id=self.h.instance_id,visibility='evaluator')
|
| 95 |
+
self.h.register_principal('other'); s=self.h.session('other')
|
| 96 |
+
with self.assertRaises(rt.ActionRejected): s.poll(response['operation_id'])
|
| 97 |
+
self.assertNotIn('ethanol',json.dumps(self.agent.read(instance_id=self.h.instance_id)))
|
| 98 |
+
kw=dict(instance_id=self.h.instance_id,capability_id='power.set',arguments={'enabled':False},request_id='off')
|
| 99 |
+
result=self.agent.invoke(**kw); revision=self.h.revision; self.assertEqual(result,self.agent.invoke(**kw)); self.assertEqual(revision,self.h.revision)
|
| 100 |
+
kw['arguments']={'enabled':True}; self.assertEqual(self.agent.invoke(**kw)['error']['code'],'REQUEST_CONFLICT')
|
| 101 |
+
def test_actual_result_schemas_and_unavailable_quality(self):
|
| 102 |
+
meta=rt.export_antonpaar_abbematadvanced_contract_metadata()
|
| 103 |
+
for cap in meta['capabilities'].values(): self.assertEqual(lint_schema(cap['input_schema']),[]); self.assertEqual(lint_schema(cap['output_schema']),[])
|
| 104 |
+
self.assertEqual(self.agent.read(instance_id=self.h.instance_id)['observations']['optical.indicated_index']['quality'],'unavailable')
|
| 105 |
+
self.ready(); self.start(); self.h.step(10)
|
| 106 |
+
for cap,args in [('refractometry.measure',{}),('calibration.configure',self.calibration()),('lid.set_angle',{'angle_rad':math.pi/2}),('cleaning.start',{'volume_m3':1e-6}),('acquisition.stop',{})]:
|
| 107 |
+
result=self.h.invoke(cap,**args); self.assertEqual(validate_value(result,meta['capabilities'][cap]['output_schema']),[])
|
| 108 |
+
for key,v in self.h.read('evaluator').items(): self.assertEqual(validate_value(v,meta['state_slots'][key]['value_schema']),[])
|
| 109 |
+
def test_templates_have_temperature_and_D_line(self):
|
| 110 |
+
self.assertGreaterEqual(sum(t['runtime_eligible'] for t in self.h.templates.values()),50)
|
| 111 |
+
for t in self.h.templates.values():
|
| 112 |
+
self.assertEqual(t['evidence'],'measured_literature'); self.assertEqual(t['wavelength_m'],589.3e-9); self.assertIsNone(t['dn_dt_per_k']); self.assertTrue(t['source'].startswith('https://pubchem.ncbi.nlm.nih.gov/'))
|
| 113 |
+
if __name__=='__main__': unittest.main()
|
tests/test_asset_antonpaar_dma5002.py
ADDED
|
@@ -0,0 +1,109 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""DMA 5002 actual protocol, physical evolution, provenance and conservation."""
|
| 2 |
+
import copy
|
| 3 |
+
import json
|
| 4 |
+
import math
|
| 5 |
+
import sys
|
| 6 |
+
import unittest
|
| 7 |
+
from pathlib import Path
|
| 8 |
+
ROOT=Path(__file__).resolve().parents[1]
|
| 9 |
+
sys.path.insert(0,str(ROOT/'scripts')); sys.path.insert(0,str(ROOT/'skills/chemistry-lab-assets/scripts'))
|
| 10 |
+
from asset_runtime import antonpaar_dma5002 as rt
|
| 11 |
+
from asset_tool import lint_schema,validate_value
|
| 12 |
+
class AntonpaarDma5002Tests(unittest.TestCase):
|
| 13 |
+
def setUp(self):
|
| 14 |
+
self.h=rt.AntonpaarDma5002Runtime(); self.agent=self.h.session()
|
| 15 |
+
self.h.register_principal('evaluator',visibility='evaluator'); self.ev=self.h.session('evaluator')
|
| 16 |
+
def ready(self,bubbles=0,contamination=0):
|
| 17 |
+
self.h.invoke('power.set',enabled=True)
|
| 18 |
+
self.h.invoke('sample.configure',substance_id='ethanol',volume_m3=1e-6,bubble_fraction=bubbles,contamination_fraction=contamination)
|
| 19 |
+
def start(self,cap='acquisition.start',args=None):
|
| 20 |
+
return self.agent.invoke(instance_id=self.h.instance_id,capability_id=cap,arguments=args or {},request_id=str(self.h._operation_count)+'start')
|
| 21 |
+
def test_real_templates(self):
|
| 22 |
+
self.assertGreaterEqual(len(self.h.templates),50)
|
| 23 |
+
for t in self.h.templates.values():
|
| 24 |
+
self.assertEqual(t['evidence'],'measured_literature'); self.assertEqual(t['unit'],'kg/m^3')
|
| 25 |
+
self.assertTrue(t['source'].startswith('https://pubchem.ncbi.nlm.nih.gov/')); self.assertIsNotNone(t['temperature_k'])
|
| 26 |
+
self.assertIsNone(t['thermal_expansion_per_k']); self.assertIsNone(t['pressure_pa'])
|
| 27 |
+
self.assertEqual(self.h.templates['ethanol']['value'],789.3)
|
| 28 |
+
def test_setpoints_and_reads_do_not_advance(self):
|
| 29 |
+
t=self.h.temperature_k; self.h.invoke('thermal.set_temperature',temperature_k=303.15)
|
| 30 |
+
self.assertEqual(t,self.h.temperature_k); self.assertEqual(self.h.time_s,0)
|
| 31 |
+
self.h.invoke('power.set',enabled=True); self.h.step(5)
|
| 32 |
+
self.assertGreater(self.h.temperature_k,t); self.assertLess(self.h.temperature_k,303.15)
|
| 33 |
+
before=copy.deepcopy(self.h.__dict__)
|
| 34 |
+
for _ in range(3): self.agent.read(instance_id=self.h.instance_id); self.agent.describe(instance_id=self.h.instance_id); self.h.invoke('density.measure')
|
| 35 |
+
self.assertEqual(before,self.h.__dict__)
|
| 36 |
+
def test_atomic_reject(self):
|
| 37 |
+
for cap,args in [('acquisition.start',{}),('power.set',{'enabled':1}),('thermal.set_temperature',{'temperature_k':math.nan}),
|
| 38 |
+
('thermal.set_temperature',{'temperature_k':374}),('method.configure',{'mode':'brix'}),('cleaning.start',{'volume_m3':1e-5}),
|
| 39 |
+
('power.set',{'enabled':True,'visibility':'evaluator'}),('calibration.check',{'reference_density_kg_m3':789.3,'reference_temperature_k':293.15})]:
|
| 40 |
+
before=copy.deepcopy(self.h.__dict__)
|
| 41 |
+
with self.assertRaises(rt.ActionRejected): self.h.invoke(cap,**args)
|
| 42 |
+
self.assertEqual(before,self.h.__dict__)
|
| 43 |
+
for dt in [0,-1,True,math.nan,math.inf]:
|
| 44 |
+
before=copy.deepcopy(self.h.__dict__)
|
| 45 |
+
with self.assertRaises(ValueError): self.h.step(dt)
|
| 46 |
+
self.assertEqual(before,self.h.__dict__)
|
| 47 |
+
def test_completed_reference_measurement(self):
|
| 48 |
+
self.ready(); r=self.start(); self.assertEqual(r['status'],'accepted'); self.assertEqual(self.agent.poll(r['operation_id'])['status'],'running')
|
| 49 |
+
self.assertIsNone(self.h.invoke('density.measure')['density_kg_m3']); self.h.step(35)
|
| 50 |
+
r=self.h.invoke('density.measure'); self.assertEqual(r['phase'],'succeeded'); self.assertAlmostEqual(r['density_kg_m3'],789.3)
|
| 51 |
+
self.assertEqual(r['evidence'],'derived'); self.assertEqual(self.h.elapsed_s,30); self.assertEqual(self.h.time_s,35)
|
| 52 |
+
self.assertAlmostEqual(self.h.invoke('calibration.check',reference_density_kg_m3=789.3,reference_temperature_k=293.15)['deviation_kg_m3'],0)
|
| 53 |
+
def test_temperature_interlock_and_synthetic_response(self):
|
| 54 |
+
self.ready(); self.h.invoke('thermal.set_temperature',temperature_k=303.15)
|
| 55 |
+
with self.assertRaises(rt.ActionRejected): self.h.invoke('acquisition.start')
|
| 56 |
+
self.h.step(180); self.start(); self.h.step(30)
|
| 57 |
+
r=self.h.invoke('density.measure'); self.assertEqual(r['evidence'],'synthetic'); self.assertLess(r['density_kg_m3'],789.3)
|
| 58 |
+
def test_bubble_and_contamination_response(self):
|
| 59 |
+
self.ready(.02,.01); self.start(); self.h.step(30); r=self.h.invoke('density.measure')
|
| 60 |
+
self.assertTrue(r['bubble_warning']); self.assertEqual(r['quality'],'suspect'); self.assertLess(r['density_kg_m3'],789.3)
|
| 61 |
+
def test_cancel_preserves_partial_cleaning_and_recover(self):
|
| 62 |
+
self.ready(); r=self.start('cleaning.start',{'volume_m3':1e-5}); self.h.step(10)
|
| 63 |
+
self.assertGreater(self.h.waste_kg,0); before=self.h.debug_snapshot()
|
| 64 |
+
self.assertEqual(self.agent.cancel(r['operation_id'],'cancel')['status'],'cancelled'); self.h.step(15)
|
| 65 |
+
self.assertEqual(before['state']['sample.cell_kg'],self.h.cell_kg)
|
| 66 |
+
self.start('cleaning.start',{'volume_m3':1e-5}); self.h.step(80)
|
| 67 |
+
self.assertEqual(self.h.cell_kg,0); self.assertEqual(self.h.cleaner_remaining_kg,0)
|
| 68 |
+
self.assertAlmostEqual(self.h.input_kg,self.h.waste_kg,places=14); self.assertAlmostEqual(self.h.cleaner_input_kg,self.h.cleaner_waste_kg,places=14)
|
| 69 |
+
self.h.invoke('sample.configure',substance_id='ethyl_acetate',volume_m3=1e-6,bubble_fraction=0,contamination_fraction=0)
|
| 70 |
+
self.assertAlmostEqual(self.h.input_kg,self.h.cell_kg+self.h.waste_kg,places=14)
|
| 71 |
+
def test_cleaning_conservation_at_every_step(self):
|
| 72 |
+
self.ready(); self.start('cleaning.start',{'volume_m3':1e-5})
|
| 73 |
+
for dt in [1,3,7,15,100]:
|
| 74 |
+
self.h.step(dt)
|
| 75 |
+
self.assertAlmostEqual(self.h.input_kg,self.h.cell_kg+self.h.waste_kg,places=14)
|
| 76 |
+
self.assertAlmostEqual(self.h.cleaner_input_kg,self.h.cleaner_remaining_kg+self.h.cleaner_waste_kg,places=14)
|
| 77 |
+
self.assertEqual(self.h.phase,'succeeded'); self.assertFalse(self.h.read()['fill.detected'])
|
| 78 |
+
def test_principal_instance_truth_isolation_and_retry(self):
|
| 79 |
+
self.ready(); other=rt.AntonpaarDma5002Runtime('other'); before=copy.deepcopy(other.__dict__)
|
| 80 |
+
r=self.start(); self.h.step(3); self.assertEqual(before,other.__dict__)
|
| 81 |
+
desc=self.agent.describe(instance_id=self.h.instance_id)
|
| 82 |
+
self.assertNotIn('sample.configure',desc['capabilities']); self.assertNotIn('sample.cell_kg',desc['state_slots'])
|
| 83 |
+
with self.assertRaises(rt.ActionRejected): self.agent.read(instance_id=self.h.instance_id,state_ids=['sample.cell_kg'])
|
| 84 |
+
with self.assertRaises(TypeError): self.agent.read(instance_id=self.h.instance_id,visibility='evaluator')
|
| 85 |
+
self.h.register_principal('other'); other_session=self.h.session('other')
|
| 86 |
+
with self.assertRaises(rt.ActionRejected): other_session.poll(r['operation_id'])
|
| 87 |
+
self.assertNotIn('ethanol',json.dumps(self.agent.read(instance_id=self.h.instance_id)))
|
| 88 |
+
kw=dict(instance_id=self.h.instance_id,capability_id='power.set',arguments={'enabled':False},request_id='off')
|
| 89 |
+
r=self.agent.invoke(**kw); revision=self.h.revision; self.assertEqual(r,self.agent.invoke(**kw)); self.assertEqual(self.h.revision,revision)
|
| 90 |
+
kw['arguments']={'enabled':True}; self.assertEqual(self.agent.invoke(**kw)['error']['code'],'REQUEST_CONFLICT')
|
| 91 |
+
def test_running_and_phase_interlocks(self):
|
| 92 |
+
self.ready(); self.start()
|
| 93 |
+
for cap,args in [('thermal.set_temperature',{'temperature_k':303.15}),('cleaning.start',{'volume_m3':1e-5}),('method.configure',{'mode':'density'})]:
|
| 94 |
+
before=copy.deepcopy(self.h.__dict__)
|
| 95 |
+
with self.assertRaises(rt.ActionRejected): self.h.invoke(cap,**args)
|
| 96 |
+
self.assertEqual(before,self.h.__dict__)
|
| 97 |
+
self.h.invoke('power.set',enabled=False); self.h.step(50); self.assertEqual(self.h.phase,'cancelled')
|
| 98 |
+
def test_all_actual_schemas(self):
|
| 99 |
+
meta=rt.export_antonpaar_dma5002_contract_metadata()
|
| 100 |
+
for cap in meta['capabilities'].values():
|
| 101 |
+
self.assertEqual(lint_schema(cap['input_schema'],'input'),[]); self.assertEqual(lint_schema(cap['output_schema'],'output'),[])
|
| 102 |
+
self.ready(); self.start(); self.h.step(30)
|
| 103 |
+
cases=[('density.measure',{}),('calibration.check',{'reference_density_kg_m3':789.3,'reference_temperature_k':293.15}),
|
| 104 |
+
('power.set',{'enabled':True}),('thermal.set_temperature',{'temperature_k':293.15}),('method.configure',{'mode':'density'}),
|
| 105 |
+
('cleaning.start',{'volume_m3':1e-5}),('acquisition.stop',{})]
|
| 106 |
+
for cap,args in cases:
|
| 107 |
+
result=self.h.invoke(cap,**args); self.assertEqual(validate_value(result,meta['capabilities'][cap]['output_schema']),[])
|
| 108 |
+
for key,value in self.h.read('evaluator').items(): self.assertEqual(validate_value(value,meta['state_slots'][key]['value_schema']),[])
|
| 109 |
+
if __name__=='__main__': unittest.main()
|
tests/test_asset_antonpaar_monowave400.py
ADDED
|
@@ -0,0 +1,101 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import copy,hashlib,json,math,sys,unittest
|
| 2 |
+
from pathlib import Path
|
| 3 |
+
ROOT=Path(__file__).resolve().parents[1];sys.path.insert(0,str(ROOT/'scripts'));sys.path.insert(0,str(ROOT/'skills/chemistry-lab-assets/scripts'))
|
| 4 |
+
from asset_runtime.antonpaar_monowave400 import *
|
| 5 |
+
from asset_tool import validate_value,lint_schema
|
| 6 |
+
def loaded(i='test'):
|
| 7 |
+
h=AntonpaarMonowave400Runtime(i);h.invoke('lid.set_lift',lift_m=.15);h.invoke('sample.configure',**EXAMPLE);h.invoke('lid.set_lift',lift_m=0.);h.invoke('lock.set_travel',travel_m=.01);h.invoke('gas.configure',**CAPS['gas.configure'][6]);h.invoke('power.set',enabled=True);h.invoke('method.configure',**CAPS['method.configure'][6]);return h
|
| 8 |
+
class MonowaveTests(unittest.TestCase):
|
| 9 |
+
def test_01_schema_all_slots_and_capabilities(self):
|
| 10 |
+
meta=export_antonpaar_monowave400_contract_metadata();h=loaded()
|
| 11 |
+
for k,(schema,*_) in SLOTS.items():self.assertEqual(validate_value(h.read('evaluator')[k],schema),[],k)
|
| 12 |
+
for k,c in meta['capabilities'].items():
|
| 13 |
+
self.assertEqual(lint_schema(c['input_schema']),[],k);self.assertEqual(lint_schema(c['output_schema']),[],k)
|
| 14 |
+
for k in ['reaction.measure','history.read','product.read']:self.assertEqual(validate_value(h.invoke(k),CAPS[k][1]),[],k)
|
| 15 |
+
def test_02_invalid_arguments_atomic(self):
|
| 16 |
+
h=loaded()
|
| 17 |
+
for cap,a in [('method.configure',dict(CAPS['method.configure'][6],power_limit_w=851)),('method.configure',dict(CAPS['method.configure'][6],stir_rpm=1201)),('method.configure',dict(CAPS['method.configure'][6],pressure_limit_pa=3000001)),('method.configure',dict(CAPS['method.configure'][6],target_k=float('nan'))),('power.set',{'enabled':1}),('lid.set_lift',{'lift_m':.16})]:
|
| 18 |
+
before=h.debug_snapshot();rev=h.revision
|
| 19 |
+
with self.assertRaises(ActionRejected):h.invoke(cap,**a)
|
| 20 |
+
self.assertEqual(before,h.debug_snapshot());self.assertEqual(rev,h.revision)
|
| 21 |
+
def test_03_pure_read(self):
|
| 22 |
+
h=loaded();before=copy.deepcopy(h.__dict__)
|
| 23 |
+
for _ in range(3):h.read();h.describe();h.invoke('reaction.measure');h.invoke('history.read');h.invoke('product.read')
|
| 24 |
+
self.assertEqual(before,h.__dict__)
|
| 25 |
+
def test_04_closed_mass_energy(self):
|
| 26 |
+
h=loaded();h.invoke('acquisition.start');h.step(8.);r=h.read('evaluator')
|
| 27 |
+
self.assertGreater(r['truth.temperature_k'],298.15);self.assertAlmostEqual(r['truth.liquid_kg']+r['truth.vapor_kg'],EXAMPLE['mass_kg'],12)
|
| 28 |
+
self.assertAlmostEqual(r['truth.stored_energy_j'],r['truth.absorbed_energy_j']-r['truth.heat_out_j'],8)
|
| 29 |
+
self.assertEqual(h.invoke('product.read')['conversion_fraction'],None)
|
| 30 |
+
def test_05_async_completes_and_unloads(self):
|
| 31 |
+
h=loaded();h.register_principal('e','evaluator');s=h.session('e');op=s.invoke(instance_id=h.instance_id,capability_id='acquisition.start',arguments={},request_id='start')['operation_id']
|
| 32 |
+
h.step(120);self.assertEqual(s.poll(op)['status'],'succeeded');self.assertLessEqual(h.temperature,301.15)
|
| 33 |
+
h.invoke('lock.set_travel',travel_m=0);h.invoke('lid.set_lift',lift_m=.15);r=h.invoke('sample.unload');self.assertTrue(r['attachment_event'].startswith('host_release:'));self.assertEqual(h.read('evaluator')['sample.removed_kg'],.008)
|
| 34 |
+
def test_06_cancel_preserves_residual(self):
|
| 35 |
+
h=loaded();s=h.session();op=s.invoke(instance_id=h.instance_id,capability_id='acquisition.start',arguments={},request_id='start')['operation_id'];h.step(1);t=h.temperature;u=h.absorbed
|
| 36 |
+
s.cancel(op,'cancel');self.assertEqual(h.phase,'cancelled');self.assertEqual(h.temperature,t);self.assertEqual(h.absorbed,u);self.assertEqual(h.output_w,0);h.step(2);self.assertLess(h.temperature,t)
|
| 37 |
+
def test_07_identity_truth_and_idempotency(self):
|
| 38 |
+
h=loaded();s=h.session();h.register_principal('e','evaluator');e=h.session('e')
|
| 39 |
+
with self.assertRaises(ActionRejected):s.read(instance_id=h.instance_id,state_ids=['truth.temperature_k'])
|
| 40 |
+
r=s.invoke(instance_id=h.instance_id,capability_id='product.read',arguments={},request_id='deny');self.assertEqual(r['status'],'rejected')
|
| 41 |
+
self.assertNotIn('truth.temperature_k',s.describe(instance_id=h.instance_id)['state_slots'])
|
| 42 |
+
a=dict(instance_id=h.instance_id,capability_id='acquisition.start',arguments={},request_id='x');r=s.invoke(**a);rev=h.revision;self.assertEqual(r,s.invoke(**a));self.assertEqual(rev,h.revision)
|
| 43 |
+
with self.assertRaises(ActionRejected):e.poll(r['operation_id'])
|
| 44 |
+
a['arguments']={'bogus':True};self.assertEqual(s.invoke(**a)['status'],'rejected')
|
| 45 |
+
def test_08_pressure_trip_and_hot_lock(self):
|
| 46 |
+
h=loaded();a=dict(CAPS['method.configure'][6],target_k=350.,pressure_limit_pa=120000.);h.invoke('method.configure',**a);h.invoke('acquisition.start');h.step(15.)
|
| 47 |
+
self.assertEqual(h.phase,'failed');self.assertEqual(h.fault,'pressure_limit');self.assertEqual(h.output_w,0)
|
| 48 |
+
# A distinct warmer fixture verifies the retained hot/pressure interlock.
|
| 49 |
+
h=loaded();h.invoke('method.configure',**dict(a,pressure_limit_pa=3e6,hold_s=100.));h.invoke('acquisition.start');h.step(20);h.invoke('acquisition.stop');self.assertFalse(h._safe())
|
| 50 |
+
before=h.debug_snapshot()
|
| 51 |
+
with self.assertRaises(ActionRejected):h.invoke('lock.set_travel',travel_m=0.)
|
| 52 |
+
self.assertEqual(before,h.debug_snapshot())
|
| 53 |
+
def test_09_gas_loss_power_and_busy(self):
|
| 54 |
+
h=loaded();h.invoke('acquisition.start');h.step(1)
|
| 55 |
+
with self.assertRaises(ActionRejected):h.invoke('lid.set_lift',lift_m=.15)
|
| 56 |
+
h.invoke('gas.configure',connected=True,pressure_pa=450000.,flow_l_min=200.);self.assertEqual(h.fault,'cooling_gas_lost');self.assertEqual(h.output_w,0)
|
| 57 |
+
h.invoke('power.set',enabled=False);self.assertIsNone(h.invoke('reaction.measure')['temperature_k'])
|
| 58 |
+
def test_10_instance_lockstep_and_step_validation(self):
|
| 59 |
+
a=loaded('a');b=loaded('b');a.invoke('acquisition.start');b.invoke('acquisition.start');a.step(2.)
|
| 60 |
+
for _ in range(20):b.step(.1)
|
| 61 |
+
for k in SLOTS:
|
| 62 |
+
if isinstance(a.read('evaluator')[k],float):self.assertAlmostEqual(a.read('evaluator')[k],b.read('evaluator')[k],7,k)
|
| 63 |
+
else:self.assertEqual(a.read('evaluator')[k],b.read('evaluator')[k],k)
|
| 64 |
+
a.invoke('power.set',enabled=False);self.assertTrue(b.powered)
|
| 65 |
+
for v in [0,-1,True,float('inf'),float('nan')]:
|
| 66 |
+
with self.assertRaises(ValueError):a.step(v)
|
| 67 |
+
def test_11_source_templates(self):
|
| 68 |
+
h=loaded();self.assertGreaterEqual(len(h.templates),50)
|
| 69 |
+
for r in h.templates.values():
|
| 70 |
+
self.assertEqual(hashlib.sha256((ROOT/r['raw_source']).read_bytes()).hexdigest(),r['sha256']);self.assertTrue(r['source'].startswith('https://webbook.nist.gov/'))
|
| 71 |
+
for f in r['fits']:
|
| 72 |
+
for point in f['reference_points']:self.assertAlmostEqual(1e5*10**(f['A']-f['B_k']/(point['temperature_k']+f['C_k'])),point['pressure_pa'],7)
|
| 73 |
+
f=h.templates['ethanol']['fits'][1];self.assertAlmostEqual(1e5*10**(f['A']-f['B_k']/(298.15+f['C_k'])),7869.08504803628,5)
|
| 74 |
+
def test_12_fit_and_container_guard(self):
|
| 75 |
+
h=loaded();before=h.debug_snapshot()
|
| 76 |
+
with self.assertRaises(ActionRejected):h.invoke('method.configure',**dict(CAPS['method.configure'][6],target_k=573.15))
|
| 77 |
+
self.assertEqual(before,h.debug_snapshot())
|
| 78 |
+
h=AntonpaarMonowave400Runtime();h.invoke('lid.set_lift',lift_m=.15)
|
| 79 |
+
for change in [dict(fit_id='missing'),dict(compatible_sealed_g30=False),dict(volume_m3=21e-6),dict(temperature_k=400.)]:
|
| 80 |
+
with self.assertRaises(ActionRejected):h.invoke('sample.configure',**dict(EXAMPLE,**change))
|
| 81 |
+
self.assertIsNone(h.sample)
|
| 82 |
+
def test_13_record_filter_and_zero_power(self):
|
| 83 |
+
h=loaded();h.invoke('method.configure',**dict(CAPS['method.configure'][6],power_limit_w=0));h.invoke('acquisition.start');h.step(2);self.assertAlmostEqual(h.temperature,298.15,7)
|
| 84 |
+
hist=h.invoke('history.read');self.assertTrue(hist['records']);self.assertIsNone(hist['records'][0]['temperature_k']);self.assertEqual(validate_value(hist,CAPS['history.read'][1]),[])
|
| 85 |
+
for k,r in h.session().read(instance_id=h.instance_id)['observations'].items():self.assertFalse(k.startswith('truth.'))
|
| 86 |
+
def test_14_all_template_cold_loading_guards(self):
|
| 87 |
+
records=loaded().templates;accepted=0
|
| 88 |
+
for r in records.values():
|
| 89 |
+
h=AntonpaarMonowave400Runtime();h.invoke('lid.set_lift',lift_m=.15)
|
| 90 |
+
fit_id=r['cold_start_fit_ids'][0] if r['runtime_eligible'] else r['fits'][0]['fit_id']
|
| 91 |
+
a=dict(EXAMPLE,substance_id=r['substance_id'],fit_id=fit_id,noncondensable_pressure_pa=0.)
|
| 92 |
+
if r['runtime_eligible']:h.invoke('sample.configure',**a);self.assertTrue(h.sample);accepted+=1
|
| 93 |
+
else:
|
| 94 |
+
with self.assertRaises(ActionRejected):h.invoke('sample.configure',**a)
|
| 95 |
+
self.assertIsNone(h.sample)
|
| 96 |
+
self.assertEqual(accepted,34)
|
| 97 |
+
def test_15_all_action_output_schemas(self):
|
| 98 |
+
h=AntonpaarMonowave400Runtime()
|
| 99 |
+
for cap,a in [('power.set',{'enabled':True}),('gas.configure',CAPS['gas.configure'][6]),('lid.set_lift',{'lift_m':.15}),('sample.configure',EXAMPLE),('method.configure',CAPS['method.configure'][6]),('lid.set_lift',{'lift_m':0}),('lock.set_travel',{'travel_m':.01}),('acquisition.start',{}),('acquisition.stop',{}),('reaction.measure',{}),('history.read',{}),('product.read',{})]:self.assertEqual(validate_value(h.invoke(cap,**a),CAPS[cap][1]),[],cap)
|
| 100 |
+
h.invoke('lock.set_travel',travel_m=0.);h.invoke('lid.set_lift',lift_m=.15);self.assertEqual(validate_value(h.invoke('sample.unload'),CAPS['sample.unload'][1]),[])
|
| 101 |
+
if __name__=='__main__':unittest.main()
|
tests/test_asset_aqualab_4te.py
ADDED
|
@@ -0,0 +1,82 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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'));sys.path.insert(0,str(ROOT/'skills/chemistry-lab-assets/scripts'))
|
| 4 |
+
from asset_runtime.aqualab_4te import Aqualab4teRuntime,CAPS,SLOTS,ActionRejected,export_aqualab_4te_contract_metadata
|
| 5 |
+
import asset_tool
|
| 6 |
+
def configure(h,sid='sodium_chloride',**kw):
|
| 7 |
+
row=h.templates[sid];index=min(range(len(row['records'])),key=lambda i:abs(row['records'][i]['temperature_k']-298.15))
|
| 8 |
+
a=dict(CAPS['sample.configure'][6],substance_id=sid,record_index=index);a.update(kw)
|
| 9 |
+
h.invoke('lid.set_angle',angle_rad=math.pi/2);h.invoke('sample.configure',**a)
|
| 10 |
+
def ready(h,sid='sodium_chloride',**kw):
|
| 11 |
+
h.invoke('power.set',enabled=True);configure(h,sid,**kw)
|
| 12 |
+
h.invoke('thermal.set_temperature',temperature_k=round((h.sample['reference']['temperature_k']-273.15)*10)/10+273.15)
|
| 13 |
+
h.invoke('lid.set_angle',angle_rad=0.);h.invoke('latch.set_angle',angle_rad=math.pi/2)
|
| 14 |
+
def ledger(h):
|
| 15 |
+
return h.water_input+h.ambient_in-(h.sample_water+h.vapor+h.water_removed+h.ambient_out)
|
| 16 |
+
class Test4TE(unittest.TestCase):
|
| 17 |
+
def test_setpoint_and_reads_pure(self):
|
| 18 |
+
h=Aqualab4teRuntime();h.invoke('thermal.set_temperature',temperature_k=303.15);self.assertEqual(h.block_k,298.15)
|
| 19 |
+
old=copy.deepcopy(h.__dict__);h.read();h.describe();h.session().read(instance_id=h.instance_id);h.invoke('water_activity.measure');self.assertEqual(old,h.__dict__)
|
| 20 |
+
def test_rejection_atomic(self):
|
| 21 |
+
h=Aqualab4teRuntime()
|
| 22 |
+
for cap,args in [('acquisition.start',{}),('sample.configure',CAPS['sample.configure'][6]),('thermal.set_temperature',{'temperature_k':298.16}),('thermal.set_temperature',{'temperature_k':True}),('thermal.set_temperature',{'temperature_k':float('nan')}),('isotherm.configure',dict(CAPS['isotherm.configure'][6],points=[{'water_activity':.5,'moisture_dry_basis':.1}]*2))]:
|
| 23 |
+
old=copy.deepcopy(h.__dict__)
|
| 24 |
+
with self.assertRaises(ActionRejected):h.invoke(cap,**args)
|
| 25 |
+
self.assertEqual(old,h.__dict__)
|
| 26 |
+
def test_lid_lock_interlock(self):
|
| 27 |
+
h=Aqualab4teRuntime();ready(h)
|
| 28 |
+
with self.assertRaises(ActionRejected):h.invoke('lid.set_angle',angle_rad=1.5)
|
| 29 |
+
h.invoke('acquisition.start');h.step(15);h.invoke('latch.set_angle',angle_rad=0.);self.assertEqual(h.phase,'cancelled');h.invoke('lid.set_angle',angle_rad=1.5)
|
| 30 |
+
with self.assertRaises(ActionRejected):h.invoke('latch.set_angle',angle_rad=1.5)
|
| 31 |
+
def test_water_and_total_mass_ledger(self):
|
| 32 |
+
h=Aqualab4teRuntime();ready(h);h.invoke('acquisition.start');h.step(400);self.assertAlmostEqual(ledger(h),0.,14)
|
| 33 |
+
h.invoke('latch.set_angle',angle_rad=0.);h.invoke('lid.set_angle',angle_rad=1.5);h.step(20);h.invoke('sample.unload');h.step(20)
|
| 34 |
+
self.assertAlmostEqual(ledger(h),0.,14);self.assertAlmostEqual(h.input_kg+h.ambient_in,h.removed_kg+h.vapor+h.ambient_out,14)
|
| 35 |
+
def test_equilibrium_warmup_and_resolution(self):
|
| 36 |
+
h=Aqualab4teRuntime();ready(h);h.invoke('acquisition.start');h.step(600);self.assertEqual(h.phase,'succeeded');r=h.invoke('water_activity.measure')
|
| 37 |
+
self.assertTrue(r['equilibrated']);self.assertLess(abs(r['water_activity']-h.sample['reference']['value']),.003);self.assertEqual(r['quality'],'warmup_incomplete');self.assertIsNone(r['moisture_dry_basis'])
|
| 38 |
+
h.step(300);self.assertTrue(h.read()['warmup.ready']);self.assertEqual(h.invoke('water_activity.measure')['quality'],'estimated')
|
| 39 |
+
def test_continuous_and_cancel_residual(self):
|
| 40 |
+
h=Aqualab4teRuntime();ready(h);h.invoke('method.configure',**dict(CAPS['method.configure'][6],mode='continuous'));h.invoke('acquisition.start');h.step(400)
|
| 41 |
+
self.assertTrue(h.stable);self.assertEqual(h.phase,'running');h.invoke('acquisition.stop');v=h.vapor;h.step(10);self.assertEqual(h.phase,'cancelled');self.assertNotEqual(v,h.vapor);self.assertAlmostEqual(ledger(h),0.,14)
|
| 42 |
+
def test_calibration_and_isotherm(self):
|
| 43 |
+
h=Aqualab4teRuntime();ready(h);h.invoke('calibration.configure',offset_aw=.001,source='synthetic test');h.invoke('isotherm.configure',**dict(CAPS['isotherm.configure'][6],matrix_id='salt'));h.step(900);h.invoke('acquisition.start');h.step(600)
|
| 44 |
+
r=h.invoke('calibration.verify',reference_aw=h.sample['reference']['value']);self.assertTrue(r['within_vendor_tolerance']);m=h.invoke('water_activity.measure');self.assertIsNotNone(m['moisture_dry_basis']);self.assertEqual(m['moisture_evidence'],'user_supplied_isotherm')
|
| 45 |
+
h.invoke('isotherm.configure',**CAPS['isotherm.configure'][6]);self.assertIsNone(h.invoke('water_activity.measure')['moisture_dry_basis']);h.invoke('power.set',enabled=False)
|
| 46 |
+
with self.assertRaises(ActionRejected):h.invoke('calibration.verify',reference_aw=.9)
|
| 47 |
+
def test_volatile_is_flagged_not_compensated(self):
|
| 48 |
+
h=Aqualab4teRuntime();ready(h,volatile_interference=True);h.step(900);h.invoke('acquisition.start');h.step(600);self.assertEqual(h.invoke('water_activity.measure')['quality'],'suspect_volatile')
|
| 49 |
+
def test_mode_limits_and_invalid_dt(self):
|
| 50 |
+
h=Aqualab4teRuntime()
|
| 51 |
+
for args in [dict(CAPS['method.configure'][6],mode='custom'),dict(CAPS['method.configure'][6],mode='low_emitting',stability_delta=.02),dict(CAPS['method.configure'][6],consecutive_readings=1.2)]:
|
| 52 |
+
with self.assertRaises(ActionRejected):h.invoke('method.configure',**args)
|
| 53 |
+
for dt in [0,-1,True,float('inf'),float('nan')]:
|
| 54 |
+
with self.assertRaises(ValueError):h.step(dt)
|
| 55 |
+
def test_async_identity_permissions_retry(self):
|
| 56 |
+
h=Aqualab4teRuntime();ready(h);s=h.session();h.register_principal('other','agent');h.register_principal('eval','evaluator')
|
| 57 |
+
a=dict(instance_id=h.instance_id,capability_id='acquisition.start',arguments={},request_id='one');r=s.invoke(**a);self.assertEqual(r['status'],'accepted');self.assertEqual(s.invoke(**a),r);h.step(20)
|
| 58 |
+
self.assertEqual(s.poll(r['operation_id'])['status'],'running')
|
| 59 |
+
with self.assertRaises(ActionRejected):h.session('other').poll(r['operation_id'])
|
| 60 |
+
self.assertEqual(s.cancel(r['operation_id'],'two')['status'],'cancelled');self.assertEqual(s.invoke(**dict(a,capability_id='acquisition.stop'))['status'],'rejected')
|
| 61 |
+
self.assertNotIn('water.sample_kg',s.read(instance_id=h.instance_id)['observations']);self.assertNotIn('sample.configure',s.describe(instance_id=h.instance_id)['capabilities'])
|
| 62 |
+
with self.assertRaises(ActionRejected):s.read(instance_id=h.instance_id,state_ids=['water.sample_kg'])
|
| 63 |
+
self.assertEqual(s.invoke(instance_id=h.instance_id,capability_id='sample.configure',arguments=CAPS['sample.configure'][6],request_id='private')['status'],'rejected')
|
| 64 |
+
def test_instance_isolation(self):
|
| 65 |
+
a=Aqualab4teRuntime('a');b=Aqualab4teRuntime('b');old=copy.deepcopy(b.__dict__);ready(a);a.invoke('acquisition.start');a.step(350);self.assertEqual(old,b.__dict__)
|
| 66 |
+
def test_quarantine_and_off_reference(self):
|
| 67 |
+
h=Aqualab4teRuntime()
|
| 68 |
+
for sid,r in h.templates.items():
|
| 69 |
+
if not r['runtime_eligible']:
|
| 70 |
+
with self.assertRaises(ActionRejected):configure(h,sid)
|
| 71 |
+
h=Aqualab4teRuntime();ready(h);h.invoke('thermal.set_temperature',temperature_k=318.15)
|
| 72 |
+
with self.assertRaises(ActionRejected):h.invoke('acquisition.start')
|
| 73 |
+
def test_every_capability_and_schema(self):
|
| 74 |
+
h=Aqualab4teRuntime();seen=set()
|
| 75 |
+
def call(cap,**args):
|
| 76 |
+
result=h.invoke(cap,**args);self.assertEqual(asset_tool.validate_value(result,CAPS[cap][1]),[],cap);seen.add(cap)
|
| 77 |
+
for cap in ['power.set','thermal.set_temperature','lid.set_angle','sample.configure','method.configure','calibration.configure','isotherm.configure']:call(cap,**CAPS[cap][6])
|
| 78 |
+
call('lid.set_angle',angle_rad=0.);call('latch.set_angle',angle_rad=math.pi/2);h.step(900);call('acquisition.start');h.step(900);call('water_activity.measure');call('calibration.verify',reference_aw=.92);call('acquisition.stop');call('latch.set_angle',angle_rad=0.);call('lid.set_angle',angle_rad=1.5);call('sample.unload')
|
| 79 |
+
self.assertEqual(seen,set(CAPS))
|
| 80 |
+
for k,v in h.read('evaluator').items():self.assertEqual(asset_tool.validate_value(v,SLOTS[k][0]),[],k)
|
| 81 |
+
for c in export_aqualab_4te_contract_metadata()['capabilities'].values():self.assertEqual(asset_tool.lint_schema(c['input_schema']),[]);self.assertEqual(asset_tool.lint_schema(c['output_schema']),[])
|
| 82 |
+
if __name__=='__main__':unittest.main()
|
tests/test_asset_buchi_minispray.py
ADDED
|
@@ -0,0 +1,77 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Real reference identities, finite physical bounds, conservative drying and sessions."""
|
| 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.buchi_minispray import *
|
| 6 |
+
def ready(volume=2e-6,plant=None,method=None,sample=None):
|
| 7 |
+
h=BuchiMinisprayRuntime();p=copy.deepcopy(EXAMPLE);p.update(plant or {});m=copy.deepcopy(METHOD_EXAMPLE);m.update(method or {});s=copy.deepcopy(SAMPLE_EXAMPLE);s['volume_m3']=volume;s.update(sample or {})
|
| 8 |
+
h.invoke('plant.configure',**p);h.invoke('sample.configure',**s);h.invoke('method.configure',**m);h.invoke('power.set',enabled=True);h.invoke('drying.prepare');h.step(20);return h
|
| 9 |
+
class SprayDryingTests(unittest.TestCase):
|
| 10 |
+
def balance(self,h):
|
| 11 |
+
i=h._inventory();self.assertAlmostEqual(i['input'],i['retained']+i['vapor']+i['exhaust']+i['removed'],places=12)
|
| 12 |
+
pools=[h.stock,*h.bins,*h.pools.values()];self.assertAlmostEqual(h.initial_solid,sum(x['s'] for x in pools),places=12)
|
| 13 |
+
for x in pools:self.assertGreaterEqual(x['w'],-1e-15);self.assertGreaterEqual(x['s'],-1e-15);self.assertGreaterEqual(x['a'],-1e-15);self.assertLessEqual(x['a'],x['s']+1e-15)
|
| 14 |
+
def test_01_fifty_actual_original_condition_references(self):
|
| 15 |
+
h=BuchiMinisprayRuntime();self.assertEqual(len(h.templates),50);self.assertEqual(sum(t['values']['glass_former'] for t in h.templates.values()),24)
|
| 16 |
+
self.assertEqual(sum(t['values']['stable_on_storage'] is True for t in h.templates.values()),15)
|
| 17 |
+
for sid,t in h.templates.items():
|
| 18 |
+
r=h.invoke('reference.lookup',substance_id=sid);validate(REFERENCE,r);self.assertEqual(r['glass_former'],t['values']['glass_former']);self.assertIsNone(r['s300_yield_fraction']);self.assertIn('B-290',r['conditions']);self.assertTrue(r['source'].startswith('https://doi.org/'))
|
| 19 |
+
self.assertEqual(h.templates['salicylic_acid']['original']['tg_c'],-38);self.assertIn('derived',h.templates['bezafibrate']['quantity_evidence']['glass_transition_k']);self.assertIn('uncertain',h.templates['albendazole']['quantity_evidence']['glass_transition_k'])
|
| 20 |
+
def test_02_rejects_invalid_and_atomic_configuration(self):
|
| 21 |
+
h=BuchiMinisprayRuntime();s=h.debug_snapshot()
|
| 22 |
+
for a in [dict(EXAMPLE,heater_power_w=2200.),dict(EXAMPLE,gas_connected=False),dict(EXAMPLE,gas_density_kg_m3=math.nan)]:
|
| 23 |
+
with self.assertRaises(ActionRejected):h.invoke('plant.configure',**a)
|
| 24 |
+
self.assertEqual(s,h.debug_snapshot())
|
| 25 |
+
for dt in [0,-1,True,math.nan,math.inf,3601]:
|
| 26 |
+
with self.assertRaises(ValueError):h.step(dt)
|
| 27 |
+
def test_03_basic_no_organic_or_ultrasonic(self):
|
| 28 |
+
h=ready();before=h.debug_snapshot()
|
| 29 |
+
with self.assertRaises(ActionRejected):h.invoke('method.configure',**dict(METHOD_EXAMPLE,inlet_target_k=523.15))
|
| 30 |
+
with self.assertRaises(ActionRejected):h.invoke('method.configure',**dict(METHOD_EXAMPLE,nozzle='ultrasonic'))
|
| 31 |
+
with self.assertRaises(ActionRejected):h.invoke('sample.configure',**dict(SAMPLE_EXAMPLE,solvent='ethanol'))
|
| 32 |
+
self.assertEqual(before,h.debug_snapshot())
|
| 33 |
+
def test_04_warmup_and_read_are_not_time(self):
|
| 34 |
+
h=BuchiMinisprayRuntime();h.invoke('plant.configure',**EXAMPLE);h.invoke('sample.configure',**SAMPLE_EXAMPLE);h.invoke('method.configure',**METHOD_EXAMPLE);h.invoke('power.set',enabled=True);h.invoke('drying.prepare')
|
| 35 |
+
with self.assertRaises(ActionRejected):h.invoke('acquisition.start')
|
| 36 |
+
t=h.time_s
|
| 37 |
+
for _ in range(10):h.read();h.invoke('drying.measure')
|
| 38 |
+
self.assertEqual(t,h.time_s);h.step(20);self.assertLess(abs(h.inlet-423.15),3)
|
| 39 |
+
def test_05_complete_mass_water_solid_and_loss_paths(self):
|
| 40 |
+
h=ready();h.invoke('acquisition.start');h.step(30);self.assertEqual(h.phase,'succeeded');self.balance(h);r=h.invoke('product.read');validate(PRODUCT,r)
|
| 41 |
+
for k in ['product','wall','filter','exhaust']:self.assertGreater(h.mass(h.pools[k]),0)
|
| 42 |
+
self.assertGreater(h.vapor,0);self.assertLess(r['yield_dry_solid_fraction'],1);self.assertGreater(r['mass_weighted_particle_diameter_m'],0);self.assertLess(r['water_mass_fraction'],.15)
|
| 43 |
+
def test_06_wet_reject_not_dry_yield(self):
|
| 44 |
+
h=ready(plant={'d2_rate_m2_s':1e-13});h.invoke('acquisition.start');h.step(30);self.balance(h);self.assertGreater(h.mass(h.pools['wet_reject']),0);self.assertEqual(h.pools['product']['s'],0);self.assertIsNone(h._product()['mass_weighted_particle_diameter_m'])
|
| 45 |
+
def test_07_cancel_drains_but_never_refeeds(self):
|
| 46 |
+
h=ready();h.invoke('acquisition.start');h.step(.3);h.invoke('acquisition.stop');stock=copy.deepcopy(h.stock);v=h.vapor;self.assertTrue(h.bins);h.step(5);self.assertEqual(h.stock,stock);self.assertGreater(h.vapor,v);self.assertFalse(h.bins);self.assertEqual(h.phase,'cancelled');self.balance(h)
|
| 47 |
+
h.invoke('acquisition.start');h.step(30);self.assertEqual(h.phase,'succeeded');self.balance(h)
|
| 48 |
+
def test_08_poweroff_cools_preserves_inventory(self):
|
| 49 |
+
h=ready();h.invoke('acquisition.start');h.step(.3);h.invoke('power.set',enabled=False);s=h.stock.copy();w=sum(b['w'] for b in h.bins);t=h.inlet;h.step(5);self.assertEqual(s,h.stock);self.assertAlmostEqual(w,sum(b['w'] for b in h.bins));self.assertLess(h.inlet,t);self.assertEqual(h.phase,'cancelled');self.balance(h)
|
| 50 |
+
def test_09_active_label_damage_conserves_solids(self):
|
| 51 |
+
h=ready(sample={'damage_rate_ref_s_inv':1.,'damage_activation_j_mol':0.});h.invoke('acquisition.start');h.step(30);self.balance(h);self.assertLess(h._product()['active_fraction'],.9)
|
| 52 |
+
def test_10_parameters_change_collection_and_filter(self):
|
| 53 |
+
a=ready(plant={'cyclone_d50_m':1e-6});b=ready(plant={'cyclone_d50_m':40e-6})
|
| 54 |
+
for h in (a,b):h.invoke('acquisition.start');h.step(30);self.balance(h)
|
| 55 |
+
self.assertGreater(a._product()['yield_dry_solid_fraction'],b._product()['yield_dry_solid_fraction']);self.assertGreater(b.mass(b.pools['filter']),a.mass(a.pools['filter']))
|
| 56 |
+
def test_11_cooldown_open_unload_is_once(self):
|
| 57 |
+
h=ready();h.invoke('acquisition.start');h.step(30)
|
| 58 |
+
with self.assertRaises(ActionRejected):h.invoke('vessel.set_lower',lower_m=.05)
|
| 59 |
+
h.invoke('drying.shutdown');h.step(20);h.invoke('airflow.stop');h.invoke('vessel.set_lower',lower_m=.05);r=h.invoke('product.unload',sample_id='feed_1');self.assertTrue(r['unloaded']);self.balance(h);self.assertGreater(h.mass(h.pools['removed']),0)
|
| 60 |
+
with self.assertRaises(ActionRejected):h.invoke('product.unload',sample_id='feed_1')
|
| 61 |
+
def test_12_session_privacy_async_ownership_and_retry(self):
|
| 62 |
+
h=ready();h.register_principal('a');h.register_principal('b');h.register_principal('judge','evaluator');a=h.session('a');b=h.session('b');v=a.read(instance_id=h.instance_id);self.assertFalse(any(k.startswith('truth.') for k in v['observations']))
|
| 63 |
+
denied=a.invoke(instance_id=h.instance_id,capability_id='product.read',arguments={},request_id='p');self.assertEqual(denied['status'],'rejected')
|
| 64 |
+
args=dict(instance_id=h.instance_id,capability_id='acquisition.start',arguments={},request_id='s');r=a.invoke(**args);self.assertEqual(r['status'],'accepted');self.assertEqual(r,a.invoke(**args))
|
| 65 |
+
with self.assertRaises(ActionRejected):b.poll(r['operation_id'])
|
| 66 |
+
h.step(.3);a.cancel(r['operation_id'],'cancel');self.assertEqual(a.poll(r['operation_id'])['status'],'cancelled');self.assertEqual(a.invoke(instance_id=h.instance_id,capability_id='drying.shutdown',arguments={},request_id='s')['status'],'rejected')
|
| 67 |
+
def test_13_metadata_schemas_and_instance_isolation(self):
|
| 68 |
+
a=ready();b=ready();a.invoke('acquisition.start');a.step(2);self.assertEqual(b.phase,'idle');self.assertEqual(b.vapor,0);meta=export_buchi_minispray_contract_metadata();self.assertEqual(set(meta['state_slots']),set(a.read('evaluator')))
|
| 69 |
+
for key,v in a.read('evaluator').items():validate(SLOTS[key][0],v)
|
| 70 |
+
for cap in ['drying.measure','product.read','history.read']:validate(CAPS[cap][1],a.invoke(cap))
|
| 71 |
+
def test_14_time_partition_consistency(self):
|
| 72 |
+
a=ready();b=ready()
|
| 73 |
+
for h in (a,b):h.invoke('acquisition.start')
|
| 74 |
+
a.step(5)
|
| 75 |
+
for _ in range(50):b.step(.1)
|
| 76 |
+
self.balance(a);self.balance(b);self.assertAlmostEqual(a.vapor,b.vapor,places=10);self.assertAlmostEqual(a.pools['product']['s'],b.pools['product']['s'],places=10)
|
| 77 |
+
if __name__=='__main__':unittest.main()
|
tests/test_asset_buchi_speedextractore.py
ADDED
|
@@ -0,0 +1,83 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import copy,hashlib,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.buchi_speedextractore import *
|
| 5 |
+
def setup(n=6,method=None,plant=None,sample=None):
|
| 6 |
+
h=BuchiSpeedextractoreRuntime();h.invoke('plant.configure',**dict(EXAMPLE,**(plant or {})));h.invoke('method.configure',**dict(METHOD_EXAMPLE,**(method or {})));h.invoke('power.set',enabled=True);h.invoke('thermal.preheat');h.step(100.);h.invoke('shield.set_lift',lift_m=.18);h.invoke('drawer.set_extension',extension_m=.16)
|
| 7 |
+
for i in range(n):h.invoke('sample.configure',**dict(SAMPLE_EXAMPLE,**dict(position=i,sample_id='soil_'+str(i),**(sample or {}))))
|
| 8 |
+
h.invoke('drawer.set_extension',extension_m=0.);h.invoke('shield.set_lift',lift_m=0.);return h
|
| 9 |
+
def finish(h,dt=.25):
|
| 10 |
+
if h.phase=='idle':h.invoke('acquisition.start')
|
| 11 |
+
for _ in range(math.ceil(1200/dt)):
|
| 12 |
+
h.step(dt)
|
| 13 |
+
if h.phase!='running':break
|
| 14 |
+
return h
|
| 15 |
+
def advance(h,stage):
|
| 16 |
+
if h.phase=='idle':h.invoke('acquisition.start')
|
| 17 |
+
for _ in range(4000):
|
| 18 |
+
h.step(.25)
|
| 19 |
+
if h.stage==stage:return
|
| 20 |
+
raise AssertionError((stage,h.phase,h.stage,h.fault))
|
| 21 |
+
class TestE916(unittest.TestCase):
|
| 22 |
+
def ledger(self,h):
|
| 23 |
+
q=h._inventory()
|
| 24 |
+
for initial,terms in [('initial_target_kg',['sorbed_target_kg','dissolved_target_kg','extract_target_kg','degraded_target_kg','removed_target_kg']),('initial_solvent_m3',['reservoir_solvent_m3','cell_solvent_m3','extract_solvent_m3','waste_solvent_m3','removed_solvent_m3']),('initial_nitrogen_mol',['remaining_nitrogen_mol','exhaust_nitrogen_mol'])]:self.assertAlmostEqual(q[initial],sum(q[k] for k in terms),places=12)
|
| 25 |
+
for c in h.cells.values():self.assertAlmostEqual(c['spec']['target_mass_kg'],c['sorbed']+c['dissolved']+c['extract']+c['degraded'],places=15)
|
| 26 |
+
def test_01_contract_and_no_clock_queries(self):
|
| 27 |
+
h=setup();m=export_buchi_speedextractore_contract_metadata();self.assertEqual(set(m['capabilities']),set(CAPS));t=h.time_s
|
| 28 |
+
for c in ['extraction.measure','product.read']:validate(CAPS[c][1],h.invoke(c))
|
| 29 |
+
for k,v in h.read('evaluator').items():validate(SLOTS[k][0],v)
|
| 30 |
+
self.assertEqual(t,h.time_s);self.assertNotIn('truth.initial_target_kg',h.read())
|
| 31 |
+
def test_02_ranges_and_atomic_rejections(self):
|
| 32 |
+
h=BuchiSpeedextractoreRuntime()
|
| 33 |
+
for updates in [dict(cycles=True),dict(cycles=1.5),dict(cycles=11),dict(pressure_gauge_pa=16e6),dict(temperature_k=474.),dict(pump_total_m3_s=51e-6/60),dict(solvent_fractions=[.5,.4,0,0]),dict(nitrogen_flush_s=59.)]:
|
| 34 |
+
old=h.read('evaluator');self.assertRaises(ActionRejected,h.invoke,'method.configure',**dict(METHOD_EXAMPLE,**updates));self.assertEqual(old,h.read('evaluator'))
|
| 35 |
+
self.assertRaises(ActionRejected,h.invoke,'method.configure',**dict(METHOD_EXAMPLE,temperature_k=473.15,pressure_gauge_pa=5e6,solvent_fractions=[1,0,0,0]))
|
| 36 |
+
def test_03_preheat_same_cells_and_clearance(self):
|
| 37 |
+
h=BuchiSpeedextractoreRuntime();h.invoke('plant.configure',**EXAMPLE);h.invoke('method.configure',**METHOD_EXAMPLE);h.invoke('power.set',enabled=True);h.invoke('shield.set_lift',lift_m=.18);h.invoke('drawer.set_extension',extension_m=.16)
|
| 38 |
+
self.assertRaises(ActionRejected,h.invoke,'sample.configure',**SAMPLE_EXAMPLE);h.invoke('thermal.preheat');h.step(100);h.invoke('sample.configure',**SAMPLE_EXAMPLE)
|
| 39 |
+
for extra in [dict(position=1,cell_volume_m3=40e-6),dict(position=True),dict(position=1,substance_id='unknown'),dict(position=1,gripper_confirmed=False)]:self.assertRaises(ActionRejected,h.invoke,'sample.configure',**dict(SAMPLE_EXAMPLE,**extra))
|
| 40 |
+
self.assertRaises(ActionRejected,h.invoke,'shield.set_lift',lift_m=0.);self.assertRaises(ActionRejected,h.invoke,'method.configure',**METHOD_EXAMPLE)
|
| 41 |
+
def test_04_complete_six_cell_conservation(self):
|
| 42 |
+
h=finish(setup());self.assertEqual(h.phase,'succeeded');self.ledger(h);self.assertEqual(len(h._product()['items']),6);self.assertEqual(h.heater,0.)
|
| 43 |
+
self.assertTrue({'sealing','tightness','fill','heatup_1','heatup_2','heatup_3','hold','discharge','nitrogen_flush','release','complete'}<={x['stage'] for x in h.history})
|
| 44 |
+
for q in h._product()['items']:self.assertGreater(q['modeled_absolute_recovery_fraction'],.1);self.assertLessEqual(q['modeled_absolute_recovery_fraction'],1);self.assertIsNone(q['measured_e916_recovery_fraction'])
|
| 45 |
+
def test_05_single_total_pump_and_inactive_flow(self):
|
| 46 |
+
for n in (1,6):
|
| 47 |
+
h=setup(n);advance(h,'fill');before=sum(h.reservoir);h.step(1.);self.assertAlmostEqual(before-sum(h.reservoir),METHOD_EXAMPLE['pump_total_m3_s']*n/6,places=13);self.ledger(h)
|
| 48 |
+
def test_06_independent_positions(self):
|
| 49 |
+
h=setup(2);h.cells[1]['spec']['kd_m3_kg_by_solvent']=[100.]*4;finish(h);q=h._product()['items'];self.assertGreater(q[0]['extract_target_kg'],q[1]['extract_target_kg']*100);self.ledger(h)
|
| 50 |
+
def test_07_real54references_and_140vapor_points(self):
|
| 51 |
+
h=BuchiSpeedextractoreRuntime();self.assertEqual(len(h.templates),54);self.assertTrue(any(q['values']['ase_to_soxtec_recovery_ratio']>1 for q in h.templates.values()))
|
| 52 |
+
for sid,q in h.templates.items():
|
| 53 |
+
r=h.invoke('reference.lookup',substance_id=sid);validate(REFERENCE,r);self.assertIsNone(q['cas']);self.assertIn('ASE',r['conditions']);self.assertIsNone(r['measured_e916_recovery_fraction'])
|
| 54 |
+
for i,sid in enumerate(SOLVENTS):
|
| 55 |
+
s=h.solvents[sid];self.assertEqual(len(s['vapor_pressure_reference_points']),35)
|
| 56 |
+
for point in s['vapor_pressure_reference_points']:
|
| 57 |
+
f=[0.]*4;f[i]=1.;self.assertLess(abs(h.saturation_pressure(point['temperature_k'],f)/point['pressure_pa']-1),1e-12)
|
| 58 |
+
self.assertAlmostEqual(h.invoke('reference.lookup',substance_id='phenol')['ase_soxtec_ratio'],1.02)
|
| 59 |
+
def test_08_cycles_increase_recovery(self):
|
| 60 |
+
a=finish(setup(1,method={'cycles':1}));b=finish(setup(1,method={'cycles':3}));self.assertGreater(b.cells[0]['extract'],a.cells[0]['extract']);self.ledger(b)
|
| 61 |
+
def test_09_transfer_and_hold_sensitivity(self):
|
| 62 |
+
a=finish(setup(1,sample={'mass_transfer_s_inv':1e-5}));b=finish(setup(1,sample={'mass_transfer_s_inv':.1}));self.assertGreater(b.cells[0]['extract'],a.cells[0]['extract']*10)
|
| 63 |
+
c=finish(setup(1,method={'hold_s':100},sample={'mass_transfer_s_inv':1e-5}));self.assertGreater(c.cells[0]['extract'],a.cells[0]['extract'])
|
| 64 |
+
def test_10_solubility_degradation_bookkeeping(self):
|
| 65 |
+
h=finish(setup(1,sample={'solubility_kg_m3':.00001,'degradation_s_inv':.001}));self.assertGreater(h.cells[0]['degraded'],0);self.assertLess(h.cells[0]['extract'],1e-8);self.ledger(h)
|
| 66 |
+
def test_11_pause_residual_and_ordered_abort(self):
|
| 67 |
+
h=setup(1);advance(h,'hold');p=h._maxp();m=h.cells[0]['dissolved'];stock=sum(h.reservoir);h.invoke('acquisition.stop');h.step(2.);self.assertEqual(h._maxp(),p);self.assertEqual(sum(h.reservoir),stock);self.assertNotEqual(h.cells[0]['dissolved'],m);self.assertRaises(ActionRejected,h.invoke,'shield.set_lift',lift_m=.18);h.invoke('acquisition.abort');finish(h);self.assertEqual((h.phase,h.stage),('cancelled','complete'));self.assertLessEqual(h._maxp(),1e5);self.ledger(h)
|
| 68 |
+
def test_12_finite_supply_failure_retains_material(self):
|
| 69 |
+
h=finish(setup(6,plant={'reservoir_m3':[1e-6]*4}));self.assertEqual(h.phase,'failed');self.assertEqual(h.fault,'solvent_supply_empty');self.ledger(h);self.assertGreater(sum(sum(c['liquid']) for c in h.cells.values()),0)
|
| 70 |
+
h=finish(setup(1,plant={'nitrogen_mol':.001}));self.assertEqual(h.fault,'nitrogen_supply_empty');self.ledger(h)
|
| 71 |
+
def test_13_vial_limit_no_disappearing_extract(self):
|
| 72 |
+
h=finish(setup(1,method={'cycles':10},plant={'vial_capacity_m3':60e-6}));self.assertEqual(h.fault,'collection_vial_full');self.assertLessEqual(sum(h.cells[0]['vial']),60e-6+1e-14);self.ledger(h)
|
| 73 |
+
def test_14_identity_idempotency_async(self):
|
| 74 |
+
h=setup(1);h.register_principal('eval','evaluator');h.register_principal('other');s=h.session();kw=dict(instance_id=h.instance_id,capability_id='acquisition.start',arguments={},request_id='start');r=s.invoke(**kw);self.assertEqual(r['status'],'accepted');self.assertEqual(r,s.invoke(**kw));self.assertEqual(h._operation_count,1);self.assertRaises(ActionRejected,h.session('other').poll,r['operation_id']);self.assertEqual(s.poll(r['operation_id'])['status'],'running');s.cancel(r['operation_id'],'cancel');self.assertEqual(h.phase,'cancelled');r=s.invoke(instance_id=h.instance_id,capability_id='product.read',arguments={},request_id='deny');self.assertEqual(r['error']['code'],'ACCESS_DENIED');self.assertRaises(ActionRejected,s.read,instance_id=h.instance_id,state_ids=['truth.initial_target_kg']);self.assertEqual(s.invoke(**dict(kw,capability_id='power.set',arguments={'enabled':False}))['error']['code'],'REQUEST_CONFLICT')
|
| 75 |
+
def test_15_convergence_power_unload_and_no_n2_discharge(self):
|
| 76 |
+
a=finish(setup(1),.25);b=finish(setup(1),.125);self.assertLess(abs(a.cells[0]['extract']/b.cells[0]['extract']-1),.01)
|
| 77 |
+
h=setup(1);advance(h,'discharge');n=h.nitrogen;h.step(1.);self.assertEqual(n,h.nitrogen);h.invoke('power.set',enabled=False);p=h._maxp();h.step(1.);self.assertEqual(h._maxp(),p);self.assertIsNone(h.read()['thermal.indicated_k']);self.ledger(h)
|
| 78 |
+
a.invoke('shield.set_lift',lift_m=.18);a.invoke('drawer.set_extension',extension_m=.16);a.invoke('sample.unload',position=0,sample_id='soil_0',gripper_confirmed=True);self.ledger(a);self.assertEqual(a._inventory()['sorbed_target_kg'],0)
|
| 79 |
+
for dt in (0,-1,True,float('nan')):self.assertRaises(ActionRejected,a.step,dt)
|
| 80 |
+
def test_16_cell_capacity_variants_and_solvent_flush(self):
|
| 81 |
+
for volume in (10e-6,40e-6):
|
| 82 |
+
h=finish(setup(1,method={'cycles':1,'solvent_flush_s':5.},sample={'cell_volume_m3':volume}));self.assertEqual(h.phase,'succeeded');self.assertIn('solvent_flush',[x['stage'] for x in h.history]);self.ledger(h)
|
| 83 |
+
if __name__=='__main__':unittest.main()
|
tests/test_asset_cem_libertyblue.py
ADDED
|
@@ -0,0 +1,93 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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'));sys.path.insert(0,str(ROOT/'skills/chemistry-lab-assets/scripts'))
|
| 4 |
+
import asset_tool
|
| 5 |
+
from asset_runtime.cem_libertyblue import *
|
| 6 |
+
def prepared(queue=None,kinetics=None,**plant):
|
| 7 |
+
h=CemLibertyblueRuntime();h.invoke('cover.set_lift',lift_m=.08);h.invoke('clamp.set_lift',lift_m=.04);h.invoke('plant.configure',**dict(copy.deepcopy(EXAMPLE),**plant));h.invoke('kinetics.configure',**dict(KINETIC_EXAMPLE,**(kinetics or {})));h.invoke('queue.configure',**(queue or QUEUE_EXAMPLE));h.invoke('cover.set_lift',lift_m=0.);h.invoke('clamp.set_lift',lift_m=0.);h.invoke('power.set',enabled=True);return h
|
| 8 |
+
class LibertyTest(unittest.TestCase):
|
| 9 |
+
def balance(self,h):
|
| 10 |
+
v=h.read('evaluator');self.assertAlmostEqual(v['truth.input_mass_kg'],sum(v['truth.'+k+'_mass_kg'] for k in ['retained','waste','vent','removed']),10)
|
| 11 |
+
for i,n in enumerate(h.initial_aa):self.assertAlmostEqual(n,sum(v['truth.'+k+'_mol'][i] for k in ['remaining_aa','bound_aa','waste_aa','removed_aa']),12)
|
| 12 |
+
for r in h.resins:
|
| 13 |
+
self.assertAlmostEqual(r['free']+r['protected'],r['site'],12);self.assertLessEqual(r['correct_free'],r['free']+1e-15);self.assertLessEqual(r['correct_protected'],r['protected']+1e-15);self.assertGreaterEqual(min(r['mass'],r['free'],r['protected'],*r['bound']),-1e-14)
|
| 14 |
+
def finish(self,h,dt=.37):
|
| 15 |
+
h.invoke('acquisition.start')
|
| 16 |
+
for _ in range(15000):
|
| 17 |
+
h.step(dt);self.balance(h)
|
| 18 |
+
if h.phase!='running':break
|
| 19 |
+
self.assertEqual(h.phase,'succeeded',h.fault)
|
| 20 |
+
def test_contract_schemas(self):
|
| 21 |
+
m=export_cem_libertyblue_contract_metadata();self.assertEqual(len(m['capabilities']),13)
|
| 22 |
+
for c in m['capabilities'].values():
|
| 23 |
+
self.assertFalse(asset_tool.lint_schema(c['input_schema']));self.assertFalse(asset_tool.lint_schema(c['output_schema']));self.assertFalse(asset_tool.validate_value(c['example_arguments'],c['input_schema']))
|
| 24 |
+
def test_all_80_real_templates_drive_query(self):
|
| 25 |
+
h=CemLibertyblueRuntime();self.assertEqual(len(h.templates),80);rows=0
|
| 26 |
+
for t in h.templates.values():
|
| 27 |
+
for i,f in enumerate(t['values']):
|
| 28 |
+
r=h.invoke('reference.lookup',substance_id=t['substance_id'],row_index=i);self.assertEqual(r['first_area'],f['values']['first_area']);self.assertAlmostEqual(r['width_minus_height'],r['first_width']-r['first_height'],12);self.assertFalse(asset_tool.validate_value(r,CAPS['reference.lookup'][1]));rows+=1
|
| 29 |
+
self.assertEqual(rows,1402)
|
| 30 |
+
def test_mass_sites_and_aa_ledger(self):
|
| 31 |
+
h=prepared();self.finish(h);self.assertGreater(sum(h.resins[0]['bound']),0);self.assertGreater(h.vent_mass,0);self.assertGreater(h.waste['volume'],0);r=h.invoke('product.read',job_index=0);self.assertTrue(r['ready_for_cleavage']);self.assertTrue(0<r['conditional_full_length_fraction']<1);self.assertIsNone(r['true_purity_fraction']);h.invoke('cover.set_lift',lift_m=.08);h.invoke('clamp.set_lift',lift_m=.04);h.invoke('resin.unload',job_index=0,resin_id='resin_01');self.balance(h)
|
| 32 |
+
def test_incomplete_deprotect_coupling_and_sequence(self):
|
| 33 |
+
outcomes=[]
|
| 34 |
+
for factor in [0.,.2,1.]:
|
| 35 |
+
q=copy.deepcopy(QUEUE_EXAMPLE)
|
| 36 |
+
for s in q['jobs'][0]['steps']:s['sequence_factor']=factor
|
| 37 |
+
h=prepared(queue=q);self.finish(h);outcomes.append(h.resins[0]['correct_free'])
|
| 38 |
+
self.assertEqual(outcomes[0],0.);self.assertLess(outcomes[1],outcomes[2])
|
| 39 |
+
h=prepared(kinetics={'deprotect_k_s_inv':0.});self.finish(h);self.assertEqual(sum(h.resins[0]['bound']),0.)
|
| 40 |
+
def test_wash_residual_changes_conditional_result(self):
|
| 41 |
+
residual=[];outcomes=[]
|
| 42 |
+
for cycles in [1,4]:
|
| 43 |
+
q=copy.deepcopy(QUEUE_EXAMPLE)
|
| 44 |
+
for s in q['jobs'][0]['steps']:s['wash_cycles']=cycles
|
| 45 |
+
h=prepared(queue=q);self.finish(h);residual.append(h.pool['base']);outcomes.append(h.resins[0]['correct_free'])
|
| 46 |
+
self.assertLess(residual[1],residual[0]);self.assertGreater(outcomes[1],outcomes[0])
|
| 47 |
+
def test_queue_module_capacities_sequential(self):
|
| 48 |
+
for module,n in [('none',1),('HT4',4),('HT12',12)]:
|
| 49 |
+
p=copy.deepcopy(EXAMPLE);p['external_stocks'][2]['volume_m3']=.001;p['external_stocks'][3]['volume_m3']=.001;q=dict(copy.deepcopy(QUEUE_EXAMPLE),jobs=[job_example('C','r'+str(i)) for i in range(n)]);h=prepared(queue=q,queue_module=module,external_stocks=p['external_stocks']);self.finish(h,1.7);self.assertEqual(len(h.resins),n);events=[p['job_index'] for p in h.history];self.assertEqual(events,sorted(events));self.assertTrue(all(r['done'] for r in h.resins))
|
| 50 |
+
def test_loading_scale_and_bad_queues_atomic(self):
|
| 51 |
+
h=CemLibertyblueRuntime();h.invoke('cover.set_lift',lift_m=.08);h.invoke('clamp.set_lift',lift_m=.04);h.invoke('plant.configure',**EXAMPLE);old=copy.deepcopy(h.__dict__)
|
| 52 |
+
for field,value in [('scale_mol',.006),('loading_mol_kg',1.),('preloaded_c_terminal','A'),('sequence_ntoc','X'),('steps',[])]:
|
| 53 |
+
q=copy.deepcopy(QUEUE_EXAMPLE);q['jobs'][0][field]=value
|
| 54 |
+
with self.assertRaises(ActionRejected):h.invoke('queue.configure',**q)
|
| 55 |
+
self.assertEqual(old,h.__dict__)
|
| 56 |
+
q=copy.deepcopy(QUEUE_EXAMPLE);q['jobs'][0]['steps'][0]['wash_cycles']=1.5
|
| 57 |
+
with self.assertRaises(ActionRejected):h.invoke('queue.configure',**q)
|
| 58 |
+
self.assertEqual(old,h.__dict__)
|
| 59 |
+
def test_hard_scale_endpoints(self):
|
| 60 |
+
for scale in [5e-6,5e-3]:
|
| 61 |
+
q=copy.deepcopy(QUEUE_EXAMPLE);q['jobs'][0].update(scale_mol=scale,resin_mass_kg=scale/.5);h=prepared(queue=q);self.assertAlmostEqual(h.resins[0]['site'],scale)
|
| 62 |
+
def test_stock_empty_partial_failure_preserves_balance(self):
|
| 63 |
+
p=copy.deepcopy(EXAMPLE);p['external_stocks'][2]['volume_m3']=.35e-6;h=prepared(external_stocks=p['external_stocks']);h.invoke('acquisition.start');h.step(4.);self.assertEqual(h.phase,'failed');self.assertIn('stock_empty',h.fault);self.assertGreater(h.pool['volume'],0);self.balance(h)
|
| 64 |
+
def test_cancel_resume_and_power_retains_stage(self):
|
| 65 |
+
h=prepared();h.invoke('acquisition.start');h.step(2.3);h.invoke('acquisition.stop');snap=h.debug_snapshot();h.step(2);self.assertEqual(snap,h.debug_snapshot());self.finish(h);h=prepared();h.invoke('acquisition.start');h.step(.4);h.invoke('power.set',enabled=False);self.assertEqual(h.phase,'cancelled');self.balance(h)
|
| 66 |
+
def test_residual_carryover_aa_effect_and_no_double_mass(self):
|
| 67 |
+
h=prepared();self.assertAlmostEqual(h.input_mass,sum(s['density_kg_m3']*s['volume_m3'] for s in h.stocks)+2e-5);self.finish(h);self.assertGreater(sum(h.waste['aa']),0.);self.assertGreater(sum(h.pool['aa']),0.)
|
| 68 |
+
def test_step_partition_consistency(self):
|
| 69 |
+
a=prepared();b=prepared();self.finish(a,.1);self.finish(b,.37);self.assertAlmostEqual(a.resins[0]['correct_free'],b.resins[0]['correct_free'],8);self.assertAlmostEqual(a.waste['volume'],b.waste['volume'],12)
|
| 70 |
+
def test_interlocks_bad_indices_and_pure_reads(self):
|
| 71 |
+
h=prepared();h.invoke('acquisition.start');old=copy.deepcopy(h.__dict__)
|
| 72 |
+
for cap,args in [('cover.set_lift',{'lift_m':.08}),('clamp.set_lift',{'lift_m':.04}),('product.read',{'job_index':True}),('reference.lookup',{'substance_id':next(iter(h.templates)),'row_index':-1})]:
|
| 73 |
+
with self.assertRaises(ActionRejected):h.invoke(cap,**args)
|
| 74 |
+
self.assertEqual(old,h.__dict__)
|
| 75 |
+
h.read();h.describe();h.invoke('synthesis.measure');h.invoke('history.read');h.invoke('product.read',job_index=0);self.assertEqual(old,h.__dict__)
|
| 76 |
+
def test_native_identity_dedup_async(self):
|
| 77 |
+
h=prepared();s=h.session();a=dict(instance_id=h.instance_id,capability_id='acquisition.start',arguments={},request_id='start');r=s.invoke(**a);self.assertEqual(r['status'],'accepted');self.assertEqual(s.invoke(**a),r);h.step(.2);self.assertEqual(s.poll(r['operation_id'])['status'],'running');self.assertNotIn('truth.free_sites_mol',s.read(instance_id=h.instance_id)['observations']);self.assertNotIn('product.read',s.describe(instance_id=h.instance_id)['capabilities']);h.register_principal('other')
|
| 78 |
+
with self.assertRaises(ActionRejected):h.session('other').poll(r['operation_id'])
|
| 79 |
+
self.assertEqual(s.cancel(r['operation_id'],'stop')['status'],'cancelled');self.balance(h)
|
| 80 |
+
def test_all_actual_outputs_and_states(self):
|
| 81 |
+
h=CemLibertyblueRuntime()
|
| 82 |
+
def ck(k,a=None):
|
| 83 |
+
r=h.invoke(k,**(CAPS[k][6] if a is None else a));self.assertFalse(asset_tool.validate_value(r,CAPS[k][1]),(k,r))
|
| 84 |
+
for k in ['cover.set_lift','clamp.set_lift','plant.configure','kinetics.configure','queue.configure','power.set']:ck(k)
|
| 85 |
+
ck('cover.set_lift',{'lift_m':0.});ck('clamp.set_lift',{'lift_m':0.});ck('acquisition.start');h.step(.2);ck('acquisition.stop');self.finish(h)
|
| 86 |
+
for k in ['synthesis.measure','history.read','product.read','reference.lookup']:ck(k)
|
| 87 |
+
ck('cover.set_lift');ck('clamp.set_lift');ck('resin.unload')
|
| 88 |
+
for k,v in h.read('evaluator').items():self.assertFalse(asset_tool.validate_value(v,SLOTS[k][0]),k)
|
| 89 |
+
def test_bad_dt(self):
|
| 90 |
+
h=prepared()
|
| 91 |
+
for dt in [0,-1,True,float('nan'),float('inf')]:
|
| 92 |
+
with self.assertRaises(ValueError):h.step(dt)
|
| 93 |
+
if __name__=='__main__':unittest.main()
|
tests/test_asset_cytiva_ktaoligosynt.py
ADDED
|
@@ -0,0 +1,97 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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'));sys.path.insert(0,str(ROOT/'skills/chemistry-lab-assets/scripts'))
|
| 4 |
+
import asset_tool
|
| 5 |
+
from asset_runtime.cytiva_ktaoligosynt import *
|
| 6 |
+
def prepared(method=None,kinetics=None,**plant):
|
| 7 |
+
h=CytivaKtaoligosyntRuntime();h.invoke('clamp.set_lift',lift_m=.04);h.invoke('plant.configure',**dict(copy.deepcopy(EXAMPLE),**plant));h.invoke('kinetics.configure',**dict(copy.deepcopy(KINETIC_EXAMPLE),**(kinetics or {})));h.invoke('method.configure',**copy.deepcopy(method or METHOD_EXAMPLE));h.invoke('clamp.set_lift',lift_m=0.);h.invoke('power.set',enabled=True);return h
|
| 8 |
+
class OligosyntTest(unittest.TestCase):
|
| 9 |
+
def balance(self,h):
|
| 10 |
+
v=h.read('evaluator');self.assertAlmostEqual(v['truth.input_mass_kg'],sum(v['truth.'+k+'_mass_kg'] for k in ['retained','waste','removed']),9)
|
| 11 |
+
for i,n in enumerate(h.initial_monomer):self.assertAlmostEqual(n,sum(v['truth.'+k+'_monomer_mol'][i] for k in ['remaining','bound','waste','removed']),11)
|
| 12 |
+
for r in h.columns.values():
|
| 13 |
+
self.assertAlmostEqual(r['free']+r['protected']+r['capped'],r['site'],12);self.assertLessEqual(r['correct_free'],r['free']+1e-14);self.assertLessEqual(r['correct_protected']+r['pending'],r['protected']+1e-14);self.assertGreaterEqual(min(r['mass'],r['free'],r['protected'],r['capped'],r['unoxidized'],*r['bound']),-1e-14)
|
| 14 |
+
self.assertGreaterEqual(min([p['mass'] for p in h.pools.values()]+[n for p in h.pools.values() for n in p['tags']]),0.)
|
| 15 |
+
def finish(self,h,dt=1.7):
|
| 16 |
+
h.invoke('acquisition.start')
|
| 17 |
+
for _ in range(5000):
|
| 18 |
+
h.step(dt);self.balance(h)
|
| 19 |
+
if h.phase!='running':break
|
| 20 |
+
self.assertEqual(h.phase,'succeeded',h.fault)
|
| 21 |
+
def test_contract_schemas(self):
|
| 22 |
+
m=export_cytiva_ktaoligosynt_contract_metadata();self.assertEqual(len(m['capabilities']),12)
|
| 23 |
+
for c in m['capabilities'].values():
|
| 24 |
+
self.assertFalse(asset_tool.lint_schema(c['input_schema']));self.assertFalse(asset_tool.lint_schema(c['output_schema']));self.assertFalse(asset_tool.validate_value(c['example_arguments'],c['input_schema']))
|
| 25 |
+
def test_all_80_real_templates_368_records(self):
|
| 26 |
+
h=CytivaKtaoligosyntRuntime();self.assertEqual(len(h.templates),80);rows=0
|
| 27 |
+
for t in h.templates.values():
|
| 28 |
+
for i,f in enumerate(t['values']):
|
| 29 |
+
r=h.invoke('reference.lookup',substance_id=t['substance_id'],row_index=i);self.assertFalse(asset_tool.validate_value(r,CAPS['reference.lookup'][1]));self.assertEqual(r['sequence_5to3'],t['sequence_5to3']);self.assertTrue(r['template_source']);rows+=1
|
| 30 |
+
if t['kind']=='measured_retention':self.assertAlmostEqual(r['normalized_retention_s'],f['original_retention_min']*60,10)
|
| 31 |
+
else:self.assertAlmostEqual(r['epsilon_m2_mol'],f['original_epsilon_l_mol_cm']*.1,10)
|
| 32 |
+
self.assertEqual(rows,368)
|
| 33 |
+
def test_mass_sites_monomer_and_unload(self):
|
| 34 |
+
h=prepared();self.finish(h);r=h.invoke('product.read',column_position=1);self.assertTrue(0<r['conditional_full_length_fraction']<1);self.assertGreater(r['unoxidized_link_mol'],0);self.assertIsNone(r['true_purity_fraction']);h.invoke('clamp.set_lift',lift_m=.04);h.invoke('support.unload',column_position=1,support_id='support_1');self.balance(h)
|
| 35 |
+
with self.assertRaises(ActionRejected):h.invoke('support.unload',column_position=1,support_id='support_1')
|
| 36 |
+
def test_oxidation_zero_preserves_physical_links(self):
|
| 37 |
+
q=copy.deepcopy(METHOD_EXAMPLE);q['jobs']=[job_example('AGC')];h=prepared(method=q,kinetics={'oxidation_k_s_inv':0.});self.finish(h);r=h.columns[1];self.assertGreater(r['unoxidized'],0);self.assertAlmostEqual(r['unoxidized'],sum(r['bound']),12);self.assertEqual(h.invoke('product.read',column_position=1)['conditional_full_length_fraction'],0.)
|
| 38 |
+
def test_zero_detritylation_and_sequence_factor(self):
|
| 39 |
+
h=prepared(kinetics={'detritylation_k_s_inv':0.});self.finish(h);self.assertEqual(sum(h.columns[1]['bound']),0.)
|
| 40 |
+
values=[]
|
| 41 |
+
for f in [0.,.2,1.]:
|
| 42 |
+
q=copy.deepcopy(METHOD_EXAMPLE)
|
| 43 |
+
for s in q['jobs'][0]['steps']:s['sequence_factor']=f
|
| 44 |
+
h=prepared(method=q);self.finish(h);values.append(h.columns[1]['correct_free'])
|
| 45 |
+
self.assertEqual(values[0],0.);self.assertLess(values[1],values[2])
|
| 46 |
+
def test_wash_changes_carryover(self):
|
| 47 |
+
values=[]
|
| 48 |
+
for t in [1.,9.]:
|
| 49 |
+
q=copy.deepcopy(METHOD_EXAMPLE)
|
| 50 |
+
for s in q['jobs'][0]['steps']:s['wash_s']=t
|
| 51 |
+
h=prepared(method=q);self.finish(h);values.append((h.pools['column_1']['tags'][4],h.columns[1]['correct_free']))
|
| 52 |
+
self.assertLess(values[1][0],values[0][0]);self.assertGreater(values[1][1],values[0][1])
|
| 53 |
+
def test_recirculation_no_external_consumption_or_waste(self):
|
| 54 |
+
h=prepared();h.invoke('acquisition.start')
|
| 55 |
+
while h._values()['cycle.stage']!='recirculate':h.step(.01)
|
| 56 |
+
h.step(.01);stocks=[s['volume_m3'] for s in h.stocks];waste=sum(w['volume'] for w in h.wastes);h.step(.2);self.assertTrue(h.recirculating);self.assertEqual(stocks,[s['volume_m3'] for s in h.stocks]);self.assertEqual(waste,sum(w['volume'] for w in h.wastes));self.balance(h)
|
| 57 |
+
def test_five_columns_serial_and_stagnant_unselected(self):
|
| 58 |
+
q=dict(copy.deepcopy(METHOD_EXAMPLE),jobs=[job_example('C',i) for i in range(1,6)],waste_position=11);h=prepared(method=q);prime=copy.deepcopy(h.pools['column_5']);h.invoke('acquisition.start');h.step(1.);self.assertEqual(prime,h.pools['column_5']);h.step(100.);self.assertEqual(h.phase,'succeeded');self.balance(h);self.assertTrue(all(r['done'] for r in h.columns.values()));self.assertEqual([p['column_position'] for p in h.history],sorted(p['column_position'] for p in h.history));self.assertTrue(all(w['volume']==0 for w in h.wastes[:10]));self.assertGreater(h.wastes[10]['volume'],0)
|
| 59 |
+
def test_loading_geometry_scale_endpoints_and_atomic_bad(self):
|
| 60 |
+
for scale in [1e-5,.012]:
|
| 61 |
+
q=copy.deepcopy(METHOD_EXAMPLE);q['jobs'][0].update(scale_mol=scale,support_mass_kg=scale/.5);h=prepared(method=q);self.assertEqual(h.columns[1]['site'],scale)
|
| 62 |
+
h=CytivaKtaoligosyntRuntime();h.invoke('clamp.set_lift',lift_m=.04);h.invoke('plant.configure',**EXAMPLE);old=copy.deepcopy(h.__dict__)
|
| 63 |
+
for field,value in [('scale_mol',.013),('loading_mol_kg',1.),('preloaded_3prime','A'),('sequence_5to3','AU'),('column_position',True),('steps',[]),('diameter_m',.1)]:
|
| 64 |
+
q=copy.deepcopy(METHOD_EXAMPLE);q['jobs'][0][field]=value
|
| 65 |
+
with self.assertRaises(ActionRejected):h.invoke('method.configure',**q)
|
| 66 |
+
self.assertEqual(old,h.__dict__)
|
| 67 |
+
def test_pressure_system_and_uv_limits(self):
|
| 68 |
+
for kwargs in [dict(line_resistance_pa_s_m3=6e12),dict(outlet_resistance_pa_s_m3=4.2e12)]:
|
| 69 |
+
h=prepared(**kwargs);before=h._inventory();h.invoke('acquisition.start');h.step(.1);self.assertEqual(h.phase,'failed');self.assertEqual(h.fault,'pressure_limit');self.assertEqual(before,h._inventory());self.balance(h)
|
| 70 |
+
h=prepared(outlet_resistance_pa_s_m3=4.2e12);e=h.plan[0];p,uvp=h._hydraulics(e,.5e-6);self.assertLess(p,2.5e6);self.assertGreater(uvp,2e6)
|
| 71 |
+
def test_flow_high_flow_kit_and_three_wavelength_grid(self):
|
| 72 |
+
q=copy.deepcopy(METHOD_EXAMPLE);q['pump_a_flow_m3_s']=150e-6/60;q['pump_b_flow_m3_s']=150e-6/60
|
| 73 |
+
with self.assertRaises(ActionRejected):prepared(method=q)
|
| 74 |
+
h=prepared(method=q,high_flow_kit=True);wash=next(e for e in h.plan if e['kind']=='wash');self.assertAlmostEqual(sum(f for _,f in wash['feeds']),300e-6/60)
|
| 75 |
+
with self.assertRaises(ActionRejected):prepared(kinetics={'wavelengths_m':[260.5e-9,280e-9,498e-9]})
|
| 76 |
+
def test_stock_empty_preserves_partial_transport(self):
|
| 77 |
+
stocks=copy.deepcopy(EXAMPLE['stocks']);stocks[19]['volume_m3']=.35e-6;h=prepared(stocks=stocks);h.invoke('acquisition.start');h.step(2.);self.assertEqual(h.phase,'failed');self.assertEqual(h.fault,'stock_empty');self.assertAlmostEqual(h.elapsed_s,.7,8);self.assertGreater(h.pools['mix']['tags'][4],0);self.balance(h)
|
| 78 |
+
def test_cancel_power_and_step_partition(self):
|
| 79 |
+
h=prepared();h.invoke('acquisition.start');h.step(2.3);h.invoke('acquisition.stop');snap=h.debug_snapshot();h.step(3);self.assertEqual(snap,h.debug_snapshot());self.finish(h);a=prepared();self.finish(a,.37);self.assertAlmostEqual(h.columns[1]['correct_free'],a.columns[1]['correct_free'],8);self.assertAlmostEqual(sum(w['volume'] for w in h.wastes),sum(w['volume'] for w in a.wastes),12)
|
| 80 |
+
h=prepared();h.invoke('acquisition.start');h.step(.1);h.invoke('power.set',enabled=False);self.assertEqual(h.phase,'cancelled');self.assertEqual(h._signals(),([None]*3,None));self.balance(h)
|
| 81 |
+
def test_interlocks_pure_reads_native_identity_async(self):
|
| 82 |
+
h=prepared();s=h.session();a=dict(instance_id=h.instance_id,capability_id='acquisition.start',arguments={},request_id='start');r=s.invoke(**a);self.assertEqual(r['status'],'accepted');self.assertEqual(r,s.invoke(**a));h.step(.2);self.assertEqual(s.poll(r['operation_id'])['status'],'running');old=copy.deepcopy(h.__dict__)
|
| 83 |
+
with self.assertRaises(ActionRejected):h.invoke('clamp.set_lift',lift_m=.04)
|
| 84 |
+
h.read();h.describe();h.invoke('synthesis.measure');h.invoke('history.read');self.assertEqual(old,h.__dict__);self.assertNotIn('truth.input_mass_kg',s.read(instance_id=h.instance_id)['observations']);self.assertNotIn('product.read',s.describe(instance_id=h.instance_id)['capabilities']);h.register_principal('other')
|
| 85 |
+
with self.assertRaises(ActionRejected):h.session('other').poll(r['operation_id'])
|
| 86 |
+
self.assertEqual(s.cancel(r['operation_id'],'stop')['status'],'cancelled');b=prepared();self.assertEqual(b.phase,'idle');self.assertEqual(b.elapsed_s,0.)
|
| 87 |
+
def test_all_outputs_states_and_invalid_dt(self):
|
| 88 |
+
h=CytivaKtaoligosyntRuntime()
|
| 89 |
+
def ck(k,a=None):
|
| 90 |
+
r=h.invoke(k,**(CAPS[k][6] if a is None else a));self.assertFalse(asset_tool.validate_value(r,CAPS[k][1]),(k,r))
|
| 91 |
+
for k in ['clamp.set_lift','plant.configure','kinetics.configure','method.configure','power.set']:ck(k)
|
| 92 |
+
ck('clamp.set_lift',{'lift_m':0.});ck('acquisition.start');h.step(.2);ck('acquisition.stop');self.finish(h)
|
| 93 |
+
for k in ['synthesis.measure','history.read','product.read','reference.lookup','clamp.set_lift','support.unload']:ck(k)
|
| 94 |
+
for k,v in h.read('evaluator').items():self.assertFalse(asset_tool.validate_value(v,SLOTS[k][0]),k)
|
| 95 |
+
for dt in [0,-1,True,float('nan'),float('inf')]:
|
| 96 |
+
with self.assertRaises(ValueError):h.step(dt)
|
| 97 |
+
if __name__=='__main__':unittest.main()
|
tests/test_asset_elma_elmasonics60h.py
ADDED
|
@@ -0,0 +1,62 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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'));sys.path.insert(0,str(ROOT/'skills/chemistry-lab-assets/scripts'))
|
| 4 |
+
from asset_runtime.elma_elmasonics60h import ElmaElmasonics60hRuntime,CAPS,SLOTS,TIMES,ActionRejected,export_elma_elmasonics60h_contract_metadata
|
| 5 |
+
import asset_tool
|
| 6 |
+
def ready(h,load=True):
|
| 7 |
+
h.invoke('cover.set_lift',lift_m=.3);h.invoke('bath.configure',**CAPS['bath.configure'][6])
|
| 8 |
+
if load:h.invoke('load.configure',**CAPS['load.configure'][6])
|
| 9 |
+
h.invoke('cover.set_lift',lift_m=0.);h.invoke('power.set',enabled=True)
|
| 10 |
+
def energy_error(h):
|
| 11 |
+
s=h.read('evaluator');return s['energy.heater_input_j']+s['energy.ultrasound_input_j']+s['energy.loading_input_j']-sum(s['energy.'+k+'_j'] for k in ['stored','ambient_loss','acoustic_loss','unloading_output'])
|
| 12 |
+
class TestS60H(unittest.TestCase):
|
| 13 |
+
def test_pure_read_and_setpoint(self):
|
| 14 |
+
h=ElmaElmasonics60hRuntime();h.invoke('thermal.set_temperature',temperature_k=333.15);self.assertEqual(h.temperature,298.15);old=copy.deepcopy(h.__dict__);h.read();h.describe();h.invoke('status.measure');h.session().read(instance_id=h.instance_id);self.assertEqual(old,h.__dict__)
|
| 15 |
+
def test_rejection_atomic(self):
|
| 16 |
+
h=ElmaElmasonics60hRuntime()
|
| 17 |
+
for cap,a in [('ultrasound.start',{'temperature_controlled':False}),('thermal.set_enabled',{'enabled':True}),('bath.configure',CAPS['bath.configure'][6]),('thermal.set_temperature',{'temperature_k':314.15}),('timer.configure',{'continuous':False,'duration_s':360.}),('power.set',{'enabled':1}),('drain.set_angle',{'angle_rad':float('nan')})]:
|
| 18 |
+
old=copy.deepcopy(h.__dict__)
|
| 19 |
+
with self.assertRaises(ActionRejected):h.invoke(cap,**a)
|
| 20 |
+
self.assertEqual(old,h.__dict__)
|
| 21 |
+
def test_all_manufacturer_timer_stages(self):
|
| 22 |
+
h=ElmaElmasonics60hRuntime()
|
| 23 |
+
for d in TIMES:h.invoke('timer.configure',continuous=False,duration_s=d);self.assertEqual(h.duration,d)
|
| 24 |
+
for i in range(11):h.invoke('thermal.select_stage',stage=i);self.assertEqual(h.target,303.15+5*i)
|
| 25 |
+
for i in [True,2.1,-1,11]:
|
| 26 |
+
with self.assertRaises(ActionRejected):h.invoke('thermal.select_stage',stage=i)
|
| 27 |
+
def test_timed_complete_and_independent_heat(self):
|
| 28 |
+
h=ElmaElmasonics60hRuntime();ready(h);h.invoke('thermal.set_enabled',enabled=True);h.invoke('ultrasound.start',temperature_controlled=False);h.step(61);self.assertEqual(h.phase,'succeeded');self.assertTrue(h.heater);self.assertEqual(h.elapsed_s,60.);self.assertFalse(h.active)
|
| 29 |
+
def test_peak_not_average_and_energy(self):
|
| 30 |
+
h=ElmaElmasonics60hRuntime();ready(h);h.invoke('ultrasound.start',temperature_controlled=False);h.step(10);self.assertAlmostEqual(h.energy['ultrasound_input'],1500.);self.assertGreater(h.temperature,298.15);self.assertAlmostEqual(energy_error(h),0.,7)
|
| 31 |
+
def test_sweep_degas_mutual_exclusion_and_auto(self):
|
| 32 |
+
h=ElmaElmasonics60hRuntime();ready(h);h.invoke('ultrasound.set_mode',mode='sweep');h.invoke('degas.start');self.assertEqual(h.mode,'degas')
|
| 33 |
+
with self.assertRaises(ActionRejected):h.invoke('ultrasound.set_mode',mode='sweep')
|
| 34 |
+
h.step(600);self.assertEqual(h.phase,'succeeded');self.assertEqual(h.elapsed_s,600);self.assertIsNone(h._measure()['degassing_fraction']);self.assertAlmostEqual(energy_error(h),0.,6)
|
| 35 |
+
def test_temperature_controlled_wait_mix(self):
|
| 36 |
+
h=ElmaElmasonics60hRuntime();ready(h);h.invoke('thermal.set_temperature',temperature_k=303.15);h.invoke('thermal.set_enabled',enabled=True);h.invoke('ultrasound.start',temperature_controlled=True);h.step(65);self.assertTrue(h.waiting);self.assertEqual(h.elapsed_s,0.);self.assertAlmostEqual(h.energy['ultrasound_input'],750.)
|
| 37 |
+
h.step(300);self.assertFalse(h.waiting);self.assertEqual(h.phase,'succeeded');self.assertTrue(h.heater);self.assertAlmostEqual(energy_error(h),0.,6)
|
| 38 |
+
def test_continuous_twelve_hour_off(self):
|
| 39 |
+
h=ElmaElmasonics60hRuntime();ready(h,False);h.invoke('timer.configure',continuous=True,duration_s=60.);h.invoke('ultrasound.set_mode',mode='degas');h.invoke('ultrasound.start',temperature_controlled=False);self.assertIsNone(h.read()['timer.remaining_s']);h.step(43200);self.assertEqual(h.phase,'succeeded');self.assertFalse(h.powered)
|
| 40 |
+
def test_mass_energy_loading_draining(self):
|
| 41 |
+
h=ElmaElmasonics60hRuntime();h.invoke('cover.set_lift',lift_m=.3);h.invoke('bath.configure',**dict(CAPS['bath.configure'][6],initial_temperature_k=288.15));h.invoke('load.configure',**dict(CAPS['load.configure'][6],initial_temperature_k=333.15));self.assertAlmostEqual(energy_error(h),0.,7)
|
| 42 |
+
h.invoke('power.set',enabled=True);h.invoke('thermal.set_enabled',enabled=True);h.step(300);h.invoke('power.set',enabled=False);h.invoke('load.unload');h.invoke('drain.set_angle',angle_rad=math.pi/2);v=h.volume;h.step(20);self.assertLess(h.volume,v);self.assertAlmostEqual(h.mass_in,h._mass()+h.mass_out,10);self.assertAlmostEqual(energy_error(h),0.,6);h.step(1200);self.assertEqual(h.volume,0.);self.assertAlmostEqual(h.mass_in,h.mass_out,10)
|
| 43 |
+
def test_privileges_async_cancel_dedup(self):
|
| 44 |
+
h=ElmaElmasonics60hRuntime();ready(h);s=h.session();a=dict(instance_id=h.instance_id,capability_id='ultrasound.start',arguments={'temperature_controlled':False},request_id='start');r=s.invoke(**a);self.assertEqual(r['status'],'accepted');self.assertEqual(s.invoke(**a),r);h.step(10);temp=h.temperature;self.assertEqual(s.cancel(r['operation_id'],'cancel')['status'],'cancelled');self.assertEqual(h.temperature,temp)
|
| 45 |
+
h.register_principal('other');
|
| 46 |
+
with self.assertRaises(ActionRejected):h.session('other').poll(r['operation_id'])
|
| 47 |
+
with self.assertRaises(ActionRejected):s.read(instance_id=h.instance_id,state_ids=['bath.volume_m3'])
|
| 48 |
+
self.assertNotIn('bath.configure',s.describe(instance_id=h.instance_id)['capabilities']);self.assertEqual(s.invoke(**dict(a,capability_id='ultrasound.stop',arguments={}))['status'],'rejected')
|
| 49 |
+
def test_two_instances_and_dt(self):
|
| 50 |
+
a=ElmaElmasonics60hRuntime('a');b=ElmaElmasonics60hRuntime('b');old=copy.deepcopy(b.__dict__);ready(a);a.invoke('degas.start');a.step(10);self.assertEqual(b.__dict__,old)
|
| 51 |
+
old=copy.deepcopy(a.__dict__);a.step(0);self.assertEqual(old,a.__dict__)
|
| 52 |
+
for x in [-1,True,float('nan'),float('inf')]:
|
| 53 |
+
with self.assertRaises(ActionRejected):a.step(x)
|
| 54 |
+
def test_all_capability_results_schemas(self):
|
| 55 |
+
h=ElmaElmasonics60hRuntime();seen=set()
|
| 56 |
+
def call(cap,**a):
|
| 57 |
+
r=h.invoke(cap,**a);seen.add(cap);self.assertEqual(asset_tool.validate_value(r,CAPS[cap][1]),[],cap)
|
| 58 |
+
for cap in ['cover.set_lift','bath.configure','load.configure','thermal.set_temperature','thermal.select_stage','timer.configure','ultrasound.set_mode','power.set','thermal.set_enabled','ultrasound.start']:call(cap,**CAPS[cap][6])
|
| 59 |
+
h.step(60);call('degas.start');h.step(3);call('ultrasound.stop');call('power.set',enabled=False);call('load.unload');call('drain.set_angle',angle_rad=math.pi/2);h.step(3);call('status.measure');self.assertEqual(seen,set(CAPS))
|
| 60 |
+
for k,v in h.read('evaluator').items():self.assertEqual(asset_tool.validate_value(v,SLOTS[k][0]),[],k)
|
| 61 |
+
for c in export_elma_elmasonics60h_contract_metadata()['capabilities'].values():self.assertEqual(asset_tool.lint_schema(c['input_schema']),[]);self.assertEqual(asset_tool.lint_schema(c['output_schema']),[])
|
| 62 |
+
if __name__=='__main__':unittest.main()
|
tests/test_asset_genevac_mivac2.py
ADDED
|
@@ -0,0 +1,92 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import copy,hashlib,importlib.util,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.genevac_mivac2 import *
|
| 5 |
+
def prepared(instance='mivac_01',plant=None,method=None,sample=None):
|
| 6 |
+
r=GenevacMivac2Runtime(instance);r.invoke('plant.configure',**(plant or PLANT_EXAMPLE));r.invoke('rotor.configure',configuration='two_swing_six_shallow',accessory_compatibility_reviewed=True);r.invoke('method.configure',**(method or METHOD_EXAMPLE));r.invoke('sample.configure',**(sample or example_sample()));r.invoke('lid.set_open',open=False);r.invoke('power.set',enabled=True);return r
|
| 7 |
+
class MiVacTests(unittest.TestCase):
|
| 8 |
+
def conserve(self,r):
|
| 9 |
+
for row in r.records:self.assertAlmostEqual(row['initial_mol'],row['liquid_mol']+row['captured_mol']+row['exhaust_mol'],places=13)
|
| 10 |
+
self.assertLessEqual(r._mass('captured_mol'),r.plant['trap_capacity_kg']+1e-12)
|
| 11 |
+
def reject_unchanged(self,r,cap,args):
|
| 12 |
+
before=r.debug_snapshot()
|
| 13 |
+
with self.assertRaises(ActionRejected):r.invoke(cap,**args)
|
| 14 |
+
self.assertEqual(before,r.debug_snapshot())
|
| 15 |
+
def test_01_real_templates_raw_sha_and_ranges(self):
|
| 16 |
+
r=GenevacMivac2Runtime();self.assertGreaterEqual(len(r.templates),50);self.assertEqual(len(r.templates),len({x['cas'] for x in r.templates.values()}))
|
| 17 |
+
for row in r.templates.values():
|
| 18 |
+
self.assertEqual(row['sha256'],hashlib.sha256((ROOT/row['raw_source']).read_bytes()).hexdigest())
|
| 19 |
+
for fit in row['fits']:
|
| 20 |
+
for point in fit['reference_points']:self.assertAlmostEqual(r._psat(row['substance_id'],fit['fit_id'],point['temperature_k']),point['pressure_pa'],places=7)
|
| 21 |
+
def test_02_all_templates_execute_without_extrapolation(self):
|
| 22 |
+
library=GenevacMivac2Runtime().templates
|
| 23 |
+
for sid,row in library.items():
|
| 24 |
+
f=row['fits'][0];t=sum(f['runtime_temperature_range_k'])/2;s=example_sample()
|
| 25 |
+
for p in s['plates']:p['species']=[dict(substance_id=sid,fit_id=f['fit_id'],amount_mol=.01)]
|
| 26 |
+
r=prepared(plant=dict(PLANT_EXAMPLE,initial_temperature_k=t),method=dict(METHOD_EXAMPLE,temperature_k=t,duration_s=15.),sample=s);r.invoke('acquisition.start');r.step(15.);self.assertEqual(r.phase,'succeeded',sid);self.conserve(r)
|
| 27 |
+
def test_03_multisolvent_mass_nonvolatile_conserved(self):
|
| 28 |
+
r=prepared();r.invoke('acquisition.start');r.step(60.);self.conserve(r);self.assertLess(r._fraction(),1.);self.assertGreater(r._mass('captured_mol'),0.);self.assertAlmostEqual(r.invoke('product.read')['nonvolatile_mass_kg'],.0006)
|
| 29 |
+
def test_04_finite_trap_exhaust_not_lost(self):
|
| 30 |
+
r=prepared(plant=dict(PLANT_EXAMPLE,trap_capacity_kg=1e-6,trap_efficiency=1.));r.invoke('acquisition.start');r.step(60.);self.conserve(r);self.assertAlmostEqual(r._mass('captured_mol'),1e-6);self.assertGreater(r._mass('exhaust_mol'),0.)
|
| 31 |
+
def test_05_lid_interlock_and_spin_down(self):
|
| 32 |
+
r=prepared();r.invoke('acquisition.start');r.step(20.);r.invoke('acquisition.stop');self.reject_unchanged(r,'lid.set_open',dict(open=True));r.step(30.);self.assertFalse(r._locked());r.invoke('lid.set_open',open=True);self.assertTrue(r.open)
|
| 33 |
+
def test_06_cancel_preserves_partial_effects(self):
|
| 34 |
+
r=prepared();r.invoke('acquisition.start');r.step(30.);before=copy.deepcopy(r.records);r.invoke('acquisition.stop');r.step(30.);self.assertEqual(before,r.records);self.assertLess(r._fraction(),1.);self.conserve(r)
|
| 35 |
+
def test_07_resume_accumulated_runtime(self):
|
| 36 |
+
r=prepared(method=dict(METHOD_EXAMPLE,duration_s=30.));r.invoke('acquisition.start');r.step(20.);r.invoke('acquisition.stop');r.step(20.);elapsed=r.elapsed_s;r.invoke('acquisition.start');r.step(10.);self.assertAlmostEqual(elapsed,20.);self.assertEqual(r.phase,'succeeded');self.conserve(r)
|
| 37 |
+
def test_08_read_does_not_step(self):
|
| 38 |
+
r=prepared();before=r.debug_snapshot();r.read();r.session().read(instance_id=r.instance_id);r.invoke('evaporation.measure');r.invoke('history.read');self.assertEqual(before,r.debug_snapshot())
|
| 39 |
+
def test_09_temperature_set_not_instant(self):
|
| 40 |
+
r=prepared();t=r.temperature;r.invoke('temperature.set',temperature_k=323.15);self.assertEqual(r.temperature,t);r.invoke('acquisition.start');r.step(1.);self.assertGreater(r.temperature,t);self.assertLess(r.temperature,323.15)
|
| 41 |
+
def test_10_pressure_controller_optional(self):
|
| 42 |
+
r=GenevacMivac2Runtime();r.invoke('plant.configure',**dict(PLANT_EXAMPLE,pressure_controller_installed=False));self.reject_unchanged(r,'method.configure',METHOD_EXAMPLE);r.invoke('method.configure',**dict(METHOD_EXAMPLE,target_pressure_pa=None));self.assertIsNone(r.method['target_pressure_pa'])
|
| 43 |
+
def test_11_limits_nan_bool_and_integer(self):
|
| 44 |
+
r=prepared()
|
| 45 |
+
for t in [303.14,353.16,float('nan'),float('inf'),True]:self.reject_unchanged(r,'temperature.set',dict(temperature_k=t))
|
| 46 |
+
for dt in [-1.,float('nan'),float('inf'),True]:
|
| 47 |
+
before=r.debug_snapshot()
|
| 48 |
+
with self.assertRaises(ActionRejected):r.step(dt)
|
| 49 |
+
self.assertEqual(before,r.debug_snapshot())
|
| 50 |
+
bad=example_sample();bad['plates'][0]['plate_index']=.5
|
| 51 |
+
with self.assertRaises(ActionRejected):validate(SAMPLE,bad)
|
| 52 |
+
def test_12_reference_boundary_and_unknown(self):
|
| 53 |
+
r=prepared();self.reject_unchanged(r,'temperature.set',dict(temperature_k=353.15));self.reject_unchanged(r,'reference.lookup',dict(substance_id='water',fit_id='0',temperature_k=303.15));self.reject_unchanged(r,'reference.lookup',dict(substance_id='unobtainium',fit_id='0',temperature_k=313.15))
|
| 54 |
+
def test_13_start_and_busy_guards(self):
|
| 55 |
+
r=GenevacMivac2Runtime();self.reject_unchanged(r,'acquisition.start',{});r=prepared();r.invoke('lid.set_open',open=True);self.reject_unchanged(r,'acquisition.start',{});r.invoke('lid.set_open',open=False);r.invoke('acquisition.start');self.reject_unchanged(r,'temperature.set',dict(temperature_k=313.15));self.reject_unchanged(r,'rotor.configure',dict(configuration='two_swing_six_shallow',accessory_compatibility_reviewed=True))
|
| 56 |
+
def test_14_balance_rejects_before_start(self):
|
| 57 |
+
s=example_sample();s['plates'][0]['tare_mass_kg']+=.002;r=prepared(sample=s);self.reject_unchanged(r,'acquisition.start',{})
|
| 58 |
+
def test_15_poweroff_spin_down_retains_solvent(self):
|
| 59 |
+
r=prepared();r.invoke('acquisition.start');r.step(30.);before=copy.deepcopy(r.records);r.invoke('power.set',enabled=False);self.assertEqual(r.phase,'cancelled');r.step(20.);self.assertEqual(before,r.records);self.assertEqual(r.speed,0.)
|
| 60 |
+
def test_16_timeout_and_duration(self):
|
| 61 |
+
for timeout,duration,phase in [(10.,20.,'failed'),(20.,10.,'succeeded')]:
|
| 62 |
+
r=prepared(method=dict(METHOD_EXAMPLE,timeout_s=timeout,duration_s=duration));r.invoke('acquisition.start');r.step(25.);self.assertEqual(r.phase,phase);self.conserve(r)
|
| 63 |
+
def test_17_native_auth_filter_and_write(self):
|
| 64 |
+
r=prepared();s=r.session();meta=s.describe(instance_id=r.instance_id);self.assertNotIn('plant.configure',meta['capabilities']);self.assertFalse(any(k.startswith('truth.') for k in s.read(instance_id=r.instance_id)['observations']))
|
| 65 |
+
response=s.invoke(instance_id=r.instance_id,capability_id='product.read',arguments={},request_id='deny');self.assertEqual(response['status'],'rejected');self.assertNotIn('records',json.dumps(response));self.assertEqual(s.write(instance_id=r.instance_id,state_id='thermal.target_k',value=313.15,request_id='write')['status'],'succeeded')
|
| 66 |
+
with self.assertRaises(ActionRejected):s.read(instance_id=r.instance_id,state_ids=['truth.liquid_mol'])
|
| 67 |
+
def test_18_native_dedup_conflict_async_owner(self):
|
| 68 |
+
r=prepared();s=r.session();args=dict(instance_id=r.instance_id,capability_id='acquisition.start',arguments={},request_id='start');a=s.invoke(**args);self.assertEqual(a,s.invoke(**args));op=a['operation_id'];self.assertEqual(a['status'],'accepted');r.step(20.);self.assertEqual(s.poll(op)['status'],'running');r.register_principal('other');
|
| 69 |
+
with self.assertRaises(ActionRejected):r.session('other').poll(op)
|
| 70 |
+
b=s.invoke(instance_id=r.instance_id,capability_id='acquisition.stop',arguments={},request_id='start');self.assertEqual(b['status'],'rejected');self.assertEqual(s.cancel(op,'cancel')['status'],'cancelled')
|
| 71 |
+
def test_19_dual_instance_independent(self):
|
| 72 |
+
a=prepared('a');b=prepared('b');old=b.debug_snapshot();a.invoke('acquisition.start');a.step(20.);self.assertEqual(b.debug_snapshot(),old);self.assertNotEqual(a.records,b.records)
|
| 73 |
+
def test_20_programs_explicit_duty(self):
|
| 74 |
+
pressures=[]
|
| 75 |
+
for program in ['water','alcohol','other']:
|
| 76 |
+
r=prepared(plant=dict(PLANT_EXAMPLE,water_pump_duty=.2,alcohol_pump_duty=.5,program_period_s=20.),method=dict(METHOD_EXAMPLE,program=program));r.invoke('acquisition.start');r.step(18.);pressures.append(r.pressure);self.conserve(r)
|
| 77 |
+
self.assertGreater(pressures[0],pressures[2]);self.assertGreater(pressures[1],pressures[2])
|
| 78 |
+
def test_21_heater_timer_freezes_prescribed_temperature(self):
|
| 79 |
+
r=prepared(method=dict(METHOD_EXAMPLE,heating_time_s=1.));r.invoke('acquisition.start');r.step(2.);t=r.temperature;r.step(2.);self.assertAlmostEqual(t,r.temperature)
|
| 80 |
+
def test_22_endpoint_partial_residual_not_dry_claim(self):
|
| 81 |
+
r=prepared(method=dict(METHOD_EXAMPLE,endpoint_remaining_fraction=.99));r.invoke('acquisition.start');r.step(60.);self.assertEqual(r.phase,'succeeded');self.assertGreater(r._fraction(),0.);self.conserve(r)
|
| 82 |
+
def test_23_schema_actual_results_and_metadata(self):
|
| 83 |
+
spec=importlib.util.spec_from_file_location('mivac_asset_tool',ROOT/'skills/chemistry-lab-assets/scripts/asset_tool.py');tool=importlib.util.module_from_spec(spec);spec.loader.exec_module(tool);meta=export_genevac_mivac2_contract_metadata();r=prepared()
|
| 84 |
+
for cap in ['evaporation.measure','product.read','history.read','reference.lookup']:
|
| 85 |
+
args=CAPS[cap][6];out=r.invoke(cap,**args);self.assertEqual(tool.validate_value(out,CAPS[cap][1]),[],cap)
|
| 86 |
+
for k,v in r._values().items():self.assertEqual(tool.validate_value(v,SLOTS[k][0]),[],k)
|
| 87 |
+
self.assertEqual(len(meta['capabilities']),13)
|
| 88 |
+
def test_24_step_partition_close(self):
|
| 89 |
+
a=prepared();b=prepared();a.invoke('acquisition.start');b.invoke('acquisition.start');a.step(30.)
|
| 90 |
+
for _ in range(300):b.step(.1)
|
| 91 |
+
self.assertAlmostEqual(a._fraction(),b._fraction(),places=10);self.assertAlmostEqual(a.pressure,b.pressure,places=7);self.conserve(a);self.conserve(b)
|
| 92 |
+
if __name__=='__main__':unittest.main()
|
tests/test_asset_gilson_cpc250.py
ADDED
|
@@ -0,0 +1,53 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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.gilson_cpc250 import *
|
| 5 |
+
def configured(**method):
|
| 6 |
+
h=GilsonCpc250Runtime();h.invoke('plant.configure',**EXAMPLE);h.invoke('method.configure',**dict(METHOD_EXAMPLE,**method));h.invoke('sample.configure',**SAMPLE_EXAMPLE);h.invoke('power.set',enabled=True);h.step(30);return h
|
| 7 |
+
class TestCpc(unittest.TestCase):
|
| 8 |
+
def assertLedger(self,h):
|
| 9 |
+
v=h.read('evaluator')
|
| 10 |
+
for u,parts in [('solute_kg',['loop','column','collected','waste']),('liquid_m3',['reservoir','loop','column','collected','waste'])]:self.assertAlmostEqual(v['truth.initial_'+u],sum(v['truth.'+p+'_'+u] for p in parts),places=12)
|
| 11 |
+
if h.sample:
|
| 12 |
+
for i,s in enumerate(h.sample['solutes']):self.assertAlmostEqual(s['mass_kg'],h.loop[i]+sum(h.mobile[i])+sum(h.stationary[i])+h.waste[i]+sum(f['solute_masses_kg'][i] for f in h.fractions),places=12)
|
| 13 |
+
def test_01_templates(self):
|
| 14 |
+
h=configured();self.assertEqual(len(h.templates),60);r=h.invoke('reference.lookup',substance_id='cas_57-55-6');self.assertEqual(r['log10_kow'],-.92);self.assertIsNone(r['temperature_k'])
|
| 15 |
+
def test_02_conservation(self):
|
| 16 |
+
h=configured();h.invoke('acquisition.start');h.step(2500);self.assertEqual(h.phase,'succeeded');self.assertLedger(h);self.assertGreater(h.col_volume,.00059);self.assertTrue(any(sum(f['solute_masses_kg'])>0 for f in h.fractions))
|
| 17 |
+
def test_03_direction(self):
|
| 18 |
+
a=configured(direction='ASC');d=configured();self.assertAlmostEqual(a.k[0]*d.k[0],1);self.assertNotEqual(a.k,d.k)
|
| 19 |
+
def test_04_windows(self):
|
| 20 |
+
h=configured(duration_s=200,collection_start_s=40,collection_end_s=100);h.invoke('acquisition.start');h.step(240);self.assertAlmostEqual(h.col_volume,60*h.method['flow_m3_s'],places=12);self.assertAlmostEqual(h.waste_volume,140*h.method['flow_m3_s'],places=12);self.assertLedger(h)
|
| 21 |
+
def test_05_cancel_coast(self):
|
| 22 |
+
h=configured();h.invoke('acquisition.start');h.step(80);before=h.read('evaluator');h.invoke('acquisition.stop');self.assertGreater(h.speed,0);h.step(30);self.assertEqual(h.speed,0);self.assertLess(h.pressure,before['pressure.gauge_pa']);self.assertEqual(h.reservoir,before['truth.reservoir_liquid_m3']);self.assertLedger(h);h.invoke('acquisition.start');h.step(30);self.assertGreater(h.elapsed_s,before['cycle.elapsed_s'])
|
| 23 |
+
def test_06_pressure_fault(self):
|
| 24 |
+
h=configured();h.plant['hydraulic_resistance_pa_s_m3']=1e14;h.invoke('acquisition.start');h.step(50);self.assertEqual(h.fault,'CPC_100BAR_GUARD');self.assertLedger(h)
|
| 25 |
+
def test_07_supply_fault(self):
|
| 26 |
+
h=GilsonCpc250Runtime();h.invoke('plant.configure',**dict(EXAMPLE,reservoir_m3=1e-6));h.invoke('method.configure',**METHOD_EXAMPLE);h.invoke('sample.configure',**SAMPLE_EXAMPLE);h.invoke('power.set',enabled=True);h.step(30);h.invoke('acquisition.start');h.step(100);self.assertEqual(h.fault,'RESERVOIR_EMPTY');self.assertLedger(h)
|
| 27 |
+
def test_08_schema_atomic(self):
|
| 28 |
+
h=configured();old=h.debug_snapshot()
|
| 29 |
+
for args in [dict(METHOD_EXAMPLE,speed_rad_s=float('nan')),dict(METHOD_EXAMPLE,flow_m3_s=True),dict(METHOD_EXAMPLE,unknown=1)]:
|
| 30 |
+
with self.assertRaises(ActionRejected):h.invoke('method.configure',**args)
|
| 31 |
+
self.assertEqual(old,h.debug_snapshot())
|
| 32 |
+
for dt in [True,-1,float('inf')]:
|
| 33 |
+
with self.assertRaises(ActionRejected):h.step(dt)
|
| 34 |
+
def test_09_boot_and_power(self):
|
| 35 |
+
h=configured();h.invoke('power.set',enabled=False);h.invoke('power.set',enabled=True)
|
| 36 |
+
with self.assertRaises(ActionRejected):h.invoke('acquisition.start')
|
| 37 |
+
h.step(30);h.invoke('acquisition.start');h.step(1)
|
| 38 |
+
with self.assertRaises(ActionRejected):h.invoke('power.set',enabled=False)
|
| 39 |
+
def test_10_exceptional_speed(self):
|
| 40 |
+
h=GilsonCpc250Runtime()
|
| 41 |
+
with self.assertRaises(ActionRejected):h.invoke('method.configure',**dict(METHOD_EXAMPLE,speed_rad_s=WMAX))
|
| 42 |
+
h.invoke('method.configure',**dict(METHOD_EXAMPLE,speed_rad_s=WMAX,exceptional_speed_reviewed=True))
|
| 43 |
+
def test_11_protocol(self):
|
| 44 |
+
h=configured();h.register_principal('host','evaluator');a=h.session();e=h.session('host');self.assertNotIn('truth.initial_solute_kg',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.poll(r['operation_id'])['status'],'running');a.cancel(r['operation_id'],'cancel');self.assertEqual(h.phase,'cancelled');self.assertEqual(a.invoke(instance_id=h.instance_id,capability_id='product.read',arguments={},request_id='deny')['status'],'rejected')
|
| 45 |
+
def test_12_partition_sensitivity(self):
|
| 46 |
+
a=configured(duration_s=500,collection_end_s=500);b=configured(direction='ASC',duration_s=500,collection_end_s=500)
|
| 47 |
+
for h in [a,b]:h.invoke('acquisition.start');h.step(540);self.assertLedger(h)
|
| 48 |
+
self.assertGreater(sum(f['solute_masses_kg'][0] for f in a.fractions),sum(f['solute_masses_kg'][0] for f in b.fractions))
|
| 49 |
+
def test_13_collector_full(self):
|
| 50 |
+
h=configured(duration_s=1000,collection_end_s=1000,fraction_volume_m3=1e-6);h.invoke('acquisition.start');h.step(1100);self.assertEqual(h.fault,'COLLECTOR_FULL');self.assertEqual(len(h.fractions),192);self.assertLedger(h)
|
| 51 |
+
def test_14_step_only_clock(self):
|
| 52 |
+
h=configured();before=h.time_s;h.invoke('cpc.measure');h.read();h.describe();self.assertEqual(h.time_s,before);h.step(0);self.assertEqual(h.time_s,before)
|
| 53 |
+
if __name__=='__main__':unittest.main()
|
tests/test_asset_hach_tl2300epa.py
ADDED
|
@@ -0,0 +1,85 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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'));sys.path.insert(0,str(ROOT/'skills/chemistry-lab-assets/scripts'))
|
| 4 |
+
from asset_runtime.hach_tl2300epa import HachTl2300epaRuntime as Runtime,CAPS,SLOTS,ActionRejected,export_hach_tl2300epa_contract_metadata
|
| 5 |
+
from asset_tool import validate_value,lint_schema
|
| 6 |
+
class TestTL2300(unittest.TestCase):
|
| 7 |
+
def ready(self,**overrides):
|
| 8 |
+
h=Runtime();h.invoke('power.set',enabled=True);h.step(3600);h.invoke('lid.set_angle',angle_rad=1.7)
|
| 9 |
+
a=copy.deepcopy(CAPS['sample.configure'][6]);a.update(overrides);h.invoke('sample.configure',**a);h.invoke('lid.set_angle',angle_rad=0.);return h
|
| 10 |
+
def measure(self,h,n=1,ratio=True,mode='single'):
|
| 11 |
+
h.invoke('method.configure',ratio_enabled=ratio,average_count=n,mode=mode);h.invoke('acquisition.start');h.step(6.8 if n==1 else 14.);return h.invoke('turbidity.measure')
|
| 12 |
+
def reject_unchanged(self,h,cap,a):
|
| 13 |
+
before=copy.deepcopy(h.__dict__)
|
| 14 |
+
with self.assertRaises(ActionRejected):h.invoke(cap,**a)
|
| 15 |
+
self.assertEqual(before,h.__dict__)
|
| 16 |
+
def test_read_describe_pure_targets_no_time(self):
|
| 17 |
+
h=self.ready();before=copy.deepcopy(h.__dict__);h.read();h.describe();h.session().read(instance_id=h.instance_id);h.invoke('turbidity.measure');self.assertEqual(before,h.__dict__)
|
| 18 |
+
h.invoke('method.configure',ratio_enabled=False,average_count=10,mode='continuous');self.assertEqual(h.time_s,3600.);self.assertIsNone(h.indicated)
|
| 19 |
+
def test_vendor_timing_resolution_and_ranges(self):
|
| 20 |
+
for n,duration in [(1,6.8),(10,14.)]:
|
| 21 |
+
h=self.ready();h.invoke('method.configure',ratio_enabled=True,average_count=n,mode='single');h.invoke('acquisition.start');h.step(duration-.01);self.assertEqual(h.phase,'running');self.assertIsNone(h.indicated);h.step(.01);self.assertEqual(h.phase,'succeeded');self.assertEqual(h.indicated,20.);self.assertAlmostEqual(h.window[1]-h.window[0],duration)
|
| 22 |
+
for sid,ratio,expected in [('stablcal_4000',True,4000.),('stablcal_200',False,None),('stablcal_20',False,20.)]:self.assertEqual(self.measure(self.ready(substance_id=sid),ratio=ratio)['ntu'],expected)
|
| 23 |
+
self.assertAlmostEqual(self.measure(self.ready(substance_id='stablcal_1000'))['reference_accuracy_ntu'],20.01)
|
| 24 |
+
self.assertEqual(self.measure(self.ready(substance_id='stablcal_4000'))['reference_accuracy_ntu'],200.)
|
| 25 |
+
def test_warmup_filter_clean_cell_and_bounds(self):
|
| 26 |
+
h=Runtime();self.reject_unchanged(h,'acquisition.start',{});h.invoke('power.set',enabled=True);h.step(1799.9);self.assertFalse(h.read()['warmup.ready']);h.step(.1);self.assertTrue(h.read()['warmup.ready']);h.invoke('method.configure',ratio_enabled=False,average_count=1,mode='single');self.assertFalse(h.read()['warmup.ready'])
|
| 27 |
+
self.reject_unchanged(h,'filter.set_installed',{'installed':False})
|
| 28 |
+
h.invoke('power.set',enabled=False);h.invoke('filter.set_installed',installed=False);self.assertFalse(h.filter_installed)
|
| 29 |
+
self.reject_unchanged(self.ready(clean_indexed_cell=False),'acquisition.start',{})
|
| 30 |
+
for key,value in [('volume_m3',19e-6),('volume_m3',31e-6),('temperature_k',343.16),('mass_kg',True),('color_absorbance',float('nan'))]:
|
| 31 |
+
h=Runtime();h.invoke('lid.set_angle',angle_rad=1.7);a=copy.deepcopy(CAPS['sample.configure'][6]);a[key]=value;self.reject_unchanged(h,'sample.configure',a)
|
| 32 |
+
def test_integer_unknown_and_busy_atomic(self):
|
| 33 |
+
h=self.ready()
|
| 34 |
+
for n in [True,1.,1.5,2,0]:self.reject_unchanged(h,'method.configure',{'ratio_enabled':True,'average_count':n,'mode':'single'})
|
| 35 |
+
self.reject_unchanged(h,'method.configure',{'ratio_enabled':True,'average_count':1,'mode':'rst'})
|
| 36 |
+
h.invoke('acquisition.start');self.reject_unchanged(h,'sample.unload',{});self.reject_unchanged(h,'method.configure',CAPS['method.configure'][6])
|
| 37 |
+
def test_mass_volume_conservation_and_unload(self):
|
| 38 |
+
h=self.ready();self.measure(h);h.invoke('lid.set_angle',angle_rad=1.7);h.invoke('sample.unload');v=h.read('evaluator')
|
| 39 |
+
for ax in ['kg','m3']:self.assertAlmostEqual(v['sample.input_'+ax],v['sample.retained_'+ax]+v['sample.removed_'+ax])
|
| 40 |
+
self.assertIsNone(h.indicated);self.assertIsNone(h.invoke('turbidity.measure')['tss_kg_m3'])
|
| 41 |
+
def test_optical_color_particle_and_exact_bubble_integral(self):
|
| 42 |
+
for ratio in [True,False]:
|
| 43 |
+
h=self.ready(color_absorbance=1.,particle_response_gain=.5,bubble_excess_ntu=10.,bubble_tau_s=30.);r=self.measure(h,ratio=ratio);v=(10+10*30/6.8*(1-math.exp(-6.8/30)))*(1 if ratio else math.exp(-1));self.assertEqual(r['ntu'],round(v,3));self.assertFalse(r['stable'])
|
| 44 |
+
a=self.ready(bubble_excess_ntu=10.);b=self.ready(bubble_excess_ntu=10.);a.invoke('acquisition.start');b.invoke('acquisition.start');a.step(6.8)
|
| 45 |
+
for _ in range(68):b.step(.1)
|
| 46 |
+
self.assertAlmostEqual(a.raw_mean,b.raw_mean,places=10)
|
| 47 |
+
def test_calibration_reference_and_persistence(self):
|
| 48 |
+
h=self.ready(particle_response_gain=.8);self.measure(h);self.assertEqual(h.indicated,16.);h.invoke('calibration.rapid');self.assertAlmostEqual(h.gain,1.25);self.assertEqual(h.indicated,20.);self.assertTrue(h.invoke('calibration.verify',reference_ntu=20.)['within_five_percent']);self.assertEqual(h._cal_status(),'rapid_0_40')
|
| 49 |
+
h.invoke('power.set',enabled=False);self.assertTrue(h.calibrated);self.assertFalse(h.stable)
|
| 50 |
+
x=self.ready(substance_id='stablcal_200');self.measure(x);self.reject_unchanged(x,'calibration.rapid',{})
|
| 51 |
+
def test_async_complete_cancel_and_owner(self):
|
| 52 |
+
h=self.ready(bubble_excess_ntu=4.);s=h.session();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(2.);before=h.bubbles;s.cancel(op,'cancel');self.assertEqual(s.poll(op)['status'],'cancelled');self.assertEqual(h.bubbles,before);self.assertEqual(h.elapsed_s,2.)
|
| 53 |
+
h.register_principal('second');other=h.session('second')
|
| 54 |
+
with self.assertRaises(ActionRejected):other.poll(op)
|
| 55 |
+
h=self.ready();s=h.session();r=s.invoke(instance_id=h.instance_id,capability_id='acquisition.start',arguments={},request_id='x');h.step(6.8);self.assertEqual(s.poll(r['operation_id'])['status'],'succeeded')
|
| 56 |
+
def test_continuous_lid_power_cancel(self):
|
| 57 |
+
h=self.ready();self.measure(h,mode='continuous');self.assertEqual(h.phase,'running');first=h.window;h.step(6.8);self.assertGreater(h.window[1],first[1]);h.invoke('lid.set_angle',angle_rad=.2);self.assertEqual(h.phase,'cancelled');self.assertEqual(h.indicated,20.)
|
| 58 |
+
h=self.ready();h.invoke('acquisition.start');h.step(1.);h.invoke('power.set',enabled=False);self.assertEqual(h.phase,'cancelled');self.assertEqual(h.elapsed_s,1.)
|
| 59 |
+
def test_principal_truth_isolation_dual_instances_idempotency(self):
|
| 60 |
+
h=self.ready();other=Runtime();s=h.session();desc=s.describe(instance_id=h.instance_id);self.assertNotIn('sample.configure',desc['capabilities']);self.assertNotIn('sample.reference_ntu',desc['state_slots'])
|
| 61 |
+
with self.assertRaises(ActionRejected):s.read(instance_id=h.instance_id,state_ids=['sample.reference_ntu'])
|
| 62 |
+
r=s.invoke(instance_id=h.instance_id,capability_id='sample.configure',arguments=CAPS['sample.configure'][6],request_id='deny');self.assertEqual(r['error']['code'],'ACCESS_DENIED');self.assertNotIn('stablcal',json.dumps(r))
|
| 63 |
+
h.register_principal('eval','evaluator');self.assertIn('sample.reference_ntu',h.session('eval').read(instance_id=h.instance_id)['observations']);self.assertFalse(other.powered);self.assertIsNone(other.sample)
|
| 64 |
+
r=s.write(instance_id=h.instance_id,state_id='power.enabled',value=True,request_id='same');rev=h.revision;self.assertEqual(r,s.write(instance_id=h.instance_id,state_id='power.enabled',value=True,request_id='same'));self.assertEqual(h.revision,rev);self.assertEqual(s.write(instance_id=h.instance_id,state_id='power.enabled',value=False,request_id='same')['error']['code'],'REQUEST_CONFLICT')
|
| 65 |
+
def test_all_capability_outputs_and_slot_schema(self):
|
| 66 |
+
h=self.ready();results={'power.set':h.invoke('power.set',enabled=True),'lid.set_angle':h.invoke('lid.set_angle',angle_rad=0.),'sample.configure':{'configured':True},'method.configure':h.invoke('method.configure',**CAPS['method.configure'][6]),'acquisition.start':h.invoke('acquisition.start')};h.step(6.8);results['calibration.rapid']=h.invoke('calibration.rapid');results['calibration.verify']=h.invoke('calibration.verify',reference_ntu=20.);results['turbidity.measure']=h.invoke('turbidity.measure');results['acquisition.stop']=h.invoke('acquisition.stop');h.invoke('lid.set_angle',angle_rad=1.7);results['sample.unload']=h.invoke('sample.unload');h.invoke('power.set',enabled=False);results['filter.set_installed']=h.invoke('filter.set_installed',installed=True)
|
| 67 |
+
configured=Runtime();configured.invoke('lid.set_angle',angle_rad=1.7);results['sample.configure']=configured.invoke('sample.configure',**CAPS['sample.configure'][6])
|
| 68 |
+
self.assertEqual(set(results),set(CAPS))
|
| 69 |
+
for key,row in CAPS.items():self.assertEqual(validate_value(results[key],row[1]),[]);self.assertEqual(lint_schema(row[0]),[]);self.assertEqual(lint_schema(row[1]),[])
|
| 70 |
+
for k,v in h.read('evaluator').items():self.assertEqual(validate_value(v,SLOTS[k][0]),[],k)
|
| 71 |
+
self.assertEqual(len(export_hach_tl2300epa_contract_metadata()['capabilities']),11)
|
| 72 |
+
def test_every_template_real_or_censored(self):
|
| 73 |
+
base=Runtime();counts={'water':0,'nominal':0,'blocked':0}
|
| 74 |
+
for sid,row in base.templates.items():
|
| 75 |
+
if not row['runtime_eligible']:
|
| 76 |
+
h=Runtime();h.invoke('lid.set_angle',angle_rad=1.7);a=copy.deepcopy(CAPS['sample.configure'][6]);a['substance_id']=sid;self.reject_unchanged(h,'sample.configure',a);counts['blocked']+=1;continue
|
| 77 |
+
h=self.ready(substance_id=sid);r=self.measure(h);self.assertEqual(r['ntu'],round(row['value'],3));self.assertIsNone(r['tss_kg_m3']);self.assertTrue(row['source']);counts['water' if row['material_class']=='environmental_water_mixture' else 'nominal']+=1
|
| 78 |
+
self.assertEqual(counts,{'water':79,'nominal':4,'blocked':6})
|
| 79 |
+
def test_mean_observation_retains_sampling_window(self):
|
| 80 |
+
h=self.ready();self.measure(h,n=10);s=h.session();a=s.read(instance_id=h.instance_id,state_ids=['turbidity.indicated_ntu'])['observations']['turbidity.indicated_ntu'];h.step(7.);b=s.read(instance_id=h.instance_id,state_ids=['turbidity.indicated_ntu'])['observations']['turbidity.indicated_ntu'];self.assertEqual(a,b);self.assertAlmostEqual(b['sample_window_s'][1]-b['sample_window_s'][0],14.);self.assertEqual(b['sample_time_s'],h.window[1]);h.invoke('power.set',enabled=False);self.assertEqual(s.read(instance_id=h.instance_id,state_ids=['turbidity.indicated_ntu'])['observations']['turbidity.indicated_ntu']['quality'],'stale')
|
| 81 |
+
def test_trusted_initial_condition_is_not_clock_advance(self):
|
| 82 |
+
h=Runtime(initial_powered=True,prior_powered_time_s=3600.);self.assertEqual(h.time_s,0.);self.assertEqual(h.warmup_s,3600.);self.assertTrue(h.read()['warmup.ready']);h.step(1.);self.assertEqual(h.time_s,1.);self.assertEqual(h.warmup_s,3601.);h.invoke('power.set',enabled=False);self.assertEqual(h.warmup_s,0.)
|
| 83 |
+
for kwargs in [{'prior_powered_time_s':1.},{'initial_powered':1},{'initial_powered':True,'prior_powered_time_s':float('nan')},{'initial_powered':True,'prior_powered_time_s':-1.}]:
|
| 84 |
+
with self.assertRaises(ValueError):Runtime(**kwargs)
|
| 85 |
+
if __name__=='__main__':unittest.main()
|
tests/test_asset_hepatochem_photoredoxbox.py
ADDED
|
@@ -0,0 +1,103 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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'));sys.path.insert(0,str(ROOT/'skills/chemistry-lab-assets/scripts'))
|
| 4 |
+
import asset_tool
|
| 5 |
+
from asset_runtime.hepatochem_photoredoxbox import *
|
| 6 |
+
def prepared(rack='8x4ml',source=None,thermal=None,**sample):
|
| 7 |
+
h=HepatochemPhotoredoxboxRuntime();h.invoke('lid.set_lift',lift_m=.12);h.invoke('rack.configure',mode=rack);h.invoke('thermal.configure',**(thermal or CAPS['thermal.configure'][6]));led=copy.deepcopy(source or LED_EXAMPLE)
|
| 8 |
+
if rack=='4x20ml':led['capture_fraction']=[r[:4] for r in led['capture_fraction']]
|
| 9 |
+
h.invoke('led.configure',**led);h.invoke('sample.configure',**dict(EXAMPLE,**sample));h.invoke('lid.set_lift',lift_m=0.);h.invoke('power.set',enabled=True);return h
|
| 10 |
+
class PhotoRedoxTest(unittest.TestCase):
|
| 11 |
+
def test_contract_schemas(self):
|
| 12 |
+
m=export_hepatochem_photoredoxbox_contract_metadata()
|
| 13 |
+
self.assertEqual(len(m['capabilities']),15)
|
| 14 |
+
for cap in m['capabilities'].values():
|
| 15 |
+
self.assertFalse(asset_tool.lint_schema(cap['input_schema']));self.assertFalse(asset_tool.lint_schema(cap['output_schema']));self.assertFalse(asset_tool.validate_value(cap['example_arguments'],cap['input_schema']))
|
| 16 |
+
def test_72_real_spectra_and_anchor_units(self):
|
| 17 |
+
h=HepatochemPhotoredoxboxRuntime();self.assertEqual(len(h.templates),72)
|
| 18 |
+
for t in h.templates.values():
|
| 19 |
+
self.assertEqual(t['evidence'],'derived');self.assertEqual(t['measurement_evidence'],'measured_literature');self.assertTrue(t['conditions']['solvent']);self.assertIsNone(t['photochemical_quantum_yield']);self.assertIn('photochemcad.com',t['source']);self.assertAlmostEqual(h.epsilon(t['substance_id'],t['calibration']['wavelength_nm']),.1*t['calibration']['epsilon_L_mol_cm'],7)
|
| 20 |
+
self.assertAlmostEqual(h.epsilon('photochemcad_H01',275),1100.)
|
| 21 |
+
def test_every_template_drives_absorption(self):
|
| 22 |
+
records=HepatochemPhotoredoxboxRuntime().templates.values()
|
| 23 |
+
for t in records:
|
| 24 |
+
self.assertTrue(t['runtime_wavelengths_nm']);wave=t['runtime_wavelengths_nm'][0];led=copy.deepcopy(LED_EXAMPLE)
|
| 25 |
+
for s in led['sources']:s['wavelength_m']=float(str(wave)+'e-9')
|
| 26 |
+
h=prepared(source=led,substance_id=t['substance_id'],solvent=t['conditions']['solvent']);h.invoke('acquisition.start');h.step(.04);self.assertGreater(h.run_incident,0);self.assertGreaterEqual(h.samples[0]['absorbed_energy_j'],0)
|
| 27 |
+
def test_four_source_dose_and_photon_equation(self):
|
| 28 |
+
h=prepared();h.invoke('acquisition.start');h.step(2.3);self.assertEqual(h.phase,'succeeded');self.assertAlmostEqual(h.elapsed_s,2.,12);self.assertAlmostEqual(h.run_emitted,4.,11);self.assertAlmostEqual(h.run_incident,.2,12)
|
| 29 |
+
absorbed=.2*.9*(1-10**(-1100*.1*.01));self.assertAlmostEqual(h.samples[0]['absorbed_energy_j'],absorbed,12);self.assertAlmostEqual(h.samples[0]['absorbed_photons_mol'],absorbed*275e-9/(NA*H*C),15)
|
| 30 |
+
def test_optical_and_thermal_balance(self):
|
| 31 |
+
h=prepared();h.invoke('acquisition.start');h.step(2.4);e=h.energy
|
| 32 |
+
self.assertAlmostEqual(e['emitted'],sum(e[k] for k in ['absorbed','container_loss','transmitted','uncaptured']),10);self.assertAlmostEqual(e['thermal_input'],h._stored()+e['ambient_loss'],8);self.assertAlmostEqual(e['nonthermal'],.2*e['absorbed'],12)
|
| 33 |
+
def test_zero_light_no_active_heater(self):
|
| 34 |
+
led=copy.deepcopy(LED_EXAMPLE)
|
| 35 |
+
for s in led['sources']:s['intensity']=0.
|
| 36 |
+
h=prepared(source=led);h.invoke('temperature.set',target_k=333.15);h.invoke('acquisition.start');h.step(2.);self.assertEqual(h.chamber_k,298.15);self.assertEqual(h.samples[0]['temperature_k'],298.15);self.assertEqual(h.run_emitted,0);self.assertEqual(h.energy['thermal_input'],0)
|
| 37 |
+
def test_cooling_and_target_only(self):
|
| 38 |
+
h=prepared();h.invoke('temperature.set',target_k=298.15);h.invoke('stir.set_speed',speed_rad_s=600*RPM);self.assertEqual(h.actual_speed,0);self.assertEqual(h.chamber_k,298.15);h.invoke('acquisition.start');h.step(2.);self.assertGreater(h.fan,0);t=h.chamber_k;h.step(30.);self.assertLess(h.chamber_k,t);self.assertAlmostEqual(h.energy['thermal_input'],h._stored()+h.energy['ambient_loss'],7)
|
| 39 |
+
def test_both_racks_capacity_and_mass_volume(self):
|
| 40 |
+
for rack,(n,volume) in RACKS.items():
|
| 41 |
+
h=prepared(rack,volume_m3=volume);h.invoke('lid.set_lift',lift_m=.12)
|
| 42 |
+
for i in range(1,n):h.invoke('sample.configure',**dict(EXAMPLE,slot=i,container_id='v'+str(i),volume_m3=volume))
|
| 43 |
+
self.assertEqual(len(h.samples),n)
|
| 44 |
+
with self.assertRaises(ActionRejected):h.invoke('sample.configure',**dict(EXAMPLE,slot=n if n<8 else 7,container_id='extra'))
|
| 45 |
+
with self.assertRaises(ActionRejected):h.invoke('rack.configure',mode=rack)
|
| 46 |
+
for i in range(n):h.invoke('sample.unload',slot=i)
|
| 47 |
+
for ax in ['kg','m3']:
|
| 48 |
+
v=h.read('evaluator');self.assertAlmostEqual(v['sample.input_'+ax],v['sample.retained_'+ax]+v['sample.removed_'+ax],12)
|
| 49 |
+
def test_empty_slots_do_not_redistribute_light(self):
|
| 50 |
+
a=prepared();b=prepared();b.invoke('lid.set_lift',lift_m=.12);b.invoke('sample.configure',**dict(EXAMPLE,slot=1,container_id='second'));b.invoke('lid.set_lift',lift_m=0.)
|
| 51 |
+
for h in [a,b]:h.invoke('acquisition.start');h.step(.2)
|
| 52 |
+
self.assertAlmostEqual(a.samples[0]['incident_energy_j'],b.samples[0]['incident_energy_j'],13);self.assertAlmostEqual(b.run_incident,2*a.run_incident,13)
|
| 53 |
+
def test_no_spectral_extrapolation_or_solvent_substitution(self):
|
| 54 |
+
h=prepared();h.invoke('lid.set_lift',lift_m=.12);led=copy.deepcopy(LED_EXAMPLE)
|
| 55 |
+
for s in led['sources']:s['wavelength_m']=808e-9
|
| 56 |
+
h.invoke('led.configure',**led);h.invoke('lid.set_lift',lift_m=0.);old=h.debug_snapshot()
|
| 57 |
+
with self.assertRaises(ActionRejected):h.invoke('acquisition.start')
|
| 58 |
+
self.assertEqual(old,h.debug_snapshot());h.invoke('lid.set_lift',lift_m=.12)
|
| 59 |
+
with self.assertRaises(ActionRejected):h.invoke('sample.configure',**dict(EXAMPLE,slot=1,container_id='b',solvent='water'))
|
| 60 |
+
def test_atomic_bad_arguments_and_interlock(self):
|
| 61 |
+
h=prepared();old=h.debug_snapshot()
|
| 62 |
+
for cap,a in [('lid.set_lift',{'lift_m':True}),('temperature.set',{'target_k':290.}),('sample.unload',{'slot':.0}),('sample.unload',{'slot':-1}),('stir.set_speed',{'speed_rad_s':float('nan')})]:
|
| 63 |
+
with self.assertRaises(ActionRejected):h.invoke(cap,**a)
|
| 64 |
+
self.assertEqual(old,h.debug_snapshot())
|
| 65 |
+
h.invoke('acquisition.start');old=h.debug_snapshot()
|
| 66 |
+
with self.assertRaises(ActionRejected):h.invoke('lid.set_lift',lift_m=.12)
|
| 67 |
+
self.assertEqual(old,h.debug_snapshot())
|
| 68 |
+
def test_explicit_power_and_capture_constraints(self):
|
| 69 |
+
h=HepatochemPhotoredoxboxRuntime();h.invoke('lid.set_lift',lift_m=.12);h.invoke('thermal.configure',**CAPS['thermal.configure'][6]);bad=copy.deepcopy(LED_EXAMPLE);bad['capture_fraction'][0]=[.2]*8
|
| 70 |
+
with self.assertRaises(ActionRejected):h.invoke('led.configure',**bad)
|
| 71 |
+
bad=copy.deepcopy(LED_EXAMPLE)
|
| 72 |
+
for s in bad['sources']:s['radiant_power_w']=25.
|
| 73 |
+
with self.assertRaises(ActionRejected):h.invoke('led.configure',**bad)
|
| 74 |
+
bad=copy.deepcopy(LED_EXAMPLE);bad['sources']=bad['sources'][:3]
|
| 75 |
+
with self.assertRaises(ActionRejected):h.invoke('led.configure',**bad)
|
| 76 |
+
def test_cancel_restart_and_removed_heat(self):
|
| 77 |
+
h=prepared();h.invoke('acquisition.start');h.step(.2);absorbed=h.samples[0]['absorbed_energy_j'];h.invoke('acquisition.stop');self.assertEqual(h.phase,'cancelled');self.assertEqual(h.samples[0]['absorbed_energy_j'],absorbed);h.invoke('acquisition.start');self.assertEqual(h.run_incident,0);h.step(.2);self.assertGreater(h.samples[0]['absorbed_energy_j'],absorbed);h.invoke('power.set',enabled=False);h.invoke('lid.set_lift',lift_m=.12);h.invoke('sample.unload',slot=0);h.step(1.);self.assertAlmostEqual(h.energy['thermal_input'],h._stored()+h.energy['ambient_loss'],8)
|
| 78 |
+
def test_ideal_overtemperature_failure(self):
|
| 79 |
+
h=prepared(initial_temperature_k=333.149,heat_capacity_j_k=.1,sample_ua_w_k=0.);h.invoke('acquisition.start');h.step(.2);self.assertEqual(h.phase,'failed');self.assertIn('not_certified',h.fault);q=h.run_emitted;h.step(.2);self.assertEqual(q,h.run_emitted)
|
| 80 |
+
def test_reads_pure_and_unknown_products(self):
|
| 81 |
+
h=prepared();h.invoke('acquisition.start');h.step(.3);old=copy.deepcopy(h.__dict__)
|
| 82 |
+
for _ in range(3):h.read();h.describe();h.invoke('irradiation.measure');h.invoke('history.read');h.invoke('product.read')
|
| 83 |
+
self.assertEqual(old,h.__dict__);self.assertIsNone(h.invoke('irradiation.measure')['yield_fraction']);self.assertIsNone(h.invoke('product.read')['samples'][0]['conversion_fraction'])
|
| 84 |
+
def test_instance_isolation_and_agent_truth_filter(self):
|
| 85 |
+
a=prepared();b=HepatochemPhotoredoxboxRuntime('other');a.invoke('acquisition.start');a.step(.2);self.assertFalse(b.powered);self.assertFalse(b.samples);s=a.session();self.assertNotIn('truth.samples',s.read(instance_id=a.instance_id)['observations']);self.assertNotIn('product.read',s.describe(instance_id=a.instance_id)['capabilities'])
|
| 86 |
+
for k in ['product.read','led.configure']:
|
| 87 |
+
r=s.invoke(instance_id=a.instance_id,capability_id=k,arguments={},request_id=k);self.assertEqual(r['error']['code'],'ACCESS_DENIED')
|
| 88 |
+
def test_native_async_dedup_window_cancel_and_write(self):
|
| 89 |
+
h=prepared();s=h.session();args=dict(instance_id=h.instance_id,capability_id='acquisition.start',arguments={},request_id='start');r=s.invoke(**args);self.assertEqual(r['status'],'accepted');self.assertEqual(s.invoke(**args),r);h.step(.2);self.assertEqual(s.poll(r['operation_id'])['status'],'running');obs=s.read(instance_id=h.instance_id,state_ids=['optics.incident_energy_j'])['observations']['optics.incident_energy_j'];self.assertEqual(obs['sample_window_s'],[h.run_start_s,h.run_start_s+h.elapsed_s]);self.assertEqual(s.cancel(r['operation_id'],'cancel')['status'],'cancelled');self.assertGreater(h.run_incident,0);self.assertEqual(s.write(instance_id=h.instance_id,state_id='stir.target_rad_s',value=600*RPM,request_id='speed')['status'],'succeeded')
|
| 90 |
+
def test_all_actual_outputs_against_schemas(self):
|
| 91 |
+
h=HepatochemPhotoredoxboxRuntime()
|
| 92 |
+
def ck(k,a=None):
|
| 93 |
+
r=h.invoke(k,**(CAPS[k][6] if a is None else a));self.assertFalse(asset_tool.validate_value(r,CAPS[k][1]),k);return r
|
| 94 |
+
for k in ['lid.set_lift','rack.configure','thermal.configure','led.configure','sample.configure','power.set','method.configure','temperature.set','stir.set_speed']:ck(k)
|
| 95 |
+
ck('lid.set_lift',{'lift_m':0.});ck('acquisition.start');h.step(.2)
|
| 96 |
+
for k in ['irradiation.measure','history.read','product.read','acquisition.stop']:ck(k)
|
| 97 |
+
for k,v in h.read('evaluator').items():self.assertFalse(asset_tool.validate_value(v,SLOTS[k][0]),k)
|
| 98 |
+
ck('stir.set_speed',{'speed_rad_s':0.});h.step(.02);ck('lid.set_lift');ck('sample.unload')
|
| 99 |
+
def test_bad_dt(self):
|
| 100 |
+
h=prepared()
|
| 101 |
+
for dt in [0,-1,True,float('nan'),float('inf')]:
|
| 102 |
+
with self.assertRaises(ValueError):h.step(dt)
|
| 103 |
+
if __name__=='__main__':unittest.main()
|
tests/test_asset_ika_electrasyn2.py
ADDED
|
@@ -0,0 +1,87 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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'));sys.path.insert(0,str(ROOT/'skills/chemistry-lab-assets/scripts'))
|
| 4 |
+
import asset_tool
|
| 5 |
+
from asset_runtime.ika_electrasyn2 import *
|
| 6 |
+
def prepared(**changes):
|
| 7 |
+
h=IkaElectrasyn2Runtime();h.invoke('power.set',enabled=True);h.invoke('cap.set_lift',lift_m=.08);h.invoke('sample.configure',**dict(EXAMPLE,**changes));h.invoke('cap.set_lift',lift_m=0.);h.invoke('electrodes.configure',**CAPS['electrodes.configure'][6]);return h
|
| 8 |
+
class ElectrasynTest(unittest.TestCase):
|
| 9 |
+
def test_contract_schemas(self):
|
| 10 |
+
meta=export_ika_electrasyn2_contract_metadata()
|
| 11 |
+
for cap in meta['capabilities'].values():
|
| 12 |
+
self.assertFalse(asset_tool.lint_schema(cap['input_schema']));self.assertFalse(asset_tool.lint_schema(cap['output_schema']));self.assertFalse(asset_tool.validate_value(cap['example_arguments'],cap['input_schema']))
|
| 13 |
+
def test_real_library(self):
|
| 14 |
+
lib=json.loads((ROOT/TEMPLATE_REL).read_text());self.assertEqual(len(lib['templates']),345);self.assertEqual(sum(x['runtime_lumped_eligible'] for x in lib['templates']),205)
|
| 15 |
+
self.assertEqual(next(x for x in lib['templates'] if x['author_molecule_index']==2)['values']['first_reduction_v'],.597)
|
| 16 |
+
ambiguous=next(x for x in lib['templates'] if x['author_molecule_index']==290);self.assertTrue(ambiguous['identity_conflicts']);self.assertFalse(ambiguous['runtime_lumped_eligible'])
|
| 17 |
+
for x in lib['templates']:self.assertEqual(x['conditions']['reference_electrode'],'saturated calomel electrode (SCE)');self.assertEqual(x['evidence'],'measured_literature')
|
| 18 |
+
def test_clock_and_target_only(self):
|
| 19 |
+
h=prepared();h.invoke('stir.set_speed',speed_rad_s=601*RPM);self.assertEqual(h.actual_speed,0);self.assertAlmostEqual(h.target_speed,600*RPM);h.invoke('acquisition.start');self.assertEqual(h.charge,0);h.step(.2);self.assertGreater(h.charge,0)
|
| 20 |
+
before=copy.deepcopy(h.__dict__)
|
| 21 |
+
for _ in range(3):h.read();h.describe();h.invoke('electrochem.measure');h.invoke('history.read')
|
| 22 |
+
self.assertEqual(before,h.__dict__)
|
| 23 |
+
def test_rejections_atomic(self):
|
| 24 |
+
h=IkaElectrasyn2Runtime()
|
| 25 |
+
for cap,a in [('acquisition.start',{}),('stir.set_speed',{'speed_rad_s':10*RPM}),('cap.set_lift',{'lift_m':True}),('sample.configure',EXAMPLE),('method.configure',dict(CAPS['method.configure'][6],cell_voltage_v=30.))]:
|
| 26 |
+
old=h.debug_snapshot()
|
| 27 |
+
with self.assertRaises(ActionRejected):h.invoke(cap,**a)
|
| 28 |
+
self.assertEqual(old,h.debug_snapshot())
|
| 29 |
+
h=prepared();h.invoke('acquisition.start');old=h.debug_snapshot()
|
| 30 |
+
with self.assertRaises(ActionRejected):h.invoke('cap.set_lift',lift_m=.08)
|
| 31 |
+
self.assertEqual(old,h.debug_snapshot())
|
| 32 |
+
def test_current_charge_energy_and_inventories(self):
|
| 33 |
+
h=prepared();h.invoke('acquisition.start');h.step(2.4);v=h.read('evaluator');self.assertEqual(h.phase,'succeeded');self.assertAlmostEqual(h.charge,.02,12);self.assertAlmostEqual(h.extent,.8*.02/F,14)
|
| 34 |
+
self.assertAlmostEqual(v['truth.working_reduced_mol']+v['truth.working_oxidized_mol'],.001,14);self.assertAlmostEqual(v['truth.counter_reduced_mol']+v['truth.counter_oxidized_mol'],.001,14)
|
| 35 |
+
self.assertAlmostEqual(v['truth.sample_charge_c'],v['truth.target_charge_c']+v['truth.side_charge_c'],13)
|
| 36 |
+
self.assertAlmostEqual(v['truth.electrical_energy_j'],v['truth.ohmic_energy_j']+v['truth.redox_work_j'],12)
|
| 37 |
+
def test_charge_stop_exact(self):
|
| 38 |
+
h=prepared();h.invoke('method.configure',**dict(h.method,stop_by='charge',charge_target_c=.00123,duration_s=100.));h.invoke('acquisition.start');h.step(2.);self.assertEqual(h.phase,'succeeded');self.assertAlmostEqual(h.charge,.00123,14);self.assertAlmostEqual(h.elapsed_s,.123,12)
|
| 39 |
+
def test_voltage_mode_and_current_compliance(self):
|
| 40 |
+
h=prepared();h.invoke('method.configure',**dict(h.method,mode='constant_cell_voltage',cell_voltage_v=4.,duration_s=20.));h.invoke('acquisition.start');h.step(.1);self.assertGreater(h.current,0);self.assertLessEqual(h.current,.1);self.assertAlmostEqual(h.voltage,4.,8)
|
| 41 |
+
h2=prepared(conductivity_s_m=100.,polarization_resistance_ohm=0.);h2.invoke('method.configure',**dict(h2.method,mode='constant_cell_voltage',cell_voltage_v=10.));h2.invoke('acquisition.start');h2.step(.1);self.assertEqual(h2.current,.1);self.assertLess(h2.voltage,10.)
|
| 42 |
+
def test_compliance_cutoff(self):
|
| 43 |
+
h=prepared(conductivity_s_m=.00001);h.invoke('acquisition.start');h.step(.1);self.assertEqual(h.phase,'failed');self.assertEqual(h.fault,'voltage_limit');self.assertEqual(h.charge,0.)
|
| 44 |
+
def test_capacity_exhaustion_and_timeout(self):
|
| 45 |
+
h=prepared(working_mol=1e-8,counter_mol=1e-8);h.invoke('acquisition.start');h.step(2);self.assertEqual(h.phase,'failed');self.assertEqual(h.fault,'formal_redox_inventory_exhausted');self.assertGreaterEqual(h.read('evaluator')['truth.counter_reduced_mol'],0)
|
| 46 |
+
h=prepared();h.invoke('method.configure',**dict(h.method,mode='constant_cell_voltage',cell_voltage_v=0.,stop_by='charge',duration_s=.1));h.invoke('acquisition.start');h.step(1);self.assertEqual(h.fault,'charge_target_timeout');self.assertEqual(h.charge,0)
|
| 47 |
+
def test_templates_affect_circuit(self):
|
| 48 |
+
a=prepared(working_substance_id='elhajj2024_q003');b=prepared(working_substance_id='elhajj2024_q004')
|
| 49 |
+
for h in [a,b]:h.invoke('acquisition.start');h.step(.2)
|
| 50 |
+
self.assertNotEqual(a.voltage,b.voltage)
|
| 51 |
+
def test_cancel_and_restart_residue(self):
|
| 52 |
+
h=prepared();h.invoke('acquisition.start');h.step(.2);extent=h.extent;res=h._redox()[3];h.invoke('acquisition.stop');self.assertEqual(h.phase,'cancelled');self.assertEqual(h.extent,extent);self.assertEqual(h._redox()[3],res);q=h.sample_charge;h.invoke('acquisition.start');self.assertEqual(h.charge,0);h.step(.2);self.assertGreater(h.sample_charge,q)
|
| 53 |
+
def test_two_instances_and_host_filter(self):
|
| 54 |
+
a=prepared();b=IkaElectrasyn2Runtime('other');a.invoke('acquisition.start');a.step(.2);self.assertFalse(b.powered);s=a.session();self.assertNotIn('truth.current_a',s.read(instance_id=a.instance_id)['observations']);self.assertNotIn('product.read',s.describe(instance_id=a.instance_id)['capabilities'])
|
| 55 |
+
denied=s.invoke(instance_id=a.instance_id,capability_id='product.read',arguments={},request_id='denied');self.assertEqual(denied['error']['code'],'ACCESS_DENIED')
|
| 56 |
+
self.assertFalse(any('truth' in k for p in s.invoke(instance_id=a.instance_id,capability_id='history.read',arguments={},request_id='history')['result']['records'] for k in p))
|
| 57 |
+
def test_native_async_dedup_write_and_window(self):
|
| 58 |
+
h=prepared();s=h.session();a=dict(instance_id=h.instance_id,capability_id='acquisition.start',arguments={},request_id='start');r=s.invoke(**a);self.assertEqual(r['status'],'accepted');self.assertEqual(s.invoke(**a),r);h.step(.2);self.assertEqual(s.poll(r['operation_id'])['status'],'running');self.assertEqual(s.cancel(operation_id=r['operation_id'],request_id='cancel')['status'],'cancelled');self.assertGreater(h.charge,0)
|
| 59 |
+
obs=s.read(instance_id=h.instance_id,state_ids=['electrochem.charge_c'])['observations']['electrochem.charge_c'];self.assertEqual(obs['sample_window_s'],[h.run_start_s,h.run_start_s+h.elapsed_s])
|
| 60 |
+
self.assertEqual(s.write(instance_id=h.instance_id,state_id='stir.target_rad_s',value=600*RPM,request_id='speed')['status'],'succeeded')
|
| 61 |
+
def test_all_actual_outputs_schema(self):
|
| 62 |
+
h=IkaElectrasyn2Runtime()
|
| 63 |
+
def checked(k,a):
|
| 64 |
+
r=h.invoke(k,**a);self.assertFalse(asset_tool.validate_value(r,CAPS[k][1]),k);return r
|
| 65 |
+
checked('cap.set_lift',{'lift_m':.08});checked('sample.configure',EXAMPLE);checked('cap.set_lift',{'lift_m':0.})
|
| 66 |
+
for k in ['power.set','electrodes.configure','method.configure','stir.set_speed']:
|
| 67 |
+
r=h.invoke(k,**CAPS[k][6]);self.assertFalse(asset_tool.validate_value(r,CAPS[k][1]))
|
| 68 |
+
checked('acquisition.start',{});h.step(.2)
|
| 69 |
+
for k in ['electrochem.measure','history.read','product.read','acquisition.stop']:
|
| 70 |
+
self.assertFalse(asset_tool.validate_value(h.invoke(k),CAPS[k][1]))
|
| 71 |
+
for k,v in h.read('evaluator').items():self.assertFalse(asset_tool.validate_value(v,SLOTS[k][0]),k)
|
| 72 |
+
checked('stir.set_speed',{'speed_rad_s':0.});h.step(.05);checked('cap.set_lift',{'lift_m':.08});checked('sample.unload',{})
|
| 73 |
+
def test_every_eligible_template_enters_circuit(self):
|
| 74 |
+
templates=IkaElectrasyn2Runtime().templates;eligible=[x for x in templates.values() if x['runtime_lumped_eligible']];low=min(eligible,key=lambda x:x['values']['first_reduction_v']);high=max(eligible,key=lambda x:x['values']['first_reduction_v'])
|
| 75 |
+
for rec in eligible:
|
| 76 |
+
working,counter=(rec,high) if rec['values']['first_reduction_v']<high['values']['first_reduction_v'] else (low,rec)
|
| 77 |
+
h=prepared(working_substance_id=working['substance_id'],counter_substance_id=counter['substance_id'],working_reduced_fraction=.5,counter_reduced_fraction=.5);h.invoke('acquisition.start');h.step(.05);self.assertGreater(h.invoke('electrochem.measure')['charge_c'],0,rec['substance_id'])
|
| 78 |
+
def test_mass_volume_unload_and_unknown_yield(self):
|
| 79 |
+
h=prepared();h.invoke('acquisition.start');h.step(2.);self.assertIsNone(h.invoke('electrochem.measure')['yield_fraction']);h.invoke('cap.set_lift',lift_m=.08);h.invoke('sample.unload');v=h.read('evaluator')
|
| 80 |
+
for ax in ['kg','m3']:self.assertAlmostEqual(v['sample.input_'+ax],v['sample.retained_'+ax]+v['sample.removed_'+ax],14)
|
| 81 |
+
def test_bad_time_and_titratable_rejected(self):
|
| 82 |
+
h=IkaElectrasyn2Runtime()
|
| 83 |
+
for dt in [0,-1,True,float('nan'),float('inf')]:
|
| 84 |
+
with self.assertRaises(ValueError):h.step(dt)
|
| 85 |
+
h.invoke('cap.set_lift',lift_m=.08)
|
| 86 |
+
with self.assertRaises(ActionRejected):h.invoke('sample.configure',**dict(EXAMPLE,working_substance_id='elhajj2024_q290'))
|
| 87 |
+
if __name__=='__main__':unittest.main()
|
tests/test_asset_ika_ks4000.py
ADDED
|
@@ -0,0 +1,66 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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'));sys.path.insert(0,str(ROOT/'skills/chemistry-lab-assets/scripts'))
|
| 4 |
+
from asset_runtime.ika_ks4000 import IkaKs4000Runtime,CAPS,SLOTS,RPM,ActionRejected,load_limit,export_ika_ks4000_contract_metadata
|
| 5 |
+
import asset_tool
|
| 6 |
+
def ready(h,**load):
|
| 7 |
+
h.invoke('power.set',enabled=True);h.invoke('hood.set_angle',angle_rad=math.pi/2);h.invoke('fixture.configure',**CAPS['fixture.configure'][6]);h.invoke('load.configure',**dict(CAPS['load.configure'][6],**load));h.invoke('hood.set_angle',angle_rad=0.)
|
| 8 |
+
def energy_error(h):
|
| 9 |
+
s=h.read('evaluator');return s['energy.heater_input_j']+s['energy.loading_input_j']-s['energy.stored_j']-s['energy.loss_j']-s['energy.unloading_output_j']
|
| 10 |
+
class TestKS4000(unittest.TestCase):
|
| 11 |
+
def test_setpoints_and_pure_reads(self):
|
| 12 |
+
h=IkaKs4000Runtime();h.invoke('thermal.set_temperature',temperature_k=320.15);h.invoke('shaking.set_speed',speed_rad_s=300*RPM);self.assertEqual(h.temperature,298.15);self.assertEqual(h.speed,0.)
|
| 13 |
+
old=copy.deepcopy(h.__dict__);h.read();h.describe();h.session().read(instance_id=h.instance_id);h.invoke('status.measure');self.assertEqual(h.__dict__,old)
|
| 14 |
+
def test_atomic_rejections(self):
|
| 15 |
+
h=IkaKs4000Runtime()
|
| 16 |
+
for cap,a in [('shaking.start',{}),('thermal.set_enabled',{'enabled':True}),('load.configure',CAPS['load.configure'][6]),('thermal.set_temperature',{'temperature_k':299.15}),('thermal.set_temperature',{'temperature_k':310.16}),('shaking.set_speed',{'speed_rad_s':float('nan')}),('power.set',{'enabled':1})]:
|
| 17 |
+
old=copy.deepcopy(h.__dict__)
|
| 18 |
+
with self.assertRaises(ActionRejected):h.invoke(cap,**a)
|
| 19 |
+
self.assertEqual(h.__dict__,old)
|
| 20 |
+
def test_manufacturer_load_derating(self):
|
| 21 |
+
for mass,rpm in [(6,500),(6.01,400),(12,400),(12.01,300),(15,300),(15.01,120),(20,120)]:self.assertAlmostEqual(load_limit(mass),rpm*RPM)
|
| 22 |
+
h=IkaKs4000Runtime();ready(h,liquid_mass_kg=9.,container_mass_kg=1.)
|
| 23 |
+
with self.assertRaises(ActionRejected):h.invoke('shaking.set_speed',speed_rad_s=400*RPM)
|
| 24 |
+
h.invoke('shaking.set_speed',speed_rad_s=300*RPM);h.invoke('shaking.start')
|
| 25 |
+
def test_overload_and_unsecured(self):
|
| 26 |
+
h=IkaKs4000Runtime();ready(h,secured=False)
|
| 27 |
+
with self.assertRaises(ActionRejected):h.invoke('shaking.start')
|
| 28 |
+
h.invoke('hood.set_angle',angle_rad=1.5);old=copy.deepcopy(h.__dict__)
|
| 29 |
+
with self.assertRaises(ActionRejected):h.invoke('load.configure',**dict(CAPS['load.configure'][6],slot=0,container_mass_kg=10.,liquid_mass_kg=10.))
|
| 30 |
+
self.assertEqual(old,h.__dict__)
|
| 31 |
+
def test_orbit_is_translation_and_analytic_phase(self):
|
| 32 |
+
h=IkaKs4000Runtime();ready(h);h.invoke('shaking.start');h.step(10);expected=(h.speed_target*(10-2*(1-math.exp(-5))))%(2*math.pi)
|
| 33 |
+
self.assertAlmostEqual(h.angle,expected,10);s=h.read();self.assertAlmostEqual(s['orbit.x_m']**2+s['orbit.y_m']**2,.0001,12)
|
| 34 |
+
def test_timer_complete_keeps_independent_heater(self):
|
| 35 |
+
h=IkaKs4000Runtime();ready(h);h.invoke('thermal.set_enabled',enabled=True);h.invoke('shaking.start');h.step(61);self.assertEqual(h.phase,'succeeded');self.assertTrue(h.heater);self.assertEqual(h.elapsed_s,60.);self.assertGreater(h.speed,0.);self.assertEqual(h.read()['timer.remaining_s'],0.)
|
| 36 |
+
def test_hood_pause_resume_with_coast(self):
|
| 37 |
+
h=IkaKs4000Runtime();ready(h);h.invoke('thermal.set_enabled',enabled=True);h.invoke('shaking.start');h.step(10);speed=h.speed;h.invoke('hood.set_angle',angle_rad=1.5);self.assertEqual(h.speed,speed);h.step(5)
|
| 38 |
+
self.assertTrue(h.paused);self.assertFalse(h.heater);self.assertAlmostEqual(h.elapsed_s,10);self.assertLess(h.speed,speed);h.invoke('hood.set_angle',angle_rad=0.);h.step(50);self.assertEqual(h.phase,'succeeded')
|
| 39 |
+
def test_fifteen_minute_open_timeout_and_reset(self):
|
| 40 |
+
h=IkaKs4000Runtime();ready(h);h.invoke('shaking.start');h.step(3);h.invoke('hood.set_angle',angle_rad=1.5);h.step(900);self.assertEqual(h.phase,'failed');self.assertEqual(h.error,'hood_open_timer_timeout');h.invoke('hood.set_angle',angle_rad=0.)
|
| 41 |
+
with self.assertRaises(ActionRejected):h.invoke('shaking.start')
|
| 42 |
+
h.invoke('power.set',enabled=False);h.invoke('power.set',enabled=True);self.assertEqual(h.error,'');h.invoke('shaking.start')
|
| 43 |
+
def test_continuous_stop_and_power_mode_a(self):
|
| 44 |
+
h=IkaKs4000Runtime();ready(h);h.invoke('timer.configure',mode='continuous',duration_s=60.);h.invoke('shaking.start');h.step(65);self.assertEqual(h.phase,'running');self.assertIsNone(h.read()['timer.remaining_s']);h.invoke('power.set',enabled=False);angle=h.angle;h.step(1);self.assertNotEqual(h.angle,angle);self.assertEqual(h.phase,'cancelled');h.invoke('power.set',enabled=True);self.assertEqual(h.phase,'cancelled')
|
| 45 |
+
def test_mass_and_energy_through_load_heat_unload(self):
|
| 46 |
+
h=IkaKs4000Runtime();ready(h,initial_temperature_k=290.15);self.assertAlmostEqual(energy_error(h),0.,7);h.invoke('thermal.set_enabled',enabled=True);h.step(400);self.assertGreater(h.temperature,298.15);self.assertAlmostEqual(energy_error(h),0.,6)
|
| 47 |
+
h.invoke('hood.set_angle',angle_rad=1.5);h.step(30);h.invoke('load.unload',slot=4);self.assertAlmostEqual(h.mass_in,h.mass_out,12);self.assertAlmostEqual(energy_error(h),0.,6)
|
| 48 |
+
def test_async_permissions_and_retry(self):
|
| 49 |
+
h=IkaKs4000Runtime();ready(h);s=h.session();h.register_principal('other','agent');a=dict(instance_id=h.instance_id,capability_id='shaking.start',arguments={},request_id='x');r=s.invoke(**a);self.assertEqual(r['status'],'accepted');self.assertEqual(s.invoke(**a),r);h.step(5)
|
| 50 |
+
with self.assertRaises(ActionRejected):h.session('other').poll(r['operation_id'])
|
| 51 |
+
self.assertEqual(s.cancel(r['operation_id'],'cancel')['status'],'cancelled');self.assertNotIn('mass.retained_kg',s.read(instance_id=h.instance_id)['observations']);self.assertNotIn('load.configure',s.describe(instance_id=h.instance_id)['capabilities'])
|
| 52 |
+
with self.assertRaises(ActionRejected):s.read(instance_id=h.instance_id,state_ids=['mass.retained_kg'])
|
| 53 |
+
self.assertEqual(s.invoke(**dict(a,capability_id='shaking.stop'))['status'],'rejected')
|
| 54 |
+
def test_two_instances_and_invalid_dt(self):
|
| 55 |
+
a=IkaKs4000Runtime('a');b=IkaKs4000Runtime('b');old=copy.deepcopy(b.__dict__);ready(a);a.invoke('shaking.start');a.step(61);self.assertEqual(b.__dict__,old)
|
| 56 |
+
for dt in [0,-1,True,float('nan'),float('inf')]:
|
| 57 |
+
with self.assertRaises(ValueError):a.step(dt)
|
| 58 |
+
def test_all_capability_results_and_schemas(self):
|
| 59 |
+
h=IkaKs4000Runtime();seen=set()
|
| 60 |
+
def call(cap,**a):
|
| 61 |
+
r=h.invoke(cap,**a);seen.add(cap);self.assertEqual(asset_tool.validate_value(r,CAPS[cap][1]),[],cap)
|
| 62 |
+
for cap in ['power.set','hood.set_angle','fixture.configure','load.configure','thermal.set_temperature','timer.configure','safety.configure','calibration.configure']:call(cap,**CAPS[cap][6])
|
| 63 |
+
call('hood.set_angle',angle_rad=0.);call('thermal.set_enabled',enabled=True);call('shaking.set_speed',**CAPS['shaking.set_speed'][6]);call('shaking.start');h.step(65);call('shaking.stop');call('thermal.set_enabled',enabled=False);call('hood.set_angle',angle_rad=1.5);h.step(30);call('load.unload',slot=4);call('status.measure');self.assertEqual(seen,set(CAPS))
|
| 64 |
+
for k,v in h.read('evaluator').items():self.assertEqual(asset_tool.validate_value(v,SLOTS[k][0]),[],k)
|
| 65 |
+
for c in export_ika_ks4000_contract_metadata()['capabilities'].values():self.assertEqual(asset_tool.lint_schema(c['input_schema']),[]);self.assertEqual(asset_tool.lint_schema(c['output_schema']),[])
|
| 66 |
+
if __name__=='__main__':unittest.main()
|
tests/test_asset_mt_hx204.py
ADDED
|
@@ -0,0 +1,160 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""HX204 actual API, physical evolution and isolation regression tests."""
|
| 2 |
+
import copy
|
| 3 |
+
import json
|
| 4 |
+
import math
|
| 5 |
+
import sys
|
| 6 |
+
import unittest
|
| 7 |
+
from pathlib import Path
|
| 8 |
+
ROOT=Path(__file__).resolve().parents[1]
|
| 9 |
+
sys.path.insert(0,str(ROOT/'scripts'))
|
| 10 |
+
sys.path.insert(0,str(ROOT/'skills/chemistry-lab-assets/scripts'))
|
| 11 |
+
from asset_runtime import mt_hx204 as rt
|
| 12 |
+
from asset_tool import lint_schema, validate_value
|
| 13 |
+
|
| 14 |
+
class MtHx204Tests(unittest.TestCase):
|
| 15 |
+
def setUp(self):
|
| 16 |
+
self.h=rt.MtHx204Runtime()
|
| 17 |
+
self.h.register_principal('evaluator',visibility='evaluator')
|
| 18 |
+
self.agent=self.h.session(); self.evaluator=self.h.session('evaluator')
|
| 19 |
+
|
| 20 |
+
def ready(self, mode='standard', basis='wet', duration=60):
|
| 21 |
+
h=self.h
|
| 22 |
+
h.invoke('power.set',enabled=True); h.invoke('lid.set_position',position_m=.1085)
|
| 23 |
+
h.invoke('sample.configure',species_kg={'ethanol':.001,'methanol':.002},residue_kg=.004)
|
| 24 |
+
h.invoke('lid.set_position',position_m=0.)
|
| 25 |
+
h.invoke('method.configure',mode=mode,duration_s=duration,basis=basis)
|
| 26 |
+
|
| 27 |
+
def start(self):
|
| 28 |
+
return self.agent.invoke(instance_id=self.h.instance_id,capability_id='acquisition.start',arguments={},request_id='start_'+str(self.h._operation_count+1))
|
| 29 |
+
|
| 30 |
+
def test_targets_do_not_advance_process(self):
|
| 31 |
+
before=self.h.temperature_k
|
| 32 |
+
self.h.invoke('thermal.set_temperature',temperature_k=400.15)
|
| 33 |
+
self.assertEqual(self.h.time_s,0); self.assertEqual(self.h.temperature_k,before)
|
| 34 |
+
self.assertEqual(self.h.target_k,400.15)
|
| 35 |
+
|
| 36 |
+
def test_read_describe_measure_are_pure_and_detached(self):
|
| 37 |
+
self.ready(); self.start(); self.h.step(3)
|
| 38 |
+
before=copy.deepcopy(self.h.__dict__)
|
| 39 |
+
for _ in range(2):
|
| 40 |
+
self.agent.read(instance_id=self.h.instance_id); d=self.agent.describe(instance_id=self.h.instance_id)
|
| 41 |
+
m=self.h.invoke('moisture.measure'); m['curve'].clear(); d['capabilities'].clear()
|
| 42 |
+
self.assertEqual(self.h.__dict__,before)
|
| 43 |
+
|
| 44 |
+
def test_invalid_inputs_and_rejected_preconditions_are_atomic(self):
|
| 45 |
+
for cap,args in [('acquisition.start',{}),('lid.set_position',{'position_m':.1}),
|
| 46 |
+
('power.set',{'enabled':1}),('thermal.set_temperature',{'temperature_k':313.5}),
|
| 47 |
+
('thermal.set_temperature',{'temperature_k':math.nan}),('power.set',{'enabled':True,'extra':1}),
|
| 48 |
+
('method.configure',{'mode':'standard','duration_s':True,'basis':'wet'})]:
|
| 49 |
+
before=copy.deepcopy(self.h.__dict__)
|
| 50 |
+
with self.assertRaises(rt.ActionRejected): self.h.invoke(cap,**args)
|
| 51 |
+
self.assertEqual(before,self.h.__dict__)
|
| 52 |
+
for dt in [0,-1,True,math.inf,math.nan]:
|
| 53 |
+
before=copy.deepcopy(self.h.__dict__)
|
| 54 |
+
with self.assertRaises(ValueError): self.h.step(dt)
|
| 55 |
+
self.assertEqual(before,self.h.__dict__)
|
| 56 |
+
|
| 57 |
+
def test_sample_range_and_unknown_species_are_atomic(self):
|
| 58 |
+
self.ready(); self.h.invoke('lid.set_position',position_m=.1085)
|
| 59 |
+
for args in [{'species_kg':{'unknown_secret':.001},'residue_kg':0},
|
| 60 |
+
{'species_kg':{'ethanol':.201},'residue_kg':.001},
|
| 61 |
+
{'species_kg':{},'residue_kg':0}]:
|
| 62 |
+
before=self.h.debug_snapshot()
|
| 63 |
+
with self.assertRaisesRegex(rt.ActionRejected,'INVALID_ARGUMENT'): self.h.invoke('sample.configure',**args)
|
| 64 |
+
self.assertEqual(before,self.h.debug_snapshot())
|
| 65 |
+
|
| 66 |
+
def test_species_and_total_mass_conservation(self):
|
| 67 |
+
self.ready(); self.start()
|
| 68 |
+
initial=self.h.read('evaluator')['sample.initial_kg']
|
| 69 |
+
for dt in [1,2,5,12,40]:
|
| 70 |
+
self.h.step(dt)
|
| 71 |
+
v=self.h.read('evaluator')
|
| 72 |
+
self.assertAlmostEqual(initial,v['sample.remaining_kg']+v['sample.evaporated_kg'],places=14)
|
| 73 |
+
for sid,m in self.h.initial_species.items():
|
| 74 |
+
self.assertAlmostEqual(m,self.h.remaining[sid]+self.h.evaporated[sid],places=14)
|
| 75 |
+
self.assertGreater(self.h.evaporated['ethanol'],0)
|
| 76 |
+
curve=self.h.invoke('moisture.measure')['curve']
|
| 77 |
+
self.assertTrue(all(a['mass_kg']>=b['mass_kg'] for a,b in zip(curve,curve[1:])))
|
| 78 |
+
|
| 79 |
+
def test_async_completion_does_not_overshoot(self):
|
| 80 |
+
self.ready(); response=self.start()
|
| 81 |
+
self.assertEqual(response['status'],'accepted')
|
| 82 |
+
self.assertEqual(self.agent.poll(response['operation_id'])['status'],'running')
|
| 83 |
+
self.h.step(90)
|
| 84 |
+
self.assertEqual(self.h.phase,'succeeded'); self.assertEqual(self.h.elapsed_s,60)
|
| 85 |
+
self.assertEqual(self.h.time_s,90); self.assertEqual(self.h.curve[-1]['time_s'],60)
|
| 86 |
+
|
| 87 |
+
def test_cancel_and_power_loss_preserve_partial_mass(self):
|
| 88 |
+
self.ready(); response=self.start(); self.h.step(10)
|
| 89 |
+
before=self.h.debug_snapshot(); curve=copy.deepcopy(self.h.curve)
|
| 90 |
+
self.assertEqual(self.agent.cancel(response['operation_id'],'cancel')['status'],'cancelled')
|
| 91 |
+
self.h.step(100)
|
| 92 |
+
self.assertEqual(self.h.remaining,before['species']); self.assertEqual(curve,self.h.curve)
|
| 93 |
+
self.assertGreater(sum(self.h.evaporated.values()),0)
|
| 94 |
+
self.ready(); self.start(); self.h.step(2); before=dict(self.h.remaining)
|
| 95 |
+
self.h.invoke('power.set',enabled=False); self.h.step(5)
|
| 96 |
+
self.assertEqual(self.h.phase,'cancelled'); self.assertEqual(self.h.remaining,before)
|
| 97 |
+
|
| 98 |
+
def test_run_interlocks_do_not_mutate(self):
|
| 99 |
+
self.ready(); self.start()
|
| 100 |
+
for cap,args in [('lid.set_position',{'position_m':.1085}),('thermal.set_temperature',{'temperature_k':400.15}),
|
| 101 |
+
('method.configure',{'mode':'rapid','duration_s':60,'basis':'wet'})]:
|
| 102 |
+
before=copy.deepcopy(self.h.__dict__)
|
| 103 |
+
with self.assertRaises(rt.ActionRejected): self.h.invoke(cap,**args)
|
| 104 |
+
self.assertEqual(before,self.h.__dict__)
|
| 105 |
+
|
| 106 |
+
def test_instance_principal_and_truth_isolation(self):
|
| 107 |
+
self.ready(); other=rt.MtHx204Runtime('other'); before=copy.deepcopy(other.__dict__)
|
| 108 |
+
self.start(); self.h.step(10); self.assertEqual(before,other.__dict__)
|
| 109 |
+
public=self.agent.describe(instance_id=self.h.instance_id)
|
| 110 |
+
self.assertNotIn('sample.configure',public['capabilities'])
|
| 111 |
+
self.assertNotIn('sample.remaining_kg',public['state_slots'])
|
| 112 |
+
with self.assertRaises(rt.ActionRejected): self.agent.read(instance_id=self.h.instance_id,state_ids=['sample.remaining_kg'])
|
| 113 |
+
with self.assertRaises(rt.ActionRejected): self.agent.read(instance_id='other')
|
| 114 |
+
with self.assertRaises(TypeError): self.agent.read(instance_id=self.h.instance_id,visibility='evaluator')
|
| 115 |
+
rejected=self.agent.invoke(instance_id=self.h.instance_id,capability_id='sample.configure',arguments={},request_id='deny')
|
| 116 |
+
self.assertEqual(rejected['error']['code'],'ACCESS_DENIED')
|
| 117 |
+
self.assertNotIn('ethanol',json.dumps(self.agent.read(instance_id=self.h.instance_id)))
|
| 118 |
+
result=self.h.invoke('moisture.measure')
|
| 119 |
+
self.assertNotIn('ethanol',json.dumps(result))
|
| 120 |
+
self.h.register_principal('other_agent'); other_session=self.h.session('other_agent')
|
| 121 |
+
with self.assertRaises(rt.ActionRejected): other_session.poll(self.h.operation_id)
|
| 122 |
+
self.assertIn('sample.remaining_kg',self.evaluator.read(instance_id=self.h.instance_id)['observations'])
|
| 123 |
+
|
| 124 |
+
def test_retry_dedup_conflict_and_write(self):
|
| 125 |
+
kwargs=dict(instance_id=self.h.instance_id,capability_id='power.set',arguments={'enabled':True},request_id='power')
|
| 126 |
+
r=self.agent.invoke(**kwargs); revision=self.h.revision
|
| 127 |
+
self.assertEqual(r,self.agent.invoke(**kwargs)); self.assertEqual(revision,self.h.revision)
|
| 128 |
+
kwargs['arguments']={'enabled':False}
|
| 129 |
+
self.assertEqual(self.agent.invoke(**kwargs)['error']['code'],'REQUEST_CONFLICT'); self.assertTrue(self.h.powered)
|
| 130 |
+
r=self.agent.write(instance_id=self.h.instance_id,state_id='thermal.target_k',value=333.15,request_id='write')
|
| 131 |
+
self.assertEqual(r['status'],'succeeded'); self.assertEqual(self.h.target_k,333.15)
|
| 132 |
+
|
| 133 |
+
def test_real_result_and_observation_schemas(self):
|
| 134 |
+
meta=rt.export_mt_hx204_contract_metadata(); self.ready()
|
| 135 |
+
cases=[('power.set',{'enabled':True}),('thermal.set_temperature',{'temperature_k':400.15}),
|
| 136 |
+
('method.configure',{'mode':'gentle','duration_s':60,'basis':'dry'}),('lid.set_position',{'position_m':.1085}),
|
| 137 |
+
('sample.configure',{'species_kg':{'ethanol':.001},'residue_kg':.001}),('lid.set_position',{'position_m':0}),
|
| 138 |
+
('acquisition.start',{}),('moisture.measure',{}),('acquisition.stop',{})]
|
| 139 |
+
for cap,args in cases:
|
| 140 |
+
with self.subTest(cap=cap):
|
| 141 |
+
spec=meta['capabilities'][cap]
|
| 142 |
+
self.assertEqual(lint_schema(spec['input_schema']),[]); self.assertEqual(lint_schema(spec['output_schema']),[])
|
| 143 |
+
result=self.h.invoke(cap,**args)
|
| 144 |
+
self.assertEqual(validate_value(result,spec['output_schema']),[])
|
| 145 |
+
for k,v in self.h.read('evaluator').items(): self.assertEqual(validate_value(v,meta['state_slots'][k]['value_schema']),[])
|
| 146 |
+
self.h.step(1)
|
| 147 |
+
|
| 148 |
+
def test_templates_and_programs_are_distinct_and_honest(self):
|
| 149 |
+
self.assertGreaterEqual(len(self.h.templates),50)
|
| 150 |
+
for row in self.h.templates.values():
|
| 151 |
+
self.assertIn('webbook.nist.gov',row['source']); self.assertEqual(row['unit'],'K')
|
| 152 |
+
temps=[]
|
| 153 |
+
for mode in ['standard','rapid','gentle','steps']:
|
| 154 |
+
self.h=rt.MtHx204Runtime(); self.ready(mode=mode)
|
| 155 |
+
self.h.invoke('acquisition.start'); self.h.step(10); temps.append(self.h.temperature_k)
|
| 156 |
+
self.assertEqual(self.h.invoke('moisture.measure')['evidence'],'synthetic')
|
| 157 |
+
self.assertEqual(len(set(temps)),4)
|
| 158 |
+
|
| 159 |
+
if __name__=='__main__': unittest.main()
|
| 160 |
+
|
tests/test_asset_mt_mp70.py
ADDED
|
@@ -0,0 +1,80 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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')); sys.path.insert(0,str(ROOT/'skills/chemistry-lab-assets/scripts'))
|
| 4 |
+
from asset_runtime.mt_mp70 import MtMp70Runtime, CAPS, SLOTS, ActionRejected, export_mt_mp70_contract_metadata
|
| 5 |
+
import asset_tool
|
| 6 |
+
def configure(h,channel=0,sid='benzoic_acid',**kwargs):
|
| 7 |
+
a=dict(channel=channel,substance_id=sid,mass_kg=2e-6,purity=1.,particle_size_m=50e-6,decomposition_onset_k=None,decomposition_source=''); a.update(kwargs); h.invoke('sample.configure',**a)
|
| 8 |
+
def ready(h,ids=('benzoic_acid',)):
|
| 9 |
+
h.invoke('power.set',enabled=True)
|
| 10 |
+
for i,sid in enumerate(ids): configure(h,i,sid)
|
| 11 |
+
vals=[h.templates[s]['value'] for s in ids]
|
| 12 |
+
h.invoke('method.configure',method_id='test',start_k=max(293.15,min(vals)-10),end_k=min(623.15,max(vals)+18),ramp_k_s=20/60,criterion='transmission'); h.invoke('method.select',method_id='test')
|
| 13 |
+
class TestMP70(unittest.TestCase):
|
| 14 |
+
def test_setpoint_read_pure(self):
|
| 15 |
+
h=MtMp70Runtime(); h.invoke('thermal.set_temperature',temperature_k=350.); self.assertEqual(h.temperature_k,293.15)
|
| 16 |
+
old=copy.deepcopy(h.__dict__); h.read(); h.describe(); h.session().read(instance_id=h.instance_id); self.assertEqual(h.__dict__,old)
|
| 17 |
+
def test_rejected_atomic(self):
|
| 18 |
+
h=MtMp70Runtime()
|
| 19 |
+
for cap,args in [('acquisition.start',{}),('method.configure',dict(method_id='bad',start_k=350.,end_k=300.,ramp_k_s=1.,criterion='transmission')),('sample.configure',dict(CAPS['sample.configure'][6],channel=4)),('thermal.set_temperature',{'temperature_k':float('nan')}),('thermal.set_temperature',{'temperature_k':True})]:
|
| 20 |
+
old=copy.deepcopy(h.__dict__)
|
| 21 |
+
with self.assertRaises(ActionRejected): h.invoke(cap,**args)
|
| 22 |
+
self.assertEqual(h.__dict__,old)
|
| 23 |
+
def test_twenty_methods(self):
|
| 24 |
+
h=MtMp70Runtime(); a=CAPS['method.configure'][6]
|
| 25 |
+
for i in range(20): h.invoke('method.configure',**dict(a,method_id=str(i)))
|
| 26 |
+
old=copy.deepcopy(h.methods)
|
| 27 |
+
with self.assertRaises(ActionRejected): h.invoke('method.configure',**dict(a,method_id='21'))
|
| 28 |
+
self.assertEqual(h.methods,old); h.invoke('method.configure',**dict(a,method_id='0',end_k=400.)); self.assertEqual(len(h.methods),20)
|
| 29 |
+
def test_four_independent_channels(self):
|
| 30 |
+
h=MtMp70Runtime(); ready(h,('benzoic_acid','acetanilide','naphthalene','vanillin')); h.invoke('acquisition.start'); h.step(1000)
|
| 31 |
+
self.assertEqual(h.phase,'succeeded'); values=[]
|
| 32 |
+
for i in range(4):
|
| 33 |
+
r=h.invoke('melting.measure',channel=i); self.assertIsNotNone(r['onset_k']); self.assertLess(r['onset_k'],r['clear_k']); values.append(r['onset_k'])
|
| 34 |
+
self.assertEqual(asset_tool.validate_value(r,CAPS['melting.measure'][1]),[])
|
| 35 |
+
self.assertEqual(len(set(values)),4)
|
| 36 |
+
def test_mass_and_cancel_residual(self):
|
| 37 |
+
h=MtMp70Runtime(); ready(h); h.invoke('acquisition.start'); h.step(100); h.invoke('acquisition.stop'); old=copy.deepcopy(h.samples); h.read(); self.assertEqual(old,h.samples)
|
| 38 |
+
self.assertEqual(h.phase,'cancelled'); self.assertAlmostEqual(h.input_kg,sum(s['mass_kg'] for s in h.samples.values())+h.removed_kg)
|
| 39 |
+
h.invoke('thermal.set_temperature',temperature_k=293.15); h.step(2000); h.invoke('sample.unload',channel=0); self.assertAlmostEqual(h.input_kg,h.removed_kg)
|
| 40 |
+
def test_cooling_not_fixed(self):
|
| 41 |
+
h=MtMp70Runtime(); h.invoke('power.set',enabled=True); h.invoke('thermal.set_temperature',temperature_k=623.15); h.step(1000); h.invoke('thermal.set_temperature',temperature_k=293.15); h.step(330)
|
| 42 |
+
self.assertGreater(h.temperature_k,323.15); h.step(100); self.assertLess(h.temperature_k,323.15)
|
| 43 |
+
def test_async_permissions_idempotency(self):
|
| 44 |
+
h=MtMp70Runtime(); ready(h); s=h.session(); h.register_principal('eval','evaluator')
|
| 45 |
+
args=dict(instance_id=h.instance_id,capability_id='acquisition.start',arguments={},request_id='a'); r=s.invoke(**args); self.assertEqual(r['status'],'accepted'); self.assertEqual(r,s.invoke(**args))
|
| 46 |
+
h.step(2); self.assertEqual(s.poll(r['operation_id'])['status'],'running'); self.assertEqual(s.cancel(r['operation_id'],'stop')['status'],'cancelled')
|
| 47 |
+
self.assertEqual(s.invoke(**dict(args,arguments={'extra':1}))['status'],'rejected')
|
| 48 |
+
self.assertNotIn('sample.input_kg',s.read(instance_id=h.instance_id)['observations'])
|
| 49 |
+
self.assertNotIn('sample.configure',s.describe(instance_id=h.instance_id)['capabilities'])
|
| 50 |
+
with self.assertRaises(ActionRejected): s.read(instance_id=h.instance_id,state_ids=['sample.input_kg'])
|
| 51 |
+
self.assertEqual(s.invoke(instance_id=h.instance_id,capability_id='sample.configure',arguments=CAPS['sample.configure'][6],request_id='private')['status'],'rejected')
|
| 52 |
+
def test_instance_isolation(self):
|
| 53 |
+
a=MtMp70Runtime('a'); b=MtMp70Runtime('b'); old=copy.deepcopy(b.__dict__); ready(a); a.invoke('acquisition.start'); a.step(300); self.assertEqual(b.__dict__,old)
|
| 54 |
+
def test_purity_particle_and_decomposition(self):
|
| 55 |
+
results=[]
|
| 56 |
+
for purity,particle,decomp in [(1.,50e-6,None),(.8,300e-6,385.)]:
|
| 57 |
+
h=MtMp70Runtime(); h.invoke('power.set',enabled=True); configure(h,purity=purity,particle_size_m=particle,decomposition_onset_k=decomp,decomposition_source='synthetic test threshold' if decomp else '')
|
| 58 |
+
h.invoke('method.configure',**dict(CAPS['method.configure'][6],start_k=380.,end_k=430.)); h.invoke('method.select',method_id='demo'); h.invoke('acquisition.start'); h.step(500)
|
| 59 |
+
results.append(h.invoke('melting.measure',channel=0)); self.assertAlmostEqual(h.input_kg,h.read('evaluator')['sample.retained_kg']+h.removed_kg)
|
| 60 |
+
self.assertNotEqual(results[0]['transmission'],results[1]['transmission']); self.assertEqual(results[1]['quality'],'suspect_decomposition')
|
| 61 |
+
def test_curves_and_schema(self):
|
| 62 |
+
h=MtMp70Runtime(); ready(h); h.invoke('acquisition.start'); h.step(200)
|
| 63 |
+
curve=h.invoke('melting.curve',channel=0); self.assertEqual(asset_tool.validate_value(curve,CAPS['melting.curve'][1]),[]); self.assertEqual(len(curve['points']),math.floor(h.elapsed_s+1e-7))
|
| 64 |
+
for a,b in zip(curve['points'],curve['points'][1:]): self.assertEqual(b['time_s']-a['time_s'],1.)
|
| 65 |
+
for k,v in h.read('evaluator').items(): self.assertEqual(asset_tool.validate_value(v,SLOTS[k][0]),[],k)
|
| 66 |
+
for cap in export_mt_mp70_contract_metadata()['capabilities'].values():
|
| 67 |
+
self.assertEqual(asset_tool.lint_schema(cap['input_schema']),[]); self.assertEqual(asset_tool.lint_schema(cap['output_schema']),[])
|
| 68 |
+
def test_invalid_dt_and_ineligible(self):
|
| 69 |
+
h=MtMp70Runtime()
|
| 70 |
+
for dt in [0,-1,True,float('inf'),float('nan')]:
|
| 71 |
+
with self.assertRaises(ValueError): h.step(dt)
|
| 72 |
+
for sid,row in h.templates.items():
|
| 73 |
+
if not row['runtime_eligible']:
|
| 74 |
+
with self.assertRaises(ActionRejected): configure(h,sid=sid)
|
| 75 |
+
def test_every_capability_actual_return_schema(self):
|
| 76 |
+
h=MtMp70Runtime()
|
| 77 |
+
for cap in ['power.set','thermal.set_temperature','method.configure','method.select','sample.configure','melting.measure','melting.curve','sample.unload']:
|
| 78 |
+
r=h.invoke(cap,**CAPS[cap][6]); self.assertEqual(asset_tool.validate_value(r,CAPS[cap][1]),[],cap)
|
| 79 |
+
configure(h); r=h.invoke('acquisition.start'); self.assertEqual(asset_tool.validate_value(r,CAPS['acquisition.start'][1]),[]); r=h.invoke('acquisition.stop'); self.assertEqual(asset_tool.validate_value(r,CAPS['acquisition.stop'][1]),[])
|
| 80 |
+
if __name__=='__main__': unittest.main()
|
tests/test_asset_sartorius_vivaflow200.py
ADDED
|
@@ -0,0 +1,56 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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.sartorius_vivaflow200 import *
|
| 5 |
+
def configured(plant=None,method=None,cassette=None,sample=None):
|
| 6 |
+
h=SartoriusVivaflow200Runtime();h.invoke('cassette.configure',**dict(CASSETTE_EXAMPLE,**(cassette or {})));h.invoke('plant.configure',**dict(EXAMPLE,**(plant or {})));h.invoke('method.configure',**dict(METHOD_EXAMPLE,**(method or {})));h.invoke('sample.configure',**dict(SAMPLE_EXAMPLE,**(sample or {})));return h
|
| 7 |
+
def finish(h,seconds=12000):h.invoke('acquisition.start');h.step(seconds);return h
|
| 8 |
+
class TestVivaflow(unittest.TestCase):
|
| 9 |
+
def assertLedger(self,h):
|
| 10 |
+
v=h.read('evaluator')
|
| 11 |
+
for u,parts in [('protein_kg',['retentate','permeate','adsorbed']),('liquid_m3',['retentate','permeate','buffer']),('osmoles_mol',['retentate','permeate','buffer'])]:self.assertAlmostEqual(v['truth.initial_'+u],sum(v['truth.'+p+'_'+u] for p in parts),places=11)
|
| 12 |
+
for i,x in enumerate(h.sample['solutes']):self.assertAlmostEqual(x['mass_kg'],h.mass[i]+h.permeate_mass[i]+h.adsorbed[i],places=12)
|
| 13 |
+
def test_01_references(self):
|
| 14 |
+
h=configured();self.assertEqual(len(h.templates),60);self.assertEqual(len(h.performance),16);r=h.invoke('reference.lookup',substance_id='uniprot_p02769');self.assertTrue(66<r['unmodified_chain_molar_mass_kg_mol']<67);self.assertIsNone(r['measured_sieving']);self.assertEqual(h.performance[4]['average_permeate_m3_s'],41e-6/60)
|
| 15 |
+
def test_02_concentration_conservation(self):
|
| 16 |
+
h=finish(configured());self.assertEqual(h.phase,'succeeded');self.assertAlmostEqual(h.volume,.0001);self.assertLedger(h);self.assertGreater(h.mass[0]/h.volume,9.);self.assertGreater(h.rf,0.)
|
| 17 |
+
def test_03_diafiltration_closed_form(self):
|
| 18 |
+
h=finish(configured(method={'mode':'diafilter','target_diavolumes':2.,'timeout_s':18000.}));self.assertEqual(h.phase,'succeeded');self.assertEqual(h.volume,.001);self.assertAlmostEqual(h.buffer_used,.002);self.assertAlmostEqual(h.osmoles,.3*math.exp(-2),places=10);self.assertLedger(h)
|
| 19 |
+
def test_04_pause_preserves_partial(self):
|
| 20 |
+
h=configured();h.invoke('acquisition.start');h.step(100);before=h.debug_snapshot();h.invoke('acquisition.stop');h.step(100);self.assertEqual(h.mass,before['masses']);self.assertEqual(h.adsorbed,before['adsorbed']);self.assertEqual(h.rf,before['state']['truth.fouling_resistance_ratio']);self.assertEqual(h.read()['pressure.retentate_gauge_pa'],0);h.invoke('acquisition.start');h.step(50);self.assertLess(h.volume,before['state']['volume.retentate_m3']);self.assertLedger(h)
|
| 21 |
+
def test_05_pressure_semantics(self):
|
| 22 |
+
h=configured();h.invoke('acquisition.start');v=h.read();self.assertEqual(v['pressure.feed_gauge_pa'],300000.);self.assertEqual(v['pressure.retentate_gauge_pa'],250000.);self.assertEqual(v['pressure.tmp_pa'],275000.);self.assertAlmostEqual(v['indicator.lift_m'],.025*250000/350000)
|
| 23 |
+
def test_06_pressure_guard_atomic(self):
|
| 24 |
+
h=SartoriusVivaflow200Runtime();h.invoke('plant.configure',**EXAMPLE);before=h.read('evaluator')
|
| 25 |
+
with self.assertRaises(ActionRejected):h.invoke('method.configure',**dict(METHOD_EXAMPLE,tmp_pa=390000.))
|
| 26 |
+
self.assertEqual(before,h.read('evaluator'))
|
| 27 |
+
def test_07_buffer_empty(self):
|
| 28 |
+
h=finish(configured(plant={'buffer_volume_m3':1e-6},method={'mode':'diafilter'}),100);self.assertEqual(h.fault,'BUFFER_EMPTY');self.assertLedger(h)
|
| 29 |
+
def test_08_permeate_full(self):
|
| 30 |
+
h=finish(configured(plant={'permeate_capacity_m3':1e-6}),100);self.assertEqual(h.fault,'PERMEATE_VESSEL_FULL');self.assertLedger(h)
|
| 31 |
+
def test_09_membrane_and_fouling(self):
|
| 32 |
+
a=configured();b=configured(cassette={'material':'RC'});c=configured(plant={'fouling_coefficient_m2_kg':0.,'adsorption_rate_s_inv':0.})
|
| 33 |
+
for h in [a,b,c]:h.invoke('acquisition.start');h.step(500);self.assertLedger(h)
|
| 34 |
+
self.assertLess(a.volume,b.volume);self.assertLess(c.volume,a.volume)
|
| 35 |
+
def test_10_osmotic_stall(self):
|
| 36 |
+
h=configured(plant={'channel_resistance_pa_s_m3':1e8},method={'tmp_pa':1000.},sample={'solutes':[{'substance_id':'uniprot_p02769','mass_kg':.05}]});finish(h,100);self.assertEqual(h.fault,'OSMOTIC_OR_FLOW_STALL');self.assertLedger(h)
|
| 37 |
+
def test_11_schema_and_clock(self):
|
| 38 |
+
h=configured();before=h.debug_snapshot();t=h.time_s;h.read();h.describe();h.invoke('filtration.measure');self.assertEqual(t,h.time_s)
|
| 39 |
+
for value in [True,-1,float('nan')]:
|
| 40 |
+
with self.assertRaises(ActionRejected):h.step(value)
|
| 41 |
+
with self.assertRaises(ActionRejected):h.invoke('method.configure',**dict(METHOD_EXAMPLE,tmp_pa=float('inf')))
|
| 42 |
+
self.assertEqual(before,h.debug_snapshot())
|
| 43 |
+
def test_12_protocol(self):
|
| 44 |
+
h=configured();h.register_principal('e','evaluator');a=h.session();e=h.session('e');self.assertNotIn('truth.initial_protein_kg',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='filtration.measure',arguments={},request_id='one')['error']['code'],'REQUEST_CONFLICT');self.assertEqual(a.poll(r['operation_id'])['status'],'running')
|
| 45 |
+
with self.assertRaises(ActionRejected):e.poll(r['operation_id'])
|
| 46 |
+
a.cancel(r['operation_id'],'cancel');self.assertEqual(h.phase,'cancelled');self.assertEqual(a.invoke(instance_id=h.instance_id,capability_id='product.read',arguments={},request_id='deny')['status'],'rejected');self.assertEqual(a.invoke(instance_id='wrong',capability_id='filtration.measure',arguments={},request_id='wrong')['status'],'rejected')
|
| 47 |
+
def test_13_cassette_identity(self):
|
| 48 |
+
h=SartoriusVivaflow200Runtime()
|
| 49 |
+
with self.assertRaises(ActionRejected):h.invoke('cassette.configure',material='RC',mwco_kg_mol=3.,legacy_2023_configuration_confirmed=True)
|
| 50 |
+
h.invoke('cassette.configure',**CASSETTE_EXAMPLE)
|
| 51 |
+
with self.assertRaises(ActionRejected):h.invoke('cassette.configure',**CASSETTE_EXAMPLE)
|
| 52 |
+
def test_14_instances_and_timeout(self):
|
| 53 |
+
a=configured(method={'timeout_s':10.});b=configured();finish(a,20);self.assertEqual(a.fault,'TIMEOUT_OR_TUBE_6H');self.assertEqual(b.phase,'idle');self.assertEqual(b.volume,.001);self.assertLedger(a)
|
| 54 |
+
def test_15_multi_solute(self):
|
| 55 |
+
h=configured(sample={'solutes':[{'substance_id':'uniprot_p02769','mass_kg':.0005},{'substance_id':'uniprot_p00698','mass_kg':.0005}]});h.invoke('acquisition.start');h.step(500);self.assertLedger(h);self.assertGreater(h.permeate_mass[1],h.permeate_mass[0]);self.assertLessEqual(sum(h.adsorbed),h.plant['adsorption_capacity_kg'])
|
| 56 |
+
if __name__=='__main__':unittest.main()
|
tests/test_asset_scp_digiprepms.py
ADDED
|
@@ -0,0 +1,97 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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.scp_digiprepms import *
|
| 5 |
+
def ready(sample=True,method=None,plant=None):
|
| 6 |
+
r=ScpDigiprepmsRuntime();r.invoke('plant.configure',**(plant or PLANT_EXAMPLE));r.invoke('method.configure',**(method or METHOD_EXAMPLE))
|
| 7 |
+
if sample:r.invoke('sample.configure',**example_sample())
|
| 8 |
+
r.invoke('power.set',enabled=True);return r
|
| 9 |
+
def cold_method():return dict(knots=[dict(time_s=0.,temperature_k=293.15)],hold_s=8.,timeout_s=30.)
|
| 10 |
+
def material(r):return [{k:v for k,v in t.items() if k!='temperature_k'} for t in r.invoke('product.read')['records']]
|
| 11 |
+
class Tests(unittest.TestCase):
|
| 12 |
+
def test_setpoint_only(self):
|
| 13 |
+
r=ready();before=r.block_t;r.invoke('thermal.set_temperature',temperature_k=363.15);self.assertEqual(r.block_t,before);self.assertEqual(r.time_s,0);self.assertEqual(r.target,363.15)
|
| 14 |
+
def test_query_pure(self):
|
| 15 |
+
r=ready();before=r.debug_snapshot();r.describe();r.read();r.invoke('reference.lookup',substance_id='gibbsite',temperature_k=368.15);r.invoke('history.read');r.session().read(instance_id=r.instance_id);self.assertEqual(before,r.debug_snapshot())
|
| 16 |
+
def test_invalid_atomic(self):
|
| 17 |
+
r=ready()
|
| 18 |
+
for a in [dict(temperature_k=True),dict(temperature_k=float('nan')),dict(temperature_k=500.),dict(temperature_k=350.,extra=1)]:
|
| 19 |
+
b=r.debug_snapshot()
|
| 20 |
+
with self.assertRaises(ActionRejected):r.invoke('thermal.set_temperature',**a)
|
| 21 |
+
self.assertEqual(b,r.debug_snapshot())
|
| 22 |
+
def test_program_order(self):
|
| 23 |
+
r=ready();m=copy.deepcopy(METHOD_EXAMPLE);m['knots']=[dict(time_s=1.,temperature_k=310.)];b=r.debug_snapshot()
|
| 24 |
+
with self.assertRaises(ActionRejected):r.invoke('method.configure',**m)
|
| 25 |
+
self.assertEqual(b,r.debug_snapshot())
|
| 26 |
+
def test_piecewise_program(self):
|
| 27 |
+
m=dict(knots=[dict(time_s=0.,temperature_k=293.15),dict(time_s=20.,temperature_k=313.15),dict(time_s=40.,temperature_k=303.15)],hold_s=60.,timeout_s=300.);r=ready(method=m);r.invoke('acquisition.start');r.step(10);self.assertAlmostEqual(r.target,303.15);self.assertLess(r.block_t,r.target);r.step(20);self.assertAlmostEqual(r.target,308.15)
|
| 28 |
+
def test_historical_heatup_not_tenfold(self):
|
| 29 |
+
r=ready(sample=False,method=dict(knots=[dict(time_s=0.,temperature_k=368.15)],hold_s=2000.,timeout_s=9000.));r.invoke('acquisition.start');r.step(2100);self.assertGreater(r.block_t,367.);self.assertLess(r.block_t,368.3)
|
| 30 |
+
def test_load_slows_heatup(self):
|
| 31 |
+
empty=ready(sample=False);loaded=ready(sample=False);s=example_sample();s['tubes']=[dict(s['tubes'][0],position=i,volume_m3=50e-6) for i in range(48)];loaded.invoke('sample.configure',**s)
|
| 32 |
+
for r in [empty,loaded]:r.invoke('acquisition.start');r.step(900)
|
| 33 |
+
self.assertLess(loaded.block_t,empty.block_t);self.assertEqual(len(loaded.tubes),48)
|
| 34 |
+
def test_capacity_and_duplicate_atomic(self):
|
| 35 |
+
r=ready(sample=False)
|
| 36 |
+
for s in [dict(example_sample(),tubes=[dict(example_sample()['tubes'][0],volume_m3=51e-6)]),dict(example_sample(),tubes=example_sample()['tubes']*2)]:
|
| 37 |
+
b=r.debug_snapshot()
|
| 38 |
+
with self.assertRaises(ActionRejected):r.invoke('sample.configure',**s)
|
| 39 |
+
self.assertEqual(b,r.debug_snapshot())
|
| 40 |
+
def test_unknown_reference_atomic(self):
|
| 41 |
+
r=ready(sample=False);s=example_sample();s['tubes'].append(dict(s['tubes'][0],position=1,substance_id='made_up'));b=r.debug_snapshot()
|
| 42 |
+
with self.assertRaises(ActionRejected):r.invoke('sample.configure',**s)
|
| 43 |
+
self.assertEqual(b,r.debug_snapshot())
|
| 44 |
+
def test_reference_range_and_real_data(self):
|
| 45 |
+
r=ScpDigiprepmsRuntime();self.assertGreaterEqual(len(r.templates),50)
|
| 46 |
+
for t in r.templates.values():self.assertAlmostEqual(r._logk(t['substance_id'],298.15),t['values'][0]['log10_k']);self.assertIsNone(t['measured_recovery'])
|
| 47 |
+
for temperature in [293.14,453.16]:
|
| 48 |
+
with self.assertRaisesRegex(ActionRejected,'REFERENCE_RANGE'):r._logk('gibbsite',temperature)
|
| 49 |
+
def test_energy_closure(self):
|
| 50 |
+
r=ready();r.invoke('acquisition.start');r.step(240);self.assertAlmostEqual(r._energy(),r.input_j-r.loss_j,places=6);r.invoke('acquisition.stop');r.step(50);self.assertAlmostEqual(r._energy(),r.input_j-r.loss_j,places=6)
|
| 51 |
+
def test_finite_three_ledgers(self):
|
| 52 |
+
r=ready();r.invoke('acquisition.start');r.step(1200)
|
| 53 |
+
for t in r.tubes:
|
| 54 |
+
self.assertAlmostEqual(t['initial_solid_mol'],t['solid_mol']+t['dissolved_mol'],places=14);self.assertAlmostEqual(t['initial_acid_mol'],sum(t[k] for k in ['acid_mol','acid_consumed_mol','acid_exhaust_mol']),places=14);self.assertAlmostEqual(t['initial_blank_mol'],t['blank_remaining_mol']+t['blank_dissolved_mol'],places=18);self.assertGreater(t['dissolved_mol'],0);self.assertGreater(t['acid_exhaust_mol'],0);self.assertGreater(t['blank_dissolved_mol'],0)
|
| 55 |
+
def test_acid_limits_dissolution(self):
|
| 56 |
+
r=ready(sample=False,method=cold_method());s=example_sample();s['tubes'][0].update(acid_mol=1e-8,rate_298_s=1.,activation_j_mol=0.,acid_evaporation_298_s=0.);r.invoke('sample.configure',**s);r.invoke('acquisition.start');r.step(20);t=r.tubes[0];self.assertLessEqual(t['dissolved_mol'],1e-8/3+1e-15);self.assertGreater(t['solid_mol'],0)
|
| 57 |
+
def test_program_completion_not_complete_digestion(self):
|
| 58 |
+
r=ready(method=cold_method());r.invoke('acquisition.start');r.step(12);self.assertEqual(r.phase,'succeeded');self.assertGreater(r.tubes[0]['solid_mol'],0)
|
| 59 |
+
def test_timeout_partial(self):
|
| 60 |
+
r=ready(method=dict(METHOD_EXAMPLE,timeout_s=3.));r.invoke('acquisition.start');r.step(10);self.assertEqual(r.phase,'failed');self.assertEqual(r.fault,'TIMEOUT');self.assertEqual(r.elapsed_s,3.)
|
| 61 |
+
def test_cancel_resume(self):
|
| 62 |
+
r=ready(method=cold_method());a=r.session().invoke(instance_id=r.instance_id,capability_id='acquisition.start',arguments={},request_id='start');self.assertEqual(a['status'],'accepted');r.step(3);op=a['operation_id'];r.session().cancel(op,'stop');before=material(r);r.step(10);self.assertEqual(before,material(r));b=r.session().invoke(instance_id=r.instance_id,capability_id='acquisition.start',arguments={},request_id='resume');self.assertNotEqual(op,b['operation_id']);r.step(8);self.assertEqual(r.session().poll(b['operation_id'])['status'],'succeeded')
|
| 63 |
+
def test_power_cancel(self):
|
| 64 |
+
r=ready();r.invoke('acquisition.start');r.step(5);r.invoke('power.set',enabled=False);self.assertEqual(r.phase,'cancelled');b=material(r);r.step(5);self.assertEqual(b,material(r));self.assertEqual(r.heater_w,0.)
|
| 65 |
+
def test_probe_connection_and_feedback(self):
|
| 66 |
+
r=ready();b=r.debug_snapshot()
|
| 67 |
+
with self.assertRaises(ActionRejected):r.invoke('probe.configure',mode='external',position=0,connected=False)
|
| 68 |
+
self.assertEqual(b,r.debug_snapshot());r.invoke('probe.configure',mode='external',position=0,connected=True);r.invoke('acquisition.start');r.step(50);self.assertEqual(r._indicated(),r.tubes[0]['temperature_k']);self.assertLess(r._indicated(),r.block_t)
|
| 69 |
+
def test_rack_goal_only_and_start_guard(self):
|
| 70 |
+
r=ready();r.invoke('rack.set',side='left',lift_m=.1);self.assertEqual(r.lift[0],0.)
|
| 71 |
+
with self.assertRaises(ActionRejected):r.invoke('acquisition.start')
|
| 72 |
+
r.step(3);self.assertAlmostEqual(r.lift[0],.06);r.invoke('rack.set',side='left',lift_m=0.);r.step(3);self.assertAlmostEqual(r.lift[0],0.)
|
| 73 |
+
def test_busy_and_hot_guards(self):
|
| 74 |
+
r=ready();r.invoke('acquisition.start');b=r.debug_snapshot()
|
| 75 |
+
with self.assertRaises(ActionRejected):r.invoke('rack.set',side='left',lift_m=.1)
|
| 76 |
+
self.assertEqual(b,r.debug_snapshot());r.step(1800);r.invoke('acquisition.stop');b=r.debug_snapshot()
|
| 77 |
+
with self.assertRaises(ActionRejected):r.invoke('rack.set',side='left',lift_m=.1)
|
| 78 |
+
self.assertEqual(b,r.debug_snapshot())
|
| 79 |
+
def test_tube_limit(self):
|
| 80 |
+
r=ready();b=r.debug_snapshot()
|
| 81 |
+
with self.assertRaises(ActionRejected):r.invoke('thermal.set_temperature',temperature_k=453.15)
|
| 82 |
+
self.assertEqual(b,r.debug_snapshot())
|
| 83 |
+
def test_two_instances(self):
|
| 84 |
+
a=ready();b=ready();before=b.debug_snapshot();a.invoke('acquisition.start');a.step(50);self.assertEqual(before,b.debug_snapshot())
|
| 85 |
+
def test_privacy_and_request_retry(self):
|
| 86 |
+
r=ready();s=r.session();self.assertNotIn('product.read',s.describe(instance_id=r.instance_id)['capabilities']);self.assertFalse(any(k.startswith('truth.') for k in r.read()));bad=s.invoke(instance_id=r.instance_id,capability_id='product.read',arguments={},request_id='truth');self.assertEqual(bad['error']['code'],'ACCESS_DENIED')
|
| 87 |
+
with self.assertRaises(ActionRejected):s.read(instance_id=r.instance_id,state_ids=['truth.solid_mol'])
|
| 88 |
+
q=dict(instance_id=r.instance_id,capability_id='power.set',arguments=dict(enabled=True),request_id='same');a=s.invoke(**q);b=r.debug_snapshot();self.assertEqual(a,s.invoke(**q));self.assertEqual(b,r.debug_snapshot());q['arguments']['enabled']=False;self.assertEqual(s.invoke(**q)['error']['code'],'REQUEST_CONFLICT');self.assertEqual(b,r.debug_snapshot())
|
| 89 |
+
def test_owner_poll_denied(self):
|
| 90 |
+
r=ready();r.register_principal('other','agent');op=r.session().invoke(instance_id=r.instance_id,capability_id='acquisition.start',arguments={},request_id='s')['operation_id']
|
| 91 |
+
with self.assertRaises(ActionRejected):r.session('other').poll(op)
|
| 92 |
+
def test_zero_step_and_invalid_dt(self):
|
| 93 |
+
r=ready();b=r.debug_snapshot();r.step(0);self.assertEqual(b,r.debug_snapshot())
|
| 94 |
+
for x in [-1.,True,float('inf')]:
|
| 95 |
+
with self.assertRaises(ActionRejected):r.step(x)
|
| 96 |
+
self.assertEqual(b,r.debug_snapshot())
|
| 97 |
+
if __name__=='__main__':unittest.main()
|
tests/test_asset_sft_sft110.py
ADDED
|
@@ -0,0 +1,74 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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.sft_sft110 import *
|
| 5 |
+
def configured(plant=None,method=None,sample=None):
|
| 6 |
+
h=SftSft110Runtime();h.invoke('plant.configure',**dict(EXAMPLE,**(plant or {})));h.invoke('method.configure',**dict(METHOD_EXAMPLE,**(method or {})));h.invoke('door.set_angle',angle_rad=1.2);h.invoke('cap.set_lift',lift_m=.07);h.invoke('sample.configure',**dict(SAMPLE_EXAMPLE,**(sample or {})));h.invoke('cap.set_lift',lift_m=0.);h.invoke('door.set_angle',angle_rad=0.);h.invoke('power.set',enabled=True);return h
|
| 7 |
+
def until(h,stage,limit=4000):
|
| 8 |
+
for _ in range(limit):
|
| 9 |
+
if h.stage==stage or h.phase in ['failed','succeeded']:return h
|
| 10 |
+
h.step(.5)
|
| 11 |
+
raise AssertionError((h.stage,h.phase))
|
| 12 |
+
def finish(h):
|
| 13 |
+
h.invoke('acquisition.start')
|
| 14 |
+
for _ in range(3000):
|
| 15 |
+
h.step(.5)
|
| 16 |
+
if h.phase!='running':return h
|
| 17 |
+
raise AssertionError((h.stage,h.phase))
|
| 18 |
+
class TestSft110(unittest.TestCase):
|
| 19 |
+
def ledger(self,h):
|
| 20 |
+
v=h.read('evaluator');self.assertAlmostEqual(v['truth.initial_co2_kg'],sum(v['truth.'+x+'_co2_kg'] for x in ['tank','chamber','exhaust']),places=10);self.assertAlmostEqual(v['truth.initial_solute_kg'],sum(v['truth.'+x+'_solute_kg'] for x in ['residue','dissolved','collected','deposit']),places=12)
|
| 21 |
+
def test_01_reference_exact_and_interpolation(self):
|
| 22 |
+
h=SftSft110Runtime();self.assertEqual(len(h.templates),60)
|
| 23 |
+
for t in h.templates.values():
|
| 24 |
+
points=t['values']['solubility_curve']
|
| 25 |
+
for p in points:self.assertAlmostEqual(h._reference(t['substance_id'],313.15,p['pressure_abs_pa'])['mole_fraction'],p['mole_fraction'],places=12)
|
| 26 |
+
a,b=points[:2];self.assertAlmostEqual(h._reference(t['substance_id'],313.15,(a['pressure_abs_pa']+b['pressure_abs_pa'])/2)['mole_fraction'],math.sqrt(a['mole_fraction']*b['mole_fraction']),places=12)
|
| 27 |
+
def test_02_full_cycle(self):
|
| 28 |
+
h=finish(configured());self.assertEqual(h.phase,'succeeded');self.assertAlmostEqual(h.pressure,101325.,delta=1.);self.assertGreater(h.collected,0);self.assertGreater(h.residue,0);self.ledger(h)
|
| 29 |
+
def test_03_static_no_flow(self):
|
| 30 |
+
h=configured();h.invoke('acquisition.start');until(h,'static');old=h.tank;h.step(20);self.assertEqual(h.tank,old);self.assertEqual(h.qin,0.);self.assertGreater(h.dissolved,0.);self.ledger(h)
|
| 31 |
+
def test_04_cancel_residual_resume(self):
|
| 32 |
+
h=configured();h.invoke('acquisition.start');until(h,'dynamic');h.step(10);old=h.read('evaluator');h.invoke('acquisition.stop');h.step(10);self.assertEqual(h.collected,old['truth.collected_solute_kg']);self.assertEqual(h.mco2,old['truth.chamber_co2_kg']);self.assertGreater(h.pressure,1e7);self.assertEqual(h._valve_angle(),0.);h.invoke('acquisition.start');h.step(10);self.assertGreater(h.collected,old['truth.collected_solute_kg']);self.ledger(h)
|
| 33 |
+
def test_05_manual_handling_guard_atomic(self):
|
| 34 |
+
h=configured();h.invoke('acquisition.start');until(h,'static');h.invoke('acquisition.stop');old=h.debug_snapshot()
|
| 35 |
+
with self.assertRaises(ActionRejected):h.invoke('door.set_angle',angle_rad=1.2)
|
| 36 |
+
self.assertEqual(old,h.debug_snapshot())
|
| 37 |
+
def test_06_power_loss_conserves_trapped_mass(self):
|
| 38 |
+
h=configured();h.invoke('acquisition.start');until(h,'dynamic');old=h.mco2;oldp=h.pressure;h.invoke('power.set',enabled=False);h.step(20);self.assertEqual(h.phase,'cancelled');self.assertEqual(h.mco2,old);self.assertLess(h.pressure,oldp);self.assertGreater(h.pressure,1e6);self.ledger(h)
|
| 39 |
+
def test_07_deposition_fault(self):
|
| 40 |
+
h=finish(configured(plant={'capture_fraction':0.,'deposit_limit_kg':1e-8}));self.assertEqual(h.fault,'RESTRICTOR_DEPOSITION_LIMIT');self.assertGreater(h.pressure,1e6);self.ledger(h)
|
| 41 |
+
def test_08_collection_full(self):
|
| 42 |
+
h=finish(configured(plant={'collection_capacity_kg':1e-7}));self.assertEqual(h.fault,'COLLECTION_FULL');self.ledger(h)
|
| 43 |
+
def test_09_finite_supply(self):
|
| 44 |
+
h=finish(configured(plant={'tank_mass_kg':.0001}));self.assertEqual(h.fault,'CO2_SUPPLY_EMPTY');self.ledger(h)
|
| 45 |
+
def test_10_reference_domain_reject(self):
|
| 46 |
+
h=configured();old=h.debug_snapshot()
|
| 47 |
+
for t,p in [(323.15,20e6),(313.15,1e6)]:
|
| 48 |
+
with self.assertRaises(ActionRejected):h.invoke('reference.lookup',substance_id=SAMPLE_EXAMPLE['substance_id'],temperature_k=t,pressure_abs_pa=p)
|
| 49 |
+
self.assertEqual(h.debug_snapshot(),old)
|
| 50 |
+
def test_11_pure_queries_clock_and_schema(self):
|
| 51 |
+
h=configured();old=h.debug_snapshot();h.read();h.describe();h.invoke('extraction.measure');self.assertEqual(old,h.debug_snapshot())
|
| 52 |
+
for dt in [True,-1,float('nan')]:
|
| 53 |
+
with self.assertRaises(ActionRejected):h.step(dt)
|
| 54 |
+
with self.assertRaises(ActionRejected):h.invoke('method.configure',**dict(METHOD_EXAMPLE,modifier_fraction=.1))
|
| 55 |
+
self.assertEqual(old,h.debug_snapshot())
|
| 56 |
+
def test_12_native_protocol(self):
|
| 57 |
+
h=configured();h.register_principal('e','evaluator');a=h.session();e=h.session('e');self.assertNotIn('truth.initial_solute_kg',a.read(instance_id=h.instance_id)['observations']);self.assertNotIn('sample.configure',a.describe(instance_id=h.instance_id)['capabilities']);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='extraction.measure',arguments={},request_id='one')['error']['code'],'REQUEST_CONFLICT');self.assertEqual(a.poll(r['operation_id'])['status'],'running')
|
| 58 |
+
with self.assertRaises(ActionRejected):e.poll(r['operation_id'])
|
| 59 |
+
a.cancel(r['operation_id'],'cancel');self.assertEqual(h.phase,'cancelled');self.assertEqual(a.invoke(instance_id=h.instance_id,capability_id='product.read',arguments={},request_id='deny')['status'],'rejected')
|
| 60 |
+
def test_13_instances_and_timeouts(self):
|
| 61 |
+
a=finish(configured(method={'timeout_s':10.}));b=configured();self.assertEqual(a.fault,'TIMEOUT');self.assertEqual(b.phase,'idle');self.assertEqual(b.tank,1.);self.ledger(a)
|
| 62 |
+
def test_14_pressure_drop_guard(self):
|
| 63 |
+
h=SftSft110Runtime();h.invoke('plant.configure',**dict(EXAMPLE,particle_diameter_m=1e-6,porosity=.1));old=h.debug_snapshot()
|
| 64 |
+
with self.assertRaises(ActionRejected):h.invoke('method.configure',**dict(METHOD_EXAMPLE,pressure_gauge_pa=68e6))
|
| 65 |
+
self.assertEqual(old,h.debug_snapshot())
|
| 66 |
+
def test_15_liquid_supply_reject(self):
|
| 67 |
+
h=SftSft110Runtime();old=h.debug_snapshot()
|
| 68 |
+
with self.assertRaises(ActionRejected):h.invoke('plant.configure',**dict(EXAMPLE,supply_temperature_k=293.15,supply_pressure_abs_pa=4e6))
|
| 69 |
+
self.assertEqual(old,h.debug_snapshot())
|
| 70 |
+
def test_16_explicit_vent(self):
|
| 71 |
+
h=configured();h.invoke('acquisition.start');until(h,'static');h.invoke('acquisition.stop');h.invoke('pressure.vent');h.step(300);self.assertEqual(h.phase,'succeeded');self.ledger(h)
|
| 72 |
+
def test_17_method_only_sets_target(self):
|
| 73 |
+
h=configured();self.assertEqual(h.temperature,EXAMPLE['ambient_k']);self.assertEqual(h.pressure,EXAMPLE['ambient_pa']);self.assertEqual(h.elapsed_s,0)
|
| 74 |
+
if __name__=='__main__':unittest.main()
|
tests/test_asset_syrris_asiadiscovery.py
ADDED
|
@@ -0,0 +1,91 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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'));sys.path.insert(0,str(ROOT/'skills/chemistry-lab-assets/scripts'))
|
| 4 |
+
import asset_tool
|
| 5 |
+
from asset_runtime.syrris_asiadiscovery import *
|
| 6 |
+
def prepared(method=None,**plant):
|
| 7 |
+
h=SyrrisAsiadiscoveryRuntime();h.invoke('clamp.set_lift',lift_m=.04)
|
| 8 |
+
if method:h.invoke('method.configure',**method)
|
| 9 |
+
h.invoke('plant.configure',**dict(EXAMPLE,**plant));h.invoke('clamp.set_lift',lift_m=0.);h.invoke('power.set',enabled=True);return h
|
| 10 |
+
class AsiaTest(unittest.TestCase):
|
| 11 |
+
def balance(self,h):
|
| 12 |
+
v=h.read('evaluator')
|
| 13 |
+
for suffix in ['volume_m3','mass_kg']:self.assertAlmostEqual(v['truth.initial_'+suffix],sum(v['truth.'+k+'_'+suffix] for k in ['retained','collected','waste','removed']),12)
|
| 14 |
+
for i in range(2):self.assertAlmostEqual(v['truth.initial_tracer_mol'][i],sum(v['truth.'+k+'_tracer_mol'][i] for k in ['retained','collected','waste','removed']),14)
|
| 15 |
+
def test_contract_schemas(self):
|
| 16 |
+
m=export_syrris_asiadiscovery_contract_metadata();self.assertEqual(len(m['capabilities']),13)
|
| 17 |
+
for cap in m['capabilities'].values():
|
| 18 |
+
self.assertFalse(asset_tool.lint_schema(cap['input_schema']));self.assertFalse(asset_tool.lint_schema(cap['output_schema']));self.assertFalse(asset_tool.validate_value(cap['example_arguments'],cap['input_schema']))
|
| 19 |
+
def test_all_78_templates_drive_runtime(self):
|
| 20 |
+
ts=SyrrisAsiadiscoveryRuntime().templates;self.assertEqual(len(ts),78);self.assertEqual(len({t['cas'] for t in ts.values()}),78)
|
| 21 |
+
for t in ts.values():
|
| 22 |
+
f=t['fits'][0];lo,hi=f['runtime_temperature_range_k'];temp=(lo+hi)/2;h=prepared(substance_id=t['substance_id'],fit_id=f['fit_id'],initial_temperature_k=temp,low_temperature_available=True);p=1e5*10**(f['A']-f['B_k']/(temp+f['C_k']));self.assertAlmostEqual(h.vapor(temp)/p,1.,12);h.invoke('pressure.set',backpressure_pa=1.9e6)
|
| 23 |
+
if p<2.001325e6:h.invoke('acquisition.start');h.step(.03);self.assertGreater(h.waste,0)
|
| 24 |
+
else:
|
| 25 |
+
with self.assertRaises(ActionRejected):h.invoke('acquisition.start')
|
| 26 |
+
self.balance(h)
|
| 27 |
+
def test_window_transport_and_mass_tracer_conservation(self):
|
| 28 |
+
h=prepared();h.invoke('acquisition.start');h.step(4.3);self.assertEqual(h.phase,'succeeded');self.assertAlmostEqual(h.elapsed_s,4.,10);self.assertAlmostEqual(sum(h.collected),sum(METHOD_EXAMPLE['flow_rates_m3_s'])*2.5,13);self.assertGreater(sum(h.collected_tracer[0]),0);self.balance(h)
|
| 29 |
+
self.assertGreater(h.cells[6][0],0);self.assertGreater(h.cells[6][1],0);h.invoke('collector.unload',slot=0,container_id='fraction_0');self.balance(h)
|
| 30 |
+
def test_ordered_injection_and_finite_dead_volume(self):
|
| 31 |
+
h=prepared();h.invoke('acquisition.start');h.step(.2);self.assertGreater(h.cells[0][0],0);self.assertEqual(h.cells[1][1],0);self.assertGreater(h.loops[1],0);self.assertEqual(sum(h.collected),0);h.step(.4);self.assertGreater(h.cells[1][1],0);self.balance(h)
|
| 32 |
+
def test_two_chip_volumes_and_RTD(self):
|
| 33 |
+
for volume in [250e-9,1e-6]:
|
| 34 |
+
h=prepared(chip_volume_m3=volume);r=h.invoke('residence.measure');self.assertAlmostEqual(r['chip_mean_s'],volume/sum(METHOD_EXAMPLE['flow_rates_m3_s']));self.assertGreater(r['mean_s'],r['chip_mean_s']);self.assertGreater(r['variance_s2'],r['chip_mean_s']**2/4)
|
| 35 |
+
def test_each_syringe_range_and_channel_specific(self):
|
| 36 |
+
for name,(lo,hi) in SYRINGES.items():
|
| 37 |
+
m=copy.deepcopy(METHOD_EXAMPLE);m['flow_rates_m3_s']=[lo*ULMIN,hi*ULMIN];h=prepared(method=m,syringes=[name]*2);h.invoke('acquisition.start');h.step(.02);self.balance(h);h.invoke('acquisition.stop');bad=copy.deepcopy(m);bad['flow_rates_m3_s'][0]=max(ULMIN,(lo-1)*ULMIN) if lo>1 else (hi+1)*ULMIN
|
| 38 |
+
with self.assertRaises(ActionRejected):h.invoke('method.configure',**bad)
|
| 39 |
+
def test_numerical_pulse_breakthrough_RTD_moments(self):
|
| 40 |
+
m=copy.deepcopy(METHOD_EXAMPLE);m.update(duration_s=20.,injection_times_s=[0.,20.],collection_windows=[]);h=prepared(method=m,loop_volumes_m3=[.1e-6]*2,loop_concentrations_mol_m3=[1.,0.]);r=h.invoke('residence.measure');h.invoke('acquisition.start');mass=first=second=0.;last=0.
|
| 41 |
+
for _ in range(1000):
|
| 42 |
+
h.step(.02);dm=h.waste_tracer[0]-last;last=h.waste_tracer[0];mid=h.elapsed_s-.01;mass+=dm;first+=dm*mid;second+=dm*mid*mid
|
| 43 |
+
pulse=.1e-6/m['flow_rates_m3_s'][0];mean=first/mass;variance=second/mass-mean*mean
|
| 44 |
+
self.assertAlmostEqual(mass,1e-7,12);self.assertAlmostEqual(mean,r['mean_s']+pulse/2,delta=.03);self.assertAlmostEqual(variance,r['variance_s2']+pulse*pulse/12,delta=.05);self.balance(h)
|
| 45 |
+
def test_pressure_loss_and_guard(self):
|
| 46 |
+
h=prepared();h.invoke('acquisition.start');p=h.pressures();q=METHOD_EXAMPLE['flow_rates_m3_s'];self.assertAlmostEqual(p[0],2e5+1e11*(sum(q)+q[0]));h.invoke('acquisition.stop');h.invoke('pressure.set',backpressure_pa=2e6);old=h.debug_snapshot()
|
| 47 |
+
with self.assertRaises(ActionRejected):h.invoke('acquisition.start')
|
| 48 |
+
self.assertEqual(old,h.debug_snapshot())
|
| 49 |
+
def test_vapor_guard_and_no_extrapolation(self):
|
| 50 |
+
h=prepared();old=h.debug_snapshot()
|
| 51 |
+
with self.assertRaises(ActionRejected):h.invoke('temperature.set',target_k=423.15)
|
| 52 |
+
self.assertEqual(old,h.debug_snapshot());h.invoke('temperature.set',target_k=356.7);h.invoke('pressure.set',backpressure_pa=1e5)
|
| 53 |
+
with self.assertRaises(ActionRejected):h.invoke('acquisition.start')
|
| 54 |
+
def test_thermal_response_only_on_step(self):
|
| 55 |
+
h=prepared();h.invoke('temperature.set',target_k=308.15);self.assertEqual(h.temp_k,298.15);h.step(1.);self.assertAlmostEqual(h.temp_k,308.15-10*math.exp(-.1),10)
|
| 56 |
+
def test_cancel_and_restart_retains_holdup(self):
|
| 57 |
+
h=prepared();h.invoke('acquisition.start');h.step(.5);old=copy.deepcopy(h.cells);loops=h.loops[:];h.invoke('acquisition.stop');h.step(.2);self.assertEqual(h.cells,old);self.assertEqual(h.loops,loops);h.invoke('acquisition.start');h.step(.2);self.assertNotEqual(h.cells,old);h.invoke('power.set',enabled=False);self.assertEqual(h.phase,'cancelled');self.balance(h)
|
| 58 |
+
def test_reservoir_and_collector_faults_retain_mass(self):
|
| 59 |
+
h=prepared(reservoir_volumes_m3=[1e-7]*2);h.invoke('acquisition.start');h.step(3.);self.assertEqual(h.fault,'reservoir_empty');self.balance(h)
|
| 60 |
+
m=copy.deepcopy(METHOD_EXAMPLE);m['duration_s']=40.;m['collection_windows']=[dict(start_s=0.,end_s=40.,slot=0)];h=prepared(method=m);h.invoke('acquisition.start');h.step(40.);self.assertEqual(h.fault,'collector_full');self.assertLessEqual(h.collected[0],5e-6+1e-15);self.balance(h)
|
| 61 |
+
def test_rejected_inputs_atomic_and_interlock(self):
|
| 62 |
+
h=prepared();old=copy.deepcopy(h.__dict__)
|
| 63 |
+
for cap,args in [('clamp.set_lift',{'lift_m':True}),('pressure.set',{'backpressure_pa':float('nan')}),('collector.unload',{'slot':.0,'container_id':'fraction_0'}),('collector.unload',{'slot':8,'container_id':'fraction_8'})]:
|
| 64 |
+
with self.assertRaises(ActionRejected):h.invoke(cap,**args)
|
| 65 |
+
self.assertEqual(old,h.__dict__)
|
| 66 |
+
m=copy.deepcopy(METHOD_EXAMPLE);m['collection_windows']=[dict(start_s=0.,end_s=3.,slot=0),dict(start_s=2.,end_s=4.,slot=1)]
|
| 67 |
+
with self.assertRaises(ActionRejected):h.invoke('method.configure',**m)
|
| 68 |
+
self.assertEqual(old,h.__dict__);h.invoke('acquisition.start')
|
| 69 |
+
with self.assertRaises(ActionRejected):h.invoke('clamp.set_lift',lift_m=.04)
|
| 70 |
+
def test_reads_pure_unknown_products(self):
|
| 71 |
+
h=prepared();h.invoke('acquisition.start');h.step(.3);old=copy.deepcopy(h.__dict__)
|
| 72 |
+
for _ in range(3):h.read();h.describe();h.invoke('flow.measure');h.invoke('history.read');h.invoke('product.read');h.invoke('residence.measure')
|
| 73 |
+
self.assertEqual(old,h.__dict__);self.assertIsNone(h.invoke('flow.measure')['yield_fraction']);self.assertIsNone(h.invoke('product.read')['reaction_products'])
|
| 74 |
+
def test_isolation_identity_filter_dedup_async(self):
|
| 75 |
+
h=prepared();b=SyrrisAsiadiscoveryRuntime('other');s=h.session();args=dict(instance_id=h.instance_id,capability_id='acquisition.start',arguments={},request_id='start');r=s.invoke(**args);self.assertEqual(r['status'],'accepted');self.assertEqual(s.invoke(**args),r);h.step(.2);self.assertEqual(s.poll(r['operation_id'])['status'],'running');self.assertNotIn('truth.cell_tracer_mol',s.read(instance_id=h.instance_id)['observations']);self.assertNotIn('product.read',s.describe(instance_id=h.instance_id)['capabilities']);self.assertFalse(b.powered)
|
| 76 |
+
x=s.invoke(instance_id=h.instance_id,capability_id='product.read',arguments={},request_id='deny');self.assertEqual(x['error']['code'],'ACCESS_DENIED');self.assertEqual(s.cancel(r['operation_id'],'cancel')['status'],'cancelled');self.balance(h)
|
| 77 |
+
self.assertEqual(s.write(instance_id=h.instance_id,state_id='pressure.backpressure_pa',value=3e5,request_id='bp')['status'],'succeeded')
|
| 78 |
+
def test_all_actual_outputs_and_slots_schema(self):
|
| 79 |
+
h=SyrrisAsiadiscoveryRuntime()
|
| 80 |
+
def ck(k,a=None):
|
| 81 |
+
r=h.invoke(k,**(CAPS[k][6] if a is None else a));self.assertFalse(asset_tool.validate_value(r,CAPS[k][1]),k)
|
| 82 |
+
for k in ['clamp.set_lift','plant.configure','power.set','method.configure','temperature.set','pressure.set']:ck(k)
|
| 83 |
+
ck('clamp.set_lift',{'lift_m':0.});ck('acquisition.start');h.step(1.)
|
| 84 |
+
for k in ['flow.measure','history.read','product.read','residence.measure','acquisition.stop']:ck(k)
|
| 85 |
+
ck('collector.unload')
|
| 86 |
+
for k,v in h.read('evaluator').items():self.assertFalse(asset_tool.validate_value(v,SLOTS[k][0]),k)
|
| 87 |
+
def test_bad_dt(self):
|
| 88 |
+
h=prepared()
|
| 89 |
+
for dt in [0,-1,True,float('nan'),float('inf')]:
|
| 90 |
+
with self.assertRaises(ValueError):h.step(dt)
|
| 91 |
+
if __name__=='__main__':unittest.main()
|
tests/test_asset_syrris_asiafllex.py
ADDED
|
@@ -0,0 +1,85 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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.syrris_asiafllex import *
|
| 5 |
+
def configured(plant=None,membrane=None,method=None,sample=None):
|
| 6 |
+
h=SyrrisAsiaFllexRuntime();h.invoke('plant.configure',**dict(EXAMPLE,**(plant or {})));h.invoke('tray.set_extension',extension_m=.07);h.invoke('separator.set_opening',opening_m=.04);h.invoke('membrane.configure',**dict(MEMBRANE_EXAMPLE,**(membrane or {})));h.invoke('separator.set_opening',opening_m=0.);h.invoke('tray.set_extension',extension_m=0.);h.invoke('method.configure',**dict(METHOD_EXAMPLE,**(method or {})));h.invoke('sample.configure',**dict(SAMPLE_EXAMPLE,**(sample or {})));h.invoke('power.set',enabled=True);return h
|
| 7 |
+
def until(h,stage,limit=4000):
|
| 8 |
+
for _ in range(limit):
|
| 9 |
+
if h.stage==stage or h.phase in ['failed','succeeded']:return h
|
| 10 |
+
h.step(.25)
|
| 11 |
+
raise AssertionError((h.stage,h.phase))
|
| 12 |
+
def finish(h,dt=.25):
|
| 13 |
+
h.invoke('acquisition.start')
|
| 14 |
+
for _ in range(20000):
|
| 15 |
+
h.step(dt)
|
| 16 |
+
if h.phase!='running':return h
|
| 17 |
+
raise AssertionError((h.stage,h.phase))
|
| 18 |
+
class TestAsiaFllex(unittest.TestCase):
|
| 19 |
+
def ledger(self,h):
|
| 20 |
+
self.assertAlmostEqual(float(h.mass.sum()),h.initial_mass,delta=1e-15)
|
| 21 |
+
for k in range(2):self.assertAlmostEqual(float(h.vol[:,k].sum()),float(h.initial_vol[k]),delta=1e-15)
|
| 22 |
+
self.assertGreaterEqual(float(h.mass.min()),0.);self.assertGreaterEqual(float(h.vol.min()),0.)
|
| 23 |
+
def test_01_reference60(self):
|
| 24 |
+
h=SyrrisAsiaFllexRuntime();self.assertEqual(len(h.templates),60)
|
| 25 |
+
for sid,t in h.templates.items():
|
| 26 |
+
r=h.invoke('reference.lookup',substance_id=sid);self.assertEqual(r['kow'],10**t['values']['log10_kow']);self.assertIsNone(r['temperature_k']);self.assertIsNone(r['ph'])
|
| 27 |
+
def test_02_full_extraction(self):
|
| 28 |
+
h=finish(configured());self.assertEqual(h.phase,'succeeded');self.assertGreater(h.mass[4],0.);self.assertGreater(h.mass[5],0.);self.assertGreater(h.mass[2],0.);self.assertGreater(h.mass[3],0.);self.assertEqual(h.bpr,2e5);self.assertAlmostEqual(h.processed_s,120.);self.assertEqual(h.purity,[1.,1.]);self.ledger(h)
|
| 29 |
+
def test_03_zero_transfer_analytic(self):
|
| 30 |
+
h=finish(configured(plant={'mass_transfer_coeff_m_s':0.}));q=h.method['aqueous_flow_m3_s'];v=h.vol[1,0];c=h.feed_conc[0];expected=v*c*(1-math.exp(-q*120/v));self.assertAlmostEqual(h.mass[2],expected,delta=1e-16);self.assertEqual(h.mass[5],0.);self.ledger(h)
|
| 31 |
+
def test_04_cancel_resume_residual(self):
|
| 32 |
+
h=configured();h.invoke('acquisition.start');until(h,'extracting');h.step(10);mass=h.mass.copy();vol=h.vol.copy();h.invoke('acquisition.stop');h.step(5);np.testing.assert_array_equal(h.mass,mass);np.testing.assert_array_equal(h.vol,vol);self.assertEqual(h.bpr,2e5);h=finish(h);self.assertEqual(h.phase,'succeeded');self.ledger(h)
|
| 33 |
+
def test_05_shutdown_traps_pressure(self):
|
| 34 |
+
h=configured();h.invoke('acquisition.start');until(h,'extracting');h.step(10);p=h.bpr;mass=h.mass.copy();h.invoke('power.set',enabled=False);h.step(50);self.assertEqual(h.phase,'cancelled');self.assertEqual(h.bpr,p);np.testing.assert_array_equal(mass,h.mass);self.ledger(h)
|
| 35 |
+
def test_06_organic_breakthrough_partial(self):
|
| 36 |
+
h=finish(configured(method={'cross_membrane_pa':1000.}));self.assertEqual(h.fault,'ORGANIC_BREAKTHROUGH');self.assertGreater(h.vol[2,1],0.);self.assertGreater(h.vol[3,1],0.);self.ledger(h)
|
| 37 |
+
def test_07_membrane_wetting_partial(self):
|
| 38 |
+
h=finish(configured(method={'cross_membrane_pa':4e4}));self.assertEqual(h.fault,'MEMBRANE_WETTING');self.assertTrue(h.wetted);self.assertGreater(h.vol[3,0],0.);self.ledger(h)
|
| 39 |
+
def test_08_continue_degraded(self):
|
| 40 |
+
h=finish(configured(method={'cross_membrane_pa':1000.,'stop_on_breakthrough':False}));self.assertEqual(h.phase,'succeeded');self.assertLess(h.purity[0],1.);self.assertGreater(h.vol[2,1],0.);self.ledger(h)
|
| 41 |
+
def test_09_finite_feed(self):
|
| 42 |
+
h=finish(configured(sample={'aqueous_feed_volume_m3':30e-9,'aqueous_solute_mass_kg':1e-8}));self.assertEqual(h.fault,'FEED_EMPTY');self.assertAlmostEqual(h.vol[0,0],0.,delta=1e-15);self.ledger(h)
|
| 43 |
+
def test_10_collection_full(self):
|
| 44 |
+
h=finish(configured(plant={'aqueous_collection_capacity_m3':30e-9}));self.assertEqual(h.fault,'COLLECTION_FULL');self.assertAlmostEqual(h.vol[2].sum(),30e-9,delta=1e-15);self.ledger(h)
|
| 45 |
+
def test_11_service_guard_atomic(self):
|
| 46 |
+
h=configured();old=h.debug_snapshot()
|
| 47 |
+
with self.assertRaises(ActionRejected):h.invoke('tray.set_extension',extension_m=.07)
|
| 48 |
+
self.assertEqual(h.debug_snapshot(),old)
|
| 49 |
+
h2=SyrrisAsiaFllexRuntime();h2.invoke('tray.set_extension',extension_m=.07);h2.invoke('separator.set_opening',opening_m=.04);old=h2.debug_snapshot()
|
| 50 |
+
with self.assertRaises(ActionRejected):h2.invoke('tray.set_extension',extension_m=0.)
|
| 51 |
+
self.assertEqual(h2.debug_snapshot(),old)
|
| 52 |
+
def test_12_method_gas_flow_atomic(self):
|
| 53 |
+
h=SyrrisAsiaFllexRuntime();h.invoke('plant.configure',**EXAMPLE);old=h.debug_snapshot()
|
| 54 |
+
for patch in [{'bpr_gauge_pa':7e5},{'organic_flow_m3_s':500e-9/60}]:
|
| 55 |
+
with self.assertRaises(ActionRejected):h.invoke('method.configure',**dict(METHOD_EXAMPLE,**patch))
|
| 56 |
+
self.assertEqual(h.debug_snapshot(),old)
|
| 57 |
+
def test_13_pure_read_clock_schema(self):
|
| 58 |
+
h=configured();old=h.debug_snapshot();h.read();h.describe();h.invoke('separation.measure');h.invoke('product.read');self.assertEqual(old,h.debug_snapshot())
|
| 59 |
+
for dt in [True,-1,float('nan'),4000]:
|
| 60 |
+
with self.assertRaises(ActionRejected):h.step(dt)
|
| 61 |
+
with self.assertRaises(ActionRejected):h.invoke('panel.select',mode='invalid')
|
| 62 |
+
self.assertEqual(old,h.debug_snapshot())
|
| 63 |
+
def test_14_protocol_identity_async(self):
|
| 64 |
+
h=configured();h.register_principal('e','evaluator');a=h.session();e=h.session('e');self.assertNotIn('truth.initial_solute_kg',a.read(instance_id=h.instance_id)['observations']);self.assertNotIn('sample.configure',a.describe(instance_id=h.instance_id)['capabilities']);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='separation.measure',arguments={},request_id='one')['error']['code'],'REQUEST_CONFLICT')
|
| 65 |
+
with self.assertRaises(ActionRejected):e.poll(r['operation_id'])
|
| 66 |
+
h.step(200);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');self.ledger(h)
|
| 67 |
+
def test_15_instances_timeout(self):
|
| 68 |
+
a=finish(configured(method={'duration_s':10.,'timeout_s':10.}));b=configured();self.assertEqual(a.fault,'TIMEOUT');self.assertEqual(b.phase,'idle');self.assertEqual(b.processed_s,0.);self.ledger(a)
|
| 69 |
+
def test_16_release_retains_holdup(self):
|
| 70 |
+
h=finish(configured());mass=h.mass.copy();vol=h.vol.copy();h.invoke('pressure.release');h.step(100);self.assertEqual(h.phase,'succeeded');self.assertEqual(h.bpr,0.);np.testing.assert_array_equal(h.mass,mass);np.testing.assert_array_equal(h.vol,vol);self.ledger(h)
|
| 71 |
+
def test_17_single_panel_modes(self):
|
| 72 |
+
h=finish(configured());self.assertEqual(h.read()['panel.value'],100.);h.invoke('panel.select',mode='bpr');self.assertEqual(h.read()['panel.value'],2.);self.assertEqual(h.read()['pressure.organic_gauge_pa'],190000.)
|
| 73 |
+
def test_18_targets_not_instant_pressure(self):
|
| 74 |
+
h=configured();self.assertEqual(h.bpr,0.);self.assertEqual(h.cmp,0.);self.assertEqual(h.processed_s,0.);self.assertEqual(h.mass[2],0.)
|
| 75 |
+
def test_19_step_convergence(self):
|
| 76 |
+
a=finish(configured(),.25);b=finish(configured(),.1);np.testing.assert_allclose(a.mass,b.mass,rtol=1e-9,atol=1e-16);np.testing.assert_allclose(a.vol,b.vol,rtol=1e-9,atol=1e-16);self.ledger(a);self.ledger(b)
|
| 77 |
+
def test_20_membrane_and_phase_preconditions(self):
|
| 78 |
+
h=SyrrisAsiaFllexRuntime();old=h.debug_snapshot()
|
| 79 |
+
with self.assertRaises(ActionRejected):h.invoke('plant.configure',**dict(EXAMPLE,pre_equilibrated_immiscible_phases=False))
|
| 80 |
+
self.assertEqual(old,h.debug_snapshot());h.invoke('plant.configure',**EXAMPLE);old=h.debug_snapshot()
|
| 81 |
+
with self.assertRaises(ActionRejected):h.invoke('membrane.configure',**MEMBRANE_EXAMPLE)
|
| 82 |
+
self.assertEqual(old,h.debug_snapshot())
|
| 83 |
+
def test_21_native_cancellation_owner(self):
|
| 84 |
+
h=configured();a=h.session();r=a.invoke(instance_id=h.instance_id,capability_id='acquisition.start',arguments={},request_id='start');h.step(50);mass=h.mass.copy();a.cancel(r['operation_id'],'cancel');self.assertEqual(a.poll(r['operation_id'])['status'],'cancelled');h.step(5);np.testing.assert_array_equal(mass,h.mass);self.ledger(h)
|
| 85 |
+
if __name__=='__main__':unittest.main()
|
tests/test_asset_thalesnano_hcube.py
ADDED
|
@@ -0,0 +1,94 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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'));sys.path.insert(0,str(ROOT/'skills/chemistry-lab-assets/scripts'))
|
| 4 |
+
import asset_tool
|
| 5 |
+
from asset_runtime.thalesnano_hcube import *
|
| 6 |
+
def prepared(method=None,kinetics=None,**plant):
|
| 7 |
+
h=ThalesnanoHcubeRuntime();h.invoke('clamp.set_lift',lift_m=.05)
|
| 8 |
+
if method:h.invoke('method.configure',**method)
|
| 9 |
+
h.invoke('plant.configure',**dict(EXAMPLE,**plant));h.invoke('kinetics.configure',**dict(KINETIC_EXAMPLE,**(kinetics or {})));h.invoke('clamp.set_lift',lift_m=0.);h.invoke('water_lid.set_lift',lift_m=.03);h.invoke('water.fill',volume_m3=100e-6,conductivity_s_m=1e-6);h.invoke('water_lid.set_lift',lift_m=0.);h.invoke('inlet.set',route='sample');h.invoke('outlet.set',route='product');h.invoke('power.set',enabled=True);return h
|
| 10 |
+
class HCubeTest(unittest.TestCase):
|
| 11 |
+
def balance(self,h):
|
| 12 |
+
v=h.read('evaluator');self.assertAlmostEqual(v['truth.input_mass_kg'],sum(v['truth.'+k+'_mass_kg'] for k in ['retained','product','waste','removed','vent']),11);self.assertAlmostEqual(h.initial_a,h._species(0)+h._species(1),12);self.assertAlmostEqual(h.h2_generated,h._species(2)+h.h2_reacted+h.h2_vented,12);self.assertAlmostEqual(h.h2_generated/2,h.o2_vented,12);self.assertAlmostEqual(h.water_input_kg,h.water_kg+h.h2_generated*MW,12)
|
| 13 |
+
for c in h.cells:self.assertGreaterEqual(min(c),-1e-16)
|
| 14 |
+
def test_contract_schemas(self):
|
| 15 |
+
m=export_thalesnano_hcube_contract_metadata();self.assertEqual(len(m['capabilities']),17);self.assertEqual(len(m['state_slots']),41)
|
| 16 |
+
for c in m['capabilities'].values():
|
| 17 |
+
self.assertFalse(asset_tool.lint_schema(c['input_schema']));self.assertFalse(asset_tool.lint_schema(c['output_schema']));self.assertFalse(asset_tool.validate_value(c['example_arguments'],c['input_schema']))
|
| 18 |
+
def test_all_78_real_templates_drive_query(self):
|
| 19 |
+
h=ThalesnanoHcubeRuntime();self.assertEqual(len(h.templates),78);self.assertEqual(len({t['cas'] for t in h.templates.values()}),78)
|
| 20 |
+
for t in h.templates.values():
|
| 21 |
+
for f in t['fits']:
|
| 22 |
+
temp=sum(f['runtime_temperature_range_k'])/2;r=h.invoke('thermo.lookup',substance_id=t['substance_id'],fit_id=f['fit_id'],temperature_k=temp);p=1e5*10**(f['A']-f['B_k']/(temp+f['C_k']));self.assertAlmostEqual(r['vapor_pressure_pa']/p,1.,12);self.assertFalse(asset_tool.validate_value(r,CAPS['thermo.lookup'][1]))
|
| 23 |
+
def test_mass_water_hydrogen_substrate_conservation(self):
|
| 24 |
+
h=prepared();h.invoke('acquisition.start')
|
| 25 |
+
for _ in range(24):h.step(.19);self.balance(h)
|
| 26 |
+
self.assertEqual(h.phase,'succeeded');self.assertAlmostEqual(h.product[0],2*MLMIN*4,13);self.assertGreater(h._species(1),0);self.assertGreater(h.h2_vented,0);self.assertLess(h.activity,1)
|
| 27 |
+
h.invoke('collector.unload',container_id='product_01');self.assertEqual(h.product[0],0);self.assertGreater(h.removed[0],0);self.balance(h)
|
| 28 |
+
def test_zero_hydrogen_no_reaction(self):
|
| 29 |
+
h=prepared(method=dict(METHOD_EXAMPLE,hydrogen_reference_flow_m3_s=0.));h.invoke('acquisition.start');h.step(4.);self.assertEqual(h.h2_generated,0);self.assertEqual(h._species(1),0);self.balance(h)
|
| 30 |
+
def test_zero_transfer_and_zero_catalyst(self):
|
| 31 |
+
for kwargs in [dict(kla_s_inv=0.),dict(kinetics={'initial_activity':0.})]:
|
| 32 |
+
h=prepared(**kwargs);h.invoke('acquisition.start');h.step(4.);self.assertEqual(h._species(1),0);self.assertGreater(h.h2_generated,0);self.balance(h)
|
| 33 |
+
def test_ergun_pressure_loss_and_limit(self):
|
| 34 |
+
h=prepared();self.assertGreater(h.dp(),0);h.invoke('acquisition.start');h.step(.02);self.assertAlmostEqual(h.pressure,4e6+h.dp(),5);self.balance(h);h.invoke('acquisition.stop');h.invoke('method.configure',**dict(METHOD_EXAMPLE,pressure_abs_pa=1e7));old=h.debug_snapshot()
|
| 35 |
+
with self.assertRaises(ActionRejected):h.invoke('acquisition.start')
|
| 36 |
+
self.assertEqual(old,h.debug_snapshot())
|
| 37 |
+
def test_bed_sizes_holdup_distinct_from_empty_volume(self):
|
| 38 |
+
for size,(empty,length) in CARTS.items():
|
| 39 |
+
h=prepared(cartridge_size=size);self.assertAlmostEqual(sum(h.volumes[1:5]),empty*.4,15);self.assertLess(sum(h.volumes[1:5]),empty);h.invoke('acquisition.start');h.step(.1);self.balance(h)
|
| 40 |
+
def test_catalyst_decay_analytical_and_thermal(self):
|
| 41 |
+
h=prepared();h.invoke('method.configure',**dict(METHOD_EXAMPLE,temperature_k=323.15));h.step(2);self.assertAlmostEqual(h.activity,math.exp(-.002),12);self.assertAlmostEqual(h.temp_k,323.15-10*math.exp(-.2),10);h.invoke('power.set',enabled=False);old=h.temp_k;h.step(1);self.assertEqual(h.temp_k,old)
|
| 42 |
+
def test_routing_and_feed_wash(self):
|
| 43 |
+
h=prepared();h.invoke('acquisition.start');h.step(1);h.invoke('outlet.set',route='waste');h.invoke('inlet.set',route='solvent');old=h.feed;h.step(2);self.assertEqual(h.feed,old);self.assertAlmostEqual(h.product[0],2*MLMIN,13);self.assertAlmostEqual(h.waste[0],4*MLMIN,13);self.balance(h)
|
| 44 |
+
def test_cancel_retains_inventory_and_residual_reaction(self):
|
| 45 |
+
h=prepared();h.invoke('acquisition.start');h.step(2);a=h._species(0);b=h._species(1);v=h.product[0];h.invoke('acquisition.stop');h.step(.5);self.assertEqual(h.product[0],v);self.assertLessEqual(h._species(0),a);self.assertGreaterEqual(h._species(1),b);self.assertEqual(h.pressure,PN);self.balance(h);h.invoke('acquisition.start');h.step(.2);h.invoke('power.set',enabled=False);self.assertEqual(h.phase,'cancelled');self.balance(h)
|
| 46 |
+
def test_water_capacity_quality_and_fault(self):
|
| 47 |
+
h=prepared();h.invoke('water_lid.set_lift',lift_m=.03);old=copy.deepcopy(h.__dict__)
|
| 48 |
+
for args in [dict(volume_m3=201e-6,conductivity_s_m=1e-6),dict(volume_m3=1e-6,conductivity_s_m=1e-3)]:
|
| 49 |
+
with self.assertRaises(ActionRejected):h.invoke('water.fill',**args)
|
| 50 |
+
self.assertEqual(old,h.__dict__)
|
| 51 |
+
h.invoke('water_lid.set_lift',lift_m=0.);h.water_kg=1e-10;h.water_input_kg=1e-10;h.invoke('acquisition.start');h.step(.1);self.assertEqual(h.fault,'water_empty');self.balance(h)
|
| 52 |
+
def test_external_pump_and_known_carrier_bans(self):
|
| 53 |
+
for args in [dict(external_pump_connected=False),dict(materials_and_recipe_reviewed=False),dict(solvent_id='acetonitrile'),dict(solvent_id='toluene'),dict(solvent_id='cyclohexane'),dict(solvent_id='dichloromethane'),dict(solvent_id='ethyl_acetate')]:
|
| 54 |
+
h=ThalesnanoHcubeRuntime();h.invoke('clamp.set_lift',lift_m=.05);old=h.debug_snapshot()
|
| 55 |
+
with self.assertRaises(ActionRejected):h.invoke('plant.configure',**dict(EXAMPLE,**args))
|
| 56 |
+
self.assertEqual(old,h.debug_snapshot())
|
| 57 |
+
def test_interlocks_and_atomic_rejection(self):
|
| 58 |
+
h=prepared();old=copy.deepcopy(h.__dict__)
|
| 59 |
+
for cap,args in [('clamp.set_lift',{'lift_m':True}),('method.configure',dict(METHOD_EXAMPLE,pressure_abs_pa=float('nan'))),('method.configure',dict(METHOD_EXAMPLE,temperature_k=423.15)),('kinetics.configure',KINETIC_EXAMPLE)]:
|
| 60 |
+
with self.assertRaises(ActionRejected):h.invoke(cap,**args)
|
| 61 |
+
self.assertEqual(old,h.__dict__)
|
| 62 |
+
h.invoke('acquisition.start')
|
| 63 |
+
for cap,args in [('clamp.set_lift',{'lift_m':.05}),('water_lid.set_lift',{'lift_m':.03})]:
|
| 64 |
+
with self.assertRaises(ActionRejected):h.invoke(cap,**args)
|
| 65 |
+
h.step(.1);h.invoke('acquisition.stop')
|
| 66 |
+
with self.assertRaises(ActionRejected):h.invoke('clamp.set_lift',lift_m=.05)
|
| 67 |
+
h.step(.1);h.invoke('clamp.set_lift',lift_m=.05)
|
| 68 |
+
def test_three_measured_reference_points_not_instance_yield(self):
|
| 69 |
+
h=prepared()
|
| 70 |
+
for q,x in [(1,1.),(2,.73),(3,.4)]:
|
| 71 |
+
r=h.invoke('calibration.reference',liquid_flow_m3_s=q*MLMIN);self.assertEqual(r['reported_conversion_fraction'],x);self.assertIn('不自动标定',r['conditions_zh'])
|
| 72 |
+
self.assertIsNone(h.invoke('hydrogenation.measure')['real_conversion_fraction'])
|
| 73 |
+
with self.assertRaises(ActionRejected):h.invoke('calibration.reference',liquid_flow_m3_s=1.5*MLMIN)
|
| 74 |
+
def test_reads_pure_and_unknown_yield(self):
|
| 75 |
+
h=prepared();h.invoke('acquisition.start');h.step(.2);old=copy.deepcopy(h.__dict__)
|
| 76 |
+
for _ in range(3):h.read();h.describe();h.invoke('hydrogenation.measure');h.invoke('history.read');h.invoke('product.read')
|
| 77 |
+
self.assertEqual(old,h.__dict__);self.assertIsNone(h.invoke('hydrogenation.measure')['isolated_yield_fraction'])
|
| 78 |
+
def test_session_identity_filter_dedup_async(self):
|
| 79 |
+
h=prepared();b=ThalesnanoHcubeRuntime('other');s=h.session();args=dict(instance_id=h.instance_id,capability_id='acquisition.start',arguments={},request_id='start');r=s.invoke(**args);self.assertEqual(r['status'],'accepted');self.assertEqual(s.invoke(**args),r);h.step(.2);self.assertEqual(s.poll(r['operation_id'])['status'],'running');self.assertNotIn('truth.cells',s.read(instance_id=h.instance_id)['observations']);self.assertNotIn('product.read',s.describe(instance_id=h.instance_id)['capabilities']);self.assertFalse(b.powered);self.assertEqual(s.invoke(instance_id=h.instance_id,capability_id='product.read',arguments={},request_id='deny')['error']['code'],'ACCESS_DENIED');h.register_principal('second');other=h.session('second')
|
| 80 |
+
with self.assertRaises(ActionRejected):other.poll(r['operation_id'])
|
| 81 |
+
self.assertEqual(s.cancel(r['operation_id'],'cancel')['status'],'cancelled');self.balance(h);self.assertEqual(s.write(instance_id=h.instance_id,state_id='inlet.route',value='solvent',request_id='wash')['status'],'succeeded')
|
| 82 |
+
def test_all_actual_outputs_and_slots_schema(self):
|
| 83 |
+
h=ThalesnanoHcubeRuntime()
|
| 84 |
+
def ck(k,a=None):
|
| 85 |
+
r=h.invoke(k,**(CAPS[k][6] if a is None else a));self.assertFalse(asset_tool.validate_value(r,CAPS[k][1]),k)
|
| 86 |
+
for k in ['clamp.set_lift','plant.configure','kinetics.configure','water_lid.set_lift','water.fill','power.set','method.configure','inlet.set','outlet.set']:ck(k)
|
| 87 |
+
ck('clamp.set_lift',{'lift_m':0.});ck('water_lid.set_lift',{'lift_m':0.});ck('acquisition.start');h.step(1.)
|
| 88 |
+
for k in ['hydrogenation.measure','history.read','product.read','thermo.lookup','calibration.reference','acquisition.stop','collector.unload']:ck(k)
|
| 89 |
+
for k,v in h.read('evaluator').items():self.assertFalse(asset_tool.validate_value(v,SLOTS[k][0]),k)
|
| 90 |
+
def test_bad_dt(self):
|
| 91 |
+
h=prepared()
|
| 92 |
+
for dt in [0,-1,True,float('nan'),float('inf')]:
|
| 93 |
+
with self.assertRaises(ValueError):h.step(dt)
|
| 94 |
+
if __name__=='__main__':unittest.main()
|
tests/test_asset_tousimis_autosamdri815.py
ADDED
|
@@ -0,0 +1,83 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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.tousimis_autosamdri815 import *
|
| 5 |
+
def ready(plant=None,sample=None,method=None):
|
| 6 |
+
h=TousimisAutosamdri815Runtime();p=copy.deepcopy(EXAMPLE);p.update(plant or {});s=copy.deepcopy(SAMPLE_EXAMPLE);s.update(sample or {});m=copy.deepcopy(METHOD_EXAMPLE);m.update(method or {})
|
| 7 |
+
h.invoke('plant.configure',**p);h.invoke('lid.set_lift',lift_m=.065);h.invoke('holder.set_lift',lift_m=.035);h.invoke('sample.configure',**s);h.invoke('holder.set_lift',lift_m=0.);h.invoke('lid.set_lift',lift_m=0.);h.invoke('method.configure',**m);h.invoke('power.set',enabled=True);return h
|
| 8 |
+
class CriticalDryingTests(unittest.TestCase):
|
| 9 |
+
def balance(self,h):
|
| 10 |
+
v=h._inventory();self.assertAlmostEqual(v['initial_co2'],sum(v[k] for k in ['tank_co2','chamber_co2','exhaust_co2']),places=10);self.assertAlmostEqual(v['initial_solvent'],sum(v[k] for k in ['bath_solvent','pore_solvent','exhaust_solvent','removed_solvent']),places=12);self.assertAlmostEqual(v['initial_solid'],v['retained_solid']+v['removed_solid'],places=12)
|
| 11 |
+
self.assertTrue(all(x>=-1e-12 for x in v.values()));self.assertTrue(0<=h.retention<=1)
|
| 12 |
+
def test_01_all59_real_correlations_not_measured_retention(self):
|
| 13 |
+
h=TousimisAutosamdri815Runtime();self.assertEqual(len(h.templates),59);self.assertEqual(len({t['cas'] for t in h.templates.values()}),59)
|
| 14 |
+
for sid,t in h.templates.items():
|
| 15 |
+
r=h.invoke('reference.lookup',substance_id=sid,temperature_k=298.15);validate(REFERENCE,r);self.assertAlmostEqual(r['surface_tension_n_m'],t['values']['surface_tension_n_m'],places=12);self.assertIn('derived',r['evidence']);self.assertFalse(r['fit_range_verified']);self.assertIsNone(t['structure_retention_fraction'])
|
| 16 |
+
self.assertFalse(h.invoke('reference.lookup',substance_id='water',temperature_k=298.15)['cpd_solvent_supported'])
|
| 17 |
+
def test_02_reference_range_and_finite_inputs(self):
|
| 18 |
+
h=ready();before=h.debug_snapshot()
|
| 19 |
+
for sid,t in [('unknown',298.15),('carbondioxide',310.),('water',250.),('methanol',513.),('ethanol',math.nan)]:
|
| 20 |
+
with self.assertRaises(ActionRejected):h.invoke('reference.lookup',substance_id=sid,temperature_k=t)
|
| 21 |
+
for dt in [0,-1,True,math.inf,math.nan,7201]:
|
| 22 |
+
with self.assertRaises(ValueError):h.step(dt)
|
| 23 |
+
self.assertEqual(before,h.debug_snapshot())
|
| 24 |
+
def test_03_pure_CO2_phase_and_abs_pressure(self):
|
| 25 |
+
# Rounded published critical pressure versus numerical EOS critical solution (1.63 Pa).
|
| 26 |
+
self.assertAlmostEqual(cp().PropsSI('Tcrit','CO2'),TC,places=4);self.assertAlmostEqual(cp().PropsSI('pcrit','CO2'),PC,delta=2.)
|
| 27 |
+
p,phase,q=co2_state(273.15,500.);self.assertEqual(phase,'twophase');self.assertTrue(0<q<1);self.assertAlmostEqual(p,3485140.,delta=200.)
|
| 28 |
+
p,phase,q=co2_state(309.15,700.);self.assertGreater(p,PC);self.assertEqual(phase,'supercritical');self.assertIsNone(q)
|
| 29 |
+
def test_04_rejected_plant_and_sample_do_not_mutate(self):
|
| 30 |
+
h=TousimisAutosamdri815Runtime();before=h.debug_snapshot()
|
| 31 |
+
for a in [dict(EXAMPLE,dip_tube_liquid_confirmed=False),dict(EXAMPLE,fill_m3_s=EXAMPLE['purge_m3_s']),dict(EXAMPLE,supply_gauge_pa=1500*PSI),dict(EXAMPLE,pressure_guard_gauge_pa=2000*PSI)]:
|
| 32 |
+
with self.assertRaises(ActionRejected):h.invoke('plant.configure',**a)
|
| 33 |
+
self.assertEqual(before,h.debug_snapshot())
|
| 34 |
+
h.invoke('plant.configure',**EXAMPLE);h.invoke('lid.set_lift',lift_m=.065);h.invoke('holder.set_lift',lift_m=.035);before=h.debug_snapshot()
|
| 35 |
+
for a in [dict(SAMPLE_EXAMPLE,water_replaced_confirmed=False),dict(SAMPLE_EXAMPLE,bath_volume_m3=20e-6,pore_volume_m3=10e-6),dict(SAMPLE_EXAMPLE,solvent_id='water')]:
|
| 36 |
+
with self.assertRaises(ActionRejected):h.invoke('sample.configure',**a)
|
| 37 |
+
self.assertEqual(before,h.debug_snapshot())
|
| 38 |
+
def test_05_setting_and_read_do_not_advance(self):
|
| 39 |
+
h=ready();t=h.time_s;h.invoke('method.configure',purge_time_s=300.,bleed_rate_pa_s=100*PSI/60)
|
| 40 |
+
for _ in range(10):h.describe();h.read();h.invoke('cpd.measure')
|
| 41 |
+
self.assertEqual(h.time_s,t);self.assertEqual(h.temperature,EXAMPLE['ambient_k']);self.assertEqual(h.method['purge_time_s'],300.)
|
| 42 |
+
def test_06_full_cycle_real_timers_and_conservation(self):
|
| 43 |
+
h=ready();h.invoke('acquisition.start');h.step(2100);self.assertEqual(h.phase,'succeeded');self.assertTrue(h.controller_pass);self.balance(h);r=h.invoke('product.read');validate(PRODUCT,r);self.assertTrue(r['dry_within_host_threshold']);self.assertIsNone(r['measured_structure_retention']);self.assertIn('synthetic',r['evidence'])
|
| 44 |
+
stages={}
|
| 45 |
+
for row in h.history:stages.setdefault(row['stage'],row['time_s'])
|
| 46 |
+
for stage in ['warmup','cool','fill','purge','postfill','heat','equilibrium','bleed','vent','complete']:self.assertIn(stage,stages)
|
| 47 |
+
for a,b,want in [('fill','purge',120),('purge','postfill',600),('postfill','heat',120),('equilibrium','bleed',240),('vent','complete',180)]:self.assertAlmostEqual(stages[b]-stages[a],want,delta=.21)
|
| 48 |
+
self.assertLess(h.pressure-h._ambient(),50);self.assertGreater(h.co2_out,0);self.assertGreater(h.solvent_out,0)
|
| 49 |
+
def test_07_zero_purge_is_not_guaranteed_clean(self):
|
| 50 |
+
h=ready(method={'purge_time_s':0.});h.invoke('acquisition.start');h.step(700);self.assertEqual(h.phase,'failed');self.assertEqual(h.fault,'insufficient_solvent_exchange');self.assertFalse(h._product()['dry_within_host_threshold']);self.balance(h)
|
| 51 |
+
def test_08_finite_supply_failure(self):
|
| 52 |
+
h=ready(plant={'tank_mass_kg':.001});h.invoke('acquisition.start');h.step(300);self.assertEqual(h.phase,'failed');self.assertEqual(h.fault,'co2_supply_empty');self.balance(h)
|
| 53 |
+
def test_09_cancel_keeps_pressure_and_thermal_evolution(self):
|
| 54 |
+
h=ready();h.invoke('acquisition.start');h.step(350);h.invoke('acquisition.stop');m=h.mco2;b=h.bath;stage=h.stage;t=h.temperature;h.step(10);self.assertEqual(h.mco2,m);self.assertEqual(h.bath,b);self.assertEqual(h.stage,stage);self.assertGreater(h.temperature,t);self.assertGreater(h.pressure-h._ambient(),50);self.balance(h)
|
| 55 |
+
before=h.debug_snapshot()
|
| 56 |
+
with self.assertRaises(ActionRejected):h.invoke('lid.set_lift',lift_m=.065)
|
| 57 |
+
self.assertEqual(before,h.debug_snapshot())
|
| 58 |
+
def test_10_resume_does_not_reset_material(self):
|
| 59 |
+
h=ready();h.invoke('acquisition.start');h.step(400);h.invoke('acquisition.stop');v=h.solvent_out;h.step(.2);h.invoke('acquisition.start');self.assertEqual(h.solvent_out,v);h.step(1800);self.assertEqual(h.phase,'succeeded');self.balance(h)
|
| 60 |
+
def test_11_open_unload_only_after_depressurized(self):
|
| 61 |
+
h=ready();h.invoke('acquisition.start');h.step(2100)
|
| 62 |
+
with self.assertRaises(ActionRejected):h.invoke('sample.unload',sample_id='wet_die_1')
|
| 63 |
+
h.invoke('lid.set_lift',lift_m=.065);h.invoke('holder.set_lift',lift_m=.035);h.invoke('sample.unload',sample_id='wet_die_1');self.balance(h)
|
| 64 |
+
with self.assertRaises(ActionRejected):h.invoke('sample.unload',sample_id='wet_die_1')
|
| 65 |
+
def test_12_condition_structure_model_responds_to_strength(self):
|
| 66 |
+
a=ready(sample={'yield_stress_pa':1e5,'damage_rate_s_inv':.01});b=ready(sample={'yield_stress_pa':1e8,'damage_rate_s_inv':.01})
|
| 67 |
+
for h in (a,b):h.invoke('acquisition.start');h.step(2100);self.balance(h)
|
| 68 |
+
self.assertLess(a.retention,b.retention);self.assertLess(a.retention,.99);self.assertEqual(b.retention,1.)
|
| 69 |
+
def test_13_safety_guard_is_not_gauge_range(self):
|
| 70 |
+
h=ready(plant={'pressure_guard_gauge_pa':1250*PSI});h.invoke('acquisition.start');h.step(1200);self.assertEqual(h.phase,'failed');self.assertEqual(h.fault,'host_pressure_guard');self.balance(h)
|
| 71 |
+
low=ready(plant={'fill_m3_s':1.1e-9,'purge_m3_s':1e-9});low.invoke('acquisition.start');low.step(1200);self.assertEqual(low.phase,'failed');self.assertEqual(low.fault,'critical_signal_order_failure');self.assertFalse(low.controller_pass);self.balance(low)
|
| 72 |
+
def test_14_session_ownership_idempotency_visibility(self):
|
| 73 |
+
h=ready();h.register_principal('a');h.register_principal('b');h.register_principal('judge','evaluator');a=h.session('a');b=h.session('b');args=dict(instance_id=h.instance_id,capability_id='acquisition.start',arguments={},request_id='start');r=a.invoke(**args);self.assertEqual(r['status'],'accepted');self.assertEqual(a.invoke(**args),r)
|
| 74 |
+
with self.assertRaises(ActionRejected):b.poll(r['operation_id'])
|
| 75 |
+
h.step(200);a.cancel(r['operation_id'],'cancel');self.assertEqual(a.poll(r['operation_id'])['status'],'cancelled');self.assertEqual(a.invoke(instance_id=h.instance_id,capability_id='cpd.measure',arguments={},request_id='start')['status'],'rejected');self.assertFalse(any(k.startswith('truth.') for k in a.read(instance_id=h.instance_id)['observations']));self.assertEqual(a.invoke(instance_id=h.instance_id,capability_id='product.read',arguments={},request_id='p')['status'],'rejected')
|
| 76 |
+
def test_15_instance_schema_isolation_and_partition(self):
|
| 77 |
+
a=ready();b=ready();a.invoke('acquisition.start');a.step(250);self.assertEqual(b.phase,'idle');self.assertEqual(b.mco2,0);meta=export_tousimis_autosamdri815_contract_metadata();self.assertEqual(set(meta['state_slots']),set(a.read('evaluator')))
|
| 78 |
+
for key,v in a.read('evaluator').items():validate(SLOTS[key][0],v)
|
| 79 |
+
for cap in ['cpd.measure','product.read','history.read']:validate(CAPS[cap][1],a.invoke(cap))
|
| 80 |
+
b.invoke('acquisition.start')
|
| 81 |
+
for _ in range(25):b.step(10)
|
| 82 |
+
self.assertAlmostEqual(a.mco2,b.mco2,places=10);self.assertAlmostEqual(a.temperature,b.temperature,places=9)
|
| 83 |
+
if __name__=='__main__':unittest.main()
|
tests/test_balance_runtime.py
ADDED
|
@@ -0,0 +1,47 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import unittest, math, sys
|
| 2 |
+
from pathlib import Path
|
| 3 |
+
sys.path.insert(0,str(Path(__file__).resolve().parents[1]/'scripts'))
|
| 4 |
+
from balance_runtime import Balance, foot_extension_m
|
| 5 |
+
|
| 6 |
+
class RuntimeTest(unittest.TestCase):
|
| 7 |
+
def settled(self,b,m):
|
| 8 |
+
b.update(m*b.g_cal,0)
|
| 9 |
+
return b.update(m*b.g_cal,b.settling_s+.01)
|
| 10 |
+
def test_tare_sample_and_negative_after_removal(self):
|
| 11 |
+
b=Balance.for_model('PX224E'); b.press('zero')
|
| 12 |
+
self.settled(b,.02); b.press('tare')
|
| 13 |
+
self.assertAlmostEqual(self.settled(b,.0212345)['net_kg'],.0012345,places=8)
|
| 14 |
+
self.assertAlmostEqual(self.settled(b,0)['net_kg'],-.02)
|
| 15 |
+
def test_overload_uses_gross_even_after_tare(self):
|
| 16 |
+
b=Balance.for_model('PX224E'); b.press('zero'); self.settled(b,.20); b.press('tare')
|
| 17 |
+
self.assertEqual(self.settled(b,.221)['status'],'OVERLOAD')
|
| 18 |
+
def test_door_invalidates_stability_without_making_mass_zero(self):
|
| 19 |
+
b=Balance.for_model('PX224E'); b.press('zero'); self.settled(b,.01)
|
| 20 |
+
r=b.update(.01*b.g_cal,4,door_fraction=.5)
|
| 21 |
+
self.assertEqual(r['status'],'UNSTABLE'); self.assertAlmostEqual(r['net_kg'],.01)
|
| 22 |
+
def test_transport_lock_and_bayonet_access(self):
|
| 23 |
+
b=Balance.for_model('SPX2201')
|
| 24 |
+
with self.assertRaises(ValueError): b.set_transport_lock(0)
|
| 25 |
+
with self.assertRaises(ValueError): b.remove_pan(0)
|
| 26 |
+
b.remove_pan(-math.radians(20)); b.set_transport_lock(0); b.install_pan(); b.press('zero')
|
| 27 |
+
self.assertEqual(self.settled(b,.1)['status'],'TRANSPORT_LOCKED')
|
| 28 |
+
def test_closing_door_requires_resettling(self):
|
| 29 |
+
b=Balance.for_model('PX224E'); b.press('zero'); self.settled(b,.01)
|
| 30 |
+
b.update(.01*b.g_cal,10,door_fraction=1)
|
| 31 |
+
self.assertEqual(b.update(.01*b.g_cal,4,door_fraction=0)['status'],'UNSTABLE')
|
| 32 |
+
self.assertEqual(b.update(.01*b.g_cal,3.1,door_fraction=0)['status'],'STABLE')
|
| 33 |
+
def test_quantization_and_units(self):
|
| 34 |
+
b=Balance.for_model('SPX2201'); b.press('zero')
|
| 35 |
+
self.assertAlmostEqual(self.settled(b,.01236)['value'],12.4)
|
| 36 |
+
b.press('print',3); self.assertAlmostEqual(b.read()['value'],.0124)
|
| 37 |
+
def test_foot_coupling(self):
|
| 38 |
+
self.assertAlmostEqual(foot_extension_m(2*math.pi),.001)
|
| 39 |
+
def test_unstable_tare_rejected(self):
|
| 40 |
+
b=Balance.for_model('PX224E'); b.press('zero')
|
| 41 |
+
with self.assertRaises(ValueError): b.press('tare')
|
| 42 |
+
def test_calibration_gate(self):
|
| 43 |
+
b=Balance.for_model('SPX2201'); b.press('zero'); self.settled(b,1)
|
| 44 |
+
self.assertFalse(b.read()['task_ready']); b.calibrate_span(1,9.81)
|
| 45 |
+
self.assertTrue(self.settled(b,1)['task_ready'])
|
| 46 |
+
|
| 47 |
+
if __name__=='__main__': unittest.main()
|
tests/test_basic40_analytical.py
ADDED
|
The diff for this file is too large to render.
See raw diff
|
|
|
tests/test_basic40_automation.py
ADDED
|
The diff for this file is too large to render.
See raw diff
|
|
|
tests/test_basic40_measure.py
ADDED
|
The diff for this file is too large to render.
See raw diff
|
|
|
tests/test_basic40_runtime.py
ADDED
|
@@ -0,0 +1,483 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Deterministic synthetic process/API tests; no real sample data or hardware."""
|
| 2 |
+
import copy
|
| 3 |
+
import math
|
| 4 |
+
from pathlib import Path
|
| 5 |
+
import sys
|
| 6 |
+
import unittest
|
| 7 |
+
|
| 8 |
+
ROOT = Path(__file__).resolve().parents[1]
|
| 9 |
+
sys.path.insert(0, str(ROOT / "scripts"))
|
| 10 |
+
sys.path.insert(0, str(ROOT / "skills" / "chemistry-lab-assets" / "scripts"))
|
| 11 |
+
from basic40_runtime import (ASSET_SPECS, LabHost, RPM_TO_RAD_S,
|
| 12 |
+
SceneSynchronizationError, export_contract_metadata)
|
| 13 |
+
from asset_tool import lint_schema, validate_value
|
| 14 |
+
|
| 15 |
+
TYPES = {"hotplate": "instrument.ika_rct_digital", "oven": "instrument.binder_fd56",
|
| 16 |
+
"pump": "instrument.ne1000_bd10ml", "hood": "instrument.esco_efa5"}
|
| 17 |
+
|
| 18 |
+
|
| 19 |
+
class Basic40RuntimeTests(unittest.TestCase):
|
| 20 |
+
def setUp(self):
|
| 21 |
+
self.scene_calls = []
|
| 22 |
+
self.host = LabHost(scene_adapter=lambda instance, updates: self.scene_calls.append((instance, copy.deepcopy(updates))))
|
| 23 |
+
for instance, type_id in TYPES.items():
|
| 24 |
+
self.host.create_instance(instance, type_id)
|
| 25 |
+
self.host.register_principal("learner", visibility="agent")
|
| 26 |
+
self.host.register_principal("judge", visibility="evaluator")
|
| 27 |
+
self.agent = self.host.session("learner")
|
| 28 |
+
self.judge = self.host.session("judge")
|
| 29 |
+
self.request_counter = 0
|
| 30 |
+
|
| 31 |
+
def invoke(self, instance, capability, **arguments):
|
| 32 |
+
self.request_counter += 1
|
| 33 |
+
return self.agent.invoke(instance_id=instance, capability_id=capability,
|
| 34 |
+
arguments=arguments, request_id=f"test_{self.request_counter}")
|
| 35 |
+
|
| 36 |
+
def ok(self, instance, capability, **arguments):
|
| 37 |
+
response = self.invoke(instance, capability, **arguments)
|
| 38 |
+
self.assertEqual(response["status"], "succeeded", response)
|
| 39 |
+
return response
|
| 40 |
+
|
| 41 |
+
def value(self, instance, state_id, *, debug=False):
|
| 42 |
+
session = self.judge if debug else self.agent
|
| 43 |
+
return session.read(instance_id=instance, state_ids=[state_id])["observations"][state_id]["value"]
|
| 44 |
+
|
| 45 |
+
def configure_pump(self, *, syringe_volume=5e-6, external_volume=0.0,
|
| 46 |
+
external_capacity=10e-6, syringe_capacity=10e-6):
|
| 47 |
+
spec = ASSET_SPECS[TYPES["pump"]]["parameters"]
|
| 48 |
+
self.host.configure_syringe("pump", diameter_m=spec["syringe_diameter_m"]["value"],
|
| 49 |
+
stroke_m=spec["syringe_stroke_m"]["value"], evidence="Synthetic nominal B-D 10 mL fixture from declared table geometry")
|
| 50 |
+
self.host.create_vessel("synthetic_syringe", volume_m3=syringe_volume, capacity_m3=syringe_capacity,
|
| 51 |
+
species_mass_kg={"synthetic_private_marker": syringe_volume * 1000})
|
| 52 |
+
self.host.create_vessel("synthetic_external", volume_m3=external_volume, capacity_m3=external_capacity,
|
| 53 |
+
species_mass_kg={"synthetic_other_marker": external_volume * 1000})
|
| 54 |
+
self.host.connect_pump("pump", "synthetic_syringe", "synthetic_external")
|
| 55 |
+
self.host.sync_scene(["pump"])
|
| 56 |
+
self.ok("pump", "power.set", enabled=True)
|
| 57 |
+
self.ok("pump", "pumping.set_flow_rate", flow_rate_m3_s=1e-8)
|
| 58 |
+
|
| 59 |
+
def totals(self):
|
| 60 |
+
vessels = self.host.debug_snapshot()["vessels"].values()
|
| 61 |
+
total_volume = sum(v["volume_m3"] for v in vessels)
|
| 62 |
+
masses = {}
|
| 63 |
+
for vessel in vessels:
|
| 64 |
+
for species, mass in vessel["species_mass_kg"].items():
|
| 65 |
+
masses[species] = masses.get(species, 0) + mass
|
| 66 |
+
return total_volume, masses
|
| 67 |
+
|
| 68 |
+
def assert_conserved(self, before):
|
| 69 |
+
after = self.totals()
|
| 70 |
+
self.assertAlmostEqual(before[0], after[0], delta=1e-18)
|
| 71 |
+
self.assertEqual(set(before[1]), set(after[1]))
|
| 72 |
+
for species in before[1]:
|
| 73 |
+
self.assertAlmostEqual(before[1][species], after[1][species], delta=1e-15)
|
| 74 |
+
|
| 75 |
+
def test_initial_scene_receives_all_slots_and_explicit_resync(self):
|
| 76 |
+
self.assertEqual(len(self.scene_calls), 4)
|
| 77 |
+
for instance, updates in self.scene_calls:
|
| 78 |
+
self.assertEqual(set(updates), set(ASSET_SPECS[TYPES[instance]]["state_slots"]))
|
| 79 |
+
self.configure_pump()
|
| 80 |
+
pump_update = [updates for instance, updates in self.scene_calls if instance == "pump"]
|
| 81 |
+
self.assertTrue(any(updates.get("pumping.plunger_displacement_m", 0) > 0 for updates in pump_update))
|
| 82 |
+
|
| 83 |
+
def test_read_is_pure_and_common_clock_has_one_authority(self):
|
| 84 |
+
self.ok("hotplate", "power.set", enabled=True)
|
| 85 |
+
self.ok("hotplate", "thermal.set_temperature", temperature_K=333.15)
|
| 86 |
+
before = self.host.debug_snapshot()
|
| 87 |
+
for _ in range(5):
|
| 88 |
+
for instance in TYPES:
|
| 89 |
+
self.agent.read(instance_id=instance)
|
| 90 |
+
self.agent.describe(instance_id=instance)
|
| 91 |
+
self.assertEqual(before, self.host.debug_snapshot())
|
| 92 |
+
self.host.step(2)
|
| 93 |
+
self.assertEqual(self.host.time_s, 2)
|
| 94 |
+
self.assertTrue(all(self.agent.read(instance_id=instance)["clock"]["time_s"] == 2 for instance in TYPES))
|
| 95 |
+
|
| 96 |
+
def test_two_instances_do_not_share_state(self):
|
| 97 |
+
self.host.create_instance("hotplate_b", TYPES["hotplate"])
|
| 98 |
+
self.ok("hotplate", "power.set", enabled=True)
|
| 99 |
+
self.ok("hotplate", "thermal.set_temperature", temperature_K=333.15)
|
| 100 |
+
self.ok("hotplate", "stirring.set_speed", speed_rad_s=300 * RPM_TO_RAD_S)
|
| 101 |
+
self.host.step(60)
|
| 102 |
+
self.assertFalse(self.value("hotplate_b", "power.enabled"))
|
| 103 |
+
self.assertEqual(self.value("hotplate_b", "thermal.temperature_k", debug=True), 293.15)
|
| 104 |
+
self.assertEqual(self.value("hotplate_b", "stirring.speed_rad_s", debug=True), 0)
|
| 105 |
+
self.assertGreater(self.value("hotplate", "thermal.temperature_k", debug=True), 293.15)
|
| 106 |
+
|
| 107 |
+
def test_dedup_replay_and_conflict_leave_asset_unchanged(self):
|
| 108 |
+
args = dict(instance_id="hotplate", capability_id="power.set", arguments={"enabled": True}, request_id="fixed")
|
| 109 |
+
response = self.agent.invoke(**args)
|
| 110 |
+
self.host.step(1)
|
| 111 |
+
before = self.host.debug_snapshot()
|
| 112 |
+
self.assertEqual(self.agent.invoke(**args), response)
|
| 113 |
+
self.assertEqual(before, self.host.debug_snapshot())
|
| 114 |
+
conflict = self.agent.invoke(**{**args, "arguments": {"enabled": False}})
|
| 115 |
+
self.assertEqual(conflict["error"]["code"], "REQUEST_CONFLICT")
|
| 116 |
+
self.assertEqual(before, self.host.debug_snapshot())
|
| 117 |
+
|
| 118 |
+
def test_request_identity_is_host_bound(self):
|
| 119 |
+
self.ok("hotplate", "power.set", enabled=True)
|
| 120 |
+
response = self.invoke("hotplate", "thermal.set_temperature", temperature_K=333.15, role="evaluator")
|
| 121 |
+
self.assertEqual(response["error"]["code"], "INVALID_ARGUMENT")
|
| 122 |
+
with self.assertRaises(TypeError):
|
| 123 |
+
self.agent.read(instance_id="hotplate", state_ids=["thermal.temperature_k"], role="evaluator")
|
| 124 |
+
with self.assertRaises(ValueError):
|
| 125 |
+
self.host.session("unregistered")
|
| 126 |
+
with self.assertRaises(ValueError):
|
| 127 |
+
self.host.register_principal("learner", visibility="evaluator")
|
| 128 |
+
|
| 129 |
+
def test_agent_truth_filter_covers_describe_read_errors_logs_and_results(self):
|
| 130 |
+
self.configure_pump()
|
| 131 |
+
self.ok("pump", "pumping.start")
|
| 132 |
+
self.host.step(1)
|
| 133 |
+
payloads = [self.agent.describe(instance_id="pump"), self.agent.read(instance_id="pump"), self.agent.logs()]
|
| 134 |
+
denied = self.agent.read(instance_id="pump", state_ids=["pumping.transferred_volume_m3"])
|
| 135 |
+
unknown = self.agent.read(instance_id="pump", state_ids=["unknown.private_truth"])
|
| 136 |
+
self.assertEqual(denied["error"], unknown["error"])
|
| 137 |
+
payloads += [denied, unknown]
|
| 138 |
+
import json
|
| 139 |
+
serialized = json.dumps(payloads)
|
| 140 |
+
self.assertNotIn("synthetic_private_marker", serialized)
|
| 141 |
+
self.assertNotIn("synthetic_other_marker", serialized)
|
| 142 |
+
self.assertNotIn("species_mass_kg", serialized)
|
| 143 |
+
self.assertNotIn("pumping.transferred_volume_m3", serialized)
|
| 144 |
+
self.assertGreater(self.value("pump", "pumping.transferred_volume_m3", debug=True), 0)
|
| 145 |
+
|
| 146 |
+
def test_scope_limits_discovery_and_instance_access(self):
|
| 147 |
+
self.host.register_principal("scoped", visibility="agent", instance_ids=["hotplate"])
|
| 148 |
+
session = self.host.session("scoped")
|
| 149 |
+
self.assertEqual(session.read(instance_id="oven")["error"]["code"], "UNKNOWN_INSTANCE")
|
| 150 |
+
self.assertEqual(session.describe(asset_type_id=TYPES["oven"])["error"]["code"], "ACCESS_DENIED")
|
| 151 |
+
self.assertEqual(session.describe(instance_id="hotplate")["asset_type_id"], TYPES["hotplate"])
|
| 152 |
+
|
| 153 |
+
def test_invalid_arguments_and_preconditions_have_no_state_effects(self):
|
| 154 |
+
cases = [("hotplate", "power.set", {"enabled": 1}),
|
| 155 |
+
("hotplate", "thermal.set_temperature", {"temperature_K": 333.15}),
|
| 156 |
+
("hotplate", "stirring.set_speed", {"speed_rad_s": True}),
|
| 157 |
+
("oven", "scene.set_door", {"angle_rad": math.inf}),
|
| 158 |
+
("hood", "scene.set_sash", {"opening_m": -.1}),
|
| 159 |
+
("pump", "pumping.set_flow_rate", {"flow_rate_m3_s": math.nan}),
|
| 160 |
+
("pump", "pumping.start", {}),
|
| 161 |
+
("pump", "pumping.set_direction", {"direction": "sideways"})]
|
| 162 |
+
for instance, capability, arguments in cases:
|
| 163 |
+
with self.subTest(capability=capability, arguments=arguments):
|
| 164 |
+
before = self.host.debug_snapshot()
|
| 165 |
+
response = self.invoke(instance, capability, **arguments)
|
| 166 |
+
self.assertEqual(response["status"], "rejected")
|
| 167 |
+
self.assertEqual(response["error"]["side_effects"], "none")
|
| 168 |
+
self.assertEqual(before, self.host.debug_snapshot())
|
| 169 |
+
|
| 170 |
+
def test_malformed_identifiers_return_errors_without_exceptions_or_mutation(self):
|
| 171 |
+
before = self.host.debug_snapshot()
|
| 172 |
+
for malformed in ([], {}, True, 0):
|
| 173 |
+
self.assertEqual(self.agent.read(instance_id=malformed)["status"], "rejected")
|
| 174 |
+
self.assertEqual(self.agent.describe(instance_id=malformed)["status"], "rejected")
|
| 175 |
+
response = self.agent.invoke(instance_id=malformed, capability_id="power.set", arguments={"enabled": True}, request_id={})
|
| 176 |
+
self.assertEqual(response["status"], "rejected")
|
| 177 |
+
self.assertIsNone(response["instance_id"])
|
| 178 |
+
self.assertIsNone(response["request_id"])
|
| 179 |
+
self.assertEqual(before, self.host.debug_snapshot())
|
| 180 |
+
|
| 181 |
+
def test_unrepresentable_json_integer_rejects_without_mutation(self):
|
| 182 |
+
huge_integer = 10**400
|
| 183 |
+
self.ok("hotplate", "power.set", enabled=True)
|
| 184 |
+
before = self.host.debug_snapshot()
|
| 185 |
+
response = self.invoke("hotplate", "thermal.set_temperature", temperature_K=huge_integer)
|
| 186 |
+
self.assertEqual(response["status"], "rejected")
|
| 187 |
+
self.assertEqual(response["error"]["code"], "INVALID_ARGUMENT")
|
| 188 |
+
self.assertEqual(before, self.host.debug_snapshot())
|
| 189 |
+
with self.assertRaises(ValueError):
|
| 190 |
+
self.host.step(huge_integer)
|
| 191 |
+
self.assertEqual(before, self.host.debug_snapshot())
|
| 192 |
+
|
| 193 |
+
def test_write_routes_through_capability_and_cannot_write_truth(self):
|
| 194 |
+
self.ok("hotplate", "power.set", enabled=True)
|
| 195 |
+
response = self.agent.write(instance_id="hotplate", state_id="thermal.target_k", value=333.15, request_id="write_temp")
|
| 196 |
+
self.assertEqual(response["result"], {"setpoint_K": 333.15})
|
| 197 |
+
self.assertEqual(self.value("hotplate", "thermal.temperature_k", debug=True), 293.15)
|
| 198 |
+
before = self.host.debug_snapshot()
|
| 199 |
+
denied = self.judge.write(instance_id="hotplate", state_id="thermal.temperature_k", value=999, request_id="write_truth")
|
| 200 |
+
self.assertEqual(denied["error"]["code"], "ACCESS_DENIED")
|
| 201 |
+
self.assertEqual(before, self.host.debug_snapshot())
|
| 202 |
+
replay = self.agent.invoke(instance_id="hotplate", capability_id="thermal.set_temperature", arguments={"temperature_K": 333.15}, request_id="write_temp")
|
| 203 |
+
self.assertEqual(response, replay)
|
| 204 |
+
|
| 205 |
+
def test_thermal_heating_is_time_dependent_power_bounded_and_cools(self):
|
| 206 |
+
self.ok("hotplate", "power.set", enabled=True)
|
| 207 |
+
self.ok("hotplate", "thermal.set_temperature", temperature_K=333.15)
|
| 208 |
+
self.assertEqual(self.value("hotplate", "thermal.temperature_k", debug=True), 293.15)
|
| 209 |
+
self.host.step(10)
|
| 210 |
+
heated = self.value("hotplate", "thermal.temperature_k", debug=True)
|
| 211 |
+
self.assertGreater(heated, 293.15)
|
| 212 |
+
self.assertLessEqual((heated - 293.15) * 1800, 600 * 10 + 1e-9)
|
| 213 |
+
self.host.step(3600)
|
| 214 |
+
self.assertAlmostEqual(self.value("hotplate", "thermal.temperature_k", debug=True), 333.15)
|
| 215 |
+
self.ok("hotplate", "power.set", enabled=False)
|
| 216 |
+
self.host.step(60)
|
| 217 |
+
self.assertLess(self.value("hotplate", "thermal.temperature_k", debug=True), 333.15)
|
| 218 |
+
|
| 219 |
+
def test_oven_open_door_reduces_heating_by_explicit_assumption(self):
|
| 220 |
+
self.host.create_instance("oven_open", TYPES["oven"])
|
| 221 |
+
for instance in ("oven", "oven_open"):
|
| 222 |
+
self.ok(instance, "power.set", enabled=True)
|
| 223 |
+
self.ok(instance, "thermal.set_temperature", temperature_K=373.15)
|
| 224 |
+
self.ok("oven_open", "scene.set_door", angle_rad=math.radians(100))
|
| 225 |
+
self.host.step(300)
|
| 226 |
+
self.assertLess(self.value("oven_open", "thermal.temperature_k", debug=True), self.value("oven", "thermal.temperature_k", debug=True))
|
| 227 |
+
before = self.host.debug_snapshot()
|
| 228 |
+
response = self.invoke("oven", "thermal.set_temperature", temperature_K=300)
|
| 229 |
+
self.assertEqual(response["error"]["code"], "INVALID_ARGUMENT")
|
| 230 |
+
self.assertEqual(before, self.host.debug_snapshot())
|
| 231 |
+
|
| 232 |
+
def test_temperature_limits_and_speed_grid_boundaries(self):
|
| 233 |
+
self.ok("hotplate", "power.set", enabled=True)
|
| 234 |
+
self.ok("hotplate", "thermal.set_temperature", temperature_K=583.15)
|
| 235 |
+
self.assertEqual(self.invoke("hotplate", "thermal.set_temperature", temperature_K=583.16)["status"], "rejected")
|
| 236 |
+
for rpm in (0, 50, 60, 1490, 1500):
|
| 237 |
+
self.ok("hotplate", "stirring.set_speed", speed_rad_s=rpm * RPM_TO_RAD_S)
|
| 238 |
+
for rpm in (-1, 10, 49, 55, 1501):
|
| 239 |
+
self.assertEqual(self.invoke("hotplate", "stirring.set_speed", speed_rad_s=rpm * RPM_TO_RAD_S)["status"], "rejected")
|
| 240 |
+
|
| 241 |
+
def test_stirring_speed_has_finite_response_and_angle_is_integrated(self):
|
| 242 |
+
self.ok("hotplate", "power.set", enabled=True)
|
| 243 |
+
target = 300 * RPM_TO_RAD_S
|
| 244 |
+
self.ok("hotplate", "stirring.set_speed", speed_rad_s=target)
|
| 245 |
+
self.assertEqual(self.value("hotplate", "stirring.speed_rad_s", debug=True), 0)
|
| 246 |
+
self.host.step(.5)
|
| 247 |
+
speed = self.value("hotplate", "stirring.speed_rad_s", debug=True)
|
| 248 |
+
self.assertGreater(speed, 0)
|
| 249 |
+
self.assertLess(speed, target)
|
| 250 |
+
expected_angle = (target * .5 - target * 1.5 * (1 - math.exp(-.5 / 1.5))) % (2 * math.pi)
|
| 251 |
+
self.assertAlmostEqual(self.value("hotplate", "stirring.angle_rad", debug=True), expected_angle)
|
| 252 |
+
self.assertTrue(any("stirring.angle_rad" in updates for _, updates in self.scene_calls))
|
| 253 |
+
self.ok("hotplate", "power.set", enabled=False)
|
| 254 |
+
self.host.step(.5)
|
| 255 |
+
self.assertLess(self.value("hotplate", "stirring.speed_rad_s", debug=True), speed)
|
| 256 |
+
|
| 257 |
+
def test_absent_scene_backend_is_unsupported_and_no_state_change(self):
|
| 258 |
+
self.host.scene_adapter = None
|
| 259 |
+
before = self.host.debug_snapshot()
|
| 260 |
+
response = self.invoke("oven", "scene.set_door", angle_rad=.5)
|
| 261 |
+
self.assertEqual(response["status"], "unsupported")
|
| 262 |
+
self.assertEqual(before, self.host.debug_snapshot())
|
| 263 |
+
self.assertEqual(self.agent.describe(instance_id="oven")["capabilities"]["scene.set_door"]["availability"], "unsupported")
|
| 264 |
+
|
| 265 |
+
def test_scene_command_failure_is_honest_and_process_state_unchanged(self):
|
| 266 |
+
def failing_callback(instance, updates):
|
| 267 |
+
raise RuntimeError("synthetic_private_marker should not leak through exception")
|
| 268 |
+
self.host.scene_adapter = failing_callback
|
| 269 |
+
before = self.host.debug_snapshot()
|
| 270 |
+
response = self.invoke("oven", "scene.set_door", angle_rad=.5)
|
| 271 |
+
self.assertEqual(response["status"], "failed")
|
| 272 |
+
self.assertEqual(response["error"]["side_effects"], "unknown")
|
| 273 |
+
self.assertNotIn("synthetic_private_marker", response["error"]["message"])
|
| 274 |
+
self.assertEqual(before, self.host.debug_snapshot())
|
| 275 |
+
|
| 276 |
+
def test_step_scene_failure_retains_partial_process_and_common_time(self):
|
| 277 |
+
self.ok("hotplate", "power.set", enabled=True)
|
| 278 |
+
self.ok("hotplate", "thermal.set_temperature", temperature_K=333.15)
|
| 279 |
+
self.host.scene_adapter = lambda instance, updates: (_ for _ in ()).throw(RuntimeError("synthetic backend failure"))
|
| 280 |
+
with self.assertRaises(SceneSynchronizationError):
|
| 281 |
+
self.host.step(10)
|
| 282 |
+
self.assertEqual(self.host.time_s, 10)
|
| 283 |
+
self.assertGreater(self.value("hotplate", "thermal.temperature_k", debug=True), 293.15)
|
| 284 |
+
self.assertTrue(self.host.debug_snapshot()["scene_faults"])
|
| 285 |
+
|
| 286 |
+
def test_pump_infuse_conserves_material_and_uses_calibrated_area(self):
|
| 287 |
+
self.configure_pump()
|
| 288 |
+
before = self.totals()
|
| 289 |
+
initial_displacement = self.value("pump", "pumping.plunger_displacement_m")
|
| 290 |
+
self.ok("pump", "pumping.start")
|
| 291 |
+
self.assertEqual(self.value("pump", "pumping.transferred_volume_m3", debug=True), 0)
|
| 292 |
+
self.host.step(100)
|
| 293 |
+
self.assert_conserved(before)
|
| 294 |
+
snapshot = self.host.debug_snapshot()
|
| 295 |
+
self.assertAlmostEqual(snapshot["vessels"]["synthetic_external"]["volume_m3"], 1e-6, delta=1e-18)
|
| 296 |
+
self.assertAlmostEqual(snapshot["vessels"]["synthetic_external"]["species_mass_kg"]["synthetic_private_marker"], .001, delta=1e-15)
|
| 297 |
+
area = math.pi * .01443**2 / 4
|
| 298 |
+
self.assertAlmostEqual(self.value("pump", "pumping.plunger_displacement_m") - initial_displacement, 1e-6 / area)
|
| 299 |
+
self.assertEqual(len(snapshot["transactions"]), 1)
|
| 300 |
+
self.assertEqual(snapshot["transactions"][0]["direction"], "infuse")
|
| 301 |
+
|
| 302 |
+
def test_pump_withdraw_reverses_transaction_and_motion(self):
|
| 303 |
+
self.configure_pump(syringe_volume=0, external_volume=2e-6)
|
| 304 |
+
before = self.totals()
|
| 305 |
+
initial_displacement = self.value("pump", "pumping.plunger_displacement_m")
|
| 306 |
+
self.ok("pump", "pumping.set_direction", direction="withdraw")
|
| 307 |
+
self.ok("pump", "pumping.start")
|
| 308 |
+
self.host.step(100)
|
| 309 |
+
self.assert_conserved(before)
|
| 310 |
+
self.assertLess(self.value("pump", "pumping.plunger_displacement_m"), initial_displacement)
|
| 311 |
+
snapshot = self.host.debug_snapshot()
|
| 312 |
+
self.assertAlmostEqual(snapshot["vessels"]["synthetic_syringe"]["volume_m3"], 1e-6)
|
| 313 |
+
self.assertEqual(snapshot["transactions"][0]["donor_id"], "synthetic_external")
|
| 314 |
+
|
| 315 |
+
def test_pump_clips_at_recipient_capacity_and_retains_partial_transfer(self):
|
| 316 |
+
self.configure_pump(external_capacity=.25e-6)
|
| 317 |
+
before = self.totals()
|
| 318 |
+
self.ok("pump", "pumping.start")
|
| 319 |
+
self.host.step(100)
|
| 320 |
+
self.assert_conserved(before)
|
| 321 |
+
self.assertFalse(self.value("pump", "pumping.running"))
|
| 322 |
+
self.assertAlmostEqual(self.value("pump", "pumping.transferred_volume_m3", debug=True), .25e-6)
|
| 323 |
+
after = self.host.debug_snapshot()
|
| 324 |
+
self.assertEqual(self.invoke("pump", "pumping.start")["status"], "rejected")
|
| 325 |
+
self.assertEqual(after, self.host.debug_snapshot())
|
| 326 |
+
|
| 327 |
+
def test_pump_clips_at_donor_empty_without_creating_liquid(self):
|
| 328 |
+
self.configure_pump(syringe_volume=.1e-6)
|
| 329 |
+
before = self.totals()
|
| 330 |
+
self.ok("pump", "pumping.start")
|
| 331 |
+
self.host.step(100)
|
| 332 |
+
self.assert_conserved(before)
|
| 333 |
+
self.assertFalse(self.value("pump", "pumping.running"))
|
| 334 |
+
self.assertAlmostEqual(self.value("pump", "pumping.transferred_volume_m3", debug=True), .1e-6, delta=1e-18)
|
| 335 |
+
self.assertAlmostEqual(self.host.debug_snapshot()["vessels"]["synthetic_syringe"]["volume_m3"], 0, delta=1e-18)
|
| 336 |
+
|
| 337 |
+
def test_pump_withdraw_clips_at_declared_syringe_stroke(self):
|
| 338 |
+
self.configure_pump(syringe_volume=9.9e-6, external_volume=2e-6, syringe_capacity=20e-6)
|
| 339 |
+
before = self.totals()
|
| 340 |
+
self.ok("pump", "pumping.set_direction", direction="withdraw")
|
| 341 |
+
self.ok("pump", "pumping.start")
|
| 342 |
+
self.host.step(100)
|
| 343 |
+
self.assert_conserved(before)
|
| 344 |
+
self.assertFalse(self.value("pump", "pumping.running"))
|
| 345 |
+
self.assertAlmostEqual(self.host.debug_snapshot()["vessels"]["synthetic_syringe"]["volume_m3"], 10e-6, delta=1e-18)
|
| 346 |
+
self.assertAlmostEqual(self.value("pump", "pumping.plunger_displacement_m"), 0, delta=1e-15)
|
| 347 |
+
|
| 348 |
+
def test_pump_stop_and_power_off_prevent_further_transfer(self):
|
| 349 |
+
self.configure_pump()
|
| 350 |
+
self.ok("pump", "pumping.start")
|
| 351 |
+
self.host.step(10)
|
| 352 |
+
self.ok("pump", "pumping.stop")
|
| 353 |
+
transferred = self.value("pump", "pumping.transferred_volume_m3", debug=True)
|
| 354 |
+
self.host.step(10)
|
| 355 |
+
self.assertEqual(self.value("pump", "pumping.transferred_volume_m3", debug=True), transferred)
|
| 356 |
+
self.ok("pump", "pumping.start")
|
| 357 |
+
self.ok("pump", "power.set", enabled=False)
|
| 358 |
+
self.host.step(10)
|
| 359 |
+
self.assertEqual(self.value("pump", "pumping.transferred_volume_m3", debug=True), transferred)
|
| 360 |
+
self.assertFalse(self.value("pump", "pumping.running"))
|
| 361 |
+
|
| 362 |
+
def test_pump_direction_change_requires_stop_and_flow_uses_bd10_limits(self):
|
| 363 |
+
self.configure_pump()
|
| 364 |
+
params = ASSET_SPECS[TYPES["pump"]]["parameters"]
|
| 365 |
+
minimum, maximum = params["minimum_flow_rate_m3_s"]["value"], params["maximum_flow_rate_m3_s"]["value"]
|
| 366 |
+
self.assertAlmostEqual(minimum, 6.876e-9 / 3600, delta=1e-25)
|
| 367 |
+
self.assertAlmostEqual(maximum, 500.4e-6 / 3600, delta=1e-22)
|
| 368 |
+
for flow in (minimum, maximum):
|
| 369 |
+
self.ok("pump", "pumping.set_flow_rate", flow_rate_m3_s=flow)
|
| 370 |
+
for flow in (0, minimum / 2, maximum * 1.01):
|
| 371 |
+
self.assertEqual(self.invoke("pump", "pumping.set_flow_rate", flow_rate_m3_s=flow)["status"], "rejected")
|
| 372 |
+
self.ok("pump", "pumping.start")
|
| 373 |
+
before = self.host.debug_snapshot()
|
| 374 |
+
self.assertEqual(self.invoke("pump", "pumping.set_direction", direction="withdraw")["status"], "rejected")
|
| 375 |
+
self.assertEqual(before, self.host.debug_snapshot())
|
| 376 |
+
|
| 377 |
+
def test_shared_pump_resource_transactions_conserve_under_world_lock(self):
|
| 378 |
+
self.configure_pump(external_capacity=1.5e-6)
|
| 379 |
+
self.host.create_instance("pump_b", TYPES["pump"])
|
| 380 |
+
p = ASSET_SPECS[TYPES["pump"]]["parameters"]
|
| 381 |
+
self.host.configure_syringe("pump_b", diameter_m=p["syringe_diameter_m"]["value"], stroke_m=p["syringe_stroke_m"]["value"], evidence="Synthetic second syringe")
|
| 382 |
+
self.host.create_vessel("synthetic_syringe_b", volume_m3=5e-6, capacity_m3=10e-6, species_mass_kg={"synthetic_b": .005})
|
| 383 |
+
self.host.connect_pump("pump_b", "synthetic_syringe_b", "synthetic_external")
|
| 384 |
+
self.ok("pump_b", "power.set", enabled=True)
|
| 385 |
+
self.ok("pump_b", "pumping.set_flow_rate", flow_rate_m3_s=1e-8)
|
| 386 |
+
before = self.totals()
|
| 387 |
+
for instance in ("pump", "pump_b"):
|
| 388 |
+
self.ok(instance, "pumping.start")
|
| 389 |
+
self.host.step(100)
|
| 390 |
+
self.assert_conserved(before)
|
| 391 |
+
snapshot = self.host.debug_snapshot()
|
| 392 |
+
self.assertAlmostEqual(snapshot["vessels"]["synthetic_external"]["volume_m3"], 1.5e-6, delta=1e-18)
|
| 393 |
+
self.assertEqual(len({t["transaction_id"] for t in snapshot["transactions"]}), 2)
|
| 394 |
+
|
| 395 |
+
def test_syringe_vessel_ownership_rejects_shared_and_cross_role_connections(self):
|
| 396 |
+
self.configure_pump()
|
| 397 |
+
self.host.create_instance("pump_b", TYPES["pump"])
|
| 398 |
+
params = ASSET_SPECS[TYPES["pump"]]["parameters"]
|
| 399 |
+
self.host.configure_syringe("pump_b", diameter_m=params["syringe_diameter_m"]["value"],
|
| 400 |
+
stroke_m=params["syringe_stroke_m"]["value"], evidence="Synthetic second exclusive syringe")
|
| 401 |
+
self.host.create_vessel("synthetic_syringe_b", volume_m3=5e-6, capacity_m3=10e-6,
|
| 402 |
+
species_mass_kg={"synthetic_b": .005})
|
| 403 |
+
self.host.create_vessel("synthetic_external_b", volume_m3=0, capacity_m3=10e-6, species_mass_kg={})
|
| 404 |
+
self.host.connect_pump("pump_b", "synthetic_syringe_b", "synthetic_external_b")
|
| 405 |
+
before = self.host.debug_snapshot()
|
| 406 |
+
invalid_connections = [
|
| 407 |
+
("synthetic_syringe", "synthetic_external_b"), # same syringe on two pumps
|
| 408 |
+
("synthetic_syringe_b", "synthetic_syringe"), # another pump's syringe used as external
|
| 409 |
+
("synthetic_external", "synthetic_external_b"), # an external vessel claimed as a syringe
|
| 410 |
+
]
|
| 411 |
+
for syringe, external in invalid_connections:
|
| 412 |
+
with self.subTest(syringe=syringe, external=external):
|
| 413 |
+
with self.assertRaises(ValueError):
|
| 414 |
+
self.host.connect_pump("pump_b", syringe, external)
|
| 415 |
+
self.assertEqual(before, self.host.debug_snapshot())
|
| 416 |
+
# Shared external collection remains valid and does not couple plunger positions.
|
| 417 |
+
self.host.connect_pump("pump_b", "synthetic_syringe_b", "synthetic_external")
|
| 418 |
+
b_position = self.value("pump_b", "pumping.plunger_displacement_m")
|
| 419 |
+
self.ok("pump", "pumping.start")
|
| 420 |
+
self.host.step(100)
|
| 421 |
+
self.assertEqual(self.value("pump_b", "pumping.plunger_displacement_m"), b_position)
|
| 422 |
+
self.assertAlmostEqual(self.host.debug_snapshot()["vessels"]["synthetic_syringe_b"]["volume_m3"], 5e-6)
|
| 423 |
+
|
| 424 |
+
def test_hood_estimate_is_external_boundary_not_a_sensor_or_power_effect(self):
|
| 425 |
+
self.host.set_external_exhaust("hood", .25)
|
| 426 |
+
observation = self.agent.read(instance_id="hood", state_ids=["ventilation.face_velocity_m_s"])["observations"]["ventilation.face_velocity_m_s"]
|
| 427 |
+
self.assertIsNone(observation["value"])
|
| 428 |
+
self.assertEqual(observation["quality"], "unavailable")
|
| 429 |
+
self.ok("hood", "scene.set_sash", opening_m=.457)
|
| 430 |
+
self.assertAlmostEqual(self.value("hood", "ventilation.face_velocity_m_s"), .25 / (1.301 * .457))
|
| 431 |
+
self.ok("hood", "power.set", enabled=True)
|
| 432 |
+
self.ok("hood", "power.set", enabled=False)
|
| 433 |
+
self.assertEqual(self.value("hood", "ventilation.external_exhaust_m3_s"), .25)
|
| 434 |
+
observation = self.agent.read(instance_id="hood", state_ids=["ventilation.face_velocity_m_s"])["observations"]["ventilation.face_velocity_m_s"]
|
| 435 |
+
self.assertEqual(observation["quality"], "estimated")
|
| 436 |
+
self.ok("hood", "scene.set_sash", opening_m=.670)
|
| 437 |
+
self.assertEqual(self.invoke("hood", "scene.set_sash", opening_m=.671)["status"], "rejected")
|
| 438 |
+
|
| 439 |
+
def test_declared_program_returns_unsupported_without_changes(self):
|
| 440 |
+
description = self.agent.describe(instance_id="pump")
|
| 441 |
+
self.assertEqual(description["capabilities"]["pumping.program"]["availability"], "declared")
|
| 442 |
+
before = self.host.debug_snapshot()
|
| 443 |
+
response = self.invoke("pump", "pumping.program", phases=[{"direction": "infuse", "flow_rate_m3_s": 1e-9, "duration_s": 10}])
|
| 444 |
+
self.assertEqual(response["status"], "unsupported")
|
| 445 |
+
self.assertEqual(before, self.host.debug_snapshot())
|
| 446 |
+
|
| 447 |
+
def test_real_outputs_and_observations_validate_against_exported_schemas(self):
|
| 448 |
+
self.configure_pump()
|
| 449 |
+
metadata = export_contract_metadata()["asset_types"]
|
| 450 |
+
for instance, type_id in TYPES.items():
|
| 451 |
+
self.ok(instance, "power.set", enabled=True)
|
| 452 |
+
for capability, info in metadata[type_id]["capabilities"].items():
|
| 453 |
+
with self.subTest(instance=instance, capability=capability):
|
| 454 |
+
self.assertEqual(lint_schema(info["input_schema"]), [])
|
| 455 |
+
self.assertEqual(lint_schema(info["output_schema"]), [])
|
| 456 |
+
args = info["example_arguments"][0]
|
| 457 |
+
self.assertEqual(validate_value(args, info["input_schema"]), [])
|
| 458 |
+
response = self.ok(instance, capability, **args)
|
| 459 |
+
self.assertEqual(validate_value(response["result"], info["output_schema"]), [])
|
| 460 |
+
self.assertEqual(set(response), {"protocol_version", "instance_id", "request_id", "operation_id", "status", "state_revision", "clock", "result", "observations", "error"})
|
| 461 |
+
self.assertEqual(response["observations"], {})
|
| 462 |
+
observations = self.judge.read(instance_id=instance)["observations"]
|
| 463 |
+
for state_id, observation in observations.items():
|
| 464 |
+
slot = metadata[type_id]["state_slots"][state_id]
|
| 465 |
+
self.assertEqual(validate_value(observation["value"], slot["value_schema"]), [])
|
| 466 |
+
self.assertEqual(observation["unit"], slot["unit"])
|
| 467 |
+
self.assertEqual(observation["sample_time_s"], self.host.time_s)
|
| 468 |
+
|
| 469 |
+
def test_host_time_metadata_is_separate_from_instrument_agent_api(self):
|
| 470 |
+
meta = self.host.describe_host()
|
| 471 |
+
self.assertEqual(meta["sim.step"]["visibility"], "trusted_host_only")
|
| 472 |
+
for instance in TYPES:
|
| 473 |
+
self.assertNotIn("sim.step", self.agent.describe(instance_id=instance)["capabilities"])
|
| 474 |
+
before = self.host.debug_snapshot()
|
| 475 |
+
for dt in (-1, math.inf, math.nan, True, 3601):
|
| 476 |
+
with self.assertRaises(ValueError):
|
| 477 |
+
self.host.step(dt)
|
| 478 |
+
self.host.step(0)
|
| 479 |
+
self.assertEqual(before, self.host.debug_snapshot())
|
| 480 |
+
|
| 481 |
+
|
| 482 |
+
if __name__ == "__main__":
|
| 483 |
+
unittest.main()
|
tests/test_basic40_thermal.py
ADDED
|
The diff for this file is too large to render.
See raw diff
|
|
|
tests/test_basic40_vacuum.py
ADDED
|
The diff for this file is too large to render.
See raw diff
|
|
|
tests/test_gc_runtime.py
ADDED
|
@@ -0,0 +1,213 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Invariant and failure-state checks for the explicitly synthetic GC model."""
|
| 2 |
+
import math
|
| 3 |
+
from pathlib import Path
|
| 4 |
+
import sys
|
| 5 |
+
import unittest
|
| 6 |
+
|
| 7 |
+
sys.path.insert(0, str(Path(__file__).resolve().parents[1] / "scripts"))
|
| 8 |
+
from gc_runtime import ActionRejected, GC, Method, Species, component_for_action
|
| 9 |
+
|
| 10 |
+
|
| 11 |
+
def prepared(method=None, species=None):
|
| 12 |
+
kwargs = {"method": method}
|
| 13 |
+
if species is not None:
|
| 14 |
+
kwargs["species"] = species
|
| 15 |
+
gc = GC(**kwargs)
|
| 16 |
+
gc.perform("plug_power", connected=True)
|
| 17 |
+
gc.perform("power", enabled=True)
|
| 18 |
+
for gas in gc.gases:
|
| 19 |
+
gc.perform("connect_gas", gas=gas, connected=True)
|
| 20 |
+
gc.step(1200)
|
| 21 |
+
gc.perform("ignite")
|
| 22 |
+
return gc
|
| 23 |
+
|
| 24 |
+
|
| 25 |
+
def inject(gc):
|
| 26 |
+
gc.perform("start")
|
| 27 |
+
gc.perform("aspirate", fraction=.01)
|
| 28 |
+
gc.perform("insert_syringe")
|
| 29 |
+
gc.perform("depress_plunger")
|
| 30 |
+
gc.perform("retract_syringe")
|
| 31 |
+
|
| 32 |
+
|
| 33 |
+
class GCRuntimeTest(unittest.TestCase):
|
| 34 |
+
def test_readiness_and_embodied_preconditions(self):
|
| 35 |
+
gc = GC()
|
| 36 |
+
with self.assertRaises(ActionRejected):
|
| 37 |
+
gc.perform("power", enabled=True)
|
| 38 |
+
self.assertFalse(gc.powered)
|
| 39 |
+
with self.assertRaises(ActionRejected):
|
| 40 |
+
gc.perform("start")
|
| 41 |
+
gc = prepared()
|
| 42 |
+
gc.perform("start")
|
| 43 |
+
gc.perform("aspirate", fraction=.01)
|
| 44 |
+
before = dict(gc.syringe)
|
| 45 |
+
with self.assertRaises(ActionRejected):
|
| 46 |
+
gc.perform("depress_plunger")
|
| 47 |
+
self.assertEqual(before, gc.syringe)
|
| 48 |
+
gc.perform("insert_syringe")
|
| 49 |
+
gc.perform("door", open=True)
|
| 50 |
+
with self.assertRaises(ActionRejected):
|
| 51 |
+
gc.perform("depress_plunger")
|
| 52 |
+
self.assertEqual(before, gc.syringe)
|
| 53 |
+
|
| 54 |
+
def test_split_mass_conservation_and_fid_charge(self):
|
| 55 |
+
gc = prepared()
|
| 56 |
+
inject(gc)
|
| 57 |
+
integrated = 0
|
| 58 |
+
for _ in range(90):
|
| 59 |
+
state = gc.step(10)
|
| 60 |
+
integrated += state["fid_current_A"] * 10
|
| 61 |
+
for ledger in state["mass_balance_kg"].values():
|
| 62 |
+
self.assertLess(abs(ledger["residual_kg"]), 1e-20)
|
| 63 |
+
expected_charge = 0
|
| 64 |
+
for name, ledger in gc.mass_balance().items():
|
| 65 |
+
expected_column = ledger["injected_kg"] / 21
|
| 66 |
+
self.assertAlmostEqual(ledger["column_loaded_kg"] / expected_column, 1, places=10)
|
| 67 |
+
self.assertAlmostEqual(ledger["eluted_kg"] / expected_column, 1, places=10)
|
| 68 |
+
self.assertAlmostEqual(ledger["split_vent_kg"] / expected_column, 20, places=10)
|
| 69 |
+
expected_charge += expected_column * gc.species[name].response_C_kg
|
| 70 |
+
self.assertAlmostEqual(gc.fid_integral_C / expected_charge, 1, places=10)
|
| 71 |
+
self.assertAlmostEqual(integrated / gc.fid_integral_C, 1, places=12)
|
| 72 |
+
|
| 73 |
+
def test_splitless_purge_transition_and_analytic_transfer(self):
|
| 74 |
+
method = Method(mode="splitless", purge_time_s=30.3)
|
| 75 |
+
gc = prepared(method)
|
| 76 |
+
inject(gc)
|
| 77 |
+
self.assertEqual(gc.flows()["split_vent"], 0)
|
| 78 |
+
gc.step(30)
|
| 79 |
+
self.assertEqual(gc.flows()["split_vent"], 0)
|
| 80 |
+
gc.step(.3)
|
| 81 |
+
self.assertEqual(gc.flows()["split_vent"], method.purge_flow_m3_s)
|
| 82 |
+
gc.step(150)
|
| 83 |
+
remaining_before_purge = math.exp(-method.column_flow_m3_s * method.purge_time_s / method.liner_volume_m3)
|
| 84 |
+
expected_fraction = (1 - remaining_before_purge + remaining_before_purge *
|
| 85 |
+
method.column_flow_m3_s / (method.column_flow_m3_s + method.purge_flow_m3_s))
|
| 86 |
+
for ledger in gc.mass_balance().values():
|
| 87 |
+
self.assertAlmostEqual(ledger["column_loaded_kg"] / ledger["injected_kg"], expected_fraction, places=10)
|
| 88 |
+
self.assertLess(abs(ledger["residual_kg"]), 1e-20)
|
| 89 |
+
|
| 90 |
+
def test_septum_purge_is_distinct_from_split_flow(self):
|
| 91 |
+
gc = prepared(Method(septum_sample_loss_fraction=.1))
|
| 92 |
+
inject(gc)
|
| 93 |
+
gc.step(100)
|
| 94 |
+
flow = gc.observe()
|
| 95 |
+
self.assertAlmostEqual(flow["carrier_total_flow_m3_s"],
|
| 96 |
+
sum(flow["flows_m3_s"][k] for k in ("column", "split_vent", "septum_purge")))
|
| 97 |
+
for ledger in gc.mass_balance().values():
|
| 98 |
+
self.assertAlmostEqual(ledger["septum_purge_kg"] / ledger["injected_kg"], .1, places=12)
|
| 99 |
+
self.assertAlmostEqual(ledger["column_loaded_kg"] / ledger["injected_kg"], .9 / 21, places=12)
|
| 100 |
+
self.assertLess(abs(ledger["residual_kg"]), 1e-20)
|
| 101 |
+
|
| 102 |
+
def test_fractional_plunger_strokes_do_not_restart_purge_timer(self):
|
| 103 |
+
gc = prepared(Method(mode="splitless", purge_time_s=10))
|
| 104 |
+
gc.perform("start")
|
| 105 |
+
gc.perform("aspirate", fraction=.01)
|
| 106 |
+
gc.perform("insert_syringe")
|
| 107 |
+
gc.perform("depress_plunger", fraction=.5)
|
| 108 |
+
first_injection_time = gc.injection_time_s
|
| 109 |
+
gc.step(6)
|
| 110 |
+
gc.perform("depress_plunger")
|
| 111 |
+
self.assertEqual(gc.injection_time_s, first_injection_time)
|
| 112 |
+
gc.step(4)
|
| 113 |
+
self.assertGreater(gc.flows()["split_vent"], 0)
|
| 114 |
+
for ledger in gc.mass_balance().values():
|
| 115 |
+
self.assertLess(abs(ledger["residual_kg"]), 1e-20)
|
| 116 |
+
|
| 117 |
+
def test_carrier_loss_stops_transport_without_destroying_mass(self):
|
| 118 |
+
gc = prepared()
|
| 119 |
+
inject(gc)
|
| 120 |
+
gc.step(30)
|
| 121 |
+
before = gc.mass_balance()
|
| 122 |
+
gc.perform("connect_gas", gas="carrier", connected=False)
|
| 123 |
+
self.assertIn("NO_CARRIER_FLOW", gc.observe()["not_ready_reasons"])
|
| 124 |
+
gc.step(100)
|
| 125 |
+
after = gc.mass_balance()
|
| 126 |
+
for name in before:
|
| 127 |
+
for quantity in ("liner_kg", "column_remaining_kg", "eluted_kg"):
|
| 128 |
+
self.assertEqual(before[name][quantity], after[name][quantity])
|
| 129 |
+
|
| 130 |
+
def test_flame_loss_elutes_sample_but_produces_no_charge(self):
|
| 131 |
+
gc = prepared()
|
| 132 |
+
inject(gc)
|
| 133 |
+
gc.perform("connect_gas", gas="hydrogen", connected=False)
|
| 134 |
+
state = gc.step(900)
|
| 135 |
+
self.assertFalse(state["flame_lit"])
|
| 136 |
+
self.assertEqual(state["fid_current_A"], 0)
|
| 137 |
+
self.assertEqual(state["fid_integral_C"], 0)
|
| 138 |
+
for ledger in state["mass_balance_kg"].values():
|
| 139 |
+
self.assertGreater(ledger["eluted_kg"], 0)
|
| 140 |
+
self.assertEqual(ledger["eluted_kg"], ledger["flame_off_eluted_kg"])
|
| 141 |
+
|
| 142 |
+
def test_open_door_cools_oven_and_clears_readiness(self):
|
| 143 |
+
gc = prepared()
|
| 144 |
+
initial = gc.zones["oven"].temperature_K
|
| 145 |
+
gc.perform("door", open=True)
|
| 146 |
+
state = gc.step(60)
|
| 147 |
+
self.assertEqual(state["heater_power_W"]["oven"], 0)
|
| 148 |
+
self.assertLess(state["temperatures_K"]["oven"], initial)
|
| 149 |
+
self.assertIn("OVEN_DOOR_OPEN", state["not_ready_reasons"])
|
| 150 |
+
gc.perform("door", open=False)
|
| 151 |
+
gc.step(1200)
|
| 152 |
+
self.assertTrue(gc.observe()["ready"])
|
| 153 |
+
|
| 154 |
+
def test_temperature_changes_retention_in_expected_direction(self):
|
| 155 |
+
species = Species("synthetic_probe", 3, -35000, 1)
|
| 156 |
+
self.assertLess(species.retention_factor(393.15), species.retention_factor(353.15))
|
| 157 |
+
self.assertGreater(species.retention_factor(313.15), species.retention_factor(353.15))
|
| 158 |
+
result = []
|
| 159 |
+
for temperature in (353.15, 393.15):
|
| 160 |
+
gc = prepared(Method(oven_temperature_K=temperature), (species,))
|
| 161 |
+
inject(gc)
|
| 162 |
+
max_signal = -1
|
| 163 |
+
peak_time = 0
|
| 164 |
+
for _ in range(500):
|
| 165 |
+
state = gc.step(1)
|
| 166 |
+
if state["fid_current_A"] > max_signal:
|
| 167 |
+
max_signal = state["fid_current_A"]
|
| 168 |
+
peak_time = state["run_time_s"]
|
| 169 |
+
result.append(peak_time)
|
| 170 |
+
self.assertLess(result[1], result[0])
|
| 171 |
+
|
| 172 |
+
def test_zero_response_species_does_not_become_a_peak(self):
|
| 173 |
+
gc = prepared(species=(Species("synthetic_nonresponsive", 1, -30000, 0),))
|
| 174 |
+
inject(gc)
|
| 175 |
+
state = gc.step(400)
|
| 176 |
+
self.assertGreater(state["mass_balance_kg"]["synthetic_nonresponsive"]["eluted_kg"], 0)
|
| 177 |
+
self.assertEqual(state["fid_integral_C"], 0)
|
| 178 |
+
|
| 179 |
+
def test_stop_ends_acquisition_but_not_chromatographic_transport(self):
|
| 180 |
+
gc = prepared(species=(Species("synthetic_probe", 1, -30000, 1),))
|
| 181 |
+
inject(gc)
|
| 182 |
+
gc.perform("stop")
|
| 183 |
+
state = gc.step(400)
|
| 184 |
+
self.assertEqual(state["fid_integral_C"], 0)
|
| 185 |
+
self.assertEqual(state["run_time_s"], 0)
|
| 186 |
+
self.assertGreater(state["mass_balance_kg"]["synthetic_probe"]["eluted_kg"], 0)
|
| 187 |
+
|
| 188 |
+
def test_invalid_numerics_and_sample_transfer(self):
|
| 189 |
+
gc = GC()
|
| 190 |
+
for invalid in (-1, 0, float("nan"), float("inf")):
|
| 191 |
+
with self.assertRaises(ValueError):
|
| 192 |
+
gc.step(invalid)
|
| 193 |
+
with self.assertRaises(ValueError):
|
| 194 |
+
Method(column_flow_m3_s=0)
|
| 195 |
+
with self.assertRaises(ValueError):
|
| 196 |
+
Species("invalid", 1, float("nan"), 1)
|
| 197 |
+
before = dict(gc.vial)
|
| 198 |
+
gc.perform("aspirate", fraction=.2)
|
| 199 |
+
for name in before:
|
| 200 |
+
self.assertAlmostEqual(gc.vial[name] + gc.syringe[name], before[name], places=20)
|
| 201 |
+
with self.assertRaises(ValueError):
|
| 202 |
+
gc.perform("aspirate", fraction=2)
|
| 203 |
+
|
| 204 |
+
def test_gas_connection_events_target_matching_physical_ports(self):
|
| 205 |
+
gc = GC()
|
| 206 |
+
for gas in ("carrier", "hydrogen", "air", "makeup"):
|
| 207 |
+
self.assertEqual(component_for_action("connect_gas", gas=gas), f"{gas}_port")
|
| 208 |
+
gc.perform("connect_gas", gas=gas, connected=True)
|
| 209 |
+
self.assertEqual(gc.events[-1]["component_id"], f"{gas}_port")
|
| 210 |
+
|
| 211 |
+
|
| 212 |
+
if __name__ == "__main__":
|
| 213 |
+
unittest.main()
|